@cortexkit/opencode-anthropic-auth 2.4.3 → 2.4.5
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/cache-diagnostics.d.ts +1 -1
- package/dist/cli.js +44 -44
- package/dist/fable-fallback.d.ts +55 -1
- package/dist/index-61bbefpq.js +2 -0
- package/dist/index-j2cv839v.js +2 -0
- package/dist/index-y35yxsnq.js +45 -0
- package/dist/index.js +1 -1
- package/dist/plugin-test-handles.d.ts +2 -0
- package/dist/sidebar-state.js +1 -1
- package/dist/transform.d.ts +9 -0
- package/dist/v2/adapter.d.ts +8 -1
- package/dist/v2/cachekeep-store.d.ts +36 -0
- package/dist/v2/cachekeep.d.ts +4 -0
- package/dist/v2/server.js +11 -11
- package/dist/v2/sidebar.d.ts +1 -1
- package/dist/v2/source.d.ts +9 -2
- package/dist/v2/tui.js +1 -1
- package/package.json +2 -2
- package/src/sidebar-state.ts +2 -2
- package/src/tui-compiled/sidebar-state.ts +2 -2
- package/dist/index-42r4bnpm.js +0 -45
- package/dist/index-hbk67489.js +0 -2
- package/dist/index-t4aky73k.js +0 -2
package/dist/cli.js
CHANGED
|
@@ -1,58 +1,58 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{y as D3}from"./index-m4dazzyf.js";import{A as Z7,B as J7,C as v9,D as h9,E as m9,F as w9,G as z7}from"./index-naff9h33.js";import{ia as c4,ja as _Z,ka as k3}from"./index-71temqvq.js";var n$=_Z((qq,m4)=>{var s$={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"},RZ={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},SZ={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?s$.up():"");if($)Z+=s$.left;return Z}};m4.exports={cursor:s$,scroll:RZ,erase:SZ,beep:"\x07"}});import{stdin as jJ,stdout as MJ}from"node:process";import{createInterface as DJ}from"node:readline/promises";import{authorize as NJ,createNativeAccountRuntime as LJ,decideOpenCodeStateLayoutOnce as PJ,exchange as CJ,formatNativeAccountState as OJ,generateRelayToken as AJ,getAccountStoragePath as IJ,isValidApiBaseURL as _J,readNativeEnrollmentMode as RJ,resolveNativePoolPaths as SJ,WORKER_SCRIPT as kJ}from"@cortexkit/anthropic-auth-core";import{randomUUID as u6}from"node:crypto";import{constants as z3}from"node:fs";import{lstat as c6,mkdir as p6,open as d6}from"node:fs/promises";import{homedir as l6}from"node:os";import{isAbsolute as a6,join as J4}from"node:path";import{types as T$}from"node:util";import{anthropicAuthStateRoot as s6,createProviderErrorRedactor as z4,createWindowsOwnerOnly as n6,ensureWindowsOwnerOnlyDirectory as i6,formatLogLine as o6,HOLDER_REGISTRATION_ERROR_MESSAGES as r6,isOwnerOnly as t6,isSecretKey as e6,isStateLayoutRefusalCode as $5,NativeMigrationError as Z5,NativePiAuthSlotError as J5,PRIVATE_FILES_UNAVAILABLE_MESSAGE as X4,RELOCATED_MESSAGE as z5,STATE_LAYOUT_REFUSAL_CODES as X5,STATE_LAYOUT_REFUSAL_PUBLIC_MESSAGES as G5,setupEnrollment as Q5,stateLayoutRefusalPublicMessage as W5}from"@cortexkit/anthropic-auth-core";import{readFile as T6}from"node:fs/promises";import{assertHostsStopped as E6,createNativeAccountRuntime as b6,discoverNativeVaultInventory as f6,inspectNativeHostAuthEntry as A$,NativePiAuthSlotError as x6,nativePiAuthSlotPaths as y6,openNativePiAuthSlot as _$,readNativeEnrollmentMode as g6,requireNoSupervisedAuthContentSnapshot as v6}from"@cortexkit/anthropic-auth-core";import{dirname as G6}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as Q6,CLAUSTRUM_PI_ENROLLMENT_NAME as W6,getHostClaustrumEnrollmentPaths as b9,resolveClaustrumConnectionPath as H6}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as CQ}from"@cortexkit/claustrum-client";import{ClaustrumClient as ZQ}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as Y7}from"@cortexkit/claustrum-client";import{SocketClosedError as U7,SocketTimeoutError as q7,SubcCallError as K7}from"@cortexkit/subc-client";class O extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var A3=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 r extends O{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function N0($){if($ instanceof r||$ instanceof U7||$ instanceof q7)return"unreachable";let Z=$ instanceof Y7||$ instanceof K7?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(A3,Z))return"answered";return A3[Z]}import{resolve as z2}from"node:path";import{storeIdentity as nJ}from"@cortexkit/claustrum-client";import{SubcClient as oJ}from"@cortexkit/subc-client";var a0=300000,v1=300000,I3=1000;class B1{#$;#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 h1{#$;#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 m1{#$;#Z=new B1;#J;#W="polling";#G;#Q;#z=!1;#X;#j=!1;#H=0;constructor($){this.#$=$,this.#J=new h1(async()=>{let Z=this.#j;if(this.#j=!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.#V(!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#V($){let Z;try{Z=await this.#$.enrollmentToken()}catch(Q){if(this.#z)return;this.#$.onError?.(Q),this.#M("token-unreadable");return}let J=this.#$.client.watchScoped;if(this.#z||this.#G||!J)return;this.#Z.restart(),this.#j=$;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.#j=!0;this.#X=Q.view,this.#J.request()},{enrollmentToken:Z})}catch(Q){this.#$.onError?.(Q),this.#M("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.#M("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.#V(!0));return}this.#M(Z.kind)}#M($){this.#Y("fallback",$),this.#q(300000,()=>void this.#V(!1))}}var u1=60000,X2=4*u1,F7=2*u1,_3=new Map,w1=new Map;function j1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function V7($){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 B7($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class G2{transport;key;#$=[];#Z=!1;#J=new Set;#W=new Map;#G=new h1(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.#W.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#J.clear()}},()=>{});#Q=new B1;#z="polling";#X=0;#j=0;#H=new Map;#Y;#q;#V={};#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 w1)if($-z>=u1)w1.delete(J);let Z=w1.get(this.key);if(Z!==void 0&&$-Z<u1)return Promise.resolve();return w1.set(this.key,$),this.#G.request()}watchMode(){return this.#z}watch($={}){this.#X++;let Z=$.provider;if(Z===void 0)this.#j++;else this.#H.set(Z,(this.#H.get(Z)??0)+1);if(this.#X===1)this.#V=$,this.#N();let J=!1;return()=>{if(J)return;if(J=!0,Z===void 0)this.#j--;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.#M()}}#M(){if(this.#q)(this.#V.clearTimeoutImpl??clearTimeout)(this.#q);this.#q=void 0;let $=this.#Y;this.#Y=void 0,$?.handle?.stop(),this.#z="polling"}#B($){this.#q=(this.#V.setTimeoutImpl??setTimeout)(()=>{if(this.#q=void 0,this.#X>0&&!this.#Y)this.#N()},$),this.#q.unref?.()}#N(){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.#P(Z,z);return}Z.handle=J,J.closed.then(()=>this.#P(Z,void 0),(z)=>this.#P(Z,z))}#_($,Z){if(this.#Y!==$)return;if($.notices++,$.notices===1)this.#z="watching";if($.notices===2)this.#U=0;let J=V7(Z);if(!J)this.#Q.restart();if(!(J?this.#Q.continuous(J):!1)||J?.provider===void 0||this.#j>0||this.#H.has(J.provider))this.#G.request()}#P($,Z){if(this.#Y!==$)return;this.#Y=void 0;let J=B7(Z);if(J==="unknown_method"||J==="usage_watch_limit"){this.#z="fallback";return}if($.notices>0){let z=Math.min(I3*2**Math.min(this.#U,16),v1);this.#U++,this.#z="polling",this.#B(z);return}if(this.#z="fallback",this.#G.request(),Z===void 0||N0(Z)==="unreachable")this.#B(v1)}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>=X2)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+X2||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>=F7?"unreachable":"cold"}}}function R3($,Z){let J=JSON.stringify([z2($.connectionFile),z2(Z)]),z=_3.get(J);if(!z)z={source:new G2($,J),refs:0},_3.set(J,z);z.refs++;let X=!1;return{source:z.source,release(){if(X)return;if(X=!0,--z.refs===0)_3.delete(J)}}}import{ClaustrumCredentialError as QQ}from"@cortexkit/claustrum-client";import{appendFileSync as S7,chmodSync as k7,existsSync as E3,renameSync as j2,statSync as T7}from"node:fs";import{open as E7}from"node:fs/promises";import{dirname as b7,resolve as f7}from"node:path";import{randomUUID as Y2}from"node:crypto";import{lstat as U2,readFile as q2,rename as j7,unlink as Q2}from"node:fs/promises";import{tmpdir as M7}from"node:os";import{dirname as L0,join as D7,resolve as t}from"node:path";var _=process.platform==="win32",W2=new Set;function S3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var H2;var K2="native-addon-unavailable";function F2($){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:$}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:K2})}function N7($,Z){return Z instanceof $.PrivateFilesUnavailableError||Z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function L7($){try{await $.verifyPrivatePath(D7(M7(),`.common-auth-private-files-probe-${Y2()}`),"file")}catch(Z){if(N7($,Z))throw F2(Z)}}function s0(){return H2??=import("@cortexkit/private-files").then(async($)=>{if(_)await L7($);return $},($)=>{throw _?F2($):$}),H2}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}: ${$} (${K2}). 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=S3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}async function i($,Z,J){try{return await J()}catch(z){if(z instanceof m)throw z;throw new m($,Z,z)}}var P7;async function F0($,Z){$=t($),Z??=P7,await i($,"safe-parent",async()=>{let J=await(await s0()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await U2($);throw new m(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function d($,Z,J=!1){if($=t($),Z==="directory")return F0($);await i($,"verify",async()=>{let z=await s0(),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 F0(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&&!W2.has($))W2.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function G0($,Z=!1,J){$=t($),await i($,"directory",async()=>{let z=await s0();try{return await U2($),await F0($,J)}catch(G){if(S3(G)!=="ENOENT")throw G}let X=L0($);if(X===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await G0(X,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(S3(G)!=="EEXIST")throw G}await F0($,J)})}async function Z0($,Z=!1){if(!_)return q2($,"utf8");return(await C7($,Z)).toString("utf8")}async function C7($,Z=!1){if(!_)return q2($);if($=t($),Z)await F0(L0($)),await d($,"file",!0);return i($,"read",async()=>(await s0()).readOwnerOnly($))}async function n0($,Z){await F0(L0(t($))),await i($,"create",async()=>{await(await s0()).createPrivateFile(t($),Z)})}async function V2($){await F0(L0(t($))),await i($,"directory-create",async()=>{await(await s0()).createOwnerOnly(t($),{kind:"dir"})})}async function T3($,Z,J={}){$=t($),Z=t(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 M=Math.min(Q??1/0,G);if(z()>=M)break;if(K)await(J.sleep??((L)=>new Promise((C)=>setTimeout(C,L))))(Math.min(K,Math.max(0,M-z())));if(z()>=M)break;let V=z();if(await J.beforeRename?.(),Q!==void 0)Q+=z()-V;if(z()>=G)break;U++;try{return await(J.rename??j7)($,Z),{attempts:U,elapsedMs:z()-X}}catch(L){H??=L;let C=L;if(!(C.win32Code!==void 0?C.win32Code===32||C.win32Code===33:["EBUSY","EPERM","EACCES"].includes(C.code??"")&&!C.reason))break;Q??=z()+500}}let Y=new m(Z,"rename",H??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw Y.attempts=U,Y.elapsedMs=z()-X,Y}async function i0($,Z,J={}){$=t($),await G0(L0($));try{await d($,"file",!0)}catch(U){if(U.code!=="ENOENT")throw U}let z=t(J.stagePath??`${$}.${Y2()}.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 n0(z,Z),X=!0,W="before-rename",Q=await T3(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 Y=U instanceof m?U:new m($,W,U);if(Y.published=G,Y.fileDurable=G,G)Object.assign(Y,Q);if(X){try{await Q2(z)}catch{Y.orphanPath=z}X=!1}throw H(Y),Y}finally{if(X)await Q2(z).catch(()=>{})}}var O7=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,A7=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function I7($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function o0($={}){let Z=[A7,...$.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 O7.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,Y)=>U.replace(Y,"***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=I7(G);if(U&&H>=8)return"[Truncated]";let Y=U?H+1:H;return Object.fromEntries((U?z(G):Object.entries(G)).map(([K,M])=>[K,Q&&J(K)?"***REDACTED***":X(M,Q,W,Y)]))}finally{W.delete(G)}}return{redact:(G)=>X(G,!0,new WeakSet),redactStrings:(G)=>X(G,!1,new WeakSet)}}var B2=o0(),_7=B2.redact,R7=B2.redactStrings;var c1={error:0,warn:1,info:2,debug:3,trace:4},D2=5242880,N2=3;function b3($){try{k7($,384)}catch{}}function x7($){try{if(!(E3($)&&T7($).size>=D2))return;for(let J=N2-1;J>=1;J--)if(E3(`${$}.${J}`)){let z=`${$}.${J+1}`;j2(`${$}.${J}`,z),b3(z)}let Z=`${$}.1`;j2($,Z),b3(Z)}catch{}}async function V0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await i(Z,"log-close",()=>J.close())}async function M2($,Z){await G0(b7(Z));try{await d(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await n0(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await d(Z,"file",!0)}}return $.handle=await i(Z,"log-open",()=>E7(Z,"a")),$.file=Z,$.handle}async function y7($,Z,J){Z=f7(Z);try{if($.file!==Z)await V0($);let z=$.handle??await M2($,Z);if((await i(Z,"log-stat",()=>z.stat())).size>=D2){await V0($);for(let G=N2-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 T3(Q,W),await d(W,"file")}z=await M2($,Z)}await i(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await V0($).catch(()=>{}),z}}function g7($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function v7($){let Z,J,z,X=o0(),G,Q=[],W,H=Promise.resolve(),U,Y={};function K(F){let q=H.then(F);return H=q.catch((B)=>{U=B}),q}function M(F){if(_&&F.file!==Z)K(()=>V0(Y)).catch(()=>{});Z=F.file,J=F.level,X=o0(F),G=F.captureSink}function V(F){if(F===void 0||F in c1)z=F}function L(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function C(){if(z)return z;let F=typeof J==="function"?J():J;if(F&&F in c1)return F;return"info"}function A(F=!0){if(W)clearTimeout(W),W=void 0;if(!Q.length){if(_)return K(async()=>{if(F)await V0(Y);if(U)throw U});return}let q;try{q=L()}catch{if(Q=[],_&&F)return K(()=>V0(Y));return}let B=Q.join("");if(Q=[],!q){if(_&&F)return K(()=>V0(Y));return}if(_)return K(async()=>{try{await y7(Y,q,B)}finally{if(F)await V0(Y)}});try{if(x7(q),E3(q))b3(q);S7(q,B,{encoding:"utf8",mode:384})}catch{}}function I(){if(!W)W=setTimeout(()=>{W=void 0;let F=A(!1);if(F instanceof Promise)F.catch(()=>{})},500)}function R(F,q,B,P){if(Z===void 0&&G===void 0)return;try{if(c1[q]>c1[C()])return;let y=X.redactStrings(B),T;try{T=X.redact(P)}catch{T="[unserializable]"}let g=`[${new Date().toISOString()}] ${q.toUpperCase()} [${F}] ${y}`+(P===void 0?"":g7(T))+`
|
|
3
|
-
`;try{G?.({channel:F,level:
|
|
4
|
-
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??
|
|
5
|
-
`,"utf8"),await G.chmod(384),J.durable)try{await G.sync()}catch(W){throw new p1(W)}if(await G.close(),G=void 0,await J.beforeRename?.(),await
|
|
6
|
-
`,{deadline:performance.now()+Math.max(0,
|
|
7
|
-
`,"utf8"),await D.chmod(384),await D.close(),D=void 0;let
|
|
8
|
-
`;if(_)await
|
|
9
|
-
`;if(_)await
|
|
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 O("invalid-state","Claustrum enrollment state is too large");if(_)return
|
|
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 B8($){let Z=$;return{providerIds:Z.providerIds,authMethod:Z.authMethod}}function j8($){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 $1{#$;#Z;#J;#W;#G;#Q;#z;#X=new WeakMap;#j=new WeakMap;#H=new Map;#Y=new WeakMap;#q;#V;#U=!1;#M=new r;#B;#N=!1;#_=-1/0;#P=2000;#K=!1;#D;#I=new Set;#F=new Set;#C;#A;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>O0(Z);else throw new O("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??l3,this.#C=t0(this.#z),this.#q=$.setTimeoutImpl??setTimeout,this.#V=$.clearTimeoutImpl??clearTimeout}transportLost($){if(this.#K||this.#U)return;this.#U=!0,this.#M=$ instanceof i2?$:new r,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.#V(this.#B);this.#B=void 0,this.#P=2000;for(let $ of this.#H.values())$.since=null;(this.#z.info??l3.info)("vault receipt serving resumed",{reason:"reachable"})}#R(){if(this.#K||!this.#U||this.#B||this.#N)return;this.#B=this.#q(()=>{this.#B=void 0,this.#L(!0)},this.#P),this.#B.unref?.()}#L($=!1){if(this.#K||!this.#U||this.#N)return;if(this.#J()-this.#_<1000){this.#R();return}this.#_=this.#J(),this.#N=!0,this.#b().catch(()=>{if($&&this.#U)this.#P=Math.min(this.#P*2,30000)}).finally(()=>{this.#N=!1,this.#R()})}#O($){if(this.#K)throw new O("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#k($){this.#O($);let Z=this.#Z();this.#F.add(Z);let J;try{J=await Z}finally{this.#F.delete(Z)}if(this.#O($),!/^[0-9a-f]{64}$/.test(J.token)||!Number.isSafeInteger(J.token_generation)||J.token_generation<1)throw new O("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 i2)throw X;if(N0(X)==="unreachable")throw new r;throw new O("unavailable","Claustrum scoped operation unavailable")}finally{z?.()}return this.#O(Z),this.reachable(),J}async discover($){let Z=await this.#b($);return this.#D=Z.view,Z}async#b($){let Z,J;try{J=await this.#k($)}catch(Y){throw this.#H.clear(),Y}try{Z=await this.#S(()=>this.#$.listScoped(J),$)}catch(Y){throw this.listFailed(Y),Y}let z=[],X=[],G=0,Q=[],W=new Map;for(let Y of Z.rows){let K=V8(Y,this.#W);if(K.kind==="not-mine"){G++;continue}if(K.kind==="refused"){X.push({...Y.id.trim()&&{credentialId:Y.id},code:K.code});continue}Q.push({row:Y,type:K.type,...K.member!==void 0&&{member:K.member}}),W.set(Y.id,(W.get(Y.id)??0)+1)}let H=[];for(let{row:Y,type:K,member:M}of Q){let V;if(!Y.id.trim())V="empty credential id";else if((W.get(Y.id)??0)>1)V="duplicate credential id";else if(Y.accountId!==void 0&&!Y.accountId.trim())V="blank account identity";else if(!Y.state.trim())V="empty state";if(V){z.push({...Y.id.trim()&&{credentialId:Y.id},...M!==void 0&&{member:M},reason:V});continue}H.push(Object.freeze({credentialId:Y.id,credentialType:K,...M!==void 0&&{member:M},...Y.accountId!==void 0&&{accountIdentity:Y.accountId},state:Y.state,...Y.email!==void 0&&{email:Y.email},...Y.orgName!==void 0&&{orgName:Y.orgName}}))}for(let Y of z)this.#z.warn("skipped malformed vault record",Y);let U=j8(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()>r2}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.#L(),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.#M){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 O("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:z,credentialType:X,accountIdentity:G}=$;if(this.#Q&&G===void 0)throw new O("identity-unasserted","Claustrum dispatch requires a known account identity");let Q=await this.#S(()=>this.#$.getScoped({credentialId:z,enrollmentToken:Z,...X==="oauth"&&{minTtlMs:a3}}),J);if(Q.credentialId!==void 0&&Q.credentialId!==z)throw new O("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()<a3))throw new O("insufficient-validity","Claustrum served credential has insufficient validity");let H=F8(Q.material),U=Q.accountId?.trim()?Q.accountId:void 0;if(this.#Q&&(Q.credentialId===void 0||U===void 0))throw new O("identity-unasserted","Claustrum served credential did not assert its identity");let Y=U===void 0?this.#G?.(H):void 0,K=U??Y;if(G!==void 0&&K!==void 0&&K!==G)throw new O("identity-changed","Claustrum served credential identity changed");let M=K??G,L=Object.freeze(Object.defineProperty({credentialId:z,credentialType:X,...M!==void 0&&{accountIdentity:M},accountIdentitySource:U!==void 0?"asserted":Y!==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(L,Z),L}async reportFailure($,Z,J){if(Z!==401)return;this.#O();let z=this.#X.get($);if(!z)throw new O("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.#j.get($);if(Q)return Q;let W=this.#S(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:z,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#j.set($,W);try{await W,this.#z.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:J})}catch(H){throw this.#j.delete($),H}}watchRoster($){this.#O();let Z=new m1({client:this.#$,enrollmentToken:()=>this.#k(),view:$.view??(()=>this.#D),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.#V});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.#V(this.#B);this.#B=void 0;for(let $ of this.#I)$.stop();this.#I.clear(),this.#H.clear(),this.#$.close()}async dispose($=this.#C){this.close(),this.#A??=e0(this.#F,$),await this.#A}}import{resolve as $3}from"node:path";var n3=30000,i3={now:()=>performance.now(),schedule($,Z){let J=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(J),unref:()=>J.unref?.()}}};var f0="all",M8=Object.freeze(["primary"]);function e2($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function J1($,Z){return JSON.stringify([$,Z])}function A0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function l($){return typeof $==="number"&&Number.isFinite($)}function t2($){return typeof $==="string"&&$.length>0}function s($,Z,J){return $[Z]===void 0||J($[Z])}function D8($){return l($)&&$>0}function o3($){return typeof $==="string"}function N8($){if(!A0($)||!t2($.scope)||!t2($.label))return!1;switch($.kind){case"reading":return l($.checkedAt)&&l($.usedPercent)&&s($,"resetsAt",o3)&&s($,"windowMinutes",D8);case"retired":return l($.retiredAt);case"absent":return l($.checkedAt);default:return!1}}function L8($){if(!A0($)||!l($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&s($,"remainingPercent",l)&&s($,"usedPercent",l)&&s($,"resetsAt",o3)&&s($,"limit",l)&&s($,"used",l)&&s($,"remaining",l)&&s($,"unit",o3)}function $9($){return A0($)&&l($.value)&&Number.isInteger($.value)&&$.value>=0&&l($.checkedAt)}function r3($){return A0($)&&Object.values($).every($9)}function P8($){return typeof $==="boolean"}function z1($){return A0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&s($,"balance",l)&&s($,"overageLimitReached",P8)&&l($.checkedAt)}function Z9($){if(!A0($))return;let Z=Object.entries($).filter(([,J])=>$9(J));return Z.length===0?void 0:Object.fromEntries(Z)}function x0($){if(Z1($))return $;if(!A0($))return;let{counters:Z,credits:J,...z}=$;if(!Z1(z))return;let X=Z9(Z),G=z1(J)?J:void 0;return{...z,...X===void 0?{}:{counters:X},...G===void 0?{}:{credits:G}}}function Z1($){if(!A0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!N8(J))return!1;let z=J1(J.scope,J.label);if(Z.has(z))return!1;Z.add(z)}return s($,"budget",L8)&&s($,"counters",r3)&&s($,"credits",z1)}class i1 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function r1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function o1($){return typeof $==="number"&&Number.isFinite($)}function J9($){return $===void 0||typeof $==="string"&&$!==""}function z9($){return typeof $==="string"&&$!==""}function C1($,Z){return $[Z]===void 0||o1($[Z])}function t3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function C8($){return r1($)&&J9($.scope)&&z9($.label)&&o1($.usedPercent)&&t3($,"resetsAt")&&($.windowMinutes===void 0||o1($.windowMinutes)&&$.windowMinutes>0)}function O8($){return r1($)&&J9($.scope)&&z9($.label)}function A8($){if(!r1($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&C1($,"remainingPercent")&&C1($,"usedPercent")&&t3($,"resetsAt")&&C1($,"limit")&&C1($,"used")&&C1($,"remaining")&&t3($,"unit")}function X1($){if(!r1($)||!o1($.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(!C8(X))return!1;let G=J1(X.scope??f0,X.label);if(z.has(G))return!1;z.add(G)}if(!J.every(O8))return!1;return($.budget===void 0||A8($.budget))&&($.counters===void 0||r3($.counters))&&($.credits===void 0||z1($.credits))}function I8($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function _8($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function R8($,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 S8($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function O1($,Z){let J=$===void 0?void 0:x0($);if($!==void 0&&J===void 0)throw new i1("stored quota map is malformed");if(!X1(Z))throw new i1("quota observation is malformed");let z=J??{limits:[]},X=Z.checkedAt,G=new Map;for(let A of z.limits)G.set(J1(A.scope,A.label),A);let Q=(A)=>{let I=G.get(A);return I===void 0||X>=e2(I)},W=new Set;for(let A of Z.readings??[]){let I=A.scope??f0,R=J1(I,A.label);if(W.add(R),!Q(R))continue;G.set(R,{scope:I,label:A.label,kind:"reading",checkedAt:X,usedPercent:A.usedPercent,...A.resetsAt===void 0?{}:{resetsAt:A.resetsAt},...A.windowMinutes===void 0?{}:{windowMinutes:A.windowMinutes}})}for(let A of Z.coverage??[]){let I=A.scope??f0,R=J1(I,A.label);if(W.has(R)||!Q(R))continue;let v=G.get(R);G.set(R,v===void 0||v.kind==="absent"?{scope:I,label:A.label,kind:"absent",checkedAt:X}:{scope:I,label:A.label,kind:"retired",retiredAt:X})}let{limits:H,budget:U,counters:Y,credits:K,...M}=z,V=_8(z.budget,Z.budget,X),L=R8(z.counters,Z.counters),C=S8(z.credits,Z.credits);return{...M,limits:[...G.values()].sort(I8),...V===void 0?{}:{budget:V},...L===void 0?{}:{counters:L},...C===void 0?{}:{credits:C}}}var k8=Object.freeze({validate:Z1,decode:x0,merge:O1});function X9($,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 f8}from"node:crypto";import{stat as x8}from"node:fs/promises";import{resolve as A1}from"node:path";function G9($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function e3($,Z,J){return $.some((z)=>G9(z,Z,J))}function $$($,Z,J){let z={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((X)=>X.credentialId!==Z||X.accountIdentity!==J),z]}function Z$($,Z,J){return $.filter((z)=>!Z.some((X)=>G9(z,X,J)))}function J$($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>W0(Z).map((J)=>({credentialId:J,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function y8($,Z){let J=W0(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 e1="vault:";function g8($){return f8("sha256").update($).digest("hex")}function v8($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function h8($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function W0($){return[$.credentialId,...$.aliases??[]]}function H9($,Z,J={}){let z=J.now??Date.now(),X=J.routePrefix??e1,G=J.reservedRouteIds??new Set,Q=$?.rows??[],W=$?void 0:J.seed,H=[...$?.declined??W?.declined??[]],U=Z.skipped.length===0,Y=new Set(Z.credentials.map((F)=>F.credentialId)),K=new Set(Z.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),M=Z.skipped.some((F)=>F.credentialId===void 0),V=(F)=>!Y.has(F)&&(K.has(F)||M),L=new Map;for(let F of Q){if(F.accountIdentity===void 0)continue;for(let q of W0(F))if(!L.has(q))L.set(q,F.accountIdentity)}let C=new Map;for(let F of Z.credentials){let q=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:L.get(F.credentialId),claimed:!1},B=h8(q),P=C.get(B)??[];P.push(q),C.set(B,P)}let A=new Set,I=new Set(G),R=[],v=(F,q)=>F.credential.credentialId.localeCompare(q.credential.credentialId),h=[...C.values()].map((F)=>F.toSorted(v)).sort((F,q)=>F[0]&&q[0]?v(F[0],q[0]):0);for(let F of h){let q=F[0]?.identity,B=F.filter((E)=>E.credential.state==="active"),P=B.length?B:F,y=P.filter((E)=>E.claimed),T=y.length?y:P,g=new Set(F.map((E)=>E.credential.credentialId)),$0=Q.find((E)=>!A.has(E)&&W0(E).some((K0)=>g.has(K0))&&(E.accountIdentity===void 0||E.accountIdentity===q)),p=T.find((E)=>E.credential.credentialId===$0?.credentialId)??T[0];if(!p)continue;let u=p.credential,a=$0??(q===void 0?void 0:Q.find((E)=>!A.has(E)&&E.accountIdentity===q));if(a)A.add(a);let q0=a?.routeId;if(!q0||G.has(q0)){let E=`${X}${u.credentialId}${q===void 0?"":`~${g8(q).slice(0,10)}`}`;q0=E;for(let K0=2;I.has(q0);K0++)q0=`${E}~${K0}`}I.add(q0);let y1=a?W0(a).filter(V):[],d0=[...new Set([...F.map((E)=>E.credential.credentialId),...y1])].filter((E)=>E!==u.credentialId).sort((E,K0)=>E.localeCompare(K0)),g1=J.mapAccount?.(u)??{};R.push({previousIndex:a?Q.indexOf(a):1/0,row:{routeId:q0,credentialId:u.credentialId,credentialType:u.credentialType,...q!==void 0&&{accountIdentity:q},...d0.length&&{aliases:d0},state:u.state,label:g1.label?.trim()||v8(u),...u.email!==void 0&&{email:u.email},...u.orgName!==void 0&&{orgName:u.orgName},enabled:![u.credentialId,...d0].some((E)=>e3(H,E,q)),addedAt:a?.addedAt??z,...a?.quota!==void 0&&{quota:a.quota},...!p.claimed&&q!==void 0&&{unclaimed:!0}}});let l0=R.at(-1);if(W&&l0)l0.previousIndex=y8(W,l0.row)}return Q.forEach((F,q)=>{if(A.has(F)||!W0(F).some(V))return;if(I.has(F.routeId))return;let[B,...P]=W0(F).filter((g)=>!Y.has(g));if(B===void 0)return;I.add(F.routeId);let{aliases:y,...T}=F;R.push({previousIndex:q,row:{...T,credentialId:B,...P.length&&{aliases:P},stale:!0}})}),R.sort((F,q)=>F.previousIndex===q.previousIndex?F.row.credentialId.localeCompare(q.row.credentialId):F.previousIndex-q.previousIndex),{version:1,view:Z.view,complete:U,...!U&&{rejected:Z.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:R.map((F)=>F.row),declined:H}}function z$($){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 I1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function G1($){return $===void 0||typeof $==="string"}function m8($){let Z=I1($)?x0($.quota):void 0;if(!I1($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!G1($.accountIdentity)||!G1($.email)||!G1($.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 w8=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function Q9($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!I1(J)||!G1(J.credentialId)||typeof J.reason!=="string"||!w8.has(J.reason))return;Z.push(J)}return Z}function Y9($){if(!I1($)||$.version!==1||!G1($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!Q9($.rejected))throw new O("invalid-state","Claustrum roster file is not valid");let Z=[];for(let X of $.rows){let G=m8(X);if(!G)throw new O("invalid-state","Claustrum roster file is not valid");Z.push(G)}let J=[];for(let X of $.declined){if(!I1(X)||typeof X.credentialId!=="string"||!G1(X.accountIdentity))throw new O("invalid-state","Claustrum roster file is not valid");J.push(X)}let z=Q9($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...z&&{rejected:z},rows:Z,declined:J}}function U9($){return Y9(JSON.parse(JSON.stringify($)))}async function w($){let Z;try{Z=await Z0($,_)}catch(z){if(z.code==="ENOENT")return;throw z}let J;try{J=JSON.parse(Z)}catch{throw new O("invalid-state","Claustrum roster file is not valid")}return Y9(J)}var q9={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},K9={name:"claustrum-roster",ttlMs:30000};async function y0($,Z,J={}){return f3($,{...q9,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 D1($,G,{beforeRename:async()=>{await J.beforePublish?.(),J.signal?.throwIfAborted(),await z.assertOwned()}});return Q})}function X$($,Z){return y0($,(J)=>{let z=J?.rows.find((G)=>G.routeId===Z);if(!J||!z)throw new O("route-unavailable","Claustrum route is not in the roster");let X=$$(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 G$($,Z){return y0($,(J)=>{let z=J?.rows.find((X)=>X.routeId===Z);if(!J||!z)throw new O("route-unavailable","Claustrum route is not in the roster");return{next:{...J,declined:Z$(J.declined,W0(z),z.accountIdentity),rows:J.rows.map((X)=>X===z?{...X,enabled:!0}:X)},result:void 0}})}function u8($){return new O("invalid-order",$)}function c8($,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 Q$($,Z,J={}){return y0($,(z)=>{let X=z?.rows??[],G=c8(X,Z);if(G)throw u8(G);let Q=new Map;for(let U of X){let Y=Q.get(U.routeId);if(Y)Y.push(U);else Q.set(U.routeId,[U])}let W=[...Z],H=W.flatMap((U)=>Q.get(U)??[]);if(!z||H.every((U,Y)=>U===X[Y]))return{result:{ids:W,outcome:"unchanged"}};return{next:{...z,rows:H},result:{ids:W,outcome:"reordered"}}},{...J.signal&&{signal:J.signal}})}function p8($,Z){if(!W0($).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")&&W0($).length===1)return"bind";return"refuse"}async function W$($,Z){let{routeId:J,observation:z,...X}=Z;return F9($,{routeId:J,observation:z,accountIdentity:X.accountIdentity,receipt:X})}async function F9($,Z){if(!X1(Z.observation))return!1;let J=o($,await w($));if(!I0(J,Z).kept)return!1;return B9($,Z)}function H$($,Z){return F9($,Z)}function I0($,Z){let J=$?.rows.find((Q)=>Q.routeId===Z.routeId),z=!J?"refuse":Z.receipt?p8(J,Z.receipt):J.accountIdentity!==void 0&&J.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!J||z==="refuse")return{roster:$,kept:!1};let X=O1(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 t1=new Map;function _1($){t1.delete(A1($))}function V9($,Z){let J=A1($);if(Z instanceof O)return Z.kind==="roster-busy";if(Z instanceof P0||Z instanceof B0)return A1(Z.details.target)===J;if(Z instanceof m){let z=A1(Z.path);return[q9.name,K9.name].some((X)=>{let G=N1(J,X);return z===G||z.startsWith(`${G}.`)})}return!1}var d8=4;async function W9($){try{let{dev:Z,ino:J,size:z,mtimeMs:X}=await x8($);return{dev:Z,ino:J,size:z,mtimeMs:X}}catch{return}}function l8($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function a8($,Z,J){for(let z=0;z<d8;z++){let X=await W9($),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(!l8(X,await W9($)))continue;if(H)return"commit";return j9($)?"commit":"unchanged"}return"commit"}async function R1($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){_1($.path);return}let J=await j0({...K9,path:$.path,renew:!0});if(!J){let Q=await w($.path);if($.signal?.throwIfAborted(),!Q?.view)throw new O("roster-busy","Claustrum account discovery is already in progress");return Q}let z=A1($.path),X=$.listedOver,G;try{let Q=await w($.path),W=X?void 0:t1.get(z);G=W&&(W.previousView===Q?.view||W.inventory.view===Q?.view)?W:{inventory:await $.custody.discover($.signal),previousView:Q?.view},t1.delete(z);let{inventory:H}=G;$.onInventory?.(H),$.signal?.throwIfAborted();let U=typeof $.projection==="function"?$.projection():$.projection,Y=(V)=>H9(V,H,U),K=async()=>{return $.signal?.throwIfAborted(),await J.assertOwned(),Z()};if(await a8($.path,(V)=>{if(X)return{target:V};let L=o($.path,V);return{target:V,...L!==V&&{local:L}}},Y)==="unchanged"){if(!await K())return;return await w($.path)}return await y0($.path,async(V)=>{if(!await Z())return{result:void 0};if($.signal?.throwIfAborted(),await J.assertOwned(),X&&V?.view!==X.view&&V?.view!==H.view)return{result:V};let L=Y(V);return{...JSON.stringify(V)!==JSON.stringify(L)&&{next:L},result:L}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await J.assertOwned()}})}catch(Q){if(Q instanceof P0&&G&&!X&&!$.signal?.aborted&&await Z())t1.set(z,G);throw Q}finally{await J.release()}}var g0=new Map,s8=Q0("claustrum"),D9=100;function N9($,Z=i3){let J=$3($),z=g0.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},g0.set(J,z);return z}function L9($,Z,J){let z=N9($,J);z.listeners.add(Z);let X;return()=>X??=(()=>{return z.listeners.delete(Z),z.listeners.size?Promise.resolve():Y$($)})()}function n8($){return X9($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function B9($,Z){if(!X1(Z.observation))return Promise.resolve(!1);let J=N9($),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 n8(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 C9(J,D9),Promise.resolve(!0)}function P9($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,J)=>Z.order-J.order)}function o($,Z){let J=g0.get($3($));if(J)for(let z of P9(J.pending)){if(z.priorReading)Z=I0(Z,z.priorReading).roster;Z=I0(Z,z.publication).roster}return Z}function j9($){return!!g0.get($3($))?.pending.size}function C9($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let J=$.draining?0:($.committedAt??-1/0)+n3-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,J),()=>{return $.timer=void 0,O9($)}),!$.draining)$.timer.unref?.()}function M9($){$.timer?.cancel(),$.timer=void 0}function O9($){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 y0($.path,(z)=>{let X=z;for(let Q of P9(Z)){if(Q.priorReading)X=I0(X,Q.priorReading).roster;X=I0(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)s8.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()):D9;C9($,J)}})(),$.running}async function Y$($,Z=1000){let J=$3($),z=g0.get(J);if(!z)return;z.draining=!0,M9(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)O9(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(),M9(z),z.pending.clear(),g0.get(J)===z)g0.delete(J)}}}var Z3=1e4;function A9(){return new r}var U$;function _9($,Z){if(!U$)throw Error("ClaustrumConsumer is not initialized");return U$($,Z)}function I9(){return new O("not-active","Claustrum scoped custody is not active")}class q${#$;#Z=new AbortController;#J;#W;#G;#Q;#z;#X;#j;#H;#Y=!1;#q=new Set;#V;#U;#M;#B;#N=new Map;#_;#P;#K;#D;#I=new WeakMap;static{U$=($,Z)=>{let J=new q$(Z);return J.#K=$,{consumer:J,hooks:J.#x()}}}constructor($){this.#$=$,this.#J=$.logger??Q0("claustrum"),this.#W=t0(this.#J,this.#Z.signal),this.#P=L9($.rosterPath,(Z)=>{this.#X=I0(this.#X,Z).roster})}#F($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#C($){return this.#q.add($),$.then(()=>this.#q.delete($),()=>this.#q.delete($)),$}async#A(){return await this.#$.isCustodyActive?.()??!0}#R($,Z){let J=k0([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.#F(),this.#G)return this.#G;if(!this.#Q){let $={timedOut:!1};this.#Q=this.#O($),this.#C(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.#F();throw A9()}if(this.#G=new $1({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=R3(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(A9())},this.#k()),X.unref?.()});return Promise.race([z,G]).finally(()=>{if(X)J(X);this.#Q=void 0})}#k(){return this.#$.connectTimeoutMs??Z3}snapshot(){return this.#X}grantReach(){if(this.#K)return this.#K.grantReach(this.#X?.view);let $=this.#j;return $&&this.#X?.view===$.view?$.reach:void 0}watchState(){if(this.#K)return Object.freeze({vault:this.#K.watchMode()});return Object.freeze({vault:this.#M?.mode??"polling",...this.#$.insula&&{insula:this.#U?.source.watchMode()??"polling"}})}#S(){this.#M?.close(),this.#M=void 0,this.#B?.(),this.#B=void 0}keptReceiptState(){if(this.#K){let $=this.#D;return $&&this.#K.leaseLive($)?$.custody.keptReceiptState():this.#K.keptReceiptState()}return this.#G?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return z$(this.#X)}refresh(){if(this.#F(),this.#K)return this.#C(this.#y(this.#K));if(this.#z)return this.#z;return this.#z=(async()=>{if(!await this.#A()){if(this.#X=void 0,this.#j=void 0,this.#S(),this.#G)this.#G.close(),this.#C(this.#G.dispose(this.#W));this.#G=void 0,this.#U?.release(),this.#U=void 0;return}let $=await this.#L(),Z,J=await R1({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.#F();let z=J?.view!==this.#X?.view;if(this.#X=o(this.#$.rosterPath,J),$.retain(J?.rows??[]),Z&&J?.view!==void 0)this.#j=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.#C(this.#z),this.#z}start(){if(this.#Y)return;if(this.#F(),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.#C($())},Z),this.#H.unref?.()};this.#C($())}async#b(){if(this.#M?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#_===void 0||$-this.#_>=a0)return!0;return!await this.#A()}#E(){let $=this.#G;if(this.#Z.signal.aborted||!$)return;if(this.#M??=$.watchRoster({view:()=>this.#X?.view,onView:()=>this.#C((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.#L(),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=o(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=o(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.#N.get($)!==J.miss)this.#N.set($,J.miss),this.#J.warn("skipped insula provider poll",{reason:J.miss});return}return this.#N.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.#F(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 O("not-active","Claustrum scoped custody is not active");let z=o(this.#$.rosterPath,await w(this.#$.rosterPath));this.#F(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 O("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 O("route-unavailable","Claustrum route is disabled, removed or changed")}let Q=await this.#R(this.#L(),Z),W=k0([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=o(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.#F(),!Z)return;if(Z.errors.has($.provider))throw Z.errors.get($.provider);return this.#X}#g($){if($&&this.#D!==$)return;this.#D?.release(),this.#D=void 0}async#f($,Z){let J=this.#D;if(J&&$.leaseLive(J))return J;this.#g();let z=await $.acquire(Z);if(this.#Z.signal.aborted)z.release(),this.#F();let X=this.#D;if(X&&$.leaseLive(X))return z.release(),X;return this.#D=z,z}async#h($,Z,J){if(this.#F(J),!this.#X)await this.#R($.refresh(),J);let z=this.#X;if(!await $.readAuthority())throw this.#g(),I9();if(this.#F(J),!z)throw new O("route-unavailable","Claustrum has no roster for this provider yet");let X=o(this.#$.rosterPath,await w(this.#$.rosterPath));this.#F(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 O("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 O("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=k0([this.#Z.signal,...J?[J]:[]]);try{for(let U=0;;U++){let Y=await this.#f($,H.signal);try{let K=await Y.custody.authorize(W,H.signal,Z);return this.#I.set(K,Y),K}catch(K){if(U>0||H.signal.aborted||$.leaseLive(Y)||!(K instanceof O)||K.kind!=="closed")throw K;if(this.#g(Y),!await $.readAuthority())throw I9()}}}finally{H.dispose()}}async reportFailure($,Z,J){if(this.#F(),this.#K){let z=this.#I.get($);if(!z)throw new O("no-receipt","Claustrum dispatch receipt has no active owner");await z.custody.reportFailure($,Z,J);return}if(!this.#G)throw new O("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(s3(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.#F(),await X$(this.#$.rosterPath,$),this.#X=o(this.#$.rosterPath,await w(this.#$.rosterPath)),this.#K)this.#K.retainUnion();else this.#G?.retain(this.#X?.rows??[])}async accept($){this.#F(),await G$(this.#$.rosterPath,$),this.#X=o(this.#$.rosterPath,await w(this.#$.rosterPath))}async reorder($){this.#F();let Z=await Q$(this.#$.rosterPath,$);return this.#X=o(this.#$.rosterPath,await w(this.#$.rosterPath)),Z}async recordQuota($,Z,J){return this.#F(),W$(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.#F(),H$(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:J})}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new O("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.#C(this.#G.dispose(this.#W));this.#D?.release(),this.#D=void 0,this.#K?.detach(),this.#U?.release(),this.#U=void 0,this.#X=void 0,this.#j=void 0,this.#P(),_1(this.#$.rosterPath)}async dispose(){this.close(),this.#V??=Promise.all([e0(this.#q,this.#W),this.#P()]).then(()=>{}),await this.#V}}import{createHash as i8}from"node:crypto";import{readdir as o8,stat as r8}from"node:fs/promises";import{dirname as t8,join as Q1}from"node:path";var e8=/^[a-z0-9][a-z0-9._-]{0,63}$/,$6=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,Z6=/^[0-9a-f]{16}$/,R9=3;function F$($,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=F$($[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=F$($[G],J);if(Q===void 0)return;z.push(`${JSON.stringify(G)}:${Q}`)}return`{${z.join(",")}}`}function J6($,Z){let J=F$({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??e1,mapAccount:$.mapAccount?String($.mapAccount):null});if(J===void 0)throw new O("invalid-state","Claustrum hub classifierInput must be plain JSON");return i8("sha256").update(J).digest("hex").slice(0,16)}function S9($,Z){if(typeof $!=="string"||!e8.test($)||$6.test($))throw new O("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function _0($="Claustrum custody lease is closed"){return new O("closed",$)}function K$(){return new O("not-active","Claustrum scoped custody is not active")}function k9(){return new r}function z6($,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 T9($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class E9{#$;#Z;#J;#W=new AbortController;#G=new Map;#Q=new WeakMap;#z=0;#X;#j;#H;#Y;#q;#V;#U=0;#M;#B;#N;#_=!1;#P=new Set;#K;#D;#I;constructor($){if(!$.family||!("classify"in $.family))throw new O("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=S9($.hostGeneration,"host generation"),J=$.members.map((X)=>S9(X,"member"));if(new Set(J).size!==J.length)throw new O("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??Q0("claustrum"),this.#J=t0(this.#Z,this.#W.signal),this.#D=Q1($.stateDir,"rosters",Z),this.#I=J6($,J);let z=Q1(this.#D,this.#I);for(let X of J)this.#G.set(X,{provider:X,path:Q1(z,`${X}.json`),closed:!1})}#F($){return this.#P.add($),$.then(()=>this.#P.delete($),()=>this.#P.delete($)),$}#C(){if(this.#W.signal.aborted)throw _0("Claustrum discovery hub is closed")}#A($){let Z=this.#G.get($);if(!Z)throw new O("wrong-consumer","Claustrum hub has no such member");return Z}rosterPath($){return this.#A($).path}member($,Z){this.#C();let J=this.#A($);if(J.hooks)throw new O("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 O("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.#M?.view===W?this.#M.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}=_9(z,X);return J.hooks=Q,G}#R(){let $={id:++this.#z,count:0,ended:!1,controller:new AbortController};return this.#X=$,$}#L($){return!$.ended&&this.#X===$&&!this.#W.signal.aborted}#O($){let Z=this.#Q.get($);return!!Z&&!Z.released&&!Z.generation.ended}#k($,Z=_0()){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.#F($.custody.dispose(this.#J))}#S($){if($.ended)return;if($.count--,$.count<=0)this.#k($)}#b($){let Z=this.#j;if(Z?.generation===$&&Z.promise)return Z.promise;let J={generation:$,timedOut:!1},z=this.#$.connectTimeoutMs??Z3,X,G=this.#$.connect().then((H)=>{if(J.timedOut)throw H.close(),k9();if(!this.#L($)||$.count<=0)throw H.close(),_0("Claustrum connection is no longer wanted");return $.custody=new $1({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.#L($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:z}),U(k9())},z),X.unref?.()});return J.promise=this.#F(Promise.race([G,Q]).finally(()=>{if(X)(this.#$.clearTimeoutImpl??clearTimeout)(X)})),J.promise.finally(()=>{if(this.#j===J)this.#j=void 0}).catch(()=>{}),this.#j=J,J.promise}acquire($){try{if(this.#C(),$?.throwIfAborted(),this.#V===!1)throw K$()}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=k0([$.controller.signal,...Z?[Z]:[]]);try{z=await z6(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.#C(),this.#V===!1)throw K$();if(!Z)throw _0();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 _0()},X=Object.freeze({authorize:async(Q,W,H)=>{z();let U=k0([$.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.#V;if(this.#V=$,!$&&Z!==!1)this.#g();return $}#g(){this.#U++;let $=this.#X;if($)this.#k($,K$());this.#H=void 0,this.#Y?.watch.close(),this.#Y=void 0,this.#M=void 0,this.#B=void 0;for(let Z of this.#G.values())Z.seen=void 0,Z.pending=void 0,Z.hooks?.reset(),_1(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 _0();return X}#m(){try{this.#C()}catch(z){return Promise.reject(z)}let $=this.#q;if($&&!$.generation?.ended)return $.promise;let Z={},J=this.#F(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.#L(J))return;let z=await this.#i().then(()=>{return},(Y)=>Y instanceof Error?Y:Error(String(Y))),X=new Map(await Promise.all([...this.#G.values()].map(async(Y)=>[Y,await w(Y.path).then((K)=>K?{file:K}:{},(K)=>K instanceof Error?K:Error(String(K)))])));if(!this.#L(J))return;let G;try{G=await Z.custody.discover(J.controller.signal)}catch(Y){if(!this.#L(J))return;for(let K of this.#G.values())if(K.pending)this.#v(K);throw Y}if(!this.#L(J))return;let Q=this.#f(),W=await Promise.all(Q.map((Y)=>Y.hooks&&!Y.closed?this.#n(Y,Y.hooks,G,z??X.get(Y),J):void 0));if(!this.#L(J))return;let H=new Map,U=!0;for(let[Y,K]of Q.entries()){let M=K.hooks,V=W[Y];if(!M||!V)continue;if("error"in V){let{error:C}=V;if(U=!1,this.#v(K),V9(K.path,C))this.#Z.debug("claustrum hub member commit refused",{member:K.provider});else H.set(K.provider,C);continue}let{roster:L}=V;if(!this.#L(J))return;if(L?.view!==G.view)U=!1,this.#v(K);else K.pending=void 0;if(!L)continue;if(this.#u(M,L)){U=!1,this.#v(K);continue}if(K.seen=JSON.stringify(U9(L)),!K.closed)M.install(L)}if(!this.#L(J))return;if(this.#w(),U)this.#M=Object.freeze({view:G.view,...G.grantReach&&{reach:G.grantReach},refused:Object.freeze([...G.refused??[]]),notMine:G.notMine??0});return this.#B=(this.#$.now??Date.now)(),{errors:H}}async#n($,Z,J,z,X){let G={...J,credentials:J.credentials.filter((Q)=>Q.member===$.provider),skipped:J.skipped.filter((Q)=>Q.member===$.provider)};try{if(!z)throw _0("Claustrum hub member has no base view");if(z instanceof Error)throw z;let Q=z.file?void 0:await this.#o($);return{roster:await R1({path:$.path,custody:{discover:async()=>G},isActive:()=>this.#L(X)&&this.#V===!0,signal:X.controller.signal,projection:()=>({...Z.projection(),...Q&&{seed:Q}}),listedOver:{view:z.file?.view}})}}catch(Q){return{error:Q}}}async#i(){for(let $ of[t8(this.#D),this.#D,Q1(this.#D,this.#I)])await r0($,{},"roster directory")}async#o($){let Z=`${$.provider}.json`,J=[Q1(this.#D,Z)];try{for(let X of await o8(this.#D))if(X!==this.#I&&Z6.test(X))J.push(Q1(this.#D,X,Z))}catch{}let z;for(let X of J)try{let G=(await r8(X)).mtimeMs,Q=await w(X);if(Q&&(!z||G>z.modified))z={modified:G,roster:Q}}catch{}return z&&J$(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(a0/J)),X=Z<=R9?1:Math.min(2**(Z-R9),z);$.pending={failures:Z,wait:X-1}}#w(){let $=this.#X?.custody;if(!$)return;$.retain(this.#f().flatMap((Z)=>Z.hooks?.roster()?.rows??[]))}async#r(){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.#V!==!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=T9(G);if(Z.seen=X,z.install(J),T9(z.roster())!==Q)this.#w()}}#t(){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>=a0}#e(){let $=this.#H,Z=$&&this.#Q.get($);if(!$||!Z||!this.#O($)||this.#V!==!0)return;let J=Z.generation;if(!this.#L(J)||this.#Y?.generation===J)return;let z=Z.custody.watchRoster({view:()=>this.#M?.view,onView:()=>this.#F((async()=>{while(this.#q)await this.#q.promise.catch(()=>{});if(!this.#L(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.#r(),this.#t())await this.#l();this.#e()}}catch(Z){this.#c(Z)}if(this.#W.signal.aborted)return;let $=this.#$.pollIntervalMs??5000;if($<=0)return;this.#N=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#N=void 0,this.#F(this.#a())},$),this.#N.unref?.()}start(){if(this.#_)return;this.#C(),this.#_=!0,this.#F(this.#a())}async refresh(){this.#d(await this.#m())}refusals(){let $=this.#M;return $&&Object.freeze({view:$.view,refused:$.refused,notMine:$.notMine})}grantReach(){return this.#M?.reach}watchState(){let $=this.#Y;return $&&this.#L($.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(_0("Claustrum discovery hub is closed")),this.#N)(this.#$.clearTimeoutImpl??clearTimeout)(this.#N);this.#N=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??=e0(this.#P,this.#J),await this.#K}}var h0={opencode:Q6,pi:W6};function V$($,Z){let{tokenPath:J}=b9($,Z);return{stateDir:G6(J),host:$,override:J}}function B$($,Z){return H6($==="pi"?Z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0,$==="pi"?{...Z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:Z)}class v0 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 j$($,Z){let J=Z??h0[$];if(typeof J!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(J))throw new v0("permission-refused");return["auth","grant","--principal",`enrolled:${J}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"]}async function f9($,Z){try{await Z.processFence();let J=await n1(Z.paths??b9($,Z.env),h0[$]);if(J.state==="blocked")throw new v0("permission-refused");let z=J.state==="approved"?J.approvedName:void 0,X=j$($,z);if((await Z.runner.run(Z.ckBinary??"ck",X,{env:Z.env})).exitCode!==0)throw new v0("permission-refused");return z}catch{throw new v0("permission-refused")}}import{createHash as B6}from"node:crypto";import{lstat as j6,mkdir as M6,readFile as d9}from"node:fs/promises";import{dirname as D6}from"node:path";import{assertHostsStopped as N6,canonicalPath as D$,createNativeAccountRuntime as L6,custodyTombstoneOAuth as P6,inspectNativeHostAuthEntry as l9,NativeMigrationError as m0,nativeJournalMayAdoptLaterHostLogin as C6,nativePoolHoldsAccountData as O6,prepareNativeMigration as A6,readNativeEnrollmentMode as a9,readNativeMigrationJournal as I6,releaseNativeMigrationPreflight as _6,requireNoSupervisedAuthContentSnapshot as R6,runNativeMigration as S6,writeNativeHostAuth as k6}from"@cortexkit/anthropic-auth-core";import{dirname as Y6,join as x9,resolve as M$}from"node:path";import{ACCOUNT_FILE_NAME as y9,ACCOUNT_STATE_FILE_NAME as U6,canonicalPath as g9,getStickyRoutingStatePath as q6,resolveLocalRoutingDestination as K6,resolveNativePoolPaths as F6}from"@cortexkit/anthropic-auth-core";async function M0($,Z){let J=$==="pi"?m9(Z):v9(Z),z=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),X=M$(z||x9(J,y9)),G=M$(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(X.endsWith(y9)?x9(Y6(X),U6):`${X}.state.json`)),Q=await F6(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"?w9(Z):h9(Z),routingSourcePath:M$(W||q6(X)),routingDestinationPath:K6($,Q,Z)}}async function u9($){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 g9(G);if(z.has(Q)&&!(X===9&&Q===await g9(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 V6}from"node:util";var c9=new WeakMap;function p9($){return typeof $==="object"&&$!==null?c9.get($):void 0}function W1($){if(!$||typeof $!=="object"||V6.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 n extends Error{constructor($){super($);this.name="SetupRefusal",c9.set(this,$)}}var N$="OpenCode's separate Anthropic login is not used. Add that account through /claude Accounts if needed, or remove the separate login from OpenCode.";function s9($){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 L$($,Z){let J=[];for(let z of $)if(await a9(z,Z)!=="local")J.push(s9(z));if(J.length)throw new n(J.join(`
|
|
13
|
-
`))}function
|
|
2
|
+
import{y as N3}from"./index-m4dazzyf.js";import{A as X7,B as G7,C as w9,D as u9,E as c9,F as p9,G as Q7}from"./index-naff9h33.js";import{ia as l4,ja as kZ,ka as T3}from"./index-71temqvq.js";var o$=kZ((Bq,c4)=>{var i$={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"},TZ={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},EZ={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?i$.up():"");if($)Z+=i$.left;return Z}};c4.exports={cursor:i$,scroll:TZ,erase:EZ,beep:"\x07"}});import{stdin as NJ,stdout as LJ}from"node:process";import{createInterface as PJ}from"node:readline/promises";import{authorize as CJ,createNativeAccountRuntime as OJ,decideOpenCodeStateLayoutOnce as AJ,exchange as IJ,formatNativeAccountState as _J,generateRelayToken as RJ,getAccountStoragePath as SJ,isValidApiBaseURL as kJ,readNativeEnrollmentMode as TJ,resolveNativePoolPaths as EJ,WORKER_SCRIPT as bJ}from"@cortexkit/anthropic-auth-core";import{randomUUID as d6}from"node:crypto";import{constants as X3}from"node:fs";import{lstat as l6,mkdir as a6,open as s6}from"node:fs/promises";import{homedir as n6}from"node:os";import{isAbsolute as i6,join as G4}from"node:path";import{types as b$}from"node:util";import{anthropicAuthStateRoot as o6,createProviderErrorRedactor as Q4,createWindowsOwnerOnly as r6,ensureWindowsOwnerOnlyDirectory as t6,formatLogLine as e6,HOLDER_REGISTRATION_ERROR_MESSAGES as $5,isOwnerOnly as Z5,isSecretKey as J5,isStateLayoutRefusalCode as z5,NativeMigrationError as X5,NativePiAuthSlotError as G5,PRIVATE_FILES_UNAVAILABLE_MESSAGE as W4,RELOCATED_MESSAGE as Q5,STATE_LAYOUT_REFUSAL_CODES as W5,STATE_LAYOUT_REFUSAL_PUBLIC_MESSAGES as H5,setupEnrollment as Y5,stateLayoutRefusalPublicMessage as U5}from"@cortexkit/anthropic-auth-core";import{readFile as f6}from"node:fs/promises";import{assertHostsStopped as x6,createNativeAccountRuntime as y6,discoverNativeVaultInventory as g6,inspectNativeHostAuthEntry as _$,NativePiAuthSlotError as v6,nativePiAuthSlotPaths as h6,openNativePiAuthSlot as S$,readNativeEnrollmentMode as m6,requireNoSupervisedAuthContentSnapshot as w6}from"@cortexkit/anthropic-auth-core";import{dirname as H6}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as Y6,CLAUSTRUM_PI_ENROLLMENT_NAME as U6,getHostClaustrumEnrollmentPaths as y9,resolveClaustrumConnectionPath as q6}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as IQ}from"@cortexkit/claustrum-client";import{ClaustrumClient as XQ}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as K7}from"@cortexkit/claustrum-client";import{SocketClosedError as F7,SocketTimeoutError as B7,SubcCallError as V7}from"@cortexkit/subc-client";class O extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var I3=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 r extends O{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function N0($){if($ instanceof r||$ instanceof F7||$ instanceof B7)return"unreachable";let Z=$ instanceof K7||$ instanceof V7?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(I3,Z))return"answered";return I3[Z]}import{resolve as Q2}from"node:path";import{storeIdentity as rJ}from"@cortexkit/claustrum-client";import{SubcClient as eJ}from"@cortexkit/subc-client";var l0=300000,v1=300000,_3=1000;class V1{#$;#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 h1{#$;#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 m1{#$;#Z=new V1;#J;#W="polling";#G;#Q;#X=!1;#z;#D=!1;#H=0;constructor($){this.#$=$,this.#J=new h1(async()=>{let Z=this.#D;if(this.#D=!1,Z||this.#z!==this.#$.view())await this.#$.discover(this.#z??"")},(Z)=>{if(!this.#X)this.#$.onError?.(Z)})}get mode(){return this.#W}start(){if(this.#X||this.#G||this.#Q)return;if(typeof this.#$.client.watchScoped!=="function"){this.#Y("fallback","client-without-watch");return}this.#V(!1)}stop(){if(this.#X)return;if(this.#X=!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?.($)}#K($,Z){this.#Q=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#Q=void 0,!this.#X)Z()},$),this.#Q.unref?.()}async#V($){let Z;try{Z=await this.#$.enrollmentToken()}catch(Q){if(this.#X)return;this.#$.onError?.(Q),this.#j("token-unreadable");return}let J=this.#$.client.watchScoped;if(this.#X||this.#G||!J)return;this.#Z.restart(),this.#D=$;let z,X;try{X=J.call(this.#$.client,(Q)=>{if(this.#X||!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.#D=!0;this.#z=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.#X||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.#K(z,()=>void this.#V(!0));return}this.#j(Z.kind)}#j($){this.#Y("fallback",$),this.#K(300000,()=>void this.#V(!1))}}var u1=60000,W2=4*u1,j7=2*u1,R3=new Map,w1=new Map;function j1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function M7($){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 D7($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class H2{transport;key;#$=[];#Z=!1;#J=new Set;#W=new Map;#G=new h1(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.#W.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#J.clear()}},()=>{});#Q=new V1;#X="polling";#z=0;#D=0;#H=new Map;#Y;#K;#V={};#U=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#G.running)return this.#G.running;if(this.#X==="watching")return Promise.resolve();for(let[J,z]of w1)if($-z>=u1)w1.delete(J);let Z=w1.get(this.key);if(Z!==void 0&&$-Z<u1)return Promise.resolve();return w1.set(this.key,$),this.#G.request()}watchMode(){return this.#X}watch($={}){this.#z++;let Z=$.provider;if(Z===void 0)this.#D++;else this.#H.set(Z,(this.#H.get(Z)??0)+1);if(this.#z===1)this.#V=$,this.#L();let J=!1;return()=>{if(J)return;if(J=!0,Z===void 0)this.#D--;else{let z=(this.#H.get(Z)??1)-1;if(z>0)this.#H.set(Z,z);else this.#H.delete(Z)}if(--this.#z===0)this.#j()}}#j(){if(this.#K)(this.#V.clearTimeoutImpl??clearTimeout)(this.#K);this.#K=void 0;let $=this.#Y;this.#Y=void 0,$?.handle?.stop(),this.#X="polling"}#M($){this.#K=(this.#V.setTimeoutImpl??setTimeout)(()=>{if(this.#K=void 0,this.#z>0&&!this.#Y)this.#L()},$),this.#K.unref?.()}#L(){let $=this.transport.watchUsage;if(!$){this.#X="fallback";return}this.#X="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.#X="watching";if($.notices===2)this.#U=0;let J=M7(Z);if(!J)this.#Q.restart();if(!(J?this.#Q.continuous(J):!1)||J?.provider===void 0||this.#D>0||this.#H.has(J.provider))this.#G.request()}#C($,Z){if(this.#Y!==$)return;this.#Y=void 0;let J=D7(Z);if(J==="unknown_method"||J==="usage_watch_limit"){this.#X="fallback";return}if($.notices>0){let z=Math.min(_3*2**Math.min(this.#U,16),v1);this.#U++,this.#X="polling",this.#M(z);return}if(this.#X="fallback",this.#G.request(),Z===void 0||N0(Z)==="unreachable")this.#M(v1)}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>=W2)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+W2||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>=j7?"unreachable":"cold"}}}function S3($,Z){let J=JSON.stringify([Q2($.connectionFile),Q2(Z)]),z=R3.get(J);if(!z)z={source:new H2($,J),refs:0},R3.set(J,z);z.refs++;let X=!1;return{source:z.source,release(){if(X)return;if(X=!0,--z.refs===0)R3.delete(J)}}}import{ClaustrumCredentialError as YQ}from"@cortexkit/claustrum-client";import{appendFileSync as E7,chmodSync as b7,existsSync as b3,renameSync as N2,statSync as f7}from"node:fs";import{open as x7}from"node:fs/promises";import{dirname as y7,resolve as g7}from"node:path";import{randomUUID as K2}from"node:crypto";import{lstat as F2,readFile as B2,rename as N7,unlink as Y2}from"node:fs/promises";import{tmpdir as L7}from"node:os";import{dirname as L0,join as P7,resolve as t}from"node:path";var _=process.platform==="win32",U2=new Set;function k3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var q2;var V2="native-addon-unavailable";function j2($){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:$}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:V2})}function C7($,Z){return Z instanceof $.PrivateFilesUnavailableError||Z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function O7($){try{await $.verifyPrivatePath(P7(L7(),`.common-auth-private-files-probe-${K2()}`),"file")}catch(Z){if(C7($,Z))throw j2(Z)}}function a0(){return q2??=import("@cortexkit/private-files").then(async($)=>{if(_)await O7($);return $},($)=>{throw _?j2($):$}),q2}class w extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor($,Z,J){let z=J;super(z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"?`Private file refused at ${Z}: ${$} (${V2}). 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=k3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}async function i($,Z,J){try{return await J()}catch(z){if(z instanceof w)throw z;throw new w($,Z,z)}}var A7;async function F0($,Z){$=t($),Z??=A7,await i($,"safe-parent",async()=>{let J=await(await a0()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await F2($);throw new w(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function d($,Z,J=!1){if($=t($),Z==="directory")return F0($);await i($,"verify",async()=>{let z=await a0(),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 F0(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&&!U2.has($))U2.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function G0($,Z=!1,J){$=t($),await i($,"directory",async()=>{let z=await a0();try{return await F2($),await F0($,J)}catch(G){if(k3(G)!=="ENOENT")throw G}let X=L0($);if(X===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await G0(X,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(k3(G)!=="EEXIST")throw G}await F0($,J)})}async function Z0($,Z=!1){if(!_)return B2($,"utf8");return(await I7($,Z)).toString("utf8")}async function I7($,Z=!1){if(!_)return B2($);if($=t($),Z)await F0(L0($)),await d($,"file",!0);return i($,"read",async()=>(await a0()).readOwnerOnly($))}async function s0($,Z){await F0(L0(t($))),await i($,"create",async()=>{await(await a0()).createPrivateFile(t($),Z)})}async function M2($){await F0(L0(t($))),await i($,"directory-create",async()=>{await(await a0()).createOwnerOnly(t($),{kind:"dir"})})}async function E3($,Z,J={}){$=t($),Z=t(Z);let z=J.now??(()=>performance.now()),X=z(),G=J.deadline??1/0,Q,W=[0,10,20,40,80,100],H,q=0;for(let U of W){let M=Math.min(Q??1/0,G);if(z()>=M)break;if(U)await(J.sleep??((L)=>new Promise((C)=>setTimeout(C,L))))(Math.min(U,Math.max(0,M-z())));if(z()>=M)break;let B=z();if(await J.beforeRename?.(),Q!==void 0)Q+=z()-B;if(z()>=G)break;q++;try{return await(J.rename??N7)($,Z),{attempts:q,elapsedMs:z()-X}}catch(L){H??=L;let C=L;if(!(C.win32Code!==void 0?C.win32Code===32||C.win32Code===33:["EBUSY","EPERM","EACCES"].includes(C.code??"")&&!C.reason))break;Q??=z()+500}}let Y=new w(Z,"rename",H??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw Y.attempts=q,Y.elapsedMs=z()-X,Y}async function n0($,Z,J={}){$=t($),await G0(L0($));try{await d($,"file",!0)}catch(q){if(q.code!=="ENOENT")throw q}let z=t(J.stagePath??`${$}.${K2()}.tmp`);if(L0(z)!==L0($))throw new w($,"stage-directory",{code:"EXDEV"});let X=!1,G=!1,Q={attempts:0,elapsedMs:0},W="stage-create",H=(q)=>{try{J.onOutcome?.({path:$,stage:q?.stage??"published",published:G,fileDurable:G,durabilityConfirmed:!1,attempts:q?.attempts??Q.attempts,elapsedMs:q?.elapsedMs??Q.elapsedMs,...q&&{code:q.code,win32Code:q.win32Code}})}catch{}};try{if(await s0(z,Z),X=!0,W="before-rename",Q=await E3(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 w($,"directory-sync-unsupported",{code:"ENOTSUP"});H()}catch(q){let Y=q instanceof w?q:new w($,W,q);if(Y.published=G,Y.fileDurable=G,G)Object.assign(Y,Q);if(X){try{await Y2(z)}catch{Y.orphanPath=z}X=!1}throw H(Y),Y}finally{if(X)await Y2(z).catch(()=>{})}}var _7=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,R7=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function S7($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function i0($={}){let Z=[R7,...$.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 _7.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 q of["code","status","cause"])if(Q[q]!==void 0)W.push([q,Q[q]]);let H=new Set(W.map(([q])=>q));for(let q of Object.entries(G))if(!H.has(q[0]))W.push(q);return W}function X(G,Q,W,H=0){if(typeof G==="string")return Z.reduce((q,Y)=>q.replace(Y,"***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((U)=>X(U,Q,W,H));let q=S7(G);if(q&&H>=8)return"[Truncated]";let Y=q?H+1:H;return Object.fromEntries((q?z(G):Object.entries(G)).map(([U,M])=>[U,Q&&J(U)?"***REDACTED***":X(M,Q,W,Y)]))}finally{W.delete(G)}}return{redact:(G)=>X(G,!0,new WeakSet),redactStrings:(G)=>X(G,!1,new WeakSet)}}var D2=i0(),k7=D2.redact,T7=D2.redactStrings;var c1={error:0,warn:1,info:2,debug:3,trace:4},P2=5242880,C2=3;function f3($){try{b7($,384)}catch{}}function v7($){try{if(!(b3($)&&f7($).size>=P2))return;for(let J=C2-1;J>=1;J--)if(b3(`${$}.${J}`)){let z=`${$}.${J+1}`;N2(`${$}.${J}`,z),f3(z)}let Z=`${$}.1`;N2($,Z),f3(Z)}catch{}}async function B0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await i(Z,"log-close",()=>J.close())}async function L2($,Z){await G0(y7(Z));try{await d(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await s0(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await d(Z,"file",!0)}}return $.handle=await i(Z,"log-open",()=>x7(Z,"a")),$.file=Z,$.handle}async function h7($,Z,J){Z=g7(Z);try{if($.file!==Z)await B0($);let z=$.handle??await L2($,Z);if((await i(Z,"log-stat",()=>z.stat())).size>=P2){await B0($);for(let G=C2-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 E3(Q,W),await d(W,"file")}z=await L2($,Z)}await i(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await B0($).catch(()=>{}),z}}function m7($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function w7($){let Z,J,z,X=i0(),G,Q=[],W,H=Promise.resolve(),q,Y={};function U(F){let K=H.then(F);return H=K.catch((V)=>{q=V}),K}function M(F){if(_&&F.file!==Z)U(()=>B0(Y)).catch(()=>{});Z=F.file,J=F.level,X=i0(F),G=F.captureSink}function B(F){if(F===void 0||F in c1)z=F}function L(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function C(){if(z)return z;let F=typeof J==="function"?J():J;if(F&&F in c1)return F;return"info"}function A(F=!0){if(W)clearTimeout(W),W=void 0;if(!Q.length){if(_)return U(async()=>{if(F)await B0(Y);if(q)throw q});return}let K;try{K=L()}catch{if(Q=[],_&&F)return U(()=>B0(Y));return}let V=Q.join("");if(Q=[],!K){if(_&&F)return U(()=>B0(Y));return}if(_)return U(async()=>{try{await h7(Y,K,V)}finally{if(F)await B0(Y)}});try{if(v7(K),b3(K))f3(K);E7(K,V,{encoding:"utf8",mode:384})}catch{}}function I(){if(!W)W=setTimeout(()=>{W=void 0;let F=A(!1);if(F instanceof Promise)F.catch(()=>{})},500)}function R(F,K,V,P){if(Z===void 0&&G===void 0)return;try{if(c1[K]>c1[C()])return;let x=X.redactStrings(V),k;try{k=X.redact(P)}catch{k="[unserializable]"}let y=`[${new Date().toISOString()}] ${K.toUpperCase()} [${F}] ${x}`+(P===void 0?"":m7(k))+`
|
|
3
|
+
`;try{G?.({channel:F,level:K,message:x,data:k})}catch{}if(Z===void 0)return;if(Q.push(y),Q.length>=50){let $0=A(!1);if($0 instanceof Promise)$0.catch(()=>{})}else I()}catch{}}function h(F){return{error:(K,V)=>R(F,"error",K,V),warn:(K,V)=>R(F,"warn",K,V),info:(K,V)=>R(F,"info",K,V),debug:(K,V)=>R(F,"debug",K,V),trace:(K,V)=>R(F,"trace",K,V)}}function m(){if(_)U(()=>B0(Y)).catch(()=>{});if(q=void 0,Q=[],W)clearTimeout(W),W=void 0;Z=void 0,J=void 0,z=void 0,X=i0(),G=void 0}if($)M($);return{configure:M,createLogger:h,setLogLevel:B,flushLogs:A,reset:m}}var u7=w7();function Q0($){return u7.createLogger($)}function S0($){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 t2}from"@cortexkit/claustrum-client";import{createHash as Z8,randomBytes as J8,randomUUID as z8}from"node:crypto";import{constants as y2}from"node:fs";import{chmod as X8,mkdir as G8,open as m2,readFile as v3,realpath as Q8,rename as W8,stat as w2,unlink as m3}from"node:fs/promises";import{basename as H8,dirname as T0,extname as ZX,isAbsolute as JX,join as Y8,resolve as zX}from"node:path";import{ClaustrumCredentialError as U8,ClaustrumClient as GX,writeEnrollmentTokenFile as q8}from"@cortexkit/claustrum-client";import{lstat as c7}from"node:fs/promises";import{resolve as p7}from"node:path";async function d7($){try{let Z=await c7($);return Z.isFile()?Z:void 0}catch(Z){return Z.code==="ENOENT"?"absent":void 0}}function l7($,Z){if($==="absent"||Z==="absent")return $===Z;return $.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs&&$.ctimeMs===Z.ctimeMs}class M1{#$=new Map;async read($,Z,J){let z=$.map((q)=>p7(q)),X=JSON.stringify(z),G=await Promise.all(z.map(d7)),Q=G.every((q)=>q!==void 0)?G:void 0,W=this.#$.get(X);if(Q&&W&&Q.every((q,Y)=>{let U=W.identities[Y];return U!==void 0&&l7(q,U)}))return J?.(Q),W.value;this.#$.delete(X);let H=await Z(z);if(Q){if(this.#$.size>=64){let q=this.#$.keys().next().value;if(q!==void 0)this.#$.delete(q)}this.#$.set(X,{identities:Q,value:H})}return H}}import{randomUUID as O2}from"node:crypto";import{mkdir as a7,open as A2,rename as s7,rm as n7}from"node:fs/promises";import{dirname as I2}from"node:path";class p1 extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function D1($,Z,J={}){await _2($,Z,J)}async function _2($,Z,J,z){if(_)return n0($,J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
4
|
+
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??O2)()}.tmp`,onRenamed:z,durable:J.durable,durability:J.durability,onOutcome:J.onOutcome});await a7(I2($),{recursive:!0});let X=`${$}.${(J.stageName??O2)()}.tmp`,G,Q=!1;try{if(G=await A2(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 p1(W)}if(await G.close(),G=void 0,await J.beforeRename?.(),await s7(X,$),Q=!1,z?.(),J.durable){let W=await A2(I2($),"r");try{await W.sync()}catch(H){throw new p1(H)}finally{await W.close()}}}finally{if(await G?.close().catch(()=>{}),Q)await n7(X,{force:!0}).catch(()=>{})}}var i7=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 d1}from"node:crypto";import{lstat as g3,mkdir as R2,open as f2,readFile as S2,rename as k2,rm as L1,stat as l1}from"node:fs/promises";import{dirname as y3,join as T2}from"node:path";function N1($,Z){return`${$}.${Z}.lock`}class P0 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class V0 extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function x3($,Z,J){let z=performance.now();for(;;){Z.signal?.throwIfAborted();let X=await j0({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(Z.signal)}let G=Z.timeoutMs-(performance.now()-z);if(G<=0)throw new P0({target:$,name:Z.name,timeoutMs:Z.timeoutMs});await new Promise((Q)=>setTimeout(Q,Math.min(25,Math.ceil(G))))}}async function E2($,Z){let J=await f2($,"wx",384),z;try{z=await J.stat()}catch{z=void 0}try{await J.writeFile(Z,"utf8")}catch(X){try{let G=await g3($).catch(()=>{return});if(z&&G&&G.dev===z.dev&&G.ino===z.ino)await L1($,{force:!0}).catch(()=>{})}catch{}throw X}finally{await J.close()}}var o7=globalThis.setTimeout.bind(globalThis),r7=globalThis.clearTimeout.bind(globalThis);function x2($){let Z=$?.code;return Z==="ENOENT"||!_&&(Z==="EINVAL"||Z==="ENOTDIR")}var b2;function t7($,Z){if($.dev!==Z.dev||$.ino!==Z.ino)return!1;if($.ino===0&&$.birthtimeMs!==Z.birthtimeMs)return!1;return!0}var e7=1000;function j0($){return $8({...$,now:Date.now})}async function $8($){let Z=N1($.path,$.name),J=T2(Z,"owner.json"),z=d1(),X=$.now??Date.now,G=null,Q=!1,W=!1,H,q,Y=new Promise((j)=>{q=j});function U(j){try{let D=$.onRenewalTimer?.(j);if(D&&(typeof D==="object"||typeof D==="function")&&"then"in D&&typeof D.then==="function")Promise.resolve(D).catch(()=>{})}catch{}}function M(){if(!G)return;r7(G),G=null,U("cancelled")}function B(j,D){if(H||Q)return;H=Object.freeze({reason:j,expectedOwnerId:z,...typeof D?.ownerId==="string"?{observedOwnerId:D.ownerId}:{},...typeof D?.expiresAt==="number"?{observedExpiresAt:D.expiresAt}:{}}),M(),q(H)}let L,C=null,A=`${Z}.evicting`,I=T2(A,"owner.json"),R=d1(),h=5000,m=8;async function F(){if(_)try{return JSON.parse(await Z0(Z,!0))}catch(j){if(j.code!=="EISDIR"&&j.reason!=="wrong-kind")throw j;return await d(Z,"directory",!0),JSON.parse(await Z0(J,!0))}try{return JSON.parse(await S2(Z,"utf8"))}catch(j){if(j.code!=="EISDIR")throw j;return JSON.parse(await S2(J,"utf8"))}}async function K(){if(_){let g=await F(),v=Number(g?.expiresAt)-X();await n0(Z,`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
6
|
+
`,{deadline:performance.now()+Math.max(0,v),beforeRename:async()=>{let B1=await F();if(B1?.ownerId!==z||!(Number(B1?.expiresAt)>X())||!await p())throw new V0({target:$.path,name:$.name})}});return}let j=`${Z}.${d1()}.tmp`,D,N=!1;try{D=await f2(j,"wx",384),N=!0,await D.writeFile(`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
7
|
+
`,"utf8"),await D.chmod(384),await D.close(),D=void 0;let g=await F();if(g?.ownerId!==z||!(Number(g?.expiresAt)>X())||!await p())throw new V0({target:$.path,name:$.name});await k2(j,Z),N=!1}finally{if(await D?.close().catch(()=>{}),N)await L1(j,{force:!0}).catch(()=>{})}}async function V(){let j=`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
8
|
+
`;if(_)await s0(Z,j);else await E2(Z,j)}async function P(j){let D=j.code;if(D!=="EEXIST"&&D!=="EISDIR")return!1;if(_){if($.onStep)await $.onStep("lease-contention-read-ready");try{if(D==="EISDIR")await d(Z,"directory",!0),await Z0(J,!0);else await F()}catch(N){if(N.code!=="ENOENT")throw N}}return!0}async function x(){if(_)await G0(y3(Z));try{return await V(),!0}catch(j){let D=j.code;if(await P(j))return!1;if(D==="ENOENT"){if(_)await G0(y3(Z));else await R2(y3(Z),{recursive:!0});try{return await V(),!0}catch(N){if(await P(N))return!1;throw N}}throw j}}async function k(){await new Promise((j)=>setTimeout(j,Math.floor(Math.random()*4)))}async function y(j=!0){if(j&&$.onStep)await $.onStep("lock-read-ready");let D;try{D=await F()}catch(g){if(_&&g.code!=="ENOENT")throw g}let N=Number(D?.expiresAt);if(Number.isFinite(N)&&N>X())return{status:"live"};if(typeof D?.ownerId==="string"&&Number.isFinite(N))return{status:"stale",identity:{kind:"owner",ownerId:D.ownerId,expiresAt:N}};try{let g=await l1(Z),v=Number.isFinite(N)?N:g.mtimeMs+$.ttlMs;if(v>X())return{status:"live"};return{status:"stale",identity:{kind:"stat",dev:g.dev,ino:g.ino,mtimeMs:g.mtimeMs,expiresAt:v}}}catch(g){if(g.code==="ENOENT"){if($.onStep)await $.onStep("lock-missing");return{status:"missing"}}throw g}}function $0(j,D){if(D.status!=="stale")return!1;let N=D.identity;if(j.kind==="owner"&&N.kind==="owner")return j.ownerId===N.ownerId&&j.expiresAt===N.expiresAt;return j.kind==="stat"&&N.kind==="stat"&&j.dev===N.dev&&j.ino===N.ino&&j.mtimeMs===N.mtimeMs&&j.expiresAt===N.expiresAt}async function p(){try{return JSON.parse(await Z0(I,_))?.ownerId===R}catch(j){if(_&&j.code!=="ENOENT")throw j;return!1}}async function c(j){if(_)await i(j,"remove",()=>L1(j,{recursive:!0,force:!0}));else await L1(j,{recursive:!0,force:!0}).catch(()=>{})}async function a(){if(await p())await c(A)}async function q0(j){if(!j)return!1;let D;try{let N=await g3(A);D={dev:N.dev,ino:N.ino,birthtimeMs:N.birthtimeMs}}catch{return!1}if(!t7(j,D))return!1;try{return await l1(I),!0}catch(N){if(N.code!=="ENOENT")return!0}try{await c(A)}catch{}return!0}async function y1(){if(_)await M2(A);else await R2(A);let j;try{let D=await g3(A);j={dev:D.dev,ino:D.ino,birthtimeMs:D.birthtimeMs}}catch{j=void 0}try{await b2?.beforeOwnerWrite?.(A,I);let D=await b2?.failOwnerWrite?.(A,I);if(D!==void 0)throw D;let N=`${JSON.stringify({ownerId:R,createdAt:X()})}
|
|
9
|
+
`;if(_)await s0(I,N);else await E2(I,N)}catch(D){let N=await q0(j);if(x2(D)&&!N)return!1;try{await a()}catch{}throw D}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function p0(){let j;try{j=await l1(A)}catch(N){if(N.code==="ENOENT")return"missing";throw N}if(_)try{await d(A,"directory",!0)}catch(N){if(N.code==="ENOENT")return"missing";throw N}if(j.mtimeMs+h>X()){let N=!0;try{await l1(I)}catch(g){if(g.code==="ENOENT")N=!1;else return"fresh"}if(N)return"fresh";if(j.mtimeMs+e7>X())return"fresh"}if($.onStep)await $.onStep("stale-marker-stat");let D=`${A}.${d1()}`;try{await k2(A,D)}catch(N){if(N.code==="ENOENT")return"missing";throw N}if($.onStep)await $.onStep("stale-marker-claimed");return await c(D),"recovered"}async function g1(j){try{if(!await y1())return!1}catch(D){if(D.code==="EEXIST"){if(_)try{await d(A,"directory",!0),await Z0(I,!0)}catch(N){if(N.code!=="ENOENT")throw N}return!1}throw D}try{await j()}finally{await a()}return!0}async function d0(){for(let j=0;j<m;j++){if($.onStep)await $.onStep("relinquish-read");let D;try{D=await F()}catch(N){if(_)throw N;return}if(D?.ownerId!==z)return;try{await L1(Z,{recursive:!0,force:!0});return}catch(N){if(_)throw N;await k()}}}function T(){if(!$.renew||Q||H)return;let j=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=o7(()=>{G=null;let D=(async()=>{let N=!Q;try{if(!await g1(async()=>{let v=await F(),B1=X();if(Q||H){N=!1;return}if(v?.ownerId!==z){B("taken-over",v),N=!1;return}if(!(Number(v?.expiresAt)>B1)){B("expired",v),N=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(Q||H){N=!1;return}if(!await p())return;if($.onStep)await $.onStep("renewal-write-fenced");if(Q||H){N=!1;return}if(!await p())return;if($.onStep)await $.onStep("renewal-write-ready");if(Q||H){N=!1;return}if(await K(),$.onStep)await $.onStep("renewal-write-finished");if(!await p()){B("marker-lost"),N=!1,await d0();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(g){if(_&&g instanceof w)L=g,B("renewal-failed"),N=!1;try{let v=await F();if(v?.ownerId!==z)B("taken-over",v);else if(!(Number(v?.expiresAt)>X()))B("expired",v)}catch{B("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(N&&!Q&&!H)T()}})();C=D,D.finally(()=>{if(C===D)C=null})},j),"unref"in G)G.unref();U("scheduled")}function K0(){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 R0=await x();if(!R0)for(let j=0;j<m;j++){if(R0=await x(),R0)break;let D=await y();if(D.status==="live")return K0();if(D.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await y1()){await k();continue}}catch(N){if(N.code!=="EEXIST")throw N;if(await p0()==="fresh")return null;await k();continue}try{let N=await y();if(N.status==="live")return K0();if(!$0(D.identity,N))continue;if(!await p())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await p())return null;let g=await y(!1);if(!$0(D.identity,g))continue;if(await c(Z),!await p())return null;if($.onStep)await $.onStep("stale-lock-removed");if(R0=await x(),!R0)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await p())return await d0(),R0=!1,null;break}finally{await a()}}if(!R0)return null;return T(),{ownerId:z,whenLost:()=>Y,hasLost:()=>H!==void 0,assertOwned:async()=>{if(L)throw L;let j;try{let D=await F();if(j=D,!Q&&!H&&D?.ownerId===z&&Number(D?.expiresAt)>X())return;B(D?.ownerId!==z?"taken-over":"expired",D)}catch(D){if(B("unreadable"),_&&D instanceof w)throw D}throw new V0({target:$.path,name:$.name,expectedOwnerId:z,...typeof j?.ownerId==="string"?{observedOwnerId:j.ownerId}:{},...typeof j?.expiresAt==="number"?{observedExpiresAt:j.expiresAt}:{}})},release:async(j)=>{if(_&&W)return;Q=!0,M(),await C;let D=performance.now()+h+1000,N=5;for(;;){try{let v=!1;if(await g1(async()=>{let X2;try{X2=await F()}catch(G2){if(_&&G2.code==="ENOENT"){v=!0;return}throw G2}if(X2?.ownerId!==z){v=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await p())return;await c(Z),v=!0})){if(_&&!v)throw new w(Z,"release-not-confirmed",{code:"EIO"});W=v;return}if(j?.aborted)return;await p0()}catch(v){if(_)throw v;return}let g=D-performance.now();if(g<=0)break;await new Promise((v)=>setTimeout(v,Math.min(N,g))),N=Math.min(N*2,50)}if(_)throw new w(Z,"release-not-confirmed",{code:"ETIMEDOUT"})}}}var K8=1,s1=16384,u2=30000,w3=/^[0-9a-f]{64}$/,c2="unknown_method",p2=new Set([c2,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),d2=new Set(["pending_queue_full"]);function h3($){if(!($ instanceof U8))return;if(p2.has($.code))return{code:$.code,disposition:"terminal"};if(d2.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function l2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function a1($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function a2($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function P1(){return new O("invalid-state","invalid Claustrum enrollment state")}function u3($){if(!l2($)||$.version!==K8||typeof $.proposedName!=="string"||$.proposedName.length===0)throw P1();if($.phase==="pending"){if(!w3.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!a1($.createdAt)||!a1($.updatedAt))throw P1();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)||!a2($.tokenGeneration)||!a1($.updatedAt))throw P1();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"||!a1($.updatedAt))throw P1();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw P1()}function c3($){if(!l2($)||!w3.test(String($.token??""))||!a2($.token_generation))throw new O("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function s2($){if(!$.isFile())throw new O("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new O("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new O("unsafe-file","Claustrum enrollment file must be owned by the current user")}function g2($){try{return JSON.parse($)}catch{throw new O("invalid-state","Claustrum enrollment file is not valid JSON")}}async function E0($){if(_)try{await G0(T0($));let J=await Z0($,!0);if(Buffer.byteLength(J)>s1)throw new O("unsafe-file","Claustrum enrollment file is too large");return g2(J)}catch(J){if(J.code==="ENOENT")return;throw J}let Z;try{Z=await m2($,y2.O_RDONLY|y2.O_NOFOLLOW)}catch(J){if(J.code==="ENOENT")return;throw new O("unsafe-file","Claustrum enrollment file could not be opened safely")}try{s2(await Z.stat());let J=Buffer.alloc(s1+1),{bytesRead:z}=await Z.read(J,0,J.byteLength,0);if(z>s1)throw new O("unsafe-file","Claustrum enrollment file is too large");return g2(J.subarray(0,z).toString("utf8"))}finally{await Z.close()}}function v2($,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 F8($,Z,J){try{let[z,X]=await Promise.all([v3(J.passwdPath??"/etc/passwd","utf8"),v3(J.groupPath??"/etc/group","utf8")]),G=v2(z,7),Q=v2(X,4);if(!G||!Q)return!1;let W=G.filter((U)=>Number(U[2])===$),H=Q.filter((U)=>Number(U[2])===Z);if(W.length!==1||H.length!==1)return!1;let q=W[0]?.[0],Y=H[0]?.[3]??"";return(Y===""||Y.split(",").every((U)=>U===q))&&!G.some((U)=>Number(U[2])!==$&&Number(U[3])===Z)}catch{return!1}}function n2($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>v3(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function i2($,Z={}){if(!_){let J=process.geteuid?.();if(J===void 0)return;let z=process.getegid?.(),X;try{X=await Q8($)}catch{return}let G;for(;;){let Q=await w2(X).catch(()=>{return});if(Q&&(Q.mode&18)!==0&&(Q.mode&512)===0){if(G===void 0)G=z!==void 0&&await F8(J,z,Z);if((Q.mode&2)!==0||Q.uid!==J||Q.gid!==z||!G)throw new O("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${X}. Another user could replace it. Run: chmod g-w,o-w ${X}`)}let W=T0(X);if(W===X)return;X=W}}try{await F0($,n2(Z))}catch(J){if(!(J instanceof w))throw J;throw new O("unsafe-file",`Claustrum enrollment parent refused: ${J.path} (${J.reason??J.code}). Use a folder that other users cannot write or replace.`)}}async function o0($,Z={},J="enrollment directory"){if(_){await G0($,!1,n2(Z));return}await G8($,{recursive:!0,mode:448});let z=await w2($),X=process.geteuid?.();if(X!==void 0&&z.uid!==X)throw new O("unsafe-file",`Claustrum ${J} must be owned by the current user`);if((z.mode&63)!==0)await X8($,448)}async function k0($,Z,J={}){let z=T0($);await o0(z,J),await i2(z,J);let X=`${JSON.stringify(Z)}
|
|
11
|
+
`;if(Buffer.byteLength(X)>s1)throw new O("invalid-state","Claustrum enrollment state is too large");if(_)return n0($,X);let G=Y8(z,`.${H8($)}.${process.pid}.${z8()}.tmp`),Q,W=!1;try{Q=await m2(G,"wx",384),W=!0,await Q.writeFile(X,"utf8"),await Q.chmod(384),await Q.sync(),await Q.close(),Q=void 0,await W8(G,$),W=!1}finally{if(await Q?.close().catch(()=>{}),W)await m3(G).catch(()=>{})}}var B8=new M1;async function n1($,Z){let J=_?await h2($,Z):await B8.read([$.tokenPath,$.statePath],async([X=$.tokenPath,G=$.statePath])=>h2({tokenPath:X,statePath:G},Z),(X)=>{for(let G of X)if(G!=="absent")s2(G)}),z={...J.status};if(J.usesProposedName&&z.state==="approved")z.proposedName=Z;return z}async function h2($,Z){let J=await E0($.tokenPath),z=J===void 0?void 0:c3(J),X=await E0($.statePath),G=X===void 0?void 0:u3(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:C0(G),usesProposedName:!1}}async function O0($){let Z=await E0($);if(Z===void 0)throw new O("not-enrolled","Claustrum enrollment is not configured");return c3(Z)}function C0($){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 o2(){return new O("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class p3{#$;#Z;#J;#W;#G;#Q;#X;constructor($){this.#X=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#J=$.proposedName,this.#W=$.now??Date.now,this.#G=$.mintSecret??(()=>J8(32).toString("hex")),this.#Q=$.writeTokenFile??q8}async status(){return n1(this.#Z,this.#J)}async resetTerminal(){return r2(this.#Z,this.#J)}async#z($,Z){let J={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#W()};return await k0(this.#Z.statePath,J,this.#X),C0(J)}async reconcile(){await o0(T0(this.#Z.statePath),this.#X);let $=await j0({name:"ceremony",path:this.#Z.statePath,ttlMs:u2,renew:!0});if(!$)return{state:"busy"};try{let Z=await E0(this.#Z.tokenPath),J=Z===void 0?void 0:c3(Z),z=await E0(this.#Z.statePath),X=z===void 0?void 0:u3(z);if(X&&X.proposedName!==this.#J)throw o2();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 k0(this.#Z.statePath,Q,this.#X),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 k0(this.#Z.statePath,Q,this.#X),C0(Q)}if(X&&X.phase!=="pending")return C0(X);if(!X){let Q=this.#W();if(X={version:1,phase:"pending",proposedName:this.#J,requestSecret:this.#G(),createdAt:Q,updatedAt:Q},!w3.test(X.requestSecret))throw new O("invalid-state","invalid minted Claustrum enrollment secret");await k0(this.#Z.statePath,X,this.#X)}if(!X.requestId)try{let Q=Z8("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 k0(this.#Z.statePath,X,this.#X)}catch(Q){let W=h3(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,retryCode:W.code};if(W.code===c2)return await $.assertOwned(),await m3(this.#Z.statePath).catch((H)=>{if(H.code!=="ENOENT")throw H}),{state:"unavailable",proposedName:X.proposedName,code:W.code};return this.#z(X,W.code)}let G=X.requestId;if(!G)return C0(X);try{let Q=await this.#$.enrollPoll({requestId:G,requestSecret:X.requestSecret});if(Q.status==="pending")return C0(X);if(Q.status==="denied"){let H={version:1,phase:"denied",proposedName:X.proposedName,updatedAt:this.#W()};return await k0(this.#Z.statePath,H,this.#X),C0(H)}await o0(T0(this.#Z.tokenPath),this.#X),await i2(T0(this.#Z.tokenPath),this.#X),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 k0(this.#Z.statePath,W,this.#X),C0(W)}catch(Q){let W=h3(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,requestId:G,retryCode:W.code};return this.#z(X,W.code)}}finally{await $.release()}}}async function r2($,Z){await o0(T0($.statePath));let J=await j0({name:"ceremony",path:$.statePath,ttlMs:u2,renew:!0});if(!J)return"busy";try{if(await E0($.tokenPath)!==void 0)return"refused-approved";let z=await E0($.statePath);if(z===void 0)return"idle";let X=u3(z);if(X.proposedName!==Z)throw o2();if(X.phase==="pending")return"refused-pending";return await J.assertOwned(),await m3($.statePath),"reset"}finally{await J.release()}}var d3="claustrum-tombstone:v1:";function r0($,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 t0($,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 e2($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function V8($,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 a3=Q0("claustrum");function n3($,Z,J,z=a3){let X=e2(Z,J);return z.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:J?.recordVersion??null,retry:X,reason:V8(Z,J)}),X}var s3=300000,$9=60000;function l3(){return new O("invalid-material","Claustrum returned invalid credential material")}function j8($){let Z=$.trim();if(Z.startsWith("{")){let J;try{J=JSON.parse(Z)}catch{throw l3()}if(!J||typeof J!=="object")throw l3();let z=J,X=z.access_token??z.access;Z=typeof X==="string"?X:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(d3))throw l3();return Z}function M8($,Z){let J={kind:"not-mine"};if(!$.operations.includes("read"))return J;if(!$.categories.includes(Z.category))return J;if("classify"in Z){let z=D8($),X;switch(z.authMethod){case"apikey":X="api_key";break;case"chatgpt":case"antigravity":case"oauth":X="oauth";break;default:return{kind:"refused",code:"unknown-auth-method"}}let G={credentialId:$.id,credentialType:X,categories:$.categories,refreshAdapter:$.refreshAdapter,...z};if(G.providerIds===void 0)return{kind:"refused",code:"unmapped"};try{let Q=Z.classify(G);if(Q.kind==="not-mine")return J;if(Q.kind==="mine"&&typeof Q.member==="string")return{kind:"mine",type:X,member:Q.member};if(Q.kind==="refused"&&typeof Q.code==="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(Q.code)&&!Q.code.includes(`
|
|
12
|
+
`)&&Z.refusalCodes.includes(Q.code))return{kind:"refused",code:Q.code}}catch{}return{kind:"refused",code:"unclassified"}}if($.credentialType!=="oauth"&&$.credentialType!=="api_key")return J;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 D8($){let Z=$;return{providerIds:Z.providerIds,authMethod:Z.authMethod}}function N8($){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 e0{#$;#Z;#J;#W;#G;#Q;#X;#z=new WeakMap;#D=new WeakMap;#H=new Map;#Y=new WeakMap;#K;#V;#U=!1;#j=new r;#M;#L=!1;#_=-1/0;#C=2000;#q=!1;#N;#A=new Set;#F=new Set;#P;#O;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>O0(Z);else throw new O("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.#X=$.logger??a3,this.#P=r0(this.#X),this.#K=$.setTimeoutImpl??setTimeout,this.#V=$.clearTimeoutImpl??clearTimeout}transportLost($){if(this.#q||this.#U)return;this.#U=!0,this.#j=$ instanceof t2?$:new r,this.#X.warn("serving kept vault receipt",{reason:"unreachable"}),this.#I()}reachable(){if(this.#q||!this.#U)return;if(this.#U=!1,this.#M)this.#V(this.#M);this.#M=void 0,this.#C=2000;for(let $ of this.#H.values())$.since=null;(this.#X.info??a3.info)("vault receipt serving resumed",{reason:"reachable"})}#I(){if(this.#q||!this.#U||this.#M||this.#L)return;this.#M=this.#K(()=>{this.#M=void 0,this.#k(!0)},this.#C),this.#M.unref?.()}#k($=!1){if(this.#q||!this.#U||this.#L)return;if(this.#J()-this.#_<1000){this.#I();return}this.#_=this.#J(),this.#L=!0,this.#T().catch(()=>{if($&&this.#U)this.#C=Math.min(this.#C*2,30000)}).finally(()=>{this.#L=!1,this.#I()})}#B($){if(this.#q)throw new O("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#R($){this.#B($);let Z=this.#Z();this.#F.add(Z);let J;try{J=await Z}finally{this.#F.delete(Z)}if(this.#B($),!/^[0-9a-f]{64}$/.test(J.token)||!Number.isSafeInteger(J.token_generation)||J.token_generation<1)throw new O("invalid-token","Invalid Claustrum enrollment token");return J.token}async#S($,Z){this.#B(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.#B(Z),N0(X)==="unreachable")this.transportLost(X);else this.reachable();if(X instanceof t2)throw X;if(N0(X)==="unreachable")throw new r;throw new O("unavailable","Claustrum scoped operation unavailable")}finally{z?.()}return this.#B(Z),this.reachable(),J}async discover($){let Z=await this.#T($);return this.#N=Z.view,Z}async#T($){let Z,J;try{J=await this.#R($)}catch(Y){throw this.#H.clear(),Y}try{Z=await this.#S(()=>this.#$.listScoped(J),$)}catch(Y){throw this.listFailed(Y),Y}let z=[],X=[],G=0,Q=[],W=new Map;for(let Y of Z.rows){let U=M8(Y,this.#W);if(U.kind==="not-mine"){G++;continue}if(U.kind==="refused"){X.push({...Y.id.trim()&&{credentialId:Y.id},code:U.code});continue}Q.push({row:Y,type:U.type,...U.member!==void 0&&{member:U.member}}),W.set(Y.id,(W.get(Y.id)??0)+1)}let H=[];for(let{row:Y,type:U,member:M}of Q){let B;if(!Y.id.trim())B="empty credential id";else if((W.get(Y.id)??0)>1)B="duplicate credential id";else if(Y.accountId!==void 0&&!Y.accountId.trim())B="blank account identity";else if(!Y.state.trim())B="empty state";if(B){z.push({...Y.id.trim()&&{credentialId:Y.id},...M!==void 0&&{member:M},reason:B});continue}H.push(Object.freeze({credentialId:Y.id,credentialType:U,...M!==void 0&&{member:M},...Y.accountId!==void 0&&{accountIdentity:Y.accountId},state:Y.state,...Y.email!==void 0&&{email:Y.email},...Y.orgName!==void 0&&{orgName:Y.orgName}}))}for(let Y of z)this.#X.warn("skipped malformed vault record",Y);let q=N8(Z);return{view:Z.view,credentials:Object.freeze(H),skipped:Object.freeze(z),..."classify"in this.#W&&{refused:Object.freeze(X),notMine:G},...q&&{grantReach:q}}}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.#x(J.attempt)){this.forget(Z);continue}if(J.since!==null)$=Math.min($??J.since,J.since)}return Object.freeze({active:$!==null,since:$})}#x($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#J()>$9}async authorize($,Z,J="vault"){this.#B(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.#R(Z)}catch(H){throw this.#H.clear(),H}if(this.#U&&Q)return this.#k(),this.#b(z,Q,W,J);try{let H=await this.#f({credentialId:z,credentialType:X,accountIdentity:G},W,Z);return this.#H.set(z,{attempt:H,routeId:J,since:null}),H}catch(H){if(this.#B(Z),N0(H)!=="unreachable")throw this.forget(z),H;return this.#b(z,Q,W,J,H)}}#b($,Z,J,z,X=this.#j){if(!Z||this.#H.get($)!==Z||!this.#x(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.#z.set(G,J),this.#Y.set(G,z),G}async#f($,Z,J){if(!$.credentialId)throw new O("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:z,credentialType:X,accountIdentity:G}=$;if(this.#Q&&G===void 0)throw new O("identity-unasserted","Claustrum dispatch requires a known account identity");let Q=await this.#S(()=>this.#$.getScoped({credentialId:z,enrollmentToken:Z,...X==="oauth"&&{minTtlMs:s3}}),J);if(Q.credentialId!==void 0&&Q.credentialId!==z)throw new O("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()<s3))throw new O("insufficient-validity","Claustrum served credential has insufficient validity");let H=j8(Q.material),q=Q.accountId?.trim()?Q.accountId:void 0;if(this.#Q&&(Q.credentialId===void 0||q===void 0))throw new O("identity-unasserted","Claustrum served credential did not assert its identity");let Y=q===void 0?this.#G?.(H):void 0,U=q??Y;if(G!==void 0&&U!==void 0&&U!==G)throw new O("identity-changed","Claustrum served credential identity changed");let M=U??G,L=Object.freeze(Object.defineProperty({credentialId:z,credentialType:X,...M!==void 0&&{accountIdentity:M},accountIdentitySource:q!==void 0?"asserted":Y!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...Q.credentialId!==void 0&&{assertedCredentialId:Q.credentialId},...q!==void 0&&{assertedAccountIdentity:q},...Q.projectId!==void 0&&{projectId:Q.projectId},recordVersion:Q.recordVersion,expiresAtMs:W},"accessToken",{value:H,enumerable:!1}));return this.#z.set(L,Z),L}async reportFailure($,Z,J){if(Z!==401)return;this.#B();let z=this.#z.get($);if(!z)throw new O("no-receipt","Claustrum failure report requires an original dispatch receipt");let X=this.#Y.get($);if(X!==void 0){this.forget($.credentialId),this.#X.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.#D.get($);if(Q)return Q;let W=this.#S(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:z,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#D.set($,W);try{await W,this.#X.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:J})}catch(H){throw this.#D.delete($),H}}watchRoster($){this.#B();let Z=new m1({client:this.#$,enrollmentToken:()=>this.#R(),view:$.view??(()=>this.#N),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.#X,now:this.#J,setTimeoutImpl:this.#K,clearTimeoutImpl:this.#V});return this.#A.add(Z),Z.start(),{get mode(){return Z.mode},close:()=>{this.#A.delete(Z),Z.stop()}}}close(){if(this.#q)return;if(this.#q=!0,this.#M)this.#V(this.#M);this.#M=void 0;for(let $ of this.#A)$.stop();this.#A.clear(),this.#H.clear(),this.#$.close()}async dispose($=this.#P){this.close(),this.#O??=t0(this.#F,$),await this.#O}}import{resolve as $3}from"node:path";var i3=30000,o3={now:()=>performance.now(),schedule($,Z){let J=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(J),unref:()=>J.unref?.()}}};var b0="all",L8=Object.freeze(["primary"]);function J9($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function Z1($,Z){return JSON.stringify([$,Z])}function A0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function l($){return typeof $==="number"&&Number.isFinite($)}function Z9($){return typeof $==="string"&&$.length>0}function s($,Z,J){return $[Z]===void 0||J($[Z])}function P8($){return l($)&&$>0}function r3($){return typeof $==="string"}function C8($){if(!A0($)||!Z9($.scope)||!Z9($.label))return!1;switch($.kind){case"reading":return l($.checkedAt)&&l($.usedPercent)&&s($,"resetsAt",r3)&&s($,"windowMinutes",P8);case"retired":return l($.retiredAt);case"absent":return l($.checkedAt);default:return!1}}function O8($){if(!A0($)||!l($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&s($,"remainingPercent",l)&&s($,"usedPercent",l)&&s($,"resetsAt",r3)&&s($,"limit",l)&&s($,"used",l)&&s($,"remaining",l)&&s($,"unit",r3)}function z9($){return A0($)&&l($.value)&&Number.isInteger($.value)&&$.value>=0&&l($.checkedAt)}function t3($){return A0($)&&Object.values($).every(z9)}function A8($){return typeof $==="boolean"}function J1($){return A0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&s($,"balance",l)&&s($,"overageLimitReached",A8)&&l($.checkedAt)}function X9($){if(!A0($))return;let Z=Object.entries($).filter(([,J])=>z9(J));return Z.length===0?void 0:Object.fromEntries(Z)}function f0($){if($1($))return $;if(!A0($))return;let{counters:Z,credits:J,...z}=$;if(!$1(z))return;let X=X9(Z),G=J1(J)?J:void 0;return{...z,...X===void 0?{}:{counters:X},...G===void 0?{}:{credits:G}}}function $1($){if(!A0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!C8(J))return!1;let z=Z1(J.scope,J.label);if(Z.has(z))return!1;Z.add(z)}return s($,"budget",O8)&&s($,"counters",t3)&&s($,"credits",J1)}class i1 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function r1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function o1($){return typeof $==="number"&&Number.isFinite($)}function G9($){return $===void 0||typeof $==="string"&&$!==""}function Q9($){return typeof $==="string"&&$!==""}function C1($,Z){return $[Z]===void 0||o1($[Z])}function e3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function I8($){return r1($)&&G9($.scope)&&Q9($.label)&&o1($.usedPercent)&&e3($,"resetsAt")&&($.windowMinutes===void 0||o1($.windowMinutes)&&$.windowMinutes>0)}function _8($){return r1($)&&G9($.scope)&&Q9($.label)}function R8($){if(!r1($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&C1($,"remainingPercent")&&C1($,"usedPercent")&&e3($,"resetsAt")&&C1($,"limit")&&C1($,"used")&&C1($,"remaining")&&e3($,"unit")}function z1($){if(!r1($)||!o1($.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(!I8(X))return!1;let G=Z1(X.scope??b0,X.label);if(z.has(G))return!1;z.add(G)}if(!J.every(_8))return!1;return($.budget===void 0||R8($.budget))&&($.counters===void 0||t3($.counters))&&($.credits===void 0||J1($.credits))}function S8($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function k8($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function T8($,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 E8($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function O1($,Z){let J=$===void 0?void 0:f0($);if($!==void 0&&J===void 0)throw new i1("stored quota map is malformed");if(!z1(Z))throw new i1("quota observation is malformed");let z=J??{limits:[]},X=Z.checkedAt,G=new Map;for(let A of z.limits)G.set(Z1(A.scope,A.label),A);let Q=(A)=>{let I=G.get(A);return I===void 0||X>=J9(I)},W=new Set;for(let A of Z.readings??[]){let I=A.scope??b0,R=Z1(I,A.label);if(W.add(R),!Q(R))continue;G.set(R,{scope:I,label:A.label,kind:"reading",checkedAt:X,usedPercent:A.usedPercent,...A.resetsAt===void 0?{}:{resetsAt:A.resetsAt},...A.windowMinutes===void 0?{}:{windowMinutes:A.windowMinutes}})}for(let A of Z.coverage??[]){let I=A.scope??b0,R=Z1(I,A.label);if(W.has(R)||!Q(R))continue;let h=G.get(R);G.set(R,h===void 0||h.kind==="absent"?{scope:I,label:A.label,kind:"absent",checkedAt:X}:{scope:I,label:A.label,kind:"retired",retiredAt:X})}let{limits:H,budget:q,counters:Y,credits:U,...M}=z,B=k8(z.budget,Z.budget,X),L=T8(z.counters,Z.counters),C=E8(z.credits,Z.credits);return{...M,limits:[...G.values()].sort(S8),...B===void 0?{}:{budget:B},...L===void 0?{}:{counters:L},...C===void 0?{}:{credits:C}}}var b8=Object.freeze({validate:$1,decode:f0,merge:O1});function W9($,Z=""){let J=new Map,{observation:z}=$,X=(W,H,q)=>J.set(`${Z}:${W}`,{at:H,order:0,publication:{...$,observation:q}}),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 g8}from"node:crypto";import{stat as v8}from"node:fs/promises";import{resolve as A1}from"node:path";function H9($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function $$($,Z,J){return $.some((z)=>H9(z,Z,J))}function Z$($,Z,J){let z={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((X)=>X.credentialId!==Z||X.accountIdentity!==J),z]}function J$($,Z,J){return $.filter((z)=>!Z.some((X)=>H9(z,X,J)))}function z$($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>W0(Z).map((J)=>({credentialId:J,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function h8($,Z){let J=W0(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 e1="vault:";function m8($){return g8("sha256").update($).digest("hex")}function w8($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function u8($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function W0($){return[$.credentialId,...$.aliases??[]]}function q9($,Z,J={}){let z=J.now??Date.now(),X=J.routePrefix??e1,G=J.reservedRouteIds??new Set,Q=$?.rows??[],W=$?void 0:J.seed,H=[...$?.declined??W?.declined??[]],q=Z.skipped.length===0,Y=new Set(Z.credentials.map((F)=>F.credentialId)),U=new Set(Z.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),M=Z.skipped.some((F)=>F.credentialId===void 0),B=(F)=>!Y.has(F)&&(U.has(F)||M),L=new Map;for(let F of Q){if(F.accountIdentity===void 0)continue;for(let K of W0(F))if(!L.has(K))L.set(K,F.accountIdentity)}let C=new Map;for(let F of Z.credentials){let K=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:L.get(F.credentialId),claimed:!1},V=u8(K),P=C.get(V)??[];P.push(K),C.set(V,P)}let A=new Set,I=new Set(G),R=[],h=(F,K)=>F.credential.credentialId.localeCompare(K.credential.credentialId),m=[...C.values()].map((F)=>F.toSorted(h)).sort((F,K)=>F[0]&&K[0]?h(F[0],K[0]):0);for(let F of m){let K=F[0]?.identity,V=F.filter((T)=>T.credential.state==="active"),P=V.length?V:F,x=P.filter((T)=>T.claimed),k=x.length?x:P,y=new Set(F.map((T)=>T.credential.credentialId)),$0=Q.find((T)=>!A.has(T)&&W0(T).some((K0)=>y.has(K0))&&(T.accountIdentity===void 0||T.accountIdentity===K)),p=k.find((T)=>T.credential.credentialId===$0?.credentialId)??k[0];if(!p)continue;let c=p.credential,a=$0??(K===void 0?void 0:Q.find((T)=>!A.has(T)&&T.accountIdentity===K));if(a)A.add(a);let q0=a?.routeId;if(!q0||G.has(q0)){let T=`${X}${c.credentialId}${K===void 0?"":`~${m8(K).slice(0,10)}`}`;q0=T;for(let K0=2;I.has(q0);K0++)q0=`${T}~${K0}`}I.add(q0);let y1=a?W0(a).filter(B):[],p0=[...new Set([...F.map((T)=>T.credential.credentialId),...y1])].filter((T)=>T!==c.credentialId).sort((T,K0)=>T.localeCompare(K0)),g1=J.mapAccount?.(c)??{};R.push({previousIndex:a?Q.indexOf(a):1/0,row:{routeId:q0,credentialId:c.credentialId,credentialType:c.credentialType,...K!==void 0&&{accountIdentity:K},...p0.length&&{aliases:p0},state:c.state,label:g1.label?.trim()||w8(c),...c.email!==void 0&&{email:c.email},...c.orgName!==void 0&&{orgName:c.orgName},enabled:![c.credentialId,...p0].some((T)=>$$(H,T,K)),addedAt:a?.addedAt??z,...a?.quota!==void 0&&{quota:a.quota},...!p.claimed&&K!==void 0&&{unclaimed:!0}}});let d0=R.at(-1);if(W&&d0)d0.previousIndex=h8(W,d0.row)}return Q.forEach((F,K)=>{if(A.has(F)||!W0(F).some(B))return;if(I.has(F.routeId))return;let[V,...P]=W0(F).filter((y)=>!Y.has(y));if(V===void 0)return;I.add(F.routeId);let{aliases:x,...k}=F;R.push({previousIndex:K,row:{...k,credentialId:V,...P.length&&{aliases:P},stale:!0}})}),R.sort((F,K)=>F.previousIndex===K.previousIndex?F.row.credentialId.localeCompare(K.row.credentialId):F.previousIndex-K.previousIndex),{version:1,view:Z.view,complete:q,...!q&&{rejected:Z.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:R.map((F)=>F.row),declined:H}}function X$($){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 I1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function X1($){return $===void 0||typeof $==="string"}function c8($){let Z=I1($)?f0($.quota):void 0;if(!I1($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!X1($.accountIdentity)||!X1($.email)||!X1($.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 p8=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function Y9($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!I1(J)||!X1(J.credentialId)||typeof J.reason!=="string"||!p8.has(J.reason))return;Z.push(J)}return Z}function K9($){if(!I1($)||$.version!==1||!X1($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!Y9($.rejected))throw new O("invalid-state","Claustrum roster file is not valid");let Z=[];for(let X of $.rows){let G=c8(X);if(!G)throw new O("invalid-state","Claustrum roster file is not valid");Z.push(G)}let J=[];for(let X of $.declined){if(!I1(X)||typeof X.credentialId!=="string"||!X1(X.accountIdentity))throw new O("invalid-state","Claustrum roster file is not valid");J.push(X)}let z=Y9($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...z&&{rejected:z},rows:Z,declined:J}}function G$($){return K9(JSON.parse(JSON.stringify($)))}async function u($){let Z;try{Z=await Z0($,_)}catch(z){if(z.code==="ENOENT")return;throw z}let J;try{J=JSON.parse(Z)}catch{throw new O("invalid-state","Claustrum roster file is not valid")}return K9(J)}var F9={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},B9={name:"claustrum-roster",ttlMs:30000};async function x0($,Z,J={}){return x3($,{...F9,signal:J.signal},async(z)=>{let X=await u($),{next:G,result:Q}=await Z(X,{assertOwned:()=>z.assertOwned()});if(G)await z.assertOwned(),await D1($,G,{beforeRename:async()=>{await J.beforePublish?.(),J.signal?.throwIfAborted(),await z.assertOwned()}});return Q})}function Q$($,Z){return x0($,(J)=>{let z=J?.rows.find((G)=>G.routeId===Z);if(!J||!z)throw new O("route-unavailable","Claustrum route is not in the roster");let X=Z$(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 W$($,Z){return x0($,(J)=>{let z=J?.rows.find((X)=>X.routeId===Z);if(!J||!z)throw new O("route-unavailable","Claustrum route is not in the roster");return{next:{...J,declined:J$(J.declined,W0(z),z.accountIdentity),rows:J.rows.map((X)=>X===z?{...X,enabled:!0}:X)},result:void 0}})}function d8($){return new O("invalid-order",$)}function l8($,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 H$($,Z,J={}){return x0($,(z)=>{let X=z?.rows??[],G=l8(X,Z);if(G)throw d8(G);let Q=new Map;for(let q of X){let Y=Q.get(q.routeId);if(Y)Y.push(q);else Q.set(q.routeId,[q])}let W=[...Z],H=W.flatMap((q)=>Q.get(q)??[]);if(!z||H.every((q,Y)=>q===X[Y]))return{result:{ids:W,outcome:"unchanged"}};return{next:{...z,rows:H},result:{ids:W,outcome:"reordered"}}},{...J.signal&&{signal:J.signal}})}function a8($,Z){if(!W0($).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")&&W0($).length===1)return"bind";return"refuse"}async function Y$($,Z){let{routeId:J,observation:z,...X}=Z;return V9($,{routeId:J,observation:z,accountIdentity:X.accountIdentity,receipt:X})}async function V9($,Z){if(!z1(Z.observation))return!1;let J=o($,await u($));if(!I0(J,Z).kept)return!1;return M9($,Z)}function U$($,Z){return V9($,Z)}function I0($,Z){let J=$?.rows.find((Q)=>Q.routeId===Z.routeId),z=!J?"refuse":Z.receipt?a8(J,Z.receipt):J.accountIdentity!==void 0&&J.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!J||z==="refuse")return{roster:$,kept:!1};let X=O1(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 t1=new Map;function _1($){t1.delete(A1($))}function j9($,Z){let J=A1($);if(Z instanceof O)return Z.kind==="roster-busy";if(Z instanceof P0||Z instanceof V0)return A1(Z.details.target)===J;if(Z instanceof w){let z=A1(Z.path);return[F9.name,B9.name].some((X)=>{let G=N1(J,X);return z===G||z.startsWith(`${G}.`)})}return!1}var s8=4;async function U9($){try{let{dev:Z,ino:J,size:z,mtimeMs:X}=await v8($);return{dev:Z,ino:J,size:z,mtimeMs:X}}catch{return}}function n8($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function i8($,Z,J){for(let z=0;z<s8;z++){let X=await U9($),G=await u($),Q,W,H;try{({target:Q,local:W}=Z(G));let q=JSON.stringify(J(Q));H=JSON.stringify(Q)!==q||W!==void 0&&JSON.stringify(W)!==q}catch{return"commit"}if(!n8(X,await U9($)))continue;if(H)return"commit";return D9($)?"commit":"unchanged"}return"commit"}async function R1($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){_1($.path);return}let J=await j0({...B9,path:$.path,renew:!0});if(!J){let Q=await u($.path);if($.signal?.throwIfAborted(),!Q?.view)throw new O("roster-busy","Claustrum account discovery is already in progress");return Q}let z=A1($.path),X=$.listedOver,G;try{let Q=await u($.path),W=X?void 0:t1.get(z);G=W&&(W.previousView===Q?.view||W.inventory.view===Q?.view)?W:{inventory:await $.custody.discover($.signal),previousView:Q?.view},t1.delete(z);let{inventory:H}=G;$.onInventory?.(H),$.signal?.throwIfAborted();let q=typeof $.projection==="function"?$.projection():$.projection,Y=(B)=>q9(B,H,q),U=async()=>{return $.signal?.throwIfAborted(),await J.assertOwned(),Z()};if(await i8($.path,(B)=>{if(X)return{target:B};let L=o($.path,B);return{target:B,...L!==B&&{local:L}}},Y)==="unchanged"){if(!await U())return;return await u($.path)}return await x0($.path,async(B)=>{if(!await Z())return{result:void 0};if($.signal?.throwIfAborted(),await J.assertOwned(),X&&B?.view!==X.view&&B?.view!==H.view)return{result:B};let L=Y(B);return{...JSON.stringify(B)!==JSON.stringify(L)&&{next:L},result:L}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await J.assertOwned()}})}catch(Q){if(Q instanceof P0&&G&&!X&&!$.signal?.aborted&&await Z())t1.set(z,G);throw Q}finally{await J.release($.signal)}}var y0=new Map,o8=Q0("claustrum"),L9=100;function P9($,Z=o3){let J=$3($),z=y0.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},y0.set(J,z);return z}function C9($,Z,J){let z=P9($,J);z.listeners.add(Z);let X;return()=>X??=(()=>{return z.listeners.delete(Z),z.listeners.size?Promise.resolve():q$($)})()}function r8($){return W9($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function M9($,Z){if(!z1(Z.observation))return Promise.resolve(!1);let J=P9($),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 r8(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 A9(J,L9),Promise.resolve(!0)}function O9($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,J)=>Z.order-J.order)}function o($,Z){let J=y0.get($3($));if(J)for(let z of O9(J.pending)){if(z.priorReading)Z=I0(Z,z.priorReading).roster;Z=I0(Z,z.publication).roster}return Z}function D9($){return!!y0.get($3($))?.pending.size}function A9($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let J=$.draining?0:($.committedAt??-1/0)+i3-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,J),()=>{return $.timer=void 0,I9($)}),!$.draining)$.timer.unref?.()}function N9($){$.timer?.cancel(),$.timer=void 0}function I9($){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 x0($.path,(z)=>{let X=z;for(let Q of O9(Z)){if(Q.priorReading)X=I0(X,Q.priorReading).roster;X=I0(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)o8.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()):L9;A9($,J)}})(),$.running}async function q$($,Z=1000){let J=$3($),z=y0.get(J);if(!z)return;z.draining=!0,N9(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)I9(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(),N9(z),z.pending.clear(),y0.get(J)===z)y0.delete(J)}}}var Z3=1e4;function _9(){return new r}var K$;function S9($,Z){if(!K$)throw Error("ClaustrumConsumer is not initialized");return K$($,Z)}function R9(){return new O("not-active","Claustrum scoped custody is not active")}class F${#$;#Z=new AbortController;#J;#W;#G;#Q;#X;#z;#D;#H;#Y=!1;#K=new Set;#V;#U;#j;#M;#L=new Map;#_;#C;#q;#N;#A=new WeakMap;static{K$=($,Z)=>{let J=new F$(Z);return J.#q=$,{consumer:J,hooks:J.#w()}}}constructor($){this.#$=$,this.#J=$.logger??Q0("claustrum"),this.#W=r0(this.#J,this.#Z.signal),this.#C=C9($.rosterPath,(Z)=>{this.#z=I0(this.#z,Z).roster})}#F($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#P($){return this.#K.add($),$.then(()=>this.#K.delete($),()=>this.#K.delete($)),$}async#O(){return await this.#$.isCustodyActive?.()??!0}#I($,Z){let J=S0([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#k(){if(this.#F(),this.#G)return this.#G;if(!this.#Q){let $={timedOut:!1};this.#Q=this.#B($),this.#P(this.#Q)}return this.#I(this.#Q)}#B($){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.#F();throw _9()}if(this.#G=new e0({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=S3(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.#R()}),W(_9())},this.#R()),X.unref?.()});return Promise.race([z,G]).finally(()=>{if(X)J(X);this.#Q=void 0})}#R(){return this.#$.connectTimeoutMs??Z3}snapshot(){return this.#z}grantReach(){if(this.#q)return this.#q.grantReach(this.#z?.view);let $=this.#D;return $&&this.#z?.view===$.view?$.reach:void 0}watchState(){if(this.#q)return Object.freeze({vault:this.#q.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.#M?.(),this.#M=void 0}keptReceiptState(){if(this.#q){let $=this.#N;return $&&this.#q.leaseLive($)?$.custody.keptReceiptState():this.#q.keptReceiptState()}return this.#G?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return X$(this.#z)}refresh(){if(this.#F(),this.#q)return this.#P(this.#y(this.#q));if(this.#X)return this.#X;return this.#X=(async()=>{if(!await this.#O()){if(this.#z=void 0,this.#D=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.#k(),Z,J=await R1({path:this.#$.rosterPath,custody:$,onInventory:(X)=>{Z=X},isActive:()=>this.#O(),signal:this.#Z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#F();let z=J?.view!==this.#z?.view;if(this.#z=o(this.#$.rosterPath,J),$.retain(J?.rows??[]),Z&&J?.view!==void 0)this.#D=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.#X=void 0}),this.#P(this.#X),this.#T(this.#X),this.#X}#T($){try{this.#$.onDiscovery?.($)}catch(Z){this.#$.onError?.(Z)}}start(){if(this.#Y)return;if(this.#F(),this.#Y=!0,this.#q){this.#q.start();return}let $=async()=>{try{if(await this.#x())await this.refresh();await this.refreshInsulaQuota(),this.#b()}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#x(){if(this.#j?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#_===void 0||$-this.#_>=l0)return!0;return!await this.#O()}#b(){let $=this.#G;if(this.#Z.signal.aborted||!$)return;if(this.#j??=$.watchRoster({view:()=>this.#z?.view,onView:()=>this.#P((async()=>{while(this.#X)await this.#X.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.#M)this.#M=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.#O())return;try{await O0(this.#$.tokenPath),await this.#k(),await this.#U?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#O())return;try{return await O0(this.#$.tokenPath),this.#f($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#O())return;try{await O0(this.#$.tokenPath);let J=o(this.#$.rosterPath,await u(this.#$.rosterPath))?.rows.find((z)=>z.routeId===$);return this.#f(J?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute($){let Z=this.#$.insula;if(!Z||this.#Z.signal.aborted||!await this.#O())return{miss:"unreachable"};try{await O0(this.#$.tokenPath);let z=o(this.#$.rosterPath,await u(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.#L.get($)!==J.miss)this.#L.set($,J.miss),this.#J.warn("skipped insula provider poll",{reason:J.miss});return}return this.#L.delete($),J.miss?Z():J.reading}#f($){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.#q)return this.#g(this.#q,$,Z);this.#F(Z);let J=this.#z??await this.#I(this.refresh(),Z);if(!J||!await this.#O())throw this.#G?.close(),this.#G=void 0,this.#S(),this.#U?.release(),this.#U=void 0,new O("not-active","Claustrum scoped custody is not active");let z=o(this.#$.rosterPath,await u(this.#$.rosterPath));this.#F(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 O("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 O("route-unavailable","Claustrum route is disabled, removed or changed")}let Q=await this.#I(this.#k(),Z),W=S0([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()}}#w(){return{discovery:($)=>{let Z=this.#q;if(!Z||!this.#$.onDiscovery||this.#Z.signal.aborted)return;let J=this.#P($.then((z)=>this.#v(Z,z)));this.#T(J)},install:($)=>{if(this.#Z.signal.aborted)return;let Z=$.view!==this.#z?.view;if(this.#z=o(this.#$.rosterPath,$),Z)try{this.#$.onRoster?.($)}catch(J){this.#$.onError?.(J)}},reset:()=>{this.#z=void 0},roster:()=>this.#z,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();return this.#v($,Z)}#v($,Z){if(this.#F(),!Z)return;if(Z.errors.has($.provider))throw Z.errors.get($.provider);return this.#z}#E($){if($&&this.#N!==$)return;this.#N?.release(),this.#N=void 0}async#u($,Z){let J=this.#N;if(J&&$.leaseLive(J))return J;this.#E();let z=await $.acquire(Z);if(this.#Z.signal.aborted)z.release(),this.#F();let X=this.#N;if(X&&$.leaseLive(X))return z.release(),X;return this.#N=z,z}async#g($,Z,J){if(this.#F(J),!this.#z)await this.#I($.refresh(),J);let z=this.#z;if(!await $.readAuthority())throw this.#E(),R9();if(this.#F(J),!z)throw new O("route-unavailable","Claustrum has no roster for this provider yet");let X=o(this.#$.rosterPath,await u(this.#$.rosterPath));this.#F(J);let G=z.rows.find((q)=>q.routeId===Z),Q=X?.rows.find((q)=>q.routeId===Z);if(Q&&!Q.enabled){if(G)$.forget(G.credentialId);throw new O("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 O("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=S0([this.#Z.signal,...J?[J]:[]]);try{for(let q=0;;q++){let Y=await this.#u($,H.signal);try{let U=await Y.custody.authorize(W,H.signal,Z);return this.#A.set(U,Y),U}catch(U){if(q>0||H.signal.aborted||$.leaseLive(Y)||!(U instanceof O)||U.kind!=="closed")throw U;if(this.#E(Y),!await $.readAuthority())throw R9()}}}finally{H.dispose()}}async reportFailure($,Z,J){if(this.#F(),this.#q){let z=this.#A.get($);if(!z)throw new O("no-receipt","Claustrum dispatch receipt has no active owner");await z.custody.reportFailure($,Z,J);return}if(!this.#G)throw new O("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(n3(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.#F(),await Q$(this.#$.rosterPath,$),this.#z=o(this.#$.rosterPath,await u(this.#$.rosterPath)),this.#z)this.#q?.publishRoster(this.#z);if(this.#q)this.#q.retainUnion();else this.#G?.retain(this.#z?.rows??[])}async accept($){if(this.#F(),await W$(this.#$.rosterPath,$),this.#z=o(this.#$.rosterPath,await u(this.#$.rosterPath)),this.#z)this.#q?.publishRoster(this.#z)}async reorder($){this.#F();let Z=await H$(this.#$.rosterPath,$);if(this.#z=o(this.#$.rosterPath,await u(this.#$.rosterPath)),this.#z)this.#q?.publishRoster(this.#z);return Z}async recordQuota($,Z,J){return this.#F(),Y$(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.#F(),U$(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:J})}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new O("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.#N?.release(),this.#N=void 0,this.#q?.detach(),this.#U?.release(),this.#U=void 0,this.#z=void 0,this.#D=void 0,this.#C(),_1(this.#$.rosterPath)}async dispose(){this.close(),this.#V??=Promise.all([t0(this.#K,this.#W),this.#C()]).then(()=>{}),await this.#V}}import{createHash as t8}from"node:crypto";import{readdir as e8,stat as $6}from"node:fs/promises";import{dirname as Z6,join as G1,resolve as k9}from"node:path";var J3=new Map,J6=/^[a-z0-9][a-z0-9._-]{0,63}$/,z6=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,X6=/^[0-9a-f]{16}$/,T9=3;function V$($,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=V$($[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=V$($[G],J);if(Q===void 0)return;z.push(`${JSON.stringify(G)}:${Q}`)}return`{${z.join(",")}}`}function G6($,Z){let J=V$({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??e1,mapAccount:$.mapAccount?String($.mapAccount):null});if(J===void 0)throw new O("invalid-state","Claustrum hub classifierInput must be plain JSON");return t8("sha256").update(J).digest("hex").slice(0,16)}function E9($,Z){if(typeof $!=="string"||!J6.test($)||z6.test($))throw new O("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function _0($="Claustrum custody lease is closed"){return new O("closed",$)}function B$(){return new O("not-active","Claustrum scoped custody is not active")}function b9(){return new r}function Q6($,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 f9($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class x9{#$;#Z;#J;#W=new AbortController;#G=new Map;#Q=new WeakMap;#X=0;#z;#D;#H;#Y;#K;#V;#U=0;#j;#M;#L;#_=!1;#C=new Set;#q;#N;#A;constructor($){if(!$.family||!("classify"in $.family))throw new O("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=E9($.hostGeneration,"host generation"),J=$.members.map((X)=>E9(X,"member"));if(new Set(J).size!==J.length)throw new O("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??Q0("claustrum"),this.#J=r0(this.#Z,this.#W.signal),this.#N=G1($.stateDir,"rosters",Z),this.#A=G6($,J);let z=G1(this.#N,this.#A);for(let X of J)this.#G.set(X,{provider:X,path:G1(z,`${X}.json`),closed:!1})}#F($){return this.#C.add($),$.then(()=>this.#C.delete($),()=>this.#C.delete($)),$}#P(){if(this.#W.signal.aborted)throw _0("Claustrum discovery hub is closed")}#O($){let Z=this.#G.get($);if(!Z)throw new O("wrong-consumer","Claustrum hub has no such member");return Z}rosterPath($){return this.#O($).path}member($,Z){this.#P();let J=this.#O($);if(J.hooks)throw new O("wrong-consumer","Claustrum hub member was already built");for(let U of["rosterPath","tokenPath","family","connect","isCustodyActive","insula","pollIntervalMs","routePrefix","mapAccount"])if(U in Z)throw new O("wrong-consumer",`Claustrum hub members cannot take ${U}`);let z={provider:J.provider,start:()=>this.start(),refresh:()=>this.#g(),readAuthority:()=>this.#y(),acquire:(U)=>this.acquire(U),leaseLive:(U)=>this.#R(U),grantReach:(U)=>U!==void 0&&this.#j?.view===U?this.#j.reach:void 0,watchMode:()=>this.watchState(),keptReceiptState:()=>this.keptReceiptState(),retainUnion:()=>this.#m(),publishRoster:(U)=>this.#I(J,U),forget:(U)=>this.#z?.custody?.forget(U),detach:()=>{J.closed=!0,J.releaseRoster?.()}},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.onDiscovery&&{onDiscovery:Z.onDiscovery},...Z.onError&&{onError:Z.onError},logger:Z.logger??this.#Z,...this.#$.now&&{now:this.#$.now}},{consumer:G,hooks:Q}=S9(z,X);J.hooks=Q;let W=k9(J.path),H=J3.get(W)??new Set,q=(U)=>{if(J.closed||this.#V!==!0||!this.#z||!this.#B(this.#z)||!Q.roster()||this.#c(Q,U))return;if(J.seen=JSON.stringify(G$(U)),Q.install(U),U.view!==this.#j?.view)J.pending??={failures:0,wait:0};this.#m()};H.add(q),J.receiveRoster=q,J3.set(W,H);let Y=!0;return J.releaseRoster=()=>{if(!Y)return;if(Y=!1,H.delete(q),!H.size)J3.delete(W)},G}#I($,Z){let J=this.#z;if($.closed||!J||!this.#B(J))return;$.seen=JSON.stringify(G$(Z)),$.hooks?.install(Z);for(let z of J3.get(k9($.path))??[]){if(!this.#B(J))return;if(z!==$.receiveRoster)z(Z)}}#k(){let $={id:++this.#X,count:0,ended:!1,controller:new AbortController};return this.#z=$,$}#B($){return!$.ended&&this.#z===$&&!this.#W.signal.aborted}#R($){let Z=this.#Q.get($);return!!Z&&!Z.released&&!Z.generation.ended}#S($,Z=_0()){if($.ended)return;if($.ended=!0,$.count=0,this.#z===$)this.#z=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.#F($.custody.dispose(this.#J))}#T($){if($.ended)return;if($.count--,$.count<=0)this.#S($)}#x($){let Z=this.#D;if(Z?.generation===$&&Z.promise)return Z.promise;let J={generation:$,timedOut:!1},z=this.#$.connectTimeoutMs??Z3,X,G=this.#$.connect().then((H)=>{if(J.timedOut)throw H.close(),b9();if(!this.#B($)||$.count<=0)throw H.close(),_0("Claustrum connection is no longer wanted");return $.custody=new e0({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,q)=>{X=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(J.timedOut=!0,!this.#B($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:z}),q(b9())},z),X.unref?.()});return J.promise=this.#F(Promise.race([G,Q]).finally(()=>{if(X)(this.#$.clearTimeoutImpl??clearTimeout)(X)})),J.promise.finally(()=>{if(this.#D===J)this.#D=void 0}).catch(()=>{}),this.#D=J,J.promise}acquire($){try{if(this.#P(),$?.throwIfAborted(),this.#V===!1)throw B$()}catch(J){return Promise.reject(J)}let Z=this.#z??this.#k();return Z.count++,this.#b(Z,$,!0)}async#b($,Z,J){let z=$.custody;if(!z){let X=S0([$.controller.signal,...Z?[Z]:[]]);try{z=await Q6(this.#x($),X.signal)}catch(G){if(!$.ended)throw this.#T($),G;return this.#f(Z,J)}finally{X.dispose()}}if($.ended)return this.#f(Z,J);if(Z?.aborted)throw this.#T($),Z.reason;return this.#w($,z)}#f($,Z){if($?.throwIfAborted(),this.#P(),this.#V===!1)throw B$();if(!Z)throw _0();let J=this.#z??this.#k();return J.count++,this.#b(J,$,!1)}#w($,Z){let J={generation:$,custody:Z,released:!1},z=()=>{if(J.released||$.ended)throw _0()},X=Object.freeze({authorize:async(Q,W,H)=>{z();let q=S0([$.controller.signal,...W?[W]:[]]);try{return await Z.authorize(Q,q.signal,H)}finally{q.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.#T($)}});return this.#Q.set(G,J),G}leaseState(){let $=this.#z;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.#V;if(this.#V=$,!$&&Z!==!1)this.#v();return $}#v(){this.#U++;let $=this.#z;if($)this.#S($,B$());this.#H=void 0,this.#Y?.watch.close(),this.#Y=void 0,this.#j=void 0,this.#M=void 0;for(let Z of this.#G.values())Z.seen=void 0,Z.pending=void 0,Z.hooks?.reset(),_1(Z.path)}#E(){return[...this.#G.values()].filter(($)=>$.hooks&&!$.closed)}async#u(){let $=this.#H,Z=$&&this.#Q.get($);if($&&Z&&this.#R($))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.#R(this.#H))return J.release(),z;this.#H=J;let X=this.#Q.get(J);if(!X)throw _0();return X}#g(){try{this.#P()}catch(z){return Promise.reject(z)}let $=this.#K;if($&&!$.generation?.ended)return $.promise;let Z={},J=this.#F(this.#n(Z).finally(()=>{if(this.#K===Z)this.#K=void 0}));Z.promise=J,this.#K=Z;for(let z of this.#E())z.hooks?.discovery(J);return J}async#n($){if(!await this.#y())return;let Z=await this.#u(),J=Z.generation;if($.generation=J,!this.#B(J))return;let z=await this.#o().then(()=>{return},(Y)=>Y instanceof Error?Y:Error(String(Y))),X=new Map(await Promise.all([...this.#G.values()].map(async(Y)=>[Y,await u(Y.path).then((U)=>U?{file:U}:{},(U)=>U instanceof Error?U:Error(String(U)))])));if(!this.#B(J))return;let G;try{G=await Z.custody.discover(J.controller.signal)}catch(Y){if(!this.#B(J))return;for(let U of this.#G.values())if(U.pending)this.#h(U);throw Y}if(!this.#B(J))return;let Q=this.#E(),W=await Promise.all(Q.map((Y)=>Y.hooks&&!Y.closed?this.#i(Y,Y.hooks,G,z??X.get(Y),J):void 0));if(!this.#B(J))return;let H=new Map,q=!0;for(let[Y,U]of Q.entries()){let M=U.hooks,B=W[Y];if(!M||!B)continue;if("error"in B){let{error:C}=B;if(q=!1,this.#h(U),j9(U.path,C))this.#Z.debug("claustrum hub member commit refused",{member:U.provider});else H.set(U.provider,C);continue}let{roster:L}=B;if(!this.#B(J))return;if(L?.view!==G.view)q=!1,this.#h(U);else U.pending=void 0;if(!L)continue;if(this.#c(M,L)){q=!1,this.#h(U);continue}this.#I(U,L)}if(!this.#B(J))return;if(this.#m(),q)this.#j=Object.freeze({view:G.view,...G.grantReach&&{reach:G.grantReach},refused:Object.freeze([...G.refused??[]]),notMine:G.notMine??0});return this.#M=(this.#$.now??Date.now)(),{errors:H}}async#i($,Z,J,z,X){let G={...J,credentials:J.credentials.filter((Q)=>Q.member===$.provider),skipped:J.skipped.filter((Q)=>Q.member===$.provider)};try{if(!z)throw _0("Claustrum hub member has no base view");if(z instanceof Error)throw z;let Q=z.file?void 0:await this.#r($);return{roster:await R1({path:$.path,custody:{discover:async()=>G},isActive:()=>this.#B(X)&&this.#V===!0,signal:X.controller.signal,projection:()=>({...Z.projection(),...Q&&{seed:Q}}),listedOver:{view:z.file?.view}})}}catch(Q){return{error:Q}}}async#o(){for(let $ of[Z6(this.#N),this.#N,G1(this.#N,this.#A)])await o0($,{},"roster directory")}async#r($){let Z=`${$.provider}.json`,J=[G1(this.#N,Z)];try{for(let X of await e8(this.#N))if(X!==this.#A&&X6.test(X))J.push(G1(this.#N,X,Z))}catch{}let z;for(let X of J)try{let G=(await $6(X)).mtimeMs,Q=await u(X);if(Q&&(!z||G>z.modified))z={modified:G,roster:Q}}catch{}return z&&z$(z.roster)}#c($,Z){let J=$.projection().reservedRouteIds;return!!J?.size&&Z.rows.some((z)=>J.has(z.routeId))}#h($){let Z=($.pending?.failures??0)+1,J=Math.max(1,this.#$.pollIntervalMs??5000),z=Math.max(1,Math.ceil(l0/J)),X=Z<=T9?1:Math.min(2**(Z-T9),z);$.pending={failures:Z,wait:X-1}}#m(){let $=this.#z?.custody;if(!$)return;$.retain(this.#E().flatMap((Z)=>Z.hooks?.roster()?.rows??[]))}async#t(){let $=this.#U;for(let Z of this.#E()){let J;try{J=await u(Z.path)}catch(W){Z.hooks?.onError(W);continue}if($!==this.#U||this.#V!==!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.#c(z,J)){Z.pending??={failures:0,wait:0};continue}let Q=f9(G);if(Z.seen=X,this.#I(Z,J),f9(z.roster())!==Q)this.#m()}}#e(){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.#M===void 0||Z-this.#M>=l0}#$0(){let $=this.#H,Z=$&&this.#Q.get($);if(!$||!Z||!this.#R($)||this.#V!==!0)return;let J=Z.generation;if(!this.#B(J)||this.#Y?.generation===J)return;let z=Z.custody.watchRoster({view:()=>this.#j?.view,onView:()=>this.#F((async()=>{while(this.#K)await this.#K.promise.catch(()=>{});if(!this.#B(J))return;await this.#a()})()),onRefused:(X)=>this.#d(X),onError:(X)=>this.#p(X)});this.#Y={generation:J,watch:z}}#p($){if(!this.#W.signal.aborted)this.#$.onError?.($)}#d($){if(this.#W.signal.aborted)return;this.#$.onError?.($);for(let Z of this.#E())Z.hooks?.onError($)}#l($){for(let[Z,J]of $?.errors??[])this.#G.get(Z)?.hooks?.onError(J)}async#a(){let $;try{$=await this.#g()}catch(Z){this.#d(Z);return}this.#l($)}async#s(){try{if(await this.#y()){if(await this.#t(),this.#e())await this.#a();this.#$0()}}catch(Z){this.#p(Z)}if(this.#W.signal.aborted)return;let $=this.#$.pollIntervalMs??5000;if($<=0)return;this.#L=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#L=void 0,this.#F(this.#s())},$),this.#L.unref?.()}start(){if(this.#_)return;this.#P(),this.#_=!0,this.#F(this.#s())}async refresh(){this.#l(await this.#g())}refusals(){let $=this.#j;return $&&Object.freeze({view:$.view,refused:$.refused,notMine:$.notMine})}grantReach(){return this.#j?.reach}watchState(){let $=this.#Y;return $&&this.#B($.generation)?$.watch.mode:"polling"}keptReceiptState(){return this.#z?.custody?.keptReceiptState()??Object.freeze({active:!1,since:null})}close(){if(this.#W.signal.aborted)return;this.#W.abort(_0("Claustrum discovery hub is closed"));for(let Z of this.#G.values())Z.releaseRoster?.();if(this.#L)(this.#$.clearTimeoutImpl??clearTimeout)(this.#L);this.#L=void 0;let $=this.#z;if($)this.#S($);this.#H=void 0,this.#Y?.watch.close(),this.#Y=void 0}async dispose(){this.close(),this.#q??=t0(this.#C,this.#J),await this.#q}}var v0={opencode:Y6,pi:U6};function j$($,Z){let{tokenPath:J}=y9($,Z);return{stateDir:H6(J),host:$,override:J}}function M$($,Z){return q6($==="pi"?Z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0,$==="pi"?{...Z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:Z)}class g0 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 D$($,Z){let J=Z??v0[$];if(typeof J!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(J))throw new g0("permission-refused");return["auth","grant","--principal",`enrolled:${J}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"]}async function g9($,Z){try{await Z.processFence();let J=await n1(Z.paths??y9($,Z.env),v0[$]);if(J.state==="blocked")throw new g0("permission-refused");let z=J.state==="approved"?J.approvedName:void 0,X=D$($,z);if((await Z.runner.run(Z.ckBinary??"ck",X,{env:Z.env})).exitCode!==0)throw new g0("permission-refused");return z}catch{throw new g0("permission-refused")}}import{createHash as D6}from"node:crypto";import{lstat as N6,mkdir as L6,readFile as s9}from"node:fs/promises";import{dirname as P6}from"node:path";import{assertHostsStopped as C6,canonicalPath as L$,createNativeAccountRuntime as O6,custodyTombstoneOAuth as A6,inspectNativeHostAuthEntry as n9,NativeMigrationError as h0,nativeJournalMayAdoptLaterHostLogin as I6,nativePoolHoldsAccountData as _6,prepareNativeMigration as R6,readNativeEnrollmentMode as i9,readNativeMigrationJournal as S6,releaseNativeMigrationPreflight as k6,requireNoSupervisedAuthContentSnapshot as T6,runNativeMigration as E6,writeNativeHostAuth as b6}from"@cortexkit/anthropic-auth-core";import{dirname as K6,join as v9,resolve as N$}from"node:path";import{ACCOUNT_FILE_NAME as h9,ACCOUNT_STATE_FILE_NAME as F6,canonicalPath as m9,getStickyRoutingStatePath as B6,resolveLocalRoutingDestination as V6,resolveNativePoolPaths as j6}from"@cortexkit/anthropic-auth-core";async function M0($,Z){let J=$==="pi"?c9(Z):w9(Z),z=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),X=N$(z||v9(J,h9)),G=N$(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(X.endsWith(h9)?v9(K6(X),F6):`${X}.state.json`)),Q=await j6(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"?p9(Z):u9(Z),routingSourcePath:N$(W||B6(X)),routingDestinationPath:V6($,Q,Z)}}async function d9($){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 m9(G);if(z.has(Q)&&!(X===9&&Q===await m9(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 M6}from"node:util";var l9=new WeakMap;function a9($){return typeof $==="object"&&$!==null?l9.get($):void 0}function Q1($){if(!$||typeof $!=="object"||M6.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 n extends Error{constructor($){super($);this.name="SetupRefusal",l9.set(this,$)}}var P$="OpenCode's separate Anthropic login is not used. Add that account through /claude Accounts if needed, or remove the separate login from OpenCode.";function o9($){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 C$($,Z){let J=[];for(let z of $)if(await i9(z,Z)!=="local")J.push(o9(z));if(J.length)throw new n(J.join(`
|
|
13
|
+
`))}function m0($,Z){return async()=>{T6(Z.env);try{await C6(Z.fence,Z.env)}catch(J){let z=Q1(J);if(z)throw new n(z);throw J}await C$([$],Z.env)}}async function O$($){try{return D6("sha256").update(await s9($)).digest("hex")}catch(Z){if(Z.code==="ENOENT")return"absent";throw new h0("unsafe-source")}}async function S1($,Z){let J;try{J=JSON.parse(await s9(Z,"utf8"))}catch(G){if(G.code!=="ENOENT")throw new h0("unsafe-source")}let z=n9($,J),X=J?.anthropic;return{...z,realLogin:z.kind==="oauth"&&Boolean(X?.access&&X.refresh)}}async function z3($,Z){let{paths:J}=$,z=$.generation2?void 0:await S1(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(O$));return JSON.stringify([await i9(J.host,Z),z?.digest,...X])}async function A$($,Z,J){let z=Z.paths??await M0($,Z.env),X=m0($,Z);await X();let G=await S6(z.paths);if(G&&G.host!==$)throw new h0("invalid-source");let Q=G?.phase==="committed"||G?.phase==="retired";if(G&&G.kind!=="empty-init"&&(G.hostAuthPath!==await L$(z.hostAuthPath)||G.routingPaths.source!==await L$(z.routingSourcePath)||G.routingPaths.destination!==await L$(z.routingDestinationPath)))throw new h0("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 h0("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 q of H){try{await N6(q)}catch(Y){if(Y.code==="ENOENT")continue;throw new h0("unsafe-source")}throw new h0("invalid-source")}}}else{W.slot=await S1($,z.hostAuthPath);let H=I6(G,$)&&W.slot.kind==="oauth";W.poolPopulation=G?.kind==="empty-init"||H?await _6({paths:z.paths}):"not-evaluated";let q=W.poolPopulation===!0;if($==="opencode"&&(q||Q&&G?.kind!=="empty-init"&&!H&&W.slot.kind==="oauth"))W.action="skip",W.notice=W.slot.realLogin;else W.preflight=await R6({...z,env:Z.env,processFence:X,removePiAnthropicAuth:Z.removePiAnthropicAuth})}return W.fingerprint=await z3(W,Z.env),W}async function W1($,Z){await m0($.paths.host,Z)();let J=await A$($.paths.host,{...Z,paths:$.paths},$.generation2);try{if(J.fingerprint!==$.fingerprint||J.action!==$.action)throw new n("Setup inputs changed. Rerun setup with all hosts stopped.")}finally{if(J.preflight)k6(J.preflight)}}async function I$($,Z){if($.paths.host!=="opencode"||$.slot?.kind!=="absent")return;let J=m0("opencode",Z);await J(),await L6(P6($.paths.hostAuthPath),{recursive:!0,mode:448}),await b6({host:"opencode",authPath:$.paths.hostAuthPath,sourceDigest:"absent",expectedDigest:n9("opencode",{anthropic:A6("anthropic")}).digest,env:Z.env,removePiAnthropicAuth:!1,processFence:J})}async function r9($,Z){let J={...Z.env},z=m0($,{...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 E6({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=O6({paths:X.paths,host:$,vault:{env:J},beforePoolWrite:z});try{if((await Q.read()).mode!=="local")throw new n(o9($));await z(),await Q.loginOAuth({routeId:"main",replace:!0,...G})}finally{await Q.close()}}if(Z.skipMigration){let Q=await S1($,X.hostAuthPath);await I$({paths:X,slot:Q},Z)}}var t9={opencode:"OpenCode",pi:"Pi"};function u6($,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`${t9[Z]} has no read grant in the vault, so setup cannot see any Claude login. Run ${["ck",...D$(Z,J)].join(" ")}, then rerun setup.`;case"grant-reaches-nothing":return`${t9[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 J0 extends Error{host;approvedName;code;constructor($,Z="opencode",J){super(u6($,Z,J));this.host=Z;this.approvedName=J;this.name="NativeVaultActivationError",this.code=$}}function c6($){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 R$($){try{return JSON.parse(await f6($,"utf8"))}catch(Z){if(Z.code==="ENOENT")return;throw new J0("host-auth-invalid")}}async function k1($,Z){if($==="opencode")return"opencode";let J=Z.paths??await M0($,Z.env),z=_$($,await R$(J.hostAuthPath)),X=S$({env:Z.env,authPath:J.hostAuthPath}),{stashPath:G}=h6({env:Z.env,authPath:J.hostAuthPath});return JSON.stringify([z.digest,await X.inspect(),await O$(G)])}async function e9($){try{w6($.env)}catch{throw new J0("auth-content-refused")}try{await x6($.fence,$.env)}catch(Z){let J=Q1(Z);if(J)throw new n(J);throw Z}}async function $4($,Z){let J={...Z.env};await(()=>e9({...Z,env:J}))();let X=Z.paths??await M0($,J),G=$==="opencode"&&Z.inspectOpenCodeAuth!==!1&&_$("opencode",await R$(X.hostAuthPath)).kind==="oauth";if($==="pi"){let Q=_$("pi",await R$(X.hostAuthPath)),W=await S$({env:J,authPath:X.hostAuthPath}).inspect();if(W.slot==="placeholder"&&W.stash==="missing")throw new v6("missing-stash");if(Q.kind!=="absent"&&W.slot!=="placeholder"&&!Z.removePiAnthropicAuth)throw new J0("consent-required")}return{priorMode:await m6($,J),fingerprint:await k1($,{...Z,env:J}),separateOpenCodeLogin:G}}async function Z4($,Z,J){let z={...Z.env},X=()=>e9({...Z,env:z});await X();let G=Z.paths??await M0($,z);if(await k1($,Z)!==J.fingerprint)throw new J0("host-auth-invalid");let Q=await g9($,{env:z,runner:Z.runner,processFence:X,ckBinary:Z.enrollment?.ckBinary,paths:Z.enrollment?.paths}),W=Z.discover??(()=>g6({paths:G.paths,host:$,env:$==="pi"?{...z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE}:z})),H,q=async()=>{return H=await W(),H},Y=y6({paths:G.paths,host:$,vault:{env:z,discover:q}});try{await X(),await Y.vault.refresh();let U=await Y.read(),M=U.accounts.find((B)=>B.id==="main");if(U.mode!=="claustrum"||!M?.accountIdentity||M.source!=="vault"){let B=c6(H);throw B==="primary-unverified"?new J0(B):new J0(B,$,Q)}if(await X(),$==="pi")await S$({env:z,authPath:G.hostAuthPath}).enterVault();return J.priorMode==="claustrum"?"already-vault":"committed"}finally{await Y.close()}}var p6=/(?:^|[/\\])(opencode|litecode|opencode2|pi)(?:\.exe)?(?=$|\s|")/i;class k$ extends Error{activeHosts;constructor($){let Z=$.map((z)=>({pid:z.pid,command:p6.exec(z.command)?.[1]??"host"})),J=Z.map((z)=>` - PID ${z.pid}: ${z.command}`).join(`
|
|
14
14
|
`);super(`OpenCode or Pi processes are currently running:
|
|
15
15
|
${J}
|
|
16
16
|
|
|
17
|
-
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=Z,this.name="ProcessFenceViolationError"}}var
|
|
18
|
-
`,$.length-
|
|
19
|
-
`,
|
|
17
|
+
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=Z,this.name="ProcessFenceViolationError"}}var q5={"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 T1(){return($)=>$}var E$=["opencode","pi"],K5=new Set(["enrolled","not-enrolled","unknown"]),H4=T1()(["auth-content-refused","host-auth-invalid","primary-conflict","consent-required","primary-unverified","no-read-grant","grant-reaches-nothing"]),Y4=T1()(["enrollment-refused","enrollment-reset","approval-refused","permission-refused"]),U4=T1()(["invalid-source","unsafe-source","consent-required","primary-unverified","migration-busy","ownership-lost","retirement-refused","pool-populated","host-login-present","settings-changed"]),q4=T1()(["invalid-options","invalid-auth","invalid-stash","unsafe-path","missing-stash","conflict","lock-timeout","lock-compromised","io"]),K4=T1()(["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"]),F5={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","RelocatedError","HolderRegistrationError","StateLayoutRefusalError"]),code:new Set([...H4,...Y4,...U4,...q4,...K4,"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","relocated","lock-timeout","managed-folder","malformed",...W5]),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"])},B5=new Set([...H4.flatMap(($)=>$==="no-read-grant"||$==="grant-reaches-nothing"?E$.map((Z)=>new J0($,Z).message):[new J0($).message]),...Y4.map(($)=>new g0($).message),...U4.map(($)=>new X5($).message),...q4.map(($)=>new G5($).message),...K4.map(($)=>`Native custody refused: ${$}`),W4,Q5,...$5,...H5,"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"]),V5=Object.values(v0).join("|"),j5="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",M5=[new RegExp(`^Claustrum approval is still pending\\. In another terminal, run: ck auth enroll approve --request-id [A-Za-z0-9_-]{1,128} --name (?:${V5}) 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\.$/],D5=new Set(["opencode","litecode","opencode2","pi","host"]),N5=64,L5=256,P5=4096,T$=65536,C5=4096,O5=3,J4="[output beyond the diagnostic limit omitted]",A5="[output withheld: no line break within the inspected window]",I5="[detail withheld: the known credentials could not be read safely]",f$=new TextEncoder,F4=new TextDecoder;function E($,Z){let J=Object.getOwnPropertyDescriptor($,Z);return J!==void 0&&"value"in J?J.value:void 0}function D0($){return $!==null&&(typeof $==="object"||typeof $==="function")&&!b$.isProxy($)}function x$($,Z){if(!D0($)||!Array.isArray($))return;let J=E($,"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 _5($){let Z=x$($,N5);if(Z===void 0||Z.length===0)return;let J=[];for(let z of Z){if(!D0(z))return;let X=E(z,"pid"),G=E(z,"command");if(typeof X!=="number"||!Number.isSafeInteger(X)||X<0)return;if(typeof G!=="string"||!D5.has(G.toLowerCase()))return;J.push({pid:X,command:G})}return J}function E1($){try{if(!D0($))return;if(E($,"name")==="ProcessInspectionError")return"";let Z=E($,"message");if(typeof Z!=="string")return;if(E($,"name")==="HostNotEnrolledError"&&Z===j5)return Z;if(B5.has(Z))return Z;if(E($,"name")==="StateLayoutRefusalError"){let X=E($,"code");if(z5(X))return U5(X)}if(E($,"name")==="NativeVaultActivationError"&&E($,"code")==="no-read-grant"){let X=E($,"host"),G=E($,"approvedName");if((X==="opencode"||X==="pi")&&typeof G==="string"){let Q=new J0("no-read-grant",X,G).message;if(Z===Q)return Q}}if(Z.startsWith("Unknown setup argument: "))return Z;if(E($,"name")==="HostNotEnrolledError"&&M5.some((X)=>X.test(Z)))return Z;if(E($,"code")==="ERR_PRIVATE_FILES_UNAVAILABLE")return W4;let J=E($,"status");if(typeof J==="number"&&Number.isInteger(J)&&J>=100&&J<=599&&Z===`OAuth metadata read failed: ${J}`)return Z;let z=_5(E($,"activeHosts"));if(z){let X=new k$(z).message;if(Z===X)return X}}catch{}return}function B4($){try{if(!D0($))return;let Z=x$(Y5($),E$.length);if(Z===void 0)return;let J=[];for(let z of Z){if(!D0(z))return;let X=E$.find((Q)=>Q===E(z,"host")),G=E(z,"outcome");if(X===void 0||!K5.has(G))return;J.push({host:X,outcome:G})}return J}catch{return}}function R5($,Z=[]){try{let J=new Set,z=x$(Z,L5);if(z===void 0)return;for(let G of z){if(typeof G!=="string")return;if(G!=="")J.add(G)}if(!D0($))return;let X=Reflect.ownKeys($);if(X.length>P5)return;for(let G of X){if(typeof G!=="string"||!J5(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 S5($,Z){let J=f$.encode($);if(J.length<=Z)return $;let z=Math.max(0,Z);while(z>0&&((J[z]??0)&192)===128)z-=1;return F4.decode(J.subarray(0,z))}function k5($,Z){let J=f$.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 F4.decode(J.subarray(z))}function T5($,Z,J){let z=$,X=!1;if($.length>T$){if(X=!0,J==="tail"){let H=$.indexOf(`
|
|
18
|
+
`,$.length-T$);z=H===-1?"":$.slice(H+1)}else{let H=$.lastIndexOf(`
|
|
19
|
+
`,T$);z=H===-1?"":$.slice(0,H)}if(z==="")return[A5]}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=C5;for(let H of G){let q=f$.encode(H).length+1;if(q<=W){Q.push(H),W-=q;continue}if(Q.length===0)Q.push(J==="tail"?k5(H,W-1):S5(H,W-1));X=!0;break}if(J==="tail")Q.reverse();if(X)if(J==="tail")Q.unshift(J4);else Q.push(J4);return Q}function V4($){let Z=$;for(let J=0;Z!==null&&J<8;J+=1){if(b$.isProxy(Z))break;let z=E(Z,"name");if(typeof z==="string")return z;Z=Object.getPrototypeOf(Z)}return"object"}function z4($,Z){let J={};if(Z===void 0)return J;try{if(!D0($))return J;let z=Q4(Z);try{for(let X of["name","code","stage","reason"]){let G=X==="name"?V4($):E($,X);if(typeof G==="string"&&F5[X].has(G)&&z.redactText(G)===G)J[X]=G}}finally{z.dispose()}}catch{return{}}return J}function E5($){if(!D0($))return;let Z=E($,"step"),J=E($,"exitCode"),z=E($,"signal"),X=E($,"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 j4($,Z){if($===null||typeof $!=="object"&&typeof $!=="function")return[`thrown ${typeof $}: ${String($)}`];if(b$.isProxy($))return["thrown proxy (not inspected)"];let J=[],z=V4($),X=E($,"message");J.push(typeof X==="string"?`${z}: ${X}`:`${z} (no message)`);let G=E($,"code");if(typeof G==="string"||typeof G==="number")J.push(`code: ${G}`);let Q=E($,"stack");if(typeof Q==="string")J.push(Q);let W=E($,"cause");if(W!==void 0)if(Z>=O5)J.push("caused by: [not described]");else J.push("caused by:",...j4(W,Z+1));return J}function X4($,Z){let J=E($,Z);return typeof J==="string"&&J!==""?J:void 0}function b5($){if(!D0($))return;let Z=X4($,"HOME"),J=o6({xdgStateHome:X4($,"XDG_STATE_HOME"),home:Z&&i6(Z)?Z:n6()});return G4(J,"diagnostics")}async function f5($,Z,J,z={}){let X=(G)=>({error:{name:"DiagnosticFileError",code:G}});try{let G=b5($);if(G===void 0)return X("ERR_DIAGNOSTICS_DIRECTORY_UNAVAILABLE");if(!await t6(G,z)){await a6(G,{recursive:!0,mode:448});let H=await l6(G);if(!H.isDirectory())return X("ERR_DIAGNOSTICS_NOT_DIRECTORY");if(!await Z5(G,()=>(H.mode&63)===0&&H.uid===process.getuid?.(),z))return X("ERR_DIAGNOSTICS_NOT_OWNER_ONLY")}let Q=G4(G,`${Z}-${Date.now()}-${process.pid}-${d6()}.log`);if(await r6(Q,J,z))return{path:Q};let W=await s6(Q,X3.O_WRONLY|X3.O_CREAT|X3.O_EXCL|(X3.O_NOFOLLOW??0),384);try{await W.writeFile(J,"utf8")}finally{await W.close()}return{path:Q}}catch(G){return{error:G}}}async function x5($,Z,J,z,X,G,Q,W={}){let H,q=R5(J,z);if(q===void 0)H=[I5];else try{let L=Q4(q);try{let{text:C,keep:A}=G();H=T5(C,L,A)}finally{L.dispose()}}catch{H=["[failure detail could not be recorded]"]}let Y=q5[$],U=e6("error","cli",`${Y} failed`,{stage:$,code:Z,...X}),M=await f5(J,$,`${[U,...H].join(`
|
|
20
20
|
`)}
|
|
21
|
-
`,W.ownership),
|
|
22
|
-
`)}catch{}}return
|
|
21
|
+
`,W.ownership),B=M.path;if(B===void 0){let L={error:z4(Q,q),saveError:z4(M.error,q)};try{(W.stderr??((A)=>process.stderr.write(A)))(`CLI failure metadata: ${JSON.stringify(L)}
|
|
22
|
+
`)}catch{}}return B===void 0?`${Y} failed (${Z}). Details could not be saved to a private diagnostics file.`:`${Y} failed (${Z}). Details were written to ${B}`}async function w0($,Z,J,z=[],X={}){let G=E1(Z);if(G!==void 0)return G;let Q=E5(Z);return x5($,`${$}/unexpected-error`,J,z,{},()=>({text:[...Q?[`step: ${Q.step}`,`exitCode: ${Q.exitCode}`,`signal: ${Q.signal}`]:[],...j4(Z,0),...Q?[`stderrTail:
|
|
23
23
|
${Q.stderrTail}`]:[]].join(`
|
|
24
|
-
`),keep:"head"}),Z,X)}import{assertHostsStopped as
|
|
25
|
-
`)J.push("enter");else if(X==="\x03")J.push("escape");else if(X&&X>=" ")J.push("char");z+=1}return J}var
|
|
26
|
-
`),L+=1},A=J.lines??[],I=1+(J.subtitle?3:0)+A.length+(A.length?1:0),R=Math.max(1,Math.min(Z.length,M-I-2-1)),
|
|
27
|
-
`),Y=!1;for(let
|
|
28
|
-
`){if(G)z+=
|
|
29
|
-
`){if(X&&
|
|
30
|
-
`)}var e=
|
|
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
|
|
24
|
+
`),keep:"head"}),Z,X)}import{assertHostsStopped as zJ,createProcessFence as W7,decideOpenCodeStateLayoutOnce as XJ,decidePiStateLayout as GJ,NativePiAuthSlotError as QJ,openNativePiAuthSlot as WJ,publishNativeEmptyInit as HJ,readNativeEnrollmentMode as YJ,releaseNativeMigrationPreflight as UJ,requireNoSupervisedAuthContentSnapshot as qJ,restoreLegacyLayout as KJ,runSetup as FJ,StateLayoutRefusalError as BJ,setupUsage as VJ}from"@cortexkit/anthropic-auth-core";import{AsyncLocalStorage as g5}from"node:async_hooks";var qW=new g5;var M4=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});var H1="commonAuthPool";var zZ=Object.freeze(["version","accounts",H1]);var jY=new M1;var S={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 d$($){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 _4=`${String.fromCharCode(27)}\\[[0-9;]*m`,XZ=new RegExp(_4,"g"),GZ=new RegExp(`^${_4}`);function R4($){return $.replace(XZ,"")}function u0($,Z){if(Z<=0)return"";if(R4($).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(GZ);if(W){X+=W[0],G+=W[0].length;continue}}X+=$[G],G+=1,Q+=1}return X.includes("\x1B[")?`${X}${S.reset}${J}`:X+J}function q1($){return $.input.isTTY===!0}var QZ=50;function WZ($){if($==="red")return S.red;if($==="cyan")return S.cyan;return""}async function Y3($,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,q=0,Y=()=>{let U=X.columns??80,M=X.rows??24,B=q;if(J.clearScreen)X.write(S.clearScreen+S.moveTo(1,1));else if(B>0)X.write(S.up(B));let L=0,C=(K)=>{X.write(`${S.clearLine}${K}
|
|
26
|
+
`),L+=1},A=J.lines??[],I=1+(J.subtitle?3:0)+A.length+(A.length?1:0),R=Math.max(1,Math.min(Z.length,M-I-2-1)),h=Math.max(0,Math.min(Q-Math.floor(R/2),Math.max(0,Z.length-R))),m=Z.slice(h,h+R);if(C(`${S.dim}┌ ${S.reset}${u0(J.message,Math.max(1,U-4))}`),J.subtitle)C(`${S.dim}│${S.reset}`),C(`${S.cyan}◆${S.reset} ${u0(J.subtitle,Math.max(1,U-4))}`),C("");for(let K of A)C(`${S.cyan}│${S.reset} ${u0(K,Math.max(1,U-4))}`);if(A.length)C(`${S.cyan}│${S.reset}`);for(let K=0;K<m.length;K++){let V=m[K];if(!V)continue;let P=h+K===Q,x=WZ(V.color),k=x?`${P?"":S.dim}${x}${V.label}${S.reset}`:P?V.label:`${S.dim}${V.label}${S.reset}`;if(V.hint)k+=` ${S.dim}${V.hint}${S.reset}`;k=u0(k,Math.max(1,U-8)),C(P?`${S.cyan}│${S.reset} ${S.green}●${S.reset} ${k}`:`${S.cyan}│${S.reset} ${S.dim}○${S.reset} ${k}`)}let F=m.length<Z.length?` (${h+1}-${h+m.length}/${Z.length})`:"";C(`${S.cyan}│${S.reset} ${S.dim}${u0(`Up/Down to select | Enter: confirm | Esc: back${F}`,Math.max(1,U-6))}${S.reset}`),C(`${S.cyan}└${S.reset}`);for(let K=L;K<B;K++)C("");q=L};return new Promise((U)=>{let M=z.isRaw??!1,B=()=>{if(H)return;if(H=!0,W)clearTimeout(W);z.removeListener("data",A);try{z.setRawMode(M),z.pause(),X.write(S.show)}catch{}G?.removeListener("SIGINT",C),G?.removeListener("SIGTERM",C)},L=(I)=>{B(),U(I)},C=()=>L(null),A=(I)=>{for(let R of d$(I)){if(H)break;if(W)clearTimeout(W),W=null;switch(R){case"up":Q=(Q-1+Z.length)%Z.length,Y();break;case"down":Q=(Q+1)%Z.length,Y();break;case"enter":L(Z[Q]?.value??null);break;case"escape":L(null);break;case"escape-start":W=setTimeout(()=>L(null),QZ);break;default:break}}};G?.once("SIGINT",C),G?.once("SIGTERM",C);try{z.setRawMode(!0)}catch{B(),U(null);return}z.resume(),X.write(S.hide),Y(),z.on("data",A)})}async function U3($,Z,J=!1){if(!q1($))return!1;return await Y3($,J?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:Z})??!1}import{execFile as FZ}from"node:child_process";import{promisify as BZ}from"node:util";var VZ=BZ(FZ),l$={async run($,Z,J={}){try{let z=J.env?{...process.env,...J.env}:process.env,{stdout:X,stderr:G}=await VZ($,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 j3}from"node:util";import{stdout as bZ,stdin as fZ}from"node:process";import xZ from"node:readline";var S4=(()=>{let $=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(Z)=>{let J=0;$.lastIndex=0;while($.test(Z))J+=1;return Z.length-J}})(),k4=($)=>{return $===12288||$>=65281&&$<=65376||$>=65504&&$<=65510},T4=($)=>{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 jZ=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,MZ=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,E4=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,DZ=/\t{1,1000}/y,b4=/[\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,NZ=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,LZ=/\p{M}+/gu,PZ={limit:1/0,ellipsis:""},f4=($,Z={},J={})=>{let z=Z.limit??1/0,X=Z.ellipsis??"",G=Z?.ellipsisWidth??(X?f4(X,PZ,J).width:0),Q=0,W=J.controlWidth??0,H=J.tabWidth??8,q=J.emojiWidth??2,Y=2,U=J.regularWidth??1,M=J.wideWidth??2,B=[[NZ,U],[jZ,0],[MZ,W],[DZ,H],[b4,q],[E4,M]],L=0,C=0,A=$.length,I=0,R=!1,h=A,m=Math.max(0,z-G),F=0,K=0,V=0,P=0;$:while(!0){if(K>F||C>=A&&C>L){let x=$.slice(F,K)||$.slice(L,C);I=0;for(let k of x.replaceAll(LZ,"")){let y=k.codePointAt(0)||0;if(k4(y))P=2;else if(T4(y))P=M;else P=U;if(V+P>m)h=Math.min(h,Math.max(F,L)+I);if(V+P>z){R=!0;break $}I+=k.length,V+=P}F=K=0}if(C>=A)break $;for(let x=0,k=B.length;x<k;x++){let[y,$0]=B[x];if(y.lastIndex=C,y.test($)){if(I=y===E4?S4($.slice(C,y.lastIndex)):y===b4?1:y.lastIndex-C,P=I*$0,V+P>m)h=Math.min(h,C+Math.floor((m-V)/$0));if(V+P>z){R=!0;break $}V+=P,F=L,K=C,C=L=y.lastIndex;continue $}}C+=1}return{width:R?m:V,index:R?h:A,truncated:R,ellipsed:R&&z>=G}},x4=f4;var CZ={limit:1/0,ellipsis:"",ellipsisWidth:0},OZ=($,Z={})=>{return x4($,CZ,Z).width},Y0=OZ;var q3="\x1B",m4="",AZ=39,s$="\x07",w4="[",IZ="]",u4="m",n$=`${IZ}8;;`,y4=new RegExp(`(?:\\${w4}(?<code>\\d+)m|\\${n$}(?<uri>.*)${s$})`,"y"),g4=($)=>{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},v4=($)=>`${q3}${w4}${$}${u4}`,h4=($)=>`${q3}${n$}${$}${s$}`,a$=($,Z,J)=>{let z=Z[Symbol.iterator](),X=!1,G=!1,Q=$.at(-1),W=Q===void 0?0:Y0(Q),H=z.next(),q=z.next(),Y=0;while(!H.done){let U=H.value,M=Y0(U);if(W+M<=J)$[$.length-1]+=U;else $.push(U),W=0;if(U===q3||U===m4)X=!0,G=Z.startsWith(n$,Y+1);if(X){if(G){if(U===s$)X=!1,G=!1}else if(U===u4)X=!1}else if(W+=M,W===J&&!q.done)$.push(""),W=0;H=q,q=z.next(),Y+=U.length}if(Q=$.at(-1),!W&&Q!==void 0&&Q.length&&$.length>1)$[$.length-2]+=$.pop()},_Z=($)=>{let Z=$.split(" "),J=Z.length;while(J){if(Y0(Z[J-1]))break;J--}if(J===Z.length)return $;return Z.slice(0,J).join(" ")+Z.slice(J).join("")},RZ=($,Z,J={})=>{if(J.trim!==!1&&$.trim()==="")return"";let z="",X,G,Q=$.split(" "),W=[""],H=0;for(let U=0;U<Q.length;U++){let M=Q[U];if(J.trim!==!1){let L=W.at(-1)??"",C=L.trimStart();if(L.length!==C.length)W[W.length-1]=C,H=Y0(C)}if(U!==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 B=Y0(M);if(J.hard&&B>Z){let L=Z-H,C=1+Math.floor((B-L-1)/Z);if(Math.floor((B-1)/Z)<C)W.push("");a$(W,M,Z),H=Y0(W.at(-1)??"");continue}if(H+B>Z&&H&&B){if(J.wordWrap===!1&&H<Z){a$(W,M,Z),H=Y0(W.at(-1)??"");continue}W.push(""),H=0}if(H+B>Z&&J.wordWrap===!1){a$(W,M,Z),H=Y0(W.at(-1)??"");continue}W[W.length-1]+=M,H+=B}if(J.trim!==!1)W=W.map((U)=>_Z(U));let q=W.join(`
|
|
27
|
+
`),Y=!1;for(let U=0;U<q.length;U++){let M=q[U];if(z+=M,!Y){if(Y=M>="\uD800"&&M<="\uDBFF",Y)continue}else Y=!1;if(M===q3||M===m4){y4.lastIndex=U+1;let L=y4.exec(q)?.groups;if(L?.code!==void 0){let C=Number.parseFloat(L.code);X=C===AZ?void 0:C}else if(L?.uri!==void 0)G=L.uri.length===0?void 0:L.uri}if(q[U+1]===`
|
|
28
|
+
`){if(G)z+=h4("");let B=X?g4(X):void 0;if(X&&B)z+=v4(B)}else if(M===`
|
|
29
|
+
`){if(X&&g4(X))z+=v4(X);if(G)z+=h4(G)}}return z},SZ=/\r?\n/;function K3($,Z,J){return String($).normalize().split(SZ).map((z)=>RZ(z,Z,J)).join(`
|
|
30
|
+
`)}var e=l4(o$(),1);function t$($,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?t$(G,Z<0?-1:1,J):G}function F3($,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 yZ=["up","down","left","right","space","enter","cancel"],gZ=["January","February","March","April","May","June","July","August","September","October","November","December"],z0={actions:new Set(yZ),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:[...gZ],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 vZ($){if($!==void 0)return $;if(z0.accessible!==void 0)return z0.accessible;let Z=process.env.ACCESSIBLE;return Z!==void 0&&Z!==""&&Z!=="0"&&Z!=="false"}function a4($,Z){if(typeof $=="string")return z0.aliases.get($)===Z;for(let J of $)if(J!==void 0&&a4(J,Z))return!0;return!1}function hZ($,Z){if($===Z)return;let J=$.split(`
|
|
32
32
|
`),z=Z.split(`
|
|
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
|
|
34
|
-
`),
|
|
35
|
-
`).length-1;this.output.write(e.cursor.move(-999,$*-1))}render(){let $=
|
|
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 Nq=globalThis.process.platform.startsWith("win"),M3=Symbol("clack:cancel");function D3($){return $===M3}function B3($,Z){let J=$;J.isTTY&&J.setRawMode(Z)}var s4=($)=>("rows"in $)&&typeof $.rows=="number"?$.rows:20;function n4($,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 K1{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return vZ(this.opts.accessible)}constructor($,Z=!0){let{input:J=fZ,output:z=bZ,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(),$(M3);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=xZ.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),B3(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(e.cursor.show),this.output.off("resize",this.render),B3(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(e.cursor.show),this.output.off("resize",this.render),B3(this.input,!1),$(M3)})})}_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&&z0.aliases.has(Z.name)&&this.emit("cursor",z0.aliases.get(Z.name)),z0.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=n4(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")}a4([$,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
|
+
`),B3(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let $=K3(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
35
|
+
`).length-1;this.output.write(e.cursor.move(-999,$*-1))}render(){let $=K3(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if($!==this._prevFrame){if(this.state==="initial")this.output.write(e.cursor.hide);else{let Z=hZ(this._prevFrame,$),J=s4(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(e.cursor.move(0,G-X)),this.output.write(e.erase.lines(1));let Q=$.split(`
|
|
36
36
|
`);this.output.write(Q[G]),this._prevFrame=$,this.output.write(e.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(e.cursor.move(0,W))}this.output.write(e.erase.down());let Q=$.split(`
|
|
37
37
|
`).slice(G);this.output.write(Q.join(`
|
|
38
|
-
`)),this._prevFrame=$;return}}this.output.write(e.erase.down())}this.output.write($),this.state==="initial"&&(this.state="active"),this._prevFrame=$}}}function gZ($,Z){if($===void 0||Z.length===0)return 0;let J=Z.findIndex((z)=>z.value===$);return J!==-1?J:0}function vZ($,Z){return(Z.label??String(Z.value)).toLowerCase().includes($.toLowerCase())}function hZ($,Z){if(Z)return $?Z:Z[0]}var mZ=class extends F1{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Z="";#J;#W;#G;#Q;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return B3(["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}${B3("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??vZ;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((Y)=>!Y.disabled&&(this.#J?this.#J(W,Y):!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 Y=String(this.focusedValue);this._clearUserInput(),this._setUserInput(Y,!0),this.isNavigating=!1;return}z||X?(this.#$=o$(this.#$,z?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):G?this.value=hZ(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=gZ(this.focusedValue,this.filteredOptions);this.#$=o$(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 wZ={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function w4($){return[...$].map((Z)=>wZ[Z])}function uZ($){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 i$($){return Number.parseInt(($||"0").replace(/_/g,"0"),10)||0}function V3($){return{year:i$($.year),month:i$($.month),day:i$($.day)}}function r$($,Z){return new Date($||2001,Z||1,0).getDate()}function a4($){let{year:Z,month:J,day:z}=V3($);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 u4($){let Z=a4($);return Z?new Date(Date.UTC(Z.year,Z.month-1,Z.day)):void 0}function cZ($,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:r$(Z.year,Z.month)}}class s4 extends F1{#$;#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.#j(this.#J)}#j($){return this.#$.map((Z)=>$[Z.type]).join(this.#Z)}#H(){this._setUserInput(this.#j(this.#J)),this._setValue(u4(this.#J)??void 0)}constructor($){let Z=$.format?{segments:w4($.format),separator:$.separator??"/"}:uZ($.locale),J=$.separator??Z.separator,z=$.format?w4($.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.#M(W,H)),this.on("finalize",()=>this.#N($))}#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)}#V($){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=cZ(J.type,V3(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.#V(1);case"down":return this.#V(-1)}}#M($,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 M=this.#X+$,V={...this.#J,[z.type]:M},L=this.#B(V,z);if(L){this.inlineError=L,this.#X=null,this.#z=!1;return}this.inlineError="",this.#J[z.type]=M,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 M=Number.parseInt($,10);H=`0${$}`,U=M<=(z.type==="month"?1:2)}if(z.type==="year"&&(H=(G.replace(/_/g,"")+$).padStart(z.len,"_")),!H.includes("_")){let M={...this.#J,[z.type]:H},V=this.#B(M,z);if(V){this.inlineError=V;return}}this.inlineError="",this.#J[z.type]=H;let Y=H.includes("_")?void 0:a4(this.#J);if(Y){let{year:M,month:V}=Y,L=r$(M,V);this.#J={year:String(Math.max(0,Math.min(9999,M))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,V))).padStart(2,"0"),day:String(Math.max(1,Math.min(L,Y.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}=V3($);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")}#N($){let{year:Z,month:J,day:z}=V3(this.#J);if(Z&&J&&z){let X=r$(Z,J);this.#J={...this.#J,day:String(Math.min(z,X)).padStart(2,"0")}}this.value=u4(this.#J)??$.defaultValue??void 0}}var pZ=class extends F1{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}})}},dZ=new Set(["up","down","left","right"]);class n4 extends F1{#$=!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(e.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 wZ($,Z){return(Z.label??String(Z.value)).toLowerCase().includes($.toLowerCase())}function uZ($,Z){if(Z)return $?Z:Z[0]}var cZ=class extends K1{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Z="";#J;#W;#G;#Q;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return j3(["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}${j3("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??wZ;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.#X(X,G)),this.on("userInput",(X)=>this.#z(X))}_isActionKey(Z,J){return Z==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&Z!==void 0&&Z!==""}#X(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,q=W!==void 0&&W!==""&&H.some((Y)=>!Y.disabled&&(this.#J?this.#J(W,Y):!0));if(J.name==="tab"&&Q&&q){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 Y=String(this.focusedValue);this._clearUserInput(),this._setUserInput(Y,!0),this.isNavigating=!1;return}z||X?(this.#$=t$(this.#$,z?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):G?this.value=uZ(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])}#z(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.#$=t$(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 pZ={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function p4($){return[...$].map((Z)=>pZ[Z])}function dZ($){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 r$($){return Number.parseInt(($||"0").replace(/_/g,"0"),10)||0}function V3($){return{year:r$($.year),month:r$($.month),day:r$($.day)}}function e$($,Z){return new Date($||2001,Z||1,0).getDate()}function i4($){let{year:Z,month:J,day:z}=V3($);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 d4($){let Z=i4($);return Z?new Date(Date.UTC(Z.year,Z.month-1,Z.day)):void 0}function lZ($,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:e$(Z.year,Z.month)}}class o4 extends K1{#$;#Z;#J;#W;#G;#Q={segmentIndex:0,positionInSegment:0};#X=!0;#z=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.#D(this.#J)}#D($){return this.#$.map((Z)=>$[Z.type]).join(this.#Z)}#H(){this._setUserInput(this.#D(this.#J)),this._setValue(d4(this.#J)??void 0)}constructor($){let Z=$.format?{segments:p4($.format),separator:$.separator??"/"}:dZ($.locale),J=$.separator??Z.separator,z=$.format?p4($.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.#L($))}#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:$}}#K($){this.inlineError="",this.#z=null;let Z=this.#Y();Z&&(this.#Q.segmentIndex=Math.max(0,Math.min(this.#$.length-1,Z.index+$)),this.#Q.positionInSegment=0,this.#X=!0)}#V($){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=lZ(J.type,V3(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.#X=!0,this.#z=null,this.#H()}#U($){if($)switch($){case"right":return this.#K(1);case"left":return this.#K(-1);case"up":return this.#V(1);case"down":return this.#V(-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.#K(-1);return}this.#J[J.segment.type]="_".repeat(J.segment.len),this.#X=!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.#X=!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.#X&&this.#z!==null&&!X){let M=this.#z+$,B={...this.#J,[z.type]:M},L=this.#M(B,z);if(L){this.inlineError=L,this.#z=null,this.#X=!1;return}this.inlineError="",this.#J[z.type]=M,this.#z=null,this.#X=!1,this.#H(),J.index<this.#$.length-1&&(this.#Q.segmentIndex=J.index+1,this.#Q.positionInSegment=0,this.#X=!0);return}this.#X&&!X&&(this.#J[z.type]="_".repeat(z.len),this.#Q.positionInSegment=0),this.#X=!1,this.#z=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),q=!1;if(W===0&&G==="__"&&(z.type==="month"||z.type==="day")){let M=Number.parseInt($,10);H=`0${$}`,q=M<=(z.type==="month"?1:2)}if(z.type==="year"&&(H=(G.replace(/_/g,"")+$).padStart(z.len,"_")),!H.includes("_")){let M={...this.#J,[z.type]:H},B=this.#M(M,z);if(B){this.inlineError=B;return}}this.inlineError="",this.#J[z.type]=H;let Y=H.includes("_")?void 0:i4(this.#J);if(Y){let{year:M,month:B}=Y,L=e$(M,B);this.#J={year:String(Math.max(0,Math.min(9999,M))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,B))).padStart(2,"0"),day:String(Math.max(1,Math.min(L,Y.day))).padStart(2,"0")}}this.#H();let U=H.indexOf("_");q?(this.#X=!0,this.#z=$):U>=0?this.#Q.positionInSegment=U:Q>=0&&J.index<this.#$.length-1?(this.#Q.segmentIndex=J.index+1,this.#Q.positionInSegment=0,this.#X=!0):this.#Q.positionInSegment=Math.min(W+1,z.len-1)}}#M($,Z){let{month:J,day:z}=V3($);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")}#L($){let{year:Z,month:J,day:z}=V3(this.#J);if(Z&&J&&z){let X=e$(Z,J);this.#J={...this.#J,day:String(Math.min(z,X)).padStart(2,"0")}}this.value=d4(this.#J)??$.defaultValue??void 0}}var aZ=class extends K1{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}})}},sZ=new Set(["up","down","left","right"]);class r4 extends K1{#$=!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===`
|
|
39
39
|
`?`${Z}█
|
|
40
|
-
${z}`:`${Z}${
|
|
40
|
+
${z}`:`${Z}${j3("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=F3(this._cursor,0,-1,Z);return;case"down":this._cursor=F3(this._cursor,0,1,Z);return;case"left":this._cursor=F3(this._cursor,-1,0,Z);return;case"right":this._cursor=F3(this._cursor,1,0,Z);return}}_shouldSubmit($,Z){if(this.#Z)return this.focused==="submit"?!0:(this.#J(`
|
|
41
41
|
`),this._cursor++,!1);let J=this.#$;return this.#$=!0,J&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
|
|
42
42
|
`&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#J(`
|
|
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&&
|
|
44
|
-
`:""}${
|
|
45
|
-
`,z=$.placeholder&&$.placeholder.length>0?
|
|
46
|
-
${W} ${
|
|
47
|
-
`}case"error":{let Q=this.error?` ${
|
|
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&&sZ.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 $2 extends K1{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}${j3("inverse",J)}${z}`}get cursor(){return this._cursor}constructor($){super({...$,initialUserInput:$.initialUserInput??$.initialValue}),this.on("userInput",(Z)=>{this._setValue(Z)}),this.on("finalize",()=>{this.value||(this.value=$.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as b,stripVTControlCharacters as bq}from"node:util";import X0 from"node:process";var e4=l4(o$(),1);function nZ(){if(X0.platform!=="win32")return X0.env.TERM!=="linux";return Boolean(X0.env.CI)||Boolean(X0.env.WT_SESSION)||Boolean(X0.env.TERMINUS_SUBLIME)||X0.env.ConEmuTask==="{cmd::Cmder}"||X0.env.TERM_PROGRAM==="Terminus-Sublime"||X0.env.TERM_PROGRAM==="vscode"||X0.env.TERM==="xterm-256color"||X0.env.TERM==="alacritty"||X0.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var iZ=nZ();var f=($,Z)=>iZ?$:Z,t4=f("◆","*"),oZ=f("■","x"),rZ=f("▲","x"),tZ=f("◇","o"),gq=f("┌","T"),c0=f("│","|"),Z2=f("└","—"),vq=f("┐","T"),hq=f("┘","—"),mq=f("●",">"),wq=f("○"," "),uq=f("◻","[•]"),cq=f("◼","[+]"),pq=f("◻","[ ]"),dq=f("▪","•"),lq=f("─","-"),aq=f("╮","+"),sq=f("├","+"),nq=f("╯","+"),iq=f("╰","+"),oq=f("╭","+"),rq=f("●","•"),tq=f("◆","*"),eq=f("▲","!"),$K=f("■","x"),eZ=($)=>{switch($){case"initial":case"active":return b("cyan",t4);case"cancel":return b("red",oZ);case"error":return b("yellow",rZ);case"submit":return b("green",tZ);case"validating":return b("dim",t4)}};var ZK=[`${b("dim","↑/↓")} to navigate`,`${b("dim","Space:")} select`,`${b("dim","Enter:")} confirm`];var JK={light:f("─","-"),heavy:f("━","="),block:f("█","#")};var zK=[`${b("dim","↑/↓")} to navigate`,`${b("dim","Enter:")} confirm`];var XK=`${b("gray",c0)} `;var $7=($)=>new $2({validate:$.validate,placeholder:$.placeholder,defaultValue:$.defaultValue,initialValue:$.initialValue,output:$.output,signal:$.signal,input:$.input,render(){let Z=$?.withGuide??z0.withGuide,J=`${`${Z?`${b("gray",c0)}
|
|
44
|
+
`:""}${eZ(this.state)} `}${$.message}
|
|
45
|
+
`,z=$.placeholder&&$.placeholder.length>0?b("inverse",$.placeholder[0])+b("dim",$.placeholder.slice(1)):b(["inverse","hidden"],"_"),X=this.userInput?this.userInputWithCursor:z,G=this.value??"";switch(this.state){case"validating":{let Q=Z?`${b("cyan",c0)} `:"",W=Z?b("cyan",Z2):"",H=b("dim",X),q=b("dim","Validating...");return`${J}${Q}${H}
|
|
46
|
+
${W} ${q}
|
|
47
|
+
`}case"error":{let Q=this.error?` ${b("yellow",this.error)}`:"",W=Z?`${b("yellow",c0)} `:"",H=Z?b("yellow",Z2):"";return`${J.trim()}
|
|
48
48
|
${W}${X}
|
|
49
49
|
${H}${Q}
|
|
50
|
-
`}case"submit":{let Q=G?`${Z?" ":""}${
|
|
51
|
-
${W}`:""}`}default:{let Q=Z?`${
|
|
50
|
+
`}case"submit":{let Q=G?`${Z?" ":""}${b("dim",G)}`:"",W=Z?b("gray",c0):"";return`${J}${W}${Q}`}case"cancel":{let Q=G?` ${b(["strikethrough","dim"],G)}`:"",W=Z?b("gray",c0):"";return`${J}${W}${Q}${G.trim()?`
|
|
51
|
+
${W}`:""}`}default:{let Q=Z?`${b("cyan",c0)} `:"",W=Z?b("cyan",Z2):"";return`${J}${Q}${X}
|
|
52
52
|
${W}
|
|
53
|
-
`}}}}).prompt();import{authorize as
|
|
54
|
-
`)}function U0($,Z){let J=$.get(Z);if(!J)throw Error("Missing setup plan");return J}async function
|
|
55
|
-
`);if($.some((
|
|
53
|
+
`}}}}).prompt();import{authorize as $J,exchange as ZJ,resolveClaudeCodeIdentity as JJ}from"@cortexkit/anthropic-auth-core";async function Z7($,Z={authorize:$J,exchange:ZJ,resolveClaudeCodeIdentity:JJ,text:$7,isCancel:D3,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 J7='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.',jJ="npx @cortexkit/opencode-anthropic-auth setup",J2="--remove-pi-auth",L3="--restore-legacy",H7="-y",Y7=["--help","-h"],z7=[{label:J2,description:"Agree in advance to move a stored Pi Anthropic login out of the way: into the local account pool, or aside privately for vault use (restored on disconnect)."},{label:L3,description:"Move anthropic-auth's state from the CortexKit state folder back into OpenCode's config folder, for example before going back to an older version. Close every OpenCode, OpenCode 2 server and Pi first. Use it on its own."},{label:H7,description:"Same as --yes."},{label:Y7.join(", "),description:"Show this help."}];function MJ(){let $=Math.max(...z7.map((Z)=>Z.label.length));return[VJ({command:jJ}),"","Also accepted by this command:",...z7.map((Z)=>` ${Z.label.padEnd($)} ${Z.description}`),"","--login cannot be combined with --claustrum, or with --opencode=2: for OpenCode 2, sign in from OpenCode itself."].join(`
|
|
54
|
+
`)}function U0($,Z){let J=$.get(Z);if(!J)throw Error("Missing setup plan");return J}async function U7($=[],Z={}){let J={...Z.env??process.env},z=Z.terminal??{input:process.stdin,output:process.stdout,signals:process},X=(K)=>z.output.write(`${K}
|
|
55
|
+
`);if($.some((K)=>Y7.includes(K)))return X(MJ()),0;if($.includes(L3))return DJ($,Z,J,X);let G=$.filter((K)=>K!==J2).map((K)=>K===H7?"--yes":K),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(N3),1;let W=Z.runner??l$,H=Z.fence??W7(W,{platform:Z.platform}),q=Z.migrateLocal??r9,Y=new Map,U=new Map,M=new Map,B=new Map,L=[],C=!1,A="setup-process-check",I=(K)=>({env:J,fence:H,paths:M.get(K),removePiAnthropicAuth:B.get(K)??!1}),R=(K)=>({...I(K),runner:W});async function h(K){if(!K.hosts.includes("pi"))return;let V=U0(M,"pi");if((await S1("pi",V.hostAuthPath)).kind==="absent")return;{let y=await WJ({env:J,authPath:V.hostAuthPath}).inspect();if(y.slot==="placeholder"&&y.stash==="missing")throw new QJ("missing-stash");if(K.mode==="claustrum"){if(y.slot==="placeholder")return}}if($.includes(J2)){B.set("pi",!0);return}let x=K.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 n(x);if(!await U3(z,K.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 n("Native account-pool setup cannot finish while the stored Pi OAuth token takes precedence.");B.set("pi",!0)}async function m(K,V){let P=U0(U,K);if(await YJ(K,J)!==(V?"claustrum":P.priorMode)||await k1(K,R(K))!==P.fingerprint)throw new n("Setup inputs changed. Rerun setup with all hosts stopped.")}let F={packages:{opencode:X7,pi:G7},version:await Q7(),displayName:"CortexKit Anthropic Auth",slashCommand:"/claude",vault:{connectionFile:M$(J.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE&&!J.OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE?"pi":"opencode",J),hosts:{opencode:{name:v0.opencode,paths:j$("opencode",J)},pi:{name:v0.pi,paths:j$("pi",J)}}},async beforeSignIn(K,V){if(A=V.mode==="claustrum"?"setup-activation":"cli-setup",!C){if(qJ(J),V.hosts.includes("opencode")){let P=await XJ({role:"setup",env:J});if(P.kind!=="state-home"&&P.registration)L.push(P.registration)}for(let P of V.hosts)M.set(P,await M0(P,J));if(await d9([...M.values()]),V.hosts.includes("pi"))L.push((await GJ({paths:U0(M,"pi").paths,role:"setup"})).registration);if(V.mode==="claustrum"){let P=V.hosts.map((k)=>M$(k,J)),x=P[0];if(new Set(P).size!==1||!x)throw new n("Selected hosts use different vault connection files.");F.vault.connectionFile=x}if(V.mode==="local"&&Q&&V.hosts.includes("opencode")&&V.opencodeGeneration==="2")throw new n(N3);if(V.mode==="local"){await C$(V.hosts,J);for(let P of V.hosts)await m0(P,I(P))()}await h(V);for(let P of V.hosts)if(V.mode==="claustrum"){if(U.set(P,await(Z.vaultPreflight??$4)(P,{...R(P),inspectOpenCodeAuth:V.opencodeGeneration!=="2"})),U0(U,P).separateOpenCodeLogin)X(J7)}else Y.set(P,await A$(P,I(P),P==="opencode"&&V.opencodeGeneration==="2"));C=!0}else if(V.mode==="claustrum")await m(K,!1);else await W1(U0(Y,K),I(K))},async signInLocal(K){let V=U0(Y,K);if(!Q){if(V.generation2)X(N3);return}if(await W1(V,I(K)),await q(K,{...I(K),login:Z.localLogin??Z7,preflight:V.preflight,skipMigration:V.action==="skip",beforeCommit:()=>W1(V,I(K))}),V.fingerprint=await z3(V,J),V.notice)X(P$)},async beforeRegister(K,V){if(V==="local")await W1(U0(Y,K),I(K));else await m(K,!0),await(Z.vaultActivate??Z4)(K,R(K),U0(U,K)),U0(U,K).fingerprint=await k1(K,R(K))},async migrate(K,V){if(V.mode==="claustrum"){if(await m(K,!0),K===V.hosts.at(-1)&&U.get("opencode")?.separateOpenCodeLogin)X(J7);return}let P=U0(Y,K);if(await W1(P,I(K)),Q)return;if(P.action==="migration")await q(K,{...I(K),preflight:P.preflight});else if(P.action==="empty-init")await HJ({paths:P.paths.paths,routingDestinationPath:P.paths.routingDestinationPath,env:J,processFence:m0(K,I(K))});else if(P.action==="skip"){if(await I$(P,I(K)),P.notice)X(P$)}P.fingerprint=await z3(P,J)}};try{return await FJ(F,G,{...Z,env:J,terminal:z,runner:W,fence:H}),0}catch(K){let P=a9(K)??E1(K)??await w0(A,K,J);if(P)X(P);for(let{host:x,outcome:k}of B4(K)??[]){if(k!=="enrolled")continue;let y=x==="opencode"?"OpenCode":"Pi";X(`${y} stays connected to the vault. In ${y}, run /claude → Accounts → Disconnect from the vault to undo it. Or run setup again to finish connecting.`)}return 1}finally{for(let K of L)K.close();for(let K of Y.values())if(K.preflight)UJ(K.preflight)}}async function DJ($,Z,J,z){if($.some((Q)=>Q!==L3))return z(`${L3} runs on its own; run it without other options.`),1;let X=Z.runner??l$,G=Z.fence??W7(X,{platform:Z.platform});try{await zJ(G,J)}catch(Q){let W=Q1(Q)??E1(Q);return z(W??await w0("setup-process-check",Q,J)),1}try{let Q=await(Z.restoreLegacy??KJ)({env:J});if(Q.status==="not-moved")return z(`Nothing to restore: ${Q.reason}.`),0;z(`anthropic-auth's state is back in ${Q.oldDir}.`);for(let W of Q.kept)z(`${W} changed after it was copied back and was left in place; delete it once you have checked it.`);return 0}catch(Q){if(Q instanceof BJ)return z(Q.message),1;return z(E1(Q)??await w0("cli-setup",Q,J)),1}}async function F1($){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Native account changes require offline setup without OPENCODE_AUTH_CONTENT");let Z=await AJ({role:"cli"}),J=await EJ(void 0,void 0,Z.layout),z=OJ({paths:J,host:"opencode"});try{return await z.read(),await $(z)}finally{if(Z.kind!=="state-home")Z.registration?.close();await z.close()}}async function P3(){if(await TJ("opencode",process.env)!=="local")throw Error("Disconnect from the vault first.")}function q7(){console.log(`Usage:
|
|
56
56
|
opencode-anthropic-auth setup [--yes] [--dry-run]
|
|
57
57
|
opencode-anthropic-auth login [label]
|
|
58
58
|
opencode-anthropic-auth api add [label]
|
|
@@ -63,9 +63,9 @@ Setup --yes selects every found host, including Pi. Run setup without --yes to c
|
|
|
63
63
|
Run setup --help to list every setup option.
|
|
64
64
|
Native credentials are managed by the offline setup migration.
|
|
65
65
|
Legacy import source:
|
|
66
|
-
${
|
|
66
|
+
${SJ()}`)}function z2($,Z){let J=$?.trim();if(!J)throw Error(`${Z} is required`);return J}async function A3($){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 fJ($,Z,J,z){return A3({token:$,method:"POST",path:`/accounts/${Z}/storage/kv/namespaces`,body:JSON.stringify({title:J}),fetchImpl:z})}async function xJ($){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([bJ],{type:"application/javascript+module"}),"worker.js"),A3({token:$.token,method:"PUT",path:`/accounts/${$.accountId}/workers/scripts/${$.scriptName}`,body:J,fetchImpl:$.fetchImpl})}async function yJ($,Z,J,z){await A3({token:$,method:"POST",path:`/accounts/${Z}/workers/scripts/${J}/subdomain`,body:JSON.stringify({enabled:!0,previews_enabled:!1}),fetchImpl:z})}async function gJ($,Z,J){return A3({token:$,method:"GET",path:`/accounts/${Z}/workers/subdomain`,fetchImpl:J}).catch(()=>null)}async function vJ($={}){await F1((B)=>B.read());let Z=$.fetchImpl??fetch,J=$.prompt??O3,z=$.warn??((B)=>console.warn(B)),X=z2(process.env.CLOUDFLARE_API_TOKEN?.trim()||await J("Cloudflare API token: "),"Cloudflare API token");$.secrets?.push(X);let G=z2(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=RJ();$.secrets?.push(H),console.log("Creating Cloudflare KV namespace...");let q=await fJ(X,G,W,Z);console.log("Uploading relay Worker..."),await xJ({token:X,accountId:G,scriptName:Q,kvNamespaceId:q.id,relayToken:H,fetchImpl:Z}),await yJ(X,G,Q,Z).catch(async(B)=>{z(await w0("cli-relay-workers-dev",B,process.env,[X,H]))});let Y=await gJ(X,G,Z),M=(Y?.subdomain?`https://${Q}.${Y.subdomain}.workers.dev`:"")||z2(await O3("Relay Worker URL: "),"Relay Worker URL");await F1((B)=>B.updateRelay({enabled:!0,url:M,token:H,fallbackToDirect:!0,transport:"http"})),console.log(`Relay enabled at ${M}`),console.log("Relay settings saved to the native account store.")}var C3=null;async function O3($){return C3??=PJ({input:NJ,output:LJ}),(await C3.question($)).trim()}function hJ(){C3?.close(),C3=null}async function mJ($,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??O3,z=Z.authorize??CJ,X=Z.exchange??IJ;await P3(),await F1(async(G)=>{let Q=await G.read(),W=$?.trim()||await J("Fallback account label (optional): "),H=await z("max");console.log(`
|
|
67
67
|
Open this URL in your browser and complete Claude sign-in:
|
|
68
68
|
`),console.log(`${H.url}
|
|
69
|
-
`);let
|
|
70
|
-
Saved native fallback account${W?` "${W}"`:""}.`)})}async function
|
|
71
|
-
Saved API fallback route${z?` "${z}"`:""} (${X}).`)}async function
|
|
69
|
+
`);let q=await J("Paste the full callback URL or authorization code here: ");Z.secrets?.push(q);let Y=await X(q,H.verifier,H.redirectUri,H.state);if(Y.type==="failed")throw Error("Authentication failed");if(Z.secrets?.push(Y.access,Y.refresh),process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Local login cannot be verified while OPENCODE_AUTH_CONTENT is set");await P3();let U=W&&W!=="main"?W:crypto.randomUUID(),M=Q.accounts.some((B)=>B.id===U&&B.source==="local");await G.loginOAuth({routeId:U,replace:M,label:W||void 0,credential:{access:Y.access,refresh:Y.refresh,expires:Y.expires}}),console.log(`
|
|
70
|
+
Saved native fallback account${W?` "${W}"`:""}.`)})}async function wJ($,Z={}){await P3(),await F1((H)=>H.read());let J=Z.prompt??O3,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(!kJ(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 F1(async(H)=>{await P3();let q=await H.read(),Y=z&&z!=="main"?z:crypto.randomUUID(),U=q.accounts.find((M)=>M.id===Y);if(U?.source==="vault")throw Error("Vault routes cannot be replaced with a local API key");await H.addApi({routeId:Y,replace:Boolean(U),label:z||void 0,apiKey:G.trim(),baseURL:X,authHeader:W})}),console.log(`
|
|
71
|
+
Saved API fallback route${z?` "${z}"`:""} (${X}).`)}async function uJ(){await F1(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?` — ${_J(z)}`:""}`)}})}async function cJ($){let[Z,J,z]=process.argv.slice(2);if(!Z||Z==="help"||Z==="--help"||Z==="-h"){q7();return}if(Z==="setup"){$.stage="cli-setup";let X=await U7(process.argv.slice(3));if(X!==0)process.exitCode=X;return}if(Z==="login"){$.stage="cli-login",await mJ(J,{secrets:$.secrets});return}if(Z==="api"&&J==="add"){$.stage="cli-api-add",await wJ(z,{secrets:$.secrets});return}if(Z==="list"){$.stage="cli-list",await uJ();return}if(Z==="relay"&&J==="setup"){$.stage="cli-relay-setup",await vJ({secrets:$.secrets});return}q7(),process.exitCode=1}if(T3.main==T3.module){let $={stage:"cli-command",secrets:[]};try{await cJ($)}catch(Z){console.error(await w0($.stage,Z,process.env,$.secrets)),process.exitCode=1}finally{hJ()}}export{U7 as runSetupCommand,vJ as relaySetup,mJ as login,wJ as addApiRoute};
|