@cortexkit/opencode-anthropic-auth 2.11.1 → 2.11.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +39 -39
- package/dist/{index-m7k9zxem.js → index-0btjtgy5.js} +1 -1
- package/dist/{index-crx0xd9j.js → index-27dah13x.js} +1 -1
- package/dist/index-2debh0ym.js +2 -0
- package/dist/{index-k6303ymz.js → index-427t44z7.js} +1 -1
- package/dist/{index-2ra790fx.js → index-6q2f3m0v.js} +1 -1
- package/dist/{index-jc8zwxvw.js → index-77sph3hf.js} +1 -1
- package/dist/{index-n8xr16kr.js → index-dpxaxyck.js} +1 -1
- package/dist/{index-qqs4ec18.js → index-gqxrgdvk.js} +1 -1
- package/dist/index-sqmwhrzx.js +45 -0
- package/dist/index.js +1 -1
- package/dist/routing-relay.d.ts +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/transform.d.ts +9 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.js +8 -8
- package/dist/v2/tui.js +1 -1
- package/package.json +2 -2
- package/dist/index-gqxkbatp.js +0 -45
- package/dist/index-pcyn2rkg.js +0 -2
package/dist/cli.js
CHANGED
|
@@ -1,58 +1,58 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{B as h3}from"./index-qqs4ec18.js";import{D as p4,E as d4,F as O7,G as A7,H as _7,I as I7,J as l4}from"./index-k6303ymz.js";import{la as k4,ma as yJ,na as r3}from"./index-n8xr16kr.js";var P$=yJ((zF,R4)=>{var L$={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"},gJ={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},vJ={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?L$.up():"");if($)Z+=L$.left;return Z}};R4.exports={cursor:L$,scroll:gJ,erase:vJ,beep:"\x07"}});import{stdin as Rz,stdout as Sz}from"node:process";import{createInterface as Tz}from"node:readline/promises";import{authorize as kz,createNativeAccountRuntime as Ez,decideOpenCodeStateLayoutOnce as bz,exchange as fz,formatNativeAccountState as xz,generateRelayToken as yz,getAccountStoragePath as gz,isValidApiBaseURL as vz,readNativeEnrollmentMode as mz,resolveNativePoolPaths as hz,WORKER_SCRIPT as wz}from"@cortexkit/anthropic-auth-core";import{randomUUID as r5}from"node:crypto";import{constants as A3}from"node:fs";import{lstat as t5,mkdir as e5,open as $Z}from"node:fs/promises";import{homedir as ZZ}from"node:os";import{isAbsolute as JZ,join as c7}from"node:path";import{types as G$}from"node:util";import{anthropicAuthStateRoot as zZ,createProviderErrorRedactor as p7,createWindowsOwnerOnly as XZ,ensureWindowsOwnerOnlyDirectory as GZ,formatLogLine as QZ,HOLDER_REGISTRATION_ERROR_MESSAGES as WZ,isOwnerOnly as YZ,isSecretKey as HZ,isStateLayoutRefusalCode as UZ,NativeMigrationError as KZ,NativePiAuthSlotError as qZ,PRIVATE_FILES_UNAVAILABLE_MESSAGE as d7,RELOCATED_MESSAGE as FZ,STATE_LAYOUT_REFUSAL_CODES as BZ,STATE_LAYOUT_REFUSAL_PUBLIC_MESSAGES as VZ,setupEnrollment as jZ,stateLayoutRefusalPublicMessage as MZ}from"@cortexkit/anthropic-auth-core";import{readFile as w5}from"node:fs/promises";import{assertHostsStopped as u5,createNativeAccountRuntime as c5,discoverNativeVaultInventory as p5,inspectNativeHostAuthEntry as e9,NativePiAuthSlotError as d5,nativePiAuthSlotPaths as l5,openNativePiAuthSlot as Z$,readNativeEnrollmentMode as a5,requireNoSupervisedAuthContentSnapshot as s5}from"@cortexkit/anthropic-auth-core";import{dirname as V5}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as j5,CLAUSTRUM_PI_ENROLLMENT_NAME as M5,getHostClaustrumEnrollmentPaths as D7,resolveClaustrumConnectionPath as D5}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as zY}from"@cortexkit/claustrum-client";import{ClaustrumClient as yW}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as r4}from"@cortexkit/claustrum-client";import{SocketClosedError as t4,SocketTimeoutError as e4,SubcCallError as $8}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",route_busy:"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 u extends O{reason;constructor($){super("unavailable","Claustrum scoped operation unavailable");if(this.name="ClaustrumUnreachableError",$==="host-accessor-missing"||$==="host-accessor-failed")this.reason=$}}function H0($){if($ instanceof u||$ instanceof t4||$ instanceof e4)return"unreachable";let Z=$ instanceof r4||$ instanceof $8?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(a3,Z))return"answered";return a3[Z]}import{resolve as x$}from"node:path";import{storeIdentity as GX}from"@cortexkit/claustrum-client";import{SubcClient as WX}from"@cortexkit/subc-client";var J1=300000,Z3=300000,s3=1000;class f1{#$;#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 J3{#$;#Z;#z;#Y=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#z}request(){if(this.#z)return this.#Y=!0,this.#z;return this.#z=(async()=>{do{this.#Y=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#Y)})().finally(()=>{this.#z=void 0}),this.#z}}class z3{#$;#Z=new f1;#z;#Y="polling";#G;#Q;#X=!1;#J;#H=!1;#W=0;constructor($){this.#$=$,this.#z=new J3(async()=>{let Z=this.#H;if(this.#H=!1,Z||this.#J!==this.#$.view())await this.#$.discover(this.#J??"")},(Z)=>{if(!this.#X)this.#$.onError?.(Z)})}get mode(){return this.#Y}start(){if(this.#X||this.#G||this.#Q)return;if(typeof this.#$.client.watchScoped!=="function"){this.#U("fallback","client-without-watch");return}this.#B(!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()}#U($,Z){if(this.#Y===$)return;this.#Y=$,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#B($){let Z;try{Z=await this.#$.enrollmentToken()}catch(Q){if(this.#X)return;this.#$.onError?.(Q),this.#V("token-unreadable");return}let J=this.#$.client.watchScoped;if(this.#X||this.#G||!J)return;this.#Z.restart(),this.#H=$;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.#U("watching","accepted");if(!this.#Z.continuous(Q))this.#H=!0;this.#J=Q.view,this.#z.request()},{enrollmentToken:Z})}catch(Q){this.#$.onError?.(Q),this.#V("watch-failed");return}z={handle:X,notices:0},this.#G=z,this.#U("polling",$?"resubscribing":"opening");let G=z;X.closed.then((Q)=>this.#q(G,Q),(Q)=>this.#q(G,{kind:"transport_lost",error:Q}))}#q($,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.#U("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#V("refused");try{this.#$.onRefused(Z.error)}catch(J){this.#$.onError?.(J)}return}if($.notices>0){let J=(this.#$.now??Date.now)();if($.acceptedAt!==void 0&&J-$.acceptedAt>=300000)this.#W=0;let z=Math.min(1000*2**Math.min(this.#W,16),300000);this.#W++,this.#U("polling","resubscribing"),this.#K(z,()=>void this.#B(!0));return}this.#V(Z.kind)}#V($){this.#U("fallback",$),this.#K(300000,()=>void this.#B(!1))}}var G3=60000,y$=4*G3,Z8=2*G3,n3=new Map,X3=new Map;function z1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function J8($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!z1(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 z8($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class g${transport;key;#$=[];#Z=!1;#z=new Set;#Y=new Map;#G=new J3(async()=>{try{let $=await this.transport.getUsage();if(!z1($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>z1(Z)&&typeof Z.provider==="string"),this.#Z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#z=new Set(this.#Z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#z)this.#Y.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#z.clear()}},()=>{});#Q=new f1;#X="polling";#J=0;#H=0;#W=new Map;#U;#K;#B={};#q=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 X3)if($-z>=G3)X3.delete(J);let Z=X3.get(this.key);if(Z!==void 0&&$-Z<G3)return Promise.resolve();return X3.set(this.key,$),this.#G.request()}watchMode(){return this.#X}watch($={}){this.#J++;let Z=$.provider;if(Z===void 0)this.#H++;else this.#W.set(Z,(this.#W.get(Z)??0)+1);if(this.#J===1)this.#B=$,this.#C();let J=!1;return()=>{if(J)return;if(J=!0,Z===void 0)this.#H--;else{let z=(this.#W.get(Z)??1)-1;if(z>0)this.#W.set(Z,z);else this.#W.delete(Z)}if(--this.#J===0)this.#V()}}#V(){if(this.#K)(this.#B.clearTimeoutImpl??clearTimeout)(this.#K);this.#K=void 0;let $=this.#U;this.#U=void 0,$?.handle?.stop(),this.#X="polling"}#D($){this.#K=(this.#B.setTimeoutImpl??setTimeout)(()=>{if(this.#K=void 0,this.#J>0&&!this.#U)this.#C()},$),this.#K.unref?.()}#C(){let $=this.transport.watchUsage;if(!$){this.#X="fallback";return}this.#X="polling",this.#Q.restart();let Z={notices:0};this.#U=Z;let J;try{J=$.call(this.transport,(z)=>this.#P(Z,z))}catch(z){this.#O(Z,z);return}Z.handle=J,J.closed.then(()=>this.#O(Z,void 0),(z)=>this.#O(Z,z))}#P($,Z){if(this.#U!==$)return;if($.notices++,$.notices===1)this.#X="watching";if($.notices===2)this.#q=0;let J=J8(Z);if(!J)this.#Q.restart();if(!(J?this.#Q.continuous(J):!1)||J?.provider===void 0||this.#H>0||this.#W.has(J.provider))this.#G.request()}#O($,Z){if(this.#U!==$)return;this.#U=void 0;let J=z8(Z);if(J==="unknown_method"||J==="usage_watch_limit"){this.#X="fallback";return}if($.notices>0){let z=Math.min(s3*2**Math.min(this.#q,16),Z3);this.#q++,this.#X="polling",this.#D(z);return}if(this.#X="fallback",this.#G.request(),Z===void 0||H0(Z)==="unreachable")this.#D(Z3)}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||!z1(z.usage))continue;let X=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(X)||J-X>=y$)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(!z1(z.usage)||!Number.isFinite(Q))return{miss:"unreachable"};let W={entry:z,context:{fetchedAt:Q,...typeof z.source==="string"&&{source:z.source}}};if(z.stale!==void 0&&(!z1(z.stale)||z.stale.class!=="local_source_unavailable"))return{miss:"upstream-failed",reading:W};return J>=Q+y$||z.stale!==void 0?{miss:"stale",reading:W}:{reading:W}}if(this.#z.has($))return{miss:"absent"};let G=this.#Y.get($)??J;return this.#Y.set($,G),{miss:J-G>=Z8?"unreachable":"cold"}}}function i3($,Z){let J=JSON.stringify([x$($.connectionFile),x$(Z)]),z=n3.get(J);if(!z)z={source:new g$($,J),refs:0},n3.set(J,z);z.refs++;let X=!1;return{source:z.source,release(){if(X)return;if(X=!0,--z.refs===0)n3.delete(J)}}}import{ClaustrumCredentialError as wW}from"@cortexkit/claustrum-client";import{appendFileSync as j8,chmodSync as M8,existsSync as e3,renameSync as s$,statSync as D8}from"node:fs";import{open as N8}from"node:fs/promises";import{dirname as L8,resolve as P8}from"node:path";import{randomUUID as w$}from"node:crypto";import{lstat as u$,readFile as c$,rename as X8,unlink as v$}from"node:fs/promises";import{tmpdir as G8}from"node:os";import{dirname as _0,join as Q8,resolve as J0}from"node:path";var _=process.platform==="win32",m$=new Set;function o3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var h$;var p$="native-addon-unavailable";function d$($){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:$}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:p$})}function W8($,Z){return Z instanceof $.PrivateFilesUnavailableError||Z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function Y8($){try{await $.verifyPrivatePath(Q8(G8(),`.common-auth-private-files-probe-${w$()}`),"file")}catch(Z){if(W8($,Z))throw d$(Z)}}function X1(){return h$??=import("@cortexkit/private-files").then(async($)=>{if(_)await Y8($);return $},($)=>{throw _?d$($):$}),h$}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}: ${$} (${p$}). 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=o3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}function Q3($){return _&&$ instanceof w&&$.reason==="io-error"&&($.win32Code===32||$.win32Code===303)}async function t($,Z,J){try{return await J()}catch(z){if(z instanceof w)throw z;throw new w($,Z,z)}}var H8;async function M0($,Z){$=J0($),Z??=H8,await t($,"safe-parent",async()=>{let J=await(await X1()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await u$($);throw new w(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function s($,Z,J=!1){if($=J0($),Z==="directory")return M0($);await t($,"verify",async()=>{let z=await X1(),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 M0(_0($)),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&&!m$.has($))m$.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function U0($,Z=!1,J){$=J0($),await t($,"directory",async()=>{let z=await X1();try{return await u$($),await M0($,J)}catch(G){if(o3(G)!=="ENOENT")throw G}let X=_0($);if(X===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await U0(X,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(o3(G)!=="EEXIST")throw G}await M0($,J)})}async function G0($,Z=!1){if(!_)return c$($,"utf8");return(await U8($,Z)).toString("utf8")}async function U8($,Z=!1){if(!_)return c$($);if($=J0($),Z)await M0(_0($)),await s($,"file",!0);return t($,"read",async()=>(await X1()).readOwnerOnly($))}async function G1($,Z){await M0(_0(J0($))),await t($,"create",async()=>{await(await X1()).createPrivateFile(J0($),Z)})}async function l$($){await M0(_0(J0($))),await t($,"directory-create",async()=>{await(await X1()).createOwnerOnly(J0($),{kind:"dir"})})}async function t3($,Z,J={}){$=J0($),Z=J0(Z);let z=J.now??(()=>performance.now()),X=z(),G=J.deadline??1/0,Q,W=[0,10,20,40,80,100],Y,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((A)=>setTimeout(A,L))))(Math.min(K,Math.max(0,M-z())));if(z()>=M)break;let F=z();if(await J.beforeRename?.(),Q!==void 0)Q+=z()-F;if(z()>=G)break;U++;try{return await(J.rename??X8)($,Z),{attempts:U,elapsedMs:z()-X}}catch(L){Y??=L;let A=L;if(!(A.win32Code!==void 0?A.win32Code===32||A.win32Code===33:["EBUSY","EPERM","EACCES"].includes(A.code??"")&&!A.reason))break;Q??=z()+500}}let H=new w(Z,"rename",Y??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw H.attempts=U,H.elapsedMs=z()-X,H}async function Q1($,Z,J={}){$=J0($),await U0(_0($));try{await s($,"file",!0)}catch(U){if(U.code!=="ENOENT")throw U}let z=J0(J.stagePath??`${$}.${w$()}.tmp`);if(_0(z)!==_0($))throw new w($,"stage-directory",{code:"EXDEV"});let X=!1,G=!1,Q={attempts:0,elapsedMs:0},W="stage-create",Y=(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 G1(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 s($,"file"),J.durable&&J.durability!=="file-only-on-windows")throw new w($,"directory-sync-unsupported",{code:"ENOTSUP"});Y()}catch(U){let H=U instanceof w?U:new w($,W,U);if(H.published=G,H.fileDurable=G,G)Object.assign(H,Q);if(X){try{await v$(z)}catch{H.orphanPath=z}X=!1}throw Y(H),H}finally{if(X)await v$(z).catch(()=>{})}}var K8=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,q8=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function F8($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function W1($={}){let Z=[q8,...$.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 K8.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 Y=new Set(W.map(([U])=>U));for(let U of Object.entries(G))if(!Y.has(U[0]))W.push(U);return W}function X(G,Q,W,Y=0){if(typeof G==="string")return Z.reduce((U,H)=>U.replace(H,"***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,Y));let U=F8(G);if(U&&Y>=8)return"[Truncated]";let H=U?Y+1:Y;return Object.fromEntries((U?z(G):Object.entries(G)).map(([K,M])=>[K,Q&&J(K)?"***REDACTED***":X(M,Q,W,H)]))}finally{W.delete(G)}}return{redact:(G)=>X(G,!0,new WeakSet),redactStrings:(G)=>X(G,!1,new WeakSet)}}var a$=W1(),B8=a$.redact,V8=a$.redactStrings;var W3={error:0,warn:1,info:2,debug:3,trace:4},i$=5242880,o$=3;function $9($){try{M8($,384)}catch{}}function C8($){try{if(!(e3($)&&D8($).size>=i$))return;for(let J=o$-1;J>=1;J--)if(e3(`${$}.${J}`)){let z=`${$}.${J+1}`;s$(`${$}.${J}`,z),$9(z)}let Z=`${$}.1`;s$($,Z),$9(Z)}catch{}}async function D0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await t(Z,"log-close",()=>J.close())}async function n$($,Z){await U0(L8(Z));try{await s(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await G1(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await s(Z,"file",!0)}}return $.handle=await t(Z,"log-open",()=>N8(Z,"a")),$.file=Z,$.handle}async function O8($,Z,J){Z=P8(Z);try{if($.file!==Z)await D0($);let z=$.handle??await n$($,Z);if((await t(Z,"log-stat",()=>z.stat())).size>=i$){await D0($);for(let G=o$-1;G>=0;G--){let Q=G===0?Z:`${Z}.${G}`,W=`${Z}.${G+1}`;try{await s(Q,"file",!0)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}try{await s(W,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}await t3(Q,W),await s(W,"file")}z=await n$($,Z)}await t(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await D0($).catch(()=>{}),z}}function A8($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function _8($){let Z,J,z,X=W1(),G,Q=[],W,Y=Promise.resolve(),U,H={};function K(V){let q=Y.then(V);return Y=q.catch((D)=>{U=D}),q}function M(V){if(_&&V.file!==Z)K(()=>D0(H)).catch(()=>{});Z=V.file,J=V.level,X=W1(V),G=V.captureSink}function F(V){if(V===void 0||V in W3)z=V}function L(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function A(){if(z)return z;let V=typeof J==="function"?J():J;if(V&&V in W3)return V;return"info"}function P(V=!0){if(W)clearTimeout(W),W=void 0;if(!Q.length){if(_)return K(async()=>{if(V)await D0(H);if(U)throw U});return}let q;try{q=L()}catch{if(Q=[],_&&V)return K(()=>D0(H));return}let D=Q.join("");if(Q=[],!q){if(_&&V)return K(()=>D0(H));return}if(_)return K(async()=>{try{await O8(H,q,D)}finally{if(V)await D0(H)}});try{if(C8(q),e3(q))$9(q);j8(q,D,{encoding:"utf8",mode:384})}catch{}}function I(){if(!W)W=setTimeout(()=>{W=void 0;let V=P(!1);if(V instanceof Promise)V.catch(()=>{})},500)}function T(V,q,D,C){if(Z===void 0&&G===void 0)return;try{if(W3[q]>W3[A()])return;let v=X.redactStrings(D),E;try{E=X.redact(C)}catch{E="[unserializable]"}let x=`[${new Date().toISOString()}] ${q.toUpperCase()} [${V}] ${v}`+(C===void 0?"":A8(E))+`
|
|
3
|
-
`;try{G?.({channel:
|
|
4
|
-
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??r$)()}.tmp`,onRenamed:z,durable:J.durable,durability:J.durability,onOutcome:J.onOutcome});await
|
|
5
|
-
`,"utf8"),await G.chmod(384),J.durable)try{await G.sync()}catch(W){throw new Y3(W)}if(await G.close(),G=void 0,await J.beforeRename?.(),await
|
|
6
|
-
`,{deadline:performance.now()+Math.max(0,S),beforeRename:async()=>{let l=await q();if(l?.ownerId!==z||!(Number(l?.expiresAt)>X())||!await
|
|
7
|
-
`,"utf8"),await j.chmod(384),await j.close(),j=void 0;let R=await q();if(R?.ownerId!==z||!(Number(R?.expiresAt)>X())||!await
|
|
8
|
-
`;if(_)await G1(Z,
|
|
9
|
-
`;if(_)await G1(I,R);else await H2(I,R)}catch(N){let R=await l3(j,B);if(q2(N)&&!R)return!1;try{await x0(B)}catch{}throw N}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function b(B){let j;try{j=await y1(P)}catch(S){if(S.code==="ENOENT")return"missing";throw S}if(_)try{await K0(P,()=>s(P,"directory",!0))}catch(S){if(S.code==="ENOENT")return"missing";throw S}if(j.mtimeMs+m>X()){let S=!0;try{await y1(I)}catch(l){if(l.code==="ENOENT")S=!1;else return"fresh"}if(S)return"fresh";if(j.mtimeMs+e8>X())return"fresh"}if($.onStep)await $.onStep("stale-marker-stat");let N=`${P}.${g1()}`;try{await X2(P,N)}catch(S){if(S.code==="ENOENT")return"missing";throw S}if($.onStep)await $.onStep("stale-marker-claimed");let R=_?await R0(N):void 0;return await E1(N,async()=>{if(!R)return!0;let S=await R0(N).catch((l)=>{if(l.code!=="ENOENT")throw l;return});return!!S&&J9(R,S)},B),"recovered"}async function j0(B,j){try{if(!await Z1(j))return!1}catch(S){if(S.code==="EEXIST"){if(_)try{await K0(P,()=>s(P,"directory",!0)),await K0(I,()=>G0(I,!0))}catch(l){if(l.code!=="ENOENT")throw l}return!1}throw S}let N=!1,R;try{await B()}catch(S){N=!0,R=S}try{await x0(j)}catch(S){if((Z0(R,Z)||v0(R,[Z,J,I]))&&(Z0(S,P)||v0(S,[I])))throw R;throw S}if(N)throw R;return!0}async function T$(){for(let B=0;B<c;B++){if($.onStep)await $.onStep("relinquish-read");let j;try{j=await q()}catch(N){if(_&&!(N instanceof x1))throw N;return}if(j?.ownerId!==z)return;try{await K1(Z,{recursive:!0,force:!0});return}catch(N){if(_)throw N;await x()}}}function k$(){if(!$.renew||Q||Y)return;let B=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=r8(()=>{G=null;let j=(async()=>{let N=!Q;try{if(!await j0(async()=>{let S=await q(),l=X();if(Q||Y){N=!1;return}if(S?.ownerId!==z){F("taken-over",S),N=!1;return}if(!(Number(S?.expiresAt)>l)){F("expired",S),N=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(Q||Y){N=!1;return}if(!await h())return;if($.onStep)await $.onStep("renewal-write-fenced");if(Q||Y){N=!1;return}if(!await h())return;if($.onStep)await $.onStep("renewal-write-ready");if(Q||Y){N=!1;return}if(await D(),$.onStep)await $.onStep("renewal-write-finished");if(!await h()){F("marker-lost"),N=!1,await T$();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(R){if(_&&R instanceof w&&!V(R))L=R,F("renewal-failed"),N=!1;try{let S=await q();if(S?.ownerId!==z)F("taken-over",S);else if(!(Number(S?.expiresAt)>X()))F("expired",S)}catch{F("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(N&&!Q&&!Y)k$()}})();A=j,j.finally(()=>{if(A===j)A=null})},B),"unref"in G)G.unref();K("scheduled")}function E$(){try{let B=$.onContended?.();if(B&&(typeof B==="object"||typeof B==="function")&&"then"in B&&typeof B.then==="function")Promise.resolve(B).catch(()=>{})}catch{}return null}let A0=!1,$3;try{A0=await E()}catch(B){if(!V(B))throw B;$3=B}if(!A0)for(let B=0;B<c;B++)try{if(A0=await E(),A0)break;let j=await $0();if(j.status==="live")return E$();if(j.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await Z1()){await x();continue}}catch(N){if(N.code!=="EEXIST")throw N;if(await b()==="fresh")return null;await x();continue}try{let N=await $0();if(N.status==="live")return E$();if(!$1(j.identity,N))continue;if(!await h())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await h())return null;let R=await $0(!1);if(!$1(j.identity,R))continue;if(await i(Z),!await h())return null;if($.onStep)await $.onStep("stale-lock-removed");if(A0=await E(),!A0)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await h())return await T$(),A0=!1,null;break}finally{await x0()}}catch(j){if(!V(j))throw j;$3??=j,await x()}if(!A0){if($3)throw $3;return null}return k$(),o8(Z,$.ttlMs,X),{ownerId:z,whenLost:()=>H,hasLost:()=>Y!==void 0,assertOwned:async()=>{if(L)throw L;let B;try{let j=await q();if(B=j,!Q&&!Y&&j?.ownerId===z&&Number(j?.expiresAt)>X())return;F(j?.ownerId!==z?"taken-over":"expired",j)}catch(j){if(F("unreadable"),_&&j instanceof w)throw j}throw new N0({target:$.path,name:$.name,expectedOwnerId:z,...typeof B?.ownerId==="string"?{observedOwnerId:B.ownerId}:{},...typeof B?.expiresAt==="number"?{observedExpiresAt:B.expiresAt}:{}})},release:async(B)=>{if(_&&W)return;Q=!0,M(),await A;let j=performance.now()+m+1000,N=5,R,S;for(;;){try{let d=!1,b1=await j0(async()=>{let b$;try{b$=await q()}catch(f$){if(_&&f$.code==="ENOENT"){d=!0;return}throw f$}if(b$?.ownerId!==z){d=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await h())return;await i(Z),d=!0},j);if(S=void 0,b1&&d){W=!0;return}if(!b1){if(B?.aborted)return;await b(j)}}catch(d){let b1=_&&(V(d)||v0(d,[Z,J,P,I]));if(!Z0(d,Z)&&!b1){if(_)throw d;return}if(b1)S??=d;else R??=d}let l=j-performance.now();if(l<=0)break;if(await new Promise((d)=>setTimeout(d,Math.min(N,l))),_&&performance.now()>=j)break;N=Math.min(N*2,50)}if(_)throw S??R??new w(Z,"release-not-confirmed",{code:"ETIMEDOUT"});z0("fs").warn("File lock release deadline expired",{lockPath:Z})}}}import{ClaustrumCredentialError as Z6}from"@cortexkit/claustrum-client";var F2=new WeakSet;function X9($){return F2.has($)}function p(){return process.env.CORTEXKIT_VAULT_HOST==="thalamus"}function G9($){if(typeof $!=="object"||$===null)return $;let Z=$;if(typeof Z.code==="string"&&(Z.class==="transient"||Z.class==="permanent"||Z.class==="auth_required"||Z.class==="context_overflow")&&(Z.action==="gone"||Z.action==="reauth"||Z.action==="retry"||Z.action==="reduce_and_retry"))return new Z6(Z.code,Z.class,Z.action);if(Z.name==="ClaustrumUnreachableError"||typeof Z.code==="string"&&H0(Object.assign(Error(),{code:Z.code}))==="unreachable")return new u(Z.reason==="host-accessor-missing"||Z.reason==="host-accessor-failed"?Z.reason:void 0);return $}function v1($){try{return $()}catch(Z){throw G9(Z)}}async function m0($){try{return await $()}catch(Z){throw G9(Z)}}function J6($){let Z=$.watchScoped?.bind($),J=$.reportUsageScoped?.bind($);return{listScoped:(...z)=>m0(()=>$.listScoped(...z)),getScoped:(...z)=>m0(()=>$.getScoped(...z)),reportAuthFailureScoped:(...z)=>m0(()=>$.reportAuthFailureScoped(...z)),close:()=>v1(()=>$.close()),...Z&&{watchScoped:(...z)=>{let X=v1(()=>Z(...z));return{stop:()=>v1(()=>X.stop()),closed:m0(async()=>{let G=await X.closed;return G.kind==="refused"||G.kind==="transport_lost"?{...G,error:G9(G.error)}:G})}}},...J&&{reportUsageScoped:(...z)=>m0(()=>J(...z))},...$.insula&&{insula:z6($.insula)}}}function z6($){let Z=$.watchUsage?.bind($);return{connectionFile:$.connectionFile,getUsage:()=>m0(()=>$.getUsage()),...Z&&{watchUsage:(...J)=>{let z=v1(()=>Z(...J));return{stop:()=>v1(()=>z.stop()),closed:m0(()=>z.closed)}}}}}function h0($){if(!p()||!$)throw new u;try{let Z=globalThis[Symbol.for("cortexkit.vault")];if(typeof Z==="function"){let J=J6(Z($));return F2.add(J),J}}catch{throw new u("host-accessor-failed")}throw new u("host-accessor-missing")}var B6=1,q3=16384,C2=30000,H9=/^[0-9a-f]{64}$/,O2="unknown_method",A2=new Set([O2,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),_2=new Set(["pending_queue_full"]);function W9($){if(!($ instanceof P2))return;if(A2.has($.code))return{code:$.code,disposition:"terminal"};if(_2.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function I2($){let Z=Array.from($).length;return Z>=1&&Z<=40&&!/[\p{Cc}\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069\u200b-\u200d\u2060\ufeff]/u.test($)}function U9($){return Array.isArray($)&&$.length>=1&&$.length<=4&&Array.from($).every((Z)=>{if(!F3(Z)||Object.keys(Z).length!==2||Z.operation!=="read"&&Z.operation!=="list"||!F3(Z.selector))return!1;let J=Object.keys(Z.selector),z=J[0];return J.length===1&&(z==="category"||z==="exact")&&typeof Z.selector[z]==="string"&&Z.selector[z].trim().length>0})}function P0($){return{...$.requestedGrants!==void 0&&{requestedGrants:$.requestedGrants},...$.requestedGrantsStatus!==void 0&&{requestedGrantsStatus:$.requestedGrantsStatus}}}function F3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function K3($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function R2($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function m1(){return new O("invalid-state","invalid Claustrum enrollment state")}function K9($){if(!F3($)||$.version!==B6||typeof $.proposedName!=="string"||$.proposedName.length===0)throw m1();if($.phase==="pending"){let Z=V2($);if(!H9.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!K3($.createdAt)||!K3($.updatedAt))throw m1();return{version:1,phase:"pending",proposedName:$.proposedName,requestSecret:$.requestSecret,...$.requestId!==void 0&&{requestId:$.requestId},createdAt:$.createdAt,updatedAt:$.updatedAt,...Z}}if($.phase==="approved"){let Z=V2($);if($.approvedName!==void 0&&(typeof $.approvedName!=="string"||$.approvedName.length===0)||!R2($.tokenGeneration)||!K3($.updatedAt))throw m1();return{version:1,phase:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration,updatedAt:$.updatedAt,...Z}}if($.phase==="denied"||$.phase==="blocked"){if($.errorCode!==void 0&&typeof $.errorCode!=="string"||!K3($.updatedAt))throw m1();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw m1()}function V2($){if($.requestedGrants!==void 0&&!U9($.requestedGrants)||$.requestedGrantsStatus!==void 0&&($.requestedGrants===void 0||$.requestedGrantsStatus!=="sent"&&$.requestedGrantsStatus!=="dropped"))return{};return P0($)}function q9($){if(!F3($)||!H9.test(String($.token??""))||!R2($.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 j2($){try{return JSON.parse($)}catch{throw new O("invalid-state","Claustrum enrollment file is not valid JSON")}}async function c0($){if(_)try{await U0(u0($));let J=await G0($,!0);if(Buffer.byteLength(J)>q3)throw new O("unsafe-file","Claustrum enrollment file is too large");return j2(J)}catch(J){if(J.code==="ENOENT")return;throw J}let Z;try{Z=await N2($,B2.O_RDONLY|B2.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(q3+1),{bytesRead:z}=await Z.read(J,0,J.byteLength,0);if(z>q3)throw new O("unsafe-file","Claustrum enrollment file is too large");return j2(J.subarray(0,z).toString("utf8"))}finally{await Z.close()}}function M2($,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
|
|
11
|
-
`;if(Buffer.byteLength(X)>q3)throw new O("invalid-state","Claustrum enrollment state is too large");if(_)return Q1($,X);let G=q6(z,`.${K6($)}.${process.pid}.${Q6()}.tmp`),Q,W=!1;try{Q=await N2(G,"wx",384),W=!0,await Q.writeFile(X,"utf8"),await Q.chmod(384),await Q.sync(),await Q.close(),Q=void 0,await U6(G,$),W=!1}finally{if(await Q?.close().catch(()=>{}),W)await Y9(G).catch(()=>{})}}var j6=new g0;async function B3($,Z){let J=_?await D2($,Z):await j6.read([$.tokenPath,$.statePath],async([X=$.tokenPath,G=$.statePath])=>D2({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 D2($,Z){let J=await c0($.tokenPath),z=J===void 0?void 0:q9(J),X=await c0($.statePath),G=X===void 0?void 0:K9(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,...G&&(G.phase==="approved"||G.phase==="pending")&&P0(G)}};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:S0(G),usesProposedName:!1}}async function T0($){let Z=await c0($);if(Z===void 0)throw new O("not-enrolled","Claustrum enrollment is not configured");return q9(Z)}function S0($){if($.phase==="pending")return{state:"pending",proposedName:$.proposedName,...$.requestId!==void 0&&{requestId:$.requestId},...P0($)};if($.phase==="approved")return{state:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration,...P0($)};if($.phase==="denied")return{state:"denied",proposedName:$.proposedName};return{state:"blocked",proposedName:$.proposedName,code:$.errorCode??"unknown"}}function E2(){return new O("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class F9{#$;#Z;#z;#Y;#G;#Q;#X;#J;#H;constructor($){if($.displayName!==void 0&&!I2($.displayName))throw new O("invalid-state","invalid Claustrum enrollment display name");if($.requestedGrants!==void 0&&!U9($.requestedGrants))throw new O("invalid-state","invalid Claustrum enrollment requested grants");this.#G=$.requestedGrants?.map((Z)=>({selector:{...Z.selector},operation:Z.operation})),this.#H=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#z=$.proposedName,this.#Y=$.displayName,this.#Q=$.now??Date.now,this.#X=$.mintSecret??(()=>G6(32).toString("hex")),this.#J=$.writeTokenFile??F6}async status(){return B3(this.#Z,this.#z)}async resetTerminal(){return b2(this.#Z,this.#z)}async#W($,Z){let J={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#Q()};return await w0(this.#Z.statePath,J,this.#H),S0(J)}async reconcile(){await F1(u0(this.#Z.statePath),this.#H);let $=await L0({name:"ceremony",path:this.#Z.statePath,ttlMs:C2,renew:!0});if(!$)return{state:"busy"};try{let Z=await c0(this.#Z.tokenPath),J=Z===void 0?void 0:q9(Z),z=await c0(this.#Z.statePath),X=z===void 0?void 0:K9(z);if(X&&X.proposedName!==this.#z)throw E2();if(J){if(!X||X.phase==="pending"){let Q={version:1,phase:"approved",proposedName:X?.proposedName??this.#z,tokenGeneration:J.token_generation,...X&&P0(X),updatedAt:this.#Q()};await w0(this.#Z.statePath,Q,this.#H),X=Q}return{state:"approved",proposedName:X.proposedName,...X.phase==="approved"&&X.approvedName!==void 0&&{approvedName:X.approvedName},tokenGeneration:J.token_generation,...X.phase==="approved"&&P0(X)}}if(X?.phase==="approved"){let Q={version:1,phase:"blocked",proposedName:X.proposedName,errorCode:"missing_token",updatedAt:this.#Q()};return await w0(this.#Z.statePath,Q,this.#H),S0(Q)}if(X&&X.phase!=="pending")return S0(X);if(!X){let Q=this.#Q();if(X={version:1,phase:"pending",proposedName:this.#z,requestSecret:this.#X(),createdAt:Q,updatedAt:Q,...this.#G!==void 0&&{requestedGrants:this.#G}},!H9.test(X.requestSecret))throw new O("invalid-state","invalid minted Claustrum enrollment secret");await w0(this.#Z.statePath,X,this.#H)}if(!X.requestId)try{let Q=X6("sha256").update(Buffer.from(X.requestSecret,"hex")).digest("hex"),W={name:X.proposedName,requestSecretHash:Q},Y,U=X.requestedGrantsStatus;try{if(Y=await this.#$.enrollPropose({...W,...this.#Y!==void 0&&{displayName:this.#Y},...X.requestedGrants!==void 0&&{requestedGrants:X.requestedGrants}}),X.requestedGrants!==void 0)U="sent"}catch(H){if(this.#Y===void 0&&X.requestedGrants===void 0||!(H instanceof P2)||H.code!=="invalid_params")throw H;if(Y=await this.#$.enrollPropose(W),X.requestedGrants!==void 0)U="dropped"}X={...X,requestId:Y.requestId,updatedAt:this.#Q(),...U!==void 0&&{requestedGrantsStatus:U}},await w0(this.#Z.statePath,X,this.#H)}catch(Q){let W=W9(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,retryCode:W.code,...P0(X)};if(W.code===O2)return await $.assertOwned(),await Y9(this.#Z.statePath).catch((Y)=>{if(Y.code!=="ENOENT")throw Y}),{state:"unavailable",proposedName:X.proposedName,code:W.code};return this.#W(X,W.code)}let G=X.requestId;if(!G)return S0(X);try{let Q=await this.#$.enrollPoll({requestId:G,requestSecret:X.requestSecret});if(Q.status==="pending")return S0(X);if(Q.status==="denied"){let Y={version:1,phase:"denied",proposedName:X.proposedName,updatedAt:this.#Q()};return await w0(this.#Z.statePath,Y,this.#H),S0(Y)}await F1(u0(this.#Z.tokenPath),this.#H),await k2(u0(this.#Z.tokenPath),this.#H),await this.#J(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,...P0(X),updatedAt:this.#Q()};return await w0(this.#Z.statePath,W,this.#H),S0(W)}catch(Q){let W=W9(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,requestId:G,retryCode:W.code,...P0(X)};return this.#W(X,W.code)}}finally{await $.release()}}}async function b2($,Z){await F1(u0($.statePath));let J=await L0({name:"ceremony",path:$.statePath,ttlMs:C2,renew:!0});if(!J)return"busy";try{if(await c0($.tokenPath)!==void 0)return"refused-approved";let z=await c0($.statePath);if(z===void 0)return"idle";let X=K9(z);if(X.proposedName!==Z)throw E2();if(X.phase==="pending")return"refused-pending";return await J.assertOwned(),await Y9($.statePath),"reset"}finally{await J.release()}}var B9="claustrum-tombstone:v1:";function B1($,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 V1($,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)}}import{ClaustrumCredentialError as M6}from"@cortexkit/claustrum-client";function f2($){return $!==null&&typeof $==="object"&&(Object.getPrototypeOf($)===Object.prototype||Object.getPrototypeOf($)===null)}class V9{options;#$=new Map;#Z=new Map;#z=new Set;#Y;#G;#Q=!1;#X=!1;#J=0;constructor($){this.options=$}state(){return{pending:this.#$.size,inFlight:this.#G!==void 0,dropped:this.#J}}report($,Z){if(this.#Q||!this.options.client.reportUsageScoped)return;try{if(!this.options.owns($)){this.#J++;return}if(!f2(Z)||"credentialId"in Z||"vouched"in Z)throw Error("invalid reading");let J=JSON.stringify(Z);if(Buffer.byteLength(J,"utf8")>15360)throw Error("oversized reading");let z=JSON.parse(J);if(!f2(z)||"credentialId"in z||"vouched"in z||typeof z.observedAtMs!=="number"||!Number.isFinite(z.observedAtMs))throw Error("invalid reading");if(z.observedAtMs<=(this.#Z.get($)??-1/0)){this.#J++;return}if(this.#$.has($))this.#J++;if(this.#Z.set($,z.observedAtMs),this.#$.set($,z),!this.#Y&&!this.#G)this.#Y=this.options.setTimeout(()=>{this.#Y=void 0,this.#H()},1000),this.#Y.unref?.()}catch{this.#J++}}forget($){if(this.#$.delete($))this.#J++;this.#Z.delete($)}#H(){if(this.#G||!this.#$.size||this.#X)return this.#G;let $=Promise.resolve().then(async()=>{while(!this.#X&&this.#$.size){let Z=this.#$.entries().next().value;if(!Z)break;let[J,z]=Z;this.#$.delete(J);try{let X=await this.options.token();if(this.#X||!this.options.owns(J)){if(!this.#X)this.#J++;continue}await this.options.client.reportUsageScoped?.({credentialId:J,reading:z,enrollmentToken:X})}catch(X){if(!this.#X)this.#J++;this.#W(X)}}});return this.#G=$,$.finally(()=>{this.#G=void 0}),$}#W($){let Z="transport_error";try{if($ instanceof M6)Z=/^[a-z][a-z0-9_]{0,63}$/.test($.code)?$.code:Z;if(this.#z.has(Z))return;this.#z.add(Z),this.options.logger.debug("claustrum usage report dropped",{code:Z})}catch{}}close(){if(this.#Q=!0,this.#Y)this.options.clearTimeout(this.#Y);return this.#Y=void 0,this.#H()}drop(){this.#X=!0,this.#J+=this.#$.size+(this.#G?1:0),this.#G=void 0,this.#$.clear(),this.#Z.clear()}}function g2($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function N6($,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 M9=z0("claustrum");function y2($){if(!/^[0-9a-f]{64}$/.test($.token)||!Number.isSafeInteger($.token_generation)||$.token_generation<1)throw new O("invalid-token","Invalid Claustrum enrollment token");return $.token}var k0=D6("common-auth.claustrum.phases");function N9($,Z,J,z=M9){let X=g2(Z,J);return z.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:J?.recordVersion??null,retry:X,reason:N6(Z,J)}),X}var D9=300000,v2=60000;function j9(){return new O("invalid-material","Claustrum returned invalid credential material")}function L6($){let Z=$.trim();if(Z.startsWith("{")){let J;try{J=JSON.parse(Z)}catch{throw j9()}if(!J||typeof J!=="object")throw j9();let z=J,X=z.access_token??z.access;Z=typeof X==="string"?X:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(B9))throw j9();return Z}function P6($,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=C6($),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 C6($){let Z=$;return{providerIds:Z.providerIds,authMethod:Z.authMethod}}function O6($){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 j1{#$;#Z;#z;#Y;#G;#Q;#X;#J=new WeakMap;#H=new WeakMap;#W=new Map;#U=new WeakMap;#K;#B=new Map;#q;#V;#D=!1;#C=new u;#P;#O=!1;#F=-1/0;#M=2000;#I=!1;#j;#N=new Set;#A=new Set;#R;#E;#L;constructor($){if(p()&&$.client&&!X9($.client))throw new u;let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>T0(Z);else if(p())this.#Z=async()=>{throw new O("not-enrolled","Claustrum enrollment token path is required")};else throw new O("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client??h0($.pluginId),this.#Y=$.family,this.#G=$.parseIdentity,this.#Q=$.requireAssertion??!1,this.#z=$.now??Date.now,this.#X=$.logger??M9,this.#R=B1(this.#X),this.#q=$.setTimeoutImpl??setTimeout,this.#V=$.clearTimeoutImpl??clearTimeout;let J=()=>this.#$;this.#K=new V9({client:{get reportUsageScoped(){let z=J();return z.reportUsageScoped?.bind(z)}},owns:(z)=>this.#B.has(z),token:async()=>p()?"":y2(await this.#Z()),logger:this.#X,setTimeout:this.#q,clearTimeout:this.#V})}replaceClient($){if(this.#_(),$===this.#$)return;if(p()&&!X9($))throw new u;this.#$=$;for(let Z of this.#N)Z.restart()}transportLost($){if(this.#I||this.#D)return;this.#D=!0,this.#C=$ instanceof x2?$:new u($ instanceof u?$.reason:void 0),this.#X.warn("serving kept vault receipt",{reason:"unreachable"}),this.#S()}reachable(){if(this.#I||!this.#D)return;if(this.#D=!1,this.#P)this.#V(this.#P);this.#P=void 0,this.#M=2000;for(let $ of this.#W.values())$.since=null;(this.#X.info??M9.info)("vault receipt serving resumed",{reason:"reachable"})}#S(){if(this.#I||!this.#D||this.#P||this.#O)return;this.#P=this.#q(()=>{this.#P=void 0,this.#k(!0)},this.#M),this.#P.unref?.()}#k($=!1){if(this.#I||!this.#D||this.#O)return;if(this.#z()-this.#F<1000){this.#S();return}this.#F=this.#z(),this.#O=!0,this.#f().catch(()=>{if($&&this.#D)this.#M=Math.min(this.#M*2,30000)}).finally(()=>{this.#O=!1,this.#S()})}#_($){if(this.#I)throw new O("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#y($){if(this.#_($),p())return"";if(k0.hasSubscribers)k0.publish({logger:this.#X,phase:"token read begin"});let Z=this.#Z();this.#A.add(Z);let J;try{J=await Z}finally{if(this.#A.delete(Z),k0.hasSubscribers)k0.publish({logger:this.#X,phase:"token read end"})}return this.#_($),y2(J)}async#b($,Z){this.#_(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.#_(Z),H0(X)==="unreachable")this.transportLost(X);else this.reachable();if(X instanceof x2)throw X;if(H0(X)==="unreachable")throw new u(X instanceof u?X.reason:void 0);throw new O("unavailable","Claustrum scoped operation unavailable")}finally{z?.()}return this.#_(Z),this.reachable(),J}async discover($){let Z=await this.#f($);return this.#j=Z.view,Z}async#f($){let Z,J;try{J=await this.#y($)}catch(H){throw this.#W.clear(),this.#g(),H}if(k0.hasSubscribers)k0.publish({logger:this.#X,phase:"list scoped begin"});try{Z=await this.#b(()=>this.#$.listScoped(J),$)}catch(H){throw this.listFailed(H),H}finally{if(k0.hasSubscribers)k0.publish({logger:this.#X,phase:"list scoped end"})}let z=[],X=[],G=0,Q=[],W=new Map;for(let H of Z.rows){let K=P6(H,this.#Y);if(K.kind==="not-mine"){G++;continue}if(K.kind==="refused"){X.push({...H.id.trim()&&{credentialId:H.id},code:K.code});continue}Q.push({row:H,type:K.type,...K.member!==void 0&&{member:K.member}}),W.set(H.id,(W.get(H.id)??0)+1)}let Y=[];for(let{row:H,type:K,member:M}of Q){let F;if(!H.id.trim())F="empty credential id";else if((W.get(H.id)??0)>1)F="duplicate credential id";else if(H.accountId!==void 0&&!H.accountId.trim())F="blank account identity";else if(!H.state.trim())F="empty state";if(F){z.push({...H.id.trim()&&{credentialId:H.id},...M!==void 0&&{member:M},reason:F});continue}Y.push(Object.freeze({credentialId:H.id,credentialType:K,...M!==void 0&&{member:M},...H.accountId!==void 0&&{accountIdentity:H.accountId},state:H.state,...H.email!==void 0&&{email:H.email},...H.orgName!==void 0&&{orgName:H.orgName}}))}for(let H of z)this.#X.warn("skipped malformed vault record",H);let U=O6(Z);return{view:Z.view,credentials:Object.freeze(Y),skipped:Object.freeze(z),..."classify"in this.#Y&&{refused:Object.freeze(X),notMine:G},...U&&{grantReach:U}}}listFailed($){if(H0($)==="unreachable")this.transportLost($);else this.reachable(),this.#W.clear(),this.#g()}forget($){this.#W.delete($),this.#B.delete($),this.#K.forget($)}#g(){for(let $ of this.#B.keys())this.#K.forget($);this.#B.clear()}retain($){let Z=new Map($.map((J)=>[J.credentialId,J]));for(let[J,z]of this.#W){let X=Z.get(J);if(!X?.enabled||X.state!=="active"||X.credentialType!==z.attempt.credentialType||X.accountIdentity!==z.attempt.expectedAccountIdentity)this.forget(J)}for(let[J,z]of this.#B){let X=Z.get(J);if(!X?.enabled||X.state!=="active"||X.credentialType!==z.credentialType||X.accountIdentity!==z.accountIdentity)this.forget(J)}}keptReceiptState(){let $=null;for(let[Z,J]of this.#W){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.#z()>v2}async authorize($,Z,J="vault"){this.#_(Z);let{credentialId:z,credentialType:X,accountIdentity:G}=$,Q=this.#W.get(z);if(Q&&(Q.attempt.credentialType!==X||Q.attempt.expectedAccountIdentity!==G))this.forget(z),Q=void 0;let W;try{W=await this.#y(Z)}catch(Y){throw this.#W.clear(),this.#g(),Y}if(this.#D&&Q)return this.#k(),this.#v(z,Q,W,J);try{let Y=await this.#T({credentialId:z,credentialType:X,accountIdentity:G},W,Z);return this.#W.set(z,{attempt:Y,routeId:J,since:null}),this.#B.set(z,{...$}),Y}catch(Y){if(this.#_(Z),H0(Y)!=="unreachable")throw this.forget(z),Y;return this.#v(z,Q,W,J,Y)}}#v($,Z,J,z,X=this.#C){if(!Z||this.#W.get($)!==Z||!this.#x(Z.attempt))throw this.forget($),X;if(Z.since===null)Z.since=this.#z();let G=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#J.set(G,this.#J.get(Z.attempt)??{token:J}),this.#U.set(G,z),G}async#T($,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.#b(()=>this.#$.getScoped({credentialId:z,enrollmentToken:Z,...X==="oauth"&&{minTtlMs:D9}}),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.#z()<D9))throw new O("insufficient-validity","Claustrum served credential has insufficient validity");let Y=L6(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 H=U===void 0?this.#G?.(Y):void 0,K=U??H;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":H!==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:Y,enumerable:!1}));return this.#J.set(L,{token:Z}),L}async reportFailure($,Z,J){if(Z!==401)return;this.#_();let z=this.#J.get($);if(!z)throw new O("no-receipt","Claustrum failure report requires an original dispatch receipt");let X=this.#U.get($);if(X!==void 0){this.forget($.credentialId),this.#X.debug("scoped 401 not reported",{routeId:X,reason:"kept-receipt"});return}let G=this.#W.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let Q=this.#H.get($);if(Q)return Q;let W=this.#b(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:z.token,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#H.set($,W);try{await W,this.#X.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:J})}catch(Y){throw this.#H.delete($),Y}}watchRoster($){this.#_();let Z=$.view??(()=>this.#j),J,z,X=(Q=!1)=>{let W=new z3({client:this.#$,enrollmentToken:()=>this.#y(),view:()=>Q?void 0:Z(),discover:async(Y)=>{while(J)await J.catch(()=>{});if(z!==W)return;Q=!1,J=Promise.resolve().then(()=>$.onView(Y));try{await J}finally{J=void 0}},onRefused:(Y)=>{this.listFailed(Y),$.onRefused?.(Y)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#X,now:this.#z,setTimeoutImpl:this.#q,clearTimeoutImpl:this.#V});return W};z=X();let G={restart:()=>{let Q=z.mode;if(z.stop(),z=X(!0),Q!==z.mode)$.onMode?.(z.mode);z.start()},stop:()=>z.stop()};return this.#N.add(G),z.start(),{get mode(){return z.mode},close:()=>{this.#N.delete(G),z.stop()}}}reportUsage($){if(this.#I)return;try{this.#K.report($.credentialId,$.reading)}catch{}}usageReportState(){return this.#K.state()}close(){if(this.#I)return;if(this.#I=!0,this.#P)this.#V(this.#P);this.#P=void 0;for(let Z of this.#N)Z.stop();this.#N.clear(),this.#W.clear();let $=this.#K.close();if($)this.#A.add($),$.then(()=>this.#A.delete($));else this.#$.close();this.#L=V1(this.#A,(Z)=>(this.#E??this.#R)(Z)).finally(()=>{if(this.#K.drop(),this.#B.clear(),$)this.#$.close()})}async dispose($=this.#R){this.#E=$,this.close(),await this.#L}}import{resolve as L3}from"node:path";var L9=30000,P9={now:()=>performance.now(),schedule($,Z){let J=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(J),unref:()=>J.unref?.()}}};var p0="all",A6=Object.freeze(["primary"]);function h2($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function D1($,Z){return JSON.stringify([$,Z])}function E0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function n($){return typeof $==="number"&&Number.isFinite($)}function m2($){return typeof $==="string"&&$.length>0}function o($,Z,J){return $[Z]===void 0||J($[Z])}function _6($){return n($)&&$>0}function C9($){return typeof $==="string"}function I6($){if(!E0($)||!m2($.scope)||!m2($.label))return!1;switch($.kind){case"reading":return n($.checkedAt)&&n($.usedPercent)&&o($,"resetsAt",C9)&&o($,"windowMinutes",_6);case"retired":return n($.retiredAt);case"absent":return n($.checkedAt);default:return!1}}function R6($){if(!E0($)||!n($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&o($,"remainingPercent",n)&&o($,"usedPercent",n)&&o($,"resetsAt",C9)&&o($,"limit",n)&&o($,"used",n)&&o($,"remaining",n)&&o($,"unit",C9)}function w2($){return E0($)&&n($.value)&&Number.isInteger($.value)&&$.value>=0&&n($.checkedAt)}function O9($){return E0($)&&Object.values($).every(w2)}function S6($){return typeof $==="boolean"}function N1($){return E0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&o($,"balance",n)&&o($,"overageLimitReached",S6)&&n($.checkedAt)}function u2($){if(!E0($))return;let Z=Object.entries($).filter(([,J])=>w2(J));return Z.length===0?void 0:Object.fromEntries(Z)}function d0($){if(M1($))return $;if(!E0($))return;let{counters:Z,credits:J,...z}=$;if(!M1(z))return;let X=u2(Z),G=N1(J)?J:void 0;return{...z,...X===void 0?{}:{counters:X},...G===void 0?{}:{credits:G}}}function M1($){if(!E0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!I6(J))return!1;let z=D1(J.scope,J.label);if(Z.has(z))return!1;Z.add(z)}return o($,"budget",R6)&&o($,"counters",O9)&&o($,"credits",N1)}class V3 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function M3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function j3($){return typeof $==="number"&&Number.isFinite($)}function c2($){return $===void 0||typeof $==="string"&&$!==""}function p2($){return typeof $==="string"&&$!==""}function h1($,Z){return $[Z]===void 0||j3($[Z])}function A9($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function T6($){return M3($)&&c2($.scope)&&p2($.label)&&j3($.usedPercent)&&A9($,"resetsAt")&&($.windowMinutes===void 0||j3($.windowMinutes)&&$.windowMinutes>0)}function k6($){return M3($)&&c2($.scope)&&p2($.label)}function E6($){if(!M3($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&h1($,"remainingPercent")&&h1($,"usedPercent")&&A9($,"resetsAt")&&h1($,"limit")&&h1($,"used")&&h1($,"remaining")&&A9($,"unit")}function L1($){if(!M3($)||!j3($.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(!T6(X))return!1;let G=D1(X.scope??p0,X.label);if(z.has(G))return!1;z.add(G)}if(!J.every(k6))return!1;return($.budget===void 0||E6($.budget))&&($.counters===void 0||O9($.counters))&&($.credits===void 0||N1($.credits))}function b6($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function f6($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function x6($,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 y6($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function w1($,Z){let J=$===void 0?void 0:d0($);if($!==void 0&&J===void 0)throw new V3("stored quota map is malformed");if(!L1(Z))throw new V3("quota observation is malformed");let z=J??{limits:[]},X=Z.checkedAt,G=new Map;for(let P of z.limits)G.set(D1(P.scope,P.label),P);let Q=(P)=>{let I=G.get(P);return I===void 0||X>=h2(I)},W=new Set;for(let P of Z.readings??[]){let I=P.scope??p0,T=D1(I,P.label);if(W.add(T),!Q(T))continue;G.set(T,{scope:I,label:P.label,kind:"reading",checkedAt:X,usedPercent:P.usedPercent,...P.resetsAt===void 0?{}:{resetsAt:P.resetsAt},...P.windowMinutes===void 0?{}:{windowMinutes:P.windowMinutes}})}for(let P of Z.coverage??[]){let I=P.scope??p0,T=D1(I,P.label);if(W.has(T)||!Q(T))continue;let m=G.get(T);G.set(T,m===void 0||m.kind==="absent"?{scope:I,label:P.label,kind:"absent",checkedAt:X}:{scope:I,label:P.label,kind:"retired",retiredAt:X})}let{limits:Y,budget:U,counters:H,credits:K,...M}=z,F=f6(z.budget,Z.budget,X),L=x6(z.counters,Z.counters),A=y6(z.credits,Z.credits);return{...M,limits:[...G.values()].sort(b6),...F===void 0?{}:{budget:F},...L===void 0?{}:{counters:L},...A===void 0?{}:{credits:A}}}var g6=Object.freeze({validate:M1,decode:d0,merge:w1});function d2($,Z=""){let J=new Map,{observation:z}=$,X=(W,Y,U)=>J.set(`${Z}:${W}`,{at:Y,order:0,publication:{...$,observation:U}}),G=(W,Y)=>JSON.stringify([W??"all",Y]),Q=new Set;for(let W of z.readings??[]){let Y=G(W.scope,W.label);Q.add(Y),X(Y,z.checkedAt,{checkedAt:z.checkedAt,readings:[{...W}]})}for(let W of z.coverage??[]){let Y=G(W.scope,W.label);if(!Q.has(Y))X(Y,z.checkedAt,{checkedAt:z.checkedAt,coverage:[{...W}]})}if(z.budget)X("budget",z.checkedAt,{checkedAt:z.checkedAt,budget:{...z.budget}});for(let[W,Y]of Object.entries(z.counters??{}))X(`counter:${W}`,Y.checkedAt,{checkedAt:z.checkedAt,counters:{[W]:{...Y}}});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 w6}from"node:crypto";import{stat as u6}from"node:fs/promises";import{resolve as u1}from"node:path";function l2($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function _9($,Z,J){return $.some((z)=>l2(z,Z,J))}function I9($,Z,J){let z={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((X)=>X.credentialId!==Z||X.accountIdentity!==J),z]}function R9($,Z,J){return $.filter((z)=>!Z.some((X)=>l2(z,X,J)))}function T9($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>q0(Z).map((J)=>({credentialId:J,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function c6($,Z){let J=q0(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 N3="vault:";function p6($){return w6("sha256").update($).digest("hex")}function d6($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function l6($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function q0($){return[$.credentialId,...$.aliases??[]]}function n2($,Z,J={}){let z=J.now??Date.now(),X=J.routePrefix??N3,G=J.reservedRouteIds??new Set,Q=$?.rows??[],W=$?void 0:J.seed,Y=[...$?.declined??W?.declined??[]],U=Z.skipped.length===0,H=new Set(Z.credentials.map((V)=>V.credentialId)),K=new Set(Z.skipped.flatMap((V)=>V.credentialId===void 0?[]:[V.credentialId])),M=Z.skipped.some((V)=>V.credentialId===void 0),F=(V)=>!H.has(V)&&(K.has(V)||M),L=new Map;for(let V of Q){if(V.accountIdentity===void 0)continue;for(let q of q0(V))if(!L.has(q))L.set(q,V.accountIdentity)}let A=new Map;for(let V of Z.credentials){let q=V.accountIdentity!==void 0?{credential:V,identity:V.accountIdentity,claimed:!0}:{credential:V,identity:L.get(V.credentialId),claimed:!1},D=l6(q),C=A.get(D)??[];C.push(q),A.set(D,C)}let P=new Set,I=new Set(G),T=[],m=(V,q)=>V.credential.credentialId.localeCompare(q.credential.credentialId),c=[...A.values()].map((V)=>V.toSorted(m)).sort((V,q)=>V[0]&&q[0]?m(V[0],q[0]):0);for(let V of c){let q=V[0]?.identity,D=V.filter((b)=>b.credential.state==="active"),C=D.length?D:V,v=C.filter((b)=>b.claimed),E=v.length?v:C,x=new Set(V.map((b)=>b.credential.credentialId)),$0=Q.find((b)=>!P.has(b)&&q0(b).some((j0)=>x.has(j0))&&(b.accountIdentity===void 0||b.accountIdentity===q)),$1=E.find((b)=>b.credential.credentialId===$0?.credentialId)??E[0];if(!$1)continue;let h=$1.credential,i=$0??(q===void 0?void 0:Q.find((b)=>!P.has(b)&&b.accountIdentity===q));if(i)P.add(i);let Z0=i?.routeId;if(!Z0||G.has(Z0)){let b=`${X}${h.credentialId}${q===void 0?"":`~${p6(q).slice(0,10)}`}`;Z0=b;for(let j0=2;I.has(Z0);j0++)Z0=`${b}~${j0}`}I.add(Z0);let E1=i?q0(i).filter(F):[],x0=[...new Set([...V.map((b)=>b.credential.credentialId),...E1])].filter((b)=>b!==h.credentialId).sort((b,j0)=>b.localeCompare(j0)),l3=J.mapAccount?.(h)??{};T.push({previousIndex:i?Q.indexOf(i):1/0,row:{routeId:Z0,credentialId:h.credentialId,credentialType:h.credentialType,...q!==void 0&&{accountIdentity:q},...x0.length&&{aliases:x0},state:h.state,label:l3.label?.trim()||d6(h),...h.email!==void 0&&{email:h.email},...h.orgName!==void 0&&{orgName:h.orgName},enabled:![h.credentialId,...x0].some((b)=>_9(Y,b,q)),addedAt:i?.addedAt??z,...i?.quota!==void 0&&{quota:i.quota},...!$1.claimed&&q!==void 0&&{unclaimed:!0}}});let Z1=T.at(-1);if(W&&Z1)Z1.previousIndex=c6(W,Z1.row)}return Q.forEach((V,q)=>{if(P.has(V)||!q0(V).some(F))return;if(I.has(V.routeId))return;let[D,...C]=q0(V).filter((x)=>!H.has(x));if(D===void 0)return;I.add(V.routeId);let{aliases:v,...E}=V;T.push({previousIndex:q,row:{...E,credentialId:D,...C.length&&{aliases:C},stale:!0}})}),T.sort((V,q)=>V.previousIndex===q.previousIndex?V.row.credentialId.localeCompare(q.row.credentialId):V.previousIndex-q.previousIndex),{version:1,view:Z.view,...$?.limits!==void 0&&{limits:$.limits},complete:U,...!U&&{rejected:Z.skipped.map((V)=>({...V.credentialId!==void 0&&{credentialId:V.credentialId},reason:V.reason}))},rows:T.map((V)=>V.row),declined:Y}}function k9($){return($?.rows??[]).filter((Z)=>Z.enabled&&Z.state==="active").map((Z)=>({id:Z.routeId,kind:Z.credentialType==="oauth"?"oauth":"api-key",...Z.quota!==void 0&&{quota:Z.quota}}))}function c1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function P1($){return $===void 0||typeof $==="string"}function a6($){let Z=c1($)?d0($.quota):void 0;if(!c1($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!P1($.accountIdentity)||!P1($.email)||!P1($.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 s6=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function a2($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!c1(J)||!P1(J.credentialId)||typeof J.reason!=="string"||!s6.has(J.reason))return;Z.push(J)}return Z}function i2($){if(!c1($)||$.version!==1||!P1($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!a2($.rejected))throw new O("invalid-state","Claustrum roster file is not valid");let Z=[];for(let X of $.rows){let G=a6(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(!c1(X)||typeof X.credentialId!=="string"||!P1(X.accountIdentity))throw new O("invalid-state","Claustrum roster file is not valid");J.push(X)}let z=a2($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...z&&{rejected:z},...$.limits!==void 0&&{limits:$.limits},rows:Z,declined:J}}function E9($){return i2(JSON.parse(JSON.stringify($)))}var n6=new g0({followSymlinks:!0});async function a($){if(_)return S9($);let Z=await n6.read([$],([J=$])=>S9(J));return structuredClone(Z)}async function S9($){let Z;try{Z=await G0($,_)}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 i2(J)}var o2={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},r2={name:"claustrum-roster",ttlMs:30000};async function l0($,Z,J={}){return Z9($,{...o2,signal:J.signal},async(z)=>{let X=await S9($),{next:G,result:Q}=await Z(X,{assertOwned:()=>z.assertOwned()});if(G){await z.assertOwned();try{await Y1($,G,{beforeRename:async()=>{await J.beforePublish?.(),J.signal?.throwIfAborted(),await z.assertOwned()}})}catch(W){if(W&&typeof W==="object"&&"published"in W&&W.published===!0)J.onPublished?.();throw W}J.onPublished?.()}return Q})}function b9($,Z){return l0($,(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=I9(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 f9($,Z){return l0($,(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:R9(J.declined,q0(z),z.accountIdentity),rows:J.rows.map((X)=>X===z?{...X,enabled:!0}:X)},result:void 0}})}function i6($){return new O("invalid-order",$)}function o6($,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 x9($,Z,J={}){return l0($,(z)=>{let X=z?.rows??[],G=o6(X,Z);if(G)throw i6(G);let Q=new Map;for(let U of X){let H=Q.get(U.routeId);if(H)H.push(U);else Q.set(U.routeId,[U])}let W=[...Z],Y=W.flatMap((U)=>Q.get(U)??[]);if(!z||Y.every((U,H)=>U===X[H]))return{result:{ids:W,outcome:"unchanged"}};return{next:{...z,rows:Y},result:{ids:W,outcome:"reordered"}}},{...J.signal&&{signal:J.signal}})}function r6($,Z){if(!q0($).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")&&q0($).length===1)return"bind";return"refuse"}async function y9($,Z){let{routeId:J,observation:z,...X}=Z;return t2($,{routeId:J,observation:z,accountIdentity:X.accountIdentity,receipt:X})}async function t2($,Z){if(!L1(Z.observation))return!1;let J=e($,await a($));if(!b0(J,Z).kept)return!1;return $7($,Z)}function g9($,Z){return t2($,Z)}function b0($,Z){let J=$?.rows.find((Q)=>Q.routeId===Z.routeId),z=!J?"refuse":Z.receipt?r6(J,Z.receipt):J.accountIdentity!==void 0&&J.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!J||z==="refuse")return{roster:$,kept:!1};let X=w1(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 D3=new Map;function p1($){D3.delete(u1($))}function e2($,Z){let J=u1($);if(Z instanceof O)return Z.kind==="roster-busy";if(Z instanceof I0||Z instanceof N0)return u1(Z.details.target)===J;if(Z instanceof w){let z=u1(Z.path);return[o2.name,r2.name].some((X)=>{let G=U1(J,X);return z===G||z.startsWith(`${G}.`)})}return!1}var t6=4;async function s2($){try{let{dev:Z,ino:J,size:z,mtimeMs:X}=await u6($);return{dev:Z,ino:J,size:z,mtimeMs:X}}catch{return}}function e6($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function $5($,Z,J){for(let z=0;z<t6;z++){let X=await s2($),G=await a($),Q,W,Y;try{({target:Q,local:W}=Z(G));let U=JSON.stringify(J(Q));Y=JSON.stringify(Q)!==U||W!==void 0&&JSON.stringify(W)!==U}catch{return"commit"}if(!e6(X,await s2($)))continue;if(Y)return"commit";return Z7($)?"commit":"unchanged"}return"commit"}async function d1($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){p1($.path);return}let J=await L0({...r2,path:$.path,renew:!0});if(!J){let Q=await a($.path);if($.signal?.throwIfAborted(),!Q?.view)throw new O("roster-busy","Claustrum account discovery is already in progress");return Q}let z=u1($.path),X=$.listedOver,G;try{let Q=await a($.path),W=X?void 0:D3.get(z);G=W&&(W.previousView===Q?.view||W.inventory.view===Q?.view)?W:{inventory:await $.custody.discover($.signal),previousView:Q?.view},D3.delete(z);let{inventory:Y}=G;$.onInventory?.(Y),$.signal?.throwIfAborted();let U=typeof $.projection==="function"?$.projection():$.projection,H=(F)=>n2(F,Y,U),K=async()=>{return $.signal?.throwIfAborted(),await J.assertOwned(),Z()};if(await $5($.path,(F)=>{if(X)return{target:F};let L=e($.path,F);return{target:F,...L!==F&&{local:L}}},H)==="unchanged"){if(!await K())return;return await a($.path)}return await l0($.path,async(F)=>{if(!await Z())return{result:void 0};if($.signal?.throwIfAborted(),await J.assertOwned(),X&&F?.view!==X.view&&F?.view!==Y.view)return{result:F};let L=H(F);return{...JSON.stringify(F)!==JSON.stringify(L)&&{next:L},result:L}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await J.assertOwned()}})}catch(Q){if(Q instanceof I0&&G&&!X&&!$.signal?.aborted&&await Z())D3.set(z,G);throw Q}finally{await J.release($.signal)}}var a0=new Map,Z5=z0("claustrum"),z7=100;function X7($,Z=P9){let J=L3($),z=a0.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},a0.set(J,z);return z}function G7($,Z,J){let z=X7($,J);z.listeners.add(Z);let X;return()=>X??=(()=>{return z.listeners.delete(Z),z.listeners.size?Promise.resolve():v9($)})()}function J5($){return d2($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function $7($,Z){if(!L1(Z.observation))return Promise.resolve(!1);let J=X7($),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 J5(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 W7(J,z7),Promise.resolve(!0)}function Q7($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,J)=>Z.order-J.order)}function e($,Z){let J=a0.get(L3($));if(J)for(let z of Q7(J.pending)){if(z.priorReading)Z=b0(Z,z.priorReading).roster;Z=b0(Z,z.publication).roster}return Z}function Z7($){return!!a0.get(L3($))?.pending.size}function W7($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let J=$.draining?0:($.committedAt??-1/0)+L9-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,J),()=>{return $.timer=void 0,Y7($)}),!$.draining)$.timer.unref?.()}function J7($){$.timer?.cancel(),$.timer=void 0}function Y7($){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 l0($.path,(z)=>{let X=z;for(let Q of Q7(Z)){if(Q.priorReading)X=b0(X,Q.priorReading).roster;X=b0(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)Z5.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()):z7;W7($,J)}})(),$.running}async function v9($,Z=1000){let J=L3($),z=a0.get(J);if(!z)return;z.draining=!0,J7(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)Y7(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(),J7(z),z.pending.clear(),a0.get(J)===z)a0.delete(J)}}}var P3=1e4;function H7(){return new u}var m9;function K7($,Z){if(!m9)throw Error("ClaustrumConsumer is not initialized");return m9($,Z)}function U7(){return new O("not-active","Claustrum scoped custody is not active")}class h9{#$;#Z=new AbortController;#z;#Y;#G;#Q;#X;#J;#H;#W;#U=!1;#K=new Set;#B;#q;#V;#D;#C=new Map;#P;#O;#F;#M;#I=new WeakMap;static{m9=($,Z)=>{let J=new h9(Z);return J.#F=$,{consumer:J,hooks:J.#g()}}}constructor($){this.#$=$,this.#z=$.logger??z0("claustrum"),this.#Y=B1(this.#z,this.#Z.signal),this.#O=G7($.rosterPath,(Z)=>{this.#J=b0(this.#J,Z).roster})}#j($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#N($){return this.#K.add($),$.then(()=>this.#K.delete($),()=>this.#K.delete($)),$}async#A(){if(p())return!0;return await this.#$.isCustodyActive?.()??!0}#R($,Z){let J=y0([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#E(){if(this.#j(),this.#G)return this.#G;if(!this.#Q){let $={timedOut:!1};this.#Q=this.#L($),this.#N(this.#Q)}return this.#R(this.#Q)}#L($){let Z=this.#$.setTimeoutImpl??setTimeout,J=this.#$.clearTimeoutImpl??clearTimeout,z=(!p()&&this.#$.connect?this.#$.connect():Promise.resolve().then(()=>h0(this.#$.pluginId))).then((Q)=>{if(this.#Z.signal.aborted||$.timedOut){if(Q.close(),!$.timedOut)this.#j();throw H7()}if(this.#G=new j1({client:Q,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#z,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&Q.insula)this.#q=i3(Q.insula,this.#$.tokenPath);return this.#G}),X,G=new Promise((Q,W)=>{X=Z(()=>{if($.timedOut=!0,this.#Z.signal.aborted)return;this.#z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:this.#S()}),W(H7())},this.#S()),X.unref?.()});return Promise.race([z,G]).finally(()=>{if(X)J(X);this.#Q=void 0})}#S(){return this.#$.connectTimeoutMs??P3}snapshot(){return this.#J}grantReach(){if(this.#F)return this.#F.grantReach(this.#J?.view);let $=this.#H;return $&&this.#J?.view===$.view?$.reach:void 0}watchState(){if(this.#F)return Object.freeze({vault:this.#F.watchMode()});return Object.freeze({vault:this.#V?.mode??"polling",...this.#$.insula&&{insula:this.#q?.source.watchMode()??"polling"}})}#k(){this.#V?.close(),this.#V=void 0,this.#D?.(),this.#D=void 0}keptReceiptState(){if(this.#F){let $=this.#M;return $&&this.#F.leaseLive($)?$.custody.keptReceiptState():this.#F.keptReceiptState()}return this.#G?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return k9(this.#J)}refresh(){if(this.#j(),this.#F)return this.#N(this.#x(this.#F));if(this.#X)return this.#X;return this.#X=(async()=>{if(!await this.#A()){if(this.#J=void 0,this.#H=void 0,this.#k(),this.#G)this.#G.close(),this.#N(this.#G.dispose(this.#Y));this.#G=void 0,this.#q?.release(),this.#q=void 0;return}let $=await this.#E(),Z,J=await d1({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.#j();let z=J?.view!==this.#J?.view;if(this.#J=e(this.#$.rosterPath,J),$.retain(J?.rows??[]),Z&&J?.view!==void 0)this.#H=Z.grantReach?{view:J.view,reach:Z.grantReach}:void 0;if(J&&z)this.#$.onRoster?.(J);return this.#P=(this.#$.now??Date.now)(),J})().finally(()=>{this.#X=void 0}),this.#N(this.#X),this.#_(this.#X),this.#X}#_($){try{this.#$.onDiscovery?.($)}catch(Z){this.#$.onError?.(Z)}}start(){if(this.#U)return;if(this.#j(),this.#U=!0,this.#F){this.#F.start();return}let $=async()=>{try{if(await this.#y())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.#W=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#W=void 0,this.#N($())},Z),this.#W.unref?.()};this.#N($())}async#y(){if(this.#V?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#P===void 0||$-this.#P>=J1)return!0;return!await this.#A()}#b(){let $=this.#G;if(this.#Z.signal.aborted||!$)return;if(this.#V??=$.watchRoster({view:()=>this.#J?.view,onView:()=>this.#N((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.#q&&!this.#D)this.#D=this.#q.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#A())return;try{if(!p())await T0(this.#$.tokenPath);await this.#E(),await this.#q?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#A())return;try{if(!p())await T0(this.#$.tokenPath);return this.#f($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#A())return;try{if(!p())await T0(this.#$.tokenPath);let J=e(this.#$.rosterPath,await a(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.#A())return{miss:"unreachable"};try{if(!p())await T0(this.#$.tokenPath);let z=e(this.#$.rosterPath,await a(this.#$.rosterPath))?.rows.find((Q)=>Q.routeId===$)?.accountIdentity;if(!z||!this.#q)return{miss:"unreachable"};let X=this.#q.source.lookup(Z.provider,z,(this.#$.now??Date.now)()),G=X.reading&&Z.normalize(X.reading.entry,X.reading.context);if(X.miss)return{miss:X.miss,...G!==void 0&&{reading:G}};return G===void 0?{miss:"unreachable"}:{reading:G}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute($,Z){let J=await this.lookupInsulaQuotaForRoute($);if(J.miss==="cold"||J.miss==="upstream-failed"){if(this.#C.get($)!==J.miss)this.#C.set($,J.miss),this.#z.warn("skipped insula provider poll",{reason:J.miss});return}return this.#C.delete($),J.miss?Z():J.reading}#f($){if(!this.#$.insula||!$)return;let Z=this.#q?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){if(this.#F)return this.#m(this.#F,$,Z);this.#j(Z);let J=this.#J??await this.#R(this.refresh(),Z);if(!J||!await this.#A())throw this.#G?.close(),this.#G=void 0,this.#k(),this.#q?.release(),this.#q=void 0,new O("not-active","Claustrum scoped custody is not active");let z=e(this.#$.rosterPath,await a(this.#$.rosterPath));this.#j(Z);let X=J.rows.find((Y)=>Y.routeId===$),G=z?.rows.find((Y)=>Y.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.#E(),Z),W=y0([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()}}#g(){return{discovery:($)=>{let Z=this.#F;if(!Z||!this.#$.onDiscovery||this.#Z.signal.aborted)return;let J=this.#N($.then((z)=>this.#v(Z,z)));this.#_(J)},install:($)=>{if(this.#Z.signal.aborted)return;let Z=$.view!==this.#J?.view;if(this.#J=e(this.#$.rosterPath,$),Z)try{this.#$.onRoster?.($)}catch(J){this.#$.onError?.(J)}},reset:()=>{this.#J=void 0},roster:()=>this.#J,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#x($){let Z=await $.refresh();return this.#v($,Z)}#v($,Z){if(this.#j(),!Z)return;if(Z.errors.has($.provider))throw Z.errors.get($.provider);return this.#J}#T($){if($&&this.#M!==$)return;this.#M?.release(),this.#M=void 0}async#u($,Z){let J=this.#M;if(J&&$.leaseLive(J))return J;this.#T();let z=await $.acquire(Z);if(this.#Z.signal.aborted)z.release(),this.#j();let X=this.#M;if(X&&$.leaseLive(X))return z.release(),X;return this.#M=z,z}async#m($,Z,J){if(this.#j(J),!this.#J)await this.#R($.refresh(),J);let z=this.#J;if(!await $.readAuthority())throw this.#T(),U7();if(this.#j(J),!z)throw new O("route-unavailable","Claustrum has no roster for this provider yet");let X=e(this.#$.rosterPath,await a(this.#$.rosterPath));this.#j(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}},Y=y0([this.#Z.signal,...J?[J]:[]]);try{for(let U=0;;U++){let H=await this.#u($,Y.signal);try{let K=await H.custody.authorize(W,Y.signal,Z);return this.#I.set(K,H),K}catch(K){if(U>0||Y.signal.aborted||$.leaseLive(H)||!(K instanceof O)||K.kind!=="closed")throw K;if(this.#T(H),!await $.readAuthority())throw U7()}}}finally{Y.dispose()}}reportUsage($){if(this.#Z.signal.aborted)return;try{let Z=this.#J?.rows.find((J)=>J.routeId===$.routeId);if(!Z?.enabled||Z.state!=="active"||Z.credentialId!==$.credentialId&&!Z.aliases?.includes($.credentialId))return;if(this.#F){if(this.#M&&this.#F.leaseLive(this.#M))this.#M.custody.reportUsage($)}else this.#G?.reportUsage($)}catch{}}usageReportState(){try{return(this.#F?this.#M?.custody:this.#G)?.usageReportState()??{pending:0,inFlight:!1,dropped:0}}catch{return{pending:0,inFlight:!1,dropped:0}}}async reportFailure($,Z,J){if(this.#j(),this.#F){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(N9(J.site,X,Q,this.#z))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.#j(),await b9(this.#$.rosterPath,$),this.#J=e(this.#$.rosterPath,await a(this.#$.rosterPath)),this.#J)this.#F?.publishRoster(this.#J);if(this.#F)this.#F.retainUnion();else this.#G?.retain(this.#J?.rows??[])}async accept($){if(this.#j(),await f9(this.#$.rosterPath,$),this.#J=e(this.#$.rosterPath,await a(this.#$.rosterPath)),this.#J)this.#F?.publishRoster(this.#J)}async reorder($){this.#j();let Z=await x9(this.#$.rosterPath,$);if(this.#J=e(this.#$.rosterPath,await a(this.#$.rosterPath)),this.#J)this.#F?.publishRoster(this.#J);return Z}async recordQuota($,Z,J){return this.#j(),y9(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.#j(),g9(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.#W)(this.#$.clearTimeoutImpl??clearTimeout)(this.#W);if(this.#W=void 0,this.#k(),this.#G)this.#G.close(),this.#N(this.#G.dispose(this.#Y));this.#M?.release(),this.#M=void 0,this.#F?.detach(),this.#q?.release(),this.#q=void 0,this.#J=void 0,this.#H=void 0,this.#O(),p1(this.#$.rosterPath)}async dispose(){this.close(),this.#B??=Promise.all([V1(this.#K,this.#Y),this.#O()]).then(()=>{}),await this.#B}}import{createHash as z5}from"node:crypto";import{channel as X5}from"node:diagnostics_channel";import{readdir as G5,stat as Q5}from"node:fs/promises";import{dirname as W5,join as C1,resolve as q7}from"node:path";var C3=new Map,Y5=/^[a-z0-9][a-z0-9._-]{0,63}$/,H5=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,U5=/^[0-9a-f]{16}$/,F7=3;function u9($,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=u9($[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=u9($[G],J);if(Q===void 0)return;z.push(`${JSON.stringify(G)}:${Q}`)}return`{${z.join(",")}}`}function K5($,Z){let J=u9({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??N3,mapAccount:$.mapAccount?String($.mapAccount):null});if(J===void 0)throw new O("invalid-state","Claustrum hub classifierInput must be plain JSON");return z5("sha256").update(J).digest("hex").slice(0,16)}function B7($,Z){if(typeof $!=="string"||!Y5.test($)||H5.test($))throw new O("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function f0($="Claustrum custody lease is closed"){return new O("closed",$)}function w9(){return new O("not-active","Claustrum scoped custody is not active")}function V7(){return new u}function q5($,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 j7($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class M7{#$;#Z;#z;#Y=new AbortController;#G=new Map;#Q=new WeakMap;#X=0;#J;#H;#W;#U;#K;#B;#q=0;#V;#D;#C;#P=!1;#O=new Set;#F;#M;#I;constructor($){if(!$.family||!("classify"in $.family))throw new O("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=B7($.hostGeneration,"host generation"),J=$.members.map((X)=>B7(X,"member"));if(new Set(J).size!==J.length)throw new O("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??z0("claustrum"),this.#z=B1(this.#Z,this.#Y.signal),this.#M=C1($.stateDir,"rosters",Z),this.#I=K5($,J);let z=C1(this.#M,this.#I);for(let X of J)this.#G.set(X,{provider:X,path:C1(z,`${X}.json`),closed:!1})}#j($){return this.#O.add($),$.then(()=>this.#O.delete($),()=>this.#O.delete($)),$}#N(){if(this.#Y.signal.aborted)throw f0("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.#N();let J=this.#A($);if(J.hooks)throw new O("wrong-consumer","Claustrum hub member was already built");for(let K of["rosterPath","tokenPath","family","connect","isCustodyActive","insula","pollIntervalMs","routePrefix","mapAccount"])if(K in Z)throw new O("wrong-consumer",`Claustrum hub members cannot take ${K}`);let z={provider:J.provider,start:()=>this.start(),refresh:()=>this.#m(),readAuthority:()=>this.#x(),acquire:(K)=>this.acquire(K),leaseLive:(K)=>this.#S(K),grantReach:(K)=>K!==void 0&&this.#V?.view===K?this.#V.reach:void 0,watchMode:()=>this.watchState(),keptReceiptState:()=>this.keptReceiptState(),retainUnion:()=>this.#w(),publishRoster:(K)=>this.#R(J,K),forget:(K)=>this.#J?.custody?.forget(K),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}=K7(z,X);J.hooks=Q;let W=q7(J.path),Y=C3.get(W)??new Set,U=(K)=>{if(J.closed||this.#B!==!0||!this.#J||!this.#L(this.#J)||!Q.roster()||this.#c(Q,K))return;if(J.seen=JSON.stringify(E9(K)),Q.install(K),K.view!==this.#V?.view)J.pending??={failures:0,wait:0};this.#w()};Y.add(U),J.receiveRoster=U,C3.set(W,Y);let H=!0;return J.releaseRoster=()=>{if(!H)return;if(H=!1,Y.delete(U),!Y.size)C3.delete(W)},G}#R($,Z){let J=this.#J;if($.closed||!J||!this.#L(J))return;$.seen=JSON.stringify(E9(Z)),$.hooks?.install(Z);for(let z of C3.get(q7($.path))??[]){if(!this.#L(J))return;if(z!==$.receiveRoster)z(Z)}}#E(){let $={id:++this.#X,count:0,ended:!1,controller:new AbortController};return this.#J=$,$}#L($){return!$.ended&&this.#J===$&&!this.#Y.signal.aborted}#S($){let Z=this.#Q.get($);return!!Z&&!Z.released&&!Z.generation.ended}#k($,Z=f0()){if($.ended)return;if($.ended=!0,$.count=0,this.#J===$)this.#J=void 0;if(this.#W&&this.#Q.get(this.#W)?.generation===$)this.#W=void 0;if(this.#U?.generation===$)this.#U.watch.close(),this.#U=void 0;if($.controller.abort(Z),$.custody)$.custody.close(),this.#j($.custody.dispose(this.#z))}#_($){if($.ended)return;if($.count--,$.count<=0)this.#k($)}#y($){let Z=this.#H;if(Z?.generation===$&&Z.promise)return Z.promise;let J={generation:$,timedOut:!1},z=this.#$.connectTimeoutMs??P3,X,G=(!p()&&this.#$.connect?this.#$.connect():Promise.resolve().then(()=>h0(this.#$.pluginId))).then((Y)=>{if(J.timedOut)throw Y.close(),V7();if(!this.#L($)||$.count<=0)throw Y.close(),f0("Claustrum connection is no longer wanted");return $.custody=new j1({client:Y,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((Y,U)=>{X=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(J.timedOut=!0,!this.#L($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:z}),U(V7())},z),X.unref?.()});return J.promise=this.#j(Promise.race([G,Q]).finally(()=>{if(X)(this.#$.clearTimeoutImpl??clearTimeout)(X)})),J.promise.finally(()=>{if(this.#H===J)this.#H=void 0}).catch(()=>{}),this.#H=J,J.promise}acquire($){try{if(this.#N(),$?.throwIfAborted(),this.#B===!1)throw w9()}catch(J){return Promise.reject(J)}let Z=this.#J??this.#E();return Z.count++,this.#b(Z,$,!0)}async#b($,Z,J){let z=$.custody;if(!z){let X=y0([$.controller.signal,...Z?[Z]:[]]);try{z=await q5(this.#y($),X.signal)}catch(G){if(!$.ended)throw this.#_($),G;return this.#f(Z,J)}finally{X.dispose()}}if($.ended)return this.#f(Z,J);if(Z?.aborted)throw this.#_($),Z.reason;return this.#g($,z)}#f($,Z){if($?.throwIfAborted(),this.#N(),this.#B===!1)throw w9();if(!Z)throw f0();let J=this.#J??this.#E();return J.count++,this.#b(J,$,!1)}#g($,Z){let J={generation:$,custody:Z,released:!1},z=()=>{if(J.released||$.ended)throw f0()},X=Object.freeze({authorize:async(Q,W,Y)=>{z();let U=y0([$.controller.signal,...W?[W]:[]]);try{return await Z.authorize(Q,U.signal,Y)}finally{U.dispose()}},reportFailure:async(Q,W,Y)=>{return z(),Z.reportFailure(Q,W,Y)},reportUsage:(Q)=>{if(!J.released&&!$.ended)Z.reportUsage(Q)},usageReportState:()=>{return z(),Z.usageReportState()},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.#_($)}});return this.#Q.set(G,J),G}leaseState(){let $=this.#J;return Object.freeze({generation:$?.id,count:$?.count??0})}async#x(){let $=p()||(await this.#$.isCustodyActive?.()??!0);if(this.#Y.signal.aborted)return!1;let Z=this.#B;if(this.#B=$,!$&&Z!==!1)this.#v();return $}#v(){this.#q++;let $=this.#J;if($)this.#k($,w9());this.#W=void 0,this.#U?.watch.close(),this.#U=void 0,this.#V=void 0,this.#D=void 0;for(let Z of this.#G.values())Z.seen=void 0,Z.pending=void 0,Z.hooks?.reset(),p1(Z.path)}#T(){return[...this.#G.values()].filter(($)=>$.hooks&&!$.closed)}async#u(){let $=this.#W,Z=$&&this.#Q.get($);if($&&Z&&this.#S($))return Z;this.#W=void 0;let J=await this.acquire(this.#Y.signal),z=this.#W&&this.#Q.get(this.#W);if(this.#W&&z&&this.#S(this.#W))return J.release(),z;this.#W=J;let X=this.#Q.get(J);if(!X)throw f0();return X}#m(){try{this.#N()}catch(z){return Promise.reject(z)}let $=this.#K;if($&&!$.generation?.ended)return $.promise;let Z={},J=this.#j(this.#n(Z).finally(()=>{if(this.#K===Z)this.#K=void 0}));Z.promise=J,this.#K=Z;for(let z of this.#T())z.hooks?.discovery(J);return J}async#n($){if(!await this.#x())return;let Z=await this.#u(),J=Z.generation;if($.generation=J,!this.#L(J))return;let z=await this.#o().then(()=>{return},(H)=>H instanceof Error?H:Error(String(H))),X=new Map(await Promise.all([...this.#G.values()].map(async(H)=>[H,await a(H.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(H){if(!this.#L(J))return;for(let K of this.#G.values())if(K.pending)this.#h(K);throw H}if(!this.#L(J))return;let Q=this.#T(),W=await Promise.all(Q.map((H)=>H.hooks&&!H.closed?this.#i(H,H.hooks,G,z??X.get(H),J):void 0));if(!this.#L(J))return;let Y=new Map,U=!0;for(let[H,K]of Q.entries()){let M=K.hooks,F=W[H];if(!M||!F)continue;if("error"in F){let{error:A}=F;if(U=!1,this.#h(K),e2(K.path,A))this.#Z.debug("claustrum hub member commit refused",{member:K.provider});else Y.set(K.provider,A);continue}let{roster:L}=F;if(!this.#L(J))return;if(L?.view!==G.view)U=!1,this.#h(K);else K.pending=void 0;if(!L)continue;if(this.#c(M,L)){U=!1,this.#h(K);continue}this.#R(K,L)}if(!this.#L(J))return;if(this.#w(),U)this.#V=Object.freeze({view:G.view,...G.grantReach&&{reach:G.grantReach},refused:Object.freeze([...G.refused??[]]),notMine:G.notMine??0});return this.#D=(this.#$.now??Date.now)(),{errors:Y}}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 f0("Claustrum hub member has no base view");if(z instanceof Error)throw z;let Q;if(!z.file){let Y=X5("common-auth.claustrum.phases");if(Y.hasSubscribers)Y.publish({logger:this.#Z,phase:`seed read ${$.provider} begin`});try{Q=await this.#r($)}finally{if(Y.hasSubscribers)Y.publish({logger:this.#Z,phase:`seed read ${$.provider} end`})}}return{roster:await d1({path:$.path,custody:{discover:async()=>G},isActive:()=>this.#L(X)&&this.#B===!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[W5(this.#M),this.#M,C1(this.#M,this.#I)])await F1($,{},"roster directory")}async#r($){let Z=`${$.provider}.json`,J=[C1(this.#M,Z)];try{for(let X of await G5(this.#M))if(X!==this.#I&&U5.test(X))J.push(C1(this.#M,X,Z))}catch{}let z;for(let X of J)try{let G=(await Q5(X)).mtimeMs,Q=await a(X);if(Q&&(!z||G>z.modified))z={modified:G,roster:Q}}catch{}return z&&T9(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(J1/J)),X=Z<=F7?1:Math.min(2**(Z-F7),z);$.pending={failures:Z,wait:X-1}}#w(){let $=this.#J?.custody;if(!$)return;$.retain(this.#T().flatMap((Z)=>Z.hooks?.roster()?.rows??[]))}async#t(){let $=this.#q;for(let Z of this.#T()){let J;try{J=await a(Z.path)}catch(W){Z.hooks?.onError(W);continue}if($!==this.#q||this.#B!==!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=j7(G);if(Z.seen=X,this.#R(Z,J),j7(z.roster())!==Q)this.#w()}}#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.#U?.watch.mode!=="watching"||$)return!0;let Z=(this.#$.now??Date.now)();return this.#D===void 0||Z-this.#D>=J1}#$0(){let $=this.#W,Z=$&&this.#Q.get($);if(!$||!Z||!this.#S($)||this.#B!==!0)return;let J=Z.generation;if(!this.#L(J)||this.#U?.generation===J)return;let z=Z.custody.watchRoster({view:()=>this.#V?.view,onView:()=>this.#j((async()=>{while(this.#K)await this.#K.promise.catch(()=>{});if(!this.#L(J))return;await this.#a()})()),onRefused:(X)=>this.#d(X),onError:(X)=>this.#p(X)});this.#U={generation:J,watch:z}}#p($){if(!this.#Y.signal.aborted)this.#$.onError?.($)}#d($){if(this.#Y.signal.aborted)return;this.#$.onError?.($);for(let Z of this.#T())Z.hooks?.onError($)}#l($){for(let[Z,J]of $?.errors??[])this.#G.get(Z)?.hooks?.onError(J)}async#a(){let $;try{$=await this.#m()}catch(Z){this.#d(Z);return}this.#l($)}async#s(){try{if(await this.#x()){if(await this.#t(),this.#e())await this.#a();this.#$0()}}catch(Z){this.#p(Z)}if(this.#Y.signal.aborted)return;let $=this.#$.pollIntervalMs??5000;if($<=0)return;this.#C=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#C=void 0,this.#j(this.#s())},$),this.#C.unref?.()}start(){if(this.#P)return;this.#N(),this.#P=!0,this.#j(this.#s())}async refresh(){this.#l(await this.#m())}refusals(){let $=this.#V;return $&&Object.freeze({view:$.view,refused:$.refused,notMine:$.notMine})}grantReach(){return this.#V?.reach}watchState(){let $=this.#U;return $&&this.#L($.generation)?$.watch.mode:"polling"}keptReceiptState(){return this.#J?.custody?.keptReceiptState()??Object.freeze({active:!1,since:null})}close(){if(this.#Y.signal.aborted)return;this.#Y.abort(f0("Claustrum discovery hub is closed"));for(let Z of this.#G.values())Z.releaseRoster?.();if(this.#C)(this.#$.clearTimeoutImpl??clearTimeout)(this.#C);this.#C=void 0;let $=this.#J;if($)this.#k($);this.#W=void 0,this.#U?.watch.close(),this.#U=void 0}async dispose(){this.close(),this.#F??=V1(this.#O,this.#z),await this.#F}}var n0={opencode:j5,pi:M5},c9={opencode:"Claude sign-in for OpenCode",pi:"Claude sign-in for Pi"};function p9($,Z){let{tokenPath:J}=D7($,Z);return{stateDir:V5(J),host:$,override:J}}function d9($,Z){return D5($==="pi"?Z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0,$==="pi"?{...Z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:Z)}class s0 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 l9($,Z){let J=Z??n0[$];if(typeof J!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(J))throw new s0("permission-refused");return["auth","grant","--principal",`enrolled:${J}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"]}async function N7($,Z){try{await Z.processFence();let J=await B3(Z.paths??D7($,Z.env),n0[$]);if(J.state==="blocked")throw new s0("permission-refused");let z=J.state==="approved"?J.approvedName:void 0;if(J.state==="approved"&&J.requestedGrantsStatus==="sent")return z;let X=l9($,z);if((await Z.runner.run(Z.ckBinary??"ck",X,{env:Z.env})).exitCode!==0)throw new s0("permission-refused");return z}catch{throw new s0("permission-refused")}}import{createHash as _5}from"node:crypto";import{lstat as I5,mkdir as R5,readFile as k7}from"node:fs/promises";import{dirname as S5}from"node:path";import{assertHostsStopped as T5,canonicalPath as s9,createNativeAccountRuntime as k5,custodyTombstoneOAuth as E5,inspectNativeHostAuthEntry as E7,NativeMigrationError as i0,nativeJournalMayAdoptLaterHostLogin as b5,nativePoolHoldsAccountData as f5,prepareNativeMigration as x5,readNativeEnrollmentMode as b7,readNativeMigrationJournal as y5,releaseNativeMigrationPreflight as g5,requireNoSupervisedAuthContentSnapshot as v5,runNativeMigration as m5,writeNativeHostAuth as h5}from"@cortexkit/anthropic-auth-core";import{dirname as N5,join as L7,resolve as a9}from"node:path";import{ACCOUNT_FILE_NAME as P7,ACCOUNT_STATE_FILE_NAME as L5,canonicalPath as C7,getStickyRoutingStatePath as P5,resolveLocalRoutingDestination as C5,resolveNativePoolPaths as O5}from"@cortexkit/anthropic-auth-core";async function C0($,Z){let J=$==="pi"?_7(Z):O7(Z),z=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),X=a9(z||L7(J,P7)),G=a9(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(X.endsWith(P7)?L7(N5(X),L5):`${X}.state.json`)),Q=await O5(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"?I7(Z):A7(Z),routingSourcePath:a9(W||P5(X)),routingDestinationPath:C5($,Q,Z)}}async function R7($){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 C7(G);if(z.has(Q)&&!(X===9&&Q===await C7(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 A5}from"node:util";var S7=new WeakMap;function T7($){return typeof $==="object"&&$!==null?S7.get($):void 0}function O1($){if(!$||typeof $!=="object"||A5.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 r extends Error{constructor($){super($);this.name="SetupRefusal",S7.set(this,$)}}var n9="OpenCode's separate Anthropic login is not used. Add that account through /claude Accounts if needed, or remove the separate login from OpenCode.";function f7($){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 i9($,Z){let J=[];for(let z of $)if(await b7(z,Z)!=="local")J.push(f7(z));if(J.length)throw new r(J.join(`
|
|
13
|
-
`))}function o0($,Z){return async()=>{
|
|
2
|
+
import{C as w3}from"./index-gqxrgdvk.js";import{E as a4,F as s4,G as I7,H as R7,I as S7,J as T7,K as n4}from"./index-427t44z7.js";import{ma as f4,na as vJ,oa as r3}from"./index-dpxaxyck.js";var P$=vJ((GF,k4)=>{var L$={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"},mJ={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},wJ={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?L$.up():"");if($)Z+=L$.left;return Z}};k4.exports={cursor:L$,scroll:mJ,erase:wJ,beep:"\x07"}});import{stdin as Tz,stdout as kz}from"node:process";import{createInterface as Ez}from"node:readline/promises";import{authorize as bz,createNativeAccountRuntime as fz,decideOpenCodeStateLayoutOnce as xz,exchange as yz,formatNativeAccountState as gz,generateRelayToken as vz,getAccountStoragePath as mz,isValidApiBaseURL as wz,readNativeEnrollmentMode as hz,resolveNativePoolPaths as uz,WORKER_SCRIPT as cz}from"@cortexkit/anthropic-auth-core";import{randomUUID as e5}from"node:crypto";import{constants as A3}from"node:fs";import{lstat as $Z,mkdir as ZZ,open as JZ}from"node:fs/promises";import{homedir as zZ}from"node:os";import{isAbsolute as XZ,join as l7}from"node:path";import{types as G$}from"node:util";import{anthropicAuthStateRoot as GZ,createProviderErrorRedactor as a7,createWindowsOwnerOnly as QZ,ensureWindowsOwnerOnlyDirectory as WZ,formatLogLine as YZ,HOLDER_REGISTRATION_ERROR_MESSAGES as HZ,isOwnerOnly as UZ,isSecretKey as KZ,isStateLayoutRefusalCode as qZ,NativeMigrationError as FZ,NativePiAuthSlotError as BZ,PRIVATE_FILES_UNAVAILABLE_MESSAGE as s7,RELOCATED_MESSAGE as VZ,STATE_LAYOUT_REFUSAL_CODES as MZ,STATE_LAYOUT_REFUSAL_PUBLIC_MESSAGES as jZ,setupEnrollment as DZ,stateLayoutRefusalPublicMessage as NZ}from"@cortexkit/anthropic-auth-core";import{readFile as c5}from"node:fs/promises";import{assertHostsStopped as p5,createNativeAccountRuntime as d5,discoverNativeVaultInventory as l5,inspectNativeHostAuthEntry as e9,NativePiAuthSlotError as a5,nativePiAuthSlotPaths as s5,openNativePiAuthSlot as Z$,readNativeEnrollmentMode as n5,requireNoSupervisedAuthContentSnapshot as i5}from"@cortexkit/anthropic-auth-core";import{dirname as j5}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as D5,CLAUSTRUM_PI_ENROLLMENT_NAME as N5,getHostClaustrumEnrollmentPaths as P7,resolveClaustrumConnectionPath as L5}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as GY}from"@cortexkit/claustrum-client";import{ClaustrumClient as vW}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as $8}from"@cortexkit/claustrum-client";import{SocketClosedError as Z8,SocketTimeoutError as J8,SubcCallError as z8}from"@cortexkit/subc-client";class A 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",route_busy:"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 u extends A{reason;constructor($){super("unavailable","Claustrum scoped operation unavailable");if(this.name="ClaustrumUnreachableError",$==="host-accessor-missing"||$==="host-accessor-failed")this.reason=$}}function J0($){if($ instanceof u||$ instanceof Z8||$ instanceof J8)return"unreachable";let Z=$ instanceof $8||$ instanceof z8?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(a3,Z))return"answered";return a3[Z]}import{resolve as x$}from"node:path";import{storeIdentity as WX}from"@cortexkit/claustrum-client";import{SubcClient as HX}from"@cortexkit/subc-client";var J1=300000,Z3=300000,s3=1000;class f1{#$;#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 J3{#$;#Z;#z;#Y=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#z}request(){if(this.#z)return this.#Y=!0,this.#z;return this.#z=(async()=>{do{this.#Y=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#Y)})().finally(()=>{this.#z=void 0}),this.#z}}class z3{#$;#Z=new f1;#z;#Y="polling";#G;#Q;#X=!1;#J;#H=!1;#W=0;constructor($){this.#$=$,this.#z=new J3(async()=>{let Z=this.#H;if(this.#H=!1,Z||this.#J!==this.#$.view())await this.#$.discover(this.#J??"")},(Z)=>{if(!this.#X)this.#$.onError?.(Z)})}get mode(){return this.#Y}start(){if(this.#X||this.#G||this.#Q)return;if(typeof this.#$.client.watchScoped!=="function"){this.#q("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()}#q($,Z){if(this.#Y===$)return;this.#Y=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#F($,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.#H=$;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.#q("watching","accepted");if(!this.#Z.continuous(Q))this.#H=!0;this.#J=Q.view,this.#z.request()},{enrollmentToken:Z})}catch(Q){this.#$.onError?.(Q),this.#j("watch-failed");return}z={handle:X,notices:0},this.#G=z,this.#q("polling",$?"resubscribing":"opening");let G=z;X.closed.then((Q)=>this.#K(G,Q),(Q)=>this.#K(G,{kind:"transport_lost",error:Q}))}#K($,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.#q("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.#W=0;let z=Math.min(1000*2**Math.min(this.#W,16),300000);this.#W++,this.#q("polling","resubscribing"),this.#F(z,()=>void this.#V(!0));return}this.#j(Z.kind)}#j($){this.#q("fallback",$),this.#F(300000,()=>void this.#V(!1))}}var G3=60000,y$=4*G3,X8=2*G3,n3=new Map,X3=new Map;function z1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function G8($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!z1(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 Q8($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class g${transport;key;#$=[];#Z=!1;#z=new Set;#Y=new Map;#G=new J3(async()=>{try{let $=await this.transport.getUsage();if(!z1($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>z1(Z)&&typeof Z.provider==="string"),this.#Z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#z=new Set(this.#Z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#z)this.#Y.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#z.clear()}},()=>{});#Q=new f1;#X="polling";#J=0;#H=0;#W=new Map;#q;#F;#V={};#K=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 X3)if($-z>=G3)X3.delete(J);let Z=X3.get(this.key);if(Z!==void 0&&$-Z<G3)return Promise.resolve();return X3.set(this.key,$),this.#G.request()}watchMode(){return this.#X}watch($={}){this.#J++;let Z=$.provider;if(Z===void 0)this.#H++;else this.#W.set(Z,(this.#W.get(Z)??0)+1);if(this.#J===1)this.#V=$,this.#O();let J=!1;return()=>{if(J)return;if(J=!0,Z===void 0)this.#H--;else{let z=(this.#W.get(Z)??1)-1;if(z>0)this.#W.set(Z,z);else this.#W.delete(Z)}if(--this.#J===0)this.#j()}}#j(){if(this.#F)(this.#V.clearTimeoutImpl??clearTimeout)(this.#F);this.#F=void 0;let $=this.#q;this.#q=void 0,$?.handle?.stop(),this.#X="polling"}#B($){this.#F=(this.#V.setTimeoutImpl??setTimeout)(()=>{if(this.#F=void 0,this.#J>0&&!this.#q)this.#O()},$),this.#F.unref?.()}#O(){let $=this.transport.watchUsage;if(!$){this.#X="fallback";return}this.#X="polling",this.#Q.restart();let Z={notices:0};this.#q=Z;let J;try{J=$.call(this.transport,(z)=>this.#A(Z,z))}catch(z){this.#I(Z,z);return}Z.handle=J,J.closed.then(()=>this.#I(Z,void 0),(z)=>this.#I(Z,z))}#A($,Z){if(this.#q!==$)return;if($.notices++,$.notices===1)this.#X="watching";if($.notices===2)this.#K=0;let J=G8(Z);if(!J)this.#Q.restart();if(!(J?this.#Q.continuous(J):!1)||J?.provider===void 0||this.#H>0||this.#W.has(J.provider))this.#G.request()}#I($,Z){if(this.#q!==$)return;this.#q=void 0;let J=Q8(Z);if(J==="unknown_method"||J==="usage_watch_limit"){this.#X="fallback";return}if($.notices>0){let z=Math.min(s3*2**Math.min(this.#K,16),Z3);this.#K++,this.#X="polling",this.#B(z);return}if(this.#X="fallback",this.#G.request(),Z===void 0||J0(Z)==="unreachable")this.#B(Z3)}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||!z1(z.usage))continue;let X=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(X)||J-X>=y$)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(!z1(z.usage)||!Number.isFinite(Q))return{miss:"unreachable"};let W={entry:z,context:{fetchedAt:Q,...typeof z.source==="string"&&{source:z.source}}};if(z.stale!==void 0&&(!z1(z.stale)||z.stale.class!=="local_source_unavailable"))return{miss:"upstream-failed",reading:W};return J>=Q+y$||z.stale!==void 0?{miss:"stale",reading:W}:{reading:W}}if(this.#z.has($))return{miss:"absent"};let G=this.#Y.get($)??J;return this.#Y.set($,G),{miss:J-G>=X8?"unreachable":"cold"}}}function i3($,Z){let J=JSON.stringify([x$($.connectionFile),x$(Z)]),z=n3.get(J);if(!z)z={source:new g$($,J),refs:0},n3.set(J,z);z.refs++;let X=!1;return{source:z.source,release(){if(X)return;if(X=!0,--z.refs===0)n3.delete(J)}}}import{ClaustrumCredentialError as cW}from"@cortexkit/claustrum-client";import{appendFileSync as N8,chmodSync as L8,existsSync as e3,renameSync as s$,statSync as P8}from"node:fs";import{open as C8}from"node:fs/promises";import{dirname as O8,resolve as A8}from"node:path";import{randomUUID as h$}from"node:crypto";import{lstat as u$,readFile as c$,rename as W8,unlink as v$}from"node:fs/promises";import{tmpdir as Y8}from"node:os";import{dirname as _0,join as H8,resolve as z0}from"node:path";var _=process.platform==="win32",m$=new Set;function o3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var w$;var p$="native-addon-unavailable";function d$($){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:$}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:p$})}function U8($,Z){return Z instanceof $.PrivateFilesUnavailableError||Z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function K8($){try{await $.verifyPrivatePath(H8(Y8(),`.common-auth-private-files-probe-${h$()}`),"file")}catch(Z){if(U8($,Z))throw d$(Z)}}function X1(){return w$??=import("@cortexkit/private-files").then(async($)=>{if(_)await K8($);return $},($)=>{throw _?d$($):$}),w$}class h 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}: ${$} (${p$}). 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=o3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}function Q3($){return _&&$ instanceof h&&$.reason==="io-error"&&($.win32Code===32||$.win32Code===303)}async function t($,Z,J){try{return await J()}catch(z){if(z instanceof h)throw z;throw new h($,Z,z)}}var q8;async function j0($,Z){$=z0($),Z??=q8,await t($,"safe-parent",async()=>{let J=await(await X1()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await u$($);throw new h(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function s($,Z,J=!1){if($=z0($),Z==="directory")return j0($);await t($,"verify",async()=>{let z=await X1(),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 j0(_0($)),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&&!m$.has($))m$.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function U0($,Z=!1,J){$=z0($),await t($,"directory",async()=>{let z=await X1();try{return await u$($),await j0($,J)}catch(G){if(o3(G)!=="ENOENT")throw G}let X=_0($);if(X===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await U0(X,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(o3(G)!=="EEXIST")throw G}await j0($,J)})}async function Q0($,Z=!1){if(!_)return c$($,"utf8");return(await F8($,Z)).toString("utf8")}async function F8($,Z=!1){if(!_)return c$($);if($=z0($),Z)await j0(_0($)),await s($,"file",!0);return t($,"read",async()=>(await X1()).readOwnerOnly($))}async function G1($,Z){await j0(_0(z0($))),await t($,"create",async()=>{await(await X1()).createPrivateFile(z0($),Z)})}async function l$($){await j0(_0(z0($))),await t($,"directory-create",async()=>{await(await X1()).createOwnerOnly(z0($),{kind:"dir"})})}async function t3($,Z,J={}){$=z0($),Z=z0(Z);let z=J.now??(()=>performance.now()),X=z(),G=J.deadline??1/0,Q,W=[0,10,20,40,80,100],Y,H=0;for(let K of W){let F=Math.min(Q??1/0,G);if(z()>=F)break;if(K)await(J.sleep??((N)=>new Promise((P)=>setTimeout(P,N))))(Math.min(K,Math.max(0,F-z())));if(z()>=F)break;let B=z();if(await J.beforeRename?.(),Q!==void 0)Q+=z()-B;if(z()>=G)break;H++;try{return await(J.rename??W8)($,Z),{attempts:H,elapsedMs:z()-X}}catch(N){Y??=N;let P=N;if(!(P.win32Code!==void 0?P.win32Code===32||P.win32Code===33:["EBUSY","EPERM","EACCES"].includes(P.code??"")&&!P.reason))break;Q??=z()+500}}let U=new h(Z,"rename",Y??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw U.attempts=H,U.elapsedMs=z()-X,U}async function Q1($,Z,J={}){$=z0($),await U0(_0($));try{await s($,"file",!0)}catch(H){if(H.code!=="ENOENT")throw H}let z=z0(J.stagePath??`${$}.${h$()}.tmp`);if(_0(z)!==_0($))throw new h($,"stage-directory",{code:"EXDEV"});let X=!1,G=!1,Q={attempts:0,elapsedMs:0},W="stage-create",Y=(H)=>{try{J.onOutcome?.({path:$,stage:H?.stage??"published",published:G,fileDurable:G,durabilityConfirmed:!1,attempts:H?.attempts??Q.attempts,elapsedMs:H?.elapsedMs??Q.elapsedMs,...H&&{code:H.code,win32Code:H.win32Code}})}catch{}};try{if(await G1(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 s($,"file"),J.durable&&J.durability!=="file-only-on-windows")throw new h($,"directory-sync-unsupported",{code:"ENOTSUP"});Y()}catch(H){let U=H instanceof h?H:new h($,W,H);if(U.published=G,U.fileDurable=G,G)Object.assign(U,Q);if(X){try{await v$(z)}catch{U.orphanPath=z}X=!1}throw Y(U),U}finally{if(X)await v$(z).catch(()=>{})}}var B8=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,V8=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function M8($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function W1($={}){let Z=[V8,...$.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 B8.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 H of["code","status","cause"])if(Q[H]!==void 0)W.push([H,Q[H]]);let Y=new Set(W.map(([H])=>H));for(let H of Object.entries(G))if(!Y.has(H[0]))W.push(H);return W}function X(G,Q,W,Y=0){if(typeof G==="string")return Z.reduce((H,U)=>H.replace(U,"***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,Y));let H=M8(G);if(H&&Y>=8)return"[Truncated]";let U=H?Y+1:Y;return Object.fromEntries((H?z(G):Object.entries(G)).map(([K,F])=>[K,Q&&J(K)?"***REDACTED***":X(F,Q,W,U)]))}finally{W.delete(G)}}return{redact:(G)=>X(G,!0,new WeakSet),redactStrings:(G)=>X(G,!1,new WeakSet)}}var a$=W1(),j8=a$.redact,D8=a$.redactStrings;var W3={error:0,warn:1,info:2,debug:3,trace:4},i$=5242880,o$=3;function $9($){try{L8($,384)}catch{}}function _8($){try{if(!(e3($)&&P8($).size>=i$))return;for(let J=o$-1;J>=1;J--)if(e3(`${$}.${J}`)){let z=`${$}.${J+1}`;s$(`${$}.${J}`,z),$9(z)}let Z=`${$}.1`;s$($,Z),$9(Z)}catch{}}async function D0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await t(Z,"log-close",()=>J.close())}async function n$($,Z){await U0(O8(Z));try{await s(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await G1(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await s(Z,"file",!0)}}return $.handle=await t(Z,"log-open",()=>C8(Z,"a")),$.file=Z,$.handle}async function I8($,Z,J){Z=A8(Z);try{if($.file!==Z)await D0($);let z=$.handle??await n$($,Z);if((await t(Z,"log-stat",()=>z.stat())).size>=i$){await D0($);for(let G=o$-1;G>=0;G--){let Q=G===0?Z:`${Z}.${G}`,W=`${Z}.${G+1}`;try{await s(Q,"file",!0)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}try{await s(W,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}await t3(Q,W),await s(W,"file")}z=await n$($,Z)}await t(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await D0($).catch(()=>{}),z}}function R8($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function S8($){let Z,J,z,X=W1(),G,Q=[],W,Y=Promise.resolve(),H,U={};function K(M){let q=Y.then(M);return Y=q.catch((D)=>{H=D}),q}function F(M){if(_&&M.file!==Z)K(()=>D0(U)).catch(()=>{});Z=M.file,J=M.level,X=W1(M),G=M.captureSink}function B(M){if(M===void 0||M in W3)z=M}function N(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function P(){if(z)return z;let M=typeof J==="function"?J():J;if(M&&M in W3)return M;return"info"}function C(M=!0){if(W)clearTimeout(W),W=void 0;if(!Q.length){if(_)return K(async()=>{if(M)await D0(U);if(H)throw H});return}let q;try{q=N()}catch{if(Q=[],_&&M)return K(()=>D0(U));return}let D=Q.join("");if(Q=[],!q){if(_&&M)return K(()=>D0(U));return}if(_)return K(async()=>{try{await I8(U,q,D)}finally{if(M)await D0(U)}});try{if(_8(q),e3(q))$9(q);N8(q,D,{encoding:"utf8",mode:384})}catch{}}function I(){if(!W)W=setTimeout(()=>{W=void 0;let M=C(!1);if(M instanceof Promise)M.catch(()=>{})},500)}function T(M,q,D,O){if(Z===void 0&&G===void 0)return;try{if(W3[q]>W3[P()])return;let v=X.redactStrings(D),E;try{E=X.redact(O)}catch{E="[unserializable]"}let x=`[${new Date().toISOString()}] ${q.toUpperCase()} [${M}] ${v}`+(O===void 0?"":R8(E))+`
|
|
3
|
+
`;try{G?.({channel:M,level:q,message:v,data:E})}catch{}if(Z===void 0)return;if(Q.push(x),Q.length>=50){let $0=C(!1);if($0 instanceof Promise)$0.catch(()=>{})}else I()}catch{}}function m(M){return{error:(q,D)=>T(M,"error",q,D),warn:(q,D)=>T(M,"warn",q,D),info:(q,D)=>T(M,"info",q,D),debug:(q,D)=>T(M,"debug",q,D),trace:(q,D)=>T(M,"trace",q,D)}}function c(){if(_)K(()=>D0(U)).catch(()=>{});if(H=void 0,Q=[],W)clearTimeout(W),W=void 0;Z=void 0,J=void 0,z=void 0,X=W1(),G=void 0}if($)F($);return{configure:F,createLogger:m,setLogLevel:B,flushLogs:C,reset:c}}var T8=S8();function X0($){return T8.createLogger($)}function y0($){let Z=new AbortController,J=[],z=!1,X=()=>{if(z)return;z=!0;for(let{source:W,listener:Y}of J)W.removeEventListener("abort",Y);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 Y=()=>G(W.reason);if(J.push({source:W,listener:Y}),W.addEventListener("abort",Y,{once:!0}),W.aborted)G(W.reason)}return{signal:Z.signal,dispose:X}}import{channel as P6}from"node:diagnostics_channel";import{ClaustrumCredentialError as x2}from"@cortexkit/claustrum-client";import{createHash as W6,randomBytes as Y6,randomUUID as H6}from"node:crypto";import{constants as B2}from"node:fs";import{chmod as U6,mkdir as K6,open as N2,readFile as Q9,realpath as q6,rename as F6,stat as L2,unlink as Y9}from"node:fs/promises";import{basename as B6,dirname as u0,extname as CG,isAbsolute as OG,join as V6,resolve as AG}from"node:path";import{ClaustrumCredentialError as P2,ClaustrumClient as IG,writeEnrollmentTokenFile as M6}from"@cortexkit/claustrum-client";import{lstat as k8,stat as E8}from"node:fs/promises";import{resolve as b8}from"node:path";async function f8($,Z){try{let J=await Z($);return J.isFile()?J:void 0}catch(J){return J.code==="ENOENT"?"absent":void 0}}function x8($,Z){if($==="absent"||Z==="absent")return $===Z;return $.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs&&$.ctimeMs===Z.ctimeMs}class g0{#$;#Z=new Map;constructor($={}){this.#$=$.followSymlinks?(Z)=>($.stat??E8)(Z):(Z)=>($.lstat??k8)(Z)}async read($,Z,J){let z=$.map((H)=>b8(H)),X=JSON.stringify(z),G=await Promise.all(z.map((H)=>f8(H,this.#$))),Q=G.every((H)=>H!==void 0)?G:void 0,W=this.#Z.get(X);if(Q&&W&&Q.every((H,U)=>{let K=W.identities[U];return K!==void 0&&x8(H,K)}))return J?.(Q),W.value;this.#Z.delete(X);let Y=await Z(z);if(Q){if(this.#Z.size>=64){let H=this.#Z.keys().next().value;if(H!==void 0)this.#Z.delete(H)}this.#Z.set(X,{identities:Q,value:Y})}return Y}}import{randomUUID as r$}from"node:crypto";import{mkdir as y8,open as t$,rename as g8,rm as v8}from"node:fs/promises";import{dirname as e$}from"node:path";class Y3 extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function Y1($,Z,J={}){await $2($,Z,J)}async function $2($,Z,J,z){if(_)return Q1($,J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
4
|
+
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??r$)()}.tmp`,onRenamed:z,durable:J.durable,durability:J.durability,onOutcome:J.onOutcome});await y8(e$($),{recursive:!0});let X=`${$}.${(J.stageName??r$)()}.tmp`,G,Q=!1;try{if(G=await t$(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 Y3(W)}if(await G.close(),G=void 0,await J.beforeRename?.(),await g8(X,$),Q=!1,z?.(),J.durable){let W=await t$(e$($),"r");try{await W.sync()}catch(Y){throw new Y3(Y)}finally{await W.close()}}}finally{if(await G?.close().catch(()=>{}),Q)await v8(X,{force:!0}).catch(()=>{})}}var m8=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 g1}from"node:crypto";import{link as c8,lstat as R0,mkdir as J2,open as U3,readdir as p8,readFile as z2,rename as X2,rm as K1,stat as y1,unlink as d8}from"node:fs/promises";import{basename as l8,dirname as H3,join as z9}from"node:path";import{resolve as Z2}from"node:path";class x1 extends Error{path;code="ENOENT";constructor($,Z){super(`Lock record disappeared: ${$}`,{cause:Z});this.path=$}}function v0($,Z){return $ instanceof h&&$.reason==="io-error"&&$.win32Code===5&&($.stage==="read"||$.stage==="verify")&&Z.some((J)=>Z2(J)===$.path)}function H1($,Z,J){return $ instanceof h&&$.reason==="io-error"&&$.win32Code===5&&$.stage===J&&Z.some((z)=>Z2(z)===$.path)}async function K0($,Z){try{return await Z()}catch(J){if(!v0(J,[$]))throw J;try{return await Z()}catch(z){if(z.code==="ENOENT")throw new x1($,J);throw J}}}import{join as w8,resolve as h8}from"node:path";function U1($,Z){return`${$}.${Z}.lock`}class I0 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class N0 extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}function u8($,Z,J){let z=h8(U1(Z,J)),X=[z,w8(z,"owner.json")];return(Q3($)||v0($,X))&&($.stage==="read"||$.stage==="verify")&&X.includes($.path)||_&&(H1($,[z],"create")||H1($,[`${z}.evicting`],"directory-create"))}async function Z9($,Z,J){let z=performance.now(),X;for(;;){Z.signal?.throwIfAborted();let G;try{G=await L0({path:$,name:Z.name,ttlMs:Z.ttlMs,renew:Z.renew??!1,...Z.onStep?{onStep:Z.onStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}}),X=void 0}catch(W){if(!u8(W,$,Z.name))throw W;G=null,X??=W}if(G)try{return Z.signal?.throwIfAborted(),await J(G)}finally{await G.release(Z.signal)}let Q=Z.timeoutMs-(performance.now()-z);if(Q<=0){if(X)throw X;throw new I0({target:$,name:Z.name,timeoutMs:Z.timeoutMs})}await new Promise((W)=>setTimeout(W,Math.min(25,Math.ceil(Q))))}}var q1;async function a8($,Z){let J=`${$}.${g1()}.tmp`,z;try{z=await U3(J,"wx",384);try{if(q1?.beforeWrite)await q1.beforeWrite(J);await z.writeFile(Z,"utf8")}finally{await z.close()}try{if(q1?.beforeLink)await q1.beforeLink(J,$);await c8(J,$)}catch(X){let G=X.code;if(G!=="EPERM"&&G!=="ENOTSUP"&&G!=="EOPNOTSUPP"&&G!=="EXDEV")throw X;await H2($,Z)}}finally{if(z)await K1(J,{force:!0}).catch(()=>{})}}async function H2($,Z){let J=await U3($,"wx",384),z;try{z=await J.stat()}catch{z=void 0}try{if(q1?.beforeWrite)await q1.beforeWrite($);await J.writeFile(Z,"utf8")}catch(X){try{let G=await R0($).catch(()=>{return});if(z&&G&&G.dev===z.dev&&G.ino===z.ino)await K1($,{force:!0}).catch(()=>{})}catch{}throw X}finally{await J.close()}}var U2=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,s8=600000,n8=256,i8=4096,G2=new Set,Q2=new Set,o8;function r8($,Z){let J=`${Z}.`,z=".tmp";if(!$.startsWith(J)||!$.endsWith(".tmp"))return!1;return U2.test($.slice(J.length,-4))}function K2($,Z){return $.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs&&$.birthtimeMs===Z.birthtimeMs}async function W2($){let Z=await R0($);if(!Z.isFile()||Z.isSymbolicLink())return;if(Z.size>i8)return;let J=await U3($,"r"),z;try{if(!K2(Z,await J.stat()))return;z=await J.readFile("utf8")}finally{await J.close()}let X;try{X=JSON.parse(z)}catch{return}if(!X||typeof X!=="object"||Array.isArray(X))return;let G=Object.keys(X).sort();if(G.length!==2||G[0]!=="expiresAt"||G[1]!=="ownerId")return;let{ownerId:Q,expiresAt:W}=X;if(typeof Q!=="string"||!U2.test(Q))return;if(typeof W!=="number"||!Number.isFinite(W))return;return{identity:Z,expiresAt:W}}async function t8($,Z,J){let z=H3($),X=l8($),G=o8,W=(await(G?.readdir??p8)(z)).filter((H)=>r8(H,X)).slice(0,n8),Y=Math.max(Number.isFinite(Z)?Z:0,s8);for(let H of W){let U=z9(z,H);try{if(J()-(await R0(U)).mtimeMs<Y)continue;let K=await W2(U);if(!K||!(K.expiresAt<J()-Y))continue;if(G?.beforeUnlink)await G.beforeUnlink(U);let F=await W2(U);if(!F||!K2(K.identity,F.identity)||!(F.expiresAt<J()-Y))continue;await(G?.unlink??d8)(U)}catch{}}}function e8($,Z,J){if(G2.has($))return;G2.add($);let z=Promise.resolve().then(()=>t8($,Z,J)).catch(()=>{});Q2.add(z),z.finally(()=>Q2.delete(z))}var $6=globalThis.setTimeout.bind(globalThis),Z6=globalThis.clearTimeout.bind(globalThis);function q2($){let Z=$?.code;return Z==="ENOENT"||!_&&(Z==="EINVAL"||Z==="ENOTDIR")}var Y2;function J9($,Z){if($.dev!==Z.dev||$.ino!==Z.ino)return!1;if($.ino===0&&$.birthtimeMs!==Z.birthtimeMs)return!1;return!0}var J6=1000;function L0($){return z6({...$,now:Date.now})}async function z6($){let Z=U1($.path,$.name),J=z9(Z,"owner.json"),z=g1(),X=$.now??Date.now,G=null,Q=!1,W=!1,Y,H,U=new Promise((V)=>{H=V});function K(V){try{let j=$.onRenewalTimer?.(V);if(j&&(typeof j==="object"||typeof j==="function")&&"then"in j&&typeof j.then==="function")Promise.resolve(j).catch(()=>{})}catch{}}function F(){if(!G)return;Z6(G),G=null,K("cancelled")}function B(V,j){if(Y||Q)return;Y=Object.freeze({reason:V,expectedOwnerId:z,...typeof j?.ownerId==="string"?{observedOwnerId:j.ownerId}:{},...typeof j?.expiresAt==="number"?{observedExpiresAt:j.expiresAt}:{}}),F(),H(Y)}let N,P=null,C=`${Z}.evicting`,I=z9(C,"owner.json"),T=g1(),m=5000,c=8;function M(V){return _&&(H1(V,[Z],"create")||H1(V,[C],"directory-create"))}async function q(){if(_)try{return JSON.parse(await K0(Z,()=>Q0(Z,!0)))}catch(V){if(V.code!=="EISDIR"&&V.reason!=="wrong-kind")throw V;return await K0(Z,()=>s(Z,"directory",!0)),JSON.parse(await K0(J,()=>Q0(J,!0)))}try{return JSON.parse(await z2(Z,"utf8"))}catch(V){if(V.code!=="EISDIR")throw V;return JSON.parse(await z2(J,"utf8"))}}async function D(){if(_){let R=await q(),S=Number(R?.expiresAt)-X();await Q1(Z,`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
6
|
+
`,{deadline:performance.now()+Math.max(0,S),beforeRename:async()=>{let l=await q();if(l?.ownerId!==z||!(Number(l?.expiresAt)>X())||!await w())throw new N0({target:$.path,name:$.name})}});return}let V=`${Z}.${g1()}.tmp`,j,L=!1;try{j=await U3(V,"wx",384),L=!0,await j.writeFile(`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
7
|
+
`,"utf8"),await j.chmod(384),await j.close(),j=void 0;let R=await q();if(R?.ownerId!==z||!(Number(R?.expiresAt)>X())||!await w())throw new N0({target:$.path,name:$.name});await X2(V,Z),L=!1}finally{if(await j?.close().catch(()=>{}),L)await K1(V,{force:!0}).catch(()=>{})}}async function O(){let V=`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
8
|
+
`;if(_)await G1(Z,V);else await a8(Z,V)}async function v(V){let j=V.code;if(j!=="EEXIST"&&j!=="EISDIR")return!1;if(_){if($.onStep)await $.onStep("lease-contention-read-ready");try{if(j==="EISDIR")await K0(Z,()=>s(Z,"directory",!0)),await K0(J,()=>Q0(J,!0));else await q()}catch(L){if(L.code!=="ENOENT")throw L}}return!0}async function E(){if(_)await U0(H3(Z));try{return await O(),!0}catch(V){let j=V.code;if(await v(V))return!1;if(j==="ENOENT"){if(_)await U0(H3(Z));else await J2(H3(Z),{recursive:!0});try{return await O(),!0}catch(L){if(await v(L))return!1;throw L}}throw V}}async function x(){await new Promise((V)=>setTimeout(V,Math.floor(Math.random()*4)))}async function $0(V=!0){if(V&&$.onStep)await $.onStep("lock-read-ready");let j;try{j=await q()}catch(R){if(R instanceof x1)return{status:"missing"};if(_&&R.code!=="ENOENT")throw R}let L=Number(j?.expiresAt);if(Number.isFinite(L)&&L>X())return{status:"live"};if(typeof j?.ownerId==="string"&&Number.isFinite(L))return{status:"stale",identity:{kind:"owner",ownerId:j.ownerId,expiresAt:L}};try{let R=await y1(Z),S=Number.isFinite(L)?L:R.mtimeMs+$.ttlMs;if(S>X())return{status:"live"};return{status:"stale",identity:{kind:"stat",dev:R.dev,ino:R.ino,mtimeMs:R.mtimeMs,expiresAt:S}}}catch(R){if(R.code==="ENOENT"){if($.onStep)await $.onStep("lock-missing");return{status:"missing"}}throw R}}function $1(V,j){if(j.status!=="stale")return!1;let L=j.identity;if(V.kind==="owner"&&L.kind==="owner")return V.ownerId===L.ownerId&&V.expiresAt===L.expiresAt;return V.kind==="stat"&&L.kind==="stat"&&V.dev===L.dev&&V.ino===L.ino&&V.mtimeMs===L.mtimeMs&&V.expiresAt===L.expiresAt}async function w(){try{return JSON.parse(await K0(I,()=>Q0(I,_)))?.ownerId===T}catch(V){if(_&&V.code!=="ENOENT")throw V;return!1}}async function i(V){if(_)await t(V,"remove",()=>K1(V,{recursive:!0,force:!0}));else await K1(V,{recursive:!0,force:!0}).catch(()=>{})}function Z0(V,j){if(!_||!(V instanceof h)||V.stage!=="remove"||V.path!==j)return!1;return Q3(V)||V.win32Code===void 0&&V.reason===void 0&&(V.code==="EBUSY"||V.code==="EPERM")}async function E1(V,j,L=performance.now()+m+1000){let R,S=5;while(await j()){try{await i(V);return}catch(d){if(!Z0(d,V))throw d;R??=d}let l=L-performance.now();if(l<=0)throw R;if(await new Promise((d)=>setTimeout(d,Math.min(S,l))),performance.now()>=L)throw R;S=Math.min(S*2,50)}}async function x0(V){let j;await E1(C,async()=>{if(!_)return w();let L=await R0(C).catch((R)=>{if(R.code!=="ENOENT")throw R;return});if(!L||j&&!J9(j,L))return!1;if(await w())return j=L,!0;if(!j)return!1;try{return await y1(I),!1}catch(R){if(R.code!=="ENOENT")throw R;return!0}},V)}async function l3(V,j){if(!V)return!1;let L=!1;try{await E1(C,async()=>{L=!1;let R=await R0(C).catch(()=>{return});if(!R||!J9(V,R))return!1;L=!0;try{return await y1(I),!1}catch(S){return S.code==="ENOENT"}},j)}catch{}return L}async function Z1(V){if(_)await l$(C);else await J2(C);let j;try{let L=await R0(C);j={dev:L.dev,ino:L.ino,birthtimeMs:L.birthtimeMs}}catch{j=void 0}try{await Y2?.beforeOwnerWrite?.(C,I);let L=await Y2?.failOwnerWrite?.(C,I);if(L!==void 0)throw L;let R=`${JSON.stringify({ownerId:T,createdAt:X()})}
|
|
9
|
+
`;if(_)await G1(I,R);else await H2(I,R)}catch(L){let R=await l3(j,V);if(q2(L)&&!R)return!1;try{await x0(V)}catch{}throw L}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function b(V){let j;try{j=await y1(C)}catch(S){if(S.code==="ENOENT")return"missing";throw S}if(_)try{await K0(C,()=>s(C,"directory",!0))}catch(S){if(S.code==="ENOENT")return"missing";throw S}if(j.mtimeMs+m>X()){let S=!0;try{await y1(I)}catch(l){if(l.code==="ENOENT")S=!1;else return"fresh"}if(S)return"fresh";if(j.mtimeMs+J6>X())return"fresh"}if($.onStep)await $.onStep("stale-marker-stat");let L=`${C}.${g1()}`;try{await X2(C,L)}catch(S){if(S.code==="ENOENT")return"missing";throw S}if($.onStep)await $.onStep("stale-marker-claimed");let R=_?await R0(L):void 0;return await E1(L,async()=>{if(!R)return!0;let S=await R0(L).catch((l)=>{if(l.code!=="ENOENT")throw l;return});return!!S&&J9(R,S)},V),"recovered"}async function M0(V,j){try{if(!await Z1(j))return!1}catch(S){if(S.code==="EEXIST"){if(_)try{await K0(C,()=>s(C,"directory",!0)),await K0(I,()=>Q0(I,!0))}catch(l){if(l.code!=="ENOENT")throw l}return!1}throw S}let L=!1,R;try{await V()}catch(S){L=!0,R=S}try{await x0(j)}catch(S){if((Z0(R,Z)||v0(R,[Z,J,I]))&&(Z0(S,C)||v0(S,[I])))throw R;throw S}if(L)throw R;return!0}async function T$(){for(let V=0;V<c;V++){if($.onStep)await $.onStep("relinquish-read");let j;try{j=await q()}catch(L){if(_&&!(L instanceof x1))throw L;return}if(j?.ownerId!==z)return;try{await K1(Z,{recursive:!0,force:!0});return}catch(L){if(_)throw L;await x()}}}function k$(){if(!$.renew||Q||Y)return;let V=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=$6(()=>{G=null;let j=(async()=>{let L=!Q;try{if(!await M0(async()=>{let S=await q(),l=X();if(Q||Y){L=!1;return}if(S?.ownerId!==z){B("taken-over",S),L=!1;return}if(!(Number(S?.expiresAt)>l)){B("expired",S),L=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(Q||Y){L=!1;return}if(!await w())return;if($.onStep)await $.onStep("renewal-write-fenced");if(Q||Y){L=!1;return}if(!await w())return;if($.onStep)await $.onStep("renewal-write-ready");if(Q||Y){L=!1;return}if(await D(),$.onStep)await $.onStep("renewal-write-finished");if(!await w()){B("marker-lost"),L=!1,await T$();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(R){if(_&&R instanceof h&&!M(R))N=R,B("renewal-failed"),L=!1;try{let S=await q();if(S?.ownerId!==z)B("taken-over",S);else if(!(Number(S?.expiresAt)>X()))B("expired",S)}catch{B("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(L&&!Q&&!Y)k$()}})();P=j,j.finally(()=>{if(P===j)P=null})},V),"unref"in G)G.unref();K("scheduled")}function E$(){try{let V=$.onContended?.();if(V&&(typeof V==="object"||typeof V==="function")&&"then"in V&&typeof V.then==="function")Promise.resolve(V).catch(()=>{})}catch{}return null}let A0=!1,$3;try{A0=await E()}catch(V){if(!M(V))throw V;$3=V}if(!A0)for(let V=0;V<c;V++)try{if(A0=await E(),A0)break;let j=await $0();if(j.status==="live")return E$();if(j.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await Z1()){await x();continue}}catch(L){if(L.code!=="EEXIST")throw L;if(await b()==="fresh")return null;await x();continue}try{let L=await $0();if(L.status==="live")return E$();if(!$1(j.identity,L))continue;if(!await w())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await w())return null;let R=await $0(!1);if(!$1(j.identity,R))continue;if(await i(Z),!await w())return null;if($.onStep)await $.onStep("stale-lock-removed");if(A0=await E(),!A0)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await w())return await T$(),A0=!1,null;break}finally{await x0()}}catch(j){if(!M(j))throw j;$3??=j,await x()}if(!A0){if($3)throw $3;return null}return k$(),e8(Z,$.ttlMs,X),{ownerId:z,whenLost:()=>U,hasLost:()=>Y!==void 0,assertOwned:async()=>{if(N)throw N;let V;try{let j=await q();if(V=j,!Q&&!Y&&j?.ownerId===z&&Number(j?.expiresAt)>X())return;B(j?.ownerId!==z?"taken-over":"expired",j)}catch(j){if(B("unreadable"),_&&j instanceof h)throw j}throw new N0({target:$.path,name:$.name,expectedOwnerId:z,...typeof V?.ownerId==="string"?{observedOwnerId:V.ownerId}:{},...typeof V?.expiresAt==="number"?{observedExpiresAt:V.expiresAt}:{}})},release:async(V)=>{if(_&&W)return;Q=!0,F(),await P;let j=performance.now()+m+1000,L=5,R,S;for(;;){try{let d=!1,b1=await M0(async()=>{let b$;try{b$=await q()}catch(f$){if(_&&f$.code==="ENOENT"){d=!0;return}throw f$}if(b$?.ownerId!==z){d=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await w())return;await i(Z),d=!0},j);if(S=void 0,b1&&d){W=!0;return}if(!b1){if(V?.aborted)return;await b(j)}}catch(d){let b1=_&&(M(d)||v0(d,[Z,J,C,I]));if(!Z0(d,Z)&&!b1){if(_)throw d;return}if(b1)S??=d;else R??=d}let l=j-performance.now();if(l<=0)break;if(await new Promise((d)=>setTimeout(d,Math.min(L,l))),_&&performance.now()>=j)break;L=Math.min(L*2,50)}if(_)throw S??R??new h(Z,"release-not-confirmed",{code:"ETIMEDOUT"});X0("fs").warn("File lock release deadline expired",{lockPath:Z})}}}import{ClaustrumCredentialError as X6}from"@cortexkit/claustrum-client";var F2=new WeakSet;function X9($){return F2.has($)}function p(){return process.env.CORTEXKIT_VAULT_HOST==="thalamus"}function G9($){if(typeof $!=="object"||$===null)return $;let Z=$;if(typeof Z.code==="string"&&(Z.class==="transient"||Z.class==="permanent"||Z.class==="auth_required"||Z.class==="context_overflow")&&(Z.action==="gone"||Z.action==="reauth"||Z.action==="retry"||Z.action==="reduce_and_retry"))return new X6(Z.code,Z.class,Z.action);if(Z.name==="ClaustrumUnreachableError"||typeof Z.code==="string"&&J0(Object.assign(Error(),{code:Z.code}))==="unreachable")return new u(Z.reason==="host-accessor-missing"||Z.reason==="host-accessor-failed"?Z.reason:void 0);return $}function v1($){try{return $()}catch(Z){throw G9(Z)}}async function m0($){try{return await $()}catch(Z){throw G9(Z)}}function G6($){let Z=$.watchScoped?.bind($),J=$.reportUsageScoped?.bind($);return{listScoped:(...z)=>m0(()=>$.listScoped(...z)),getScoped:(...z)=>m0(()=>$.getScoped(...z)),reportAuthFailureScoped:(...z)=>m0(()=>$.reportAuthFailureScoped(...z)),close:()=>v1(()=>$.close()),...Z&&{watchScoped:(...z)=>{let X=v1(()=>Z(...z));return{stop:()=>v1(()=>X.stop()),closed:m0(async()=>{let G=await X.closed;return G.kind==="refused"||G.kind==="transport_lost"?{...G,error:G9(G.error)}:G})}}},...J&&{reportUsageScoped:(...z)=>m0(()=>J(...z))},...$.insula&&{insula:Q6($.insula)}}}function Q6($){let Z=$.watchUsage?.bind($);return{connectionFile:$.connectionFile,getUsage:()=>m0(()=>$.getUsage()),...Z&&{watchUsage:(...J)=>{let z=v1(()=>Z(...J));return{stop:()=>v1(()=>z.stop()),closed:m0(()=>z.closed)}}}}}function w0($){if(!p()||!$)throw new u;try{let Z=globalThis[Symbol.for("cortexkit.vault")];if(typeof Z==="function"){let J=G6(Z($));return F2.add(J),J}}catch{throw new u("host-accessor-failed")}throw new u("host-accessor-missing")}var j6=1,q3=16384,C2=30000,H9=/^[0-9a-f]{64}$/,O2="unknown_method",A2=new Set([O2,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),_2=new Set(["pending_queue_full"]);function W9($){if(!($ instanceof P2))return;if(A2.has($.code))return{code:$.code,disposition:"terminal"};if(_2.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function I2($){let Z=Array.from($).length;return Z>=1&&Z<=40&&!/[\p{Cc}\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069\u200b-\u200d\u2060\ufeff]/u.test($)}function U9($){return Array.isArray($)&&$.length>=1&&$.length<=4&&Array.from($).every((Z)=>{if(!F3(Z)||Object.keys(Z).length!==2||Z.operation!=="read"&&Z.operation!=="list"||!F3(Z.selector))return!1;let J=Object.keys(Z.selector),z=J[0];return J.length===1&&(z==="category"||z==="exact")&&typeof Z.selector[z]==="string"&&Z.selector[z].trim().length>0})}function P0($){return{...$.requestedGrants!==void 0&&{requestedGrants:$.requestedGrants},...$.requestedGrantsStatus!==void 0&&{requestedGrantsStatus:$.requestedGrantsStatus}}}function F3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function K3($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function R2($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function m1(){return new A("invalid-state","invalid Claustrum enrollment state")}function K9($){if(!F3($)||$.version!==j6||typeof $.proposedName!=="string"||$.proposedName.length===0)throw m1();if($.phase==="pending"){let Z=V2($);if(!H9.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!K3($.createdAt)||!K3($.updatedAt))throw m1();return{version:1,phase:"pending",proposedName:$.proposedName,requestSecret:$.requestSecret,...$.requestId!==void 0&&{requestId:$.requestId},createdAt:$.createdAt,updatedAt:$.updatedAt,...Z}}if($.phase==="approved"){let Z=V2($);if($.approvedName!==void 0&&(typeof $.approvedName!=="string"||$.approvedName.length===0)||!R2($.tokenGeneration)||!K3($.updatedAt))throw m1();return{version:1,phase:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration,updatedAt:$.updatedAt,...Z}}if($.phase==="denied"||$.phase==="blocked"){if($.errorCode!==void 0&&typeof $.errorCode!=="string"||!K3($.updatedAt))throw m1();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw m1()}function V2($){if($.requestedGrants!==void 0&&!U9($.requestedGrants)||$.requestedGrantsStatus!==void 0&&($.requestedGrants===void 0||$.requestedGrantsStatus!=="sent"&&$.requestedGrantsStatus!=="dropped"))return{};return P0($)}function q9($){if(!F3($)||!H9.test(String($.token??""))||!R2($.token_generation))throw new A("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function S2($){if(!$.isFile())throw new A("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new A("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new A("unsafe-file","Claustrum enrollment file must be owned by the current user")}function M2($){try{return JSON.parse($)}catch{throw new A("invalid-state","Claustrum enrollment file is not valid JSON")}}async function c0($){if(_)try{await U0(u0($));let J=await Q0($,!0);if(Buffer.byteLength(J)>q3)throw new A("unsafe-file","Claustrum enrollment file is too large");return M2(J)}catch(J){if(J.code==="ENOENT")return;throw J}let Z;try{Z=await N2($,B2.O_RDONLY|B2.O_NOFOLLOW)}catch(J){if(J.code==="ENOENT")return;throw new A("unsafe-file","Claustrum enrollment file could not be opened safely")}try{S2(await Z.stat());let J=Buffer.alloc(q3+1),{bytesRead:z}=await Z.read(J,0,J.byteLength,0);if(z>q3)throw new A("unsafe-file","Claustrum enrollment file is too large");return M2(J.subarray(0,z).toString("utf8"))}finally{await Z.close()}}function j2($,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 D6($,Z,J){try{let[z,X]=await Promise.all([Q9(J.passwdPath??"/etc/passwd","utf8"),Q9(J.groupPath??"/etc/group","utf8")]),G=j2(z,7),Q=j2(X,4);if(!G||!Q)return!1;let W=G.filter((K)=>Number(K[2])===$),Y=Q.filter((K)=>Number(K[2])===Z);if(W.length!==1||Y.length!==1)return!1;let H=W[0]?.[0],U=Y[0]?.[3]??"";return(U===""||U.split(",").every((K)=>K===H))&&!G.some((K)=>Number(K[2])!==$&&Number(K[3])===Z)}catch{return!1}}function T2($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>Q9(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function k2($,Z={}){if(!_){let J=process.geteuid?.();if(J===void 0)return;let z=process.getegid?.(),X;try{X=await q6($)}catch{return}let G;for(;;){let Q=await L2(X).catch(()=>{return});if(Q&&(Q.mode&18)!==0&&(Q.mode&512)===0){if(G===void 0)G=z!==void 0&&await D6(J,z,Z);if((Q.mode&2)!==0||Q.uid!==J||Q.gid!==z||!G)throw new A("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${X}. Another user could replace it. Run: chmod g-w,o-w ${X}`)}let W=u0(X);if(W===X)return;X=W}}try{await j0($,T2(Z))}catch(J){if(!(J instanceof h))throw J;throw new A("unsafe-file",`Claustrum enrollment parent refused: ${J.path} (${J.reason??J.code}). Use a folder that other users cannot write or replace.`)}}async function F1($,Z={},J="enrollment directory"){if(_){await U0($,!1,T2(Z));return}await K6($,{recursive:!0,mode:448});let z=await L2($),X=process.geteuid?.();if(X!==void 0&&z.uid!==X)throw new A("unsafe-file",`Claustrum ${J} must be owned by the current user`);if((z.mode&63)!==0)await U6($,448)}async function h0($,Z,J={}){let z=u0($);await F1(z,J),await k2(z,J);let X=`${JSON.stringify(Z)}
|
|
11
|
+
`;if(Buffer.byteLength(X)>q3)throw new A("invalid-state","Claustrum enrollment state is too large");if(_)return Q1($,X);let G=V6(z,`.${B6($)}.${process.pid}.${H6()}.tmp`),Q,W=!1;try{Q=await N2(G,"wx",384),W=!0,await Q.writeFile(X,"utf8"),await Q.chmod(384),await Q.sync(),await Q.close(),Q=void 0,await F6(G,$),W=!1}finally{if(await Q?.close().catch(()=>{}),W)await Y9(G).catch(()=>{})}}var N6=new g0;async function B3($,Z){let J=_?await D2($,Z):await N6.read([$.tokenPath,$.statePath],async([X=$.tokenPath,G=$.statePath])=>D2({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 D2($,Z){let J=await c0($.tokenPath),z=J===void 0?void 0:q9(J),X=await c0($.statePath),G=X===void 0?void 0:K9(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,...G&&(G.phase==="approved"||G.phase==="pending")&&P0(G)}};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:S0(G),usesProposedName:!1}}async function T0($){let Z=await c0($);if(Z===void 0)throw new A("not-enrolled","Claustrum enrollment is not configured");return q9(Z)}function S0($){if($.phase==="pending")return{state:"pending",proposedName:$.proposedName,...$.requestId!==void 0&&{requestId:$.requestId},...P0($)};if($.phase==="approved")return{state:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration,...P0($)};if($.phase==="denied")return{state:"denied",proposedName:$.proposedName};return{state:"blocked",proposedName:$.proposedName,code:$.errorCode??"unknown"}}function E2(){return new A("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class F9{#$;#Z;#z;#Y;#G;#Q;#X;#J;#H;constructor($){if($.displayName!==void 0&&!I2($.displayName))throw new A("invalid-state","invalid Claustrum enrollment display name");if($.requestedGrants!==void 0&&!U9($.requestedGrants))throw new A("invalid-state","invalid Claustrum enrollment requested grants");this.#G=$.requestedGrants?.map((Z)=>({selector:{...Z.selector},operation:Z.operation})),this.#H=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#z=$.proposedName,this.#Y=$.displayName,this.#Q=$.now??Date.now,this.#X=$.mintSecret??(()=>Y6(32).toString("hex")),this.#J=$.writeTokenFile??M6}async status(){return B3(this.#Z,this.#z)}async resetTerminal(){return b2(this.#Z,this.#z)}async#W($,Z){let J={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#Q()};return await h0(this.#Z.statePath,J,this.#H),S0(J)}async reconcile(){await F1(u0(this.#Z.statePath),this.#H);let $=await L0({name:"ceremony",path:this.#Z.statePath,ttlMs:C2,renew:!0});if(!$)return{state:"busy"};try{let Z=await c0(this.#Z.tokenPath),J=Z===void 0?void 0:q9(Z),z=await c0(this.#Z.statePath),X=z===void 0?void 0:K9(z);if(X&&X.proposedName!==this.#z)throw E2();if(J){if(!X||X.phase==="pending"){let Q={version:1,phase:"approved",proposedName:X?.proposedName??this.#z,tokenGeneration:J.token_generation,...X&&P0(X),updatedAt:this.#Q()};await h0(this.#Z.statePath,Q,this.#H),X=Q}return{state:"approved",proposedName:X.proposedName,...X.phase==="approved"&&X.approvedName!==void 0&&{approvedName:X.approvedName},tokenGeneration:J.token_generation,...X.phase==="approved"&&P0(X)}}if(X?.phase==="approved"){let Q={version:1,phase:"blocked",proposedName:X.proposedName,errorCode:"missing_token",updatedAt:this.#Q()};return await h0(this.#Z.statePath,Q,this.#H),S0(Q)}if(X&&X.phase!=="pending")return S0(X);if(!X){let Q=this.#Q();if(X={version:1,phase:"pending",proposedName:this.#z,requestSecret:this.#X(),createdAt:Q,updatedAt:Q,...this.#G!==void 0&&{requestedGrants:this.#G}},!H9.test(X.requestSecret))throw new A("invalid-state","invalid minted Claustrum enrollment secret");await h0(this.#Z.statePath,X,this.#H)}if(!X.requestId)try{let Q=W6("sha256").update(Buffer.from(X.requestSecret,"hex")).digest("hex"),W={name:X.proposedName,requestSecretHash:Q},Y,H=X.requestedGrantsStatus;try{if(Y=await this.#$.enrollPropose({...W,...this.#Y!==void 0&&{displayName:this.#Y},...X.requestedGrants!==void 0&&{requestedGrants:X.requestedGrants}}),X.requestedGrants!==void 0)H="sent"}catch(U){if(this.#Y===void 0&&X.requestedGrants===void 0||!(U instanceof P2)||U.code!=="invalid_params")throw U;if(Y=await this.#$.enrollPropose(W),X.requestedGrants!==void 0)H="dropped"}X={...X,requestId:Y.requestId,updatedAt:this.#Q(),...H!==void 0&&{requestedGrantsStatus:H}},await h0(this.#Z.statePath,X,this.#H)}catch(Q){let W=W9(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,retryCode:W.code,...P0(X)};if(W.code===O2)return await $.assertOwned(),await Y9(this.#Z.statePath).catch((Y)=>{if(Y.code!=="ENOENT")throw Y}),{state:"unavailable",proposedName:X.proposedName,code:W.code};return this.#W(X,W.code)}let G=X.requestId;if(!G)return S0(X);try{let Q=await this.#$.enrollPoll({requestId:G,requestSecret:X.requestSecret});if(Q.status==="pending")return S0(X);if(Q.status==="denied"){let Y={version:1,phase:"denied",proposedName:X.proposedName,updatedAt:this.#Q()};return await h0(this.#Z.statePath,Y,this.#H),S0(Y)}await F1(u0(this.#Z.tokenPath),this.#H),await k2(u0(this.#Z.tokenPath),this.#H),await this.#J(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,...P0(X),updatedAt:this.#Q()};return await h0(this.#Z.statePath,W,this.#H),S0(W)}catch(Q){let W=W9(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,requestId:G,retryCode:W.code,...P0(X)};return this.#W(X,W.code)}}finally{await $.release()}}}async function b2($,Z){await F1(u0($.statePath));let J=await L0({name:"ceremony",path:$.statePath,ttlMs:C2,renew:!0});if(!J)return"busy";try{if(await c0($.tokenPath)!==void 0)return"refused-approved";let z=await c0($.statePath);if(z===void 0)return"idle";let X=K9(z);if(X.proposedName!==Z)throw E2();if(X.phase==="pending")return"refused-pending";return await J.assertOwned(),await Y9($.statePath),"reset"}finally{await J.release()}}var B9="claustrum-tombstone:v1:";function B1($,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 V1($,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)}}import{ClaustrumCredentialError as L6}from"@cortexkit/claustrum-client";function f2($){return $!==null&&typeof $==="object"&&(Object.getPrototypeOf($)===Object.prototype||Object.getPrototypeOf($)===null)}class V9{options;#$=new Map;#Z=new Map;#z=new Set;#Y;#G;#Q=!1;#X=!1;#J=0;constructor($){this.options=$}state(){return{pending:this.#$.size,inFlight:this.#G!==void 0,dropped:this.#J}}report($,Z){if(this.#Q||!this.options.client.reportUsageScoped)return;try{if(!this.options.owns($)){this.#J++;return}if(!f2(Z)||"credentialId"in Z||"vouched"in Z)throw Error("invalid reading");let J=JSON.stringify(Z);if(Buffer.byteLength(J,"utf8")>15360)throw Error("oversized reading");let z=JSON.parse(J);if(!f2(z)||"credentialId"in z||"vouched"in z||typeof z.observedAtMs!=="number"||!Number.isFinite(z.observedAtMs))throw Error("invalid reading");if(z.observedAtMs<=(this.#Z.get($)??-1/0)){this.#J++;return}if(this.#$.has($))this.#J++;if(this.#Z.set($,z.observedAtMs),this.#$.set($,z),!this.#Y&&!this.#G)this.#Y=this.options.setTimeout(()=>{this.#Y=void 0,this.#H()},1000),this.#Y.unref?.()}catch{this.#J++}}forget($){if(this.#$.delete($))this.#J++;this.#Z.delete($)}#H(){if(this.#G||!this.#$.size||this.#X)return this.#G;let $=Promise.resolve().then(async()=>{while(!this.#X&&this.#$.size){let Z=this.#$.entries().next().value;if(!Z)break;let[J,z]=Z;this.#$.delete(J);try{let X=await this.options.token();if(this.#X||!this.options.owns(J)){if(!this.#X)this.#J++;continue}await this.options.client.reportUsageScoped?.({credentialId:J,reading:z,enrollmentToken:X})}catch(X){if(!this.#X)this.#J++;this.#W(X)}}});return this.#G=$,$.finally(()=>{this.#G=void 0}),$}#W($){let Z="transport_error";try{if($ instanceof L6)Z=/^[a-z][a-z0-9_]{0,63}$/.test($.code)?$.code:Z;if(this.#z.has(Z))return;this.#z.add(Z),this.options.logger.debug("claustrum usage report dropped",{code:Z})}catch{}}close(){if(this.#Q=!0,this.#Y)this.options.clearTimeout(this.#Y);return this.#Y=void 0,this.#H()}drop(){this.#X=!0,this.#J+=this.#$.size+(this.#G?1:0),this.#G=void 0,this.#$.clear(),this.#Z.clear()}}function g2($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function C6($,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 j9=X0("claustrum");function y2($){if(!/^[0-9a-f]{64}$/.test($.token)||!Number.isSafeInteger($.token_generation)||$.token_generation<1)throw new A("invalid-token","Invalid Claustrum enrollment token");return $.token}var k0=P6("common-auth.claustrum.phases");function N9($,Z,J,z=j9){let X=g2(Z,J);return z.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:J?.recordVersion??null,retry:X,reason:C6(Z,J)}),X}var D9=300000,v2=60000,m2=1e4,w2=60000;function M9(){return new A("invalid-material","Claustrum returned invalid credential material")}function O6($){let Z=$.trim();if(Z.startsWith("{")){let J;try{J=JSON.parse(Z)}catch{throw M9()}if(!J||typeof J!=="object")throw M9();let z=J,X=z.access_token??z.access;Z=typeof X==="string"?X:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(B9))throw M9();return Z}function A6($,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=_6($),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 _6($){let Z=$;return{providerIds:Z.providerIds,authMethod:Z.authMethod}}function I6($){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 M1{#$;#Z;#z;#Y;#G;#Q;#X;#J=new WeakMap;#H=new WeakMap;#W=new Map;#q=new WeakMap;#F;#V=new Map;#K;#j;#B=!1;#O=0;#A=!1;#I=new u;#U=new Map;#M;#_=!1;#D=-1/0;#P=2000;#L=!1;#k;#R=new Set;#E=new Set;#N;#S;#b;constructor($){if(p()&&$.client&&!X9($.client))throw new u;let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>T0(Z);else if(p())this.#Z=async()=>{throw new A("not-enrolled","Claustrum enrollment token path is required")};else throw new A("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client??w0($.pluginId),this.#Y=$.family,this.#G=$.parseIdentity,this.#Q=$.requireAssertion??!1,this.#z=$.now??Date.now,this.#X=$.logger??j9,this.#N=B1(this.#X),this.#K=$.setTimeoutImpl??setTimeout,this.#j=$.clearTimeoutImpl??clearTimeout;let J=()=>this.#$;this.#F=new V9({client:{get reportUsageScoped(){let z=J();return z.reportUsageScoped?.bind(z)}},owns:(z)=>this.#V.has(z),token:async()=>p()?"":y2(await this.#Z()),logger:this.#X,setTimeout:this.#K,clearTimeout:this.#j})}replaceClient($){if(this.#C(),$===this.#$)return;if(p()&&!X9($))throw new u;this.#$=$;for(let Z of this.#R)Z.restart()}transportLost($){if(this.#L||this.#B)return;this.#B=!0,this.#O=this.#z(),this.#A=!1,this.#I=$ instanceof x2?$:new u($ instanceof u?$.reason:void 0),this.#X.warn("serving kept vault receipt",{reason:"unreachable"}),this.#f()}reachable(){if(this.#L||!this.#B)return;if(this.#B=!1,this.#M)this.#j(this.#M);this.#M=void 0,this.#P=2000;for(let $ of this.#W.values())$.since=null;(this.#X.info??j9.info)("vault receipt serving resumed",{reason:"reachable"})}#f(){if(this.#L||!this.#B||this.#M||this.#_)return;this.#M=this.#K(()=>{this.#M=void 0,this.#m(!0)},this.#P),this.#M.unref?.()}#m($=!1){if(this.#L||!this.#B||this.#_)return;if(this.#z()-this.#D<1000){this.#f();return}this.#D=this.#z(),this.#_=!0,this.#x().catch(()=>{if($&&this.#B)this.#P=Math.min(this.#P*2,30000)}).finally(()=>{this.#_=!1,this.#f()})}#C($){if(this.#L)throw new A("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#g($){if(this.#C($),p())return"";if(k0.hasSubscribers)k0.publish({logger:this.#X,phase:"token read begin"});let Z=this.#Z();this.#E.add(Z);let J;try{J=await Z}finally{if(this.#E.delete(Z),k0.hasSubscribers)k0.publish({logger:this.#X,phase:"token read end"})}return this.#C($),y2(J)}async#v($,Z){this.#C(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.#C(Z),J0(X)==="unreachable")this.transportLost(X);else this.reachable();if(X instanceof x2)throw X;if(J0(X)==="unreachable")throw new u(X instanceof u?X.reason:void 0);throw new A("unavailable","Claustrum scoped operation unavailable")}finally{z?.()}return this.#C(Z),this.reachable(),J}async discover($){let Z=await this.#x($);return this.#k=Z.view,Z}async#x($){let Z,J;try{J=await this.#g($)}catch(U){throw this.#W.clear(),this.#y(),U}if(k0.hasSubscribers)k0.publish({logger:this.#X,phase:"list scoped begin"});try{Z=await this.#v(()=>this.#$.listScoped(J),$)}catch(U){throw this.listFailed(U),U}finally{if(k0.hasSubscribers)k0.publish({logger:this.#X,phase:"list scoped end"})}let z=[],X=[],G=0,Q=[],W=new Map;for(let U of Z.rows){let K=A6(U,this.#Y);if(K.kind==="not-mine"){G++;continue}if(K.kind==="refused"){X.push({...U.id.trim()&&{credentialId:U.id},code:K.code});continue}Q.push({row:U,type:K.type,...K.member!==void 0&&{member:K.member}}),W.set(U.id,(W.get(U.id)??0)+1)}let Y=[];for(let{row:U,type:K,member:F}of Q){let B;if(!U.id.trim())B="empty credential id";else if((W.get(U.id)??0)>1)B="duplicate credential id";else if(U.accountId!==void 0&&!U.accountId.trim())B="blank account identity";else if(!U.state.trim())B="empty state";if(B){z.push({...U.id.trim()&&{credentialId:U.id},...F!==void 0&&{member:F},reason:B});continue}Y.push(Object.freeze({credentialId:U.id,credentialType:K,...F!==void 0&&{member:F},...U.accountId!==void 0&&{accountIdentity:U.accountId},state:U.state,...U.email!==void 0&&{email:U.email},...U.orgName!==void 0&&{orgName:U.orgName}}))}for(let U of z)this.#X.warn("skipped malformed vault record",U);let H=I6(Z);return{view:Z.view,credentials:Object.freeze(Y),skipped:Object.freeze(z),..."classify"in this.#Y&&{refused:Object.freeze(X),notMine:G},...H&&{grantReach:H}}}listFailed($){if(J0($)==="unreachable")this.transportLost($);else this.reachable(),this.#W.clear(),this.#y()}forget($){this.#W.delete($),this.#V.delete($),this.#F.forget($)}#y(){for(let $ of this.#V.keys())this.#F.forget($);this.#V.clear()}retain($){let Z=new Map($.map((J)=>[J.credentialId,J]));for(let[J,z]of this.#W){let X=Z.get(J);if(!X?.enabled||X.state!=="active"||X.credentialType!==z.attempt.credentialType||X.accountIdentity!==z.attempt.expectedAccountIdentity)this.forget(J)}for(let[J,z]of this.#V){let X=Z.get(J);if(!X?.enabled||X.state!=="active"||X.credentialType!==z.credentialType||X.accountIdentity!==z.accountIdentity)this.forget(J)}}keptReceiptState(){let $=null;for(let[Z,J]of this.#W){if(!this.#T(J.attempt)){this.forget(Z);continue}if(J.since!==null)$=Math.min($??J.since,J.since)}return Object.freeze({active:$!==null,since:$})}#T($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#z()>v2}async authorize($,Z,J="vault"){this.#C(Z);let z=this.#z(),{credentialId:X,credentialType:G,accountIdentity:Q}=$,W=this.#W.get(X);if(W&&(W.attempt.credentialType!==G||W.attempt.expectedAccountIdentity!==Q||!this.#T(W.attempt)))this.forget(X),W=void 0;let Y;try{Y=await this.#g(Z)}catch(H){throw this.#W.clear(),this.#y(),H}if(this.#B&&W)return this.#m(),this.#u(X,W,Y,J);try{let H;try{if(this.#B&&this.#U.has(this.#w({credentialId:X,credentialType:G,accountIdentity:Q},Y)))throw this.#I;H=await this.#c({credentialId:X,credentialType:G,accountIdentity:Q},Y,Z)}catch(U){if(this.#C(Z),J0(U)!=="unreachable"||W)throw U;H=await this.#h({credentialId:X,credentialType:G,accountIdentity:Q},Y,z,U,Z)}return this.#W.set(X,{attempt:H,routeId:J,since:null}),this.#V.set(X,{...$}),H}catch(H){if(this.#C(Z),J0(H)!=="unreachable")throw this.forget(X),H;return this.#u(X,W,Y,J,H)}}#w($,Z){return JSON.stringify([$.credentialId,$.credentialType,$.accountIdentity,Z])}async#h($,Z,J,z,X){let G=m2-(this.#z()-J);if(G<=0||this.#A||this.#z()-this.#O>=w2)throw z;let Q=this.#w($,Z),W=this.#U.get(Q);if(!W){let K=new AbortController,F={controller:K,users:0,error:z,pending:Promise.resolve().then(async()=>{let N=250;for(;;){await this.#l(N,K.signal);try{return await this.#c($,Z,K.signal)}catch(P){if(this.#C(K.signal),J0(P)!=="unreachable")throw P;F.error=P,N=Math.min(N*2,1000)}}})};W=F,this.#U.set(Q,W);let B=()=>{if(this.#U.get(Q)===F)this.#U.delete(Q)};W.pending.then(B,B)}let Y=W;Y.users++;let H,U;try{let K=await Promise.race([Y.pending,new Promise((B,N)=>{if(H=this.#K(()=>{if(this.#B)this.#A=!0;N(Y.error)},G),H.unref?.(),X){if(U=()=>N(X.reason),X.addEventListener("abort",U,{once:!0}),X.aborted)U()}})]);this.#C(X);let F=Object.freeze(Object.defineProperty({...K},"accessToken",{value:K.accessToken,enumerable:!1}));return this.#J.set(F,{token:Z}),F}finally{if(H)this.#j(H);if(U)X?.removeEventListener("abort",U);if(--Y.users===0){if(Y.controller.abort(),this.#U.get(Q)===Y)this.#U.delete(Q)}}}#l($,Z){return this.#C(Z),new Promise((J,z)=>{let X=()=>{this.#j(G),Z.removeEventListener("abort",X),z(Z.reason)},G=this.#K(()=>{Z.removeEventListener("abort",X),J()},$);if(G.unref?.(),Z.addEventListener("abort",X,{once:!0}),Z.aborted)X()})}#u($,Z,J,z,X=this.#I){if(!Z||this.#W.get($)!==Z||!this.#T(Z.attempt))throw this.forget($),X;if(Z.since===null)Z.since=this.#z();let G=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#J.set(G,this.#J.get(Z.attempt)??{token:J}),this.#q.set(G,z),G}async#c($,Z,J){if(!$.credentialId)throw new A("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:z,credentialType:X,accountIdentity:G}=$;if(this.#Q&&G===void 0)throw new A("identity-unasserted","Claustrum dispatch requires a known account identity");let Q=await this.#v(()=>this.#$.getScoped({credentialId:z,enrollmentToken:Z,...X==="oauth"&&{minTtlMs:D9}}),J);if(Q.credentialId!==void 0&&Q.credentialId!==z)throw new A("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.#z()<D9))throw new A("insufficient-validity","Claustrum served credential has insufficient validity");let Y=O6(Q.material),H=Q.accountId?.trim()?Q.accountId:void 0;if(this.#Q&&(Q.credentialId===void 0||H===void 0))throw new A("identity-unasserted","Claustrum served credential did not assert its identity");let U=H===void 0?this.#G?.(Y):void 0,K=H??U;if(G!==void 0&&K!==void 0&&K!==G)throw new A("identity-changed","Claustrum served credential identity changed");let F=K??G,N=Object.freeze(Object.defineProperty({credentialId:z,credentialType:X,...F!==void 0&&{accountIdentity:F},accountIdentitySource:H!==void 0?"asserted":U!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...Q.credentialId!==void 0&&{assertedCredentialId:Q.credentialId},...H!==void 0&&{assertedAccountIdentity:H},...Q.projectId!==void 0&&{projectId:Q.projectId},recordVersion:Q.recordVersion,expiresAtMs:W},"accessToken",{value:Y,enumerable:!1}));return this.#J.set(N,{token:Z}),N}async reportFailure($,Z,J){if(Z!==401)return;this.#C();let z=this.#J.get($);if(!z)throw new A("no-receipt","Claustrum failure report requires an original dispatch receipt");let X=this.#q.get($);if(X!==void 0){this.forget($.credentialId),this.#X.debug("scoped 401 not reported",{routeId:X,reason:"kept-receipt"});return}let G=this.#W.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let Q=this.#H.get($);if(Q)return Q;let W=this.#v(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:z.token,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#H.set($,W);try{await W,this.#X.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:J})}catch(Y){throw this.#H.delete($),Y}}watchRoster($){this.#C();let Z=$.view??(()=>this.#k),J,z,X=(Q=!1)=>{let W=new z3({client:this.#$,enrollmentToken:()=>this.#g(),view:()=>Q?void 0:Z(),discover:async(Y)=>{while(J)await J.catch(()=>{});if(z!==W)return;Q=!1,J=Promise.resolve().then(()=>$.onView(Y));try{await J}finally{J=void 0}},onRefused:(Y)=>{this.listFailed(Y),$.onRefused?.(Y)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#X,now:this.#z,setTimeoutImpl:this.#K,clearTimeoutImpl:this.#j});return W};z=X();let G={restart:()=>{let Q=z.mode;if(z.stop(),z=X(!0),Q!==z.mode)$.onMode?.(z.mode);z.start()},stop:()=>z.stop()};return this.#R.add(G),z.start(),{get mode(){return z.mode},close:()=>{this.#R.delete(G),z.stop()}}}reportUsage($){if(this.#L)return;try{this.#F.report($.credentialId,$.reading)}catch{}}usageReportState(){return this.#F.state()}close(){if(this.#L)return;this.#L=!0;for(let Z of this.#U.values())Z.controller.abort();if(this.#U.clear(),this.#M)this.#j(this.#M);this.#M=void 0;for(let Z of this.#R)Z.stop();this.#R.clear(),this.#W.clear();let $=this.#F.close();if($)this.#E.add($),$.then(()=>this.#E.delete($));else this.#$.close();this.#b=V1(this.#E,(Z)=>(this.#S??this.#N)(Z)).finally(()=>{if(this.#F.drop(),this.#V.clear(),$)this.#$.close()})}async dispose($=this.#N){this.#S=$,this.close(),await this.#b}}import{resolve as L3}from"node:path";var L9=30000,P9={now:()=>performance.now(),schedule($,Z){let J=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(J),unref:()=>J.unref?.()}}};var p0="all",R6=Object.freeze(["primary"]);function u2($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function D1($,Z){return JSON.stringify([$,Z])}function E0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function n($){return typeof $==="number"&&Number.isFinite($)}function h2($){return typeof $==="string"&&$.length>0}function o($,Z,J){return $[Z]===void 0||J($[Z])}function S6($){return n($)&&$>0}function C9($){return typeof $==="string"}function T6($){if(!E0($)||!h2($.scope)||!h2($.label))return!1;switch($.kind){case"reading":return n($.checkedAt)&&n($.usedPercent)&&o($,"resetsAt",C9)&&o($,"windowMinutes",S6);case"retired":return n($.retiredAt);case"absent":return n($.checkedAt);default:return!1}}function k6($){if(!E0($)||!n($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&o($,"remainingPercent",n)&&o($,"usedPercent",n)&&o($,"resetsAt",C9)&&o($,"limit",n)&&o($,"used",n)&&o($,"remaining",n)&&o($,"unit",C9)}function c2($){return E0($)&&n($.value)&&Number.isInteger($.value)&&$.value>=0&&n($.checkedAt)}function O9($){return E0($)&&Object.values($).every(c2)}function E6($){return typeof $==="boolean"}function N1($){return E0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&o($,"balance",n)&&o($,"overageLimitReached",E6)&&n($.checkedAt)}function p2($){if(!E0($))return;let Z=Object.entries($).filter(([,J])=>c2(J));return Z.length===0?void 0:Object.fromEntries(Z)}function d0($){if(j1($))return $;if(!E0($))return;let{counters:Z,credits:J,...z}=$;if(!j1(z))return;let X=p2(Z),G=N1(J)?J:void 0;return{...z,...X===void 0?{}:{counters:X},...G===void 0?{}:{credits:G}}}function j1($){if(!E0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!T6(J))return!1;let z=D1(J.scope,J.label);if(Z.has(z))return!1;Z.add(z)}return o($,"budget",k6)&&o($,"counters",O9)&&o($,"credits",N1)}class V3 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function j3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function M3($){return typeof $==="number"&&Number.isFinite($)}function d2($){return $===void 0||typeof $==="string"&&$!==""}function l2($){return typeof $==="string"&&$!==""}function w1($,Z){return $[Z]===void 0||M3($[Z])}function A9($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function b6($){return j3($)&&d2($.scope)&&l2($.label)&&M3($.usedPercent)&&A9($,"resetsAt")&&($.windowMinutes===void 0||M3($.windowMinutes)&&$.windowMinutes>0)}function f6($){return j3($)&&d2($.scope)&&l2($.label)}function x6($){if(!j3($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&w1($,"remainingPercent")&&w1($,"usedPercent")&&A9($,"resetsAt")&&w1($,"limit")&&w1($,"used")&&w1($,"remaining")&&A9($,"unit")}function L1($){if(!j3($)||!M3($.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(!b6(X))return!1;let G=D1(X.scope??p0,X.label);if(z.has(G))return!1;z.add(G)}if(!J.every(f6))return!1;return($.budget===void 0||x6($.budget))&&($.counters===void 0||O9($.counters))&&($.credits===void 0||N1($.credits))}function y6($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function g6($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function v6($,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 m6($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function h1($,Z){let J=$===void 0?void 0:d0($);if($!==void 0&&J===void 0)throw new V3("stored quota map is malformed");if(!L1(Z))throw new V3("quota observation is malformed");let z=J??{limits:[]},X=Z.checkedAt,G=new Map;for(let C of z.limits)G.set(D1(C.scope,C.label),C);let Q=(C)=>{let I=G.get(C);return I===void 0||X>=u2(I)},W=new Set;for(let C of Z.readings??[]){let I=C.scope??p0,T=D1(I,C.label);if(W.add(T),!Q(T))continue;G.set(T,{scope:I,label:C.label,kind:"reading",checkedAt:X,usedPercent:C.usedPercent,...C.resetsAt===void 0?{}:{resetsAt:C.resetsAt},...C.windowMinutes===void 0?{}:{windowMinutes:C.windowMinutes}})}for(let C of Z.coverage??[]){let I=C.scope??p0,T=D1(I,C.label);if(W.has(T)||!Q(T))continue;let m=G.get(T);G.set(T,m===void 0||m.kind==="absent"?{scope:I,label:C.label,kind:"absent",checkedAt:X}:{scope:I,label:C.label,kind:"retired",retiredAt:X})}let{limits:Y,budget:H,counters:U,credits:K,...F}=z,B=g6(z.budget,Z.budget,X),N=v6(z.counters,Z.counters),P=m6(z.credits,Z.credits);return{...F,limits:[...G.values()].sort(y6),...B===void 0?{}:{budget:B},...N===void 0?{}:{counters:N},...P===void 0?{}:{credits:P}}}var w6=Object.freeze({validate:j1,decode:d0,merge:h1});function a2($,Z=""){let J=new Map,{observation:z}=$,X=(W,Y,H)=>J.set(`${Z}:${W}`,{at:Y,order:0,publication:{...$,observation:H}}),G=(W,Y)=>JSON.stringify([W??"all",Y]),Q=new Set;for(let W of z.readings??[]){let Y=G(W.scope,W.label);Q.add(Y),X(Y,z.checkedAt,{checkedAt:z.checkedAt,readings:[{...W}]})}for(let W of z.coverage??[]){let Y=G(W.scope,W.label);if(!Q.has(Y))X(Y,z.checkedAt,{checkedAt:z.checkedAt,coverage:[{...W}]})}if(z.budget)X("budget",z.checkedAt,{checkedAt:z.checkedAt,budget:{...z.budget}});for(let[W,Y]of Object.entries(z.counters??{}))X(`counter:${W}`,Y.checkedAt,{checkedAt:z.checkedAt,counters:{[W]:{...Y}}});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 p6}from"node:crypto";import{stat as d6}from"node:fs/promises";import{resolve as u1}from"node:path";function s2($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function _9($,Z,J){return $.some((z)=>s2(z,Z,J))}function I9($,Z,J){let z={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((X)=>X.credentialId!==Z||X.accountIdentity!==J),z]}function R9($,Z,J){return $.filter((z)=>!Z.some((X)=>s2(z,X,J)))}function T9($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>q0(Z).map((J)=>({credentialId:J,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function l6($,Z){let J=q0(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 N3="vault:";function a6($){return p6("sha256").update($).digest("hex")}function s6($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function n6($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function q0($){return[$.credentialId,...$.aliases??[]]}function o2($,Z,J={}){let z=J.now??Date.now(),X=J.routePrefix??N3,G=J.reservedRouteIds??new Set,Q=$?.rows??[],W=$?void 0:J.seed,Y=[...$?.declined??W?.declined??[]],H=Z.skipped.length===0,U=new Set(Z.credentials.map((M)=>M.credentialId)),K=new Set(Z.skipped.flatMap((M)=>M.credentialId===void 0?[]:[M.credentialId])),F=Z.skipped.some((M)=>M.credentialId===void 0),B=(M)=>!U.has(M)&&(K.has(M)||F),N=new Map;for(let M of Q){if(M.accountIdentity===void 0)continue;for(let q of q0(M))if(!N.has(q))N.set(q,M.accountIdentity)}let P=new Map;for(let M of Z.credentials){let q=M.accountIdentity!==void 0?{credential:M,identity:M.accountIdentity,claimed:!0}:{credential:M,identity:N.get(M.credentialId),claimed:!1},D=n6(q),O=P.get(D)??[];O.push(q),P.set(D,O)}let C=new Set,I=new Set(G),T=[],m=(M,q)=>M.credential.credentialId.localeCompare(q.credential.credentialId),c=[...P.values()].map((M)=>M.toSorted(m)).sort((M,q)=>M[0]&&q[0]?m(M[0],q[0]):0);for(let M of c){let q=M[0]?.identity,D=M.filter((b)=>b.credential.state==="active"),O=D.length?D:M,v=O.filter((b)=>b.claimed),E=v.length?v:O,x=new Set(M.map((b)=>b.credential.credentialId)),$0=Q.find((b)=>!C.has(b)&&q0(b).some((M0)=>x.has(M0))&&(b.accountIdentity===void 0||b.accountIdentity===q)),$1=E.find((b)=>b.credential.credentialId===$0?.credentialId)??E[0];if(!$1)continue;let w=$1.credential,i=$0??(q===void 0?void 0:Q.find((b)=>!C.has(b)&&b.accountIdentity===q));if(i)C.add(i);let Z0=i?.routeId;if(!Z0||G.has(Z0)){let b=`${X}${w.credentialId}${q===void 0?"":`~${a6(q).slice(0,10)}`}`;Z0=b;for(let M0=2;I.has(Z0);M0++)Z0=`${b}~${M0}`}I.add(Z0);let E1=i?q0(i).filter(B):[],x0=[...new Set([...M.map((b)=>b.credential.credentialId),...E1])].filter((b)=>b!==w.credentialId).sort((b,M0)=>b.localeCompare(M0)),l3=J.mapAccount?.(w)??{};T.push({previousIndex:i?Q.indexOf(i):1/0,row:{routeId:Z0,credentialId:w.credentialId,credentialType:w.credentialType,...q!==void 0&&{accountIdentity:q},...x0.length&&{aliases:x0},state:w.state,label:l3.label?.trim()||s6(w),...w.email!==void 0&&{email:w.email},...w.orgName!==void 0&&{orgName:w.orgName},enabled:![w.credentialId,...x0].some((b)=>_9(Y,b,q)),addedAt:i?.addedAt??z,...i?.quota!==void 0&&{quota:i.quota},...!$1.claimed&&q!==void 0&&{unclaimed:!0}}});let Z1=T.at(-1);if(W&&Z1)Z1.previousIndex=l6(W,Z1.row)}return Q.forEach((M,q)=>{if(C.has(M)||!q0(M).some(B))return;if(I.has(M.routeId))return;let[D,...O]=q0(M).filter((x)=>!U.has(x));if(D===void 0)return;I.add(M.routeId);let{aliases:v,...E}=M;T.push({previousIndex:q,row:{...E,credentialId:D,...O.length&&{aliases:O},stale:!0}})}),T.sort((M,q)=>M.previousIndex===q.previousIndex?M.row.credentialId.localeCompare(q.row.credentialId):M.previousIndex-q.previousIndex),{version:1,view:Z.view,...$?.limits!==void 0&&{limits:$.limits},complete:H,...!H&&{rejected:Z.skipped.map((M)=>({...M.credentialId!==void 0&&{credentialId:M.credentialId},reason:M.reason}))},rows:T.map((M)=>M.row),declined:Y}}function k9($){return($?.rows??[]).filter((Z)=>Z.enabled&&Z.state==="active").map((Z)=>({id:Z.routeId,kind:Z.credentialType==="oauth"?"oauth":"api-key",...Z.quota!==void 0&&{quota:Z.quota}}))}function c1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function P1($){return $===void 0||typeof $==="string"}function i6($){let Z=c1($)?d0($.quota):void 0;if(!c1($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!P1($.accountIdentity)||!P1($.email)||!P1($.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 o6=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function n2($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!c1(J)||!P1(J.credentialId)||typeof J.reason!=="string"||!o6.has(J.reason))return;Z.push(J)}return Z}function r2($){if(!c1($)||$.version!==1||!P1($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!n2($.rejected))throw new A("invalid-state","Claustrum roster file is not valid");let Z=[];for(let X of $.rows){let G=i6(X);if(!G)throw new A("invalid-state","Claustrum roster file is not valid");Z.push(G)}let J=[];for(let X of $.declined){if(!c1(X)||typeof X.credentialId!=="string"||!P1(X.accountIdentity))throw new A("invalid-state","Claustrum roster file is not valid");J.push(X)}let z=n2($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...z&&{rejected:z},...$.limits!==void 0&&{limits:$.limits},rows:Z,declined:J}}function E9($){return r2(JSON.parse(JSON.stringify($)))}var r6=new g0({followSymlinks:!0});async function a($){if(_)return S9($);let Z=await r6.read([$],([J=$])=>S9(J));return structuredClone(Z)}async function S9($){let Z;try{Z=await Q0($,_)}catch(z){if(z.code==="ENOENT")return;throw z}let J;try{J=JSON.parse(Z)}catch{throw new A("invalid-state","Claustrum roster file is not valid")}return r2(J)}var t2={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},e2={name:"claustrum-roster",ttlMs:30000};async function l0($,Z,J={}){return Z9($,{...t2,signal:J.signal},async(z)=>{let X=await S9($),{next:G,result:Q}=await Z(X,{assertOwned:()=>z.assertOwned()});if(G){await z.assertOwned();try{await Y1($,G,{beforeRename:async()=>{await J.beforePublish?.(),J.signal?.throwIfAborted(),await z.assertOwned()}})}catch(W){if(W&&typeof W==="object"&&"published"in W&&W.published===!0)J.onPublished?.();throw W}J.onPublished?.()}return Q})}function b9($,Z){return l0($,(J)=>{let z=J?.rows.find((G)=>G.routeId===Z);if(!J||!z)throw new A("route-unavailable","Claustrum route is not in the roster");let X=I9(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 f9($,Z){return l0($,(J)=>{let z=J?.rows.find((X)=>X.routeId===Z);if(!J||!z)throw new A("route-unavailable","Claustrum route is not in the roster");return{next:{...J,declined:R9(J.declined,q0(z),z.accountIdentity),rows:J.rows.map((X)=>X===z?{...X,enabled:!0}:X)},result:void 0}})}function t6($){return new A("invalid-order",$)}function e6($,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 x9($,Z,J={}){return l0($,(z)=>{let X=z?.rows??[],G=e6(X,Z);if(G)throw t6(G);let Q=new Map;for(let H of X){let U=Q.get(H.routeId);if(U)U.push(H);else Q.set(H.routeId,[H])}let W=[...Z],Y=W.flatMap((H)=>Q.get(H)??[]);if(!z||Y.every((H,U)=>H===X[U]))return{result:{ids:W,outcome:"unchanged"}};return{next:{...z,rows:Y},result:{ids:W,outcome:"reordered"}}},{...J.signal&&{signal:J.signal}})}function $5($,Z){if(!q0($).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")&&q0($).length===1)return"bind";return"refuse"}async function y9($,Z){let{routeId:J,observation:z,...X}=Z;return $7($,{routeId:J,observation:z,accountIdentity:X.accountIdentity,receipt:X})}async function $7($,Z){if(!L1(Z.observation))return!1;let J=e($,await a($));if(!b0(J,Z).kept)return!1;return J7($,Z)}function g9($,Z){return $7($,Z)}function b0($,Z){let J=$?.rows.find((Q)=>Q.routeId===Z.routeId),z=!J?"refuse":Z.receipt?$5(J,Z.receipt):J.accountIdentity!==void 0&&J.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!J||z==="refuse")return{roster:$,kept:!1};let X=h1(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 D3=new Map;function p1($){D3.delete(u1($))}function Z7($,Z){let J=u1($);if(Z instanceof A)return Z.kind==="roster-busy";if(Z instanceof I0||Z instanceof N0)return u1(Z.details.target)===J;if(Z instanceof h){let z=u1(Z.path);return[t2.name,e2.name].some((X)=>{let G=U1(J,X);return z===G||z.startsWith(`${G}.`)})}return!1}var Z5=4;async function i2($){try{let{dev:Z,ino:J,size:z,mtimeMs:X}=await d6($);return{dev:Z,ino:J,size:z,mtimeMs:X}}catch{return}}function J5($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function z5($,Z,J){for(let z=0;z<Z5;z++){let X=await i2($),G=await a($),Q,W,Y;try{({target:Q,local:W}=Z(G));let H=JSON.stringify(J(Q));Y=JSON.stringify(Q)!==H||W!==void 0&&JSON.stringify(W)!==H}catch{return"commit"}if(!J5(X,await i2($)))continue;if(Y)return"commit";return z7($)?"commit":"unchanged"}return"commit"}async function d1($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){p1($.path);return}let J=await L0({...e2,path:$.path,renew:!0});if(!J){let Q=await a($.path);if($.signal?.throwIfAborted(),!Q?.view)throw new A("roster-busy","Claustrum account discovery is already in progress");return Q}let z=u1($.path),X=$.listedOver,G;try{let Q=await a($.path),W=X?void 0:D3.get(z);G=W&&(W.previousView===Q?.view||W.inventory.view===Q?.view)?W:{inventory:await $.custody.discover($.signal),previousView:Q?.view},D3.delete(z);let{inventory:Y}=G;$.onInventory?.(Y),$.signal?.throwIfAborted();let H=typeof $.projection==="function"?$.projection():$.projection,U=(B)=>o2(B,Y,H),K=async()=>{return $.signal?.throwIfAborted(),await J.assertOwned(),Z()};if(await z5($.path,(B)=>{if(X)return{target:B};let N=e($.path,B);return{target:B,...N!==B&&{local:N}}},U)==="unchanged"){if(!await K())return;return await a($.path)}return await l0($.path,async(B)=>{if(!await Z())return{result:void 0};if($.signal?.throwIfAborted(),await J.assertOwned(),X&&B?.view!==X.view&&B?.view!==Y.view)return{result:B};let N=U(B);return{...JSON.stringify(B)!==JSON.stringify(N)&&{next:N},result:N}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await J.assertOwned()}})}catch(Q){if(Q instanceof I0&&G&&!X&&!$.signal?.aborted&&await Z())D3.set(z,G);throw Q}finally{await J.release($.signal)}}var a0=new Map,X5=X0("claustrum"),G7=100;function Q7($,Z=P9){let J=L3($),z=a0.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},a0.set(J,z);return z}function W7($,Z,J){let z=Q7($,J);z.listeners.add(Z);let X;return()=>X??=(()=>{return z.listeners.delete(Z),z.listeners.size?Promise.resolve():v9($)})()}function G5($){return a2($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function J7($,Z){if(!L1(Z.observation))return Promise.resolve(!1);let J=Q7($),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 G5(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 H7(J,G7),Promise.resolve(!0)}function Y7($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,J)=>Z.order-J.order)}function e($,Z){let J=a0.get(L3($));if(J)for(let z of Y7(J.pending)){if(z.priorReading)Z=b0(Z,z.priorReading).roster;Z=b0(Z,z.publication).roster}return Z}function z7($){return!!a0.get(L3($))?.pending.size}function H7($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let J=$.draining?0:($.committedAt??-1/0)+L9-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,J),()=>{return $.timer=void 0,U7($)}),!$.draining)$.timer.unref?.()}function X7($){$.timer?.cancel(),$.timer=void 0}function U7($){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 l0($.path,(z)=>{let X=z;for(let Q of Y7(Z)){if(Q.priorReading)X=b0(X,Q.priorReading).roster;X=b0(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)X5.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()):G7;H7($,J)}})(),$.running}async function v9($,Z=1000){let J=L3($),z=a0.get(J);if(!z)return;z.draining=!0,X7(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)U7(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(),X7(z),z.pending.clear(),a0.get(J)===z)a0.delete(J)}}}var P3=1e4;function K7(){return new u}var m9;function F7($,Z){if(!m9)throw Error("ClaustrumConsumer is not initialized");return m9($,Z)}function q7(){return new A("not-active","Claustrum scoped custody is not active")}class w9{#$;#Z=new AbortController;#z;#Y;#G;#Q;#X;#J;#H;#W;#q=!1;#F=new Set;#V;#K;#j;#B;#O=new Map;#A;#I;#U;#M;#_=new WeakMap;static{m9=($,Z)=>{let J=new w9(Z);return J.#U=$,{consumer:J,hooks:J.#g()}}}constructor($){this.#$=$,this.#z=$.logger??X0("claustrum"),this.#Y=B1(this.#z,this.#Z.signal),this.#I=W7($.rosterPath,(Z)=>{this.#J=b0(this.#J,Z).roster})}#D($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#P($){return this.#F.add($),$.then(()=>this.#F.delete($),()=>this.#F.delete($)),$}async#L(){if(p())return!0;return await this.#$.isCustodyActive?.()??!0}#k($,Z){let J=y0([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#R(){if(this.#D(),this.#G)return this.#G;if(!this.#Q){let $={timedOut:!1};this.#Q=this.#E($),this.#P(this.#Q)}return this.#k(this.#Q)}#E($){let Z=this.#$.setTimeoutImpl??setTimeout,J=this.#$.clearTimeoutImpl??clearTimeout,z=(!p()&&this.#$.connect?this.#$.connect():Promise.resolve().then(()=>w0(this.#$.pluginId))).then((Q)=>{if(this.#Z.signal.aborted||$.timedOut){if(Q.close(),!$.timedOut)this.#D();throw K7()}if(this.#G=new M1({client:Q,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#z,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&Q.insula)this.#K=i3(Q.insula,this.#$.tokenPath);return this.#G}),X,G=new Promise((Q,W)=>{X=Z(()=>{if($.timedOut=!0,this.#Z.signal.aborted)return;this.#z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:this.#N()}),W(K7())},this.#N()),X.unref?.()});return Promise.race([z,G]).finally(()=>{if(X)J(X);this.#Q=void 0})}#N(){return this.#$.connectTimeoutMs??P3}snapshot(){return this.#J}grantReach(){if(this.#U)return this.#U.grantReach(this.#J?.view);let $=this.#H;return $&&this.#J?.view===$.view?$.reach:void 0}watchState(){if(this.#U)return Object.freeze({vault:this.#U.watchMode()});return Object.freeze({vault:this.#j?.mode??"polling",...this.#$.insula&&{insula:this.#K?.source.watchMode()??"polling"}})}#S(){this.#j?.close(),this.#j=void 0,this.#B?.(),this.#B=void 0}keptReceiptState(){if(this.#U){let $=this.#M;return $&&this.#U.leaseLive($)?$.custody.keptReceiptState():this.#U.keptReceiptState()}return this.#G?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return k9(this.#J)}refresh(){if(this.#D(),this.#U)return this.#P(this.#v(this.#U));if(this.#X)return this.#X;return this.#X=(async()=>{if(!await this.#L()){if(this.#J=void 0,this.#H=void 0,this.#S(),this.#G)this.#G.close(),this.#P(this.#G.dispose(this.#Y));this.#G=void 0,this.#K?.release(),this.#K=void 0;return}let $=await this.#R(),Z,J=await d1({path:this.#$.rosterPath,custody:$,onInventory:(X)=>{Z=X},isActive:()=>this.#L(),signal:this.#Z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#D();let z=J?.view!==this.#J?.view;if(this.#J=e(this.#$.rosterPath,J),$.retain(J?.rows??[]),Z&&J?.view!==void 0)this.#H=Z.grantReach?{view:J.view,reach:Z.grantReach}:void 0;if(J&&z)this.#$.onRoster?.(J);return this.#A=(this.#$.now??Date.now)(),J})().finally(()=>{this.#X=void 0}),this.#P(this.#X),this.#b(this.#X),this.#X}#b($){try{this.#$.onDiscovery?.($)}catch(Z){this.#$.onError?.(Z)}}start(){if(this.#q)return;if(this.#D(),this.#q=!0,this.#U){this.#U.start();return}let $=async()=>{try{if(await this.#f())await this.refresh();await this.refreshInsulaQuota(),this.#m()}catch(J){if(!this.#Z.signal.aborted)this.#$.onError?.(J)}if(this.#Z.signal.aborted)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#W=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#W=void 0,this.#P($())},Z),this.#W.unref?.()};this.#P($())}async#f(){if(this.#j?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#A===void 0||$-this.#A>=J1)return!0;return!await this.#L()}#m(){let $=this.#G;if(this.#Z.signal.aborted||!$)return;if(this.#j??=$.watchRoster({view:()=>this.#J?.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.#K&&!this.#B)this.#B=this.#K.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#L())return;try{if(!p())await T0(this.#$.tokenPath);await this.#R(),await this.#K?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#L())return;try{if(!p())await T0(this.#$.tokenPath);return this.#C($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#L())return;try{if(!p())await T0(this.#$.tokenPath);let J=e(this.#$.rosterPath,await a(this.#$.rosterPath))?.rows.find((z)=>z.routeId===$);return this.#C(J?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute($){let Z=this.#$.insula;if(!Z||this.#Z.signal.aborted||!await this.#L())return{miss:"unreachable"};try{if(!p())await T0(this.#$.tokenPath);let z=e(this.#$.rosterPath,await a(this.#$.rosterPath))?.rows.find((Q)=>Q.routeId===$)?.accountIdentity;if(!z||!this.#K)return{miss:"unreachable"};let X=this.#K.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.#O.get($)!==J.miss)this.#O.set($,J.miss),this.#z.warn("skipped insula provider poll",{reason:J.miss});return}return this.#O.delete($),J.miss?Z():J.reading}#C($){if(!this.#$.insula||!$)return;let Z=this.#K?.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.#U)return this.#w(this.#U,$,Z);this.#D(Z);let J=this.#J??await this.#k(this.refresh(),Z);if(!J||!await this.#L())throw this.#G?.close(),this.#G=void 0,this.#S(),this.#K?.release(),this.#K=void 0,new A("not-active","Claustrum scoped custody is not active");let z=e(this.#$.rosterPath,await a(this.#$.rosterPath));this.#D(Z);let X=J.rows.find((Y)=>Y.routeId===$),G=z?.rows.find((Y)=>Y.routeId===$);if(G&&!G.enabled){if(X)this.#G?.forget(X.credentialId);throw new A("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 A("route-unavailable","Claustrum route is disabled, removed or changed")}let Q=await this.#k(this.#R(),Z),W=y0([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()}}#g(){return{discovery:($)=>{let Z=this.#U;if(!Z||!this.#$.onDiscovery||this.#Z.signal.aborted)return;let J=this.#P($.then((z)=>this.#x(Z,z)));this.#b(J)},install:($)=>{if(this.#Z.signal.aborted)return;let Z=$.view!==this.#J?.view;if(this.#J=e(this.#$.rosterPath,$),Z)try{this.#$.onRoster?.($)}catch(J){this.#$.onError?.(J)}},reset:()=>{this.#J=void 0},roster:()=>this.#J,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#v($){let Z=await $.refresh();return this.#x($,Z)}#x($,Z){if(this.#D(),!Z)return;if(Z.errors.has($.provider))throw Z.errors.get($.provider);return this.#J}#y($){if($&&this.#M!==$)return;this.#M?.release(),this.#M=void 0}async#T($,Z){let J=this.#M;if(J&&$.leaseLive(J))return J;this.#y();let z=await $.acquire(Z);if(this.#Z.signal.aborted)z.release(),this.#D();let X=this.#M;if(X&&$.leaseLive(X))return z.release(),X;return this.#M=z,z}async#w($,Z,J){if(this.#D(J),!this.#J)await this.#k($.refresh(),J);let z=this.#J;if(!await $.readAuthority())throw this.#y(),q7();if(this.#D(J),!z)throw new A("route-unavailable","Claustrum has no roster for this provider yet");let X=e(this.#$.rosterPath,await a(this.#$.rosterPath));this.#D(J);let G=z.rows.find((H)=>H.routeId===Z),Q=X?.rows.find((H)=>H.routeId===Z);if(Q&&!Q.enabled){if(G)$.forget(G.credentialId);throw new A("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 A("route-unavailable","Claustrum route is disabled, removed or changed")}let W={credentialId:Q.credentialId,credentialType:Q.credentialType,...Q.accountIdentity!==void 0&&{accountIdentity:Q.accountIdentity}},Y=y0([this.#Z.signal,...J?[J]:[]]);try{for(let H=0;;H++){let U=await this.#T($,Y.signal);try{let K=await U.custody.authorize(W,Y.signal,Z);return this.#_.set(K,U),K}catch(K){if(H>0||Y.signal.aborted||$.leaseLive(U)||!(K instanceof A)||K.kind!=="closed")throw K;if(this.#y(U),!await $.readAuthority())throw q7()}}}finally{Y.dispose()}}reportUsage($){if(this.#Z.signal.aborted)return;try{let Z=this.#J?.rows.find((J)=>J.routeId===$.routeId);if(!Z?.enabled||Z.state!=="active"||Z.credentialId!==$.credentialId&&!Z.aliases?.includes($.credentialId))return;if(this.#U){if(this.#M&&this.#U.leaseLive(this.#M))this.#M.custody.reportUsage($)}else this.#G?.reportUsage($)}catch{}}usageReportState(){try{return(this.#U?this.#M?.custody:this.#G)?.usageReportState()??{pending:0,inFlight:!1,dropped:0}}catch{return{pending:0,inFlight:!1,dropped:0}}}async reportFailure($,Z,J){if(this.#D(),this.#U){let z=this.#_.get($);if(!z)throw new A("no-receipt","Claustrum dispatch receipt has no active owner");await z.custody.reportFailure($,Z,J);return}if(!this.#G)throw new A("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(N9(J.site,X,Q,this.#z))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.#D(),await b9(this.#$.rosterPath,$),this.#J=e(this.#$.rosterPath,await a(this.#$.rosterPath)),this.#J)this.#U?.publishRoster(this.#J);if(this.#U)this.#U.retainUnion();else this.#G?.retain(this.#J?.rows??[])}async accept($){if(this.#D(),await f9(this.#$.rosterPath,$),this.#J=e(this.#$.rosterPath,await a(this.#$.rosterPath)),this.#J)this.#U?.publishRoster(this.#J)}async reorder($){this.#D();let Z=await x9(this.#$.rosterPath,$);if(this.#J=e(this.#$.rosterPath,await a(this.#$.rosterPath)),this.#J)this.#U?.publishRoster(this.#J);return Z}async recordQuota($,Z,J){return this.#D(),y9(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.#D(),g9(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:J})}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new A("closed","Claustrum consumer is closed")),this.#W)(this.#$.clearTimeoutImpl??clearTimeout)(this.#W);if(this.#W=void 0,this.#S(),this.#G)this.#G.close(),this.#P(this.#G.dispose(this.#Y));this.#M?.release(),this.#M=void 0,this.#U?.detach(),this.#K?.release(),this.#K=void 0,this.#J=void 0,this.#H=void 0,this.#I(),p1(this.#$.rosterPath)}async dispose(){this.close(),this.#V??=Promise.all([V1(this.#F,this.#Y),this.#I()]).then(()=>{}),await this.#V}}import{createHash as Q5}from"node:crypto";import{channel as B7}from"node:diagnostics_channel";import{readdir as W5,stat as Y5}from"node:fs/promises";import{dirname as H5,join as C1,resolve as V7}from"node:path";var C3=new Map,U5=/^[a-z0-9][a-z0-9._-]{0,63}$/,K5=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,q5=/^[0-9a-f]{16}$/,M7=3;function u9($,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=u9($[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=u9($[G],J);if(Q===void 0)return;z.push(`${JSON.stringify(G)}:${Q}`)}return`{${z.join(",")}}`}function F5($,Z){let J=u9({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??N3,mapAccount:$.mapAccount?String($.mapAccount):null});if(J===void 0)throw new A("invalid-state","Claustrum hub classifierInput must be plain JSON");return Q5("sha256").update(J).digest("hex").slice(0,16)}function j7($,Z){if(typeof $!=="string"||!U5.test($)||K5.test($))throw new A("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function f0($="Claustrum custody lease is closed"){return new A("closed",$)}function h9(){return new A("not-active","Claustrum scoped custody is not active")}function D7(){return new u}function B5($,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 N7($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class L7{#$;#Z;#z;#Y=new AbortController;#G=new Map;#Q=new WeakMap;#X=0;#J;#H;#W;#q;#F;#V=new Set;#K;#j=0;#B;#O;#A;#I=!1;#U=new Set;#M;#_;#D;constructor($){if(!$.family||!("classify"in $.family))throw new A("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=j7($.hostGeneration,"host generation"),J=$.members.map((X)=>j7(X,"member"));if(new Set(J).size!==J.length)throw new A("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??X0("claustrum"),this.#z=B1(this.#Z,this.#Y.signal),this.#_=C1($.stateDir,"rosters",Z),this.#D=F5($,J);let z=C1(this.#_,this.#D);for(let X of J)this.#G.set(X,{provider:X,path:C1(z,`${X}.json`),closed:!1})}#P($){return this.#U.add($),$.then(()=>this.#U.delete($),()=>this.#U.delete($)),$}#L(){if(this.#Y.signal.aborted)throw f0("Claustrum discovery hub is closed")}#k($){let Z=this.#G.get($);if(!Z)throw new A("wrong-consumer","Claustrum hub has no such member");return Z}rosterPath($){return this.#k($).path}member($,Z){this.#L();let J=this.#k($);if(J.hooks)throw new A("wrong-consumer","Claustrum hub member was already built");for(let K of["rosterPath","tokenPath","family","connect","isCustodyActive","insula","pollIntervalMs","routePrefix","mapAccount"])if(K in Z)throw new A("wrong-consumer",`Claustrum hub members cannot take ${K}`);let z={provider:J.provider,start:()=>this.start(),refresh:()=>this.#h(),readAuthority:()=>this.#x(),acquire:(K)=>this.acquire(K),leaseLive:(K)=>this.#S(K),grantReach:(K)=>K!==void 0&&this.#B?.view===K?this.#B.reach:void 0,watchMode:()=>this.watchState(),keptReceiptState:()=>this.keptReceiptState(),retainUnion:()=>this.#d(),publishRoster:(K)=>this.#R(J,K),forget:(K)=>this.#J?.custody?.forget(K),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}=F7(z,X);J.hooks=Q;let W=V7(J.path),Y=C3.get(W)??new Set,H=(K)=>{if(J.closed||this.#K!==!0||!this.#J||!this.#N(this.#J)||!Q.roster()||this.#a(Q,K))return;if(J.seen=JSON.stringify(E9(K)),Q.install(K),K.view!==this.#B?.view)J.pending??={failures:0,wait:0};this.#d()};Y.add(H),J.receiveRoster=H,C3.set(W,Y);let U=!0;return J.releaseRoster=()=>{if(!U)return;if(U=!1,Y.delete(H),!Y.size)C3.delete(W)},G}#R($,Z){let J=this.#J;if($.closed||!J||!this.#N(J))return;$.seen=JSON.stringify(E9(Z)),$.hooks?.install(Z);for(let z of C3.get(V7($.path))??[]){if(!this.#N(J))return;if(z!==$.receiveRoster)z(Z)}}#E(){let $={id:++this.#X,count:0,ended:!1,controller:new AbortController};return this.#J=$,$}#N($){return!$.ended&&this.#J===$&&!this.#Y.signal.aborted}#S($){let Z=this.#Q.get($);return!!Z&&!Z.released&&!Z.generation.ended}#b($,Z=f0()){if($.ended)return;if($.ended=!0,$.count=0,this.#J===$)this.#J=void 0;if(this.#W&&this.#Q.get(this.#W)?.generation===$)this.#W=void 0;if(this.#q?.generation===$)this.#q.watch.close(),this.#q=void 0;if($.controller.abort(Z),$.custody)$.custody.close(),this.#P($.custody.dispose(this.#z))}#f($){if($.ended)return;if($.count--,$.count<=0)this.#b($)}#m($){let Z=this.#H;if(Z?.generation===$&&Z.promise)return Z.promise;let J={generation:$,timedOut:!1},z=this.#$.connectTimeoutMs??P3,X,G=(!p()&&this.#$.connect?this.#$.connect():Promise.resolve().then(()=>w0(this.#$.pluginId))).then((Y)=>{if(J.timedOut)throw Y.close(),D7();if(!this.#N($)||$.count<=0)throw Y.close(),f0("Claustrum connection is no longer wanted");return $.custody=new M1({client:Y,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((Y,H)=>{X=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(J.timedOut=!0,!this.#N($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:z}),H(D7())},z),X.unref?.()});return J.promise=this.#P(Promise.race([G,Q]).finally(()=>{if(X)(this.#$.clearTimeoutImpl??clearTimeout)(X)})),J.promise.finally(()=>{if(this.#H===J)this.#H=void 0}).catch(()=>{}),this.#H=J,J.promise}acquire($){try{if(this.#L(),$?.throwIfAborted(),this.#K===!1)throw h9()}catch(J){return Promise.reject(J)}let Z=this.#J??this.#E();return Z.count++,this.#C(Z,$,!0)}async#C($,Z,J){let z=$.custody;if(!z){let X=y0([$.controller.signal,...Z?[Z]:[]]);try{z=await B5(this.#m($),X.signal)}catch(G){if(!$.ended)throw this.#f($),G;return this.#g(Z,J)}finally{X.dispose()}}if($.ended)return this.#g(Z,J);if(Z?.aborted)throw this.#f($),Z.reason;return this.#v($,z)}#g($,Z){if($?.throwIfAborted(),this.#L(),this.#K===!1)throw h9();if(!Z)throw f0();let J=this.#J??this.#E();return J.count++,this.#C(J,$,!1)}#v($,Z){let J={generation:$,custody:Z,released:!1},z=()=>{if(J.released||$.ended)throw f0()},X=Object.freeze({authorize:async(Q,W,Y)=>{z();let H=y0([$.controller.signal,...W?[W]:[]]);try{return await Z.authorize(Q,H.signal,Y)}finally{H.dispose()}},reportFailure:async(Q,W,Y)=>{return z(),Z.reportFailure(Q,W,Y)},reportUsage:(Q)=>{if(!J.released&&!$.ended)Z.reportUsage(Q)},usageReportState:()=>{return z(),Z.usageReportState()},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.#f($)}});return this.#Q.set(G,J),G}leaseState(){let $=this.#J;return Object.freeze({generation:$?.id,count:$?.count??0})}async#x(){let $=p()||(await this.#$.isCustodyActive?.()??!0);if(this.#Y.signal.aborted)return!1;let Z=this.#K;if(this.#K=$,!$&&Z!==!1)this.#y();return $}#y(){this.#j++;let $=this.#J;if($)this.#b($,h9());this.#W=void 0,this.#q?.watch.close(),this.#q=void 0,this.#B=void 0,this.#O=void 0;for(let Z of this.#G.values())Z.seen=void 0,Z.pending=void 0,Z.hooks?.reset(),p1(Z.path)}#T(){return[...this.#G.values()].filter(($)=>$.hooks&&!$.closed)}async#w(){let $=this.#W,Z=$&&this.#Q.get($);if($&&Z&&this.#S($))return Z;this.#W=void 0;let J=await this.acquire(this.#Y.signal),z=this.#W&&this.#Q.get(this.#W);if(this.#W&&z&&this.#S(this.#W))return J.release(),z;this.#W=J;let X=this.#Q.get(J);if(!X)throw f0();return X}#h(){try{this.#L()}catch(z){return Promise.reject(z)}let $=this.#F;if($&&!$.generation?.ended)return $.promise;let Z={},J=this.#P(this.#l(Z).finally(()=>{if(this.#F===Z)this.#F=void 0}));Z.promise=J,this.#F=Z;for(let z of this.#T())z.hooks?.discovery(J);return J}async#l($){if(!await this.#x())return;let Z=await this.#w(),J=Z.generation;if($.generation=J,!this.#N(J))return;let z=await this.#t().then(()=>{return},(K)=>K instanceof Error?K:Error(String(K)));if(await this.#c(),!this.#N(J))return;let X=new Map(await Promise.all([...this.#G.values()].map(async(K)=>[K,await a(K.path).then((F)=>F?{file:F}:{},(F)=>F instanceof Error?F:Error(String(F)))])));if(!this.#N(J))return;let G;try{G=await Z.custody.discover(J.controller.signal)}catch(K){if(!this.#N(J))return;for(let F of this.#G.values())if(F.pending)this.#p(F);throw K}if(!this.#N(J))return;let Q=this.#T(),W=Promise.all(Q.map((K)=>K.hooks&&!K.closed?this.#u(K,K.hooks,G,z??X.get(K),J):void 0));this.#V.add(W);let Y;try{Y=await W}finally{this.#V.delete(W)}if(!this.#N(J))return;let H=new Map,U=!0;for(let[K,F]of Q.entries()){let B=F.hooks,N=Y[K];if(!B||!N)continue;if("error"in N){let{error:C}=N;if(U=!1,this.#p(F),Z7(F.path,C))this.#Z.debug("claustrum hub member commit refused",{member:F.provider});else H.set(F.provider,C);continue}let{roster:P}=N;if(!this.#N(J))return;if(P?.view!==G.view)U=!1,this.#p(F);else F.pending=void 0;if(!P)continue;if(this.#a(B,P)){U=!1,this.#p(F);continue}this.#R(F,P)}if(!this.#N(J))return;if(this.#d(),U)this.#B=Object.freeze({view:G.view,...G.grantReach&&{reach:G.grantReach},refused:Object.freeze([...G.refused??[]]),notMine:G.notMine??0});return this.#O=(this.#$.now??Date.now)(),{errors:H}}async#u($,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 f0("Claustrum hub member has no base view");if(z instanceof Error)throw z;let Q;if(!z.file){let Y=B7("common-auth.claustrum.phases");if(Y.hasSubscribers)Y.publish({logger:this.#Z,phase:`seed read ${$.provider} begin`});try{Q=await this.#e($)}finally{if(Y.hasSubscribers)Y.publish({logger:this.#Z,phase:`seed read ${$.provider} end`})}}return{roster:await d1({path:$.path,custody:{discover:async()=>G},isActive:()=>this.#N(X)&&this.#K===!0,signal:X.controller.signal,projection:()=>({...Z.projection(),...Q&&{seed:Q}}),listedOver:{view:z.file?.view}})}}catch(Q){return{error:Q}}}async#c(){if(!this.#V.size)return;let $=B7("common-auth.claustrum.phases"),Z=(J)=>{if($.hasSubscribers)$.publish({logger:this.#Z,phase:J})};Z("earlier fan-out drain begin");try{while(this.#V.size)await Promise.allSettled([...this.#V])}finally{Z("earlier fan-out drain end")}}async#t(){for(let $ of[H5(this.#_),this.#_,C1(this.#_,this.#D)])await F1($,{},"roster directory")}async#e($){let Z=`${$.provider}.json`,J=[C1(this.#_,Z)];try{for(let X of await W5(this.#_))if(X!==this.#D&&q5.test(X))J.push(C1(this.#_,X,Z))}catch{}let z;for(let X of J)try{let G=(await Y5(X)).mtimeMs,Q=await a(X);if(Q&&(!z||G>z.modified))z={modified:G,roster:Q}}catch{}return z&&T9(z.roster)}#a($,Z){let J=$.projection().reservedRouteIds;return!!J?.size&&Z.rows.some((z)=>J.has(z.routeId))}#p($){let Z=($.pending?.failures??0)+1,J=Math.max(1,this.#$.pollIntervalMs??5000),z=Math.max(1,Math.ceil(J1/J)),X=Z<=M7?1:Math.min(2**(Z-M7),z);$.pending={failures:Z,wait:X-1}}#d(){let $=this.#J?.custody;if(!$)return;$.retain(this.#T().flatMap((Z)=>Z.hooks?.roster()?.rows??[]))}async#$0(){let $=this.#j;for(let Z of this.#T()){let J;try{J=await a(Z.path)}catch(W){Z.hooks?.onError(W);continue}if($!==this.#j||this.#K!==!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.#a(z,J)){Z.pending??={failures:0,wait:0};continue}let Q=N7(G);if(Z.seen=X,this.#R(Z,J),N7(z.roster())!==Q)this.#d()}}#Z0(){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.#q?.watch.mode!=="watching"||$)return!0;let Z=(this.#$.now??Date.now)();return this.#O===void 0||Z-this.#O>=J1}#J0(){let $=this.#W,Z=$&&this.#Q.get($);if(!$||!Z||!this.#S($)||this.#K!==!0)return;let J=Z.generation;if(!this.#N(J)||this.#q?.generation===J)return;let z=Z.custody.watchRoster({view:()=>this.#B?.view,onView:()=>this.#P((async()=>{while(this.#F)await this.#F.promise.catch(()=>{});if(!this.#N(J))return;await this.#o()})()),onRefused:(X)=>this.#n(X),onError:(X)=>this.#s(X)});this.#q={generation:J,watch:z}}#s($){if(!this.#Y.signal.aborted)this.#$.onError?.($)}#n($){if(this.#Y.signal.aborted)return;this.#$.onError?.($);for(let Z of this.#T())Z.hooks?.onError($)}#i($){for(let[Z,J]of $?.errors??[])this.#G.get(Z)?.hooks?.onError(J)}async#o(){let $;try{$=await this.#h()}catch(Z){this.#n(Z);return}this.#i($)}async#r(){try{if(await this.#x()){if(await this.#$0(),this.#Z0())await this.#o();this.#J0()}}catch(Z){this.#s(Z)}if(this.#Y.signal.aborted)return;let $=this.#$.pollIntervalMs??5000;if($<=0)return;this.#A=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#A=void 0,this.#P(this.#r())},$),this.#A.unref?.()}start(){if(this.#I)return;this.#L(),this.#I=!0,this.#P(this.#r())}async refresh(){this.#i(await this.#h())}refusals(){let $=this.#B;return $&&Object.freeze({view:$.view,refused:$.refused,notMine:$.notMine})}grantReach(){return this.#B?.reach}watchState(){let $=this.#q;return $&&this.#N($.generation)?$.watch.mode:"polling"}keptReceiptState(){return this.#J?.custody?.keptReceiptState()??Object.freeze({active:!1,since:null})}close(){if(this.#Y.signal.aborted)return;this.#Y.abort(f0("Claustrum discovery hub is closed"));for(let Z of this.#G.values())Z.releaseRoster?.();if(this.#A)(this.#$.clearTimeoutImpl??clearTimeout)(this.#A);this.#A=void 0;let $=this.#J;if($)this.#b($);this.#W=void 0,this.#q?.watch.close(),this.#q=void 0}async dispose(){this.close(),this.#M??=V1(this.#U,this.#z),await this.#M}}var n0={opencode:D5,pi:N5},c9={opencode:"Claude sign-in for OpenCode",pi:"Claude sign-in for Pi"};function p9($,Z){let{tokenPath:J}=P7($,Z);return{stateDir:j5(J),host:$,override:J}}function d9($,Z){return L5($==="pi"?Z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0,$==="pi"?{...Z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:Z)}class s0 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 l9($,Z){let J=Z??n0[$];if(typeof J!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(J))throw new s0("permission-refused");return["auth","grant","--principal",`enrolled:${J}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"]}async function C7($,Z){try{await Z.processFence();let J=await B3(Z.paths??P7($,Z.env),n0[$]);if(J.state==="blocked")throw new s0("permission-refused");let z=J.state==="approved"?J.approvedName:void 0;if(J.state==="approved"&&J.requestedGrantsStatus==="sent")return z;let X=l9($,z);if((await Z.runner.run(Z.ckBinary??"ck",X,{env:Z.env})).exitCode!==0)throw new s0("permission-refused");return z}catch{throw new s0("permission-refused")}}import{createHash as R5}from"node:crypto";import{lstat as S5,mkdir as T5,readFile as f7}from"node:fs/promises";import{dirname as k5}from"node:path";import{assertHostsStopped as E5,canonicalPath as s9,createNativeAccountRuntime as b5,custodyTombstoneOAuth as f5,inspectNativeHostAuthEntry as x7,NativeMigrationError as i0,nativeJournalMayAdoptLaterHostLogin as x5,nativePoolHoldsAccountData as y5,prepareNativeMigration as g5,readNativeEnrollmentMode as y7,readNativeMigrationJournal as v5,releaseNativeMigrationPreflight as m5,requireNoSupervisedAuthContentSnapshot as w5,runNativeMigration as h5,writeNativeHostAuth as u5}from"@cortexkit/anthropic-auth-core";import{dirname as P5,join as O7,resolve as a9}from"node:path";import{ACCOUNT_FILE_NAME as A7,ACCOUNT_STATE_FILE_NAME as C5,canonicalPath as _7,getStickyRoutingStatePath as O5,resolveLocalRoutingDestination as A5,resolveNativePoolPaths as _5}from"@cortexkit/anthropic-auth-core";async function C0($,Z){let J=$==="pi"?S7(Z):I7(Z),z=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),X=a9(z||O7(J,A7)),G=a9(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(X.endsWith(A7)?O7(P5(X),C5):`${X}.state.json`)),Q=await _5(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"?T7(Z):R7(Z),routingSourcePath:a9(W||O5(X)),routingDestinationPath:A5($,Q,Z)}}async function k7($){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 _7(G);if(z.has(Q)&&!(X===9&&Q===await _7(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 I5}from"node:util";var E7=new WeakMap;function b7($){return typeof $==="object"&&$!==null?E7.get($):void 0}function O1($){if(!$||typeof $!=="object"||I5.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 r extends Error{constructor($){super($);this.name="SetupRefusal",E7.set(this,$)}}var n9="OpenCode's separate Anthropic login is not used. Add that account through /claude Accounts if needed, or remove the separate login from OpenCode.";function g7($){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 i9($,Z){let J=[];for(let z of $)if(await y7(z,Z)!=="local")J.push(g7(z));if(J.length)throw new r(J.join(`
|
|
13
|
+
`))}function o0($,Z){return async()=>{w5(Z.env);try{await E5(Z.fence,Z.env)}catch(J){let z=O1(J);if(z)throw new r(z);throw J}await i9([$],Z.env)}}async function o9($){try{return R5("sha256").update(await f7($)).digest("hex")}catch(Z){if(Z.code==="ENOENT")return"absent";throw new i0("unsafe-source")}}async function l1($,Z){let J;try{J=JSON.parse(await f7(Z,"utf8"))}catch(G){if(G.code!=="ENOENT")throw new i0("unsafe-source")}let z=x7($,J),X=J?.anthropic;return{...z,realLogin:z.kind==="oauth"&&Boolean(X?.access&&X.refresh)}}async function O3($,Z){let{paths:J}=$,z=$.generation2?void 0:await l1(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(o9));return JSON.stringify([await y7(J.host,Z),z?.digest,...X])}async function r9($,Z,J){let z=Z.paths??await C0($,Z.env),X=o0($,Z);await X();let G=await v5(z.paths);if(G&&G.host!==$)throw new i0("invalid-source");let Q=G?.phase==="committed"||G?.phase==="retired";if(G&&G.kind!=="empty-init"&&(G.hostAuthPath!==await s9(z.hostAuthPath)||G.routingPaths.source!==await s9(z.routingSourcePath)||G.routingPaths.destination!==await s9(z.routingDestinationPath)))throw new i0("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 i0("invalid-source");if(W.action=G?"reuse":"empty-init",!G){let Y=[z.paths.config,z.paths.state,z.paths.runtime,z.paths.roster];if(!Z.env.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE)Y.push(z.routingDestinationPath);for(let H of Y){try{await S5(H)}catch(U){if(U.code==="ENOENT")continue;throw new i0("unsafe-source")}throw new i0("invalid-source")}}}else{W.slot=await l1($,z.hostAuthPath);let Y=x5(G,$)&&W.slot.kind==="oauth";W.poolPopulation=G?.kind==="empty-init"||Y?await y5({paths:z.paths}):"not-evaluated";let H=W.poolPopulation===!0;if($==="opencode"&&(H||Q&&G?.kind!=="empty-init"&&!Y&&W.slot.kind==="oauth"))W.action="skip",W.notice=W.slot.realLogin;else W.preflight=await g5({...z,env:Z.env,processFence:X,removePiAnthropicAuth:Z.removePiAnthropicAuth})}return W.fingerprint=await O3(W,Z.env),W}async function A1($,Z){await o0($.paths.host,Z)();let J=await r9($.paths.host,{...Z,paths:$.paths},$.generation2);try{if(J.fingerprint!==$.fingerprint||J.action!==$.action)throw new r("Setup inputs changed. Rerun setup with all hosts stopped.")}finally{if(J.preflight)m5(J.preflight)}}async function t9($,Z){if($.paths.host!=="opencode"||$.slot?.kind!=="absent")return;let J=o0("opencode",Z);await J(),await T5(k5($.paths.hostAuthPath),{recursive:!0,mode:448}),await u5({host:"opencode",authPath:$.paths.hostAuthPath,sourceDigest:"absent",expectedDigest:x7("opencode",{anthropic:f5("anthropic")}).digest,env:Z.env,removePiAnthropicAuth:!1,processFence:J})}async function v7($,Z){let J={...Z.env},z=o0($,{...Z,env:J});await z();let X=Z.paths??await C0($,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 h5({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=b5({paths:X.paths,host:$,vault:{env:J},beforePoolWrite:z});try{if((await Q.read()).mode!=="local")throw new r(g7($));await z(),await Q.loginOAuth({routeId:"main",replace:!0,...G})}finally{await Q.close()}}if(Z.skipMigration){let Q=await l1($,X.hostAuthPath);await t9({paths:X,slot:Q},Z)}}var m7={opencode:"OpenCode",pi:"Pi"};function o5($,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`${m7[Z]} has no read grant in the vault, so setup cannot see any Claude login. Run ${["ck",...l9(Z,J)].join(" ")}, then rerun setup.`;case"grant-reaches-nothing":return`${m7[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 W0 extends Error{host;approvedName;code;constructor($,Z="opencode",J){super(o5($,Z,J));this.host=Z;this.approvedName=J;this.name="NativeVaultActivationError",this.code=$}}function r5($){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 $$($){try{return JSON.parse(await c5($,"utf8"))}catch(Z){if(Z.code==="ENOENT")return;throw new W0("host-auth-invalid")}}async function a1($,Z){if($==="opencode")return"opencode";let J=Z.paths??await C0($,Z.env),z=e9($,await $$(J.hostAuthPath)),X=Z$({env:Z.env,authPath:J.hostAuthPath}),{stashPath:G}=s5({env:Z.env,authPath:J.hostAuthPath});return JSON.stringify([z.digest,await X.inspect(),await o9(G)])}async function w7($){try{i5($.env)}catch{throw new W0("auth-content-refused")}try{await p5($.fence,$.env)}catch(Z){let J=O1(Z);if(J)throw new r(J);throw Z}}async function h7($,Z){let J={...Z.env};await(()=>w7({...Z,env:J}))();let X=Z.paths??await C0($,J),G=$==="opencode"&&Z.inspectOpenCodeAuth!==!1&&e9("opencode",await $$(X.hostAuthPath)).kind==="oauth";if($==="pi"){let Q=e9("pi",await $$(X.hostAuthPath)),W=await Z$({env:J,authPath:X.hostAuthPath}).inspect();if(W.slot==="placeholder"&&W.stash==="missing")throw new a5("missing-stash");if(Q.kind!=="absent"&&W.slot!=="placeholder"&&!Z.removePiAnthropicAuth)throw new W0("consent-required")}return{priorMode:await n5($,J),fingerprint:await a1($,{...Z,env:J}),separateOpenCodeLogin:G}}async function u7($,Z,J){let z={...Z.env},X=()=>w7({...Z,env:z});await X();let G=Z.paths??await C0($,z);if(await a1($,Z)!==J.fingerprint)throw new W0("host-auth-invalid");let Q=await C7($,{env:z,runner:Z.runner,processFence:X,ckBinary:Z.enrollment?.ckBinary,paths:Z.enrollment?.paths}),W=Z.discover??(()=>l5({paths:G.paths,host:$,env:$==="pi"?{...z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE}:z})),Y,H=async()=>{return Y=await W(),Y},U=d5({paths:G.paths,host:$,vault:{env:z,discover:H}});try{await X(),await U.vault.refresh();let K=await U.read(),F=K.accounts.find((B)=>B.id==="main");if(K.mode!=="claustrum"||!F?.accountIdentity||F.source!=="vault"){let B=r5(Y);throw B==="primary-unverified"?new W0(B):new W0(B,$,Q)}if(await X(),$==="pi")await Z$({env:z,authPath:G.hostAuthPath}).enterVault();return J.priorMode==="claustrum"?"already-vault":"committed"}finally{await U.close()}}var t5=/(?:^|[/\\])(opencode|litecode|opencode2|pi)(?:\.exe)?(?=$|\s|")/i;class J$ extends Error{activeHosts;constructor($){let Z=$.map((z)=>({pid:z.pid,command:t5.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
|
|
17
|
+
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=Z,this.name="ProcessFenceViolationError"}}var LZ={"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 s1(){return($)=>$}var X$=["opencode","pi"],PZ=new Set(["enrolled","not-enrolled","unknown"]),n7=s1()(["auth-content-refused","host-auth-invalid","primary-conflict","consent-required","primary-unverified","no-read-grant","grant-reaches-nothing"]),i7=s1()(["enrollment-refused","enrollment-reset","approval-refused","permission-refused"]),o7=s1()(["invalid-source","unsafe-source","consent-required","primary-unverified","migration-busy","ownership-lost","retirement-refused","pool-populated","host-login-present","settings-changed"]),r7=s1()(["invalid-options","invalid-auth","invalid-stash","unsafe-path","missing-stash","conflict","lock-timeout","lock-compromised","io"]),t7=s1()(["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"]),CZ={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([...n7,...i7,...o7,...r7,...t7,"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",...MZ]),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"])},OZ=new Set([...n7.flatMap(($)=>$==="no-read-grant"||$==="grant-reaches-nothing"?X$.map((Z)=>new W0($,Z).message):[new W0($).message]),...i7.map(($)=>new s0($).message),...o7.map(($)=>new FZ($).message),...r7.map(($)=>new BZ($).message),...t7.map(($)=>`Native custody refused: ${$}`),s7,VZ,...HZ,...jZ,"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"]),AZ=Object.values(n0).join("|"),_Z="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",IZ=[new RegExp(`^Claustrum approval is still pending\\. In another terminal, run: ck auth enroll approve --request-id [A-Za-z0-9_-]{1,128} --name (?:${AZ}) 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\.$/],RZ=new Set(["opencode","litecode","opencode2","pi","host"]),SZ=64,TZ=256,kZ=4096,z$=65536,EZ=4096,bZ=3,c7="[output beyond the diagnostic limit omitted]",fZ="[output withheld: no line break within the inspected window]",xZ="[detail withheld: the known credentials could not be read safely]",Q$=new TextEncoder,e7=new TextDecoder;function f($,Z){let J=Object.getOwnPropertyDescriptor($,Z);return J!==void 0&&"value"in J?J.value:void 0}function O0($){return $!==null&&(typeof $==="object"||typeof $==="function")&&!G$.isProxy($)}function W$($,Z){if(!O0($)||!Array.isArray($))return;let J=f($,"length");if(typeof J!=="number"||J>Z)return;let z=[];for(let X=0;X<J;X+=1){let G=Object.getOwnPropertyDescriptor($,String(X));if(G===void 0||!("value"in G))return;z.push(G.value)}return z}function yZ($){let Z=W$($,SZ);if(Z===void 0||Z.length===0)return;let J=[];for(let z of Z){if(!O0(z))return;let X=f(z,"pid"),G=f(z,"command");if(typeof X!=="number"||!Number.isSafeInteger(X)||X<0)return;if(typeof G!=="string"||!RZ.has(G.toLowerCase()))return;J.push({pid:X,command:G})}return J}function n1($){try{if(!O0($))return;if(f($,"name")==="ProcessInspectionError")return"";let Z=f($,"message");if(typeof Z!=="string")return;if(f($,"name")==="HostNotEnrolledError"&&Z===_Z)return Z;if(OZ.has(Z))return Z;if(f($,"name")==="StateLayoutRefusalError"){let X=f($,"code");if(qZ(X))return NZ(X)}if(f($,"name")==="NativeVaultActivationError"&&f($,"code")==="no-read-grant"){let X=f($,"host"),G=f($,"approvedName");if((X==="opencode"||X==="pi")&&typeof G==="string"){let Q=new W0("no-read-grant",X,G).message;if(Z===Q)return Q}}if(Z.startsWith("Unknown setup argument: "))return Z;if(f($,"name")==="HostNotEnrolledError"&&IZ.some((X)=>X.test(Z)))return Z;if(f($,"code")==="ERR_PRIVATE_FILES_UNAVAILABLE")return s7;let J=f($,"status");if(typeof J==="number"&&Number.isInteger(J)&&J>=100&&J<=599&&Z===`OAuth metadata read failed: ${J}`)return Z;let z=yZ(f($,"activeHosts"));if(z){let X=new J$(z).message;if(Z===X)return X}}catch{}return}function $4($){try{if(!O0($))return;let Z=W$(DZ($),X$.length);if(Z===void 0)return;let J=[];for(let z of Z){if(!O0(z))return;let X=X$.find((Q)=>Q===f(z,"host")),G=f(z,"outcome");if(X===void 0||!PZ.has(G))return;J.push({host:X,outcome:G})}return J}catch{return}}function gZ($,Z=[]){try{let J=new Set,z=W$(Z,TZ);if(z===void 0)return;for(let G of z){if(typeof G!=="string")return;if(G!=="")J.add(G)}if(!O0($))return;let X=Reflect.ownKeys($);if(X.length>kZ)return;for(let G of X){if(typeof G!=="string"||!KZ(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 vZ($,Z){let J=Q$.encode($);if(J.length<=Z)return $;let z=Math.max(0,Z);while(z>0&&((J[z]??0)&192)===128)z-=1;return e7.decode(J.subarray(0,z))}function mZ($,Z){let J=Q$.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 e7.decode(J.subarray(z))}function wZ($,Z,J){let z=$,X=!1;if($.length>z$){if(X=!0,J==="tail"){let Y=$.indexOf(`
|
|
18
18
|
`,$.length-z$);z=Y===-1?"":$.slice(Y+1)}else{let Y=$.lastIndexOf(`
|
|
19
|
-
`,z$);z=Y===-1?"":$.slice(0,Y)}if(z==="")return[
|
|
19
|
+
`,z$);z=Y===-1?"":$.slice(0,Y)}if(z==="")return[fZ]}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=EZ;for(let Y of G){let H=Q$.encode(Y).length+1;if(H<=W){Q.push(Y),W-=H;continue}if(Q.length===0)Q.push(J==="tail"?mZ(Y,W-1):vZ(Y,W-1));X=!0;break}if(J==="tail")Q.reverse();if(X)if(J==="tail")Q.unshift(c7);else Q.push(c7);return Q}function Z4($){let Z=$;for(let J=0;Z!==null&&J<8;J+=1){if(G$.isProxy(Z))break;let z=f(Z,"name");if(typeof z==="string")return z;Z=Object.getPrototypeOf(Z)}return"object"}function p7($,Z){let J={};if(Z===void 0)return J;try{if(!O0($))return J;let z=a7(Z);try{for(let X of["name","code","stage","reason"]){let G=X==="name"?Z4($):f($,X);if(typeof G==="string"&&CZ[X].has(G)&&z.redactText(G)===G)J[X]=G}}finally{z.dispose()}}catch{return{}}return J}function hZ($){if(!O0($))return;let Z=f($,"step"),J=f($,"exitCode"),z=f($,"signal"),X=f($,"stderrTail");if(typeof Z!=="string"||Z.length===0||!(J===null||typeof J==="number"&&Number.isInteger(J))||!(z===null||typeof z==="string")||typeof X!=="string")return;return{step:Z,exitCode:J,signal:z,stderrTail:X}}function J4($,Z){if($===null||typeof $!=="object"&&typeof $!=="function")return[`thrown ${typeof $}: ${String($)}`];if(G$.isProxy($))return["thrown proxy (not inspected)"];let J=[],z=Z4($),X=f($,"message");J.push(typeof X==="string"?`${z}: ${X}`:`${z} (no message)`);let G=f($,"code");if(typeof G==="string"||typeof G==="number")J.push(`code: ${G}`);let Q=f($,"stack");if(typeof Q==="string")J.push(Q);let W=f($,"cause");if(W!==void 0)if(Z>=bZ)J.push("caused by: [not described]");else J.push("caused by:",...J4(W,Z+1));return J}function d7($,Z){let J=f($,Z);return typeof J==="string"&&J!==""?J:void 0}function uZ($){if(!O0($))return;let Z=d7($,"HOME"),J=GZ({xdgStateHome:d7($,"XDG_STATE_HOME"),home:Z&&XZ(Z)?Z:zZ()});return l7(J,"diagnostics")}async function cZ($,Z,J,z={}){let X=(G)=>({error:{name:"DiagnosticFileError",code:G}});try{let G=uZ($);if(G===void 0)return X("ERR_DIAGNOSTICS_DIRECTORY_UNAVAILABLE");if(!await WZ(G,z)){await ZZ(G,{recursive:!0,mode:448});let Y=await $Z(G);if(!Y.isDirectory())return X("ERR_DIAGNOSTICS_NOT_DIRECTORY");if(!await UZ(G,()=>(Y.mode&63)===0&&Y.uid===process.getuid?.(),z))return X("ERR_DIAGNOSTICS_NOT_OWNER_ONLY")}let Q=l7(G,`${Z}-${Date.now()}-${process.pid}-${e5()}.log`);if(await QZ(Q,J,z))return{path:Q};let W=await JZ(Q,A3.O_WRONLY|A3.O_CREAT|A3.O_EXCL|(A3.O_NOFOLLOW??0),384);try{await W.writeFile(J,"utf8")}finally{await W.close()}return{path:Q}}catch(G){return{error:G}}}async function pZ($,Z,J,z,X,G,Q,W={}){let Y,H=gZ(J,z);if(H===void 0)Y=[xZ];else try{let N=a7(H);try{let{text:P,keep:C}=G();Y=wZ(P,N,C)}finally{N.dispose()}}catch{Y=["[failure detail could not be recorded]"]}let U=LZ[$],K=YZ("error","cli",`${U} failed`,{stage:$,code:Z,...X}),F=await cZ(J,$,`${[K,...Y].join(`
|
|
20
20
|
`)}
|
|
21
|
-
`,W.ownership),F
|
|
22
|
-
`)}catch{}}return
|
|
21
|
+
`,W.ownership),B=F.path;if(B===void 0){let N={error:p7(Q,H),saveError:p7(F.error,H)};try{(W.stderr??((C)=>process.stderr.write(C)))(`CLI failure metadata: ${JSON.stringify(N)}
|
|
22
|
+
`)}catch{}}return B===void 0?`${U} failed (${Z}). Details could not be saved to a private diagnostics file.`:`${U} failed (${Z}). Details were written to ${B}`}async function r0($,Z,J,z=[],X={}){let G=n1(Z);if(G!==void 0)return G;let Q=hZ(Z);return pZ($,`${$}/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
|
-
`),
|
|
27
|
-
`),
|
|
28
|
-
`){if(G)z+=
|
|
29
|
-
`){if(X&&
|
|
30
|
-
`)}var
|
|
31
|
-
`),G=0,Q=$;for(let Y of X){if(Q<=Y.length)break;Q-=Y.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 Y=0;Y<G;Y++)W+=X[Y].length+1;return W+Q}var
|
|
24
|
+
`),keep:"head"}),Z,X)}import{assertHostsStopped as Kz,createProcessFence as i4,decideOpenCodeStateLayoutOnce as qz,decidePiStateLayout as Fz,isVaultHosted as Bz,NativePiAuthSlotError as Vz,openNativePiAuthSlot as Mz,publishNativeEmptyInit as jz,readNativeEnrollmentMode as Dz,releaseNativeMigrationPreflight as Nz,requireNoSupervisedAuthContentSnapshot as Lz,restoreLegacyLayout as Pz,runSetup as Cz,StateLayoutRefusalError as Oz,setupUsage as Az,VAULT_HOST_CONNECT_REFUSAL as _z}from"@cortexkit/anthropic-auth-core";import{AsyncLocalStorage as z4}from"node:async_hooks";var lY=new z4,aY=new z4;var X4=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});var _1="commonAuthPool";var KJ=Object.freeze(["version","accounts",_1]);var XK=new g0;var k={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 V$($){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 Y={A:"up",B:"down",C:"right",D:"left"}[Q];if(Y)J.push(Y);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 B4=`${String.fromCharCode(27)}\\[[0-9;]*m`,qJ=new RegExp(B4,"g"),FJ=new RegExp(`^${B4}`);function V4($){return $.replace(qJ,"")}function t0($,Z){if(Z<=0)return"";if(V4($).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(FJ);if(W){X+=W[0],G+=W[0].length;continue}}X+=$[G],G+=1,Q+=1}return X.includes("\x1B[")?`${X}${k.reset}${J}`:X+J}function S1($){return $.input.isTTY===!0}var BJ=50;function VJ($){if($==="red")return k.red;if($==="cyan")return k.cyan;return""}async function T3($,Z,J){if(!S1($))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,Y=!1,H=0,U=()=>{let K=X.columns??80,F=X.rows??24,B=H;if(J.clearScreen)X.write(k.clearScreen+k.moveTo(1,1));else if(B>0)X.write(k.up(B));let N=0,P=(q)=>{X.write(`${k.clearLine}${q}
|
|
26
|
+
`),N+=1},C=J.lines??[],I=1+(J.subtitle?3:0)+C.length+(C.length?1:0),T=Math.max(1,Math.min(Z.length,F-I-2-1)),m=Math.max(0,Math.min(Q-Math.floor(T/2),Math.max(0,Z.length-T))),c=Z.slice(m,m+T);if(P(`${k.dim}┌ ${k.reset}${t0(J.message,Math.max(1,K-4))}`),J.subtitle)P(`${k.dim}│${k.reset}`),P(`${k.cyan}◆${k.reset} ${t0(J.subtitle,Math.max(1,K-4))}`),P("");for(let q of C)P(`${k.cyan}│${k.reset} ${t0(q,Math.max(1,K-4))}`);if(C.length)P(`${k.cyan}│${k.reset}`);for(let q=0;q<c.length;q++){let D=c[q];if(!D)continue;let O=m+q===Q,v=VJ(D.color),E=v?`${O?"":k.dim}${v}${D.label}${k.reset}`:O?D.label:`${k.dim}${D.label}${k.reset}`;if(D.hint)E+=` ${k.dim}${D.hint}${k.reset}`;E=t0(E,Math.max(1,K-8)),P(O?`${k.cyan}│${k.reset} ${k.green}●${k.reset} ${E}`:`${k.cyan}│${k.reset} ${k.dim}○${k.reset} ${E}`)}let M=c.length<Z.length?` (${m+1}-${m+c.length}/${Z.length})`:"";P(`${k.cyan}│${k.reset} ${k.dim}${t0(`Up/Down to select | Enter: confirm | Esc: back${M}`,Math.max(1,K-6))}${k.reset}`),P(`${k.cyan}└${k.reset}`);for(let q=N;q<B;q++)P("");H=N};return new Promise((K)=>{let F=z.isRaw??!1,B=()=>{if(Y)return;if(Y=!0,W)clearTimeout(W);z.removeListener("data",C);try{z.setRawMode(F),z.pause(),X.write(k.show)}catch{}G?.removeListener("SIGINT",P),G?.removeListener("SIGTERM",P)},N=(I)=>{B(),K(I)},P=()=>N(null),C=(I)=>{for(let T of V$(I)){if(Y)break;if(W)clearTimeout(W),W=null;switch(T){case"up":Q=(Q-1+Z.length)%Z.length,U();break;case"down":Q=(Q+1)%Z.length,U();break;case"enter":N(Z[Q]?.value??null);break;case"escape":N(null);break;case"escape-start":W=setTimeout(()=>N(null),BJ);break;default:break}}};G?.once("SIGINT",P),G?.once("SIGTERM",P);try{z.setRawMode(!0)}catch{B(),K(null);return}z.resume(),X.write(k.hide),U(),z.on("data",C)})}async function k3($,Z,J=!1){if(!S1($))return!1;return await T3($,J?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:Z})??!1}import{execFile as PJ}from"node:child_process";import{promisify as CJ}from"node:util";var OJ=CJ(PJ),M$={async run($,Z,J={}){try{let z={...process.env,...J.env};delete z.CORTEXKIT_VAULT_HOST;let{stdout:X,stderr:G}=await OJ($,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 g3}from"node:util";import{stdout as hJ,stdin as uJ}from"node:process";import cJ from"node:readline";var M4=(()=>{let $=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(Z)=>{let J=0;$.lastIndex=0;while($.test(Z))J+=1;return Z.length-J}})(),j4=($)=>{return $===12288||$>=65281&&$<=65376||$>=65504&&$<=65510},D4=($)=>{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 AJ=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,_J=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,N4=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,IJ=/\t{1,1000}/y,L4=/[\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,RJ=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,SJ=/\p{M}+/gu,TJ={limit:1/0,ellipsis:""},P4=($,Z={},J={})=>{let z=Z.limit??1/0,X=Z.ellipsis??"",G=Z?.ellipsisWidth??(X?P4(X,TJ,J).width:0),Q=0,W=J.controlWidth??0,Y=J.tabWidth??8,H=J.emojiWidth??2,U=2,K=J.regularWidth??1,F=J.wideWidth??2,B=[[RJ,K],[AJ,0],[_J,W],[IJ,Y],[L4,H],[N4,F]],N=0,P=0,C=$.length,I=0,T=!1,m=C,c=Math.max(0,z-G),M=0,q=0,D=0,O=0;$:while(!0){if(q>M||P>=C&&P>N){let v=$.slice(M,q)||$.slice(N,P);I=0;for(let E of v.replaceAll(SJ,"")){let x=E.codePointAt(0)||0;if(j4(x))O=2;else if(D4(x))O=F;else O=K;if(D+O>c)m=Math.min(m,Math.max(M,N)+I);if(D+O>z){T=!0;break $}I+=E.length,D+=O}M=q=0}if(P>=C)break $;for(let v=0,E=B.length;v<E;v++){let[x,$0]=B[v];if(x.lastIndex=P,x.test($)){if(I=x===N4?M4($.slice(P,x.lastIndex)):x===L4?1:x.lastIndex-P,O=I*$0,D+O>c)m=Math.min(m,P+Math.floor((c-D)/$0));if(D+O>z){T=!0;break $}D+=O,M=N,q=P,P=N=x.lastIndex;continue $}}P+=1}return{width:T?c:D,index:T?m:C,truncated:T,ellipsed:T&&z>=G}},C4=P4;var kJ={limit:1/0,ellipsis:"",ellipsisWidth:0},EJ=($,Z={})=>{return C4($,kJ,Z).width},B0=EJ;var E3="\x1B",R4="",bJ=39,D$="\x07",S4="[",fJ="]",T4="m",N$=`${fJ}8;;`,O4=new RegExp(`(?:\\${S4}(?<code>\\d+)m|\\${N$}(?<uri>.*)${D$})`,"y"),A4=($)=>{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},_4=($)=>`${E3}${S4}${$}${T4}`,I4=($)=>`${E3}${N$}${$}${D$}`,j$=($,Z,J)=>{let z=Z[Symbol.iterator](),X=!1,G=!1,Q=$.at(-1),W=Q===void 0?0:B0(Q),Y=z.next(),H=z.next(),U=0;while(!Y.done){let K=Y.value,F=B0(K);if(W+F<=J)$[$.length-1]+=K;else $.push(K),W=0;if(K===E3||K===R4)X=!0,G=Z.startsWith(N$,U+1);if(X){if(G){if(K===D$)X=!1,G=!1}else if(K===T4)X=!1}else if(W+=F,W===J&&!H.done)$.push(""),W=0;Y=H,H=z.next(),U+=K.length}if(Q=$.at(-1),!W&&Q!==void 0&&Q.length&&$.length>1)$[$.length-2]+=$.pop()},xJ=($)=>{let Z=$.split(" "),J=Z.length;while(J){if(B0(Z[J-1]))break;J--}if(J===Z.length)return $;return Z.slice(0,J).join(" ")+Z.slice(J).join("")},yJ=($,Z,J={})=>{if(J.trim!==!1&&$.trim()==="")return"";let z="",X,G,Q=$.split(" "),W=[""],Y=0;for(let K=0;K<Q.length;K++){let F=Q[K];if(J.trim!==!1){let N=W.at(-1)??"",P=N.trimStart();if(N.length!==P.length)W[W.length-1]=P,Y=B0(P)}if(K!==0){if(Y>=Z&&(J.wordWrap===!1||J.trim===!1))W.push(""),Y=0;if(Y||J.trim===!1)W[W.length-1]+=" ",Y++}let B=B0(F);if(J.hard&&B>Z){let N=Z-Y,P=1+Math.floor((B-N-1)/Z);if(Math.floor((B-1)/Z)<P)W.push("");j$(W,F,Z),Y=B0(W.at(-1)??"");continue}if(Y+B>Z&&Y&&B){if(J.wordWrap===!1&&Y<Z){j$(W,F,Z),Y=B0(W.at(-1)??"");continue}W.push(""),Y=0}if(Y+B>Z&&J.wordWrap===!1){j$(W,F,Z),Y=B0(W.at(-1)??"");continue}W[W.length-1]+=F,Y+=B}if(J.trim!==!1)W=W.map((K)=>xJ(K));let H=W.join(`
|
|
27
|
+
`),U=!1;for(let K=0;K<H.length;K++){let F=H[K];if(z+=F,!U){if(U=F>="\uD800"&&F<="\uDBFF",U)continue}else U=!1;if(F===E3||F===R4){O4.lastIndex=K+1;let N=O4.exec(H)?.groups;if(N?.code!==void 0){let P=Number.parseFloat(N.code);X=P===bJ?void 0:P}else if(N?.uri!==void 0)G=N.uri.length===0?void 0:N.uri}if(H[K+1]===`
|
|
28
|
+
`){if(G)z+=I4("");let B=X?A4(X):void 0;if(X&&B)z+=_4(B)}else if(F===`
|
|
29
|
+
`){if(X&&A4(X))z+=_4(X);if(G)z+=I4(G)}}return z},gJ=/\r?\n/;function b3($,Z,J){return String($).normalize().split(gJ).map((z)=>yJ(z,Z,J)).join(`
|
|
30
|
+
`)}var G0=f4(P$(),1);function O$($,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?O$(G,Z<0?-1:1,J):G}function f3($,Z,J,z){let X=z.split(`
|
|
31
|
+
`),G=0,Q=$;for(let Y of X){if(Q<=Y.length)break;Q-=Y.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 Y=0;Y<G;Y++)W+=X[Y].length+1;return W+Q}var pJ=["up","down","left","right","space","enter","cancel"],dJ=["January","February","March","April","May","June","July","August","September","October","November","December"],Y0={actions:new Set(pJ),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:[...dJ],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 lJ($){if($!==void 0)return $;if(Y0.accessible!==void 0)return Y0.accessible;let Z=process.env.ACCESSIBLE;return Z!==void 0&&Z!==""&&Z!=="0"&&Z!=="false"}function x4($,Z){if(typeof $=="string")return Y0.aliases.get($)===Z;for(let J of $)if(J!==void 0&&x4(J,Z))return!0;return!1}function aJ($,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
|
|
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 UF=globalThis.process.platform.startsWith("win"),v3=Symbol("clack:cancel");function m3($){return $===v3}function x3($,Z){let J=$;J.isTTY&&J.setRawMode(Z)}var y4=($)=>("rows"in $)&&typeof $.rows=="number"?$.rows:20;function g4($,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 T1{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return lJ(this.opts.accessible)}constructor($,Z=!0){let{input:J=uJ,output:z=hJ,render:X,signal:G,...Q}=$;this.opts=Q,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=X.bind(this),this._track=Z,this._abortSignal=G,this.input=J,this.output=z}unsubscribe(){this._subscribers.clear()}setSubscriber($,Z){let J=this._subscribers.get($)??[];J.push(Z),this._subscribers.set($,J)}on($,Z){this.setSubscriber($,{cb:Z})}once($,Z){this.setSubscriber($,{cb:Z,once:!0})}emit($,...Z){let J=this._subscribers.get($)??[],z=[];for(let X of J)X.cb(...Z),X.once&&z.push(()=>J.splice(J.indexOf(X),1));for(let X of z)X()}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(v3);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=cJ.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),x3(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(G0.cursor.show),this.output.off("resize",this.render),x3(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(G0.cursor.show),this.output.off("resize",this.render),x3(this.input,!1),$(v3)})})}_isActionKey($,Z){return $==="\t"}_shouldSubmit($,Z){return!0}_setValue($){this.value=$,this.emit("value",this.value)}_setUserInput($,Z){this.userInput=$??"",this.emit("userInput",this.userInput),Z&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}async onKeypress($,Z){if(this.state!=="validating"){if(this._track&&Z.name!=="return"&&(Z.name&&this._isActionKey($,Z)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),Z?.name&&(!this._track&&Y0.aliases.has(Z.name)&&this.emit("cursor",Y0.aliases.get(Z.name)),Y0.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=g4(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")}x4([$,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
34
|
`),x3(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let $=b3(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
35
|
-
`).length-1;this.output.write(
|
|
36
|
-
`);this.output.write(Q[G]),this._prevFrame=$,this.output.write(
|
|
35
|
+
`).length-1;this.output.write(G0.cursor.move(-999,$*-1))}render(){let $=b3(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if($!==this._prevFrame){if(this.state==="initial")this.output.write(G0.cursor.hide);else{let Z=aJ(this._prevFrame,$),J=y4(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(G0.cursor.move(0,G-X)),this.output.write(G0.erase.lines(1));let Q=$.split(`
|
|
36
|
+
`);this.output.write(Q[G]),this._prevFrame=$,this.output.write(G0.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(G0.cursor.move(0,W))}this.output.write(G0.erase.down());let Q=$.split(`
|
|
37
37
|
`).slice(G);this.output.write(Q.join(`
|
|
38
|
-
`)),this._prevFrame=$;return}}this.output.write(X0.erase.down())}this.output.write($),this.state==="initial"&&(this.state="active"),this._prevFrame=$}}}function lJ($,Z){if($===void 0||Z.length===0)return 0;let J=Z.findIndex((z)=>z.value===$);return J!==-1?J:0}function aJ($,Z){return(Z.label??String(Z.value)).toLowerCase().includes($.toLowerCase())}function sJ($,Z){if(Z)return $?Z:Z[0]}var nJ=class extends T1{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Z="";#z;#Y;#G;#Q;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return g3(["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}${g3("inverse",J)}${z}`}get options(){return typeof this.#Y=="function"?this.#Y():this.#Y}constructor(Z){super(Z),this.#Y=Z.options,this.#G=Z.placeholder,this.#Q=Z.completeOnTab===!0;let J=this.options;this.filteredOptions=[...J],this.multiple=Z.multiple===!0,this.#z=typeof Z.options=="function"?Z.filter:Z.filter??aJ;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.#J(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,Y=this.options,U=W!==void 0&&W!==""&&Y.some((H)=>!H.disabled&&(this.#z?this.#z(W,H):!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 H=String(this.focusedValue);this._clearUserInput(),this._setUserInput(H,!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=sJ(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])}#J(Z){if(Z!==this.#Z){this.#Z=Z;let J=this.options;Z&&this.#z?this.filteredOptions=J.filter((G)=>this.#z?.(Z,G)):this.filteredOptions=[...J];let z=lJ(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 iJ={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function S4($){return[...$].map((Z)=>iJ[Z])}function oJ($){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 C$($){return Number.parseInt(($||"0").replace(/_/g,"0"),10)||0}function y3($){return{year:C$($.year),month:C$($.month),day:C$($.day)}}function A$($,Z){return new Date($||2001,Z||1,0).getDate()}function x4($){let{year:Z,month:J,day:z}=y3($);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 T4($){let Z=x4($);return Z?new Date(Date.UTC(Z.year,Z.month-1,Z.day)):void 0}function rJ($,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:A$(Z.year,Z.month)}}class y4 extends T1{#$;#Z;#z;#Y;#G;#Q={segmentIndex:0,positionInSegment:0};#X=!0;#J=null;inlineError="";get segmentCursor(){return{...this.#Q}}get segmentValues(){return{...this.#z}}get segments(){return this.#$}get separator(){return this.#Z}get formattedValue(){return this.#H(this.#z)}#H($){return this.#$.map((Z)=>$[Z.type]).join(this.#Z)}#W(){this._setUserInput(this.#H(this.#z)),this._setValue(T4(this.#z)??void 0)}constructor($){let Z=$.format?{segments:S4($.format),separator:$.separator??"/"}:oJ($.locale),J=$.separator??Z.separator,z=$.format?S4($.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.#z=G,this.#Y=$.minDate,this.#G=$.maxDate,this.#W(),this.on("cursor",(W)=>this.#q(W)),this.on("key",(W,Y)=>this.#V(W,Y)),this.on("finalize",()=>this.#C($))}#U(){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.#J=null;let Z=this.#U();Z&&(this.#Q.segmentIndex=Math.max(0,Math.min(this.#$.length-1,Z.index+$)),this.#Q.positionInSegment=0,this.#X=!0)}#B($){let Z=this.#U();if(!Z)return;let{segment:J}=Z,z=this.#z[J.type],X=!z||z.replace(/_/g,"")==="",G=Number.parseInt((z||"0").replace(/_/g,"0"),10)||0,Q=rJ(J.type,y3(this.#z),this.#Y,this.#G),W;X?W=$===1?Q.min:Q.max:W=Math.max(Math.min(Q.max,G+$),Q.min),this.#z={...this.#z,[J.type]:W.toString().padStart(J.len,"0")},this.#X=!0,this.#J=null,this.#W()}#q($){if($)switch($){case"right":return this.#K(1);case"left":return this.#K(-1);case"up":return this.#B(1);case"down":return this.#B(-1)}}#V($,Z){if(Z?.name==="backspace"||Z?.sequence===""||Z?.sequence==="\b"||$===""||$==="\b"){this.inlineError="";let J=this.#U();if(!J)return;if(!this.#z[J.segment.type].replace(/_/g,"")){this.#K(-1);return}this.#z[J.segment.type]="_".repeat(J.segment.len),this.#X=!0,this.#Q.positionInSegment=0,this.#W();return}if(Z?.name==="tab"){this.inlineError="";let J=this.#U();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.#U();if(!J)return;let{segment:z}=J,X=!this.#z[z.type].replace(/_/g,"");if(this.#X&&this.#J!==null&&!X){let M=this.#J+$,F={...this.#z,[z.type]:M},L=this.#D(F,z);if(L){this.inlineError=L,this.#J=null,this.#X=!1;return}this.inlineError="",this.#z[z.type]=M,this.#J=null,this.#X=!1,this.#W(),J.index<this.#$.length-1&&(this.#Q.segmentIndex=J.index+1,this.#Q.positionInSegment=0,this.#X=!0);return}this.#X&&!X&&(this.#z[z.type]="_".repeat(z.len),this.#Q.positionInSegment=0),this.#X=!1,this.#J=null;let G=this.#z[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 Y=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);Y=`0${$}`,U=M<=(z.type==="month"?1:2)}if(z.type==="year"&&(Y=(G.replace(/_/g,"")+$).padStart(z.len,"_")),!Y.includes("_")){let M={...this.#z,[z.type]:Y},F=this.#D(M,z);if(F){this.inlineError=F;return}}this.inlineError="",this.#z[z.type]=Y;let H=Y.includes("_")?void 0:x4(this.#z);if(H){let{year:M,month:F}=H,L=A$(M,F);this.#z={year:String(Math.max(0,Math.min(9999,M))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,F))).padStart(2,"0"),day:String(Math.max(1,Math.min(L,H.day))).padStart(2,"0")}}this.#W();let K=Y.indexOf("_");U?(this.#X=!0,this.#J=$):K>=0?this.#Q.positionInSegment=K: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)}}#D($,Z){let{month:J,day:z}=y3($);if(Z.type==="month"&&(J<0||J>12))return W0.date.messages.invalidMonth;if(Z.type==="day"&&(z<0||z>31))return W0.date.messages.invalidDay(31,"any month")}#C($){let{year:Z,month:J,day:z}=y3(this.#z);if(Z&&J&&z){let X=A$(Z,J);this.#z={...this.#z,day:String(Math.min(z,X)).padStart(2,"0")}}this.value=T4(this.#z)??$.defaultValue??void 0}}var tJ=class extends T1{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}})}},eJ=new Set(["up","down","left","right"]);class g4 extends T1{#$=!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(G0.erase.down())}this.output.write($),this.state==="initial"&&(this.state="active"),this._prevFrame=$}}}function sJ($,Z){if($===void 0||Z.length===0)return 0;let J=Z.findIndex((z)=>z.value===$);return J!==-1?J:0}function nJ($,Z){return(Z.label??String(Z.value)).toLowerCase().includes($.toLowerCase())}function iJ($,Z){if(Z)return $?Z:Z[0]}var oJ=class extends T1{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Z="";#z;#Y;#G;#Q;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return g3(["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}${g3("inverse",J)}${z}`}get options(){return typeof this.#Y=="function"?this.#Y():this.#Y}constructor(Z){super(Z),this.#Y=Z.options,this.#G=Z.placeholder,this.#Q=Z.completeOnTab===!0;let J=this.options;this.filteredOptions=[...J],this.multiple=Z.multiple===!0,this.#z=typeof Z.options=="function"?Z.filter:Z.filter??nJ;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.#J(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,Y=this.options,H=W!==void 0&&W!==""&&Y.some((U)=>!U.disabled&&(this.#z?this.#z(W,U):!0));if(J.name==="tab"&&Q&&H){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 U=String(this.focusedValue);this._clearUserInput(),this._setUserInput(U,!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=iJ(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])}#J(Z){if(Z!==this.#Z){this.#Z=Z;let J=this.options;Z&&this.#z?this.filteredOptions=J.filter((G)=>this.#z?.(Z,G)):this.filteredOptions=[...J];let z=sJ(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 rJ={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function E4($){return[...$].map((Z)=>rJ[Z])}function tJ($){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 C$($){return Number.parseInt(($||"0").replace(/_/g,"0"),10)||0}function y3($){return{year:C$($.year),month:C$($.month),day:C$($.day)}}function A$($,Z){return new Date($||2001,Z||1,0).getDate()}function v4($){let{year:Z,month:J,day:z}=y3($);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 b4($){let Z=v4($);return Z?new Date(Date.UTC(Z.year,Z.month-1,Z.day)):void 0}function eJ($,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:A$(Z.year,Z.month)}}class m4 extends T1{#$;#Z;#z;#Y;#G;#Q={segmentIndex:0,positionInSegment:0};#X=!0;#J=null;inlineError="";get segmentCursor(){return{...this.#Q}}get segmentValues(){return{...this.#z}}get segments(){return this.#$}get separator(){return this.#Z}get formattedValue(){return this.#H(this.#z)}#H($){return this.#$.map((Z)=>$[Z.type]).join(this.#Z)}#W(){this._setUserInput(this.#H(this.#z)),this._setValue(b4(this.#z)??void 0)}constructor($){let Z=$.format?{segments:E4($.format),separator:$.separator??"/"}:tJ($.locale),J=$.separator??Z.separator,z=$.format?E4($.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.#z=G,this.#Y=$.minDate,this.#G=$.maxDate,this.#W(),this.on("cursor",(W)=>this.#K(W)),this.on("key",(W,Y)=>this.#j(W,Y)),this.on("finalize",()=>this.#O($))}#q(){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:$}}#F($){this.inlineError="",this.#J=null;let Z=this.#q();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.#q();if(!Z)return;let{segment:J}=Z,z=this.#z[J.type],X=!z||z.replace(/_/g,"")==="",G=Number.parseInt((z||"0").replace(/_/g,"0"),10)||0,Q=eJ(J.type,y3(this.#z),this.#Y,this.#G),W;X?W=$===1?Q.min:Q.max:W=Math.max(Math.min(Q.max,G+$),Q.min),this.#z={...this.#z,[J.type]:W.toString().padStart(J.len,"0")},this.#X=!0,this.#J=null,this.#W()}#K($){if($)switch($){case"right":return this.#F(1);case"left":return this.#F(-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.#q();if(!J)return;if(!this.#z[J.segment.type].replace(/_/g,"")){this.#F(-1);return}this.#z[J.segment.type]="_".repeat(J.segment.len),this.#X=!0,this.#Q.positionInSegment=0,this.#W();return}if(Z?.name==="tab"){this.inlineError="";let J=this.#q();if(!J)return;let z=Z.shift?-1:1,X=J.index+z;X>=0&&X<this.#$.length&&(this.#Q.segmentIndex=X,this.#Q.positionInSegment=0,this.#X=!0);return}if($&&/^[0-9]$/.test($)){let J=this.#q();if(!J)return;let{segment:z}=J,X=!this.#z[z.type].replace(/_/g,"");if(this.#X&&this.#J!==null&&!X){let F=this.#J+$,B={...this.#z,[z.type]:F},N=this.#B(B,z);if(N){this.inlineError=N,this.#J=null,this.#X=!1;return}this.inlineError="",this.#z[z.type]=F,this.#J=null,this.#X=!1,this.#W(),J.index<this.#$.length-1&&(this.#Q.segmentIndex=J.index+1,this.#Q.positionInSegment=0,this.#X=!0);return}this.#X&&!X&&(this.#z[z.type]="_".repeat(z.len),this.#Q.positionInSegment=0),this.#X=!1,this.#J=null;let G=this.#z[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 Y=G.slice(0,W)+$+G.slice(W+1),H=!1;if(W===0&&G==="__"&&(z.type==="month"||z.type==="day")){let F=Number.parseInt($,10);Y=`0${$}`,H=F<=(z.type==="month"?1:2)}if(z.type==="year"&&(Y=(G.replace(/_/g,"")+$).padStart(z.len,"_")),!Y.includes("_")){let F={...this.#z,[z.type]:Y},B=this.#B(F,z);if(B){this.inlineError=B;return}}this.inlineError="",this.#z[z.type]=Y;let U=Y.includes("_")?void 0:v4(this.#z);if(U){let{year:F,month:B}=U,N=A$(F,B);this.#z={year:String(Math.max(0,Math.min(9999,F))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,B))).padStart(2,"0"),day:String(Math.max(1,Math.min(N,U.day))).padStart(2,"0")}}this.#W();let K=Y.indexOf("_");H?(this.#X=!0,this.#J=$):K>=0?this.#Q.positionInSegment=K: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)}}#B($,Z){let{month:J,day:z}=y3($);if(Z.type==="month"&&(J<0||J>12))return Y0.date.messages.invalidMonth;if(Z.type==="day"&&(z<0||z>31))return Y0.date.messages.invalidDay(31,"any month")}#O($){let{year:Z,month:J,day:z}=y3(this.#z);if(Z&&J&&z){let X=A$(Z,J);this.#z={...this.#z,day:String(Math.min(z,X)).padStart(2,"0")}}this.value=b4(this.#z)??$.defaultValue??void 0}}var $z=class extends T1{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}})}},Zz=new Set(["up","down","left","right"]);class w4 extends T1{#$=!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
40
|
${z}`:`${Z}${g3("inverse",J)}${z}`}get cursor(){return this._cursor}#z($){if(this.userInput.length===0){this._setUserInput($);return}this._setUserInput(this.userInput.slice(0,this.cursor)+$+this.userInput.slice(this.cursor))}#Y($){let Z=this.value??"";switch($){case"up":this._cursor=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.#z(`
|
|
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.#z(`
|
|
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?y("inverse",$.placeholder[0])+y("dim",$.placeholder.slice(1)):y(["inverse","hidden"],"_"),X=this.userInput?this.userInputWithCursor:z,G=this.value??"";switch(this.state){case"validating":{let Q=Z?`${y("cyan",e0)} `:"",W=Z?y("cyan",I$):"",Y=y("dim",X),
|
|
46
|
-
${W} ${
|
|
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&&Zz.has(z.name)){this.#$=!1,this.#Y(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.#z(J??""),this._cursor++)}}),this.on("userInput",(J)=>{this._setValue(J)}),this.on("finalize",()=>{this.value||(this.value=$.defaultValue),this.value===void 0&&(this.value="")})}}class _$ extends T1{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}${g3("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 y,stripVTControlCharacters as OF}from"node:util";import H0 from"node:process";var u4=f4(P$(),1);function Jz(){if(H0.platform!=="win32")return H0.env.TERM!=="linux";return Boolean(H0.env.CI)||Boolean(H0.env.WT_SESSION)||Boolean(H0.env.TERMINUS_SUBLIME)||H0.env.ConEmuTask==="{cmd::Cmder}"||H0.env.TERM_PROGRAM==="Terminus-Sublime"||H0.env.TERM_PROGRAM==="vscode"||H0.env.TERM==="xterm-256color"||H0.env.TERM==="alacritty"||H0.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var zz=Jz();var g=($,Z)=>zz?$:Z,h4=g("◆","*"),Xz=g("■","x"),Gz=g("▲","x"),Qz=g("◇","o"),RF=g("┌","T"),e0=g("│","|"),I$=g("└","—"),SF=g("┐","T"),TF=g("┘","—"),kF=g("●",">"),EF=g("○"," "),bF=g("◻","[•]"),fF=g("◼","[+]"),xF=g("◻","[ ]"),yF=g("▪","•"),gF=g("─","-"),vF=g("╮","+"),mF=g("├","+"),wF=g("╯","+"),hF=g("╰","+"),uF=g("╭","+"),cF=g("●","•"),pF=g("◆","*"),dF=g("▲","!"),lF=g("■","x"),Wz=($)=>{switch($){case"initial":case"active":return y("cyan",h4);case"cancel":return y("red",Xz);case"error":return y("yellow",Gz);case"submit":return y("green",Qz);case"validating":return y("dim",h4)}};var aF=[`${y("dim","↑/↓")} to navigate`,`${y("dim","Space:")} select`,`${y("dim","Enter:")} confirm`];var sF={light:g("─","-"),heavy:g("━","="),block:g("█","#")};var nF=[`${y("dim","↑/↓")} to navigate`,`${y("dim","Enter:")} confirm`];var iF=`${y("gray",e0)} `;var c4=($)=>new _$({validate:$.validate,placeholder:$.placeholder,defaultValue:$.defaultValue,initialValue:$.initialValue,output:$.output,signal:$.signal,input:$.input,render(){let Z=$?.withGuide??Y0.withGuide,J=`${`${Z?`${y("gray",e0)}
|
|
44
|
+
`:""}${Wz(this.state)} `}${$.message}
|
|
45
|
+
`,z=$.placeholder&&$.placeholder.length>0?y("inverse",$.placeholder[0])+y("dim",$.placeholder.slice(1)):y(["inverse","hidden"],"_"),X=this.userInput?this.userInputWithCursor:z,G=this.value??"";switch(this.state){case"validating":{let Q=Z?`${y("cyan",e0)} `:"",W=Z?y("cyan",I$):"",Y=y("dim",X),H=y("dim","Validating...");return`${J}${Q}${Y}
|
|
46
|
+
${W} ${H}
|
|
47
47
|
`}case"error":{let Q=this.error?` ${y("yellow",this.error)}`:"",W=Z?`${y("yellow",e0)} `:"",Y=Z?y("yellow",I$):"";return`${J.trim()}
|
|
48
48
|
${W}${X}
|
|
49
49
|
${Y}${Q}
|
|
50
50
|
`}case"submit":{let Q=G?`${Z?" ":""}${y("dim",G)}`:"",W=Z?y("gray",e0):"";return`${J}${W}${Q}`}case"cancel":{let Q=G?` ${y(["strikethrough","dim"],G)}`:"",W=Z?y("gray",e0):"";return`${J}${W}${Q}${G.trim()?`
|
|
51
51
|
${W}`:""}`}default:{let Q=Z?`${y("cyan",e0)} `:"",W=Z?y("cyan",I$):"";return`${J}${Q}${X}
|
|
52
52
|
${W}
|
|
53
|
-
`}}}}).prompt();import{authorize as
|
|
54
|
-
`)}function V0($,Z){let J=$.get(Z);if(!J)throw Error("Missing setup plan");return J}async function
|
|
55
|
-
`);if($.some((q)=>
|
|
53
|
+
`}}}}).prompt();import{authorize as Yz,exchange as Hz,resolveClaudeCodeIdentity as Uz}from"@cortexkit/anthropic-auth-core";async function p4($,Z={authorize:Yz,exchange:Hz,resolveClaudeCodeIdentity:Uz,text:c4,isCancel:m3,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 d4='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.',Iz="npx @cortexkit/opencode-anthropic-auth setup",R$="--remove-pi-auth",h3="--restore-legacy",o4="-y",r4=["--help","-h"],l4=[{label:R$,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:h3,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:o4,description:"Same as --yes."},{label:r4.join(", "),description:"Show this help."}];function Rz(){let $=Math.max(...l4.map((Z)=>Z.label.length));return[Az({command:Iz}),"","Also accepted by this command:",...l4.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 V0($,Z){let J=$.get(Z);if(!J)throw Error("Missing setup plan");return J}async function t4($=[],Z={}){let J={...Z.env??process.env},z=Z.terminal??{input:process.stdin,output:process.stdout,signals:process},X=(q)=>z.output.write(`${q}
|
|
55
|
+
`);if($.some((q)=>r4.includes(q)))return X(Rz()),0;if(Bz())return X(_z),1;if($.includes(h3))return Sz($,Z,J,X);let G=$.filter((q)=>q!==R$).map((q)=>q===o4?"--yes":q),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(w3),1;let W=Z.runner??M$,Y=Z.fence??i4(W,{platform:Z.platform}),H=Z.migrateLocal??v7,U=new Map,K=new Map,F=new Map,B=new Map,N=[],P=!1,C="setup-process-check",I=(q)=>({env:J,fence:Y,paths:F.get(q),removePiAnthropicAuth:B.get(q)??!1}),T=(q)=>({...I(q),runner:W});async function m(q){if(!q.hosts.includes("pi"))return;let D=V0(F,"pi");if((await l1("pi",D.hostAuthPath)).kind==="absent")return;{let x=await Mz({env:J,authPath:D.hostAuthPath}).inspect();if(x.slot==="placeholder"&&x.stash==="missing")throw new Vz("missing-stash");if(q.mode==="claustrum"){if(x.slot==="placeholder")return}}if($.includes(R$)){B.set("pi",!0);return}let v=q.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 r(v);if(!await k3(z,q.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 r("Native account-pool setup cannot finish while the stored Pi OAuth token takes precedence.");B.set("pi",!0)}async function c(q,D){let O=V0(K,q);if(await Dz(q,J)!==(D?"claustrum":O.priorMode)||await a1(q,T(q))!==O.fingerprint)throw new r("Setup inputs changed. Rerun setup with all hosts stopped.")}let M={packages:{opencode:a4,pi:s4},version:await n4(),displayName:"CortexKit Anthropic Auth",slashCommand:"/claude",vault:{connectionFile:d9(J.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE&&!J.OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE?"pi":"opencode",J),hosts:{opencode:{name:n0.opencode,displayName:c9.opencode,requestedGrants:[{selector:{category:"anthropic-native"},operation:"read"}],paths:p9("opencode",J)},pi:{name:n0.pi,displayName:c9.pi,requestedGrants:[{selector:{category:"anthropic-native"},operation:"read"}],paths:p9("pi",J)}}},async beforeSignIn(q,D){if(C=D.mode==="claustrum"?"setup-activation":"cli-setup",!P){if(Lz(J),D.hosts.includes("opencode")){let O=await qz({role:"setup",env:J});if(O.kind!=="state-home"&&O.registration)N.push(O.registration)}for(let O of D.hosts)F.set(O,await C0(O,J));if(await k7([...F.values()]),D.hosts.includes("pi"))N.push((await Fz({paths:V0(F,"pi").paths,role:"setup"})).registration);if(D.mode==="claustrum"){let O=D.hosts.map((E)=>d9(E,J)),v=O[0];if(new Set(O).size!==1||!v)throw new r("Selected hosts use different vault connection files.");M.vault.connectionFile=v}if(D.mode==="local"&&Q&&D.hosts.includes("opencode")&&D.opencodeGeneration==="2")throw new r(w3);if(D.mode==="local"){await i9(D.hosts,J);for(let O of D.hosts)await o0(O,I(O))()}await m(D);for(let O of D.hosts)if(D.mode==="claustrum"){if(K.set(O,await(Z.vaultPreflight??h7)(O,{...T(O),inspectOpenCodeAuth:D.opencodeGeneration!=="2"})),V0(K,O).separateOpenCodeLogin)X(d4)}else U.set(O,await r9(O,I(O),O==="opencode"&&D.opencodeGeneration==="2"));P=!0}else if(D.mode==="claustrum")await c(q,!1);else await A1(V0(U,q),I(q))},async signInLocal(q){let D=V0(U,q);if(!Q){if(D.generation2)X(w3);return}if(await A1(D,I(q)),await H(q,{...I(q),login:Z.localLogin??p4,preflight:D.preflight,skipMigration:D.action==="skip",beforeCommit:()=>A1(D,I(q))}),D.fingerprint=await O3(D,J),D.notice)X(n9)},async beforeRegister(q,D){if(D==="local")await A1(V0(U,q),I(q));else await c(q,!0),await(Z.vaultActivate??u7)(q,T(q),V0(K,q)),V0(K,q).fingerprint=await a1(q,T(q))},async migrate(q,D){if(D.mode==="claustrum"){if(await c(q,!0),q===D.hosts.at(-1)&&K.get("opencode")?.separateOpenCodeLogin)X(d4);return}let O=V0(U,q);if(await A1(O,I(q)),Q)return;if(O.action==="migration")await H(q,{...I(q),preflight:O.preflight});else if(O.action==="empty-init")await jz({paths:O.paths.paths,routingDestinationPath:O.paths.routingDestinationPath,env:J,processFence:o0(q,I(q))});else if(O.action==="skip"){if(await t9(O,I(q)),O.notice)X(n9)}O.fingerprint=await O3(O,J)}};try{return await Cz(M,G,{...Z,env:J,terminal:z,runner:W,fence:Y}),0}catch(q){let O=b7(q)??n1(q)??await r0(C,q,J);if(O)X(O);for(let{host:v,outcome:E}of $4(q)??[]){if(E!=="enrolled")continue;let x=v==="opencode"?"OpenCode":"Pi";X(`${x} stays connected to the vault. In ${x}, run /claude → Accounts → Disconnect from the vault to undo it. Or run setup again to finish connecting.`)}return 1}finally{for(let q of N)q.close();for(let q of U.values())if(q.preflight)Nz(q.preflight)}}async function Sz($,Z,J,z){if($.some((Q)=>Q!==h3))return z(`${h3} runs on its own; run it without other options.`),1;let X=Z.runner??M$,G=Z.fence??i4(X,{platform:Z.platform});try{await Kz(G,J)}catch(Q){let W=O1(Q)??n1(Q);return z(W??await r0("setup-process-check",Q,J)),1}try{let Q=await(Z.restoreLegacy??Pz)({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 Oz)return z(Q.message),1;return z(n1(Q)??await r0("cli-setup",Q,J)),1}}async function k1($){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Native account changes require offline setup without OPENCODE_AUTH_CONTENT");let Z=await xz({role:"cli",requireExistingAuthority:!0}),J=await uz(void 0,void 0,Z.layout),z=fz({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 u3(){if(await hz("opencode",process.env)!=="local")throw Error("Disconnect from the vault first.")}function e4(){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
|
+
${mz()}`)}function S$($,Z){let J=$?.trim();if(!J)throw Error(`${Z} is required`);return J}async function d3($){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 pz($,Z,J,z){return d3({token:$,method:"POST",path:`/accounts/${Z}/storage/kv/namespaces`,body:JSON.stringify({title:J}),fetchImpl:z})}async function dz($){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([cz],{type:"application/javascript+module"}),"worker.js"),d3({token:$.token,method:"PUT",path:`/accounts/${$.accountId}/workers/scripts/${$.scriptName}`,body:J,fetchImpl:$.fetchImpl})}async function lz($,Z,J,z){await d3({token:$,method:"POST",path:`/accounts/${Z}/workers/scripts/${J}/subdomain`,body:JSON.stringify({enabled:!0,previews_enabled:!1}),fetchImpl:z})}async function az($,Z,J){return d3({token:$,method:"GET",path:`/accounts/${Z}/workers/subdomain`,fetchImpl:J}).catch(()=>null)}async function sz($={}){await k1((B)=>B.read());let Z=$.fetchImpl??fetch,J=$.prompt??p3,z=$.warn??((B)=>console.warn(B)),X=S$(process.env.CLOUDFLARE_API_TOKEN?.trim()||await J("Cloudflare API token: "),"Cloudflare API token");$.secrets?.push(X);let G=S$(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`,Y=vz();$.secrets?.push(Y),console.log("Creating Cloudflare KV namespace...");let H=await pz(X,G,W,Z);console.log("Uploading relay Worker..."),await dz({token:X,accountId:G,scriptName:Q,kvNamespaceId:H.id,relayToken:Y,fetchImpl:Z}),await lz(X,G,Q,Z).catch(async(B)=>{z(await r0("cli-relay-workers-dev",B,process.env,[X,Y]))});let U=await az(X,G,Z),F=(U?.subdomain?`https://${Q}.${U.subdomain}.workers.dev`:"")||S$(await p3("Relay Worker URL: "),"Relay Worker URL");await k1((B)=>B.updateRelay({enabled:!0,url:F,token:Y,fallbackToDirect:!0,transport:"http"})),console.log(`Relay enabled at ${F}`),console.log("Relay settings saved to the native account store.")}var c3=null;async function p3($){return c3??=Ez({input:Tz,output:kz}),(await c3.question($)).trim()}function nz(){c3?.close(),c3=null}async function iz($,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??p3,z=Z.authorize??bz,X=Z.exchange??yz;await u3(),await k1(async(G)=>{let Q=await G.read(),W=$?.trim()||await J("Fallback account label (optional): "),Y=await z("max");console.log(`
|
|
67
67
|
Open this URL in your browser and complete Claude sign-in:
|
|
68
68
|
`),console.log(`${Y.url}
|
|
69
|
-
`);let
|
|
70
|
-
Saved native fallback account${W?` "${W}"`:""}.`)})}async function
|
|
71
|
-
Saved API fallback route${z?` "${z}"`:""} (${X}).`)}async function
|
|
69
|
+
`);let H=await J("Paste the full callback URL or authorization code here: ");Z.secrets?.push(H);let U=await X(H,Y.verifier,Y.redirectUri,Y.state);if(U.type==="failed")throw Error("Authentication failed");if(Z.secrets?.push(U.access,U.refresh),process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Local login cannot be verified while OPENCODE_AUTH_CONTENT is set");await u3();let K=W&&W!=="main"?W:crypto.randomUUID(),F=Q.accounts.some((B)=>B.id===K&&B.source==="local");await G.loginOAuth({routeId:K,replace:F,label:W||void 0,credential:{access:U.access,refresh:U.refresh,expires:U.expires}}),console.log(`
|
|
70
|
+
Saved native fallback account${W?` "${W}"`:""}.`)})}async function oz($,Z={}){await u3(),await k1((Y)=>Y.read());let J=Z.prompt??p3,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(!wz(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 k1(async(Y)=>{await u3();let H=await Y.read(),U=z&&z!=="main"?z:crypto.randomUUID(),K=H.accounts.find((F)=>F.id===U);if(K?.source==="vault")throw Error("Vault routes cannot be replaced with a local API key");await Y.addApi({routeId:U,replace:Boolean(K),label:z||void 0,apiKey:G.trim(),baseURL:X,authHeader:W})}),console.log(`
|
|
71
|
+
Saved API fallback route${z?` "${z}"`:""} (${X}).`)}async function rz(){await k1(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,Y=Q===void 0&&W===void 0?"quota unknown":`5h ${Q??"?"}%, 1w ${W??"?"}% remaining`;console.log(`${J+1}. ${X} (${G}) — ${Y}${z.state?` — ${gz(z)}`:""}`)}})}async function tz($){let[Z,J,z]=process.argv.slice(2);if(!Z||Z==="help"||Z==="--help"||Z==="-h"){e4();return}if(Z==="setup"){$.stage="cli-setup";let X=await t4(process.argv.slice(3));if(X!==0)process.exitCode=X;return}if(Z==="login"){$.stage="cli-login",await iz(J,{secrets:$.secrets});return}if(Z==="api"&&J==="add"){$.stage="cli-api-add",await oz(z,{secrets:$.secrets});return}if(Z==="list"){$.stage="cli-list",await rz();return}if(Z==="relay"&&J==="setup"){$.stage="cli-relay-setup",await sz({secrets:$.secrets});return}e4(),process.exitCode=1}if(r3.main==r3.module){let $={stage:"cli-command",secrets:[]};try{await tz($)}catch(Z){console.error(await r0($.stage,Z,process.env,$.secrets)),process.exitCode=1}finally{nz()}}export{t4 as runSetupCommand,sz as relaySetup,iz as login,oz as addApiRoute};
|