@cortexkit/opencode-anthropic-auth 2.2.7 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +43 -42
- package/dist/index-2jsr8wvj.js +43 -0
- package/dist/index-46e2gk3c.js +2 -0
- package/dist/{index-62x1p34p.js → index-71temqvq.js} +1 -1
- package/dist/{index-ppdrzs41.js → index-bcp23wwb.js} +1 -1
- package/dist/{index-hazrk5c3.js → index-c8ehrd0p.js} +1 -1
- package/dist/index-dpnhamzw.js +2 -0
- package/dist/{index-0kxy8k2c.js → index-m4dazzyf.js} +1 -1
- package/dist/{index-b1dvkp15.js → index-naff9h33.js} +1 -1
- package/dist/{index-6chd6jnr.js → index-sg0knfec.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/oauth-destination.d.ts +35 -0
- package/dist/plugin-test-handles.d.ts +26 -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/sidebar-state.d.ts +6 -3
- package/dist/sidebar-state.js +1 -1
- package/dist/tui/claude-sidebar.d.ts +58 -0
- package/dist/tui/menu-status.d.ts +70 -0
- package/dist/tui-preferences.js +2 -2
- package/dist/v2/adapter.d.ts +13 -8
- package/dist/v2/server.js +10 -10
- package/dist/v2/tui.d.ts +12 -0
- package/dist/v2/tui.js +4 -5
- package/package.json +2 -2
- package/src/sidebar-state.ts +55 -46
- package/src/tui/claude-sidebar.tsx +155 -15
- package/src/tui/entry.mjs +13 -0
- package/src/tui/menu-status.tsx +300 -0
- package/src/tui-compiled/sidebar-state.ts +55 -46
- package/src/tui-compiled/tui/claude-sidebar.tsx +112 -12
- package/src/tui-compiled/tui/menu-status.tsx +388 -0
- package/src/tui-compiled/tui-preferences.ts +32 -3
- package/src/tui-preferences.ts +32 -3
- package/dist/index-20d6rmjj.js +0 -2
- package/dist/index-cjjjgewq.js +0 -43
- package/dist/index-jvhs8sxv.js +0 -2
package/dist/cli.js
CHANGED
|
@@ -1,56 +1,57 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{x as $3}from"./index-0kxy8k2c.js";import{A as D4,B as o$,C as t$,D as e$,E as $9,F as L4,z as B4}from"./index-b1dvkp15.js";import{ha as G4,ia as M5,ja as q3}from"./index-62x1p34p.js";var I2=M5((oH,J4)=>{var _2={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"},V5={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},F5={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?_2.up():"");if($)Z+=_2.left;return Z}};J4.exports={cursor:_2,scroll:V5,erase:F5,beep:"\x07"}});import{stdin as r5,stdout as o5}from"node:process";import{createInterface as t5}from"node:readline/promises";import{authorize as e5,createNativeAccountRuntime as $Z,exchange as ZZ,formatNativeAccountState as JZ,generateRelayToken as zZ,getAccountStoragePath as XZ,isValidApiBaseURL as GZ,readNativeEnrollmentMode as QZ,resolveNativePoolPaths as WZ,WORKER_SCRIPT as HZ}from"@cortexkit/anthropic-auth-core";import{randomUUID as y8}from"node:crypto";import{constants as v1}from"node:fs";import{lstat as h8,mkdir as v8,open as m8}from"node:fs/promises";import{homedir as w8}from"node:os";import{isAbsolute as j9,join as H2}from"node:path";import{types as U2}from"node:util";import{createProviderErrorRedactor as B9,createWindowsOwnerOnly as u8,ensureWindowsOwnerOnlyDirectory as c8,formatLogLine as p8,isOwnerOnly as d8,isSecretKey as l8,NativeMigrationError as a8,NativePiAuthSlotError as s8,PRIVATE_FILES_UNAVAILABLE_MESSAGE as D9,setupEnrollment as n8}from"@cortexkit/anthropic-auth-core";import{readFile as I8}from"node:fs/promises";import{assertHostsStopped as A8,createNativeAccountRuntime as R8,discoverNativeVaultInventory as S8,inspectNativeHostAuthEntry as z2,NativePiAuthSlotError as b8,nativePiAuthSlotPaths as k8,openNativePiAuthSlot as G2,readNativeEnrollmentMode as T8,requireNoSupervisedAuthContentSnapshot as E8}from"@cortexkit/anthropic-auth-core";import{dirname as $8}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as Z8,CLAUSTRUM_PI_ENROLLMENT_NAME as J8,getHostClaustrumEnrollmentPaths as a$,resolveClaustrumConnectionPath as z8}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as AX}from"@cortexkit/claustrum-client";import{ClaustrumClient as WX}from"@cortexkit/claustrum-client";import{resolve as f2}from"node:path";import{storeIdentity as RZ}from"@cortexkit/claustrum-client";import{SubcClient as bZ}from"@cortexkit/subc-client";import{ClaustrumCredentialError as P4}from"@cortexkit/claustrum-client";import{SocketClosedError as O4,SocketTimeoutError as _4,SubcCallError as I4}from"@cortexkit/subc-client";class _ extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var G3=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class P0 extends _{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function M0($){if($ instanceof P0||$ instanceof O4||$ instanceof _4)return"unreachable";let Z=$ instanceof P4||$ instanceof I4?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(G3,Z))return"answered";return G3[Z]}var Q3=300000,D1=300000,W3=1000;class Z1{#$;#z=0;restart(){this.#z=0}continuous($){let Z=$.kind==="changed"&&$.seq===this.#z+1&&(this.#$===void 0||$.epoch===this.#$);return this.#$=$.epoch,this.#z=$.seq,Z}}class L1{#$;#z;#J;#X=!1;constructor($,Z){this.#$=$,this.#z=Z}get running(){return this.#J}request(){if(this.#J)return this.#X=!0,this.#J;return this.#J=(async()=>{do{this.#X=!1;try{await this.#$()}catch($){this.#z($)}}while(this.#X)})().finally(()=>{this.#J=void 0}),this.#J}}class N1{#$;#z=new Z1;#J;#X="polling";#H;#G;#Z=!1;#Y;#K=!1;#W=0;constructor($){this.#$=$,this.#J=new L1(async()=>{let Z=this.#K;if(this.#K=!1,Z||this.#Y!==this.#$.view())await this.#$.discover(this.#Y??"")},(Z)=>{if(!this.#Z)this.#$.onError?.(Z)})}get mode(){return this.#X}start(){if(this.#Z||this.#H||this.#G)return;if(typeof this.#$.client.watchScoped!=="function"){this.#Q("fallback","client-without-watch");return}this.#M(!1)}stop(){if(this.#Z)return;if(this.#Z=!0,this.#G)(this.#$.clearTimeoutImpl??clearTimeout)(this.#G);this.#G=void 0;let $=this.#H;this.#H=void 0,$?.handle.stop()}#Q($,Z){if(this.#X===$)return;this.#X=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#U($,Z){this.#G=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#G=void 0,!this.#Z)Z()},$),this.#G.unref?.()}async#M($){let Z;try{Z=await this.#$.enrollmentToken()}catch(Q){if(this.#Z)return;this.#$.onError?.(Q),this.#F("token-unreadable");return}let J=this.#$.client.watchScoped;if(this.#Z||this.#H||!J)return;this.#z.restart(),this.#K=$;let z,X;try{X=J.call(this.#$.client,(Q)=>{if(this.#Z||!z||this.#H!==z)return;if(z.notices++,z.notices===1)this.#$.onReachable?.(),z.acceptedAt=(this.#$.now??Date.now)(),this.#Q("watching","accepted");if(!this.#z.continuous(Q))this.#K=!0;this.#Y=Q.view,this.#J.request()},{enrollmentToken:Z})}catch(Q){this.#$.onError?.(Q),this.#F("watch-failed");return}z={handle:X,notices:0},this.#H=z,this.#Q("polling",$?"resubscribing":"opening");let G=z;X.closed.then((Q)=>this.#j(G,Q),(Q)=>this.#j(G,{kind:"transport_lost",error:Q}))}#j($,Z){if(this.#Z||this.#H!==$)return;if(this.#H=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#Q("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#F("refused");try{this.#$.onRefused(Z.error)}catch(J){this.#$.onError?.(J)}return}if($.notices>0){let J=(this.#$.now??Date.now)();if($.acceptedAt!==void 0&&J-$.acceptedAt>=300000)this.#W=0;let z=Math.min(1000*2**Math.min(this.#W,16),300000);this.#W++,this.#Q("polling","resubscribing"),this.#U(z,()=>void this.#M(!0));return}this.#F(Z.kind)}#F($){this.#Q("fallback",$),this.#U(300000,()=>void this.#M(!1))}}var P1=60000,g2=4*P1,A4=2*P1,H3=new Map,C1=new Map;function J1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function R4($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!J1(Z)||typeof Z.kind!=="string"||typeof Z.epoch!=="string"||Z.epoch.length===0||typeof Z.seq!=="number"||!Number.isSafeInteger(Z.seq)||Z.seq<1||Z.provider!==void 0&&typeof Z.provider!=="string")return;return{kind:Z.kind,epoch:Z.epoch,seq:Z.seq,...typeof Z.provider==="string"&&{provider:Z.provider}}}function S4($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class x2{transport;key;#$=[];#z=!1;#J=new Set;#X=new Map;#H=new L1(async()=>{try{let $=await this.transport.getUsage();if(!J1($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>J1(Z)&&typeof Z.provider==="string"),this.#z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#J=new Set(this.#z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#J)this.#X.delete(Z)}catch{this.#$=[],this.#z=!1,this.#J.clear()}},()=>{});#G=new Z1;#Z="polling";#Y=0;#K=0;#W=new Map;#Q;#U;#M={};#j=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#H.running)return this.#H.running;if(this.#Z==="watching")return Promise.resolve();for(let[J,z]of C1)if($-z>=P1)C1.delete(J);let Z=C1.get(this.key);if(Z!==void 0&&$-Z<P1)return Promise.resolve();return C1.set(this.key,$),this.#H.request()}watchMode(){return this.#Z}watch($={}){this.#Y++;let Z=$.provider;if(Z===void 0)this.#K++;else this.#W.set(Z,(this.#W.get(Z)??0)+1);if(this.#Y===1)this.#M=$,this.#q();let J=!1;return()=>{if(J)return;if(J=!0,Z===void 0)this.#K--;else{let z=(this.#W.get(Z)??1)-1;if(z>0)this.#W.set(Z,z);else this.#W.delete(Z)}if(--this.#Y===0)this.#F()}}#F(){if(this.#U)(this.#M.clearTimeoutImpl??clearTimeout)(this.#U);this.#U=void 0;let $=this.#Q;this.#Q=void 0,$?.handle?.stop(),this.#Z="polling"}#V($){this.#U=(this.#M.setTimeoutImpl??setTimeout)(()=>{if(this.#U=void 0,this.#Y>0&&!this.#Q)this.#q()},$),this.#U.unref?.()}#q(){let $=this.transport.watchUsage;if(!$){this.#Z="fallback";return}this.#Z="polling",this.#G.restart();let Z={notices:0};this.#Q=Z;let J;try{J=$.call(this.transport,(z)=>this.#B(Z,z))}catch(z){this.#D(Z,z);return}Z.handle=J,J.closed.then(()=>this.#D(Z,void 0),(z)=>this.#D(Z,z))}#B($,Z){if(this.#Q!==$)return;if($.notices++,$.notices===1)this.#Z="watching";if($.notices===2)this.#j=0;let J=R4(Z);if(!J)this.#G.restart();if(!(J?this.#G.continuous(J):!1)||J?.provider===void 0||this.#K>0||this.#W.has(J.provider))this.#H.request()}#D($,Z){if(this.#Q!==$)return;this.#Q=void 0;let J=S4(Z);if(J==="unknown_method"||J==="usage_watch_limit"){this.#Z="fallback";return}if($.notices>0){let z=Math.min(W3*2**Math.min(this.#j,16),D1);this.#j++,this.#Z="polling",this.#V(z);return}if(this.#Z="fallback",this.#H.request(),Z===void 0||M0(Z)==="unreachable")this.#V(D1)}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||!J1(z.usage))continue;let X=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(X)||J-X>=g2)continue;return{entry:z,context:{fetchedAt:X,...typeof z.source==="string"&&{source:z.source}}}}return}lookup($,Z,J){if(!this.#z)return{miss:"unreachable"};let z=this.#$.find((Q)=>Q.provider===$&&typeof Q.account==="string"&&Q.account.trim()===Z),X=(z??this.#$.find((Q)=>Q.provider===$&&Q.account===void 0&&Q.errorClass!==void 0))?.errorClass;if(X==="upstream_failed")return{miss:"upstream-failed"};if(X==="credential_absent"||X==="credential_unusable"||X==="credential_rejected")return{miss:"credential"};if(X!==void 0)return{miss:"unreachable"};if(z){let Q=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!J1(z.usage)||!Number.isFinite(Q))return{miss:"unreachable"};let W={entry:z,context:{fetchedAt:Q,...typeof z.source==="string"&&{source:z.source}}};return J>=Q+g2||z.stale!==void 0?{miss:"stale",reading:W}:{reading:W}}if(this.#J.has($))return{miss:"absent"};let G=this.#X.get($)??J;return this.#X.set($,G),{miss:J-G>=A4?"unreachable":"cold"}}}function Y3($,Z){let J=JSON.stringify([f2($.connectionFile),f2(Z)]),z=H3.get(J);if(!z)z={source:new x2($,J),refs:0},H3.set(J,z);z.refs++;let X=!1;return{source:z.source,release(){if(X)return;if(X=!0,--z.refs===0)H3.delete(J)}}}import{ClaustrumCredentialError as qX}from"@cortexkit/claustrum-client";import{appendFileSync as u4,chmodSync as c4,existsSync as j3,renameSync as a2,statSync as p4}from"node:fs";import{open as d4}from"node:fs/promises";import{dirname as l4,resolve as a4}from"node:path";import{randomUUID as m2}from"node:crypto";import{lstat as w2,readFile as u2,rename as b4,unlink as y2}from"node:fs/promises";import{tmpdir as k4}from"node:os";import{dirname as V0,join as T4,resolve as i}from"node:path";var I=process.platform==="win32",h2=new Set;function U3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var v2;var c2="native-addon-unavailable";function p2($){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:$}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:c2})}function E4($,Z){return Z instanceof $.PrivateFilesUnavailableError||Z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function f4($){try{await $.verifyPrivatePath(T4(k4(),`.common-auth-private-files-probe-${m2()}`),"file")}catch(Z){if(E4($,Z))throw p2(Z)}}function m0(){return v2??=import("@cortexkit/private-files").then(async($)=>{if(I)await f4($);return $},($)=>{throw I?p2($):$}),v2}class u 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(z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"?`Private file refused at ${Z}: ${$} (${c2}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`:`Private file refused at ${Z}: ${$} (${z?.reason??z?.code??"io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`,{cause:J});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=U3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}async function s($,Z,J){try{return await J()}catch(z){if(z instanceof u)throw z;throw new u($,Z,z)}}var g4;async function W0($,Z){$=i($),Z??=g4,await s($,"safe-parent",async()=>{let J=await(await m0()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await w2($);throw new u(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function p($,Z,J=!1){if($=i($),Z==="directory")return W0($);await s($,"verify",async()=>{let z=await m0(),X=await z.verifyOwnerOnly($),G=!1;if(!X.ok){let{reason:Q}=X.refusal;if(Q==="io-error")await z.verifyPrivatePath($,Z);if(J&&[z.EXTRA_ACE,z.NOT_PROTECTED,z.NULL_DACL,z.EMPTY_DACL].includes(Q))await W0(V0($)),await z.securePrivatePath($,Z),G=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:Q,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await z.verifyPrivatePath($,Z),G&&!h2.has($))h2.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function z0($,Z=!1,J){$=i($),await s($,"directory",async()=>{let z=await m0();try{return await w2($),await W0($,J)}catch(G){if(U3(G)!=="ENOENT")throw G}let X=V0($);if(X===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await z0(X,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(U3(G)!=="EEXIST")throw G}await W0($,J)})}async function e($,Z=!1){if(!I)return u2($,"utf8");return(await x4($,Z)).toString("utf8")}async function x4($,Z=!1){if(!I)return u2($);if($=i($),Z)await W0(V0($)),await p($,"file",!0);return s($,"read",async()=>(await m0()).readOwnerOnly($))}async function w0($,Z){await W0(V0(i($))),await s($,"create",async()=>{await(await m0()).createPrivateFile(i($),Z)})}async function d2($){await W0(V0(i($))),await s($,"directory-create",async()=>{await(await m0()).createOwnerOnly(i($),{kind:"dir"})})}async function K3($,Z,J={}){$=i($),Z=i(Z);let z=J.now??(()=>performance.now()),X=z(),G=J.deadline??1/0,Q,W=[0,10,20,40,80,100],H,U=0;for(let K of W){let B=Math.min(Q??1/0,G);if(z()>=B)break;if(K)await(J.sleep??((P)=>new Promise((C)=>setTimeout(C,P))))(Math.min(K,Math.max(0,B-z())));if(z()>=B)break;let F=z();if(await J.beforeRename?.(),Q!==void 0)Q+=z()-F;if(z()>=G)break;U++;try{return await(J.rename??b4)($,Z),{attempts:U,elapsedMs:z()-X}}catch(P){H??=P;let C=P;if(!(C.win32Code!==void 0?C.win32Code===32||C.win32Code===33:["EBUSY","EPERM","EACCES"].includes(C.code??"")&&!C.reason))break;Q??=z()+500}}let q=new u(Z,"rename",H??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw q.attempts=U,q.elapsedMs=z()-X,q}async function u0($,Z,J={}){$=i($),await z0(V0($));try{await p($,"file",!0)}catch(U){if(U.code!=="ENOENT")throw U}let z=i(J.stagePath??`${$}.${m2()}.tmp`);if(V0(z)!==V0($))throw new u($,"stage-directory",{code:"EXDEV"});let X=!1,G=!1,Q={attempts:0,elapsedMs:0},W="stage-create",H=(U)=>{try{J.onOutcome?.({path:$,stage:U?.stage??"published",published:G,fileDurable:G,durabilityConfirmed:!1,attempts:U?.attempts??Q.attempts,elapsedMs:U?.elapsedMs??Q.elapsedMs,...U&&{code:U.code,win32Code:U.win32Code}})}catch{}};try{if(await w0(z,Z),X=!0,W="before-rename",Q=await K3(z,$,J),X=!1,G=!0,W="published-callback",J.onRenamed?.(),W="published-verify",await p($,"file"),J.durable&&J.durability!=="file-only-on-windows")throw new u($,"directory-sync-unsupported",{code:"ENOTSUP"});H()}catch(U){let q=U instanceof u?U:new u($,W,U);if(q.published=G,q.fileDurable=G,G)Object.assign(q,Q);if(X){try{await y2(z)}catch{q.orphanPath=z}X=!1}throw H(q),q}finally{if(X)await y2(z).catch(()=>{})}}var y4=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,h4=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function v4($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function c0($={}){let Z=[h4,...$.extraValuePatterns??[]].map((G)=>new RegExp(G.source,G.flags.includes("g")?G.flags:`${G.flags}g`));function J(G){let Q=G.toLowerCase().replace(/[-_]/g,"");return y4.test(G)||Q.includes("apikey")||Q.endsWith("secret")||Q.endsWith("password")||Q.endsWith("token")&&!Q.endsWith("tokens")||!!$.extraSecretKeys?.(Q)}function z(G){let Q=G,W=[["name",G.name],["message",G.message],["stack",G.stack]];for(let U of["code","status","cause"])if(Q[U]!==void 0)W.push([U,Q[U]]);let H=new Set(W.map(([U])=>U));for(let U of Object.entries(G))if(!H.has(U[0]))W.push(U);return W}function X(G,Q,W,H=0){if(typeof G==="string")return Z.reduce((U,q)=>U.replace(q,"***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((K)=>X(K,Q,W,H));let U=v4(G);if(U&&H>=8)return"[Truncated]";let q=U?H+1:H;return Object.fromEntries((U?z(G):Object.entries(G)).map(([K,B])=>[K,Q&&J(K)?"***REDACTED***":X(B,Q,W,q)]))}finally{W.delete(G)}}return{redact:(G)=>X(G,!0,new WeakSet),redactStrings:(G)=>X(G,!1,new WeakSet)}}var l2=c0(),m4=l2.redact,w4=l2.redactStrings;var O1={error:0,warn:1,info:2,debug:3,trace:4},n2=5242880,i2=3;function M3($){try{c4($,384)}catch{}}function s4($){try{if(!(j3($)&&p4($).size>=n2))return;for(let J=i2-1;J>=1;J--)if(j3(`${$}.${J}`)){let z=`${$}.${J+1}`;a2(`${$}.${J}`,z),M3(z)}let Z=`${$}.1`;a2($,Z),M3(Z)}catch{}}async function H0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await s(Z,"log-close",()=>J.close())}async function s2($,Z){await z0(l4(Z));try{await p(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await w0(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await p(Z,"file",!0)}}return $.handle=await s(Z,"log-open",()=>d4(Z,"a")),$.file=Z,$.handle}async function n4($,Z,J){Z=a4(Z);try{if($.file!==Z)await H0($);let z=$.handle??await s2($,Z);if((await s(Z,"log-stat",()=>z.stat())).size>=n2){await H0($);for(let G=i2-1;G>=0;G--){let Q=G===0?Z:`${Z}.${G}`,W=`${Z}.${G+1}`;try{await p(Q,"file",!0)}catch(H){if(H.code==="ENOENT")continue;throw H}try{await p(W,"file",!0)}catch(H){if(H.code!=="ENOENT")throw H}await K3(Q,W),await p(W,"file")}z=await s2($,Z)}await s(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await H0($).catch(()=>{}),z}}function i4($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function r4($){let Z,J,z,X=c0(),G,Q=[],W,H=Promise.resolve(),U,q={};function K(Y){let j=H.then(Y);return H=j.catch((M)=>{U=M}),j}function B(Y){if(I&&Y.file!==Z)K(()=>H0(q)).catch(()=>{});Z=Y.file,J=Y.level,X=c0(Y),G=Y.captureSink}function F(Y){if(Y===void 0||Y in O1)z=Y}function P(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function C(){if(z)return z;let Y=typeof J==="function"?J():J;if(Y&&Y in O1)return Y;return"info"}function D(Y=!0){if(W)clearTimeout(W),W=void 0;if(!Q.length){if(I)return K(async()=>{if(Y)await H0(q);if(U)throw U});return}let j;try{j=P()}catch{if(Q=[],I&&Y)return K(()=>H0(q));return}let M=Q.join("");if(Q=[],!j){if(I&&Y)return K(()=>H0(q));return}if(I)return K(async()=>{try{await n4(q,j,M)}finally{if(Y)await H0(q)}});try{if(s4(j),j3(j))M3(j);u4(j,M,{encoding:"utf8",mode:384})}catch{}}function R(){if(!W)W=setTimeout(()=>{W=void 0;let Y=D(!1);if(Y instanceof Promise)Y.catch(()=>{})},500)}function S(Y,j,M,b){if(Z===void 0&&G===void 0)return;try{if(O1[j]>O1[C()])return;let x=X.redactStrings(M),k;try{k=X.redact(b)}catch{k="[unserializable]"}let m=`[${new Date().toISOString()}] ${j.toUpperCase()} [${Y}] ${x}`+(b===void 0?"":i4(k))+`
|
|
3
|
-
`;try{G?.({channel:Y,level:
|
|
4
|
-
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??
|
|
5
|
-
`,"utf8"),await G.chmod(384),J.durable)try{await G.sync()}catch(W){throw new
|
|
6
|
-
`,{deadline:performance.now()+Math.max(0,
|
|
7
|
-
`,"utf8"),await N.chmod(384),await N.close(),N=void 0;let y=await Y();if(y?.ownerId!==z||!(Number(y?.expiresAt)>X())||!await
|
|
8
|
-
`;if(
|
|
9
|
-
`;if(
|
|
10
|
-
`)){if(z.trim()===""||z.startsWith("#"))continue;let X=z.split(":");if(X.length!==Z||!/^[^\s:,]+$/.test(X[0]??"")||!/^\d+$/.test(X[2]??"")||!Number.isSafeInteger(Number(X[2]))||Z===7&&(!/^\d+$/.test(X[3]??"")||!Number.isSafeInteger(Number(X[3])))||Z===4&&X[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(X[3]??""))return;J.push(X)}return J}async function
|
|
11
|
-
`;if(Buffer.byteLength(X)>S1)throw new _("invalid-state","Claustrum enrollment state is too large");if(I)return u0($,X);let G=j7(z,`.${K7($)}.${process.pid}.${W7()}.tmp`),Q,W=!1;try{Q=await q$(G,"wx",384),W=!0,await Q.writeFile(X,"utf8"),await Q.chmod(384),await Q.sync(),await Q.close(),Q=void 0,await q7(G,$),W=!1}finally{if(await Q?.close().catch(()=>{}),W)await C3(G).catch(()=>{})}}async function k1($,Z){let J=await S0($.tokenPath),z=J===void 0?void 0:_3(J),X=await S0($.statePath),G=X===void 0?void 0:O3(X);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 F0(G)}async function B0($){let Z=await S0($);if(Z===void 0)throw new _("not-enrolled","Claustrum enrollment is not configured");return _3(Z)}function F0($){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 _("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class I3{#$;#z;#J;#X;#H;#G;#Z;constructor($){this.#Z=$.ancestorOptions??{},this.#$=$.client,this.#z=$.paths,this.#J=$.proposedName,this.#X=$.now??Date.now,this.#H=$.mintSecret??(()=>Q7(32).toString("hex")),this.#G=$.writeTokenFile??V7}async status(){return k1(this.#z,this.#J)}async resetTerminal(){return P$(this.#z,this.#J)}async#Y($,Z){let J={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#X()};return await A0(this.#z.statePath,J,this.#Z),F0(J)}async reconcile(){await b1(R0(this.#z.statePath),this.#Z);let $=await Y0({name:"ceremony",path:this.#z.statePath,ttlMs:j$,renew:!0});if(!$)return{state:"busy"};try{let Z=await S0(this.#z.tokenPath),J=Z===void 0?void 0:_3(Z),z=await S0(this.#z.statePath),X=z===void 0?void 0:O3(z);if(X&&X.proposedName!==this.#J)throw C$();if(J){if(!X||X.phase==="pending"){let Q={version:1,phase:"approved",proposedName:X?.proposedName??this.#J,tokenGeneration:J.token_generation,updatedAt:this.#X()};await A0(this.#z.statePath,Q,this.#Z),X=Q}return{state:"approved",proposedName:X.proposedName,...X.phase==="approved"&&X.approvedName!==void 0&&{approvedName:X.approvedName},tokenGeneration:J.token_generation}}if(X?.phase==="approved"){let Q={version:1,phase:"blocked",proposedName:X.proposedName,errorCode:"missing_token",updatedAt:this.#X()};return await A0(this.#z.statePath,Q,this.#Z),F0(Q)}if(X&&X.phase!=="pending")return F0(X);if(!X){let Q=this.#X();if(X={version:1,phase:"pending",proposedName:this.#J,requestSecret:this.#H(),createdAt:Q,updatedAt:Q},!P3.test(X.requestSecret))throw new _("invalid-state","invalid minted Claustrum enrollment secret");await A0(this.#z.statePath,X,this.#Z)}if(!X.requestId)try{let Q=G7("sha256").update(Buffer.from(X.requestSecret,"hex")).digest("hex"),W=await this.#$.enrollPropose({name:X.proposedName,requestSecretHash:Q});X={...X,requestId:W.requestId,updatedAt:this.#X()},await A0(this.#z.statePath,X,this.#Z)}catch(Q){let W=N3(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,retryCode:W.code};if(W.code===M$)return await $.assertOwned(),await C3(this.#z.statePath).catch((H)=>{if(H.code!=="ENOENT")throw H}),{state:"unavailable",proposedName:X.proposedName,code:W.code};return this.#Y(X,W.code)}let G=X.requestId;if(!G)return F0(X);try{let Q=await this.#$.enrollPoll({requestId:G,requestSecret:X.requestSecret});if(Q.status==="pending")return F0(X);if(Q.status==="denied"){let H={version:1,phase:"denied",proposedName:X.proposedName,updatedAt:this.#X()};return await A0(this.#z.statePath,H,this.#Z),F0(H)}await b1(R0(this.#z.tokenPath),this.#Z),await N$(R0(this.#z.tokenPath),this.#Z),await this.#G(this.#z.tokenPath,{token:Q.token,token_generation:Q.tokenGeneration});let W={version:1,phase:"approved",proposedName:X.proposedName,approvedName:Q.name,tokenGeneration:Q.tokenGeneration,updatedAt:this.#X()};return await A0(this.#z.statePath,W,this.#Z),F0(W)}catch(Q){let W=N3(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,requestId:G,retryCode:W.code};return this.#Y(X,W.code)}}finally{await $.release()}}}async function P$($,Z){await b1(R0($.statePath));let J=await Y0({name:"ceremony",path:$.statePath,ttlMs:j$,renew:!0});if(!J)return"busy";try{if(await S0($.tokenPath)!==void 0)return"refused-approved";let z=await S0($.statePath);if(z===void 0)return"idle";let X=O3(z);if(X.proposedName!==Z)throw C$();if(X.phase==="pending")return"refused-pending";return await J.assertOwned(),await C3($.statePath),"reset"}finally{await J.release()}}var A3="claustrum-tombstone:v1:";function _$($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function L7($,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 S3=O0("claustrum");function k3($,Z,J,z=S3){let X=_$(Z,J);return z.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:J?.recordVersion??null,retry:X,reason:L7(Z,J)}),X}var b3=300000,I$=60000;function R3(){return new _("invalid-material","Claustrum returned invalid credential material")}function N7($){let Z=$.trim();if(Z.startsWith("{")){let J;try{J=JSON.parse(Z)}catch{throw R3()}if(!J||typeof J!=="object")throw R3();let z=J,X=z.access_token??z.access;Z=typeof X==="string"?X:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(A3))throw R3();return Z}function C7($,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}function P7($){let{grants:Z,grantTuples:J}=$;if(Z===void 0||J===void 0)return;return Object.freeze({grants:Z,tuples:Object.freeze(J.map(({selectorKind:z,selector:X,operation:G})=>Object.freeze({selectorKind:z,selector:X,operation:G})))})}class T1{#$;#z;#J;#X;#H;#G;#Z;#Y=new WeakMap;#K=new WeakMap;#W=new Map;#Q=new WeakMap;#U;#M;#j=!1;#F=new P0;#V;#q=!1;#B=-1/0;#D=2000;#L=!1;#C;#P=new Set;constructor($){let Z=$.tokenPath;if($.readToken)this.#z=$.readToken;else if(Z)this.#z=()=>B0(Z);else throw new _("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#X=$.family,this.#H=$.parseIdentity,this.#G=$.requireAssertion??!1,this.#J=$.now??Date.now,this.#Z=$.logger??S3,this.#U=$.setTimeoutImpl??setTimeout,this.#M=$.clearTimeoutImpl??clearTimeout}transportLost($){if(this.#L||this.#j)return;this.#j=!0,this.#F=$ instanceof O$?$:new P0,this.#Z.warn("serving kept vault receipt",{reason:"unreachable"}),this.#O()}reachable(){if(this.#L||!this.#j)return;if(this.#j=!1,this.#V)this.#M(this.#V);this.#V=void 0,this.#D=2000;for(let $ of this.#W.values())$.since=null;(this.#Z.info??S3.info)("vault receipt serving resumed",{reason:"reachable"})}#O(){if(this.#L||!this.#j||this.#V||this.#q)return;this.#V=this.#U(()=>{this.#V=void 0,this.#_(!0)},this.#D),this.#V.unref?.()}#_($=!1){if(this.#L||!this.#j||this.#q)return;if(this.#J()-this.#B<1000){this.#O();return}this.#B=this.#J(),this.#q=!0,this.#R().catch(()=>{if($&&this.#j)this.#D=Math.min(this.#D*2,30000)}).finally(()=>{this.#q=!1,this.#O()})}#N($){if(this.#L)throw new _("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#I($){this.#N($);let Z=await this.#z();if(this.#N($),!/^[0-9a-f]{64}$/.test(Z.token)||!Number.isSafeInteger(Z.token_generation)||Z.token_generation<1)throw new _("invalid-token","Invalid Claustrum enrollment token");return Z.token}async#A($,Z){this.#N(Z);let J,z;try{let X=$();J=Z?await Promise.race([X,new Promise((G,Q)=>{let W=()=>Q(Z.reason);if(Z.addEventListener("abort",W,{once:!0}),z=()=>Z.removeEventListener("abort",W),Z.aborted)W()})]):await X}catch(X){if(this.#N(Z),M0(X)==="unreachable")this.transportLost(X);else this.reachable();if(X instanceof O$)throw X;if(M0(X)==="unreachable")throw new P0;throw new _("unavailable","Claustrum scoped operation unavailable")}finally{z?.()}return this.#N(Z),this.reachable(),J}async discover($){let Z=await this.#R($);return this.#C=Z.view,Z}async#R($){let Z,J;try{J=await this.#I($)}catch(H){throw this.#W.clear(),H}try{Z=await this.#A(()=>this.#$.listScoped(J),$)}catch(H){throw this.listFailed(H),H}let z=[],X=[],G=new Map;for(let H of Z.rows){let U=C7(H,this.#X);if(!U)continue;X.push({row:H,type:U}),G.set(H.id,(G.get(H.id)??0)+1)}let Q=[];for(let{row:H,type:U}of X){let q;if(!H.id.trim())q="empty credential id";else if((G.get(H.id)??0)>1)q="duplicate credential id";else if(H.accountId!==void 0&&!H.accountId.trim())q="blank account identity";else if(!H.state.trim())q="empty state";if(q){z.push({...H.id.trim()&&{credentialId:H.id},reason:q});continue}Q.push(Object.freeze({credentialId:H.id,credentialType:U,...H.accountId!==void 0&&{accountIdentity:H.accountId},state:H.state,...H.email!==void 0&&{email:H.email},...H.orgName!==void 0&&{orgName:H.orgName}}))}for(let H of z)this.#Z.warn("skipped malformed vault record",H);let W=P7(Z);return{view:Z.view,credentials:Object.freeze(Q),skipped:Object.freeze(z),...W&&{grantReach:W}}}listFailed($){if(M0($)==="unreachable")this.transportLost($);else this.reachable(),this.#W.clear()}forget($){this.#W.delete($)}retain($){let Z=new Map($.map((J)=>[J.credentialId,J]));for(let[J,z]of this.#W){let X=Z.get(J);if(!X?.enabled||X.state!=="active"||X.credentialType!==z.attempt.credentialType||X.accountIdentity!==z.attempt.expectedAccountIdentity)this.forget(J)}}keptReceiptState(){let $=null;for(let[Z,J]of this.#W){if(!this.#S(J.attempt)){this.forget(Z);continue}if(J.since!==null)$=Math.min($??J.since,J.since)}return Object.freeze({active:$!==null,since:$})}#S($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#J()>I$}async authorize($,Z,J="vault"){this.#N(Z);let{credentialId:z,credentialType:X,accountIdentity:G}=$,Q=this.#W.get(z);if(Q&&(Q.attempt.credentialType!==X||Q.attempt.expectedAccountIdentity!==G))this.forget(z),Q=void 0;let W;try{W=await this.#I(Z)}catch(H){throw this.#W.clear(),H}if(this.#j&&Q)return this.#_(),this.#b(z,Q,W,J);try{let H=await this.#k({credentialId:z,credentialType:X,accountIdentity:G},W,Z);return this.#W.set(z,{attempt:H,routeId:J,since:null}),H}catch(H){if(this.#N(Z),M0(H)!=="unreachable")throw this.forget(z),H;return this.#b(z,Q,W,J,H)}}#b($,Z,J,z,X=this.#F){if(!Z||this.#W.get($)!==Z||!this.#S(Z.attempt))throw this.forget($),X;if(Z.since===null)Z.since=this.#J();let G=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#Y.set(G,J),this.#Q.set(G,z),G}async#k($,Z,J){if(!$.credentialId)throw new _("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:z,credentialType:X,accountIdentity:G}=$;if(this.#G&&G===void 0)throw new _("identity-unasserted","Claustrum dispatch requires a known account identity");let Q=await this.#A(()=>this.#$.getScoped({credentialId:z,enrollmentToken:Z,...X==="oauth"&&{minTtlMs:b3}}),J);if(Q.credentialId!==void 0&&Q.credentialId!==z)throw new _("identity-changed","Claustrum served credential identity changed");let W=Q.expiresAtMs;if(!Number.isSafeInteger(Q.recordVersion)||Q.recordVersion<0||W===null&&X==="oauth"||W!==null&&(!Number.isFinite(W)||W-this.#J()<b3))throw new _("insufficient-validity","Claustrum served credential has insufficient validity");let H=N7(Q.material),U=Q.accountId?.trim()?Q.accountId:void 0;if(this.#G&&(Q.credentialId===void 0||U===void 0))throw new _("identity-unasserted","Claustrum served credential did not assert its identity");let q=U===void 0?this.#H?.(H):void 0,K=U??q;if(G!==void 0&&K!==void 0&&K!==G)throw new _("identity-changed","Claustrum served credential identity changed");let B=K??G,P=Object.freeze(Object.defineProperty({credentialId:z,credentialType:X,...B!==void 0&&{accountIdentity:B},accountIdentitySource:U!==void 0?"asserted":q!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...Q.credentialId!==void 0&&{assertedCredentialId:Q.credentialId},...U!==void 0&&{assertedAccountIdentity:U},...Q.projectId!==void 0&&{projectId:Q.projectId},recordVersion:Q.recordVersion,expiresAtMs:W},"accessToken",{value:H,enumerable:!1}));return this.#Y.set(P,Z),P}async reportFailure($,Z,J){if(Z!==401)return;this.#N();let z=this.#Y.get($);if(!z)throw new _("no-receipt","Claustrum failure report requires an original dispatch receipt");let X=this.#Q.get($);if(X!==void 0){this.forget($.credentialId),this.#Z.debug("scoped 401 not reported",{routeId:X,reason:"kept-receipt"});return}let G=this.#W.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let Q=this.#K.get($);if(Q)return Q;let W=this.#A(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:z,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#K.set($,W);try{await W,this.#Z.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:J})}catch(H){throw this.#K.delete($),H}}watchRoster($){this.#N();let Z=new N1({client:this.#$,enrollmentToken:()=>this.#I(),view:$.view??(()=>this.#C),discover:async(J)=>{await $.onView(J)},onRefused:(J)=>{this.listFailed(J),$.onRefused?.(J)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#Z,now:this.#J,setTimeoutImpl:this.#U,clearTimeoutImpl:this.#M});return this.#P.add(Z),Z.start(),{get mode(){return Z.mode},close:()=>{this.#P.delete(Z),Z.stop()}}}close(){if(this.#L)return;if(this.#L=!0,this.#V)this.#M(this.#V);this.#V=void 0;for(let $ of this.#P)$.stop();this.#P.clear(),this.#W.clear(),this.#$.close()}}import{resolve as a3}from"node:path";var b0="all",O7=Object.freeze(["primary"]);function R$($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function d0($,Z){return JSON.stringify([$,Z])}function D0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function d($){return typeof $==="number"&&Number.isFinite($)}function A$($){return typeof $==="string"&&$.length>0}function l($,Z,J){return $[Z]===void 0||J($[Z])}function _7($){return d($)&&$>0}function T3($){return typeof $==="string"}function I7($){if(!D0($)||!A$($.scope)||!A$($.label))return!1;switch($.kind){case"reading":return d($.checkedAt)&&d($.usedPercent)&&l($,"resetsAt",T3)&&l($,"windowMinutes",_7);case"retired":return d($.retiredAt);case"absent":return d($.checkedAt);default:return!1}}function A7($){if(!D0($)||!d($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&l($,"remainingPercent",d)&&l($,"usedPercent",d)&&l($,"resetsAt",T3)&&l($,"limit",d)&&l($,"used",d)&&l($,"remaining",d)&&l($,"unit",T3)}function S$($){return D0($)&&d($.value)&&Number.isInteger($.value)&&$.value>=0&&d($.checkedAt)}function E3($){return D0($)&&Object.values($).every(S$)}function R7($){return typeof $==="boolean"}function l0($){return D0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&l($,"balance",d)&&l($,"overageLimitReached",R7)&&d($.checkedAt)}function b$($){if(!D0($))return;let Z=Object.entries($).filter(([,J])=>S$(J));return Z.length===0?void 0:Object.fromEntries(Z)}function k0($){if(p0($))return $;if(!D0($))return;let{counters:Z,credits:J,...z}=$;if(!p0(z))return;let X=b$(Z),G=l0(J)?J:void 0;return{...z,...X===void 0?{}:{counters:X},...G===void 0?{}:{credits:G}}}function p0($){if(!D0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!I7(J))return!1;let z=d0(J.scope,J.label);if(Z.has(z))return!1;Z.add(z)}return l($,"budget",A7)&&l($,"counters",E3)&&l($,"credits",l0)}class E1 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function g1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function f1($){return typeof $==="number"&&Number.isFinite($)}function k$($){return $===void 0||typeof $==="string"&&$!==""}function T$($){return typeof $==="string"&&$!==""}function G1($,Z){return $[Z]===void 0||f1($[Z])}function f3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function S7($){return g1($)&&k$($.scope)&&T$($.label)&&f1($.usedPercent)&&f3($,"resetsAt")&&($.windowMinutes===void 0||f1($.windowMinutes)&&$.windowMinutes>0)}function b7($){return g1($)&&k$($.scope)&&T$($.label)}function k7($){if(!g1($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&G1($,"remainingPercent")&&G1($,"usedPercent")&&f3($,"resetsAt")&&G1($,"limit")&&G1($,"used")&&G1($,"remaining")&&f3($,"unit")}function a0($){if(!g1($)||!f1($.checkedAt))return!1;let Z=$.readings??[],J=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(J))return!1;let z=new Set;for(let X of Z){if(!S7(X))return!1;let G=d0(X.scope??b0,X.label);if(z.has(G))return!1;z.add(G)}if(!J.every(b7))return!1;return($.budget===void 0||k7($.budget))&&($.counters===void 0||E3($.counters))&&($.credits===void 0||l0($.credits))}function T7($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function E7($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function f7($,Z){let J=new Map(Object.entries($??{}));for(let[z,X]of Object.entries(Z??{})){let G=J.get(z);if(G===void 0||X.checkedAt>=G.checkedAt)J.set(z,X)}return J.size===0?void 0:Object.fromEntries(J)}function g7($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function Q1($,Z){let J=$===void 0?void 0:k0($);if($!==void 0&&J===void 0)throw new E1("stored quota map is malformed");if(!a0(Z))throw new E1("quota observation is malformed");let z=J??{limits:[]},X=Z.checkedAt,G=new Map;for(let D of z.limits)G.set(d0(D.scope,D.label),D);let Q=(D)=>{let R=G.get(D);return R===void 0||X>=R$(R)},W=new Set;for(let D of Z.readings??[]){let R=D.scope??b0,S=d0(R,D.label);if(W.add(S),!Q(S))continue;G.set(S,{scope:R,label:D.label,kind:"reading",checkedAt:X,usedPercent:D.usedPercent,...D.resetsAt===void 0?{}:{resetsAt:D.resetsAt},...D.windowMinutes===void 0?{}:{windowMinutes:D.windowMinutes}})}for(let D of Z.coverage??[]){let R=D.scope??b0,S=d0(R,D.label);if(W.has(S)||!Q(S))continue;let h=G.get(S);G.set(S,h===void 0||h.kind==="absent"?{scope:R,label:D.label,kind:"absent",checkedAt:X}:{scope:R,label:D.label,kind:"retired",retiredAt:X})}let{limits:H,budget:U,counters:q,credits:K,...B}=z,F=E7(z.budget,Z.budget,X),P=f7(z.counters,Z.counters),C=g7(z.credits,Z.credits);return{...B,limits:[...G.values()].sort(T7),...F===void 0?{}:{budget:F},...P===void 0?{}:{counters:P},...C===void 0?{}:{credits:C}}}var x7=Object.freeze({validate:p0,decode:k0,merge:Q1});import{createHash as m7}from"node:crypto";import{resolve as g$}from"node:path";function E$($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function g3($,Z,J){return $.some((z)=>E$(z,Z,J))}function x3($,Z,J){let z={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((X)=>X.credentialId!==Z||X.accountIdentity!==J),z]}function y3($,Z,J){return $.filter((z)=>!Z.some((X)=>E$(z,X,J)))}var x$="vault:";function w7($){return m7("sha256").update($).digest("hex")}function u7($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function c7($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function L0($){return[$.credentialId,...$.aliases??[]]}function y$($,Z,J={}){let z=J.now??Date.now(),X=J.routePrefix??x$,G=J.reservedRouteIds??new Set,Q=$?.rows??[],W=[...$?.declined??[]],H=Z.skipped.length===0,U=new Set(Z.credentials.map((L)=>L.credentialId)),q=new Set(Z.skipped.flatMap((L)=>L.credentialId===void 0?[]:[L.credentialId])),K=Z.skipped.some((L)=>L.credentialId===void 0),B=(L)=>!U.has(L)&&(q.has(L)||K),F=new Map;for(let L of Q){if(L.accountIdentity===void 0)continue;for(let Y of L0(L))if(!F.has(Y))F.set(Y,L.accountIdentity)}let P=new Map;for(let L of Z.credentials){let Y=L.accountIdentity!==void 0?{credential:L,identity:L.accountIdentity,claimed:!0}:{credential:L,identity:F.get(L.credentialId),claimed:!1},j=c7(Y),M=P.get(j)??[];M.push(Y),P.set(j,M)}let C=new Set,D=new Set(G),R=[],S=(L,Y)=>L.credential.credentialId.localeCompare(Y.credential.credentialId),h=[...P.values()].map((L)=>L.toSorted(S)).sort((L,Y)=>L[0]&&Y[0]?S(L[0],Y[0]):0);for(let L of h){let Y=L[0]?.identity,j=L.filter((T)=>T.credential.state==="active"),M=j.length?j:L,b=M.filter((T)=>T.claimed),x=b.length?b:M,k=new Set(L.map((T)=>T.credential.credentialId)),m=Q.find((T)=>!C.has(T)&&L0(T).some((Q0)=>k.has(Q0))&&(T.accountIdentity===void 0||T.accountIdentity===Y)),n=x.find((T)=>T.credential.credentialId===m?.credentialId)??x[0];if(!n)continue;let v=n.credential,c=m??(Y===void 0?void 0:Q.find((T)=>!C.has(T)&&T.accountIdentity===Y));if(c)C.add(c);let t=c?.routeId;if(!t||G.has(t)){let T=`${X}${v.credentialId}${Y===void 0?"":`~${w7(Y).slice(0,10)}`}`;t=T;for(let Q0=2;D.has(t);Q0++)t=`${T}~${Q0}`}D.add(t);let V1=c?L0(c).filter(B):[],v0=[...new Set([...L.map((T)=>T.credential.credentialId),...V1])].filter((T)=>T!==v.credentialId).sort((T,Q0)=>T.localeCompare(Q0)),F1=J.mapAccount?.(v)??{};R.push({previousIndex:c?Q.indexOf(c):1/0,row:{routeId:t,credentialId:v.credentialId,credentialType:v.credentialType,...Y!==void 0&&{accountIdentity:Y},...v0.length&&{aliases:v0},state:v.state,label:F1.label?.trim()||u7(v),...v.email!==void 0&&{email:v.email},...v.orgName!==void 0&&{orgName:v.orgName},enabled:![v.credentialId,...v0].some((T)=>g3(W,T,Y)),addedAt:c?.addedAt??z,...c?.quota!==void 0&&{quota:c.quota},...!n.claimed&&Y!==void 0&&{unclaimed:!0}}})}return Q.forEach((L,Y)=>{if(C.has(L)||!L0(L).some(B))return;if(D.has(L.routeId))return;let[j,...M]=L0(L).filter((k)=>!U.has(k));if(j===void 0)return;D.add(L.routeId);let{aliases:b,...x}=L;R.push({previousIndex:Y,row:{...x,credentialId:j,...M.length&&{aliases:M},stale:!0}})}),R.sort((L,Y)=>L.previousIndex===Y.previousIndex?L.row.credentialId.localeCompare(Y.row.credentialId):L.previousIndex-Y.previousIndex),{version:1,view:Z.view,complete:H,...!H&&{rejected:Z.skipped.map((L)=>({...L.credentialId!==void 0&&{credentialId:L.credentialId},reason:L.reason}))},rows:R.map((L)=>L.row),declined:W}}function h3($){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 W1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function s0($){return $===void 0||typeof $==="string"}function p7($){let Z=W1($)?k0($.quota):void 0;if(!W1($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!s0($.accountIdentity)||!s0($.email)||!s0($.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 d7=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function f$($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!W1(J)||!s0(J.credentialId)||typeof J.reason!=="string"||!d7.has(J.reason))return;Z.push(J)}return Z}function l7($){if(!W1($)||$.version!==1||!s0($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!f$($.rejected))throw new _("invalid-state","Claustrum roster file is not valid");let Z=[];for(let X of $.rows){let G=p7(X);if(!G)throw new _("invalid-state","Claustrum roster file is not valid");Z.push(G)}let J=[];for(let X of $.declined){if(!W1(X)||typeof X.credentialId!=="string"||!s0(X.accountIdentity))throw new _("invalid-state","Claustrum roster file is not valid");J.push(X)}let z=f$($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...z&&{rejected:z},rows:Z,declined:J}}async function r($){let Z;try{Z=await e($,I)}catch(z){if(z.code==="ENOENT")return;throw z}let J;try{J=JSON.parse(Z)}catch{throw new _("invalid-state","Claustrum roster file is not valid")}return l7(J)}var a7={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},s7={name:"claustrum-roster",ttlMs:30000};async function T0($,Z,J={}){return B3($,{...a7,signal:J.signal},async(z)=>{let X=await r($),{next:G,result:Q}=await Z(X,{assertOwned:()=>z.assertOwned()});if(G)await z.assertOwned(),await z1($,G,{beforeRename:async()=>{await J.beforePublish?.(),J.signal?.throwIfAborted(),await z.assertOwned()}});return Q})}function v3($,Z){return T0($,(J)=>{let z=J?.rows.find((G)=>G.routeId===Z);if(!J||!z)throw new _("route-unavailable","Claustrum route is not in the roster");let X=x3(J.declined,z.credentialId,z.accountIdentity);return{next:{...J,declined:X,rows:J.rows.map((G)=>G===z?{...G,enabled:!1}:G)},result:void 0}})}function m3($,Z){return T0($,(J)=>{let z=J?.rows.find((X)=>X.routeId===Z);if(!J||!z)throw new _("route-unavailable","Claustrum route is not in the roster");return{next:{...J,declined:y3(J.declined,L0(z),z.accountIdentity),rows:J.rows.map((X)=>X===z?{...X,enabled:!0}:X)},result:void 0}})}function n7($){return new _("invalid-order",$)}function i7($,Z){if(!Array.isArray(Z))return"route ids must be an array of route ids";let J=new Set($.map((G)=>G.routeId)),z=new Set;for(let G of Z){if(typeof G!=="string")return"route ids must be an array of route ids";if(z.has(G))return`route id ${G} appears more than once`;if(!J.has(G))return`route id ${G} is not in the roster`;z.add(G)}let X=[...J].filter((G)=>!z.has(G)).length;if(X>0)return`the order leaves out ${X} roster route id${X===1?"":"s"}`;return}function w3($,Z,J={}){return T0($,(z)=>{let X=z?.rows??[],G=i7(X,Z);if(G)throw n7(G);let Q=new Map;for(let U of X){let q=Q.get(U.routeId);if(q)q.push(U);else Q.set(U.routeId,[U])}let W=[...Z],H=W.flatMap((U)=>Q.get(U)??[]);if(!z||H.every((U,q)=>U===X[q]))return{result:{ids:W,outcome:"unchanged"}};return{next:{...z,rows:H},result:{ids:W,outcome:"reordered"}}},{...J.signal&&{signal:J.signal}})}function r7($,Z){if(!L0($).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")&&L0($).length===1)return"bind";return"refuse"}async function u3($,Z){let{routeId:J,observation:z,...X}=Z;return h$($,{routeId:J,observation:z,accountIdentity:X.accountIdentity,receipt:X})}async function h$($,Z){if(!a0(Z.observation))return!1;let J=X0($,await r($));if(!N0(J,Z).kept)return!1;return v$($,Z)}function c3($,Z){return h$($,Z)}function N0($,Z){let J=$?.rows.find((Q)=>Q.routeId===Z.routeId),z=!J?"refuse":Z.receipt?r7(J,Z.receipt):J.accountIdentity!==void 0&&J.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!J||z==="refuse")return{roster:$,kept:!1};let X=Q1(J.quota,Z.observation),G=z==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{roster:{...$,rows:$.rows.map((Q)=>Q===J?{...Q,...G,quota:X}:Q)},kept:!0}}var x1=new Map;function p3($){x1.delete(g$($))}async function d3($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){p3($.path);return}let J=await Y0({...s7,path:$.path,renew:!0});if(!J){let G=await r($.path);if($.signal?.throwIfAborted(),!G?.view)throw new _("roster-busy","Claustrum account discovery is already in progress");return G}let z=g$($.path),X;try{let G=await r($.path),Q=x1.get(z);X=Q&&(Q.previousView===G?.view||Q.inventory.view===G?.view)?Q:{inventory:await $.custody.discover($.signal),previousView:G?.view},x1.delete(z);let{inventory:W}=X;return $.onInventory?.(W),$.signal?.throwIfAborted(),await T0($.path,async(H)=>{if(!await Z())return{result:void 0};$.signal?.throwIfAborted(),await J.assertOwned();let U=typeof $.projection==="function"?$.projection():$.projection,q=y$(H,W,U);return{...JSON.stringify(H)!==JSON.stringify(q)&&{next:q},result:q}},{beforePublish:async()=>{$.signal?.throwIfAborted(),await J.assertOwned()}})}catch(G){if(G instanceof _0&&X&&!$.signal?.aborted&&await Z())x1.set(z,X);throw G}finally{await J.release()}}var n0=new Map,o7=O0("claustrum"),m$=100;function w$($){let Z=a3($),J=n0.get(Z);if(!J)J={path:Z,pending:new Map,listeners:new Set,wake:new Set,abort:new AbortController,failures:0,draining:!1,order:0},n0.set(Z,J);return J}function u$($,Z){let J=w$($);J.listeners.add(Z);let z;return()=>z??=(()=>{return J.listeners.delete(Z),J.listeners.size?Promise.resolve():l3($)})()}function t7($){let Z=new Map,{observation:J}=$,z=JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]),X=(W,H,U)=>Z.set(`${z}:${W}`,{at:H,order:0,publication:{...$,observation:U}}),G=(W,H)=>JSON.stringify([W??"all",H]),Q=new Set;for(let W of J.readings??[]){let H=G(W.scope,W.label);Q.add(H),X(H,J.checkedAt,{checkedAt:J.checkedAt,readings:[{...W}]})}for(let W of J.coverage??[]){let H=G(W.scope,W.label);if(!Q.has(H))X(H,J.checkedAt,{checkedAt:J.checkedAt,coverage:[{...W}]})}if(J.budget)X("budget",J.checkedAt,{checkedAt:J.checkedAt,budget:{...J.budget}});for(let[W,H]of Object.entries(J.counters??{}))X(`counter:${W}`,H.checkedAt,{checkedAt:J.checkedAt,counters:{[W]:{...H}}});if(J.credits)X("credits",J.credits.checkedAt,{checkedAt:J.checkedAt,credits:{...J.credits}});if(!Z.size)X("empty",J.checkedAt,{checkedAt:J.checkedAt});return Z}function v$($,Z){if(!a0(Z.observation))return Promise.resolve(!1);let J=w$($),z=JSON.stringify([Z.accountIdentity??null,Z.accountIdentity===void 0?Z.routeId:null]),X=J.pending.get(z)??new Map;for(let[G,Q]of t7(Z)){let W=X.get(G);if(!W||Q.at>=W.at){if(Q.order=++J.order,Q.publication.observation.coverage)Q.priorReading=W?.publication.observation.readings?W.publication:W?.priorReading;X.set(G,Q)}}if(X.size)J.pending.set(z,X);for(let G of J.listeners)G(Z);return p$(J,m$),Promise.resolve(!0)}function c$($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,J)=>Z.order-J.order)}function X0($,Z){let J=n0.get(a3($));if(J)for(let z of c$(J.pending)){if(z.priorReading)Z=N0(Z,z.priorReading).roster;Z=N0(Z,z.publication).roster}return Z}function p$($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;if($.timer=setTimeout(()=>{$.timer=void 0,d$($)},Z),!$.draining)$.timer.unref?.()}function d$($){if($.running||$.abort.signal.aborted)return;let Z=new Map([...$.pending].map(([J,z])=>[J,new Map(z)]));$.running=(async()=>{try{await T0($.path,(J)=>{let z=J;for(let X of c$(Z)){if(X.priorReading)z=N0(z,X.priorReading).roster;z=N0(z,X.publication).roster}return{...z!==J&&{next:z},result:void 0}},{signal:$.abort.signal});for(let[J,z]of Z){let X=$.pending.get(J);for(let[G,Q]of z)if(X?.get(G)===Q)X.delete(G);if(!X?.size)$.pending.delete(J)}$.failures=0}catch(J){if(!$.abort.signal.aborted&&$.failures++===0)o7.warn("vault quota publication delayed; retrying",{error:J instanceof Error?J.message:String(J)})}finally{$.running=void 0;for(let z of $.wake)z();let J=$.failures?Math.min(5000,100*2**Math.min($.failures,6))*(0.5+Math.random()):m$;p$($,J)}})()}async function l3($,Z=1000){let J=a3($),z=n0.get(J);if(!z)return;z.draining=!0,clearTimeout(z.timer),z.timer=void 0;let X,G,Q=new Promise((W)=>{G=()=>{if(!z.pending.size||z.abort.signal.aborted)W()},z.wake.add(G),G()});try{if(z.pending.size)d$(z);await Promise.race([Q,new Promise((W)=>{X=setTimeout(W,Math.max(0,Z))})])}finally{if(clearTimeout(X),G)z.wake.delete(G);if(z.draining=!1,!z.listeners.size){if(z.abort.abort(),clearTimeout(z.timer),z.pending.clear(),n0.get(J)===z)n0.delete(J)}}}class l${#$;#z=new AbortController;#J;#X;#H;#G;#Z;#Y;#K;#W=!1;#Q;#U;#M;#j=new Map;#F;#V;constructor($){this.#$=$,this.#J=$.logger??O0("claustrum"),this.#V=u$($.rosterPath,(Z)=>{this.#Z=N0(this.#Z,Z).roster})}#q($){this.#z.signal.throwIfAborted(),$?.throwIfAborted()}async#B(){return await this.#$.isCustodyActive?.()??!0}#D($,Z){let J=V3([this.#z.signal,...Z?[Z]:[]]);return new Promise((z,X)=>{let G=()=>{J.signal.removeEventListener("abort",Q),J.dispose()},Q=()=>{G(),X(J.signal.reason)};if(J.signal.addEventListener("abort",Q,{once:!0}),$.then((W)=>{if(G(),J.signal.aborted)X(J.signal.reason);else z(W)},(W)=>{G(),X(W)}),J.signal.aborted)Q()})}async#L(){if(this.#q(),this.#X)return this.#X;if(!this.#H)this.#H=this.#$.connect().then(($)=>{if(this.#z.signal.aborted)$.close(),this.#q();if(this.#X=new T1({client:$,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#J,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&$.insula)this.#Q=Y3($.insula,this.#$.tokenPath);return this.#X}).finally(()=>{this.#H=void 0});return this.#D(this.#H)}snapshot(){return this.#Z}grantReach(){let $=this.#Y;return $&&this.#Z?.view===$.view?$.reach:void 0}watchState(){return Object.freeze({vault:this.#U?.mode??"polling",...this.#$.insula&&{insula:this.#Q?.source.watchMode()??"polling"}})}#C(){this.#U?.close(),this.#U=void 0,this.#M?.(),this.#M=void 0}keptReceiptState(){return this.#X?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return h3(this.#Z)}refresh(){if(this.#q(),this.#G)return this.#G;return this.#G=(async()=>{if(!await this.#B()){this.#Z=void 0,this.#Y=void 0,this.#C(),this.#X?.close(),this.#X=void 0,this.#Q?.release(),this.#Q=void 0;return}let $=await this.#L(),Z,J=await d3({path:this.#$.rosterPath,custody:$,onInventory:(X)=>{Z=X},isActive:()=>this.#B(),signal:this.#z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#q();let z=J?.view!==this.#Z?.view;if(this.#Z=X0(this.#$.rosterPath,J),$.retain(J?.rows??[]),Z&&J?.view!==void 0)this.#Y=Z.grantReach?{view:J.view,reach:Z.grantReach}:void 0;if(J&&z)this.#$.onRoster?.(J);return this.#F=(this.#$.now??Date.now)(),J})().finally(()=>{this.#G=void 0}),this.#G}start(){if(this.#W)return;this.#q(),this.#W=!0;let $=async()=>{try{if(await this.#P())await this.refresh();await this.refreshInsulaQuota(),this.#O()}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.#K=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#K=void 0,$()},Z),this.#K.unref?.()};$()}async#P(){if(this.#U?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#F===void 0||$-this.#F>=Q3)return!0;return!await this.#B()}#O(){let $=this.#X;if(this.#z.signal.aborted||!$)return;if(this.#U??=$.watchRoster({view:()=>this.#Z?.view,onView:async()=>{while(this.#G)await this.#G.catch(()=>{});await this.refresh()},onRefused:(Z)=>this.#$.onError?.(Z),onError:(Z)=>{if(!this.#z.signal.aborted)this.#$.onError?.(Z)}}),this.#$.insula&&this.#Q&&!this.#M)this.#M=this.#Q.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#z.signal.aborted||!await this.#B())return;try{await B0(this.#$.tokenPath),await this.#L(),await this.#Q?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#z.signal.aborted||!await this.#B())return;try{return await B0(this.#$.tokenPath),this.#_($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#z.signal.aborted||!await this.#B())return;try{await B0(this.#$.tokenPath);let J=X0(this.#$.rosterPath,await r(this.#$.rosterPath))?.rows.find((z)=>z.routeId===$);return this.#_(J?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute($){let Z=this.#$.insula;if(!Z||this.#z.signal.aborted||!await this.#B())return{miss:"unreachable"};try{await B0(this.#$.tokenPath);let z=X0(this.#$.rosterPath,await r(this.#$.rosterPath))?.rows.find((Q)=>Q.routeId===$)?.accountIdentity;if(!z||!this.#Q)return{miss:"unreachable"};let X=this.#Q.source.lookup(Z.provider,z,(this.#$.now??Date.now)()),G=X.reading&&Z.normalize(X.reading.entry,X.reading.context);if(X.miss)return{miss:X.miss,...G!==void 0&&{reading:G}};return G===void 0?{miss:"unreachable"}:{reading:G}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute($,Z){let J=await this.lookupInsulaQuotaForRoute($);if(J.miss==="cold"||J.miss==="upstream-failed"){if(this.#j.get($)!==J.miss)this.#j.set($,J.miss),this.#J.warn("skipped insula provider poll",{reason:J.miss});return}return this.#j.delete($),J.miss?Z():J.reading}#_($){if(!this.#$.insula||!$)return;let Z=this.#Q?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){this.#q(Z);let J=this.#Z??await this.#D(this.refresh(),Z);if(!J||!await this.#B())throw this.#X?.close(),this.#X=void 0,this.#C(),this.#Q?.release(),this.#Q=void 0,new _("not-active","Claustrum scoped custody is not active");let z=X0(this.#$.rosterPath,await r(this.#$.rosterPath));this.#q(Z);let X=J.rows.find((H)=>H.routeId===$),G=z?.rows.find((H)=>H.routeId===$);if(G&&!G.enabled){if(X)this.#X?.forget(X.credentialId);throw new _("route-declined","Claustrum route is disabled")}if(!X||!G||G.state!=="active"||G.credentialId!==X.credentialId||G.accountIdentity!==X.accountIdentity||G.credentialType!==X.credentialType){if(X)this.#X?.forget(X.credentialId);throw new _("route-unavailable","Claustrum route is disabled, removed or changed")}let Q=await this.#D(this.#L(),Z),W=V3([this.#z.signal,...Z?[Z]:[]]);try{return await Q.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.#q(),!this.#X)throw new _("no-receipt","Claustrum dispatch receipt has no active owner");await this.#X.reportFailure($,Z,J)}async send($,Z,J){let z=J.signal,X=await this.authorize($,z),G=await Z(X,z);if(G.status===401&&X.fromKeptReceipt)return await this.reportFailure(X,401,J.reporterSource??"direct"),G;if(G.status===401&&!z?.aborted){let Q;try{Q=await this.authorize($,z),z?.throwIfAborted()}catch(W){if(z?.aborted)throw W}if(k3(J.site,X,Q,this.#J))await G.body?.cancel().catch(()=>{}),X=Q,G=await Z(Q,z)}if(G.status===401)await this.reportFailure(X,401,J.reporterSource??"direct").catch((Q)=>this.#$.onError?.(Q)),Promise.resolve().then(()=>this.refresh()).catch((Q)=>{if(!this.#z.signal.aborted)this.#$.onError?.(Q)});return G}async decline($){this.#q(),await v3(this.#$.rosterPath,$),this.#Z=X0(this.#$.rosterPath,await r(this.#$.rosterPath)),this.#X?.retain(this.#Z?.rows??[])}async accept($){this.#q(),await m3(this.#$.rosterPath,$),this.#Z=X0(this.#$.rosterPath,await r(this.#$.rosterPath))}async reorder($){this.#q();let Z=await w3(this.#$.rosterPath,$);return this.#Z=X0(this.#$.rosterPath,await r(this.#$.rosterPath)),Z}async recordQuota($,Z,J){return this.#q(),u3(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}})}async recordAccountQuota($,Z,J){return this.#q(),c3(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:J})}close(){if(this.#z.signal.aborted)return;if(this.#z.abort(new _("closed","Claustrum consumer is closed")),this.#K)(this.#$.clearTimeoutImpl??clearTimeout)(this.#K);this.#K=void 0,this.#C(),this.#X?.close(),this.#Q?.release(),this.#Q=void 0,this.#Z=void 0,this.#Y=void 0,this.#V(),p3(this.#$.rosterPath)}async dispose(){this.close(),await this.#V()}}var f0={opencode:Z8,pi:J8};function s3($,Z){let{tokenPath:J}=a$($,Z);return{stateDir:$8(J),host:$,override:J}}function n3($,Z){return z8($==="pi"?Z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0,$==="pi"?{...Z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:Z)}class E0 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"}}function i3($,Z){let J=Z??f0[$];if(typeof J!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(J))throw new E0("permission-refused");return["auth","grant","--principal",`enrolled:${J}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"]}async function s$($,Z){try{await Z.processFence();let J=await k1(Z.paths??a$($,Z.env),f0[$]);if(J.state==="blocked")throw new E0("permission-refused");let z=J.state==="approved"?J.approvedName:void 0,X=i3($,z);if((await Z.runner.run(Z.ckBinary??"ck",X,{env:Z.env})).exitCode!==0)throw new E0("permission-refused");return z}catch{throw new E0("permission-refused")}}import{createHash as U8}from"node:crypto";import{lstat as q8,mkdir as K8,readFile as X9}from"node:fs/promises";import{dirname as j8}from"node:path";import{assertHostsStopped as M8,canonicalPath as o3,createNativeAccountRuntime as V8,custodyTombstoneOAuth as F8,inspectNativeHostAuthEntry as G9,NativeMigrationError as g0,nativeJournalMayAdoptLaterHostLogin as B8,nativePoolHoldsAccountData as D8,prepareNativeMigration as L8,readNativeEnrollmentMode as Q9,readNativeMigrationJournal as N8,releaseNativeMigrationPreflight as C8,requireNoSupervisedAuthContentSnapshot as P8,runNativeMigration as O8,writeNativeHostAuth as _8}from"@cortexkit/anthropic-auth-core";import{dirname as X8,join as n$,resolve as r3}from"node:path";import{ACCOUNT_FILE_NAME as i$,ACCOUNT_STATE_FILE_NAME as G8,canonicalPath as r$,getStickyRoutingStatePath as Q8,resolveLocalRoutingDestination as W8,resolveNativePoolPaths as H8}from"@cortexkit/anthropic-auth-core";async function U0($,Z){let J=$==="pi"?e$(Z):o$(Z),z=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),X=r3(z||n$(J,i$)),G=r3(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(X.endsWith(i$)?n$(X8(X),G8):`${X}.state.json`)),Q=await H8(X,G),W=$==="pi"?Z.PI_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim();return{host:$,paths:Q,legacyConfigPath:X,legacyStatePath:G,hostAuthPath:$==="pi"?$9(Z):t$(Z),routingSourcePath:r3(W||Q8(X)),routingDestinationPath:W8($,Q,Z)}}async function Z9($){let Z=new Map;for(let J of $){let z=new Set;for(let[X,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 Q=await r$(G);if(z.has(Q)&&!(X===9&&Q===await r$(J.routingSourcePath)))throw Error("Native setup storage paths overlap");let W=Z.get(Q);if(W!==void 0&&W!==J.host)throw Error("Native setup storage paths overlap between selected hosts");Z.set(Q,J.host),z.add(Q)}}}import{types as Y8}from"node:util";var J9=new WeakMap;function z9($){return typeof $==="object"&&$!==null?J9.get($):void 0}function y1($){if(!$||typeof $!=="object"||Y8.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 a extends Error{constructor($){super($);this.name="SetupRefusal",J9.set(this,$)}}var t3="OpenCode's separate Anthropic login is not used. Add that account through /claude Accounts if needed, or remove the separate login from OpenCode.";function W9($){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 e3($,Z){let J=[];for(let z of $)if(await Q9(z,Z)!=="local")J.push(W9(z));if(J.length)throw new a(J.join(`
|
|
12
|
-
`))}function x0($,Z){return async()=>{P8(Z.env);try{await M8(Z.fence,Z.env)}catch(J){let z=y1(J);if(z)throw new a(z);throw J}await e3([$],Z.env)}}async function $2($){try{return U8("sha256").update(await X9($)).digest("hex")}catch(Z){if(Z.code==="ENOENT")return"absent";throw new g0("unsafe-source")}}async function H1($,Z){let J;try{J=JSON.parse(await X9(Z,"utf8"))}catch(G){if(G.code!=="ENOENT")throw new g0("unsafe-source")}let z=G9($,J),X=J?.anthropic;return{...z,realLogin:z.kind==="oauth"&&Boolean(X?.access&&X.refresh)}}async function h1($,Z){let{paths:J}=$,z=$.generation2?void 0:await H1(J.host,J.hostAuthPath),X=await Promise.all([J.paths.config,J.paths.state,J.paths.runtime,J.paths.roster,J.paths.journal,J.routingDestinationPath].map($2));return JSON.stringify([await Q9(J.host,Z),z?.digest,...X])}async function Z2($,Z,J){let z=Z.paths??await U0($,Z.env),X=x0($,Z);await X();let G=await N8(z.paths);if(G&&G.host!==$)throw new g0("invalid-source");let Q=G?.phase==="committed"||G?.phase==="retired";if(G&&G.kind!=="empty-init"&&(G.hostAuthPath!==await o3(z.hostAuthPath)||G.routingPaths.source!==await o3(z.routingSourcePath)||G.routingPaths.destination!==await o3(z.routingDestinationPath)))throw new g0("invalid-source");let W={paths:z,generation2:J,action:"migration",notice:!1,fingerprint:"",authorityPhase:G?.phase??"absent",poolPopulation:"not-evaluated"};if(J){if(G&&!Q)throw new g0("invalid-source");if(W.action=G?"reuse":"empty-init",!G){let H=[z.paths.config,z.paths.state,z.paths.runtime,z.paths.roster];if(!Z.env.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE)H.push(z.routingDestinationPath);for(let U of H){try{await q8(U)}catch(q){if(q.code==="ENOENT")continue;throw new g0("unsafe-source")}throw new g0("invalid-source")}}}else{W.slot=await H1($,z.hostAuthPath);let H=B8(G,$)&&W.slot.kind==="oauth";W.poolPopulation=G?.kind==="empty-init"||H?await D8({paths:z.paths}):"not-evaluated";let U=W.poolPopulation===!0;if($==="opencode"&&(U||Q&&G?.kind!=="empty-init"&&!H&&W.slot.kind==="oauth"))W.action="skip",W.notice=W.slot.realLogin;else W.preflight=await L8({...z,env:Z.env,processFence:X,removePiAnthropicAuth:Z.removePiAnthropicAuth})}return W.fingerprint=await h1(W,Z.env),W}async function i0($,Z){await x0($.paths.host,Z)();let J=await Z2($.paths.host,{...Z,paths:$.paths},$.generation2);try{if(J.fingerprint!==$.fingerprint||J.action!==$.action)throw new a("Setup inputs changed. Rerun setup with all hosts stopped.")}finally{if(J.preflight)C8(J.preflight)}}async function J2($,Z){if($.paths.host!=="opencode"||$.slot?.kind!=="absent")return;let J=x0("opencode",Z);await J(),await K8(j8($.paths.hostAuthPath),{recursive:!0,mode:448}),await _8({host:"opencode",authPath:$.paths.hostAuthPath,sourceDigest:"absent",expectedDigest:G9("opencode",{anthropic:F8("anthropic")}).digest,env:Z.env,removePiAnthropicAuth:!1,processFence:J})}async function H9($,Z){let J={...Z.env},z=x0($,{...Z,env:J});await z();let X=Z.paths??await U0($,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 O8({paths:X.paths,legacyConfigPath:X.legacyConfigPath,legacyStatePath:X.legacyStatePath,host:$,hostAuthPath:X.hostAuthPath,routingSourcePath:X.routingSourcePath,routingDestinationPath:X.routingDestinationPath,env:J,processFence:z,removePiAnthropicAuth:Z.removePiAnthropicAuth,preflight:Z.preflight});if(G){let Q=V8({paths:X.paths,host:$,vault:{env:J},beforePoolWrite:z});try{if((await Q.read()).mode!=="local")throw new a(W9($));await z(),await Q.loginOAuth({routeId:"main",replace:!0,...G})}finally{Q.close()}}if(Z.skipMigration){let Q=await H1($,X.hostAuthPath);await J2({paths:X,slot:Q},Z)}}var Y9={opencode:"OpenCode",pi:"Pi"};function f8($,Z,J){switch($){case"auth-content-refused":return"Run setup without OPENCODE_AUTH_CONTENT in the environment.";case"host-auth-invalid":return"The host auth file could not be read safely.";case"primary-conflict":return"Pi has a stored Anthropic API key, which would take precedence over the vault account. Remove it in Pi, then rerun setup.";case"consent-required":return"Pi has stored Anthropic authentication. Explicit consent is required to move it aside for vault use.";case"primary-unverified":return"The vault has no verified default Claude account. Sign in through the vault and rerun setup.";case"no-read-grant":return`${Y9[Z]} has no read grant in the vault, so setup cannot see any Claude login. Run ${["ck",...i3(Z,J)].join(" ")}, then rerun setup.`;case"grant-reaches-nothing":return`${Y9[Z]}'s vault read grant reaches no Claude login: no vault login carries the anthropic-native category, which logins saved before vault categories existed lack. Run ck auth reclassify --from-registry, check the logins with ck auth status, then rerun setup.`}}class $0 extends Error{host;approvedName;code;constructor($,Z="opencode",J){super(f8($,Z,J));this.host=Z;this.approvedName=J;this.name="NativeVaultActivationError",this.code=$}}function g8($){let Z=$?.grantReach;if(!Z||$.credentials.length>0||$.skipped.length>0)return"primary-unverified";return Z.grants===0?"no-read-grant":"grant-reaches-nothing"}async function X2($){try{return JSON.parse(await I8($,"utf8"))}catch(Z){if(Z.code==="ENOENT")return;throw new $0("host-auth-invalid")}}async function Y1($,Z){if($==="opencode")return"opencode";let J=Z.paths??await U0($,Z.env),z=z2($,await X2(J.hostAuthPath)),X=G2({env:Z.env,authPath:J.hostAuthPath}),{stashPath:G}=k8({env:Z.env,authPath:J.hostAuthPath});return JSON.stringify([z.digest,await X.inspect(),await $2(G)])}async function U9($){try{E8($.env)}catch{throw new $0("auth-content-refused")}try{await A8($.fence,$.env)}catch(Z){let J=y1(Z);if(J)throw new a(J);throw Z}}async function q9($,Z){let J={...Z.env};await(()=>U9({...Z,env:J}))();let X=Z.paths??await U0($,J),G=$==="opencode"&&Z.inspectOpenCodeAuth!==!1&&z2("opencode",await X2(X.hostAuthPath)).kind==="oauth";if($==="pi"){let Q=z2("pi",await X2(X.hostAuthPath)),W=await G2({env:J,authPath:X.hostAuthPath}).inspect();if(W.slot==="placeholder"&&W.stash==="missing")throw new b8("missing-stash");if(Q.kind!=="absent"&&W.slot!=="placeholder"&&!Z.removePiAnthropicAuth)throw new $0("consent-required")}return{priorMode:await T8($,J),fingerprint:await Y1($,{...Z,env:J}),separateOpenCodeLogin:G}}async function K9($,Z,J){let z={...Z.env},X=()=>U9({...Z,env:z});await X();let G=Z.paths??await U0($,z);if(await Y1($,Z)!==J.fingerprint)throw new $0("host-auth-invalid");let Q=await s$($,{env:z,runner:Z.runner,processFence:X,ckBinary:Z.enrollment?.ckBinary,paths:Z.enrollment?.paths}),W=Z.discover??(()=>S8({paths:G.paths,host:$,env:$==="pi"?{...z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE}:z})),H,U=async()=>{return H=await W(),H},q=R8({paths:G.paths,host:$,vault:{env:z,discover:U}});try{await X(),await q.vault.refresh();let K=await q.read(),B=K.accounts.find((F)=>F.id==="main");if(K.mode!=="claustrum"||!B?.accountIdentity||B.source!=="vault"){let F=g8(H);throw F==="primary-unverified"?new $0(F):new $0(F,$,Q)}if(await X(),$==="pi")await G2({env:z,authPath:G.hostAuthPath}).enterVault();return J.priorMode==="claustrum"?"already-vault":"committed"}finally{q.close()}}var x8=/(?:^|[/\\])(opencode|litecode|opencode2|pi)(?:\.exe)?(?=$|\s|")/i;class Q2 extends Error{activeHosts;constructor($){let Z=$.map((z)=>({pid:z.pid,command:x8.exec(z.command)?.[1]??"host"})),J=Z.map((z)=>` - PID ${z.pid}: ${z.command}`).join(`
|
|
2
|
+
import{y as B3}from"./index-m4dazzyf.js";import{A as i4,B as o4,C as E9,D as b9,E as f9,F as x9,G as r4}from"./index-naff9h33.js";import{ia as v4,ja as QZ,ka as _3}from"./index-71temqvq.js";var d$=QZ((yU,x4)=>{var p$={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"},WZ={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},HZ={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?p$.up():"");if($)Z+=p$.left;return Z}};x4.exports={cursor:p$,scroll:WZ,erase:HZ,beep:"\x07"}});import{stdin as cZ,stdout as pZ}from"node:process";import{createInterface as dZ}from"node:readline/promises";import{authorize as lZ,createNativeAccountRuntime as aZ,exchange as sZ,formatNativeAccountState as nZ,generateRelayToken as iZ,getAccountStoragePath as oZ,isValidApiBaseURL as rZ,readNativeEnrollmentMode as tZ,resolveNativePoolPaths as eZ,WORKER_SCRIPT as $J}from"@cortexkit/anthropic-auth-core";import{randomUUID as k6}from"node:crypto";import{constants as $3}from"node:fs";import{lstat as T6,mkdir as E6,open as b6}from"node:fs/promises";import{homedir as f6}from"node:os";import{isAbsolute as s9,join as A$}from"node:path";import{types as I$}from"node:util";import{createProviderErrorRedactor as r9,createWindowsOwnerOnly as x6,ensureWindowsOwnerOnlyDirectory as y6,formatLogLine as g6,isOwnerOnly as v6,isSecretKey as h6,NativeMigrationError as m6,NativePiAuthSlotError as w6,PRIVATE_FILES_UNAVAILABLE_MESSAGE as t9,setupEnrollment as u6}from"@cortexkit/anthropic-auth-core";import{readFile as D6}from"node:fs/promises";import{assertHostsStopped as N6,createNativeAccountRuntime as L6,discoverNativeVaultInventory as C6,inspectNativeHostAuthEntry as N$,NativePiAuthSlotError as P6,nativePiAuthSlotPaths as O6,openNativePiAuthSlot as C$,readNativeEnrollmentMode as A6,requireNoSupervisedAuthContentSnapshot as _6}from"@cortexkit/anthropic-auth-core";import{dirname as s8}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as n8,CLAUSTRUM_PI_ENROLLMENT_NAME as i8,getHostClaustrumEnrollmentPaths as I9,resolveClaustrumConnectionPath as o8}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as aG}from"@cortexkit/claustrum-client";import{ClaustrumClient as _G}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as $7}from"@cortexkit/claustrum-client";import{SocketClosedError as Z7,SocketTimeoutError as J7,SubcCallError as z7}from"@cortexkit/subc-client";class L extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var L3=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class t extends L{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function N0($){if($ instanceof t||$ instanceof Z7||$ instanceof J7)return"unreachable";let Z=$ instanceof $7||$ instanceof z7?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(L3,Z))return"answered";return L3[Z]}import{resolve as r$}from"node:path";import{storeIdentity as NJ}from"@cortexkit/claustrum-client";import{SubcClient as CJ}from"@cortexkit/subc-client";var p0=300000,b1=300000,C3=1000;class Y1{#$;#Z=0;restart(){this.#Z=0}continuous($){let Z=$.kind==="changed"&&$.seq===this.#Z+1&&(this.#$===void 0||$.epoch===this.#$);return this.#$=$.epoch,this.#Z=$.seq,Z}}class f1{#$;#Z;#J;#W=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#J}request(){if(this.#J)return this.#W=!0,this.#J;return this.#J=(async()=>{do{this.#W=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#W)})().finally(()=>{this.#J=void 0}),this.#J}}class x1{#$;#Z=new Y1;#J;#W="polling";#G;#Q;#z=!1;#X;#M=!1;#H=0;constructor($){this.#$=$,this.#J=new f1(async()=>{let Z=this.#M;if(this.#M=!1,Z||this.#X!==this.#$.view())await this.#$.discover(this.#X??"")},(Z)=>{if(!this.#z)this.#$.onError?.(Z)})}get mode(){return this.#W}start(){if(this.#z||this.#G||this.#Q)return;if(typeof this.#$.client.watchScoped!=="function"){this.#Y("fallback","client-without-watch");return}this.#F(!1)}stop(){if(this.#z)return;if(this.#z=!0,this.#Q)(this.#$.clearTimeoutImpl??clearTimeout)(this.#Q);this.#Q=void 0;let $=this.#G;this.#G=void 0,$?.handle.stop()}#Y($,Z){if(this.#W===$)return;this.#W=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#q($,Z){this.#Q=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#Q=void 0,!this.#z)Z()},$),this.#Q.unref?.()}async#F($){let Z;try{Z=await this.#$.enrollmentToken()}catch(Q){if(this.#z)return;this.#$.onError?.(Q),this.#j("token-unreadable");return}let J=this.#$.client.watchScoped;if(this.#z||this.#G||!J)return;this.#Z.restart(),this.#M=$;let z,X;try{X=J.call(this.#$.client,(Q)=>{if(this.#z||!z||this.#G!==z)return;if(z.notices++,z.notices===1)this.#$.onReachable?.(),z.acceptedAt=(this.#$.now??Date.now)(),this.#Y("watching","accepted");if(!this.#Z.continuous(Q))this.#M=!0;this.#X=Q.view,this.#J.request()},{enrollmentToken:Z})}catch(Q){this.#$.onError?.(Q),this.#j("watch-failed");return}z={handle:X,notices:0},this.#G=z,this.#Y("polling",$?"resubscribing":"opening");let G=z;X.closed.then((Q)=>this.#U(G,Q),(Q)=>this.#U(G,{kind:"transport_lost",error:Q}))}#U($,Z){if(this.#z||this.#G!==$)return;if(this.#G=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#Y("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#j("refused");try{this.#$.onRefused(Z.error)}catch(J){this.#$.onError?.(J)}return}if($.notices>0){let J=(this.#$.now??Date.now)();if($.acceptedAt!==void 0&&J-$.acceptedAt>=300000)this.#H=0;let z=Math.min(1000*2**Math.min(this.#H,16),300000);this.#H++,this.#Y("polling","resubscribing"),this.#q(z,()=>void this.#F(!0));return}this.#j(Z.kind)}#j($){this.#Y("fallback",$),this.#q(300000,()=>void this.#F(!1))}}var g1=60000,t$=4*g1,X7=2*g1,P3=new Map,y1=new Map;function U1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function G7($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!U1(Z)||typeof Z.kind!=="string"||typeof Z.epoch!=="string"||Z.epoch.length===0||typeof Z.seq!=="number"||!Number.isSafeInteger(Z.seq)||Z.seq<1||Z.provider!==void 0&&typeof Z.provider!=="string")return;return{kind:Z.kind,epoch:Z.epoch,seq:Z.seq,...typeof Z.provider==="string"&&{provider:Z.provider}}}function Q7($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class e${transport;key;#$=[];#Z=!1;#J=new Set;#W=new Map;#G=new f1(async()=>{try{let $=await this.transport.getUsage();if(!U1($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>U1(Z)&&typeof Z.provider==="string"),this.#Z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#J=new Set(this.#Z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#J)this.#W.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#J.clear()}},()=>{});#Q=new Y1;#z="polling";#X=0;#M=0;#H=new Map;#Y;#q;#F={};#U=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#G.running)return this.#G.running;if(this.#z==="watching")return Promise.resolve();for(let[J,z]of y1)if($-z>=g1)y1.delete(J);let Z=y1.get(this.key);if(Z!==void 0&&$-Z<g1)return Promise.resolve();return y1.set(this.key,$),this.#G.request()}watchMode(){return this.#z}watch($={}){this.#X++;let Z=$.provider;if(Z===void 0)this.#M++;else this.#H.set(Z,(this.#H.get(Z)??0)+1);if(this.#X===1)this.#F=$,this.#D();let J=!1;return()=>{if(J)return;if(J=!0,Z===void 0)this.#M--;else{let z=(this.#H.get(Z)??1)-1;if(z>0)this.#H.set(Z,z);else this.#H.delete(Z)}if(--this.#X===0)this.#j()}}#j(){if(this.#q)(this.#F.clearTimeoutImpl??clearTimeout)(this.#q);this.#q=void 0;let $=this.#Y;this.#Y=void 0,$?.handle?.stop(),this.#z="polling"}#B($){this.#q=(this.#F.setTimeoutImpl??setTimeout)(()=>{if(this.#q=void 0,this.#X>0&&!this.#Y)this.#D()},$),this.#q.unref?.()}#D(){let $=this.transport.watchUsage;if(!$){this.#z="fallback";return}this.#z="polling",this.#Q.restart();let Z={notices:0};this.#Y=Z;let J;try{J=$.call(this.transport,(z)=>this.#_(Z,z))}catch(z){this.#C(Z,z);return}Z.handle=J,J.closed.then(()=>this.#C(Z,void 0),(z)=>this.#C(Z,z))}#_($,Z){if(this.#Y!==$)return;if($.notices++,$.notices===1)this.#z="watching";if($.notices===2)this.#U=0;let J=G7(Z);if(!J)this.#Q.restart();if(!(J?this.#Q.continuous(J):!1)||J?.provider===void 0||this.#M>0||this.#H.has(J.provider))this.#G.request()}#C($,Z){if(this.#Y!==$)return;this.#Y=void 0;let J=Q7(Z);if(J==="unknown_method"||J==="usage_watch_limit"){this.#z="fallback";return}if($.notices>0){let z=Math.min(C3*2**Math.min(this.#U,16),b1);this.#U++,this.#z="polling",this.#B(z);return}if(this.#z="fallback",this.#G.request(),Z===void 0||N0(Z)==="unreachable")this.#B(b1)}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||!U1(z.usage))continue;let X=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(X)||J-X>=t$)continue;return{entry:z,context:{fetchedAt:X,...typeof z.source==="string"&&{source:z.source}}}}return}lookup($,Z,J){if(!this.#Z)return{miss:"unreachable"};let z=this.#$.find((Q)=>Q.provider===$&&typeof Q.account==="string"&&Q.account.trim()===Z),X=(z??this.#$.find((Q)=>Q.provider===$&&Q.account===void 0&&Q.errorClass!==void 0))?.errorClass;if(X==="upstream_failed")return{miss:"upstream-failed"};if(X==="credential_absent"||X==="credential_unusable"||X==="credential_rejected")return{miss:"credential"};if(X!==void 0)return{miss:"unreachable"};if(z){let Q=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!U1(z.usage)||!Number.isFinite(Q))return{miss:"unreachable"};let W={entry:z,context:{fetchedAt:Q,...typeof z.source==="string"&&{source:z.source}}};return J>=Q+t$||z.stale!==void 0?{miss:"stale",reading:W}:{reading:W}}if(this.#J.has($))return{miss:"absent"};let G=this.#W.get($)??J;return this.#W.set($,G),{miss:J-G>=X7?"unreachable":"cold"}}}function O3($,Z){let J=JSON.stringify([r$($.connectionFile),r$(Z)]),z=P3.get(J);if(!z)z={source:new e$($,J),refs:0},P3.set(J,z);z.refs++;let X=!1;return{source:z.source,release(){if(X)return;if(X=!0,--z.refs===0)P3.delete(J)}}}import{ClaustrumCredentialError as TG}from"@cortexkit/claustrum-client";import{appendFileSync as N7,chmodSync as L7,existsSync as R3,renameSync as U2,statSync as C7}from"node:fs";import{open as P7}from"node:fs/promises";import{dirname as O7,resolve as A7}from"node:path";import{randomUUID as z2}from"node:crypto";import{lstat as X2,readFile as G2,rename as W7,unlink as $2}from"node:fs/promises";import{tmpdir as H7}from"node:os";import{dirname as L0,join as Y7,resolve as e}from"node:path";var A=process.platform==="win32",Z2=new Set;function A3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var J2;var Q2="native-addon-unavailable";function W2($){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:$}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:Q2})}function U7($,Z){return Z instanceof $.PrivateFilesUnavailableError||Z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function q7($){try{await $.verifyPrivatePath(Y7(H7(),`.common-auth-private-files-probe-${z2()}`),"file")}catch(Z){if(U7($,Z))throw W2(Z)}}function d0(){return J2??=import("@cortexkit/private-files").then(async($)=>{if(A)await q7($);return $},($)=>{throw A?W2($):$}),J2}class m 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(z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"?`Private file refused at ${Z}: ${$} (${Q2}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`:`Private file refused at ${Z}: ${$} (${z?.reason??z?.code??"io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`,{cause:J});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=A3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}async function o($,Z,J){try{return await J()}catch(z){if(z instanceof m)throw z;throw new m($,Z,z)}}var K7;async function K0($,Z){$=e($),Z??=K7,await o($,"safe-parent",async()=>{let J=await(await d0()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await X2($);throw new m(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function d($,Z,J=!1){if($=e($),Z==="directory")return K0($);await o($,"verify",async()=>{let z=await d0(),X=await z.verifyOwnerOnly($),G=!1;if(!X.ok){let{reason:Q}=X.refusal;if(Q==="io-error")await z.verifyPrivatePath($,Z);if(J&&[z.EXTRA_ACE,z.NOT_PROTECTED,z.NULL_DACL,z.EMPTY_DACL].includes(Q))await K0(L0($)),await z.securePrivatePath($,Z),G=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:Q,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await z.verifyPrivatePath($,Z),G&&!Z2.has($))Z2.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function W0($,Z=!1,J){$=e($),await o($,"directory",async()=>{let z=await d0();try{return await X2($),await K0($,J)}catch(G){if(A3(G)!=="ENOENT")throw G}let X=L0($);if(X===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await W0(X,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(A3(G)!=="EEXIST")throw G}await K0($,J)})}async function J0($,Z=!1){if(!A)return G2($,"utf8");return(await V7($,Z)).toString("utf8")}async function V7($,Z=!1){if(!A)return G2($);if($=e($),Z)await K0(L0($)),await d($,"file",!0);return o($,"read",async()=>(await d0()).readOwnerOnly($))}async function l0($,Z){await K0(L0(e($))),await o($,"create",async()=>{await(await d0()).createPrivateFile(e($),Z)})}async function H2($){await K0(L0(e($))),await o($,"directory-create",async()=>{await(await d0()).createOwnerOnly(e($),{kind:"dir"})})}async function I3($,Z,J={}){$=e($),Z=e(Z);let z=J.now??(()=>performance.now()),X=z(),G=J.deadline??1/0,Q,W=[0,10,20,40,80,100],H,U=0;for(let K of W){let B=Math.min(Q??1/0,G);if(z()>=B)break;if(K)await(J.sleep??((C)=>new Promise((P)=>setTimeout(P,C))))(Math.min(K,Math.max(0,B-z())));if(z()>=B)break;let F=z();if(await J.beforeRename?.(),Q!==void 0)Q+=z()-F;if(z()>=G)break;U++;try{return await(J.rename??W7)($,Z),{attempts:U,elapsedMs:z()-X}}catch(C){H??=C;let P=C;if(!(P.win32Code!==void 0?P.win32Code===32||P.win32Code===33:["EBUSY","EPERM","EACCES"].includes(P.code??"")&&!P.reason))break;Q??=z()+500}}let q=new m(Z,"rename",H??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw q.attempts=U,q.elapsedMs=z()-X,q}async function a0($,Z,J={}){$=e($),await W0(L0($));try{await d($,"file",!0)}catch(U){if(U.code!=="ENOENT")throw U}let z=e(J.stagePath??`${$}.${z2()}.tmp`);if(L0(z)!==L0($))throw new m($,"stage-directory",{code:"EXDEV"});let X=!1,G=!1,Q={attempts:0,elapsedMs:0},W="stage-create",H=(U)=>{try{J.onOutcome?.({path:$,stage:U?.stage??"published",published:G,fileDurable:G,durabilityConfirmed:!1,attempts:U?.attempts??Q.attempts,elapsedMs:U?.elapsedMs??Q.elapsedMs,...U&&{code:U.code,win32Code:U.win32Code}})}catch{}};try{if(await l0(z,Z),X=!0,W="before-rename",Q=await I3(z,$,J),X=!1,G=!0,W="published-callback",J.onRenamed?.(),W="published-verify",await d($,"file"),J.durable&&J.durability!=="file-only-on-windows")throw new m($,"directory-sync-unsupported",{code:"ENOTSUP"});H()}catch(U){let q=U instanceof m?U:new m($,W,U);if(q.published=G,q.fileDurable=G,G)Object.assign(q,Q);if(X){try{await $2(z)}catch{q.orphanPath=z}X=!1}throw H(q),q}finally{if(X)await $2(z).catch(()=>{})}}var F7=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,B7=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function M7($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function s0($={}){let Z=[B7,...$.extraValuePatterns??[]].map((G)=>new RegExp(G.source,G.flags.includes("g")?G.flags:`${G.flags}g`));function J(G){let Q=G.toLowerCase().replace(/[-_]/g,"");return F7.test(G)||Q.includes("apikey")||Q.endsWith("secret")||Q.endsWith("password")||Q.endsWith("token")&&!Q.endsWith("tokens")||!!$.extraSecretKeys?.(Q)}function z(G){let Q=G,W=[["name",G.name],["message",G.message],["stack",G.stack]];for(let U of["code","status","cause"])if(Q[U]!==void 0)W.push([U,Q[U]]);let H=new Set(W.map(([U])=>U));for(let U of Object.entries(G))if(!H.has(U[0]))W.push(U);return W}function X(G,Q,W,H=0){if(typeof G==="string")return Z.reduce((U,q)=>U.replace(q,"***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((K)=>X(K,Q,W,H));let U=M7(G);if(U&&H>=8)return"[Truncated]";let q=U?H+1:H;return Object.fromEntries((U?z(G):Object.entries(G)).map(([K,B])=>[K,Q&&J(K)?"***REDACTED***":X(B,Q,W,q)]))}finally{W.delete(G)}}return{redact:(G)=>X(G,!0,new WeakSet),redactStrings:(G)=>X(G,!1,new WeakSet)}}var Y2=s0(),j7=Y2.redact,D7=Y2.redactStrings;var v1={error:0,warn:1,info:2,debug:3,trace:4},K2=5242880,V2=3;function S3($){try{L7($,384)}catch{}}function _7($){try{if(!(R3($)&&C7($).size>=K2))return;for(let J=V2-1;J>=1;J--)if(R3(`${$}.${J}`)){let z=`${$}.${J+1}`;U2(`${$}.${J}`,z),S3(z)}let Z=`${$}.1`;U2($,Z),S3(Z)}catch{}}async function V0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await o(Z,"log-close",()=>J.close())}async function q2($,Z){await W0(O7(Z));try{await d(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await l0(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await d(Z,"file",!0)}}return $.handle=await o(Z,"log-open",()=>P7(Z,"a")),$.file=Z,$.handle}async function I7($,Z,J){Z=A7(Z);try{if($.file!==Z)await V0($);let z=$.handle??await q2($,Z);if((await o(Z,"log-stat",()=>z.stat())).size>=K2){await V0($);for(let G=V2-1;G>=0;G--){let Q=G===0?Z:`${Z}.${G}`,W=`${Z}.${G+1}`;try{await d(Q,"file",!0)}catch(H){if(H.code==="ENOENT")continue;throw H}try{await d(W,"file",!0)}catch(H){if(H.code!=="ENOENT")throw H}await I3(Q,W),await d(W,"file")}z=await q2($,Z)}await o(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await V0($).catch(()=>{}),z}}function R7($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function S7($){let Z,J,z,X=s0(),G,Q=[],W,H=Promise.resolve(),U,q={};function K(Y){let V=H.then(Y);return H=V.catch((M)=>{U=M}),V}function B(Y){if(A&&Y.file!==Z)K(()=>V0(q)).catch(()=>{});Z=Y.file,J=Y.level,X=s0(Y),G=Y.captureSink}function F(Y){if(Y===void 0||Y in v1)z=Y}function C(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function P(){if(z)return z;let Y=typeof J==="function"?J():J;if(Y&&Y in v1)return Y;return"info"}function D(Y=!0){if(W)clearTimeout(W),W=void 0;if(!Q.length){if(A)return K(async()=>{if(Y)await V0(q);if(U)throw U});return}let V;try{V=C()}catch{if(Q=[],A&&Y)return K(()=>V0(q));return}let M=Q.join("");if(Q=[],!V){if(A&&Y)return K(()=>V0(q));return}if(A)return K(async()=>{try{await I7(q,V,M)}finally{if(Y)await V0(q)}});try{if(_7(V),R3(V))S3(V);N7(V,M,{encoding:"utf8",mode:384})}catch{}}function I(){if(!W)W=setTimeout(()=>{W=void 0;let Y=D(!1);if(Y instanceof Promise)Y.catch(()=>{})},500)}function R(Y,V,M,S){if(Z===void 0&&G===void 0)return;try{if(v1[V]>v1[P()])return;let g=X.redactStrings(M),k;try{k=X.redact(S)}catch{k="[unserializable]"}let h=`[${new Date().toISOString()}] ${V.toUpperCase()} [${Y}] ${g}`+(S===void 0?"":R7(k))+`
|
|
3
|
+
`;try{G?.({channel:Y,level:V,message:g,data:k})}catch{}if(Z===void 0)return;if(Q.push(h),Q.length>=50){let Z0=D(!1);if(Z0 instanceof Promise)Z0.catch(()=>{})}else I()}catch{}}function x(Y){return{error:(V,M)=>R(Y,"error",V,M),warn:(V,M)=>R(Y,"warn",V,M),info:(V,M)=>R(Y,"info",V,M),debug:(V,M)=>R(Y,"debug",V,M),trace:(V,M)=>R(Y,"trace",V,M)}}function v(){if(A)K(()=>V0(q)).catch(()=>{});if(U=void 0,Q=[],W)clearTimeout(W),W=void 0;Z=void 0,J=void 0,z=void 0,X=s0(),G=void 0}if($)B($);return{configure:B,createLogger:x,setLogLevel:F,flushLogs:D,reset:v}}var k7=S7();function H0($){return k7.createLogger($)}function R0($){let Z=new AbortController,J=[],z=!1,X=()=>{if(z)return;z=!0;for(let{source:W,listener:H}of J)W.removeEventListener("abort",H);J.length=0},G=(W)=>{if(z||Z.signal.aborted)return;Z.abort(W),X()},Q=$.find((W)=>W.aborted);if(Q)return Z.abort(Q.reason),{signal:Z.signal,dispose:X};for(let W of $){if(Z.signal.aborted)break;let H=()=>G(W.reason);if(J.push({source:W,listener:H}),W.addEventListener("abort",H,{once:!0}),W.aborted)G(W.reason)}return{signal:Z.signal,dispose:X}}import{ClaustrumCredentialError as p2}from"@cortexkit/claustrum-client";import{createHash as u7,randomBytes as c7,randomUUID as p7}from"node:crypto";import{constants as I2}from"node:fs";import{chmod as d7,mkdir as l7,open as T2,readFile as E3,realpath as a7,rename as s7,stat as E2,unlink as f3}from"node:fs/promises";import{basename as n7,dirname as k0,extname as Oz,isAbsolute as Az,join as i7,resolve as _z}from"node:path";import{ClaustrumCredentialError as o7,ClaustrumClient as Rz,writeEnrollmentTokenFile as r7}from"@cortexkit/claustrum-client";import{lstat as T7}from"node:fs/promises";import{resolve as E7}from"node:path";async function b7($){try{let Z=await T7($);return Z.isFile()?Z:void 0}catch(Z){return Z.code==="ENOENT"?"absent":void 0}}function f7($,Z){if($==="absent"||Z==="absent")return $===Z;return $.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs&&$.ctimeMs===Z.ctimeMs}class q1{#$=new Map;async read($,Z,J){let z=$.map((U)=>E7(U)),X=JSON.stringify(z),G=await Promise.all(z.map(b7)),Q=G.every((U)=>U!==void 0)?G:void 0,W=this.#$.get(X);if(Q&&W&&Q.every((U,q)=>{let K=W.identities[q];return K!==void 0&&f7(U,K)}))return J?.(Q),W.value;this.#$.delete(X);let H=await Z(z);if(Q){if(this.#$.size>=64){let U=this.#$.keys().next().value;if(U!==void 0)this.#$.delete(U)}this.#$.set(X,{identities:Q,value:H})}return H}}import{randomUUID as F2}from"node:crypto";import{mkdir as x7,open as B2,rename as y7,rm as g7}from"node:fs/promises";import{dirname as M2}from"node:path";class h1 extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function K1($,Z,J={}){await j2($,Z,J)}async function j2($,Z,J,z){if(A)return a0($,J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
4
|
+
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??F2)()}.tmp`,onRenamed:z,durable:J.durable,durability:J.durability,onOutcome:J.onOutcome});await x7(M2($),{recursive:!0});let X=`${$}.${(J.stageName??F2)()}.tmp`,G,Q=!1;try{if(G=await B2(X,"wx",384),Q=!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 h1(W)}if(await G.close(),G=void 0,await J.beforeRename?.(),await y7(X,$),Q=!1,z?.(),J.durable){let W=await B2(M2($),"r");try{await W.sync()}catch(H){throw new h1(H)}finally{await W.close()}}}finally{if(await G?.close().catch(()=>{}),Q)await g7(X,{force:!0}).catch(()=>{})}}var v7=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 m1}from"node:crypto";import{mkdir as D2,open as A2,readFile as N2,rename as L2,rm as w1,stat as C2}from"node:fs/promises";import{dirname as T3,join as P2}from"node:path";function V1($,Z){return`${$}.${Z}.lock`}class C0 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class F0 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(;;){Z.signal?.throwIfAborted();let X=await B0({path:$,name:Z.name,ttlMs:Z.ttlMs,renew:Z.renew??!1,...Z.onStep?{onStep:Z.onStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}});if(X)try{return Z.signal?.throwIfAborted(),await J(X)}finally{await X.release()}let G=Z.timeoutMs-(performance.now()-z);if(G<=0)throw new C0({target:$,name:Z.name,timeoutMs:Z.timeoutMs});await new Promise((Q)=>setTimeout(Q,Math.min(25,Math.ceil(G))))}}async function O2($,Z){let J=await A2($,"wx",384);try{await J.writeFile(Z,"utf8")}finally{await J.close()}}var h7=globalThis.setTimeout.bind(globalThis),m7=globalThis.clearTimeout.bind(globalThis);function _2($){let Z=$?.code;return Z==="ENOENT"||!A&&(Z==="EINVAL"||Z==="ENOTDIR")}function B0($){return w7({...$,now:Date.now})}async function w7($){let Z=V1($.path,$.name),J=P2(Z,"owner.json"),z=m1(),X=$.now??Date.now,G=null,Q=!1,W=!1,H,U,q=new Promise((j)=>{U=j});function K(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 B(){if(!G)return;m7(G),G=null,K("cancelled")}function F(j,N){if(H||Q)return;H=Object.freeze({reason:j,expectedOwnerId:z,...typeof N?.ownerId==="string"?{observedOwnerId:N.ownerId}:{},...typeof N?.expiresAt==="number"?{observedExpiresAt:N.expiresAt}:{}}),B(),U(H)}let C,P=null,D=`${Z}.evicting`,I=P2(D,"owner.json"),R=m1(),x=5000,v=8;async function Y(){if(A)try{return JSON.parse(await J0(Z,!0))}catch(j){if(j.code!=="EISDIR"&&j.reason!=="wrong-kind")throw j;return await d(Z,"directory",!0),JSON.parse(await J0(J,!0))}try{return JSON.parse(await N2(Z,"utf8"))}catch(j){if(j.code!=="EISDIR")throw j;return JSON.parse(await N2(J,"utf8"))}}async function V(){if(A){let y=await Y(),u=Number(y?.expiresAt)-X();await a0(Z,`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
6
|
+
`,{deadline:performance.now()+Math.max(0,u),beforeRename:async()=>{let E1=await Y();if(E1?.ownerId!==z||!(Number(E1?.expiresAt)>X())||!await p())throw new F0({target:$.path,name:$.name})}});return}let j=`${Z}.${m1()}.tmp`,N,O=!1;try{N=await A2(j,"wx",384),O=!0,await N.writeFile(`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
7
|
+
`,"utf8"),await N.chmod(384),await N.close(),N=void 0;let y=await Y();if(y?.ownerId!==z||!(Number(y?.expiresAt)>X())||!await p())throw new F0({target:$.path,name:$.name});await L2(j,Z),O=!1}finally{if(await N?.close().catch(()=>{}),O)await w1(j,{force:!0}).catch(()=>{})}}async function M(){let j=`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
8
|
+
`;if(A)await l0(Z,j);else await O2(Z,j)}async function S(j){let N=j.code;if(N!=="EEXIST"&&N!=="EISDIR")return!1;if(A){if($.onStep)await $.onStep("lease-contention-read-ready");try{if(N==="EISDIR")await d(Z,"directory",!0),await J0(J,!0);else await Y()}catch(O){if(O.code!=="ENOENT")throw O}}return!0}async function g(){if(A)await W0(T3(Z));try{return await M(),!0}catch(j){let N=j.code;if(await S(j))return!1;if(N==="ENOENT"){if(A)await W0(T3(Z));else await D2(T3(Z),{recursive:!0});try{return await M(),!0}catch(O){if(await S(O))return!1;throw O}}throw j}}async function k(){await new Promise((j)=>setTimeout(j,Math.floor(Math.random()*4)))}async function h(j=!0){if(j&&$.onStep)await $.onStep("lock-read-ready");let N;try{N=await Y()}catch(y){if(A&&y.code!=="ENOENT")throw y}let O=Number(N?.expiresAt);if(Number.isFinite(O)&&O>X())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 C2(Z),u=Number.isFinite(O)?O:y.mtimeMs+$.ttlMs;if(u>X())return{status:"live"};return{status:"stale",identity:{kind:"stat",dev:y.dev,ino:y.ino,mtimeMs:y.mtimeMs,expiresAt:u}}}catch(y){if(y.code==="ENOENT"){if($.onStep)await $.onStep("lock-missing");return{status:"missing"}}throw y}}function Z0(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 p(){try{return JSON.parse(await J0(I,A))?.ownerId===R}catch(j){if(A&&j.code!=="ENOENT")throw j;return!1}}async function c(j){if(A)await o(j,"remove",()=>w1(j,{recursive:!0,force:!0}));else await w1(j,{recursive:!0,force:!0}).catch(()=>{})}async function a(){if(await p())await c(D)}async function Q0(){if(A)await H2(D);else await D2(D);try{let j=`${JSON.stringify({ownerId:R,createdAt:X()})}
|
|
9
|
+
`;if(A)await l0(I,j);else await O2(I,j)}catch(j){if(_2(j))return!1;throw await a(),j}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function k1(){let j;try{j=await C2(D)}catch(O){if(O.code==="ENOENT")return"missing";throw O}if(A)await d(D,"directory",!0);if(j.mtimeMs+x>X())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let N=`${D}.${m1()}`;try{await L2(D,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 u0(j){try{if(!await Q0())return!1}catch(N){if(N.code==="EEXIST"){if(A){await d(D,"directory",!0);try{await J0(I,!0)}catch(O){if(O.code!=="ENOENT")throw O}}return!1}throw N}try{await j()}finally{await a()}return!0}async function T1(){for(let j=0;j<v;j++){if($.onStep)await $.onStep("relinquish-read");let N;try{N=await Y()}catch(O){if(A)throw O;return}if(N?.ownerId!==z)return;try{await w1(Z,{recursive:!0,force:!0});return}catch(O){if(A)throw O;await k()}}}function c0(){if(!$.renew||Q||H)return;let j=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=h7(()=>{G=null;let N=(async()=>{let O=!Q;try{if(!await u0(async()=>{let u=await Y(),E1=X();if(Q||H){O=!1;return}if(u?.ownerId!==z){F("taken-over",u),O=!1;return}if(!(Number(u?.expiresAt)>E1)){F("expired",u),O=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(Q||H){O=!1;return}if(!await p())return;if($.onStep)await $.onStep("renewal-write-fenced");if(Q||H){O=!1;return}if(!await p())return;if($.onStep)await $.onStep("renewal-write-ready");if(Q||H){O=!1;return}if(await V(),$.onStep)await $.onStep("renewal-write-finished");if(!await p()){F("marker-lost"),O=!1,await T1();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(y){if(A&&y instanceof m)C=y,F("renewal-failed"),O=!1;try{let u=await Y();if(u?.ownerId!==z)F("taken-over",u);else if(!(Number(u?.expiresAt)>X()))F("expired",u)}catch{F("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(O&&!Q&&!H)c0()}})();P=N,N.finally(()=>{if(P===N)P=null})},j),"unref"in G)G.unref();K("scheduled")}function T(){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 s=await g();if(!s)for(let j=0;j<v;j++){if(s=await g(),s)break;let N=await h();if(N.status==="live")return T();if(N.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await Q0()){await k();continue}}catch(O){if(O.code!=="EEXIST")throw O;if(await k1()==="fresh")return null;await k();continue}try{let O=await h();if(O.status==="live")return T();if(!Z0(N.identity,O))continue;if(!await p())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await p())return null;let y=await h(!1);if(!Z0(N.identity,y))continue;if(await c(Z),!await p())return null;if($.onStep)await $.onStep("stale-lock-removed");if(s=await g(),!s)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await p())return await T1(),s=!1,null;break}finally{await a()}}if(!s)return null;return c0(),{ownerId:z,whenLost:()=>q,hasLost:()=>H!==void 0,assertOwned:async()=>{if(C)throw C;let j;try{let N=await Y();if(j=N,!Q&&!H&&N?.ownerId===z&&Number(N?.expiresAt)>X())return;F(N?.ownerId!==z?"taken-over":"expired",N)}catch(N){if(F("unreadable"),A&&N instanceof m)throw N}throw new F0({target:$.path,name:$.name,expectedOwnerId:z,...typeof j?.ownerId==="string"?{observedOwnerId:j.ownerId}:{},...typeof j?.expiresAt==="number"?{observedExpiresAt:j.expiresAt}:{}})},release:async()=>{if(A&&W)return;Q=!0,B(),await P;for(let j=0;j<v;j++){try{let N=!1;if(await u0(async()=>{let y;try{y=await Y()}catch(u){if(A&&u.code==="ENOENT"){N=!0;return}throw u}if(y?.ownerId!==z){N=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await p())return;await c(Z),N=!0})){if(A&&!N)throw new m(Z,"release-not-confirmed",{code:"EIO"});W=N;return}await k1()}catch(N){if(A)throw N;return}await k()}if(A)throw new m(Z,"release-not-confirmed",{code:"ETIMEDOUT"})}}}var t7=1,c1=16384,b2=30000,x3=/^[0-9a-f]{64}$/,f2="unknown_method",x2=new Set([f2,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),y2=new Set(["pending_queue_full"]);function b3($){if(!($ instanceof o7))return;if(x2.has($.code))return{code:$.code,disposition:"terminal"};if(y2.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function g2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function u1($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function v2($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function F1(){return new L("invalid-state","invalid Claustrum enrollment state")}function y3($){if(!g2($)||$.version!==t7||typeof $.proposedName!=="string"||$.proposedName.length===0)throw F1();if($.phase==="pending"){if(!x3.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!u1($.createdAt)||!u1($.updatedAt))throw F1();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)||!v2($.tokenGeneration)||!u1($.updatedAt))throw F1();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"||!u1($.updatedAt))throw F1();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw F1()}function g3($){if(!g2($)||!x3.test(String($.token??""))||!v2($.token_generation))throw new L("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function h2($){if(!$.isFile())throw new L("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new L("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new L("unsafe-file","Claustrum enrollment file must be owned by the current user")}function R2($){try{return JSON.parse($)}catch{throw new L("invalid-state","Claustrum enrollment file is not valid JSON")}}async function T0($){if(A)try{await W0(k0($));let J=await J0($,!0);if(Buffer.byteLength(J)>c1)throw new L("unsafe-file","Claustrum enrollment file is too large");return R2(J)}catch(J){if(J.code==="ENOENT")return;throw J}let Z;try{Z=await T2($,I2.O_RDONLY|I2.O_NOFOLLOW)}catch(J){if(J.code==="ENOENT")return;throw new L("unsafe-file","Claustrum enrollment file could not be opened safely")}try{h2(await Z.stat());let J=Buffer.alloc(c1+1),{bytesRead:z}=await Z.read(J,0,J.byteLength,0);if(z>c1)throw new L("unsafe-file","Claustrum enrollment file is too large");return R2(J.subarray(0,z).toString("utf8"))}finally{await Z.close()}}function S2($,Z){let J=[];for(let z of $.split(`
|
|
10
|
+
`)){if(z.trim()===""||z.startsWith("#"))continue;let X=z.split(":");if(X.length!==Z||!/^[^\s:,]+$/.test(X[0]??"")||!/^\d+$/.test(X[2]??"")||!Number.isSafeInteger(Number(X[2]))||Z===7&&(!/^\d+$/.test(X[3]??"")||!Number.isSafeInteger(Number(X[3])))||Z===4&&X[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(X[3]??""))return;J.push(X)}return J}async function e7($,Z,J){try{let[z,X]=await Promise.all([E3(J.passwdPath??"/etc/passwd","utf8"),E3(J.groupPath??"/etc/group","utf8")]),G=S2(z,7),Q=S2(X,4);if(!G||!Q)return!1;let W=G.filter((K)=>Number(K[2])===$),H=Q.filter((K)=>Number(K[2])===Z);if(W.length!==1||H.length!==1)return!1;let U=W[0]?.[0],q=H[0]?.[3]??"";return(q===""||q.split(",").every((K)=>K===U))&&!G.some((K)=>Number(K[2])!==$&&Number(K[3])===Z)}catch{return!1}}function m2($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>E3(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function w2($,Z={}){if(!A){let J=process.geteuid?.();if(J===void 0)return;let z=process.getegid?.(),X;try{X=await a7($)}catch{return}let G;for(;;){let Q=await E2(X).catch(()=>{return});if(Q&&(Q.mode&18)!==0&&(Q.mode&512)===0){if(G===void 0)G=z!==void 0&&await e7(J,z,Z);if((Q.mode&2)!==0||Q.uid!==J||Q.gid!==z||!G)throw new L("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${X}. Another user could replace it. Run: chmod g-w,o-w ${X}`)}let W=k0(X);if(W===X)return;X=W}}try{await K0($,m2(Z))}catch(J){if(!(J instanceof m))throw J;throw new L("unsafe-file",`Claustrum enrollment parent refused: ${J.path} (${J.reason??J.code}). Use a folder that other users cannot write or replace.`)}}async function p1($,Z={}){if(A){await W0($,!1,m2(Z));return}await l7($,{recursive:!0,mode:448});let J=await E2($),z=process.geteuid?.();if(z!==void 0&&J.uid!==z)throw new L("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((J.mode&63)!==0)await d7($,448)}async function S0($,Z,J={}){let z=k0($);await p1(z,J),await w2(z,J);let X=`${JSON.stringify(Z)}
|
|
11
|
+
`;if(Buffer.byteLength(X)>c1)throw new L("invalid-state","Claustrum enrollment state is too large");if(A)return a0($,X);let G=i7(z,`.${n7($)}.${process.pid}.${p7()}.tmp`),Q,W=!1;try{Q=await T2(G,"wx",384),W=!0,await Q.writeFile(X,"utf8"),await Q.chmod(384),await Q.sync(),await Q.close(),Q=void 0,await s7(G,$),W=!1}finally{if(await Q?.close().catch(()=>{}),W)await f3(G).catch(()=>{})}}var $8=new q1;async function d1($,Z){let J=A?await k2($,Z):await $8.read([$.tokenPath,$.statePath],async([X=$.tokenPath,G=$.statePath])=>k2({tokenPath:X,statePath:G},Z),(X)=>{for(let G of X)if(G!=="absent")h2(G)}),z={...J.status};if(J.usesProposedName&&z.state==="approved")z.proposedName=Z;return z}async function k2($,Z){let J=await T0($.tokenPath),z=J===void 0?void 0:g3(J),X=await T0($.statePath),G=X===void 0?void 0:y3(X);if(z)return{usesProposedName:G===void 0,status:{state:"approved",proposedName:G?.proposedName??Z,...G?.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:z.token_generation}};if(!G)return{status:{state:"idle"},usesProposedName:!1};if(G.phase==="approved")return{usesProposedName:!1,status:{state:"blocked",proposedName:G.proposedName,code:"missing_token"}};return{status:P0(G),usesProposedName:!1}}async function O0($){let Z=await T0($);if(Z===void 0)throw new L("not-enrolled","Claustrum enrollment is not configured");return g3(Z)}function P0($){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 u2(){return new L("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class v3{#$;#Z;#J;#W;#G;#Q;#z;constructor($){this.#z=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#J=$.proposedName,this.#W=$.now??Date.now,this.#G=$.mintSecret??(()=>c7(32).toString("hex")),this.#Q=$.writeTokenFile??r7}async status(){return d1(this.#Z,this.#J)}async resetTerminal(){return c2(this.#Z,this.#J)}async#X($,Z){let J={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#W()};return await S0(this.#Z.statePath,J,this.#z),P0(J)}async reconcile(){await p1(k0(this.#Z.statePath),this.#z);let $=await B0({name:"ceremony",path:this.#Z.statePath,ttlMs:b2,renew:!0});if(!$)return{state:"busy"};try{let Z=await T0(this.#Z.tokenPath),J=Z===void 0?void 0:g3(Z),z=await T0(this.#Z.statePath),X=z===void 0?void 0:y3(z);if(X&&X.proposedName!==this.#J)throw u2();if(J){if(!X||X.phase==="pending"){let Q={version:1,phase:"approved",proposedName:X?.proposedName??this.#J,tokenGeneration:J.token_generation,updatedAt:this.#W()};await S0(this.#Z.statePath,Q,this.#z),X=Q}return{state:"approved",proposedName:X.proposedName,...X.phase==="approved"&&X.approvedName!==void 0&&{approvedName:X.approvedName},tokenGeneration:J.token_generation}}if(X?.phase==="approved"){let Q={version:1,phase:"blocked",proposedName:X.proposedName,errorCode:"missing_token",updatedAt:this.#W()};return await S0(this.#Z.statePath,Q,this.#z),P0(Q)}if(X&&X.phase!=="pending")return P0(X);if(!X){let Q=this.#W();if(X={version:1,phase:"pending",proposedName:this.#J,requestSecret:this.#G(),createdAt:Q,updatedAt:Q},!x3.test(X.requestSecret))throw new L("invalid-state","invalid minted Claustrum enrollment secret");await S0(this.#Z.statePath,X,this.#z)}if(!X.requestId)try{let Q=u7("sha256").update(Buffer.from(X.requestSecret,"hex")).digest("hex"),W=await this.#$.enrollPropose({name:X.proposedName,requestSecretHash:Q});X={...X,requestId:W.requestId,updatedAt:this.#W()},await S0(this.#Z.statePath,X,this.#z)}catch(Q){let W=b3(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,retryCode:W.code};if(W.code===f2)return await $.assertOwned(),await f3(this.#Z.statePath).catch((H)=>{if(H.code!=="ENOENT")throw H}),{state:"unavailable",proposedName:X.proposedName,code:W.code};return this.#X(X,W.code)}let G=X.requestId;if(!G)return P0(X);try{let Q=await this.#$.enrollPoll({requestId:G,requestSecret:X.requestSecret});if(Q.status==="pending")return P0(X);if(Q.status==="denied"){let H={version:1,phase:"denied",proposedName:X.proposedName,updatedAt:this.#W()};return await S0(this.#Z.statePath,H,this.#z),P0(H)}await p1(k0(this.#Z.tokenPath),this.#z),await w2(k0(this.#Z.tokenPath),this.#z),await this.#Q(this.#Z.tokenPath,{token:Q.token,token_generation:Q.tokenGeneration});let W={version:1,phase:"approved",proposedName:X.proposedName,approvedName:Q.name,tokenGeneration:Q.tokenGeneration,updatedAt:this.#W()};return await S0(this.#Z.statePath,W,this.#z),P0(W)}catch(Q){let W=b3(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,requestId:G,retryCode:W.code};return this.#X(X,W.code)}}finally{await $.release()}}}async function c2($,Z){await p1(k0($.statePath));let J=await B0({name:"ceremony",path:$.statePath,ttlMs:b2,renew:!0});if(!J)return"busy";try{if(await T0($.tokenPath)!==void 0)return"refused-approved";let z=await T0($.statePath);if(z===void 0)return"idle";let X=y3(z);if(X.proposedName!==Z)throw u2();if(X.phase==="pending")return"refused-pending";return await J.assertOwned(),await f3($.statePath),"reset"}finally{await J.release()}}var h3="claustrum-tombstone:v1:";function n0($,Z){let J=!1;return(z)=>{if(J)return;if(!Z||Z.aborted)J=!0;$.warn("claustrum shutdown drain timed out",{pendingOperations:z})}}async function i0($,Z){if(!$.size)return;let J,z=!1,X=(async()=>{while(!z&&$.size)await Promise.allSettled([...$])})();try{if(await Promise.race([X,new Promise((G)=>{J=setTimeout(()=>{z=!0,G()},2000)})]),z&&$.size)Z($.size)}finally{z=!0,clearTimeout(J)}}function d2($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function Z8($,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 w3=H0("claustrum");function c3($,Z,J,z=w3){let X=d2(Z,J);return z.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:J?.recordVersion??null,retry:X,reason:Z8(Z,J)}),X}var u3=300000,l2=60000;function m3(){return new L("invalid-material","Claustrum returned invalid credential material")}function J8($){let Z=$.trim();if(Z.startsWith("{")){let J;try{J=JSON.parse(Z)}catch{throw m3()}if(!J||typeof J!=="object")throw m3();let z=J,X=z.access_token??z.access;Z=typeof X==="string"?X:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(h3))throw m3();return Z}function z8($,Z){let J={kind:"not-mine"};if(!$.operations.includes("read"))return J;if(!$.categories.includes(Z.category))return J;if($.credentialType!=="oauth"&&$.credentialType!=="api_key")return J;if("classify"in Z){let z={credentialId:$.id,credentialType:$.credentialType,categories:$.categories,refreshAdapter:$.refreshAdapter,...X8($)};if(z.providerIds===void 0)return{kind:"refused",code:"unmapped"};try{let X=Z.classify(z);if(X.kind==="not-mine")return J;if(X.kind==="mine"&&typeof X.member==="string")return{kind:"mine",type:$.credentialType,member:X.member};if(X.kind==="refused"&&typeof X.code==="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(X.code)&&!X.code.includes(`
|
|
12
|
+
`)&&Z.refusalCodes.includes(X.code))return{kind:"refused",code:X.code}}catch{}return{kind:"refused",code:"unclassified"}}if($.credentialType==="oauth")return $.refreshAdapter===Z.refreshAdapter?{kind:"mine",type:"oauth"}:J;if($.credentialType==="api_key"&&Z.apiKeys)return $.refreshAdapter===void 0?{kind:"mine",type:"api_key"}:J;return J}function X8($){let Z=$;return{providerIds:Z.providerIds,authMethod:Z.authMethod}}function G8($){let{grants:Z,grantTuples:J}=$;if(Z===void 0||J===void 0)return;return Object.freeze({grants:Z,tuples:Object.freeze(J.map(({selectorKind:z,selector:X,operation:G})=>Object.freeze({selectorKind:z,selector:X,operation:G})))})}class o0{#$;#Z;#J;#W;#G;#Q;#z;#X=new WeakMap;#M=new WeakMap;#H=new Map;#Y=new WeakMap;#q;#F;#U=!1;#j=new t;#B;#D=!1;#_=-1/0;#C=2000;#K=!1;#L;#I=new Set;#V=new Set;#P;#A;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>O0(Z);else throw new L("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#W=$.family,this.#G=$.parseIdentity,this.#Q=$.requireAssertion??!1,this.#J=$.now??Date.now,this.#z=$.logger??w3,this.#P=n0(this.#z),this.#q=$.setTimeoutImpl??setTimeout,this.#F=$.clearTimeoutImpl??clearTimeout}transportLost($){if(this.#K||this.#U)return;this.#U=!0,this.#j=$ instanceof p2?$:new t,this.#z.warn("serving kept vault receipt",{reason:"unreachable"}),this.#R()}reachable(){if(this.#K||!this.#U)return;if(this.#U=!1,this.#B)this.#F(this.#B);this.#B=void 0,this.#C=2000;for(let $ of this.#H.values())$.since=null;(this.#z.info??w3.info)("vault receipt serving resumed",{reason:"reachable"})}#R(){if(this.#K||!this.#U||this.#B||this.#D)return;this.#B=this.#q(()=>{this.#B=void 0,this.#N(!0)},this.#C),this.#B.unref?.()}#N($=!1){if(this.#K||!this.#U||this.#D)return;if(this.#J()-this.#_<1000){this.#R();return}this.#_=this.#J(),this.#D=!0,this.#b().catch(()=>{if($&&this.#U)this.#C=Math.min(this.#C*2,30000)}).finally(()=>{this.#D=!1,this.#R()})}#O($){if(this.#K)throw new L("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#k($){this.#O($);let Z=this.#Z();this.#V.add(Z);let J;try{J=await Z}finally{this.#V.delete(Z)}if(this.#O($),!/^[0-9a-f]{64}$/.test(J.token)||!Number.isSafeInteger(J.token_generation)||J.token_generation<1)throw new L("invalid-token","Invalid Claustrum enrollment token");return J.token}async#S($,Z){this.#O(Z);let J,z;try{let X=$();J=Z?await Promise.race([X,new Promise((G,Q)=>{let W=()=>Q(Z.reason);if(Z.addEventListener("abort",W,{once:!0}),z=()=>Z.removeEventListener("abort",W),Z.aborted)W()})]):await X}catch(X){if(this.#O(Z),N0(X)==="unreachable")this.transportLost(X);else this.reachable();if(X instanceof p2)throw X;if(N0(X)==="unreachable")throw new t;throw new L("unavailable","Claustrum scoped operation unavailable")}finally{z?.()}return this.#O(Z),this.reachable(),J}async discover($){let Z=await this.#b($);return this.#L=Z.view,Z}async#b($){let Z,J;try{J=await this.#k($)}catch(q){throw this.#H.clear(),q}try{Z=await this.#S(()=>this.#$.listScoped(J),$)}catch(q){throw this.listFailed(q),q}let z=[],X=[],G=0,Q=[],W=new Map;for(let q of Z.rows){let K=z8(q,this.#W);if(K.kind==="not-mine"){G++;continue}if(K.kind==="refused"){X.push({...q.id.trim()&&{credentialId:q.id},code:K.code});continue}Q.push({row:q,type:K.type,...K.member!==void 0&&{member:K.member}}),W.set(q.id,(W.get(q.id)??0)+1)}let H=[];for(let{row:q,type:K,member:B}of Q){let F;if(!q.id.trim())F="empty credential id";else if((W.get(q.id)??0)>1)F="duplicate credential id";else if(q.accountId!==void 0&&!q.accountId.trim())F="blank account identity";else if(!q.state.trim())F="empty state";if(F){z.push({...q.id.trim()&&{credentialId:q.id},...B!==void 0&&{member:B},reason:F});continue}H.push(Object.freeze({credentialId:q.id,credentialType:K,...B!==void 0&&{member:B},...q.accountId!==void 0&&{accountIdentity:q.accountId},state:q.state,...q.email!==void 0&&{email:q.email},...q.orgName!==void 0&&{orgName:q.orgName}}))}for(let q of z)this.#z.warn("skipped malformed vault record",q);let U=G8(Z);return{view:Z.view,credentials:Object.freeze(H),skipped:Object.freeze(z),..."classify"in this.#W&&{refused:Object.freeze(X),notMine:G},...U&&{grantReach:U}}}listFailed($){if(N0($)==="unreachable")this.transportLost($);else this.reachable(),this.#H.clear()}forget($){this.#H.delete($)}retain($){let Z=new Map($.map((J)=>[J.credentialId,J]));for(let[J,z]of this.#H){let X=Z.get(J);if(!X?.enabled||X.state!=="active"||X.credentialType!==z.attempt.credentialType||X.accountIdentity!==z.attempt.expectedAccountIdentity)this.forget(J)}}keptReceiptState(){let $=null;for(let[Z,J]of this.#H){if(!this.#E(J.attempt)){this.forget(Z);continue}if(J.since!==null)$=Math.min($??J.since,J.since)}return Object.freeze({active:$!==null,since:$})}#E($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#J()>l2}async authorize($,Z,J="vault"){this.#O(Z);let{credentialId:z,credentialType:X,accountIdentity:G}=$,Q=this.#H.get(z);if(Q&&(Q.attempt.credentialType!==X||Q.attempt.expectedAccountIdentity!==G))this.forget(z),Q=void 0;let W;try{W=await this.#k(Z)}catch(H){throw this.#H.clear(),H}if(this.#U&&Q)return this.#N(),this.#T(z,Q,W,J);try{let H=await this.#x({credentialId:z,credentialType:X,accountIdentity:G},W,Z);return this.#H.set(z,{attempt:H,routeId:J,since:null}),H}catch(H){if(this.#O(Z),N0(H)!=="unreachable")throw this.forget(z),H;return this.#T(z,Q,W,J,H)}}#T($,Z,J,z,X=this.#j){if(!Z||this.#H.get($)!==Z||!this.#E(Z.attempt))throw this.forget($),X;if(Z.since===null)Z.since=this.#J();let G=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#X.set(G,J),this.#Y.set(G,z),G}async#x($,Z,J){if(!$.credentialId)throw new L("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:z,credentialType:X,accountIdentity:G}=$;if(this.#Q&&G===void 0)throw new L("identity-unasserted","Claustrum dispatch requires a known account identity");let Q=await this.#S(()=>this.#$.getScoped({credentialId:z,enrollmentToken:Z,...X==="oauth"&&{minTtlMs:u3}}),J);if(Q.credentialId!==void 0&&Q.credentialId!==z)throw new L("identity-changed","Claustrum served credential identity changed");let W=Q.expiresAtMs;if(!Number.isSafeInteger(Q.recordVersion)||Q.recordVersion<0||W===null&&X==="oauth"||W!==null&&(!Number.isFinite(W)||W-this.#J()<u3))throw new L("insufficient-validity","Claustrum served credential has insufficient validity");let H=J8(Q.material),U=Q.accountId?.trim()?Q.accountId:void 0;if(this.#Q&&(Q.credentialId===void 0||U===void 0))throw new L("identity-unasserted","Claustrum served credential did not assert its identity");let q=U===void 0?this.#G?.(H):void 0,K=U??q;if(G!==void 0&&K!==void 0&&K!==G)throw new L("identity-changed","Claustrum served credential identity changed");let B=K??G,C=Object.freeze(Object.defineProperty({credentialId:z,credentialType:X,...B!==void 0&&{accountIdentity:B},accountIdentitySource:U!==void 0?"asserted":q!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...Q.credentialId!==void 0&&{assertedCredentialId:Q.credentialId},...U!==void 0&&{assertedAccountIdentity:U},...Q.projectId!==void 0&&{projectId:Q.projectId},recordVersion:Q.recordVersion,expiresAtMs:W},"accessToken",{value:H,enumerable:!1}));return this.#X.set(C,Z),C}async reportFailure($,Z,J){if(Z!==401)return;this.#O();let z=this.#X.get($);if(!z)throw new L("no-receipt","Claustrum failure report requires an original dispatch receipt");let X=this.#Y.get($);if(X!==void 0){this.forget($.credentialId),this.#z.debug("scoped 401 not reported",{routeId:X,reason:"kept-receipt"});return}let G=this.#H.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let Q=this.#M.get($);if(Q)return Q;let W=this.#S(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:z,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#M.set($,W);try{await W,this.#z.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:J})}catch(H){throw this.#M.delete($),H}}watchRoster($){this.#O();let Z=new x1({client:this.#$,enrollmentToken:()=>this.#k(),view:$.view??(()=>this.#L),discover:async(J)=>{await $.onView(J)},onRefused:(J)=>{this.listFailed(J),$.onRefused?.(J)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#z,now:this.#J,setTimeoutImpl:this.#q,clearTimeoutImpl:this.#F});return this.#I.add(Z),Z.start(),{get mode(){return Z.mode},close:()=>{this.#I.delete(Z),Z.stop()}}}close(){if(this.#K)return;if(this.#K=!0,this.#B)this.#F(this.#B);this.#B=void 0;for(let $ of this.#I)$.stop();this.#I.clear(),this.#H.clear(),this.#$.close()}async dispose($=this.#P){this.close(),this.#A??=i0(this.#V,$),await this.#A}}import{resolve as o1}from"node:path";var p3=30000,d3={now:()=>performance.now(),schedule($,Z){let J=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(J),unref:()=>J.unref?.()}}};var E0="all",Q8=Object.freeze(["primary"]);function s2($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function t0($,Z){return JSON.stringify([$,Z])}function A0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function l($){return typeof $==="number"&&Number.isFinite($)}function a2($){return typeof $==="string"&&$.length>0}function n($,Z,J){return $[Z]===void 0||J($[Z])}function W8($){return l($)&&$>0}function l3($){return typeof $==="string"}function H8($){if(!A0($)||!a2($.scope)||!a2($.label))return!1;switch($.kind){case"reading":return l($.checkedAt)&&l($.usedPercent)&&n($,"resetsAt",l3)&&n($,"windowMinutes",W8);case"retired":return l($.retiredAt);case"absent":return l($.checkedAt);default:return!1}}function Y8($){if(!A0($)||!l($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&n($,"remainingPercent",l)&&n($,"usedPercent",l)&&n($,"resetsAt",l3)&&n($,"limit",l)&&n($,"used",l)&&n($,"remaining",l)&&n($,"unit",l3)}function n2($){return A0($)&&l($.value)&&Number.isInteger($.value)&&$.value>=0&&l($.checkedAt)}function a3($){return A0($)&&Object.values($).every(n2)}function U8($){return typeof $==="boolean"}function e0($){return A0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&n($,"balance",l)&&n($,"overageLimitReached",U8)&&l($.checkedAt)}function i2($){if(!A0($))return;let Z=Object.entries($).filter(([,J])=>n2(J));return Z.length===0?void 0:Object.fromEntries(Z)}function b0($){if(r0($))return $;if(!A0($))return;let{counters:Z,credits:J,...z}=$;if(!r0(z))return;let X=i2(Z),G=e0(J)?J:void 0;return{...z,...X===void 0?{}:{counters:X},...G===void 0?{}:{credits:G}}}function r0($){if(!A0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!H8(J))return!1;let z=t0(J.scope,J.label);if(Z.has(z))return!1;Z.add(z)}return n($,"budget",Y8)&&n($,"counters",a3)&&n($,"credits",e0)}class l1 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function s1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function a1($){return typeof $==="number"&&Number.isFinite($)}function o2($){return $===void 0||typeof $==="string"&&$!==""}function r2($){return typeof $==="string"&&$!==""}function B1($,Z){return $[Z]===void 0||a1($[Z])}function s3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function q8($){return s1($)&&o2($.scope)&&r2($.label)&&a1($.usedPercent)&&s3($,"resetsAt")&&($.windowMinutes===void 0||a1($.windowMinutes)&&$.windowMinutes>0)}function K8($){return s1($)&&o2($.scope)&&r2($.label)}function V8($){if(!s1($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&B1($,"remainingPercent")&&B1($,"usedPercent")&&s3($,"resetsAt")&&B1($,"limit")&&B1($,"used")&&B1($,"remaining")&&s3($,"unit")}function $1($){if(!s1($)||!a1($.checkedAt))return!1;let Z=$.readings??[],J=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(J))return!1;let z=new Set;for(let X of Z){if(!q8(X))return!1;let G=t0(X.scope??E0,X.label);if(z.has(G))return!1;z.add(G)}if(!J.every(K8))return!1;return($.budget===void 0||V8($.budget))&&($.counters===void 0||a3($.counters))&&($.credits===void 0||e0($.credits))}function F8($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function B8($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function M8($,Z){let J=new Map(Object.entries($??{}));for(let[z,X]of Object.entries(Z??{})){let G=J.get(z);if(G===void 0||X.checkedAt>=G.checkedAt)J.set(z,X)}return J.size===0?void 0:Object.fromEntries(J)}function j8($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function M1($,Z){let J=$===void 0?void 0:b0($);if($!==void 0&&J===void 0)throw new l1("stored quota map is malformed");if(!$1(Z))throw new l1("quota observation is malformed");let z=J??{limits:[]},X=Z.checkedAt,G=new Map;for(let D of z.limits)G.set(t0(D.scope,D.label),D);let Q=(D)=>{let I=G.get(D);return I===void 0||X>=s2(I)},W=new Set;for(let D of Z.readings??[]){let I=D.scope??E0,R=t0(I,D.label);if(W.add(R),!Q(R))continue;G.set(R,{scope:I,label:D.label,kind:"reading",checkedAt:X,usedPercent:D.usedPercent,...D.resetsAt===void 0?{}:{resetsAt:D.resetsAt},...D.windowMinutes===void 0?{}:{windowMinutes:D.windowMinutes}})}for(let D of Z.coverage??[]){let I=D.scope??E0,R=t0(I,D.label);if(W.has(R)||!Q(R))continue;let x=G.get(R);G.set(R,x===void 0||x.kind==="absent"?{scope:I,label:D.label,kind:"absent",checkedAt:X}:{scope:I,label:D.label,kind:"retired",retiredAt:X})}let{limits:H,budget:U,counters:q,credits:K,...B}=z,F=B8(z.budget,Z.budget,X),C=M8(z.counters,Z.counters),P=j8(z.credits,Z.credits);return{...B,limits:[...G.values()].sort(F8),...F===void 0?{}:{budget:F},...C===void 0?{}:{counters:C},...P===void 0?{}:{credits:P}}}var D8=Object.freeze({validate:r0,decode:b0,merge:M1});function t2($,Z=""){let J=new Map,{observation:z}=$,X=(W,H,U)=>J.set(`${Z}:${W}`,{at:H,order:0,publication:{...$,observation:U}}),G=(W,H)=>JSON.stringify([W??"all",H]),Q=new Set;for(let W of z.readings??[]){let H=G(W.scope,W.label);Q.add(H),X(H,z.checkedAt,{checkedAt:z.checkedAt,readings:[{...W}]})}for(let W of z.coverage??[]){let H=G(W.scope,W.label);if(!Q.has(H))X(H,z.checkedAt,{checkedAt:z.checkedAt,coverage:[{...W}]})}if(z.budget)X("budget",z.checkedAt,{checkedAt:z.checkedAt,budget:{...z.budget}});for(let[W,H]of Object.entries(z.counters??{}))X(`counter:${W}`,H.checkedAt,{checkedAt:z.checkedAt,counters:{[W]:{...H}}});if(z.credits)X("credits",z.credits.checkedAt,{checkedAt:z.checkedAt,credits:{...z.credits}});if(!J.size)X("empty",z.checkedAt,{checkedAt:z.checkedAt});return J}import{createHash as P8}from"node:crypto";import{stat as O8}from"node:fs/promises";import{resolve as j1}from"node:path";function e2($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function n3($,Z,J){return $.some((z)=>e2(z,Z,J))}function i3($,Z,J){let z={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((X)=>X.credentialId!==Z||X.accountIdentity!==J),z]}function o3($,Z,J){return $.filter((z)=>!Z.some((X)=>e2(z,X,J)))}function r3($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>Y0(Z).map((J)=>({credentialId:J,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function A8($,Z){let J=Y0(Z),z=Z.accountIdentity===void 0?-1:$.order.findIndex((G)=>G.accountIdentity===Z.accountIdentity),X=z>=0?z:$.order.findIndex((G)=>J.includes(G.credentialId));return X>=0?X:1/0}var i1="vault:";function _8($){return P8("sha256").update($).digest("hex")}function I8($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function R8($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function Y0($){return[$.credentialId,...$.aliases??[]]}function J9($,Z,J={}){let z=J.now??Date.now(),X=J.routePrefix??i1,G=J.reservedRouteIds??new Set,Q=$?.rows??[],W=$?void 0:J.seed,H=[...$?.declined??W?.declined??[]],U=Z.skipped.length===0,q=new Set(Z.credentials.map((Y)=>Y.credentialId)),K=new Set(Z.skipped.flatMap((Y)=>Y.credentialId===void 0?[]:[Y.credentialId])),B=Z.skipped.some((Y)=>Y.credentialId===void 0),F=(Y)=>!q.has(Y)&&(K.has(Y)||B),C=new Map;for(let Y of Q){if(Y.accountIdentity===void 0)continue;for(let V of Y0(Y))if(!C.has(V))C.set(V,Y.accountIdentity)}let P=new Map;for(let Y of Z.credentials){let V=Y.accountIdentity!==void 0?{credential:Y,identity:Y.accountIdentity,claimed:!0}:{credential:Y,identity:C.get(Y.credentialId),claimed:!1},M=R8(V),S=P.get(M)??[];S.push(V),P.set(M,S)}let D=new Set,I=new Set(G),R=[],x=(Y,V)=>Y.credential.credentialId.localeCompare(V.credential.credentialId),v=[...P.values()].map((Y)=>Y.toSorted(x)).sort((Y,V)=>Y[0]&&V[0]?x(Y[0],V[0]):0);for(let Y of v){let V=Y[0]?.identity,M=Y.filter((T)=>T.credential.state==="active"),S=M.length?M:Y,g=S.filter((T)=>T.claimed),k=g.length?g:S,h=new Set(Y.map((T)=>T.credential.credentialId)),Z0=Q.find((T)=>!D.has(T)&&Y0(T).some((s)=>h.has(s))&&(T.accountIdentity===void 0||T.accountIdentity===V)),p=k.find((T)=>T.credential.credentialId===Z0?.credentialId)??k[0];if(!p)continue;let c=p.credential,a=Z0??(V===void 0?void 0:Q.find((T)=>!D.has(T)&&T.accountIdentity===V));if(a)D.add(a);let Q0=a?.routeId;if(!Q0||G.has(Q0)){let T=`${X}${c.credentialId}${V===void 0?"":`~${_8(V).slice(0,10)}`}`;Q0=T;for(let s=2;I.has(Q0);s++)Q0=`${T}~${s}`}I.add(Q0);let k1=a?Y0(a).filter(F):[],u0=[...new Set([...Y.map((T)=>T.credential.credentialId),...k1])].filter((T)=>T!==c.credentialId).sort((T,s)=>T.localeCompare(s)),T1=J.mapAccount?.(c)??{};R.push({previousIndex:a?Q.indexOf(a):1/0,row:{routeId:Q0,credentialId:c.credentialId,credentialType:c.credentialType,...V!==void 0&&{accountIdentity:V},...u0.length&&{aliases:u0},state:c.state,label:T1.label?.trim()||I8(c),...c.email!==void 0&&{email:c.email},...c.orgName!==void 0&&{orgName:c.orgName},enabled:![c.credentialId,...u0].some((T)=>n3(H,T,V)),addedAt:a?.addedAt??z,...a?.quota!==void 0&&{quota:a.quota},...!p.claimed&&V!==void 0&&{unclaimed:!0}}});let c0=R.at(-1);if(W&&c0)c0.previousIndex=A8(W,c0.row)}return Q.forEach((Y,V)=>{if(D.has(Y)||!Y0(Y).some(F))return;if(I.has(Y.routeId))return;let[M,...S]=Y0(Y).filter((h)=>!q.has(h));if(M===void 0)return;I.add(Y.routeId);let{aliases:g,...k}=Y;R.push({previousIndex:V,row:{...k,credentialId:M,...S.length&&{aliases:S},stale:!0}})}),R.sort((Y,V)=>Y.previousIndex===V.previousIndex?Y.row.credentialId.localeCompare(V.row.credentialId):Y.previousIndex-V.previousIndex),{version:1,view:Z.view,complete:U,...!U&&{rejected:Z.skipped.map((Y)=>({...Y.credentialId!==void 0&&{credentialId:Y.credentialId},reason:Y.reason}))},rows:R.map((Y)=>Y.row),declined:H}}function t3($){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 D1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Z1($){return $===void 0||typeof $==="string"}function S8($){let Z=D1($)?b0($.quota):void 0;if(!D1($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!Z1($.accountIdentity)||!Z1($.email)||!Z1($.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 k8=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function $9($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!D1(J)||!Z1(J.credentialId)||typeof J.reason!=="string"||!k8.has(J.reason))return;Z.push(J)}return Z}function z9($){if(!D1($)||$.version!==1||!Z1($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!$9($.rejected))throw new L("invalid-state","Claustrum roster file is not valid");let Z=[];for(let X of $.rows){let G=S8(X);if(!G)throw new L("invalid-state","Claustrum roster file is not valid");Z.push(G)}let J=[];for(let X of $.declined){if(!D1(X)||typeof X.credentialId!=="string"||!Z1(X.accountIdentity))throw new L("invalid-state","Claustrum roster file is not valid");J.push(X)}let z=$9($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...z&&{rejected:z},rows:Z,declined:J}}function X9($){return z9(JSON.parse(JSON.stringify($)))}async function w($){let Z;try{Z=await J0($,A)}catch(z){if(z.code==="ENOENT")return;throw z}let J;try{J=JSON.parse(Z)}catch{throw new L("invalid-state","Claustrum roster file is not valid")}return z9(J)}var G9={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},Q9={name:"claustrum-roster",ttlMs:30000};async function f0($,Z,J={}){return k3($,{...G9,signal:J.signal},async(z)=>{let X=await w($),{next:G,result:Q}=await Z(X,{assertOwned:()=>z.assertOwned()});if(G)await z.assertOwned(),await K1($,G,{beforeRename:async()=>{await J.beforePublish?.(),J.signal?.throwIfAborted(),await z.assertOwned()}});return Q})}function e3($,Z){return f0($,(J)=>{let z=J?.rows.find((G)=>G.routeId===Z);if(!J||!z)throw new L("route-unavailable","Claustrum route is not in the roster");let X=i3(J.declined,z.credentialId,z.accountIdentity);return{next:{...J,declined:X,rows:J.rows.map((G)=>G===z?{...G,enabled:!1}:G)},result:void 0}})}function $$($,Z){return f0($,(J)=>{let z=J?.rows.find((X)=>X.routeId===Z);if(!J||!z)throw new L("route-unavailable","Claustrum route is not in the roster");return{next:{...J,declined:o3(J.declined,Y0(z),z.accountIdentity),rows:J.rows.map((X)=>X===z?{...X,enabled:!0}:X)},result:void 0}})}function T8($){return new L("invalid-order",$)}function E8($,Z){if(!Array.isArray(Z))return"route ids must be an array of route ids";let J=new Set($.map((G)=>G.routeId)),z=new Set;for(let G of Z){if(typeof G!=="string")return"route ids must be an array of route ids";if(z.has(G))return`route id ${G} appears more than once`;if(!J.has(G))return`route id ${G} is not in the roster`;z.add(G)}let X=[...J].filter((G)=>!z.has(G)).length;if(X>0)return`the order leaves out ${X} roster route id${X===1?"":"s"}`;return}function Z$($,Z,J={}){return f0($,(z)=>{let X=z?.rows??[],G=E8(X,Z);if(G)throw T8(G);let Q=new Map;for(let U of X){let q=Q.get(U.routeId);if(q)q.push(U);else Q.set(U.routeId,[U])}let W=[...Z],H=W.flatMap((U)=>Q.get(U)??[]);if(!z||H.every((U,q)=>U===X[q]))return{result:{ids:W,outcome:"unchanged"}};return{next:{...z,rows:H},result:{ids:W,outcome:"reordered"}}},{...J.signal&&{signal:J.signal}})}function b8($,Z){if(!Y0($).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")&&Y0($).length===1)return"bind";return"refuse"}async function J$($,Z){let{routeId:J,observation:z,...X}=Z;return W9($,{routeId:J,observation:z,accountIdentity:X.accountIdentity,receipt:X})}async function W9($,Z){if(!$1(Z.observation))return!1;let J=r($,await w($));if(!_0(J,Z).kept)return!1;return Y9($,Z)}function z$($,Z){return W9($,Z)}function _0($,Z){let J=$?.rows.find((Q)=>Q.routeId===Z.routeId),z=!J?"refuse":Z.receipt?b8(J,Z.receipt):J.accountIdentity!==void 0&&J.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!J||z==="refuse")return{roster:$,kept:!1};let X=M1(J.quota,Z.observation),G=z==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{roster:{...$,rows:$.rows.map((Q)=>Q===J?{...Q,...G,quota:X}:Q)},kept:!0}}var n1=new Map;function N1($){n1.delete(j1($))}function H9($,Z){let J=j1($);if(Z instanceof L)return Z.kind==="roster-busy";if(Z instanceof C0||Z instanceof F0)return j1(Z.details.target)===J;if(Z instanceof m){let z=j1(Z.path);return[G9.name,Q9.name].some((X)=>{let G=V1(J,X);return z===G||z.startsWith(`${G}.`)})}return!1}var f8=4;async function Z9($){try{let{dev:Z,ino:J,size:z,mtimeMs:X}=await O8($);return{dev:Z,ino:J,size:z,mtimeMs:X}}catch{return}}function x8($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function y8($,Z,J){for(let z=0;z<f8;z++){let X=await Z9($),G=await w($),Q,W,H;try{({target:Q,local:W}=Z(G));let U=JSON.stringify(J(Q));H=JSON.stringify(Q)!==U||W!==void 0&&JSON.stringify(W)!==U}catch{return"commit"}if(!x8(X,await Z9($)))continue;if(H)return"commit";return U9($)?"commit":"unchanged"}return"commit"}async function L1($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){N1($.path);return}let J=await B0({...Q9,path:$.path,renew:!0});if(!J){let Q=await w($.path);if($.signal?.throwIfAborted(),!Q?.view)throw new L("roster-busy","Claustrum account discovery is already in progress");return Q}let z=j1($.path),X=$.listedOver,G;try{let Q=await w($.path),W=X?void 0:n1.get(z);G=W&&(W.previousView===Q?.view||W.inventory.view===Q?.view)?W:{inventory:await $.custody.discover($.signal),previousView:Q?.view},n1.delete(z);let{inventory:H}=G;$.onInventory?.(H),$.signal?.throwIfAborted();let U=typeof $.projection==="function"?$.projection():$.projection,q=(F)=>J9(F,H,U),K=async()=>{return $.signal?.throwIfAborted(),await J.assertOwned(),Z()};if(await y8($.path,(F)=>{if(X)return{target:F};let C=r($.path,F);return{target:F,...C!==F&&{local:C}}},q)==="unchanged"){if(!await K())return;return await w($.path)}return await f0($.path,async(F)=>{if(!await Z())return{result:void 0};if($.signal?.throwIfAborted(),await J.assertOwned(),X&&F?.view!==X.view&&F?.view!==H.view)return{result:F};let C=q(F);return{...JSON.stringify(F)!==JSON.stringify(C)&&{next:C},result:C}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await J.assertOwned()}})}catch(Q){if(Q instanceof C0&&G&&!X&&!$.signal?.aborted&&await Z())n1.set(z,G);throw Q}finally{await J.release()}}var x0=new Map,g8=H0("claustrum"),K9=100;function V9($,Z=d3){let J=o1($),z=x0.get(J);if(!z)z={path:J,pending:new Map,listeners:new Set,wake:new Set,abort:new AbortController,clock:Z,failures:0,draining:!1,order:0},x0.set(J,z);return z}function F9($,Z,J){let z=V9($,J);z.listeners.add(Z);let X;return()=>X??=(()=>{return z.listeners.delete(Z),z.listeners.size?Promise.resolve():X$($)})()}function v8($){return t2($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function Y9($,Z){if(!$1(Z.observation))return Promise.resolve(!1);let J=V9($),z=JSON.stringify([Z.accountIdentity??null,Z.accountIdentity===void 0?Z.routeId:null]),X=J.pending.get(z)??new Map;for(let[G,Q]of v8(Z)){let W=X.get(G);if(!W||Q.at>=W.at){if(Q.order=++J.order,Q.publication.observation.coverage)Q.priorReading=W?.publication.observation.readings?W.publication:W?.priorReading;X.set(G,Q)}}if(X.size)J.pending.set(z,X);for(let G of J.listeners)G(Z);return M9(J,K9),Promise.resolve(!0)}function B9($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,J)=>Z.order-J.order)}function r($,Z){let J=x0.get(o1($));if(J)for(let z of B9(J.pending)){if(z.priorReading)Z=_0(Z,z.priorReading).roster;Z=_0(Z,z.publication).roster}return Z}function U9($){return!!x0.get(o1($))?.pending.size}function M9($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let J=$.draining?0:($.committedAt??-1/0)+p3-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,J),()=>{return $.timer=void 0,j9($)}),!$.draining)$.timer.unref?.()}function q9($){$.timer?.cancel(),$.timer=void 0}function j9($){if($.running||$.abort.signal.aborted)return $.running??Promise.resolve();let Z=new Map([...$.pending].map(([J,z])=>[J,new Map(z)]));return $.running=(async()=>{try{if(await f0($.path,(z)=>{let X=z;for(let Q of B9(Z)){if(Q.priorReading)X=_0(X,Q.priorReading).roster;X=_0(X,Q.publication).roster}let G=JSON.stringify(X)!==JSON.stringify(z);return{...G&&{next:X},result:G}},{signal:$.abort.signal}))$.committedAt=$.clock.now();for(let[z,X]of Z){let G=$.pending.get(z);for(let[Q,W]of X)if(G?.get(Q)===W)G.delete(Q);if(!G?.size)$.pending.delete(z)}$.failures=0}catch(J){if(!$.abort.signal.aborted&&$.failures++===0)g8.warn("vault quota publication delayed; retrying",{error:J instanceof Error?J.message:String(J)})}finally{$.running=void 0;for(let z of $.wake)z();let J=$.failures?Math.min(5000,100*2**Math.min($.failures,6))*(0.5+Math.random()):K9;M9($,J)}})(),$.running}async function X$($,Z=1000){let J=o1($),z=x0.get(J);if(!z)return;z.draining=!0,q9(z);let X,G,Q=new Promise((W)=>{G=()=>{if(!z.pending.size||z.abort.signal.aborted)W()},z.wake.add(G),G()});try{if(z.pending.size)j9(z);await Promise.race([Q,new Promise((W)=>{X=setTimeout(W,Math.max(0,Z))})])}finally{if(clearTimeout(X),G)z.wake.delete(G);if(z.draining=!1,!z.listeners.size){if(z.abort.abort(),q9(z),z.pending.clear(),x0.get(J)===z)x0.delete(J)}}}var r1=1e4;function D9(){return new t}var G$;function L9($,Z){if(!G$)throw Error("ClaustrumConsumer is not initialized");return G$($,Z)}function N9(){return new L("not-active","Claustrum scoped custody is not active")}class Q${#$;#Z=new AbortController;#J;#W;#G;#Q;#z;#X;#M;#H;#Y=!1;#q=new Set;#F;#U;#j;#B;#D=new Map;#_;#C;#K;#L;#I=new WeakMap;static{G$=($,Z)=>{let J=new Q$(Z);return J.#K=$,{consumer:J,hooks:J.#x()}}}constructor($){this.#$=$,this.#J=$.logger??H0("claustrum"),this.#W=n0(this.#J,this.#Z.signal),this.#C=F9($.rosterPath,(Z)=>{this.#X=_0(this.#X,Z).roster})}#V($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#P($){return this.#q.add($),$.then(()=>this.#q.delete($),()=>this.#q.delete($)),$}async#A(){return await this.#$.isCustodyActive?.()??!0}#R($,Z){let J=R0([this.#Z.signal,...Z?[Z]:[]]);return new Promise((z,X)=>{let G=()=>{J.signal.removeEventListener("abort",Q),J.dispose()},Q=()=>{G(),X(J.signal.reason)};if(J.signal.addEventListener("abort",Q,{once:!0}),$.then((W)=>{if(G(),J.signal.aborted)X(J.signal.reason);else z(W)},(W)=>{G(),X(W)}),J.signal.aborted)Q()})}async#N(){if(this.#V(),this.#G)return this.#G;if(!this.#Q){let $={timedOut:!1};this.#Q=this.#O($),this.#P(this.#Q)}return this.#R(this.#Q)}#O($){let Z=this.#$.setTimeoutImpl??setTimeout,J=this.#$.clearTimeoutImpl??clearTimeout,z=this.#$.connect().then((Q)=>{if(this.#Z.signal.aborted||$.timedOut){if(Q.close(),!$.timedOut)this.#V();throw D9()}if(this.#G=new o0({client:Q,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#J,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&Q.insula)this.#U=O3(Q.insula,this.#$.tokenPath);return this.#G}),X,G=new Promise((Q,W)=>{X=Z(()=>{if($.timedOut=!0,this.#Z.signal.aborted)return;this.#J.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:this.#k()}),W(D9())},this.#k()),X.unref?.()});return Promise.race([z,G]).finally(()=>{if(X)J(X);this.#Q=void 0})}#k(){return this.#$.connectTimeoutMs??r1}snapshot(){return this.#X}grantReach(){if(this.#K)return this.#K.grantReach(this.#X?.view);let $=this.#M;return $&&this.#X?.view===$.view?$.reach:void 0}watchState(){if(this.#K)return Object.freeze({vault:this.#K.watchMode()});return Object.freeze({vault:this.#j?.mode??"polling",...this.#$.insula&&{insula:this.#U?.source.watchMode()??"polling"}})}#S(){this.#j?.close(),this.#j=void 0,this.#B?.(),this.#B=void 0}keptReceiptState(){if(this.#K){let $=this.#L;return $&&this.#K.leaseLive($)?$.custody.keptReceiptState():this.#K.keptReceiptState()}return this.#G?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return t3(this.#X)}refresh(){if(this.#V(),this.#K)return this.#P(this.#y(this.#K));if(this.#z)return this.#z;return this.#z=(async()=>{if(!await this.#A()){if(this.#X=void 0,this.#M=void 0,this.#S(),this.#G)this.#G.close(),this.#P(this.#G.dispose(this.#W));this.#G=void 0,this.#U?.release(),this.#U=void 0;return}let $=await this.#N(),Z,J=await L1({path:this.#$.rosterPath,custody:$,onInventory:(X)=>{Z=X},isActive:()=>this.#A(),signal:this.#Z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#V();let z=J?.view!==this.#X?.view;if(this.#X=r(this.#$.rosterPath,J),$.retain(J?.rows??[]),Z&&J?.view!==void 0)this.#M=Z.grantReach?{view:J.view,reach:Z.grantReach}:void 0;if(J&&z)this.#$.onRoster?.(J);return this.#_=(this.#$.now??Date.now)(),J})().finally(()=>{this.#z=void 0}),this.#P(this.#z),this.#z}start(){if(this.#Y)return;if(this.#V(),this.#Y=!0,this.#K){this.#K.start();return}let $=async()=>{try{if(await this.#b())await this.refresh();await this.refreshInsulaQuota(),this.#E()}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.#H=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#H=void 0,this.#P($())},Z),this.#H.unref?.()};this.#P($())}async#b(){if(this.#j?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#_===void 0||$-this.#_>=p0)return!0;return!await this.#A()}#E(){let $=this.#G;if(this.#Z.signal.aborted||!$)return;if(this.#j??=$.watchRoster({view:()=>this.#X?.view,onView:()=>this.#P((async()=>{while(this.#z)await this.#z.catch(()=>{});if(this.#Z.signal.aborted)return;await this.refresh()})()),onRefused:(Z)=>this.#$.onError?.(Z),onError:(Z)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(Z)}}),this.#$.insula&&this.#U&&!this.#B)this.#B=this.#U.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#A())return;try{await O0(this.#$.tokenPath),await this.#N(),await this.#U?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#A())return;try{return await O0(this.#$.tokenPath),this.#T($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#A())return;try{await O0(this.#$.tokenPath);let J=r(this.#$.rosterPath,await w(this.#$.rosterPath))?.rows.find((z)=>z.routeId===$);return this.#T(J?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute($){let Z=this.#$.insula;if(!Z||this.#Z.signal.aborted||!await this.#A())return{miss:"unreachable"};try{await O0(this.#$.tokenPath);let z=r(this.#$.rosterPath,await w(this.#$.rosterPath))?.rows.find((Q)=>Q.routeId===$)?.accountIdentity;if(!z||!this.#U)return{miss:"unreachable"};let X=this.#U.source.lookup(Z.provider,z,(this.#$.now??Date.now)()),G=X.reading&&Z.normalize(X.reading.entry,X.reading.context);if(X.miss)return{miss:X.miss,...G!==void 0&&{reading:G}};return G===void 0?{miss:"unreachable"}:{reading:G}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute($,Z){let J=await this.lookupInsulaQuotaForRoute($);if(J.miss==="cold"||J.miss==="upstream-failed"){if(this.#D.get($)!==J.miss)this.#D.set($,J.miss),this.#J.warn("skipped insula provider poll",{reason:J.miss});return}return this.#D.delete($),J.miss?Z():J.reading}#T($){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){if(this.#K)return this.#h(this.#K,$,Z);this.#V(Z);let J=this.#X??await this.#R(this.refresh(),Z);if(!J||!await this.#A())throw this.#G?.close(),this.#G=void 0,this.#S(),this.#U?.release(),this.#U=void 0,new L("not-active","Claustrum scoped custody is not active");let z=r(this.#$.rosterPath,await w(this.#$.rosterPath));this.#V(Z);let X=J.rows.find((H)=>H.routeId===$),G=z?.rows.find((H)=>H.routeId===$);if(G&&!G.enabled){if(X)this.#G?.forget(X.credentialId);throw new L("route-declined","Claustrum route is disabled")}if(!X||!G||G.state!=="active"||G.credentialId!==X.credentialId||G.accountIdentity!==X.accountIdentity||G.credentialType!==X.credentialType){if(X)this.#G?.forget(X.credentialId);throw new L("route-unavailable","Claustrum route is disabled, removed or changed")}let Q=await this.#R(this.#N(),Z),W=R0([this.#Z.signal,...Z?[Z]:[]]);try{return await Q.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},W.signal,$)}finally{W.dispose()}}#x(){return{install:($)=>{if(this.#Z.signal.aborted)return;let Z=$.view!==this.#X?.view;if(this.#X=r(this.#$.rosterPath,$),Z)try{this.#$.onRoster?.($)}catch(J){this.#$.onError?.(J)}},reset:()=>{this.#X=void 0},roster:()=>this.#X,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()}),onError:($)=>{if(!this.#Z.signal.aborted)this.#$.onError?.($)}}}async#y($){let Z=await $.refresh();if(this.#V(),!Z)return;if(Z.errors.has($.provider))throw Z.errors.get($.provider);return this.#X}#g($){if($&&this.#L!==$)return;this.#L?.release(),this.#L=void 0}async#f($,Z){let J=this.#L;if(J&&$.leaseLive(J))return J;this.#g();let z=await $.acquire(Z);if(this.#Z.signal.aborted)z.release(),this.#V();let X=this.#L;if(X&&$.leaseLive(X))return z.release(),X;return this.#L=z,z}async#h($,Z,J){if(this.#V(J),!this.#X)await this.#R($.refresh(),J);let z=this.#X;if(!await $.readAuthority())throw this.#g(),N9();if(this.#V(J),!z)throw new L("route-unavailable","Claustrum has no roster for this provider yet");let X=r(this.#$.rosterPath,await w(this.#$.rosterPath));this.#V(J);let G=z.rows.find((U)=>U.routeId===Z),Q=X?.rows.find((U)=>U.routeId===Z);if(Q&&!Q.enabled){if(G)$.forget(G.credentialId);throw new L("route-declined","Claustrum route is disabled")}if(!G||!Q||Q.state!=="active"||Q.credentialId!==G.credentialId||Q.accountIdentity!==G.accountIdentity||Q.credentialType!==G.credentialType){if(G)$.forget(G.credentialId);throw new L("route-unavailable","Claustrum route is disabled, removed or changed")}let W={credentialId:Q.credentialId,credentialType:Q.credentialType,...Q.accountIdentity!==void 0&&{accountIdentity:Q.accountIdentity}},H=R0([this.#Z.signal,...J?[J]:[]]);try{for(let U=0;;U++){let q=await this.#f($,H.signal);try{let K=await q.custody.authorize(W,H.signal,Z);return this.#I.set(K,q),K}catch(K){if(U>0||H.signal.aborted||$.leaseLive(q)||!(K instanceof L)||K.kind!=="closed")throw K;if(this.#g(q),!await $.readAuthority())throw N9()}}}finally{H.dispose()}}async reportFailure($,Z,J){if(this.#V(),this.#K){let z=this.#I.get($);if(!z)throw new L("no-receipt","Claustrum dispatch receipt has no active owner");await z.custody.reportFailure($,Z,J);return}if(!this.#G)throw new L("no-receipt","Claustrum dispatch receipt has no active owner");await this.#G.reportFailure($,Z,J)}async send($,Z,J){let z=J.signal,X=await this.authorize($,z),G=await Z(X,z);if(G.status===401&&X.fromKeptReceipt)return await this.reportFailure(X,401,J.reporterSource??"direct"),G;if(G.status===401&&!z?.aborted){let Q;try{Q=await this.authorize($,z),z?.throwIfAborted()}catch(W){if(z?.aborted)throw W}if(c3(J.site,X,Q,this.#J))await G.body?.cancel().catch(()=>{}),X=Q,G=await Z(Q,z)}if(G.status===401)await this.reportFailure(X,401,J.reporterSource??"direct").catch((Q)=>this.#$.onError?.(Q)),Promise.resolve().then(()=>this.refresh()).catch((Q)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(Q)});return G}async decline($){if(this.#V(),await e3(this.#$.rosterPath,$),this.#X=r(this.#$.rosterPath,await w(this.#$.rosterPath)),this.#K)this.#K.retainUnion();else this.#G?.retain(this.#X?.rows??[])}async accept($){this.#V(),await $$(this.#$.rosterPath,$),this.#X=r(this.#$.rosterPath,await w(this.#$.rosterPath))}async reorder($){this.#V();let Z=await Z$(this.#$.rosterPath,$);return this.#X=r(this.#$.rosterPath,await w(this.#$.rosterPath)),Z}async recordQuota($,Z,J){return this.#V(),J$(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}})}async recordAccountQuota($,Z,J){return this.#V(),z$(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:J})}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new L("closed","Claustrum consumer is closed")),this.#H)(this.#$.clearTimeoutImpl??clearTimeout)(this.#H);if(this.#H=void 0,this.#S(),this.#G)this.#G.close(),this.#P(this.#G.dispose(this.#W));this.#L?.release(),this.#L=void 0,this.#K?.detach(),this.#U?.release(),this.#U=void 0,this.#X=void 0,this.#M=void 0,this.#C(),N1(this.#$.rosterPath)}async dispose(){this.close(),this.#F??=Promise.all([i0(this.#q,this.#W),this.#C()]).then(()=>{}),await this.#F}}import{createHash as h8}from"node:crypto";import{readdir as m8,stat as w8}from"node:fs/promises";import{join as C1}from"node:path";var u8=/^[a-z0-9][a-z0-9._-]{0,63}$/,c8=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,p8=/^[0-9a-f]{16}$/,C9=3;function H$($,Z=new Set){if($===null)return"null";if(typeof $==="string"||typeof $==="boolean")return JSON.stringify($);if(typeof $==="number")return Number.isFinite($)?JSON.stringify($):void 0;if(typeof $!=="object"||Z.has($))return;let J=new Set(Z).add($),z=[];if(Array.isArray($)){for(let G=0;G<$.length;G++){let Q=H$($[G],J);if(Q===void 0)return;z.push(Q)}return`[${z.join(",")}]`}let X=Object.getPrototypeOf($);if(X!==Object.prototype&&X!==null)return;for(let G of Object.keys($).sort()){let Q=H$($[G],J);if(Q===void 0)return;z.push(`${JSON.stringify(G)}:${Q}`)}return`{${z.join(",")}}`}function d8($,Z){let J=H$({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??i1,mapAccount:$.mapAccount?String($.mapAccount):null});if(J===void 0)throw new L("invalid-state","Claustrum hub classifierInput must be plain JSON");return h8("sha256").update(J).digest("hex").slice(0,16)}function P9($,Z){if(typeof $!=="string"||!u8.test($)||c8.test($))throw new L("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function I0($="Claustrum custody lease is closed"){return new L("closed",$)}function W$(){return new L("not-active","Claustrum scoped custody is not active")}function O9(){return new t}function l8($,Z){return new Promise((J,z)=>{let X=()=>z(Z.reason);if(Z.addEventListener("abort",X,{once:!0}),$.then((G)=>{Z.removeEventListener("abort",X),J(G)},(G)=>{Z.removeEventListener("abort",X),z(G)}),Z.aborted)X()})}function A9($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class _9{#$;#Z;#J;#W=new AbortController;#G=new Map;#Q=new WeakMap;#z=0;#X;#M;#H;#Y;#q;#F;#U=0;#j;#B;#D;#_=!1;#C=new Set;#K;#L;#I;constructor($){if(!$.family||!("classify"in $.family))throw new L("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=P9($.hostGeneration,"host generation"),J=$.members.map((X)=>P9(X,"member"));if(new Set(J).size!==J.length)throw new L("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??H0("claustrum"),this.#J=n0(this.#Z,this.#W.signal),this.#L=C1($.stateDir,"rosters",Z),this.#I=d8($,J);let z=C1(this.#L,this.#I);for(let X of J)this.#G.set(X,{provider:X,path:C1(z,`${X}.json`),closed:!1})}#V($){return this.#C.add($),$.then(()=>this.#C.delete($),()=>this.#C.delete($)),$}#P(){if(this.#W.signal.aborted)throw I0("Claustrum discovery hub is closed")}#A($){let Z=this.#G.get($);if(!Z)throw new L("wrong-consumer","Claustrum hub has no such member");return Z}rosterPath($){return this.#A($).path}member($,Z){this.#P();let J=this.#A($);if(J.hooks)throw new L("wrong-consumer","Claustrum hub member was already built");for(let W of["rosterPath","tokenPath","family","connect","isCustodyActive","insula","pollIntervalMs","routePrefix","mapAccount"])if(W in Z)throw new L("wrong-consumer",`Claustrum hub members cannot take ${W}`);let z={provider:J.provider,start:()=>this.start(),refresh:()=>this.#m(),readAuthority:()=>this.#y(),acquire:(W)=>this.acquire(W),leaseLive:(W)=>this.#O(W),grantReach:(W)=>W!==void 0&&this.#j?.view===W?this.#j.reach:void 0,watchMode:()=>this.watchState(),keptReceiptState:()=>this.keptReceiptState(),retainUnion:()=>this.#w(),forget:(W)=>this.#X?.custody?.forget(W),detach:()=>{J.closed=!0}},X={rosterPath:J.path,...Z.reservedRouteIds&&{reservedRouteIds:Z.reservedRouteIds},...this.#$.routePrefix!==void 0&&{routePrefix:this.#$.routePrefix},...this.#$.mapAccount&&{mapAccount:this.#$.mapAccount},...Z.onRoster&&{onRoster:Z.onRoster},...Z.onError&&{onError:Z.onError},logger:Z.logger??this.#Z,...this.#$.now&&{now:this.#$.now}},{consumer:G,hooks:Q}=L9(z,X);return J.hooks=Q,G}#R(){let $={id:++this.#z,count:0,ended:!1,controller:new AbortController};return this.#X=$,$}#N($){return!$.ended&&this.#X===$&&!this.#W.signal.aborted}#O($){let Z=this.#Q.get($);return!!Z&&!Z.released&&!Z.generation.ended}#k($,Z=I0()){if($.ended)return;if($.ended=!0,$.count=0,this.#X===$)this.#X=void 0;if(this.#H&&this.#Q.get(this.#H)?.generation===$)this.#H=void 0;if(this.#Y?.generation===$)this.#Y.watch.close(),this.#Y=void 0;if($.controller.abort(Z),$.custody)$.custody.close(),this.#V($.custody.dispose(this.#J))}#S($){if($.ended)return;if($.count--,$.count<=0)this.#k($)}#b($){let Z=this.#M;if(Z?.generation===$&&Z.promise)return Z.promise;let J={generation:$,timedOut:!1},z=this.#$.connectTimeoutMs??r1,X,G=this.#$.connect().then((H)=>{if(J.timedOut)throw H.close(),O9();if(!this.#N($)||$.count<=0)throw H.close(),I0("Claustrum connection is no longer wanted");return $.custody=new o0({client:H,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Z,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),$.custody}),Q=new Promise((H,U)=>{X=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(J.timedOut=!0,!this.#N($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:z}),U(O9())},z),X.unref?.()});return J.promise=this.#V(Promise.race([G,Q]).finally(()=>{if(X)(this.#$.clearTimeoutImpl??clearTimeout)(X)})),J.promise.finally(()=>{if(this.#M===J)this.#M=void 0}).catch(()=>{}),this.#M=J,J.promise}acquire($){try{if(this.#P(),$?.throwIfAborted(),this.#F===!1)throw W$()}catch(J){return Promise.reject(J)}let Z=this.#X??this.#R();return Z.count++,this.#E(Z,$,!0)}async#E($,Z,J){let z=$.custody;if(!z){let X=R0([$.controller.signal,...Z?[Z]:[]]);try{z=await l8(this.#b($),X.signal)}catch(G){if(!$.ended)throw this.#S($),G;return this.#T(Z,J)}finally{X.dispose()}}if($.ended)return this.#T(Z,J);if(Z?.aborted)throw this.#S($),Z.reason;return this.#x($,z)}#T($,Z){if($?.throwIfAborted(),this.#P(),this.#F===!1)throw W$();if(!Z)throw I0();let J=this.#X??this.#R();return J.count++,this.#E(J,$,!1)}#x($,Z){let J={generation:$,custody:Z,released:!1},z=()=>{if(J.released||$.ended)throw I0()},X=Object.freeze({authorize:async(Q,W,H)=>{z();let U=R0([$.controller.signal,...W?[W]:[]]);try{return await Z.authorize(Q,U.signal,H)}finally{U.dispose()}},reportFailure:async(Q,W,H)=>{return z(),Z.reportFailure(Q,W,H)},forget:(Q)=>{z(),Z.forget(Q)},keptReceiptState:()=>{return z(),Z.keptReceiptState()}}),G=Object.freeze({custody:X,generation:$.id,release:()=>{if(J.released)return;J.released=!0,this.#S($)}});return this.#Q.set(G,J),G}leaseState(){let $=this.#X;return Object.freeze({generation:$?.id,count:$?.count??0})}async#y(){let $=await this.#$.isCustodyActive?.()??!0;if(this.#W.signal.aborted)return!1;let Z=this.#F;if(this.#F=$,!$&&Z!==!1)this.#g();return $}#g(){this.#U++;let $=this.#X;if($)this.#k($,W$());this.#H=void 0,this.#Y?.watch.close(),this.#Y=void 0,this.#j=void 0,this.#B=void 0;for(let Z of this.#G.values())Z.seen=void 0,Z.pending=void 0,Z.hooks?.reset(),N1(Z.path)}#f(){return[...this.#G.values()].filter(($)=>$.hooks&&!$.closed)}async#h(){let $=this.#H,Z=$&&this.#Q.get($);if($&&Z&&this.#O($))return Z;this.#H=void 0;let J=await this.acquire(this.#W.signal),z=this.#H&&this.#Q.get(this.#H);if(this.#H&&z&&this.#O(this.#H))return J.release(),z;this.#H=J;let X=this.#Q.get(J);if(!X)throw I0();return X}#m(){try{this.#P()}catch(z){return Promise.reject(z)}let $=this.#q;if($&&!$.generation?.ended)return $.promise;let Z={},J=this.#V(this.#s(Z).finally(()=>{if(this.#q===Z)this.#q=void 0}));return Z.promise=J,this.#q=Z,J}async#s($){if(!await this.#y())return;let Z=await this.#h(),J=Z.generation;if($.generation=J,!this.#N(J))return;let z=new Map;for(let W of this.#G.values())z.set(W,await w(W.path).then((H)=>H?{file:H}:{},(H)=>H instanceof Error?H:Error(String(H))));if(!this.#N(J))return;let X;try{X=await Z.custody.discover(J.controller.signal)}catch(W){if(!this.#N(J))return;for(let H of this.#G.values())if(H.pending)this.#v(H);throw W}let G=new Map,Q=!0;for(let W of this.#f()){if(!this.#N(J))return;let H=W.hooks;if(!H||W.closed)continue;let U={...X,credentials:X.credentials.filter((B)=>B.member===W.provider),skipped:X.skipped.filter((B)=>B.member===W.provider)},q=z.get(W),K;try{if(!q)throw I0("Claustrum hub member has no base view");if(q instanceof Error)throw q;let B=q.file?void 0:await this.#n(W);K=await L1({path:W.path,custody:{discover:async()=>U},isActive:()=>this.#N(J)&&this.#F===!0,signal:J.controller.signal,projection:()=>({...H.projection(),...B&&{seed:B}}),listedOver:{view:q.file?.view}})}catch(B){if(!this.#N(J))return;if(Q=!1,this.#v(W),H9(W.path,B))this.#Z.debug("claustrum hub member commit refused",{member:W.provider});else G.set(W.provider,B);continue}if(!this.#N(J))return;if(K?.view!==X.view)Q=!1,this.#v(W);else W.pending=void 0;if(!K)continue;if(this.#u(H,K)){Q=!1,this.#v(W);continue}if(W.seen=JSON.stringify(X9(K)),!W.closed)H.install(K)}if(!this.#N(J))return;if(this.#w(),Q)this.#j=Object.freeze({view:X.view,...X.grantReach&&{reach:X.grantReach},refused:Object.freeze([...X.refused??[]]),notMine:X.notMine??0});return this.#B=(this.#$.now??Date.now)(),{errors:G}}async#n($){let Z=`${$.provider}.json`,J=[C1(this.#L,Z)];try{for(let X of await m8(this.#L))if(X!==this.#I&&p8.test(X))J.push(C1(this.#L,X,Z))}catch{}let z;for(let X of J)try{let G=(await w8(X)).mtimeMs,Q=await w(X);if(Q&&(!z||G>z.modified))z={modified:G,roster:Q}}catch{}return z&&r3(z.roster)}#u($,Z){let J=$.projection().reservedRouteIds;return!!J?.size&&Z.rows.some((z)=>J.has(z.routeId))}#v($){let Z=($.pending?.failures??0)+1,J=Math.max(1,this.#$.pollIntervalMs??5000),z=Math.max(1,Math.ceil(p0/J)),X=Z<=C9?1:Math.min(2**(Z-C9),z);$.pending={failures:Z,wait:X-1}}#w(){let $=this.#X?.custody;if(!$)return;$.retain(this.#f().flatMap((Z)=>Z.hooks?.roster()?.rows??[]))}async#i(){let $=this.#U;for(let Z of this.#f()){let J;try{J=await w(Z.path)}catch(W){Z.hooks?.onError(W);continue}if($!==this.#U||this.#F!==!0)return;let z=Z.hooks;if(!J||!z||Z.closed)continue;let X=JSON.stringify(J);if(X===Z.seen)continue;let G=z.roster();if(!G||G.view!==J.view||this.#u(z,J)){Z.pending??={failures:0,wait:0};continue}let Q=A9(G);if(Z.seen=X,z.install(J),A9(z.roster())!==Q)this.#w()}}#o(){let $=!1;for(let J of this.#G.values()){if(!J.pending)continue;if(J.pending.wait<=0)$=!0;else J.pending.wait--}if(this.#Y?.watch.mode!=="watching"||$)return!0;let Z=(this.#$.now??Date.now)();return this.#B===void 0||Z-this.#B>=p0}#r(){let $=this.#H,Z=$&&this.#Q.get($);if(!$||!Z||!this.#O($)||this.#F!==!0)return;let J=Z.generation;if(!this.#N(J)||this.#Y?.generation===J)return;let z=Z.custody.watchRoster({view:()=>this.#j?.view,onView:()=>this.#V((async()=>{while(this.#q)await this.#q.promise.catch(()=>{});if(!this.#N(J))return;await this.#l()})()),onRefused:(X)=>this.#p(X),onError:(X)=>this.#c(X)});this.#Y={generation:J,watch:z}}#c($){if(!this.#W.signal.aborted)this.#$.onError?.($)}#p($){if(this.#W.signal.aborted)return;this.#$.onError?.($);for(let Z of this.#f())Z.hooks?.onError($)}#d($){for(let[Z,J]of $?.errors??[])this.#G.get(Z)?.hooks?.onError(J)}async#l(){let $;try{$=await this.#m()}catch(Z){this.#p(Z);return}this.#d($)}async#a(){try{if(await this.#y()){if(await this.#i(),this.#o())await this.#l();this.#r()}}catch(Z){this.#c(Z)}if(this.#W.signal.aborted)return;let $=this.#$.pollIntervalMs??5000;if($<=0)return;this.#D=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#D=void 0,this.#V(this.#a())},$),this.#D.unref?.()}start(){if(this.#_)return;this.#P(),this.#_=!0,this.#V(this.#a())}async refresh(){this.#d(await this.#m())}refusals(){let $=this.#j;return $&&Object.freeze({view:$.view,refused:$.refused,notMine:$.notMine})}grantReach(){return this.#j?.reach}watchState(){let $=this.#Y;return $&&this.#N($.generation)?$.watch.mode:"polling"}keptReceiptState(){return this.#X?.custody?.keptReceiptState()??Object.freeze({active:!1,since:null})}close(){if(this.#W.signal.aborted)return;if(this.#W.abort(I0("Claustrum discovery hub is closed")),this.#D)(this.#$.clearTimeoutImpl??clearTimeout)(this.#D);this.#D=void 0;let $=this.#X;if($)this.#k($);this.#H=void 0,this.#Y?.watch.close(),this.#Y=void 0}async dispose(){this.close(),this.#K??=i0(this.#C,this.#J),await this.#K}}var g0={opencode:n8,pi:i8};function Y$($,Z){let{tokenPath:J}=I9($,Z);return{stateDir:s8(J),host:$,override:J}}function U$($,Z){return o8($==="pi"?Z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0,$==="pi"?{...Z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:Z)}class y0 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"}}function q$($,Z){let J=Z??g0[$];if(typeof J!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(J))throw new y0("permission-refused");return["auth","grant","--principal",`enrolled:${J}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"]}async function R9($,Z){try{await Z.processFence();let J=await d1(Z.paths??I9($,Z.env),g0[$]);if(J.state==="blocked")throw new y0("permission-refused");let z=J.state==="approved"?J.approvedName:void 0,X=q$($,z);if((await Z.runner.run(Z.ckBinary??"ck",X,{env:Z.env})).exitCode!==0)throw new y0("permission-refused");return z}catch{throw new y0("permission-refused")}}import{createHash as z6}from"node:crypto";import{lstat as X6,mkdir as G6,readFile as h9}from"node:fs/promises";import{dirname as Q6}from"node:path";import{assertHostsStopped as W6,canonicalPath as V$,createNativeAccountRuntime as H6,custodyTombstoneOAuth as Y6,inspectNativeHostAuthEntry as m9,NativeMigrationError as v0,nativeJournalMayAdoptLaterHostLogin as U6,nativePoolHoldsAccountData as q6,prepareNativeMigration as K6,readNativeEnrollmentMode as w9,readNativeMigrationJournal as V6,releaseNativeMigrationPreflight as F6,requireNoSupervisedAuthContentSnapshot as B6,runNativeMigration as M6,writeNativeHostAuth as j6}from"@cortexkit/anthropic-auth-core";import{dirname as r8,join as S9,resolve as K$}from"node:path";import{ACCOUNT_FILE_NAME as k9,ACCOUNT_STATE_FILE_NAME as t8,canonicalPath as T9,getStickyRoutingStatePath as e8,resolveLocalRoutingDestination as $6,resolveNativePoolPaths as Z6}from"@cortexkit/anthropic-auth-core";async function M0($,Z){let J=$==="pi"?f9(Z):E9(Z),z=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),X=K$(z||S9(J,k9)),G=K$(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(X.endsWith(k9)?S9(r8(X),t8):`${X}.state.json`)),Q=await Z6(X,G),W=$==="pi"?Z.PI_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim();return{host:$,paths:Q,legacyConfigPath:X,legacyStatePath:G,hostAuthPath:$==="pi"?x9(Z):b9(Z),routingSourcePath:K$(W||e8(X)),routingDestinationPath:$6($,Q,Z)}}async function y9($){let Z=new Map;for(let J of $){let z=new Set;for(let[X,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 Q=await T9(G);if(z.has(Q)&&!(X===9&&Q===await T9(J.routingSourcePath)))throw Error("Native setup storage paths overlap");let W=Z.get(Q);if(W!==void 0&&W!==J.host)throw Error("Native setup storage paths overlap between selected hosts");Z.set(Q,J.host),z.add(Q)}}}import{types as J6}from"node:util";var g9=new WeakMap;function v9($){return typeof $==="object"&&$!==null?g9.get($):void 0}function t1($){if(!$||typeof $!=="object"||J6.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 i extends Error{constructor($){super($);this.name="SetupRefusal",g9.set(this,$)}}var F$="OpenCode's separate Anthropic login is not used. Add that account through /claude Accounts if needed, or remove the separate login from OpenCode.";function u9($){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 B$($,Z){let J=[];for(let z of $)if(await w9(z,Z)!=="local")J.push(u9(z));if(J.length)throw new i(J.join(`
|
|
13
|
+
`))}function h0($,Z){return async()=>{B6(Z.env);try{await W6(Z.fence,Z.env)}catch(J){let z=t1(J);if(z)throw new i(z);throw J}await B$([$],Z.env)}}async function M$($){try{return z6("sha256").update(await h9($)).digest("hex")}catch(Z){if(Z.code==="ENOENT")return"absent";throw new v0("unsafe-source")}}async function P1($,Z){let J;try{J=JSON.parse(await h9(Z,"utf8"))}catch(G){if(G.code!=="ENOENT")throw new v0("unsafe-source")}let z=m9($,J),X=J?.anthropic;return{...z,realLogin:z.kind==="oauth"&&Boolean(X?.access&&X.refresh)}}async function e1($,Z){let{paths:J}=$,z=$.generation2?void 0:await P1(J.host,J.hostAuthPath),X=await Promise.all([J.paths.config,J.paths.state,J.paths.runtime,J.paths.roster,J.paths.journal,J.routingDestinationPath].map(M$));return JSON.stringify([await w9(J.host,Z),z?.digest,...X])}async function j$($,Z,J){let z=Z.paths??await M0($,Z.env),X=h0($,Z);await X();let G=await V6(z.paths);if(G&&G.host!==$)throw new v0("invalid-source");let Q=G?.phase==="committed"||G?.phase==="retired";if(G&&G.kind!=="empty-init"&&(G.hostAuthPath!==await V$(z.hostAuthPath)||G.routingPaths.source!==await V$(z.routingSourcePath)||G.routingPaths.destination!==await V$(z.routingDestinationPath)))throw new v0("invalid-source");let W={paths:z,generation2:J,action:"migration",notice:!1,fingerprint:"",authorityPhase:G?.phase??"absent",poolPopulation:"not-evaluated"};if(J){if(G&&!Q)throw new v0("invalid-source");if(W.action=G?"reuse":"empty-init",!G){let H=[z.paths.config,z.paths.state,z.paths.runtime,z.paths.roster];if(!Z.env.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE)H.push(z.routingDestinationPath);for(let U of H){try{await X6(U)}catch(q){if(q.code==="ENOENT")continue;throw new v0("unsafe-source")}throw new v0("invalid-source")}}}else{W.slot=await P1($,z.hostAuthPath);let H=U6(G,$)&&W.slot.kind==="oauth";W.poolPopulation=G?.kind==="empty-init"||H?await q6({paths:z.paths}):"not-evaluated";let U=W.poolPopulation===!0;if($==="opencode"&&(U||Q&&G?.kind!=="empty-init"&&!H&&W.slot.kind==="oauth"))W.action="skip",W.notice=W.slot.realLogin;else W.preflight=await K6({...z,env:Z.env,processFence:X,removePiAnthropicAuth:Z.removePiAnthropicAuth})}return W.fingerprint=await e1(W,Z.env),W}async function J1($,Z){await h0($.paths.host,Z)();let J=await j$($.paths.host,{...Z,paths:$.paths},$.generation2);try{if(J.fingerprint!==$.fingerprint||J.action!==$.action)throw new i("Setup inputs changed. Rerun setup with all hosts stopped.")}finally{if(J.preflight)F6(J.preflight)}}async function D$($,Z){if($.paths.host!=="opencode"||$.slot?.kind!=="absent")return;let J=h0("opencode",Z);await J(),await G6(Q6($.paths.hostAuthPath),{recursive:!0,mode:448}),await j6({host:"opencode",authPath:$.paths.hostAuthPath,sourceDigest:"absent",expectedDigest:m9("opencode",{anthropic:Y6("anthropic")}).digest,env:Z.env,removePiAnthropicAuth:!1,processFence:J})}async function c9($,Z){let J={...Z.env},z=h0($,{...Z,env:J});await z();let X=Z.paths??await M0($,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 M6({paths:X.paths,legacyConfigPath:X.legacyConfigPath,legacyStatePath:X.legacyStatePath,host:$,hostAuthPath:X.hostAuthPath,routingSourcePath:X.routingSourcePath,routingDestinationPath:X.routingDestinationPath,env:J,processFence:z,removePiAnthropicAuth:Z.removePiAnthropicAuth,preflight:Z.preflight});if(G){let Q=H6({paths:X.paths,host:$,vault:{env:J},beforePoolWrite:z});try{if((await Q.read()).mode!=="local")throw new i(u9($));await z(),await Q.loginOAuth({routeId:"main",replace:!0,...G})}finally{await Q.close()}}if(Z.skipMigration){let Q=await P1($,X.hostAuthPath);await D$({paths:X,slot:Q},Z)}}var p9={opencode:"OpenCode",pi:"Pi"};function I6($,Z,J){switch($){case"auth-content-refused":return"Run setup without OPENCODE_AUTH_CONTENT in the environment.";case"host-auth-invalid":return"The host auth file could not be read safely.";case"primary-conflict":return"Pi has a stored Anthropic API key, which would take precedence over the vault account. Remove it in Pi, then rerun setup.";case"consent-required":return"Pi has stored Anthropic authentication. Explicit consent is required to move it aside for vault use.";case"primary-unverified":return"The vault has no verified default Claude account. Sign in through the vault and rerun setup.";case"no-read-grant":return`${p9[Z]} has no read grant in the vault, so setup cannot see any Claude login. Run ${["ck",...q$(Z,J)].join(" ")}, then rerun setup.`;case"grant-reaches-nothing":return`${p9[Z]}'s vault read grant reaches no Claude login: no vault login carries the anthropic-native category, which logins saved before vault categories existed lack. Run ck auth reclassify --from-registry, check the logins with ck auth status, then rerun setup.`}}class z0 extends Error{host;approvedName;code;constructor($,Z="opencode",J){super(I6($,Z,J));this.host=Z;this.approvedName=J;this.name="NativeVaultActivationError",this.code=$}}function R6($){let Z=$?.grantReach;if(!Z||$.credentials.length>0||$.skipped.length>0)return"primary-unverified";return Z.grants===0?"no-read-grant":"grant-reaches-nothing"}async function L$($){try{return JSON.parse(await D6($,"utf8"))}catch(Z){if(Z.code==="ENOENT")return;throw new z0("host-auth-invalid")}}async function O1($,Z){if($==="opencode")return"opencode";let J=Z.paths??await M0($,Z.env),z=N$($,await L$(J.hostAuthPath)),X=C$({env:Z.env,authPath:J.hostAuthPath}),{stashPath:G}=O6({env:Z.env,authPath:J.hostAuthPath});return JSON.stringify([z.digest,await X.inspect(),await M$(G)])}async function d9($){try{_6($.env)}catch{throw new z0("auth-content-refused")}try{await N6($.fence,$.env)}catch(Z){let J=t1(Z);if(J)throw new i(J);throw Z}}async function l9($,Z){let J={...Z.env};await(()=>d9({...Z,env:J}))();let X=Z.paths??await M0($,J),G=$==="opencode"&&Z.inspectOpenCodeAuth!==!1&&N$("opencode",await L$(X.hostAuthPath)).kind==="oauth";if($==="pi"){let Q=N$("pi",await L$(X.hostAuthPath)),W=await C$({env:J,authPath:X.hostAuthPath}).inspect();if(W.slot==="placeholder"&&W.stash==="missing")throw new P6("missing-stash");if(Q.kind!=="absent"&&W.slot!=="placeholder"&&!Z.removePiAnthropicAuth)throw new z0("consent-required")}return{priorMode:await A6($,J),fingerprint:await O1($,{...Z,env:J}),separateOpenCodeLogin:G}}async function a9($,Z,J){let z={...Z.env},X=()=>d9({...Z,env:z});await X();let G=Z.paths??await M0($,z);if(await O1($,Z)!==J.fingerprint)throw new z0("host-auth-invalid");let Q=await R9($,{env:z,runner:Z.runner,processFence:X,ckBinary:Z.enrollment?.ckBinary,paths:Z.enrollment?.paths}),W=Z.discover??(()=>C6({paths:G.paths,host:$,env:$==="pi"?{...z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE}:z})),H,U=async()=>{return H=await W(),H},q=L6({paths:G.paths,host:$,vault:{env:z,discover:U}});try{await X(),await q.vault.refresh();let K=await q.read(),B=K.accounts.find((F)=>F.id==="main");if(K.mode!=="claustrum"||!B?.accountIdentity||B.source!=="vault"){let F=R6(H);throw F==="primary-unverified"?new z0(F):new z0(F,$,Q)}if(await X(),$==="pi")await C$({env:z,authPath:G.hostAuthPath}).enterVault();return J.priorMode==="claustrum"?"already-vault":"committed"}finally{await q.close()}}var S6=/(?:^|[/\\])(opencode|litecode|opencode2|pi)(?:\.exe)?(?=$|\s|")/i;class P$ extends Error{activeHosts;constructor($){let Z=$.map((z)=>({pid:z.pid,command:S6.exec(z.command)?.[1]??"host"})),J=Z.map((z)=>` - PID ${z.pid}: ${z.command}`).join(`
|
|
13
14
|
`);super(`OpenCode or Pi processes are currently running:
|
|
14
15
|
${J}
|
|
15
16
|
|
|
16
|
-
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=Z,this.name="ProcessFenceViolationError"}}var
|
|
17
|
-
`,$.length-
|
|
18
|
-
`,
|
|
17
|
+
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=Z,this.name="ProcessFenceViolationError"}}var c6={"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 A1(){return($)=>$}var _$=["opencode","pi"],p6=new Set(["enrolled","not-enrolled","unknown"]),e9=A1()(["auth-content-refused","host-auth-invalid","primary-conflict","consent-required","primary-unverified","no-read-grant","grant-reaches-nothing"]),$4=A1()(["enrollment-refused","enrollment-reset","approval-refused","permission-refused"]),Z4=A1()(["invalid-source","unsafe-source","consent-required","primary-unverified","migration-busy","ownership-lost","retirement-refused","pool-populated","host-login-present","settings-changed"]),J4=A1()(["invalid-options","invalid-auth","invalid-stash","unsafe-path","missing-stash","conflict","lock-timeout","lock-compromised","io"]),z4=A1()(["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","invalid-order"]),d6={name:new Set(["Error","TypeError","SyntaxError","RangeError","AggregateError","AbortError","PrivateFileError","PrivateFilesUnavailableError","DiagnosticFileError","NativeRuntimeError","NativeAuthorityError","NativeMigrationError","NativeMigrationSourceError","NativeHostAuthError","NativeHostAuthWriteError","NativePiAuthSlotError","NativeCustodyError","NativeVaultActivationError","NativeVaultEnrollmentError","SetupCommandError","HostNotEnrolledError","ProcessFenceViolationError","ProcessInspectionError","LockOwnershipError","LockContentionError","ClaustrumConsumerError","ClaustrumCredentialError"]),code:new Set([...e9,...$4,...Z4,...J4,...z4,"EACCES","EPERM","ENOENT","EEXIST","ENOTDIR","EISDIR","ENOTEMPTY","EBUSY","ETIMEDOUT","ECONNREFUSED","ECONNRESET","ECANCELED","EIO","EINVAL","ENOTSUP","ENOSYS","ENOMEM","EMFILE","ENFILE","ELOOP","EROFS","EXDEV","ENAMETOOLONG","EBADF","EPIPE","ENOSPC","EINTR","ERR_INVALID_ARG_TYPE","ERR_INVALID_ARG_VALUE","ERR_OUT_OF_RANGE","ERR_FEATURE_UNAVAILABLE_ON_PLATFORM","ERR_PRIVATE_FILES_SECURITY","ERR_PRIVATE_FILES_UNAVAILABLE","ERR_PRIVATE_FILE","ERR_DIAGNOSTICS_DIRECTORY_UNAVAILABLE","ERR_DIAGNOSTICS_NOT_DIRECTORY","ERR_DIAGNOSTICS_NOT_OWNER_ONLY","unsafe-runtime","invalid-runtime","runtime-io","runtime-conflict","publication-refused","invalid-journal","source-io","source-changed","source-too-large","write-io"]),stage:new Set(["safe-parent","verify","directory","read","create","directory-create","rename","stage-directory","stage-create","before-rename","published-callback","published-verify","directory-sync-unsupported"]),reason:new Set(["wrong-owner","extra-ace","not-protected","null-dacl","empty-dacl","reparse-point","unsupported-filesystem","native-addon-unavailable","unsafe-ancestor","wrong-kind","io-error","mode","writable-by-others"])},l6=new Set([...e9.flatMap(($)=>$==="no-read-grant"||$==="grant-reaches-nothing"?_$.map((Z)=>new z0($,Z).message):[new z0($).message]),...$4.map(($)=>new y0($).message),...Z4.map(($)=>new m6($).message),...J4.map(($)=>new w6($).message),...z4.map(($)=>`Native custody refused: ${$}`),t9,"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 omit vault-only flags and 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 npx @cortexkit/opencode-anthropic-auth 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","Claustrum connection failed; start ck and rerun setup.","Claustrum enrollment refused; inspect its status with ck before rerunning setup.","Invalid enrollment request id.","This Claustrum vault does not support connecting plugins yet, so setup cannot connect to it. Run setup without --claustrum to use local accounts.",'This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or run setup without --claustrum to use local accounts.',"OAuth metadata read failed"]),a6=Object.values(g0).join("|"),s6="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",n6=[new RegExp(`^Claustrum approval is still pending\\. In another terminal, run: ck auth enroll approve --request-id [A-Za-z0-9_-]{1,128} --name (?:${a6}) and then rerun setup\\.$`),/^The vault never created the enrollment request \(last error: [a-z][a-z0-9_]{0,63}\)\. Check that ck is running, then rerun setup\.$/],i6=new Set(["opencode","litecode","opencode2","pi","host"]),o6=64,r6=256,t6=4096,O$=65536,e6=4096,$5=3,n9="[output beyond the diagnostic limit omitted]",Z5="[output withheld: no line break within the inspected window]",J5="[detail withheld: the known credentials could not be read safely]",R$=new TextEncoder,X4=new TextDecoder;function f($,Z){let J=Object.getOwnPropertyDescriptor($,Z);return J!==void 0&&"value"in J?J.value:void 0}function j0($){return $!==null&&(typeof $==="object"||typeof $==="function")&&!I$.isProxy($)}function S$($,Z){if(!j0($)||!Array.isArray($))return;let J=f($,"length");if(typeof J!=="number"||J>Z)return;let z=[];for(let X=0;X<J;X+=1){let G=Object.getOwnPropertyDescriptor($,String(X));if(G===void 0||!("value"in G))return;z.push(G.value)}return z}function z5($){let Z=S$($,o6);if(Z===void 0||Z.length===0)return;let J=[];for(let z of Z){if(!j0(z))return;let X=f(z,"pid"),G=f(z,"command");if(typeof X!=="number"||!Number.isSafeInteger(X)||X<0)return;if(typeof G!=="string"||!i6.has(G.toLowerCase()))return;J.push({pid:X,command:G})}return J}function k$($){try{if(!j0($))return;if(f($,"name")==="ProcessInspectionError")return"";let Z=f($,"message");if(typeof Z!=="string")return;if(f($,"name")==="HostNotEnrolledError"&&Z===s6)return Z;if(l6.has(Z))return Z;if(f($,"name")==="NativeVaultActivationError"&&f($,"code")==="no-read-grant"){let X=f($,"host"),G=f($,"approvedName");if((X==="opencode"||X==="pi")&&typeof G==="string"){let Q=new z0("no-read-grant",X,G).message;if(Z===Q)return Q}}if(Z.startsWith("Unknown setup argument: "))return Z;if(f($,"name")==="HostNotEnrolledError"&&n6.some((X)=>X.test(Z)))return Z;if(f($,"code")==="ERR_PRIVATE_FILES_UNAVAILABLE")return t9;let J=f($,"status");if(typeof J==="number"&&Number.isInteger(J)&&J>=100&&J<=599&&Z===`OAuth metadata read failed: ${J}`)return Z;let z=z5(f($,"activeHosts"));if(z){let X=new P$(z).message;if(Z===X)return X}}catch{}return}function G4($){try{if(!j0($))return;let Z=S$(u6($),_$.length);if(Z===void 0)return;let J=[];for(let z of Z){if(!j0(z))return;let X=_$.find((Q)=>Q===f(z,"host")),G=f(z,"outcome");if(X===void 0||!p6.has(G))return;J.push({host:X,outcome:G})}return J}catch{return}}function X5($,Z=[]){try{let J=new Set,z=S$(Z,r6);if(z===void 0)return;for(let G of z){if(typeof G!=="string")return;if(G!=="")J.add(G)}if(!j0($))return;let X=Reflect.ownKeys($);if(X.length>t6)return;for(let G of X){if(typeof G!=="string"||!h6(G))continue;let Q=Object.getOwnPropertyDescriptor($,G);if(Q===void 0)continue;if(!("value"in Q))return;if(Q.value===void 0||Q.value==="")continue;if(typeof Q.value!=="string")return;J.add(Q.value)}return[...J]}catch{return}}function G5($,Z){let J=R$.encode($);if(J.length<=Z)return $;let z=Math.max(0,Z);while(z>0&&((J[z]??0)&192)===128)z-=1;return X4.decode(J.subarray(0,z))}function Q5($,Z){let J=R$.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 X4.decode(J.subarray(z))}function W5($,Z,J){let z=$,X=!1;if($.length>O$){if(X=!0,J==="tail"){let H=$.indexOf(`
|
|
18
|
+
`,$.length-O$);z=H===-1?"":$.slice(H+1)}else{let H=$.lastIndexOf(`
|
|
19
|
+
`,O$);z=H===-1?"":$.slice(0,H)}if(z==="")return[Z5]}let G=Z.redactText(z).split(/\r?\n/);if(G.length>1&&G[G.length-1]==="")G.pop();if(J==="tail")G.reverse();let Q=[],W=e6;for(let H of G){let U=R$.encode(H).length+1;if(U<=W){Q.push(H),W-=U;continue}if(Q.length===0)Q.push(J==="tail"?Q5(H,W-1):G5(H,W-1));X=!0;break}if(J==="tail")Q.reverse();if(X)if(J==="tail")Q.unshift(n9);else Q.push(n9);return Q}function Q4($){let Z=$;for(let J=0;Z!==null&&J<8;J+=1){if(I$.isProxy(Z))break;let z=f(Z,"name");if(typeof z==="string")return z;Z=Object.getPrototypeOf(Z)}return"object"}function i9($,Z){let J={};if(Z===void 0)return J;try{if(!j0($))return J;let z=r9(Z);try{for(let X of["name","code","stage","reason"]){let G=X==="name"?Q4($):f($,X);if(typeof G==="string"&&d6[X].has(G)&&z.redactText(G)===G)J[X]=G}}finally{z.dispose()}}catch{return{}}return J}function H5($){if(!j0($))return;let Z=f($,"step"),J=f($,"exitCode"),z=f($,"signal"),X=f($,"stderrTail");if(typeof Z!=="string"||Z.length===0||!(J===null||typeof J==="number"&&Number.isInteger(J))||!(z===null||typeof z==="string")||typeof X!=="string")return;return{step:Z,exitCode:J,signal:z,stderrTail:X}}function W4($,Z){if($===null||typeof $!=="object"&&typeof $!=="function")return[`thrown ${typeof $}: ${String($)}`];if(I$.isProxy($))return["thrown proxy (not inspected)"];let J=[],z=Q4($),X=f($,"message");J.push(typeof X==="string"?`${z}: ${X}`:`${z} (no message)`);let G=f($,"code");if(typeof G==="string"||typeof G==="number")J.push(`code: ${G}`);let Q=f($,"stack");if(typeof Q==="string")J.push(Q);let W=f($,"cause");if(W!==void 0)if(Z>=$5)J.push("caused by: [not described]");else J.push("caused by:",...W4(W,Z+1));return J}function o9($,Z){let J=f($,Z);return typeof J==="string"&&J!==""?J:void 0}function Y5($){if(!j0($))return;let Z=o9($,"XDG_STATE_HOME"),J=o9($,"HOME"),z=Z&&s9(Z)?Z:A$(J&&s9(J)?J:f6(),".local","state");return A$(z,"cortexkit","anthropic-auth","diagnostics")}async function U5($,Z,J,z={}){let X=(G)=>({error:{name:"DiagnosticFileError",code:G}});try{let G=Y5($);if(G===void 0)return X("ERR_DIAGNOSTICS_DIRECTORY_UNAVAILABLE");if(!await y6(G,z)){await E6(G,{recursive:!0,mode:448});let H=await T6(G);if(!H.isDirectory())return X("ERR_DIAGNOSTICS_NOT_DIRECTORY");if(!await v6(G,()=>(H.mode&63)===0&&H.uid===process.getuid?.(),z))return X("ERR_DIAGNOSTICS_NOT_OWNER_ONLY")}let Q=A$(G,`${Z}-${Date.now()}-${process.pid}-${k6()}.log`);if(await x6(Q,J,z))return{path:Q};let W=await b6(Q,$3.O_WRONLY|$3.O_CREAT|$3.O_EXCL|($3.O_NOFOLLOW??0),384);try{await W.writeFile(J,"utf8")}finally{await W.close()}return{path:Q}}catch(G){return{error:G}}}async function q5($,Z,J,z,X,G,Q,W={}){let H,U=X5(J,z);if(U===void 0)H=[J5];else try{let C=r9(U);try{let{text:P,keep:D}=G();H=W5(P,C,D)}finally{C.dispose()}}catch{H=["[failure detail could not be recorded]"]}let q=c6[$],K=g6("error","cli",`${q} failed`,{stage:$,code:Z,...X}),B=await U5(J,$,`${[K,...H].join(`
|
|
19
20
|
`)}
|
|
20
|
-
`,W.ownership),F=B.path;if(F===void 0){let
|
|
21
|
-
`)}catch{}}return F===void 0?`${q} failed (${Z}). Details could not be saved to a private diagnostics file.`:`${q} failed (${Z}). Details were written to ${F}`}async function
|
|
21
|
+
`,W.ownership),F=B.path;if(F===void 0){let C={error:i9(Q,U),saveError:i9(B.error,U)};try{(W.stderr??((D)=>process.stderr.write(D)))(`CLI failure metadata: ${JSON.stringify(C)}
|
|
22
|
+
`)}catch{}}return F===void 0?`${q} failed (${Z}). Details could not be saved to a private diagnostics file.`:`${q} failed (${Z}). Details were written to ${F}`}async function _1($,Z,J,z=[],X={}){let G=k$(Z);if(G!==void 0)return G;let Q=H5(Z);return q5($,`${$}/unexpected-error`,J,z,{},()=>({text:[...Q?[`step: ${Q.step}`,`exitCode: ${Q.exitCode}`,`signal: ${Q.signal}`]:[],...W4(Z,0),...Q?[`stderrTail:
|
|
22
23
|
${Q.stderrTail}`]:[]].join(`
|
|
23
|
-
`),keep:"head"}),Z,X)}import{createProcessFence as
|
|
24
|
-
`)J.push("enter");else if(X==="\x03")J.push("escape");else if(X&&X>=" ")J.push("char");z+=1}return J}var
|
|
25
|
-
`),
|
|
26
|
-
`),q=!1;for(let K=0;K<U.length;K++){let B=U[K];if(z+=B,!q){if(q=B>="\uD800"&&B<="\uDBFF",q)continue}else q=!1;if(B===
|
|
27
|
-
`){if(G)z+=
|
|
28
|
-
`){if(X&&
|
|
29
|
-
`)}var
|
|
30
|
-
`),G=0,Q=$;for(let H of X){if(Q<=H.length)break;Q-=H.length+1,G++}for(G=Math.max(0,Math.min(X.length-1,G+J)),Q=Math.min(Q,X[G].length)+Z;Q<0&&G>0;)G--,Q+=X[G].length+1;for(;Q>X[G].length&&G<X.length-1;)Q-=X[G].length+1,G++;Q=Math.max(0,Math.min(X[G].length,Q));let W=0;for(let H=0;H<G;H++)W+=X[H].length+1;return W+Q}var
|
|
24
|
+
`),keep:"head"}),Z,X)}import{createProcessFence as xZ,NativePiAuthSlotError as yZ,openNativePiAuthSlot as gZ,publishNativeEmptyInit as vZ,readNativeEnrollmentMode as hZ,releaseNativeMigrationPreflight as mZ,requireNoSupervisedAuthContentSnapshot as wZ,runSetup as uZ}from"@cortexkit/anthropic-auth-core";import{AsyncLocalStorage as V5}from"node:async_hooks";var bQ=new V5;var H4=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});var z1="commonAuthPool";var x5=Object.freeze(["version","accounts",z1]);var vH=new q1;var _={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 m$($){let Z=$.toString(),J=[];for(let z=0;z<Z.length;){let X=Z[z];if(X==="\x1B"){let G=Z.slice(z,z+3),Q=G[1]==="["||G[1]==="O"?G[2]:void 0;if(Q&&"ABCD".includes(Q)){let H={A:"up",B:"down",C:"right",D:"left"}[Q];if(H)J.push(H);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(X==="\r"||X===`
|
|
25
|
+
`)J.push("enter");else if(X==="\x03")J.push("escape");else if(X&&X>=" ")J.push("char");z+=1}return J}var j4=`${String.fromCharCode(27)}\\[[0-9;]*m`,y5=new RegExp(j4,"g"),g5=new RegExp(`^${j4}`);function D4($){return $.replace(y5,"")}function m0($,Z){if(Z<=0)return"";if(D4($).length<=Z)return $;let J=Z>=3?"...":".".repeat(Z),z=Math.max(0,Z-J.length),X="",G=0,Q=0;while(G<$.length&&Q<z){if($[G]==="\x1B"){let W=$.slice(G).match(g5);if(W){X+=W[0],G+=W[0].length;continue}}X+=$[G],G+=1,Q+=1}return X.includes("\x1B[")?`${X}${_.reset}${J}`:X+J}function Q1($){return $.input.isTTY===!0}var v5=50;function h5($){if($==="red")return _.red;if($==="cyan")return _.cyan;return""}async function G3($,Z,J){if(!Q1($))throw Error("Interactive select requires a TTY terminal");if(Z.length===0)throw Error("No menu items provided");let{input:z,output:X,signals:G}=$,Q=0,W=null,H=!1,U=0,q=()=>{let K=X.columns??80,B=X.rows??24,F=U;if(J.clearScreen)X.write(_.clearScreen+_.moveTo(1,1));else if(F>0)X.write(_.up(F));let C=0,P=(V)=>{X.write(`${_.clearLine}${V}
|
|
26
|
+
`),C+=1},D=J.lines??[],I=1+(J.subtitle?3:0)+D.length+(D.length?1:0),R=Math.max(1,Math.min(Z.length,B-I-2-1)),x=Math.max(0,Math.min(Q-Math.floor(R/2),Math.max(0,Z.length-R))),v=Z.slice(x,x+R);if(P(`${_.dim}┌ ${_.reset}${m0(J.message,Math.max(1,K-4))}`),J.subtitle)P(`${_.dim}│${_.reset}`),P(`${_.cyan}◆${_.reset} ${m0(J.subtitle,Math.max(1,K-4))}`),P("");for(let V of D)P(`${_.cyan}│${_.reset} ${m0(V,Math.max(1,K-4))}`);if(D.length)P(`${_.cyan}│${_.reset}`);for(let V=0;V<v.length;V++){let M=v[V];if(!M)continue;let S=x+V===Q,g=h5(M.color),k=g?`${S?"":_.dim}${g}${M.label}${_.reset}`:S?M.label:`${_.dim}${M.label}${_.reset}`;if(M.hint)k+=` ${_.dim}${M.hint}${_.reset}`;k=m0(k,Math.max(1,K-8)),P(S?`${_.cyan}│${_.reset} ${_.green}●${_.reset} ${k}`:`${_.cyan}│${_.reset} ${_.dim}○${_.reset} ${k}`)}let Y=v.length<Z.length?` (${x+1}-${x+v.length}/${Z.length})`:"";P(`${_.cyan}│${_.reset} ${_.dim}${m0(`Up/Down to select | Enter: confirm | Esc: back${Y}`,Math.max(1,K-6))}${_.reset}`),P(`${_.cyan}└${_.reset}`);for(let V=C;V<F;V++)P("");U=C};return new Promise((K)=>{let B=z.isRaw??!1,F=()=>{if(H)return;if(H=!0,W)clearTimeout(W);z.removeListener("data",D);try{z.setRawMode(B),z.pause(),X.write(_.show)}catch{}G?.removeListener("SIGINT",P),G?.removeListener("SIGTERM",P)},C=(I)=>{F(),K(I)},P=()=>C(null),D=(I)=>{for(let R of m$(I)){if(H)break;if(W)clearTimeout(W),W=null;switch(R){case"up":Q=(Q-1+Z.length)%Z.length,q();break;case"down":Q=(Q+1)%Z.length,q();break;case"enter":C(Z[Q]?.value??null);break;case"escape":C(null);break;case"escape-start":W=setTimeout(()=>C(null),v5);break;default:break}}};G?.once("SIGINT",P),G?.once("SIGTERM",P);try{z.setRawMode(!0)}catch{F(),K(null);return}z.resume(),X.write(_.hide),q(),z.on("data",D)})}async function Q3($,Z,J=!1){if(!Q1($))return!1;return await G3($,J?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:Z})??!1}import{execFile as d5}from"node:child_process";import{promisify as l5}from"node:util";var a5=l5(d5),N4={async run($,Z,J={}){try{let z=J.env?{...process.env,...J.env}:process.env,{stdout:X,stderr:G}=await a5($,Z,{env:z,timeout:J.timeoutMs??15000,maxBuffer:10485760});return{exitCode:0,stdout:typeof X==="string"?X:String(X),stderr:typeof G==="string"?G:String(G)}}catch(z){let X=z;return{exitCode:typeof X?.code==="number"?X.code:1,signal:typeof X?.signal==="string"?X.signal:null,...typeof X?.syscall==="string"&&(X.syscall==="spawn"||X.syscall.startsWith("spawn "))?{spawnError:!0}:{},stdout:typeof X?.stdout==="string"?X.stdout:X?.stdout!=null?String(X.stdout):"",stderr:typeof X?.stderr==="string"?X.stderr:X?.stderr!=null?String(X.stderr):String(X?.message??z)}}}};import{styleText as K3}from"node:util";import{stdout as YZ,stdin as UZ}from"node:process";import qZ from"node:readline";var L4=(()=>{let $=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(Z)=>{let J=0;$.lastIndex=0;while($.test(Z))J+=1;return Z.length-J}})(),C4=($)=>{return $===12288||$>=65281&&$<=65376||$>=65504&&$<=65510},P4=($)=>{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 s5=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,n5=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,O4=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,i5=/\t{1,1000}/y,A4=/[\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,o5=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,r5=/\p{M}+/gu,t5={limit:1/0,ellipsis:""},_4=($,Z={},J={})=>{let z=Z.limit??1/0,X=Z.ellipsis??"",G=Z?.ellipsisWidth??(X?_4(X,t5,J).width:0),Q=0,W=J.controlWidth??0,H=J.tabWidth??8,U=J.emojiWidth??2,q=2,K=J.regularWidth??1,B=J.wideWidth??2,F=[[o5,K],[s5,0],[n5,W],[i5,H],[A4,U],[O4,B]],C=0,P=0,D=$.length,I=0,R=!1,x=D,v=Math.max(0,z-G),Y=0,V=0,M=0,S=0;$:while(!0){if(V>Y||P>=D&&P>C){let g=$.slice(Y,V)||$.slice(C,P);I=0;for(let k of g.replaceAll(r5,"")){let h=k.codePointAt(0)||0;if(C4(h))S=2;else if(P4(h))S=B;else S=K;if(M+S>v)x=Math.min(x,Math.max(Y,C)+I);if(M+S>z){R=!0;break $}I+=k.length,M+=S}Y=V=0}if(P>=D)break $;for(let g=0,k=F.length;g<k;g++){let[h,Z0]=F[g];if(h.lastIndex=P,h.test($)){if(I=h===O4?L4($.slice(P,h.lastIndex)):h===A4?1:h.lastIndex-P,S=I*Z0,M+S>v)x=Math.min(x,P+Math.floor((v-M)/Z0));if(M+S>z){R=!0;break $}M+=S,Y=C,V=P,P=C=h.lastIndex;continue $}}P+=1}return{width:R?v:M,index:R?x:D,truncated:R,ellipsed:R&&z>=G}},I4=_4;var e5={limit:1/0,ellipsis:"",ellipsisWidth:0},$Z=($,Z={})=>{return I4($,e5,Z).width},q0=$Z;var W3="\x1B",E4="",ZZ=39,u$="\x07",b4="[",JZ="]",f4="m",c$=`${JZ}8;;`,R4=new RegExp(`(?:\\${b4}(?<code>\\d+)m|\\${c$}(?<uri>.*)${u$})`,"y"),S4=($)=>{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},k4=($)=>`${W3}${b4}${$}${f4}`,T4=($)=>`${W3}${c$}${$}${u$}`,w$=($,Z,J)=>{let z=Z[Symbol.iterator](),X=!1,G=!1,Q=$.at(-1),W=Q===void 0?0:q0(Q),H=z.next(),U=z.next(),q=0;while(!H.done){let K=H.value,B=q0(K);if(W+B<=J)$[$.length-1]+=K;else $.push(K),W=0;if(K===W3||K===E4)X=!0,G=Z.startsWith(c$,q+1);if(X){if(G){if(K===u$)X=!1,G=!1}else if(K===f4)X=!1}else if(W+=B,W===J&&!U.done)$.push(""),W=0;H=U,U=z.next(),q+=K.length}if(Q=$.at(-1),!W&&Q!==void 0&&Q.length&&$.length>1)$[$.length-2]+=$.pop()},zZ=($)=>{let Z=$.split(" "),J=Z.length;while(J){if(q0(Z[J-1]))break;J--}if(J===Z.length)return $;return Z.slice(0,J).join(" ")+Z.slice(J).join("")},XZ=($,Z,J={})=>{if(J.trim!==!1&&$.trim()==="")return"";let z="",X,G,Q=$.split(" "),W=[""],H=0;for(let K=0;K<Q.length;K++){let B=Q[K];if(J.trim!==!1){let C=W.at(-1)??"",P=C.trimStart();if(C.length!==P.length)W[W.length-1]=P,H=q0(P)}if(K!==0){if(H>=Z&&(J.wordWrap===!1||J.trim===!1))W.push(""),H=0;if(H||J.trim===!1)W[W.length-1]+=" ",H++}let F=q0(B);if(J.hard&&F>Z){let C=Z-H,P=1+Math.floor((F-C-1)/Z);if(Math.floor((F-1)/Z)<P)W.push("");w$(W,B,Z),H=q0(W.at(-1)??"");continue}if(H+F>Z&&H&&F){if(J.wordWrap===!1&&H<Z){w$(W,B,Z),H=q0(W.at(-1)??"");continue}W.push(""),H=0}if(H+F>Z&&J.wordWrap===!1){w$(W,B,Z),H=q0(W.at(-1)??"");continue}W[W.length-1]+=B,H+=F}if(J.trim!==!1)W=W.map((K)=>zZ(K));let U=W.join(`
|
|
27
|
+
`),q=!1;for(let K=0;K<U.length;K++){let B=U[K];if(z+=B,!q){if(q=B>="\uD800"&&B<="\uDBFF",q)continue}else q=!1;if(B===W3||B===E4){R4.lastIndex=K+1;let C=R4.exec(U)?.groups;if(C?.code!==void 0){let P=Number.parseFloat(C.code);X=P===ZZ?void 0:P}else if(C?.uri!==void 0)G=C.uri.length===0?void 0:C.uri}if(U[K+1]===`
|
|
28
|
+
`){if(G)z+=T4("");let F=X?S4(X):void 0;if(X&&F)z+=k4(F)}else if(B===`
|
|
29
|
+
`){if(X&&S4(X))z+=k4(X);if(G)z+=T4(G)}}return z},GZ=/\r?\n/;function H3($,Z,J){return String($).normalize().split(GZ).map((z)=>XZ(z,Z,J)).join(`
|
|
30
|
+
`)}var $0=v4(d$(),1);function a$($,Z,J){if(!J.some((Q)=>!Q.disabled))return $;let z=$+Z,X=Math.max(J.length-1,0),G=z<0?X:z>X?0:z;return J[G]?.disabled?a$(G,Z<0?-1:1,J):G}function Y3($,Z,J,z){let X=z.split(`
|
|
31
|
+
`),G=0,Q=$;for(let H of X){if(Q<=H.length)break;Q-=H.length+1,G++}for(G=Math.max(0,Math.min(X.length-1,G+J)),Q=Math.min(Q,X[G].length)+Z;Q<0&&G>0;)G--,Q+=X[G].length+1;for(;Q>X[G].length&&G<X.length-1;)Q-=X[G].length+1,G++;Q=Math.max(0,Math.min(X[G].length,Q));let W=0;for(let H=0;H<G;H++)W+=X[H].length+1;return W+Q}var KZ=["up","down","left","right","space","enter","cancel"],VZ=["January","February","March","April","May","June","July","August","September","October","November","December"],X0={actions:new Set(KZ),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:[...VZ],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 FZ($){if($!==void 0)return $;if(X0.accessible!==void 0)return X0.accessible;let Z=process.env.ACCESSIBLE;return Z!==void 0&&Z!==""&&Z!=="0"&&Z!=="false"}function h4($,Z){if(typeof $=="string")return X0.aliases.get($)===Z;for(let J of $)if(J!==void 0&&h4(J,Z))return!0;return!1}function BZ($,Z){if($===Z)return;let J=$.split(`
|
|
31
32
|
`),z=Z.split(`
|
|
32
|
-
`),X=Math.max(J.length,z.length),G=[];for(let Q=0;Q<X;Q++)J[Q]!==z[Q]&&G.push(Q);return{lines:G,numLinesBefore:J.length,numLinesAfter:z.length,numLines:X}}var
|
|
33
|
-
`),
|
|
34
|
-
`).length-1;this.output.write(
|
|
35
|
-
`);this.output.write(Q[G]),this._prevFrame=$,this.output.write(
|
|
33
|
+
`),X=Math.max(J.length,z.length),G=[];for(let Q=0;Q<X;Q++)J[Q]!==z[Q]&&G.push(Q);return{lines:G,numLinesBefore:J.length,numLinesAfter:z.length,numLines:X}}var wU=globalThis.process.platform.startsWith("win"),V3=Symbol("clack:cancel");function F3($){return $===V3}function U3($,Z){let J=$;J.isTTY&&J.setRawMode(Z)}var m4=($)=>("rows"in $)&&typeof $.rows=="number"?$.rows:20;function w4($,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 W1{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return FZ(this.opts.accessible)}constructor($,Z=!0){let{input:J=UZ,output:z=YZ,render:X,signal:G,...Q}=$;this.opts=Q,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=X.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 X of J)X.cb(...Z),X.once&&z.push(()=>J.splice(J.indexOf(X),1));for(let X of z)X()}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(V3);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=qZ.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),U3(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write($0.cursor.show),this.output.off("resize",this.render),U3(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write($0.cursor.show),this.output.off("resize",this.render),U3(this.input,!1),$(V3)})})}_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&&X0.aliases.has(Z.name)&&this.emit("cursor",X0.aliases.get(Z.name)),X0.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=w4(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")}h4([$,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(`
|
|
34
|
+
`),U3(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let $=H3(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
35
|
+
`).length-1;this.output.write($0.cursor.move(-999,$*-1))}render(){let $=H3(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if($!==this._prevFrame){if(this.state==="initial")this.output.write($0.cursor.hide);else{let Z=BZ(this._prevFrame,$),J=m4(this.output);if(this.restoreCursor(),Z){let z=Math.max(0,Z.numLinesAfter-J),X=Math.max(0,Z.numLinesBefore-J),G=Z.lines.find((Q)=>Q>=z);if(G===void 0){this._prevFrame=$;return}if(Z.lines.length===1){this.output.write($0.cursor.move(0,G-X)),this.output.write($0.erase.lines(1));let Q=$.split(`
|
|
36
|
+
`);this.output.write(Q[G]),this._prevFrame=$,this.output.write($0.cursor.move(0,Q.length-G-1));return}else if(Z.lines.length>1){if(z<X)G=z;else{let W=G-X;W>0&&this.output.write($0.cursor.move(0,W))}this.output.write($0.erase.down());let Q=$.split(`
|
|
36
37
|
`).slice(G);this.output.write(Q.join(`
|
|
37
|
-
`)),this._prevFrame=$;return}}this.output.write(o.erase.down())}this.output.write($),this.state==="initial"&&(this.state="active"),this._prevFrame=$}}}function _5($,Z){if($===void 0||Z.length===0)return 0;let J=Z.findIndex((z)=>z.value===$);return J!==-1?J:0}function I5($,Z){return(Z.label??String(Z.value)).toLowerCase().includes($.toLowerCase())}function A5($,Z){if(Z)return $?Z:Z[0]}var R5=class extends e0{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#z="";#J;#X;#H;#G;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return o1(["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}${o1("inverse",J)}${z}`}get options(){return typeof this.#X=="function"?this.#X():this.#X}constructor(Z){super(Z),this.#X=Z.options,this.#H=Z.placeholder,this.#G=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??I5;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 X of z){let G=J.findIndex((Q)=>Q.value===X);G!==-1&&(this.toggleSelected(X),this.#$=G)}this.focusedValue=this.options[this.#$]?.value,this.on("key",(X,G)=>this.#Z(X,G)),this.on("userInput",(X)=>this.#Y(X))}_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",X=J.name==="down",G=J.name==="return",Q=this.userInput===""||this.userInput==="\t",W=this.#H,H=this.options,U=W!==void 0&&W!==""&&H.some((q)=>!q.disabled&&(this.#J?this.#J(W,q):!0));if(J.name==="tab"&&Q&&U){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(W,!0),this.isNavigating=!1;return}if(J.name==="tab"&&this.#G&&!this.multiple&&this.focusedValue!==void 0){let q=String(this.focusedValue);this._clearUserInput(),this._setUserInput(q,!0),this.isNavigating=!1;return}z||X?(this.#$=R2(this.#$,z?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):G?this.value=A5(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(Z){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(Z)?this.selectedValues=this.selectedValues.filter((J)=>J!==Z):this.selectedValues=[...this.selectedValues,Z]:this.selectedValues=[Z])}#Y(Z){if(Z!==this.#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=_5(this.focusedValue,this.filteredOptions);this.#$=R2(z,0,this.filteredOptions);let X=this.filteredOptions[this.#$];X&&!X.disabled?this.focusedValue=X.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};var S5={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function z4($){return[...$].map((Z)=>S5[Z])}function b5($){let Z=new Intl.DateTimeFormat($,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),J=[],z="/";for(let X of Z)X.type==="literal"?z=X.value.trim()||X.value:(X.type==="year"||X.type==="month"||X.type==="day")&&J.push({type:X.type,len:X.type==="year"?4:2});return{segments:J,separator:z}}function A2($){return Number.parseInt(($||"0").replace(/_/g,"0"),10)||0}function r1($){return{year:A2($.year),month:A2($.month),day:A2($.day)}}function S2($,Z){return new Date($||2001,Z||1,0).getDate()}function Y4($){let{year:Z,month:J,day:z}=r1($);if(!Z||Z<0||Z>9999||!J||J<1||J>12||!z||z<1)return;let X=new Date(Date.UTC(Z,J-1,z));if(!(X.getUTCFullYear()!==Z||X.getUTCMonth()!==J-1||X.getUTCDate()!==z))return{year:Z,month:J,day:z}}function X4($){let Z=Y4($);return Z?new Date(Date.UTC(Z.year,Z.month-1,Z.day)):void 0}function k5($,Z,J,z){let X=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:X?.year??1,max:G?.year??9999}:$==="month"?{min:X&&Z.year===X.year?X.month:1,max:G&&Z.year===G.year?G.month:12}:{min:X&&Z.year===X.year&&Z.month===X.month?X.day:1,max:G&&Z.year===G.year&&Z.month===G.month?G.day:S2(Z.year,Z.month)}}class U4 extends e0{#$;#z;#J;#X;#H;#G={segmentIndex:0,positionInSegment:0};#Z=!0;#Y=null;inlineError="";get segmentCursor(){return{...this.#G}}get segmentValues(){return{...this.#J}}get segments(){return this.#$}get separator(){return this.#z}get formattedValue(){return this.#K(this.#J)}#K($){return this.#$.map((Z)=>$[Z.type]).join(this.#z)}#W(){this._setUserInput(this.#K(this.#J)),this._setValue(X4(this.#J)??void 0)}constructor($){let Z=$.format?{segments:z4($.format),separator:$.separator??"/"}:b5($.locale),J=$.separator??Z.separator,z=$.format?z4($.format):Z.segments,X=$.initialValue??$.defaultValue,G=X?{year:String(X.getUTCFullYear()).padStart(4,"0"),month:String(X.getUTCMonth()+1).padStart(2,"0"),day:String(X.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},Q=z.map((W)=>G[W.type]).join(J);super({...$,initialUserInput:Q},!1),this.#$=z,this.#z=J,this.#J=G,this.#X=$.minDate,this.#H=$.maxDate,this.#W(),this.on("cursor",(W)=>this.#j(W)),this.on("key",(W,H)=>this.#F(W,H)),this.on("finalize",()=>this.#q($))}#Q(){let $=Math.max(0,Math.min(this.#G.segmentIndex,this.#$.length-1)),Z=this.#$[$];if(Z)return this.#G.positionInSegment=Math.max(0,Math.min(this.#G.positionInSegment,Z.len-1)),{segment:Z,index:$}}#U($){this.inlineError="",this.#Y=null;let Z=this.#Q();Z&&(this.#G.segmentIndex=Math.max(0,Math.min(this.#$.length-1,Z.index+$)),this.#G.positionInSegment=0,this.#Z=!0)}#M($){let Z=this.#Q();if(!Z)return;let{segment:J}=Z,z=this.#J[J.type],X=!z||z.replace(/_/g,"")==="",G=Number.parseInt((z||"0").replace(/_/g,"0"),10)||0,Q=k5(J.type,r1(this.#J),this.#X,this.#H),W;X?W=$===1?Q.min:Q.max:W=Math.max(Math.min(Q.max,G+$),Q.min),this.#J={...this.#J,[J.type]:W.toString().padStart(J.len,"0")},this.#Z=!0,this.#Y=null,this.#W()}#j($){if($)switch($){case"right":return this.#U(1);case"left":return this.#U(-1);case"up":return this.#M(1);case"down":return this.#M(-1)}}#F($,Z){if(Z?.name==="backspace"||Z?.sequence===""||Z?.sequence==="\b"||$===""||$==="\b"){this.inlineError="";let J=this.#Q();if(!J)return;if(!this.#J[J.segment.type].replace(/_/g,"")){this.#U(-1);return}this.#J[J.segment.type]="_".repeat(J.segment.len),this.#Z=!0,this.#G.positionInSegment=0,this.#W();return}if(Z?.name==="tab"){this.inlineError="";let J=this.#Q();if(!J)return;let z=Z.shift?-1:1,X=J.index+z;X>=0&&X<this.#$.length&&(this.#G.segmentIndex=X,this.#G.positionInSegment=0,this.#Z=!0);return}if($&&/^[0-9]$/.test($)){let J=this.#Q();if(!J)return;let{segment:z}=J,X=!this.#J[z.type].replace(/_/g,"");if(this.#Z&&this.#Y!==null&&!X){let B=this.#Y+$,F={...this.#J,[z.type]:B},P=this.#V(F,z);if(P){this.inlineError=P,this.#Y=null,this.#Z=!1;return}this.inlineError="",this.#J[z.type]=B,this.#Y=null,this.#Z=!1,this.#W(),J.index<this.#$.length-1&&(this.#G.segmentIndex=J.index+1,this.#G.positionInSegment=0,this.#Z=!0);return}this.#Z&&!X&&(this.#J[z.type]="_".repeat(z.len),this.#G.positionInSegment=0),this.#Z=!1,this.#Y=null;let G=this.#J[z.type],Q=G.indexOf("_"),W=Q>=0?Q:Math.min(this.#G.positionInSegment,z.len-1);if(W<0||W>=z.len)return;let H=G.slice(0,W)+$+G.slice(W+1),U=!1;if(W===0&&G==="__"&&(z.type==="month"||z.type==="day")){let B=Number.parseInt($,10);H=`0${$}`,U=B<=(z.type==="month"?1:2)}if(z.type==="year"&&(H=(G.replace(/_/g,"")+$).padStart(z.len,"_")),!H.includes("_")){let B={...this.#J,[z.type]:H},F=this.#V(B,z);if(F){this.inlineError=F;return}}this.inlineError="",this.#J[z.type]=H;let q=H.includes("_")?void 0:Y4(this.#J);if(q){let{year:B,month:F}=q,P=S2(B,F);this.#J={year:String(Math.max(0,Math.min(9999,B))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,F))).padStart(2,"0"),day:String(Math.max(1,Math.min(P,q.day))).padStart(2,"0")}}this.#W();let K=H.indexOf("_");U?(this.#Z=!0,this.#Y=$):K>=0?this.#G.positionInSegment=K:Q>=0&&J.index<this.#$.length-1?(this.#G.segmentIndex=J.index+1,this.#G.positionInSegment=0,this.#Z=!0):this.#G.positionInSegment=Math.min(W+1,z.len-1)}}#V($,Z){let{month:J,day:z}=r1($);if(Z.type==="month"&&(J<0||J>12))return Z0.date.messages.invalidMonth;if(Z.type==="day"&&(z<0||z>31))return Z0.date.messages.invalidDay(31,"any month")}#q($){let{year:Z,month:J,day:z}=r1(this.#J);if(Z&&J&&z){let X=S2(Z,J);this.#J={...this.#J,day:String(Math.min(z,X)).padStart(2,"0")}}this.value=X4(this.#J)??$.defaultValue??void 0}}var T5=class extends e0{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((X)=>z.includes(X.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((X)=>z.findIndex((G)=>G.value===X)===-1):this.value=[...this.value,...z.map((X)=>X.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,X])=>[{value:z,group:!0,label:z},...X.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 X=this.options[this.cursor]?.group===!0;!this.#$&&X&&(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 X=this.options[this.cursor]?.group===!0;!this.#$&&X&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},E5=new Set(["up","down","left","right"]);class q4 extends e0{#$=!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===`
|
|
38
|
+
`)),this._prevFrame=$;return}}this.output.write($0.erase.down())}this.output.write($),this.state==="initial"&&(this.state="active"),this._prevFrame=$}}}function MZ($,Z){if($===void 0||Z.length===0)return 0;let J=Z.findIndex((z)=>z.value===$);return J!==-1?J:0}function jZ($,Z){return(Z.label??String(Z.value)).toLowerCase().includes($.toLowerCase())}function DZ($,Z){if(Z)return $?Z:Z[0]}var NZ=class extends W1{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Z="";#J;#W;#G;#Q;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return K3(["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}${K3("inverse",J)}${z}`}get options(){return typeof this.#W=="function"?this.#W():this.#W}constructor(Z){super(Z),this.#W=Z.options,this.#G=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??jZ;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 X of z){let G=J.findIndex((Q)=>Q.value===X);G!==-1&&(this.toggleSelected(X),this.#$=G)}this.focusedValue=this.options[this.#$]?.value,this.on("key",(X,G)=>this.#z(X,G)),this.on("userInput",(X)=>this.#X(X))}_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",X=J.name==="down",G=J.name==="return",Q=this.userInput===""||this.userInput==="\t",W=this.#G,H=this.options,U=W!==void 0&&W!==""&&H.some((q)=>!q.disabled&&(this.#J?this.#J(W,q):!0));if(J.name==="tab"&&Q&&U){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 q=String(this.focusedValue);this._clearUserInput(),this._setUserInput(q,!0),this.isNavigating=!1;return}z||X?(this.#$=a$(this.#$,z?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):G?this.value=DZ(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])}#X(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=MZ(this.focusedValue,this.filteredOptions);this.#$=a$(z,0,this.filteredOptions);let X=this.filteredOptions[this.#$];X&&!X.disabled?this.focusedValue=X.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};var LZ={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function y4($){return[...$].map((Z)=>LZ[Z])}function CZ($){let Z=new Intl.DateTimeFormat($,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),J=[],z="/";for(let X of Z)X.type==="literal"?z=X.value.trim()||X.value:(X.type==="year"||X.type==="month"||X.type==="day")&&J.push({type:X.type,len:X.type==="year"?4:2});return{segments:J,separator:z}}function l$($){return Number.parseInt(($||"0").replace(/_/g,"0"),10)||0}function q3($){return{year:l$($.year),month:l$($.month),day:l$($.day)}}function s$($,Z){return new Date($||2001,Z||1,0).getDate()}function u4($){let{year:Z,month:J,day:z}=q3($);if(!Z||Z<0||Z>9999||!J||J<1||J>12||!z||z<1)return;let X=new Date(Date.UTC(Z,J-1,z));if(!(X.getUTCFullYear()!==Z||X.getUTCMonth()!==J-1||X.getUTCDate()!==z))return{year:Z,month:J,day:z}}function g4($){let Z=u4($);return Z?new Date(Date.UTC(Z.year,Z.month-1,Z.day)):void 0}function PZ($,Z,J,z){let X=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:X?.year??1,max:G?.year??9999}:$==="month"?{min:X&&Z.year===X.year?X.month:1,max:G&&Z.year===G.year?G.month:12}:{min:X&&Z.year===X.year&&Z.month===X.month?X.day:1,max:G&&Z.year===G.year&&Z.month===G.month?G.day:s$(Z.year,Z.month)}}class c4 extends W1{#$;#Z;#J;#W;#G;#Q={segmentIndex:0,positionInSegment:0};#z=!0;#X=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.#M(this.#J)}#M($){return this.#$.map((Z)=>$[Z.type]).join(this.#Z)}#H(){this._setUserInput(this.#M(this.#J)),this._setValue(g4(this.#J)??void 0)}constructor($){let Z=$.format?{segments:y4($.format),separator:$.separator??"/"}:CZ($.locale),J=$.separator??Z.separator,z=$.format?y4($.format):Z.segments,X=$.initialValue??$.defaultValue,G=X?{year:String(X.getUTCFullYear()).padStart(4,"0"),month:String(X.getUTCMonth()+1).padStart(2,"0"),day:String(X.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},Q=z.map((W)=>G[W.type]).join(J);super({...$,initialUserInput:Q},!1),this.#$=z,this.#Z=J,this.#J=G,this.#W=$.minDate,this.#G=$.maxDate,this.#H(),this.on("cursor",(W)=>this.#U(W)),this.on("key",(W,H)=>this.#j(W,H)),this.on("finalize",()=>this.#D($))}#Y(){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:$}}#q($){this.inlineError="",this.#X=null;let Z=this.#Y();Z&&(this.#Q.segmentIndex=Math.max(0,Math.min(this.#$.length-1,Z.index+$)),this.#Q.positionInSegment=0,this.#z=!0)}#F($){let Z=this.#Y();if(!Z)return;let{segment:J}=Z,z=this.#J[J.type],X=!z||z.replace(/_/g,"")==="",G=Number.parseInt((z||"0").replace(/_/g,"0"),10)||0,Q=PZ(J.type,q3(this.#J),this.#W,this.#G),W;X?W=$===1?Q.min:Q.max:W=Math.max(Math.min(Q.max,G+$),Q.min),this.#J={...this.#J,[J.type]:W.toString().padStart(J.len,"0")},this.#z=!0,this.#X=null,this.#H()}#U($){if($)switch($){case"right":return this.#q(1);case"left":return this.#q(-1);case"up":return this.#F(1);case"down":return this.#F(-1)}}#j($,Z){if(Z?.name==="backspace"||Z?.sequence===""||Z?.sequence==="\b"||$===""||$==="\b"){this.inlineError="";let J=this.#Y();if(!J)return;if(!this.#J[J.segment.type].replace(/_/g,"")){this.#q(-1);return}this.#J[J.segment.type]="_".repeat(J.segment.len),this.#z=!0,this.#Q.positionInSegment=0,this.#H();return}if(Z?.name==="tab"){this.inlineError="";let J=this.#Y();if(!J)return;let z=Z.shift?-1:1,X=J.index+z;X>=0&&X<this.#$.length&&(this.#Q.segmentIndex=X,this.#Q.positionInSegment=0,this.#z=!0);return}if($&&/^[0-9]$/.test($)){let J=this.#Y();if(!J)return;let{segment:z}=J,X=!this.#J[z.type].replace(/_/g,"");if(this.#z&&this.#X!==null&&!X){let B=this.#X+$,F={...this.#J,[z.type]:B},C=this.#B(F,z);if(C){this.inlineError=C,this.#X=null,this.#z=!1;return}this.inlineError="",this.#J[z.type]=B,this.#X=null,this.#z=!1,this.#H(),J.index<this.#$.length-1&&(this.#Q.segmentIndex=J.index+1,this.#Q.positionInSegment=0,this.#z=!0);return}this.#z&&!X&&(this.#J[z.type]="_".repeat(z.len),this.#Q.positionInSegment=0),this.#z=!1,this.#X=null;let G=this.#J[z.type],Q=G.indexOf("_"),W=Q>=0?Q:Math.min(this.#Q.positionInSegment,z.len-1);if(W<0||W>=z.len)return;let H=G.slice(0,W)+$+G.slice(W+1),U=!1;if(W===0&&G==="__"&&(z.type==="month"||z.type==="day")){let B=Number.parseInt($,10);H=`0${$}`,U=B<=(z.type==="month"?1:2)}if(z.type==="year"&&(H=(G.replace(/_/g,"")+$).padStart(z.len,"_")),!H.includes("_")){let B={...this.#J,[z.type]:H},F=this.#B(B,z);if(F){this.inlineError=F;return}}this.inlineError="",this.#J[z.type]=H;let q=H.includes("_")?void 0:u4(this.#J);if(q){let{year:B,month:F}=q,C=s$(B,F);this.#J={year:String(Math.max(0,Math.min(9999,B))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,F))).padStart(2,"0"),day:String(Math.max(1,Math.min(C,q.day))).padStart(2,"0")}}this.#H();let K=H.indexOf("_");U?(this.#z=!0,this.#X=$):K>=0?this.#Q.positionInSegment=K:Q>=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)}}#B($,Z){let{month:J,day:z}=q3($);if(Z.type==="month"&&(J<0||J>12))return X0.date.messages.invalidMonth;if(Z.type==="day"&&(z<0||z>31))return X0.date.messages.invalidDay(31,"any month")}#D($){let{year:Z,month:J,day:z}=q3(this.#J);if(Z&&J&&z){let X=s$(Z,J);this.#J={...this.#J,day:String(Math.min(z,X)).padStart(2,"0")}}this.value=g4(this.#J)??$.defaultValue??void 0}}var OZ=class extends W1{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((X)=>z.includes(X.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((X)=>z.findIndex((G)=>G.value===X)===-1):this.value=[...this.value,...z.map((X)=>X.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,X])=>[{value:z,group:!0,label:z},...X.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 X=this.options[this.cursor]?.group===!0;!this.#$&&X&&(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 X=this.options[this.cursor]?.group===!0;!this.#$&&X&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},AZ=new Set(["up","down","left","right"]);class p4 extends W1{#$=!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===`
|
|
38
39
|
`?`${Z}█
|
|
39
|
-
${z}`:`${Z}${
|
|
40
|
+
${z}`:`${Z}${K3("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))}#W($){let Z=this.value??"";switch($){case"up":this._cursor=Y3(this._cursor,0,-1,Z);return;case"down":this._cursor=Y3(this._cursor,0,1,Z);return;case"left":this._cursor=Y3(this._cursor,-1,0,Z);return;case"right":this._cursor=Y3(this._cursor,1,0,Z);return}}_shouldSubmit($,Z){if(this.#Z)return this.focused==="submit"?!0:(this.#J(`
|
|
40
41
|
`),this._cursor++,!1);let J=this.#$;return this.#$=!0,J&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
|
|
41
42
|
`&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#J(`
|
|
42
|
-
`),this._cursor++,!1)}constructor($){let Z=$.initialUserInput??$.initialValue;super({...$,initialUserInput:Z},!1),Z!==void 0&&(this._cursor=Z.length),this.#
|
|
43
|
-
`:""}${
|
|
44
|
-
`,z=$.placeholder&&$.placeholder.length>0?E("inverse",$.placeholder[0])+E("dim",$.placeholder.slice(1)):E(["inverse","hidden"],"_"),X=this.userInput?this.userInputWithCursor:z,G=this.value??"";switch(this.state){case"validating":{let Q=Z?`${E("cyan",
|
|
43
|
+
`),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&&AZ.has(z.name)){this.#$=!1,this.#W(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 n$ extends W1{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}${K3("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 E,stripVTControlCharacters as eU}from"node:util";import G0 from"node:process";var l4=v4(d$(),1);function _Z(){if(G0.platform!=="win32")return G0.env.TERM!=="linux";return Boolean(G0.env.CI)||Boolean(G0.env.WT_SESSION)||Boolean(G0.env.TERMINUS_SUBLIME)||G0.env.ConEmuTask==="{cmd::Cmder}"||G0.env.TERM_PROGRAM==="Terminus-Sublime"||G0.env.TERM_PROGRAM==="vscode"||G0.env.TERM==="xterm-256color"||G0.env.TERM==="alacritty"||G0.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var IZ=_Z();var b=($,Z)=>IZ?$:Z,d4=b("◆","*"),RZ=b("■","x"),SZ=b("▲","x"),kZ=b("◇","o"),zq=b("┌","T"),w0=b("│","|"),i$=b("└","—"),Xq=b("┐","T"),Gq=b("┘","—"),Qq=b("●",">"),Wq=b("○"," "),Hq=b("◻","[•]"),Yq=b("◼","[+]"),Uq=b("◻","[ ]"),qq=b("▪","•"),Kq=b("─","-"),Vq=b("╮","+"),Fq=b("├","+"),Bq=b("╯","+"),Mq=b("╰","+"),jq=b("╭","+"),Dq=b("●","•"),Nq=b("◆","*"),Lq=b("▲","!"),Cq=b("■","x"),TZ=($)=>{switch($){case"initial":case"active":return E("cyan",d4);case"cancel":return E("red",RZ);case"error":return E("yellow",SZ);case"submit":return E("green",kZ);case"validating":return E("dim",d4)}};var Pq=[`${E("dim","↑/↓")} to navigate`,`${E("dim","Space:")} select`,`${E("dim","Enter:")} confirm`];var Oq={light:b("─","-"),heavy:b("━","="),block:b("█","#")};var Aq=[`${E("dim","↑/↓")} to navigate`,`${E("dim","Enter:")} confirm`];var _q=`${E("gray",w0)} `;var a4=($)=>new n$({validate:$.validate,placeholder:$.placeholder,defaultValue:$.defaultValue,initialValue:$.initialValue,output:$.output,signal:$.signal,input:$.input,render(){let Z=$?.withGuide??X0.withGuide,J=`${`${Z?`${E("gray",w0)}
|
|
44
|
+
`:""}${TZ(this.state)} `}${$.message}
|
|
45
|
+
`,z=$.placeholder&&$.placeholder.length>0?E("inverse",$.placeholder[0])+E("dim",$.placeholder.slice(1)):E(["inverse","hidden"],"_"),X=this.userInput?this.userInputWithCursor:z,G=this.value??"";switch(this.state){case"validating":{let Q=Z?`${E("cyan",w0)} `:"",W=Z?E("cyan",i$):"",H=E("dim",X),U=E("dim","Validating...");return`${J}${Q}${H}
|
|
45
46
|
${W} ${U}
|
|
46
|
-
`}case"error":{let Q=this.error?` ${E("yellow",this.error)}`:"",W=Z?`${E("yellow",
|
|
47
|
+
`}case"error":{let Q=this.error?` ${E("yellow",this.error)}`:"",W=Z?`${E("yellow",w0)} `:"",H=Z?E("yellow",i$):"";return`${J.trim()}
|
|
47
48
|
${W}${X}
|
|
48
49
|
${H}${Q}
|
|
49
|
-
`}case"submit":{let Q=G?`${Z?" ":""}${E("dim",G)}`:"",W=Z?E("gray",
|
|
50
|
-
${W}`:""}`}default:{let Q=Z?`${E("cyan",
|
|
50
|
+
`}case"submit":{let Q=G?`${Z?" ":""}${E("dim",G)}`:"",W=Z?E("gray",w0):"";return`${J}${W}${Q}`}case"cancel":{let Q=G?` ${E(["strikethrough","dim"],G)}`:"",W=Z?E("gray",w0):"";return`${J}${W}${Q}${G.trim()?`
|
|
51
|
+
${W}`:""}`}default:{let Q=Z?`${E("cyan",w0)} `:"",W=Z?E("cyan",i$):"";return`${J}${Q}${X}
|
|
51
52
|
${W}
|
|
52
|
-
`}}}}).prompt();import{authorize as
|
|
53
|
-
`),G=$.filter((Y)=>Y!=="--remove-pi-auth").map((Y)=>Y==="-y"?"--yes":Y),Q=G.includes("--login");if(Q&&G.includes("--claustrum"))return X("Local sign-in and vault setup are two separate choices. Use --login or --claustrum, not both."),1;if(Q&&G.includes("--opencode=2"))return X(
|
|
53
|
+
`}}}}).prompt();import{authorize as EZ,exchange as bZ,resolveClaudeCodeIdentity as fZ}from"@cortexkit/anthropic-auth-core";async function s4($,Z={authorize:EZ,exchange:bZ,resolveClaudeCodeIdentity:fZ,text:a4,isCancel:F3,print:console.log}){let J=await Z.authorize("max");Z.print(`Claude sign-in for ${$==="pi"?"Pi":"OpenCode"}`),Z.print(J.url);let z=await Z.text({message:"Paste the Claude callback URL or authorization code:"});if(Z.isCancel(z))throw Error("Claude sign-in cancelled");let X=await Z.exchange(z,J.verifier,J.redirectUri,J.state);if(X.type!=="success")throw Error("Claude sign-in failed");let G=await Z.resolveClaudeCodeIdentity(X.access,void 0,void 0);if(!G.accountUuid)throw Error("Claude sign-in did not establish an account UUID");return{accountIdentity:G.accountUuid,credential:{type:"oauth",access:X.access,refresh:X.refresh,expires:X.expires}}}var n4='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 D0($,Z){let J=$.get(Z);if(!J)throw Error("Missing setup plan");return J}async function t4($=[],Z={}){let J={...Z.env??process.env},z=Z.terminal??{input:process.stdin,output:process.stdout,signals:process},X=(Y)=>z.output.write(`${Y}
|
|
54
|
+
`),G=$.filter((Y)=>Y!=="--remove-pi-auth").map((Y)=>Y==="-y"?"--yes":Y),Q=G.includes("--login");if(Q&&G.includes("--claustrum"))return X("Local sign-in and vault setup are two separate choices. Use --login or --claustrum, not both."),1;if(Q&&G.includes("--opencode=2"))return X(B3),1;let W=Z.runner??N4,H=Z.fence??xZ(W,{platform:Z.platform}),U=Z.migrateLocal??c9,q=new Map,K=new Map,B=new Map,F=new Map,C=!1,P="setup-process-check",D=(Y)=>({env:J,fence:H,paths:B.get(Y),removePiAnthropicAuth:F.get(Y)??!1}),I=(Y)=>({...D(Y),runner:W});async function R(Y){if(!Y.hosts.includes("pi"))return;let V=D0(B,"pi");if((await P1("pi",V.hostAuthPath)).kind==="absent")return;{let k=await gZ({env:J,authPath:V.hostAuthPath}).inspect();if(k.slot==="placeholder"&&k.stash==="missing")throw new yZ("missing-stash");if(Y.mode==="claustrum"){if(k.slot==="placeholder")return}}if($.includes("--remove-pi-auth")){F.set("pi",!0);return}let S=Y.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 i(S);if(!await Q3(z,Y.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 i("Native account-pool setup cannot finish while the stored Pi OAuth token takes precedence.");F.set("pi",!0)}async function x(Y,V){let M=D0(K,Y);if(await hZ(Y,J)!==(V?"claustrum":M.priorMode)||await O1(Y,I(Y))!==M.fingerprint)throw new i("Setup inputs changed. Rerun setup with all hosts stopped.")}let v={packages:{opencode:i4,pi:o4},version:await r4(),displayName:"CortexKit Anthropic Auth",slashCommand:"/claude",vault:{connectionFile:U$(J.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE&&!J.OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE?"pi":"opencode",J),hosts:{opencode:{name:g0.opencode,paths:Y$("opencode",J)},pi:{name:g0.pi,paths:Y$("pi",J)}}},async beforeSignIn(Y,V){if(P=V.mode==="claustrum"?"setup-activation":"cli-setup",!C){wZ(J);for(let M of V.hosts)B.set(M,await M0(M,J));if(await y9([...B.values()]),V.mode==="claustrum"){let M=V.hosts.map((g)=>U$(g,J)),S=M[0];if(new Set(M).size!==1||!S)throw new i("Selected hosts use different vault connection files.");v.vault.connectionFile=S}if(V.mode==="local"&&Q&&V.hosts.includes("opencode")&&V.opencodeGeneration==="2")throw new i(B3);if(V.mode==="local"){await B$(V.hosts,J);for(let M of V.hosts)await h0(M,D(M))()}await R(V);for(let M of V.hosts)if(V.mode==="claustrum"){if(K.set(M,await(Z.vaultPreflight??l9)(M,{...I(M),inspectOpenCodeAuth:V.opencodeGeneration!=="2"})),D0(K,M).separateOpenCodeLogin)X(n4)}else q.set(M,await j$(M,D(M),M==="opencode"&&V.opencodeGeneration==="2"));C=!0}else if(V.mode==="claustrum")await x(Y,!1);else await J1(D0(q,Y),D(Y))},async signInLocal(Y){let V=D0(q,Y);if(!Q){if(V.generation2)X(B3);return}if(await J1(V,D(Y)),await U(Y,{...D(Y),login:Z.localLogin??s4,preflight:V.preflight,skipMigration:V.action==="skip",beforeCommit:()=>J1(V,D(Y))}),V.fingerprint=await e1(V,J),V.notice)X(F$)},async beforeRegister(Y,V){if(V==="local")await J1(D0(q,Y),D(Y));else await x(Y,!0),await(Z.vaultActivate??a9)(Y,I(Y),D0(K,Y)),D0(K,Y).fingerprint=await O1(Y,I(Y))},async migrate(Y,V){if(V.mode==="claustrum"){if(await x(Y,!0),Y===V.hosts.at(-1)&&K.get("opencode")?.separateOpenCodeLogin)X(n4);return}let M=D0(q,Y);if(await J1(M,D(Y)),Q)return;if(M.action==="migration")await U(Y,{...D(Y),preflight:M.preflight});else if(M.action==="empty-init")await vZ({paths:M.paths.paths,routingDestinationPath:M.paths.routingDestinationPath,env:J,processFence:h0(Y,D(Y))});else if(M.action==="skip"){if(await D$(M,D(Y)),M.notice)X(F$)}M.fingerprint=await e1(M,J)}};try{return await uZ(v,G,{...Z,env:J,terminal:z,runner:W,fence:H}),0}catch(Y){let M=v9(Y)??k$(Y)??await _1(P,Y,J);if(M)X(M);for(let{host:S,outcome:g}of G4(Y)??[]){if(g!=="enrolled")continue;let k=S==="opencode"?"OpenCode":"Pi";X(`${k} stays connected to the vault. In ${k}, run /claude → Accounts → Disconnect from the vault to undo it. Or run setup again to finish connecting.`)}return 1}finally{for(let Y of q.values())if(Y.preflight)mZ(Y.preflight)}}async function H1($){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Native account changes require offline setup without OPENCODE_AUTH_CONTENT");let Z=await eZ(),J=aZ({paths:Z,host:"opencode"});try{return await J.read(),await $(J)}finally{await J.close()}}async function M3(){if(await tZ("opencode",process.env)!=="local")throw Error("Disconnect from the vault first.")}function e4(){console.log(`Usage:
|
|
54
55
|
opencode-anthropic-auth setup [--yes] [--dry-run]
|
|
55
56
|
opencode-anthropic-auth login [label]
|
|
56
57
|
opencode-anthropic-auth api add [label]
|
|
@@ -60,9 +61,9 @@ ${W}
|
|
|
60
61
|
Setup --yes selects every found host, including Pi. Run setup without --yes to choose hosts.
|
|
61
62
|
Native credentials are managed by the offline setup migration.
|
|
62
63
|
Legacy import source:
|
|
63
|
-
${
|
|
64
|
+
${oZ()}`)}function o$($,Z){let J=$?.trim();if(!J)throw Error(`${Z} is required`);return J}async function N3($){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(),X;try{X=JSON.parse(z)}catch{throw Error(`Cloudflare API returned ${J.status}: ${z}`)}if(!J.ok||X.success===!1){let G=X.errors?.map((Q)=>Q.message).filter(Boolean).join("; ");throw Error(G||`Cloudflare API returned ${J.status}`)}return X.result}async function ZJ($,Z,J,z){return N3({token:$,method:"POST",path:`/accounts/${Z}/storage/kv/namespaces`,body:JSON.stringify({title:J}),fetchImpl:z})}async function JJ($){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([$J],{type:"application/javascript+module"}),"worker.js"),N3({token:$.token,method:"PUT",path:`/accounts/${$.accountId}/workers/scripts/${$.scriptName}`,body:J,fetchImpl:$.fetchImpl})}async function zJ($,Z,J,z){await N3({token:$,method:"POST",path:`/accounts/${Z}/workers/scripts/${J}/subdomain`,body:JSON.stringify({enabled:!0,previews_enabled:!1}),fetchImpl:z})}async function XJ($,Z,J){return N3({token:$,method:"GET",path:`/accounts/${Z}/workers/subdomain`,fetchImpl:J}).catch(()=>null)}async function GJ($={}){await H1((F)=>F.read());let Z=$.fetchImpl??fetch,J=$.prompt??D3,z=$.warn??((F)=>console.warn(F)),X=o$(process.env.CLOUDFLARE_API_TOKEN?.trim()||await J("Cloudflare API token: "),"Cloudflare API token");$.secrets?.push(X);let G=o$(process.env.CLOUDFLARE_ACCOUNT_ID||await J("Cloudflare account ID: "),"Cloudflare account ID"),Q=await J("Worker name [opencode-anthropic-relay]: ")||"opencode-anthropic-relay",W=`${Q}-state`,H=iZ();$.secrets?.push(H),console.log("Creating Cloudflare KV namespace...");let U=await ZJ(X,G,W,Z);console.log("Uploading relay Worker..."),await JJ({token:X,accountId:G,scriptName:Q,kvNamespaceId:U.id,relayToken:H,fetchImpl:Z}),await zJ(X,G,Q,Z).catch(async(F)=>{z(await _1("cli-relay-workers-dev",F,process.env,[X,H]))});let q=await XJ(X,G,Z),B=(q?.subdomain?`https://${Q}.${q.subdomain}.workers.dev`:"")||o$(await D3("Relay Worker URL: "),"Relay Worker URL");await H1((F)=>F.updateRelay({enabled:!0,url:B,token:H,fallbackToDirect:!0,transport:"http"})),console.log(`Relay enabled at ${B}`),console.log("Relay settings saved to the native account store.")}var j3=null;async function D3($){return j3??=dZ({input:cZ,output:pZ}),(await j3.question($)).trim()}function QJ(){j3?.close(),j3=null}async function WJ($,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??D3,z=Z.authorize??lZ,X=Z.exchange??sZ;await M3(),await H1(async(G)=>{let Q=await G.read(),W=$?.trim()||await J("Fallback account label (optional): "),H=await z("max");console.log(`
|
|
64
65
|
Open this URL in your browser and complete Claude sign-in:
|
|
65
66
|
`),console.log(`${H.url}
|
|
66
|
-
`);let U=await J("Paste the full callback URL or authorization code here: ");Z.secrets?.push(U);let q=await X(U,H.verifier,H.redirectUri,H.state);if(q.type==="failed")throw Error("Authentication failed");if(Z.secrets?.push(q.access,q.refresh),process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Local login cannot be verified while OPENCODE_AUTH_CONTENT is set");await
|
|
67
|
-
Saved native fallback account${W?` "${W}"`:""}.`)})}async function
|
|
68
|
-
Saved API fallback route${z?` "${z}"`:""} (${X}).`)}async function
|
|
67
|
+
`);let U=await J("Paste the full callback URL or authorization code here: ");Z.secrets?.push(U);let q=await X(U,H.verifier,H.redirectUri,H.state);if(q.type==="failed")throw Error("Authentication failed");if(Z.secrets?.push(q.access,q.refresh),process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Local login cannot be verified while OPENCODE_AUTH_CONTENT is set");await M3();let K=W&&W!=="main"?W:crypto.randomUUID(),B=Q.accounts.some((F)=>F.id===K&&F.source==="local");await G.loginOAuth({routeId:K,replace:B,label:W||void 0,credential:{access:q.access,refresh:q.refresh,expires:q.expires}}),console.log(`
|
|
68
|
+
Saved native fallback account${W?` "${W}"`:""}.`)})}async function HJ($,Z={}){await M3(),await H1((H)=>H.read());let J=Z.prompt??D3,z=$?.trim()||await J("API fallback label (optional): "),X=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(!rZ(X))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 H1(async(H)=>{await M3();let U=await H.read(),q=z&&z!=="main"?z:crypto.randomUUID(),K=U.accounts.find((B)=>B.id===q);if(K?.source==="vault")throw Error("Vault routes cannot be replaced with a local API key");await H.addApi({routeId:q,replace:Boolean(K),label:z||void 0,apiKey:G.trim(),baseURL:X,authHeader:W})}),console.log(`
|
|
69
|
+
Saved API fallback route${z?` "${z}"`:""} (${X}).`)}async function YJ(){await H1(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 X=z.label||z.id,G=z.enabled?"enabled":"disabled";if(z.type==="api"){console.log(`${J+1}. ${X} (${G}) — API route ${z.baseURL}`);continue}let Q=z.quota?.five_hour?.remainingPercent,W=z.quota?.seven_day?.remainingPercent,H=Q===void 0&&W===void 0?"quota unknown":`5h ${Q??"?"}%, 1w ${W??"?"}% remaining`;console.log(`${J+1}. ${X} (${G}) — ${H}${z.state?` — ${nZ(z)}`:""}`)}})}async function UJ($){let[Z,J,z]=process.argv.slice(2);if(!Z||Z==="help"||Z==="--help"||Z==="-h"){e4();return}if(Z==="setup"){$.stage="cli-setup";let X=await t4(process.argv.slice(3));if(X!==0)process.exitCode=X;return}if(Z==="login"){$.stage="cli-login",await WJ(J,{secrets:$.secrets});return}if(Z==="api"&&J==="add"){$.stage="cli-api-add",await HJ(z,{secrets:$.secrets});return}if(Z==="list"){$.stage="cli-list",await YJ();return}if(Z==="relay"&&J==="setup"){$.stage="cli-relay-setup",await GJ({secrets:$.secrets});return}e4(),process.exitCode=1}if(_3.main==_3.module){let $={stage:"cli-command",secrets:[]};try{await UJ($)}catch(Z){console.error(await _1($.stage,Z,process.env,$.secrets)),process.exitCode=1}finally{QJ()}}export{t4 as runSetupCommand,GJ as relaySetup,WJ as login,HJ as addApiRoute};
|