@cortexkit/opencode-anthropic-auth 2.6.0 → 2.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +3 -3
- package/dist/index-2cg2an3s.js +45 -0
- package/dist/index.js +1 -1
- package/dist/v2/adapter.d.ts +15 -0
- package/dist/v2/cachekeep.d.ts +11 -3
- package/dist/v2/server.js +11 -11
- package/dist/v2/source.d.ts +19 -2
- package/package.json +2 -2
- package/dist/index-c85qdpfy.js +0 -45
package/dist/cli.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{B as k3}from"./index-qqs4ec18.js";import{D as A4,E as _4,F as X7,G as G7,H as Q7,I as W7,J as I4}from"./index-k6303ymz.js";import{la as K4,ma as WJ,na as u3}from"./index-n8xr16kr.js";var H$=WJ((Oq,Y4)=>{var Y$={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"},YJ={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},HJ={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?Y$.up():"");if($)Z+=Y$.left;return Z}};Y4.exports={cursor:Y$,scroll:YJ,erase:HJ,beep:"\x07"}});import{stdin as eJ,stdout as $z}from"node:process";import{createInterface as Zz}from"node:readline/promises";import{authorize as Jz,createNativeAccountRuntime as zz,decideOpenCodeStateLayoutOnce as Xz,exchange as Gz,formatNativeAccountState as Qz,generateRelayToken as Wz,getAccountStoragePath as Yz,isValidApiBaseURL as Hz,readNativeEnrollmentMode as Uz,resolveNativePoolPaths as Kz,WORKER_SCRIPT as qz}from"@cortexkit/anthropic-auth-core";import{randomUUID as O5}from"node:crypto";import{constants as V3}from"node:fs";import{lstat as A5,mkdir as _5,open as I5}from"node:fs/promises";import{homedir as R5}from"node:os";import{isAbsolute as S5,join as O7}from"node:path";import{types as s9}from"node:util";import{anthropicAuthStateRoot as T5,createProviderErrorRedactor as A7,createWindowsOwnerOnly as k5,ensureWindowsOwnerOnlyDirectory as E5,formatLogLine as b5,HOLDER_REGISTRATION_ERROR_MESSAGES as f5,isOwnerOnly as x5,isSecretKey as y5,isStateLayoutRefusalCode as g5,NativeMigrationError as v5,NativePiAuthSlotError as h5,PRIVATE_FILES_UNAVAILABLE_MESSAGE as _7,RELOCATED_MESSAGE as m5,STATE_LAYOUT_REFUSAL_CODES as w5,STATE_LAYOUT_REFUSAL_PUBLIC_MESSAGES as u5,setupEnrollment as c5,stateLayoutRefusalPublicMessage as p5}from"@cortexkit/anthropic-auth-core";import{readFile as q5}from"node:fs/promises";import{assertHostsStopped as F5,createNativeAccountRuntime as B5,discoverNativeVaultInventory as V5,inspectNativeHostAuthEntry as u9,NativePiAuthSlotError as j5,nativePiAuthSlotPaths as M5,openNativePiAuthSlot as p9,readNativeEnrollmentMode as D5,requireNoSupervisedAuthContentSnapshot as N5}from"@cortexkit/anthropic-auth-core";import{dirname as u6}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as c6,CLAUSTRUM_PI_ENROLLMENT_NAME as p6,getHostClaustrumEnrollmentPaths as e2,resolveClaustrumConnectionPath as d6}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as OW}from"@cortexkit/claustrum-client";import{ClaustrumClient as ZW}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as b4}from"@cortexkit/claustrum-client";import{SocketClosedError as f4,SocketTimeoutError as x4,SubcCallError as y4}from"@cortexkit/subc-client";class O extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var g3=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class c extends O{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function Y0($){if($ instanceof c||$ instanceof f4||$ instanceof x4)return"unreachable";let Z=$ instanceof b4||$ instanceof y4?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(g3,Z))return"answered";return g3[Z]}import{resolve as P$}from"node:path";import{storeIdentity as Ez}from"@cortexkit/claustrum-client";import{SubcClient as fz}from"@cortexkit/subc-client";var r0=300000,i1=300000,v3=1000;class S1{#$;#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 o1{#$;#Z;#X;#Q=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#X}request(){if(this.#X)return this.#Q=!0,this.#X;return this.#X=(async()=>{do{this.#Q=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#Q)})().finally(()=>{this.#X=void 0}),this.#X}}class r1{#$;#Z=new S1;#X;#Q="polling";#G;#W;#z=!1;#J;#V=!1;#Y=0;constructor($){this.#$=$,this.#X=new o1(async()=>{let Z=this.#V;if(this.#V=!1,Z||this.#J!==this.#$.view())await this.#$.discover(this.#J??"")},(Z)=>{if(!this.#z)this.#$.onError?.(Z)})}get mode(){return this.#Q}start(){if(this.#z||this.#G||this.#W)return;if(typeof this.#$.client.watchScoped!=="function"){this.#H("fallback","client-without-watch");return}this.#F(!1)}stop(){if(this.#z)return;if(this.#z=!0,this.#W)(this.#$.clearTimeoutImpl??clearTimeout)(this.#W);this.#W=void 0;let $=this.#G;this.#G=void 0,$?.handle.stop()}#H($,Z){if(this.#Q===$)return;this.#Q=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#U($,Z){this.#W=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#W=void 0,!this.#z)Z()},$),this.#W.unref?.()}async#F($){let Z;try{Z=await this.#$.enrollmentToken()}catch(Q){if(this.#z)return;this.#$.onError?.(Q),this.#B("token-unreadable");return}let J=this.#$.client.watchScoped;if(this.#z||this.#G||!J)return;this.#Z.restart(),this.#V=$;let z,X;try{X=J.call(this.#$.client,(Q)=>{if(this.#z||!z||this.#G!==z)return;if(z.notices++,z.notices===1)this.#$.onReachable?.(),z.acceptedAt=(this.#$.now??Date.now)(),this.#H("watching","accepted");if(!this.#Z.continuous(Q))this.#V=!0;this.#J=Q.view,this.#X.request()},{enrollmentToken:Z})}catch(Q){this.#$.onError?.(Q),this.#B("watch-failed");return}z={handle:X,notices:0},this.#G=z,this.#H("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.#z||this.#G!==$)return;if(this.#G=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#H("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#B("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.#Y=0;let z=Math.min(1000*2**Math.min(this.#Y,16),300000);this.#Y++,this.#H("polling","resubscribing"),this.#U(z,()=>void this.#F(!0));return}this.#B(Z.kind)}#B($){this.#H("fallback",$),this.#U(300000,()=>void this.#F(!1))}}var e1=60000,C$=4*e1,g4=2*e1,h3=new Map,t1=new Map;function t0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function v4($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!t0(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 h4($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class O${transport;key;#$=[];#Z=!1;#X=new Set;#Q=new Map;#G=new o1(async()=>{try{let $=await this.transport.getUsage();if(!t0($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>t0(Z)&&typeof Z.provider==="string"),this.#Z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#X=new Set(this.#Z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#X)this.#Q.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#X.clear()}},()=>{});#W=new S1;#z="polling";#J=0;#V=0;#Y=new Map;#H;#U;#F={};#K=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#G.running)return this.#G.running;if(this.#z==="watching")return Promise.resolve();for(let[J,z]of t1)if($-z>=e1)t1.delete(J);let Z=t1.get(this.key);if(Z!==void 0&&$-Z<e1)return Promise.resolve();return t1.set(this.key,$),this.#G.request()}watchMode(){return this.#z}watch($={}){this.#J++;let Z=$.provider;if(Z===void 0)this.#V++;else this.#Y.set(Z,(this.#Y.get(Z)??0)+1);if(this.#J===1)this.#F=$,this.#C();let J=!1;return()=>{if(J)return;if(J=!0,Z===void 0)this.#V--;else{let z=(this.#Y.get(Z)??1)-1;if(z>0)this.#Y.set(Z,z);else this.#Y.delete(Z)}if(--this.#J===0)this.#B()}}#B(){if(this.#U)(this.#F.clearTimeoutImpl??clearTimeout)(this.#U);this.#U=void 0;let $=this.#H;this.#H=void 0,$?.handle?.stop(),this.#z="polling"}#D($){this.#U=(this.#F.setTimeoutImpl??setTimeout)(()=>{if(this.#U=void 0,this.#J>0&&!this.#H)this.#C()},$),this.#U.unref?.()}#C(){let $=this.transport.watchUsage;if(!$){this.#z="fallback";return}this.#z="polling",this.#W.restart();let Z={notices:0};this.#H=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.#H!==$)return;if($.notices++,$.notices===1)this.#z="watching";if($.notices===2)this.#K=0;let J=v4(Z);if(!J)this.#W.restart();if(!(J?this.#W.continuous(J):!1)||J?.provider===void 0||this.#V>0||this.#Y.has(J.provider))this.#G.request()}#O($,Z){if(this.#H!==$)return;this.#H=void 0;let J=h4(Z);if(J==="unknown_method"||J==="usage_watch_limit"){this.#z="fallback";return}if($.notices>0){let z=Math.min(v3*2**Math.min(this.#K,16),i1);this.#K++,this.#z="polling",this.#D(z);return}if(this.#z="fallback",this.#G.request(),Z===void 0||Y0(Z)==="unreachable")this.#D(i1)}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||!t0(z.usage))continue;let X=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(X)||J-X>=C$)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(!t0(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&&(!t0(z.stale)||z.stale.class!=="local_source_unavailable"))return{miss:"upstream-failed",reading:W};return J>=Q+C$||z.stale!==void 0?{miss:"stale",reading:W}:{reading:W}}if(this.#X.has($))return{miss:"absent"};let G=this.#Q.get($)??J;return this.#Q.set($,G),{miss:J-G>=g4?"unreachable":"cold"}}}function m3($,Z){let J=JSON.stringify([P$($.connectionFile),P$(Z)]),z=h3.get(J);if(!z)z={source:new O$($,J),refs:0},h3.set(J,z);z.refs++;let X=!1;return{source:z.source,release(){if(X)return;if(X=!0,--z.refs===0)h3.delete(J)}}}import{ClaustrumCredentialError as QW}from"@cortexkit/claustrum-client";import{appendFileSync as r4,chmodSync as t4,existsSync as p3,renameSync as x$,statSync as e4}from"node:fs";import{open as $8}from"node:fs/promises";import{dirname as Z8,resolve as J8}from"node:path";import{randomUUID as R$}from"node:crypto";import{lstat as S$,readFile as T$,rename as m4,unlink as A$}from"node:fs/promises";import{tmpdir as w4}from"node:os";import{dirname as C0,join as u4,resolve as $0}from"node:path";var _=process.platform==="win32",_$=new Set;function w3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var I$;var k$="native-addon-unavailable";function E$($){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:$}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:k$})}function c4($,Z){return Z instanceof $.PrivateFilesUnavailableError||Z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function p4($){try{await $.verifyPrivatePath(u4(w4(),`.common-auth-private-files-probe-${R$()}`),"file")}catch(Z){if(c4($,Z))throw E$(Z)}}function e0(){return I$??=import("@cortexkit/private-files").then(async($)=>{if(_)await p4($);return $},($)=>{throw _?E$($):$}),I$}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}: ${$} (${k$}). 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=w3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}function $3($){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 d4;async function j0($,Z){$=$0($),Z??=d4,await t($,"safe-parent",async()=>{let J=await(await e0()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await S$($);throw new w(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function n($,Z,J=!1){if($=$0($),Z==="directory")return j0($);await t($,"verify",async()=>{let z=await e0(),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(C0($)),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&&!_$.has($))_$.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function H0($,Z=!1,J){$=$0($),await t($,"directory",async()=>{let z=await e0();try{return await S$($),await j0($,J)}catch(G){if(w3(G)!=="ENOENT")throw G}let X=C0($);if(X===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await H0(X,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(w3(G)!=="EEXIST")throw G}await j0($,J)})}async function X0($,Z=!1){if(!_)return T$($,"utf8");return(await l4($,Z)).toString("utf8")}async function l4($,Z=!1){if(!_)return T$($);if($=$0($),Z)await j0(C0($)),await n($,"file",!0);return t($,"read",async()=>(await e0()).readOwnerOnly($))}async function $1($,Z){await j0(C0($0($))),await t($,"create",async()=>{await(await e0()).createPrivateFile($0($),Z)})}async function b$($){await j0(C0($0($))),await t($,"directory-create",async()=>{await(await e0()).createOwnerOnly($0($),{kind:"dir"})})}async function c3($,Z,J={}){$=$0($),Z=$0(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 D=Math.min(Q??1/0,G);if(z()>=D)break;if(K)await(J.sleep??((L)=>new Promise((C)=>setTimeout(C,L))))(Math.min(K,Math.max(0,D-z())));if(z()>=D)break;let B=z();if(await J.beforeRename?.(),Q!==void 0)Q+=z()-B;if(z()>=G)break;U++;try{return await(J.rename??m4)($,Z),{attempts:U,elapsedMs:z()-X}}catch(L){Y??=L;let C=L;if(!(C.win32Code!==void 0?C.win32Code===32||C.win32Code===33:["EBUSY","EPERM","EACCES"].includes(C.code??"")&&!C.reason))break;Q??=z()+500}}let 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 Z1($,Z,J={}){$=$0($),await H0(C0($));try{await n($,"file",!0)}catch(U){if(U.code!=="ENOENT")throw U}let z=$0(J.stagePath??`${$}.${R$()}.tmp`);if(C0(z)!==C0($))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 $1(z,Z),X=!0,W="before-rename",Q=await c3(z,$,J),X=!1,G=!0,W="published-callback",J.onRenamed?.(),W="published-verify",await n($,"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 A$(z)}catch{H.orphanPath=z}X=!1}throw Y(H),H}finally{if(X)await A$(z).catch(()=>{})}}var a4=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,s4=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function n4($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function J1($={}){let Z=[s4,...$.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 a4.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=n4(G);if(U&&Y>=8)return"[Truncated]";let H=U?Y+1:Y;return Object.fromEntries((U?z(G):Object.entries(G)).map(([K,D])=>[K,Q&&J(K)?"***REDACTED***":X(D,Q,W,H)]))}finally{W.delete(G)}}return{redact:(G)=>X(G,!0,new WeakSet),redactStrings:(G)=>X(G,!1,new WeakSet)}}var f$=J1(),i4=f$.redact,o4=f$.redactStrings;var Z3={error:0,warn:1,info:2,debug:3,trace:4},g$=5242880,v$=3;function d3($){try{t4($,384)}catch{}}function z8($){try{if(!(p3($)&&e4($).size>=g$))return;for(let J=v$-1;J>=1;J--)if(p3(`${$}.${J}`)){let z=`${$}.${J+1}`;x$(`${$}.${J}`,z),d3(z)}let Z=`${$}.1`;x$($,Z),d3(Z)}catch{}}async function M0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await t(Z,"log-close",()=>J.close())}async function y$($,Z){await H0(Z8(Z));try{await n(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await $1(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await n(Z,"file",!0)}}return $.handle=await t(Z,"log-open",()=>$8(Z,"a")),$.file=Z,$.handle}async function X8($,Z,J){Z=J8(Z);try{if($.file!==Z)await M0($);let z=$.handle??await y$($,Z);if((await t(Z,"log-stat",()=>z.stat())).size>=g$){await M0($);for(let G=v$-1;G>=0;G--){let Q=G===0?Z:`${Z}.${G}`,W=`${Z}.${G+1}`;try{await n(Q,"file",!0)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}try{await n(W,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}await c3(Q,W),await n(W,"file")}z=await y$($,Z)}await t(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await M0($).catch(()=>{}),z}}function G8($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function Q8($){let Z,J,z,X=J1(),G,Q=[],W,Y=Promise.resolve(),U,H={};function K(F){let q=Y.then(F);return Y=q.catch((j)=>{U=j}),q}function D(F){if(_&&F.file!==Z)K(()=>M0(H)).catch(()=>{});Z=F.file,J=F.level,X=J1(F),G=F.captureSink}function B(F){if(F===void 0||F in Z3)z=F}function L(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function C(){if(z)return z;let F=typeof J==="function"?J():J;if(F&&F in Z3)return F;return"info"}function A(F=!0){if(W)clearTimeout(W),W=void 0;if(!Q.length){if(_)return K(async()=>{if(F)await M0(H);if(U)throw U});return}let q;try{q=L()}catch{if(Q=[],_&&F)return K(()=>M0(H));return}let j=Q.join("");if(Q=[],!q){if(_&&F)return K(()=>M0(H));return}if(_)return K(async()=>{try{await X8(H,q,j)}finally{if(F)await M0(H)}});try{if(z8(q),p3(q))d3(q);r4(q,j,{encoding:"utf8",mode:384})}catch{}}function I(){if(!W)W=setTimeout(()=>{W=void 0;let F=A(!1);if(F instanceof Promise)F.catch(()=>{})},500)}function T(F,q,j,P){if(Z===void 0&&G===void 0)return;try{if(Z3[q]>Z3[C()])return;let g=X.redactStrings(j),E;try{E=X.redact(P)}catch{E="[unserializable]"}let v=`[${new Date().toISOString()}] ${q.toUpperCase()} [${F}] ${g}`+(P===void 0?"":G8(E))+`
|
|
2
|
+
import{B as k3}from"./index-qqs4ec18.js";import{D as A4,E as _4,F as X7,G as G7,H as Q7,I as W7,J as I4}from"./index-k6303ymz.js";import{la as K4,ma as WJ,na as u3}from"./index-n8xr16kr.js";var H$=WJ((Oq,Y4)=>{var Y$={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"},YJ={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},HJ={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?Y$.up():"");if($)Z+=Y$.left;return Z}};Y4.exports={cursor:Y$,scroll:YJ,erase:HJ,beep:"\x07"}});import{stdin as eJ,stdout as $z}from"node:process";import{createInterface as Zz}from"node:readline/promises";import{authorize as Jz,createNativeAccountRuntime as zz,decideOpenCodeStateLayoutOnce as Xz,exchange as Gz,formatNativeAccountState as Qz,generateRelayToken as Wz,getAccountStoragePath as Yz,isValidApiBaseURL as Hz,readNativeEnrollmentMode as Uz,resolveNativePoolPaths as Kz,WORKER_SCRIPT as qz}from"@cortexkit/anthropic-auth-core";import{randomUUID as O5}from"node:crypto";import{constants as V3}from"node:fs";import{lstat as A5,mkdir as _5,open as I5}from"node:fs/promises";import{homedir as R5}from"node:os";import{isAbsolute as S5,join as O7}from"node:path";import{types as s9}from"node:util";import{anthropicAuthStateRoot as T5,createProviderErrorRedactor as A7,createWindowsOwnerOnly as k5,ensureWindowsOwnerOnlyDirectory as E5,formatLogLine as b5,HOLDER_REGISTRATION_ERROR_MESSAGES as f5,isOwnerOnly as x5,isSecretKey as y5,isStateLayoutRefusalCode as g5,NativeMigrationError as v5,NativePiAuthSlotError as h5,PRIVATE_FILES_UNAVAILABLE_MESSAGE as _7,RELOCATED_MESSAGE as m5,STATE_LAYOUT_REFUSAL_CODES as w5,STATE_LAYOUT_REFUSAL_PUBLIC_MESSAGES as u5,setupEnrollment as c5,stateLayoutRefusalPublicMessage as p5}from"@cortexkit/anthropic-auth-core";import{readFile as q5}from"node:fs/promises";import{assertHostsStopped as F5,createNativeAccountRuntime as B5,discoverNativeVaultInventory as V5,inspectNativeHostAuthEntry as u9,NativePiAuthSlotError as j5,nativePiAuthSlotPaths as M5,openNativePiAuthSlot as p9,readNativeEnrollmentMode as D5,requireNoSupervisedAuthContentSnapshot as N5}from"@cortexkit/anthropic-auth-core";import{dirname as u6}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as c6,CLAUSTRUM_PI_ENROLLMENT_NAME as p6,getHostClaustrumEnrollmentPaths as e2,resolveClaustrumConnectionPath as d6}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as OW}from"@cortexkit/claustrum-client";import{ClaustrumClient as ZW}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as b4}from"@cortexkit/claustrum-client";import{SocketClosedError as f4,SocketTimeoutError as x4,SubcCallError as y4}from"@cortexkit/subc-client";class O extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var g3=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",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 p extends O{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function Y0($){if($ instanceof p||$ instanceof f4||$ instanceof x4)return"unreachable";let Z=$ instanceof b4||$ instanceof y4?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(g3,Z))return"answered";return g3[Z]}import{resolve as P$}from"node:path";import{storeIdentity as Ez}from"@cortexkit/claustrum-client";import{SubcClient as fz}from"@cortexkit/subc-client";var r0=300000,i1=300000,v3=1000;class S1{#$;#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 o1{#$;#Z;#X;#Q=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#X}request(){if(this.#X)return this.#Q=!0,this.#X;return this.#X=(async()=>{do{this.#Q=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#Q)})().finally(()=>{this.#X=void 0}),this.#X}}class r1{#$;#Z=new S1;#X;#Q="polling";#G;#W;#z=!1;#J;#V=!1;#Y=0;constructor($){this.#$=$,this.#X=new o1(async()=>{let Z=this.#V;if(this.#V=!1,Z||this.#J!==this.#$.view())await this.#$.discover(this.#J??"")},(Z)=>{if(!this.#z)this.#$.onError?.(Z)})}get mode(){return this.#Q}start(){if(this.#z||this.#G||this.#W)return;if(typeof this.#$.client.watchScoped!=="function"){this.#H("fallback","client-without-watch");return}this.#F(!1)}stop(){if(this.#z)return;if(this.#z=!0,this.#W)(this.#$.clearTimeoutImpl??clearTimeout)(this.#W);this.#W=void 0;let $=this.#G;this.#G=void 0,$?.handle.stop()}#H($,Z){if(this.#Q===$)return;this.#Q=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#U($,Z){this.#W=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#W=void 0,!this.#z)Z()},$),this.#W.unref?.()}async#F($){let Z;try{Z=await this.#$.enrollmentToken()}catch(Q){if(this.#z)return;this.#$.onError?.(Q),this.#B("token-unreadable");return}let J=this.#$.client.watchScoped;if(this.#z||this.#G||!J)return;this.#Z.restart(),this.#V=$;let z,X;try{X=J.call(this.#$.client,(Q)=>{if(this.#z||!z||this.#G!==z)return;if(z.notices++,z.notices===1)this.#$.onReachable?.(),z.acceptedAt=(this.#$.now??Date.now)(),this.#H("watching","accepted");if(!this.#Z.continuous(Q))this.#V=!0;this.#J=Q.view,this.#X.request()},{enrollmentToken:Z})}catch(Q){this.#$.onError?.(Q),this.#B("watch-failed");return}z={handle:X,notices:0},this.#G=z,this.#H("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.#z||this.#G!==$)return;if(this.#G=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#H("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#B("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.#Y=0;let z=Math.min(1000*2**Math.min(this.#Y,16),300000);this.#Y++,this.#H("polling","resubscribing"),this.#U(z,()=>void this.#F(!0));return}this.#B(Z.kind)}#B($){this.#H("fallback",$),this.#U(300000,()=>void this.#F(!1))}}var e1=60000,C$=4*e1,g4=2*e1,h3=new Map,t1=new Map;function t0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function v4($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!t0(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 h4($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class O${transport;key;#$=[];#Z=!1;#X=new Set;#Q=new Map;#G=new o1(async()=>{try{let $=await this.transport.getUsage();if(!t0($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>t0(Z)&&typeof Z.provider==="string"),this.#Z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#X=new Set(this.#Z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#X)this.#Q.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#X.clear()}},()=>{});#W=new S1;#z="polling";#J=0;#V=0;#Y=new Map;#H;#U;#F={};#K=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#G.running)return this.#G.running;if(this.#z==="watching")return Promise.resolve();for(let[J,z]of t1)if($-z>=e1)t1.delete(J);let Z=t1.get(this.key);if(Z!==void 0&&$-Z<e1)return Promise.resolve();return t1.set(this.key,$),this.#G.request()}watchMode(){return this.#z}watch($={}){this.#J++;let Z=$.provider;if(Z===void 0)this.#V++;else this.#Y.set(Z,(this.#Y.get(Z)??0)+1);if(this.#J===1)this.#F=$,this.#C();let J=!1;return()=>{if(J)return;if(J=!0,Z===void 0)this.#V--;else{let z=(this.#Y.get(Z)??1)-1;if(z>0)this.#Y.set(Z,z);else this.#Y.delete(Z)}if(--this.#J===0)this.#B()}}#B(){if(this.#U)(this.#F.clearTimeoutImpl??clearTimeout)(this.#U);this.#U=void 0;let $=this.#H;this.#H=void 0,$?.handle?.stop(),this.#z="polling"}#D($){this.#U=(this.#F.setTimeoutImpl??setTimeout)(()=>{if(this.#U=void 0,this.#J>0&&!this.#H)this.#C()},$),this.#U.unref?.()}#C(){let $=this.transport.watchUsage;if(!$){this.#z="fallback";return}this.#z="polling",this.#W.restart();let Z={notices:0};this.#H=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.#H!==$)return;if($.notices++,$.notices===1)this.#z="watching";if($.notices===2)this.#K=0;let J=v4(Z);if(!J)this.#W.restart();if(!(J?this.#W.continuous(J):!1)||J?.provider===void 0||this.#V>0||this.#Y.has(J.provider))this.#G.request()}#O($,Z){if(this.#H!==$)return;this.#H=void 0;let J=h4(Z);if(J==="unknown_method"||J==="usage_watch_limit"){this.#z="fallback";return}if($.notices>0){let z=Math.min(v3*2**Math.min(this.#K,16),i1);this.#K++,this.#z="polling",this.#D(z);return}if(this.#z="fallback",this.#G.request(),Z===void 0||Y0(Z)==="unreachable")this.#D(i1)}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||!t0(z.usage))continue;let X=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(X)||J-X>=C$)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(!t0(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&&(!t0(z.stale)||z.stale.class!=="local_source_unavailable"))return{miss:"upstream-failed",reading:W};return J>=Q+C$||z.stale!==void 0?{miss:"stale",reading:W}:{reading:W}}if(this.#X.has($))return{miss:"absent"};let G=this.#Q.get($)??J;return this.#Q.set($,G),{miss:J-G>=g4?"unreachable":"cold"}}}function m3($,Z){let J=JSON.stringify([P$($.connectionFile),P$(Z)]),z=h3.get(J);if(!z)z={source:new O$($,J),refs:0},h3.set(J,z);z.refs++;let X=!1;return{source:z.source,release(){if(X)return;if(X=!0,--z.refs===0)h3.delete(J)}}}import{ClaustrumCredentialError as QW}from"@cortexkit/claustrum-client";import{appendFileSync as r4,chmodSync as t4,existsSync as p3,renameSync as x$,statSync as e4}from"node:fs";import{open as $8}from"node:fs/promises";import{dirname as Z8,resolve as J8}from"node:path";import{randomUUID as R$}from"node:crypto";import{lstat as S$,readFile as T$,rename as m4,unlink as A$}from"node:fs/promises";import{tmpdir as w4}from"node:os";import{dirname as C0,join as u4,resolve as $0}from"node:path";var _=process.platform==="win32",_$=new Set;function w3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var I$;var k$="native-addon-unavailable";function E$($){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:$}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:k$})}function c4($,Z){return Z instanceof $.PrivateFilesUnavailableError||Z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function p4($){try{await $.verifyPrivatePath(u4(w4(),`.common-auth-private-files-probe-${R$()}`),"file")}catch(Z){if(c4($,Z))throw E$(Z)}}function e0(){return I$??=import("@cortexkit/private-files").then(async($)=>{if(_)await p4($);return $},($)=>{throw _?E$($):$}),I$}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}: ${$} (${k$}). 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=w3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}function $3($){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 d4;async function j0($,Z){$=$0($),Z??=d4,await t($,"safe-parent",async()=>{let J=await(await e0()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await S$($);throw new w(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function n($,Z,J=!1){if($=$0($),Z==="directory")return j0($);await t($,"verify",async()=>{let z=await e0(),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(C0($)),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&&!_$.has($))_$.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function H0($,Z=!1,J){$=$0($),await t($,"directory",async()=>{let z=await e0();try{return await S$($),await j0($,J)}catch(G){if(w3(G)!=="ENOENT")throw G}let X=C0($);if(X===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await H0(X,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(w3(G)!=="EEXIST")throw G}await j0($,J)})}async function X0($,Z=!1){if(!_)return T$($,"utf8");return(await l4($,Z)).toString("utf8")}async function l4($,Z=!1){if(!_)return T$($);if($=$0($),Z)await j0(C0($)),await n($,"file",!0);return t($,"read",async()=>(await e0()).readOwnerOnly($))}async function $1($,Z){await j0(C0($0($))),await t($,"create",async()=>{await(await e0()).createPrivateFile($0($),Z)})}async function b$($){await j0(C0($0($))),await t($,"directory-create",async()=>{await(await e0()).createOwnerOnly($0($),{kind:"dir"})})}async function c3($,Z,J={}){$=$0($),Z=$0(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 D=Math.min(Q??1/0,G);if(z()>=D)break;if(K)await(J.sleep??((L)=>new Promise((C)=>setTimeout(C,L))))(Math.min(K,Math.max(0,D-z())));if(z()>=D)break;let B=z();if(await J.beforeRename?.(),Q!==void 0)Q+=z()-B;if(z()>=G)break;U++;try{return await(J.rename??m4)($,Z),{attempts:U,elapsedMs:z()-X}}catch(L){Y??=L;let C=L;if(!(C.win32Code!==void 0?C.win32Code===32||C.win32Code===33:["EBUSY","EPERM","EACCES"].includes(C.code??"")&&!C.reason))break;Q??=z()+500}}let 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 Z1($,Z,J={}){$=$0($),await H0(C0($));try{await n($,"file",!0)}catch(U){if(U.code!=="ENOENT")throw U}let z=$0(J.stagePath??`${$}.${R$()}.tmp`);if(C0(z)!==C0($))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 $1(z,Z),X=!0,W="before-rename",Q=await c3(z,$,J),X=!1,G=!0,W="published-callback",J.onRenamed?.(),W="published-verify",await n($,"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 A$(z)}catch{H.orphanPath=z}X=!1}throw Y(H),H}finally{if(X)await A$(z).catch(()=>{})}}var a4=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,s4=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function n4($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function J1($={}){let Z=[s4,...$.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 a4.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=n4(G);if(U&&Y>=8)return"[Truncated]";let H=U?Y+1:Y;return Object.fromEntries((U?z(G):Object.entries(G)).map(([K,D])=>[K,Q&&J(K)?"***REDACTED***":X(D,Q,W,H)]))}finally{W.delete(G)}}return{redact:(G)=>X(G,!0,new WeakSet),redactStrings:(G)=>X(G,!1,new WeakSet)}}var f$=J1(),i4=f$.redact,o4=f$.redactStrings;var Z3={error:0,warn:1,info:2,debug:3,trace:4},g$=5242880,v$=3;function d3($){try{t4($,384)}catch{}}function z8($){try{if(!(p3($)&&e4($).size>=g$))return;for(let J=v$-1;J>=1;J--)if(p3(`${$}.${J}`)){let z=`${$}.${J+1}`;x$(`${$}.${J}`,z),d3(z)}let Z=`${$}.1`;x$($,Z),d3(Z)}catch{}}async function M0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await t(Z,"log-close",()=>J.close())}async function y$($,Z){await H0(Z8(Z));try{await n(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await $1(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await n(Z,"file",!0)}}return $.handle=await t(Z,"log-open",()=>$8(Z,"a")),$.file=Z,$.handle}async function X8($,Z,J){Z=J8(Z);try{if($.file!==Z)await M0($);let z=$.handle??await y$($,Z);if((await t(Z,"log-stat",()=>z.stat())).size>=g$){await M0($);for(let G=v$-1;G>=0;G--){let Q=G===0?Z:`${Z}.${G}`,W=`${Z}.${G+1}`;try{await n(Q,"file",!0)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}try{await n(W,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}await c3(Q,W),await n(W,"file")}z=await y$($,Z)}await t(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await M0($).catch(()=>{}),z}}function G8($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function Q8($){let Z,J,z,X=J1(),G,Q=[],W,Y=Promise.resolve(),U,H={};function K(F){let q=Y.then(F);return Y=q.catch((j)=>{U=j}),q}function D(F){if(_&&F.file!==Z)K(()=>M0(H)).catch(()=>{});Z=F.file,J=F.level,X=J1(F),G=F.captureSink}function B(F){if(F===void 0||F in Z3)z=F}function L(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function C(){if(z)return z;let F=typeof J==="function"?J():J;if(F&&F in Z3)return F;return"info"}function A(F=!0){if(W)clearTimeout(W),W=void 0;if(!Q.length){if(_)return K(async()=>{if(F)await M0(H);if(U)throw U});return}let q;try{q=L()}catch{if(Q=[],_&&F)return K(()=>M0(H));return}let j=Q.join("");if(Q=[],!q){if(_&&F)return K(()=>M0(H));return}if(_)return K(async()=>{try{await X8(H,q,j)}finally{if(F)await M0(H)}});try{if(z8(q),p3(q))d3(q);r4(q,j,{encoding:"utf8",mode:384})}catch{}}function I(){if(!W)W=setTimeout(()=>{W=void 0;let F=A(!1);if(F instanceof Promise)F.catch(()=>{})},500)}function T(F,q,j,P){if(Z===void 0&&G===void 0)return;try{if(Z3[q]>Z3[C()])return;let g=X.redactStrings(j),E;try{E=X.redact(P)}catch{E="[unserializable]"}let v=`[${new Date().toISOString()}] ${q.toUpperCase()} [${F}] ${g}`+(P===void 0?"":G8(E))+`
|
|
3
3
|
`;try{G?.({channel:F,level:q,message:g,data:E})}catch{}if(Z===void 0)return;if(Q.push(v),Q.length>=50){let J0=A(!1);if(J0 instanceof Promise)J0.catch(()=>{})}else I()}catch{}}function m(F){return{error:(q,j)=>T(F,"error",q,j),warn:(q,j)=>T(F,"warn",q,j),info:(q,j)=>T(F,"info",q,j),debug:(q,j)=>T(F,"debug",q,j),trace:(q,j)=>T(F,"trace",q,j)}}function u(){if(_)K(()=>M0(H)).catch(()=>{});if(U=void 0,Q=[],W)clearTimeout(W),W=void 0;Z=void 0,J=void 0,z=void 0,X=J1(),G=void 0}if($)D($);return{configure:D,createLogger:m,setLogLevel:B,flushLogs:A,reset:u}}var W8=Q8();function U0($){return W8.createLogger($)}function E0($){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 d8}from"node:diagnostics_channel";import{ClaustrumCredentialError as V2}from"@cortexkit/claustrum-client";import{createHash as T8,randomBytes as k8,randomUUID as E8}from"node:crypto";import{constants as r$}from"node:fs";import{chmod as b8,mkdir as f8,open as Z2,readFile as o3,realpath as x8,rename as y8,stat as J2,unlink as t3}from"node:fs/promises";import{basename as g8,dirname as g0,extname as wX,isAbsolute as uX,join as v8,resolve as cX}from"node:path";import{ClaustrumCredentialError as h8,ClaustrumClient as dX,writeEnrollmentTokenFile as m8}from"@cortexkit/claustrum-client";import{lstat as Y8,stat as H8}from"node:fs/promises";import{resolve as U8}from"node:path";async function K8($,Z){try{let J=await(Z?H8($):Y8($));return J.isFile()?J:void 0}catch(J){return J.code==="ENOENT"?"absent":void 0}}function q8($,Z){if($==="absent"||Z==="absent")return $===Z;return $.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs&&$.ctimeMs===Z.ctimeMs}class b0{#$;#Z=new Map;constructor($={}){this.#$=$.followSymlinks??!1}async read($,Z,J){let z=$.map((U)=>U8(U)),X=JSON.stringify(z),G=await Promise.all(z.map((U)=>K8(U,this.#$))),Q=G.every((U)=>U!==void 0)?G:void 0,W=this.#Z.get(X);if(Q&&W&&Q.every((U,H)=>{let K=W.identities[H];return K!==void 0&&q8(U,K)}))return J?.(Q),W.value;this.#Z.delete(X);let Y=await Z(z);if(Q){if(this.#Z.size>=64){let U=this.#Z.keys().next().value;if(U!==void 0)this.#Z.delete(U)}this.#Z.set(X,{identities:Q,value:Y})}return Y}}import{randomUUID as h$}from"node:crypto";import{mkdir as F8,open as m$,rename as B8,rm as V8}from"node:fs/promises";import{dirname as w$}from"node:path";class J3 extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function z1($,Z,J={}){await u$($,Z,J)}async function u$($,Z,J,z){if(_)return Z1($,J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
4
4
|
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??h$)()}.tmp`,onRenamed:z,durable:J.durable,durability:J.durability,onOutcome:J.onOutcome});await F8(w$($),{recursive:!0});let X=`${$}.${(J.stageName??h$)()}.tmp`,G,Q=!1;try{if(G=await m$(X,"wx",384),Q=!0,await G.writeFile(J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
5
5
|
`,"utf8"),await G.chmod(384),J.durable)try{await G.sync()}catch(W){throw new J3(W)}if(await G.close(),G=void 0,await J.beforeRename?.(),await B8(X,$),Q=!1,z?.(),J.durable){let W=await m$(w$($),"r");try{await W.sync()}catch(Y){throw new J3(Y)}finally{await W.close()}}}finally{if(await G?.close().catch(()=>{}),Q)await V8(X,{force:!0}).catch(()=>{})}}var j8=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 k1}from"node:crypto";import{link as L8,lstat as G1,mkdir as c$,open as n3,readFile as p$,rename as d$,rm as Q1,stat as T1}from"node:fs/promises";import{dirname as a3,join as l$}from"node:path";import{join as M8,resolve as D8}from"node:path";function X1($,Z){return`${$}.${Z}.lock`}class O0 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class D0 extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}function N8($,Z,J){if(!$3($)||$.stage!=="read"&&$.stage!=="verify")return!1;let z=D8(X1(Z,J));return $.path===z||$.path===M8(z,"owner.json")}async function l3($,Z,J){let z=performance.now();for(;;){Z.signal?.throwIfAborted();let X,G;try{X=await N0({path:$,name:Z.name,ttlMs:Z.ttlMs,renew:Z.renew??!1,...Z.onStep?{onStep:Z.onStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}})}catch(W){if(!N8(W,$,Z.name))throw W;X=null,G=W}if(X)try{return Z.signal?.throwIfAborted(),await J(X)}finally{await X.release(Z.signal)}let Q=Z.timeoutMs-(performance.now()-z);if(Q<=0){if(G)throw G;throw new O0({target:$,name:Z.name,timeoutMs:Z.timeoutMs})}await new Promise((W)=>setTimeout(W,Math.min(25,Math.ceil(Q))))}}var W1;async function P8($,Z){let J=`${$}.${k1()}.tmp`,z;try{z=await n3(J,"wx",384);try{if(W1?.beforeWrite)await W1.beforeWrite(J);await z.writeFile(Z,"utf8")}finally{await z.close()}try{if(W1?.beforeLink)await W1.beforeLink(J,$);await L8(J,$)}catch(X){let G=X.code;if(G!=="EPERM"&&G!=="ENOTSUP"&&G!=="EOPNOTSUPP"&&G!=="EXDEV")throw X;await s$($,Z)}}finally{if(z)await Q1(J,{force:!0}).catch(()=>{})}}async function s$($,Z){let J=await n3($,"wx",384),z;try{z=await J.stat()}catch{z=void 0}try{if(W1?.beforeWrite)await W1.beforeWrite($);await J.writeFile(Z,"utf8")}catch(X){try{let G=await G1($).catch(()=>{return});if(z&&G&&G.dev===z.dev&&G.ino===z.ino)await Q1($,{force:!0}).catch(()=>{})}catch{}throw X}finally{await J.close()}}var C8=globalThis.setTimeout.bind(globalThis),O8=globalThis.clearTimeout.bind(globalThis);function n$($){let Z=$?.code;return Z==="ENOENT"||!_&&(Z==="EINVAL"||Z==="ENOTDIR")}var a$;function s3($,Z){if($.dev!==Z.dev||$.ino!==Z.ino)return!1;if($.ino===0&&$.birthtimeMs!==Z.birthtimeMs)return!1;return!0}var A8=1000;function N0($){return _8({...$,now:Date.now})}async function _8($){let Z=X1($.path,$.name),J=l$(Z,"owner.json"),z=k1(),X=$.now??Date.now,G=null,Q=!1,W=!1,Y,U,H=new Promise((V)=>{U=V});function K(V){try{let M=$.onRenewalTimer?.(V);if(M&&(typeof M==="object"||typeof M==="function")&&"then"in M&&typeof M.then==="function")Promise.resolve(M).catch(()=>{})}catch{}}function D(){if(!G)return;O8(G),G=null,K("cancelled")}function B(V,M){if(Y||Q)return;Y=Object.freeze({reason:V,expectedOwnerId:z,...typeof M?.ownerId==="string"?{observedOwnerId:M.ownerId}:{},...typeof M?.expiresAt==="number"?{observedExpiresAt:M.expiresAt}:{}}),D(),U(Y)}let L,C=null,A=`${Z}.evicting`,I=l$(A,"owner.json"),T=k1(),m=5000,u=8;async function F(){if(_)try{return JSON.parse(await X0(Z,!0))}catch(V){if(V.code!=="EISDIR"&&V.reason!=="wrong-kind")throw V;return await n(Z,"directory",!0),JSON.parse(await X0(J,!0))}try{return JSON.parse(await p$(Z,"utf8"))}catch(V){if(V.code!=="EISDIR")throw V;return JSON.parse(await p$(J,"utf8"))}}async function q(){if(_){let R=await F(),S=Number(R?.expiresAt)-X();await Z1(Z,`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
6
6
|
`,{deadline:performance.now()+Math.max(0,S),beforeRename:async()=>{let h=await F();if(h?.ownerId!==z||!(Number(h?.expiresAt)>X())||!await l())throw new D0({target:$.path,name:$.name})}});return}let V=`${Z}.${k1()}.tmp`,M,N=!1;try{M=await n3(V,"wx",384),N=!0,await M.writeFile(`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
7
7
|
`,"utf8"),await M.chmod(384),await M.close(),M=void 0;let R=await F();if(R?.ownerId!==z||!(Number(R?.expiresAt)>X())||!await l())throw new D0({target:$.path,name:$.name});await d$(V,Z),N=!1}finally{if(await M?.close().catch(()=>{}),N)await Q1(V,{force:!0}).catch(()=>{})}}async function j(){let V=`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
8
8
|
`;if(_)await $1(Z,V);else await P8(Z,V)}async function P(V){let M=V.code;if(M!=="EEXIST"&&M!=="EISDIR")return!1;if(_){if($.onStep)await $.onStep("lease-contention-read-ready");try{if(M==="EISDIR")await n(Z,"directory",!0),await X0(J,!0);else await F()}catch(N){if(N.code!=="ENOENT")throw N}}return!0}async function g(){if(_)await H0(a3(Z));try{return await j(),!0}catch(V){let M=V.code;if(await P(V))return!1;if(M==="ENOENT"){if(_)await H0(a3(Z));else await c$(a3(Z),{recursive:!0});try{return await j(),!0}catch(N){if(await P(N))return!1;throw N}}throw V}}async function E(){await new Promise((V)=>setTimeout(V,Math.floor(Math.random()*4)))}async function v(V=!0){if(V&&$.onStep)await $.onStep("lock-read-ready");let M;try{M=await F()}catch(R){if(_&&R.code!=="ENOENT")throw R}let N=Number(M?.expiresAt);if(Number.isFinite(N)&&N>X())return{status:"live"};if(typeof M?.ownerId==="string"&&Number.isFinite(N))return{status:"stale",identity:{kind:"owner",ownerId:M.ownerId,expiresAt:N}};try{let R=await T1(Z),S=Number.isFinite(N)?N: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 J0(V,M){if(M.status!=="stale")return!1;let N=M.identity;if(V.kind==="owner"&&N.kind==="owner")return V.ownerId===N.ownerId&&V.expiresAt===N.expiresAt;return V.kind==="stat"&&N.kind==="stat"&&V.dev===N.dev&&V.ino===N.ino&&V.mtimeMs===N.mtimeMs&&V.expiresAt===N.expiresAt}async function l(){try{return JSON.parse(await X0(I,_))?.ownerId===T}catch(V){if(_&&V.code!=="ENOENT")throw V;return!1}}async function a(V){if(_)await t(V,"remove",()=>Q1(V,{recursive:!0,force:!0}));else await Q1(V,{recursive:!0,force:!0}).catch(()=>{})}function s(V,M){if(!_||!(V instanceof w)||V.stage!=="remove"||V.path!==M)return!1;return $3(V)||V.win32Code===void 0&&V.reason===void 0&&(V.code==="EBUSY"||V.code==="EPERM")}async function z0(V,M,N=performance.now()+m+1000){let R,S=5;while(await M()){try{await a(V);return}catch(o0){if(!s(o0,V))throw o0;R??=o0}let h=N-performance.now();if(h<=0)throw R;if(await new Promise((o0)=>setTimeout(o0,Math.min(S,h))),performance.now()>=N)throw R;S=Math.min(S*2,50)}}async function I1(V){let M;await z0(A,async()=>{if(!_)return l();let N=await G1(A).catch((R)=>{if(R.code!=="ENOENT")throw R;return});if(!N||M&&!s3(M,N))return!1;if(await l())return M=N,!0;if(!M)return!1;try{return await T1(I),!1}catch(R){if(R.code!=="ENOENT")throw R;return!0}},V)}async function R1(V,M){if(!V)return!1;let N=!1;try{await z0(A,async()=>{N=!1;let R=await G1(A).catch(()=>{return});if(!R||!s3(V,R))return!1;N=!0;try{return await T1(I),!1}catch(S){return S.code==="ENOENT"}},M)}catch{}return N}async function n1(V){if(_)await b$(A);else await c$(A);let M;try{let N=await G1(A);M={dev:N.dev,ino:N.ino,birthtimeMs:N.birthtimeMs}}catch{M=void 0}try{await a$?.beforeOwnerWrite?.(A,I);let N=await a$?.failOwnerWrite?.(A,I);if(N!==void 0)throw N;let R=`${JSON.stringify({ownerId:T,createdAt:X()})}
|
|
9
|
-
`;if(_)await $1(I,R);else await s$(I,R)}catch(N){let R=await R1(M,V);if(n$(N)&&!R)return!1;try{await I1(V)}catch{}throw N}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function i0(V){let M;try{M=await T1(A)}catch(S){if(S.code==="ENOENT")return"missing";throw S}if(_)try{await n(A,"directory",!0)}catch(S){if(S.code==="ENOENT")return"missing";throw S}if(M.mtimeMs+m>X()){let S=!0;try{await T1(I)}catch(h){if(h.code==="ENOENT")S=!1;else return"fresh"}if(S)return"fresh";if(M.mtimeMs+A8>X())return"fresh"}if($.onStep)await $.onStep("stale-marker-stat");let N=`${A}.${k1()}`;try{await d$(A,N)}catch(S){if(S.code==="ENOENT")return"missing";throw S}if($.onStep)await $.onStep("stale-marker-claimed");let R=_?await G1(N):void 0;return await z0(N,async()=>{if(!R)return!0;let S=await G1(N).catch((h)=>{if(h.code!=="ENOENT")throw h;return});return!!S&&s3(R,S)},V),"recovered"}async function b(V,M){try{if(!await n1(M))return!1}catch(S){if(S.code==="EEXIST"){if(_)try{await n(A,"directory",!0),await X0(I,!0)}catch(h){if(h.code!=="ENOENT")throw h}return!1}throw S}let N=!1,R;try{await V()}catch(S){N=!0,R=S}try{await I1(M)}catch(S){if(s(R,Z)&&s(S,A))throw R;throw S}if(N)throw R;return!0}async function V0(){for(let V=0;V<u;V++){if($.onStep)await $.onStep("relinquish-read");let M;try{M=await F()}catch(N){if(_)throw N;return}if(M?.ownerId!==z)return;try{await Q1(Z,{recursive:!0,force:!0});return}catch(N){if(_)throw N;await E()}}}function M$(){if(!$.renew||Q||Y)return;let V=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=C8(()=>{G=null;let M=(async()=>{let N=!Q;try{if(!await b(async()=>{let S=await F(),h=X();if(Q||Y){N=!1;return}if(S?.ownerId!==z){B("taken-over",S),N=!1;return}if(!(Number(S?.expiresAt)>h)){B("expired",S),N=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(Q||Y){N=!1;return}if(!await l())return;if($.onStep)await $.onStep("renewal-write-fenced");if(Q||Y){N=!1;return}if(!await l())return;if($.onStep)await $.onStep("renewal-write-ready");if(Q||Y){N=!1;return}if(await q(),$.onStep)await $.onStep("renewal-write-finished");if(!await l()){B("marker-lost"),N=!1,await V0();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(R){if(_&&R instanceof w)L=R,B("renewal-failed"),N=!1;try{let S=await F();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(N&&!Q&&!Y)M$()}})();C=M,M.finally(()=>{if(C===M)C=null})},V),"unref"in G)G.unref();K("scheduled")}function D$(){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 k0=await g();if(!k0)for(let V=0;V<u;V++){if(k0=await g(),k0)break;let M=await v();if(M.status==="live")return D$();if(M.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await n1()){await E();continue}}catch(N){if(N.code!=="EEXIST")throw N;if(await i0()==="fresh")return null;await E();continue}try{let N=await v();if(N.status==="live")return D$();if(!J0(M.identity,N))continue;if(!await l())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await l())return null;let R=await v(!1);if(!J0(M.identity,R))continue;if(await a(Z),!await l())return null;if($.onStep)await $.onStep("stale-lock-removed");if(k0=await g(),!k0)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await l())return await V0(),k0=!1,null;break}finally{await I1()}}if(!k0)return null;return M$(),{ownerId:z,whenLost:()=>H,hasLost:()=>Y!==void 0,assertOwned:async()=>{if(L)throw L;let V;try{let M=await F();if(V=M,!Q&&!Y&&M?.ownerId===z&&Number(M?.expiresAt)>X())return;B(M?.ownerId!==z?"taken-over":"expired",M)}catch(M){if(B("unreadable"),_&&M instanceof w)throw M}throw new D0({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,D(),await C;let M=performance.now()+m+1000,N=5,R;for(;;){try{let h=!1;if(await b(async()=>{let N$;try{N$=await F()}catch(L$){if(_&&L$.code==="ENOENT"){h=!0;return}throw L$}if(N$?.ownerId!==z){h=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await l())return;await a(Z),h=!0},M)){if(_&&!h)throw new w(Z,"release-not-confirmed",{code:"EIO"});W=h;return}if(V?.aborted)return;await i0(M)}catch(h){if(!s(h,Z)){if(_)throw h;return}R??=h}let S=M-performance.now();if(S<=0)break;if(await new Promise((h)=>setTimeout(h,Math.min(N,S))),_&&performance.now()>=M)break;N=Math.min(N*2,50)}if(_)throw R??new w(Z,"release-not-confirmed",{code:"ETIMEDOUT"})}}}import{ClaustrumCredentialError as I8}from"@cortexkit/claustrum-client";var i$=new WeakSet;function o$($){return i$.has($)}function
|
|
9
|
+
`;if(_)await $1(I,R);else await s$(I,R)}catch(N){let R=await R1(M,V);if(n$(N)&&!R)return!1;try{await I1(V)}catch{}throw N}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function i0(V){let M;try{M=await T1(A)}catch(S){if(S.code==="ENOENT")return"missing";throw S}if(_)try{await n(A,"directory",!0)}catch(S){if(S.code==="ENOENT")return"missing";throw S}if(M.mtimeMs+m>X()){let S=!0;try{await T1(I)}catch(h){if(h.code==="ENOENT")S=!1;else return"fresh"}if(S)return"fresh";if(M.mtimeMs+A8>X())return"fresh"}if($.onStep)await $.onStep("stale-marker-stat");let N=`${A}.${k1()}`;try{await d$(A,N)}catch(S){if(S.code==="ENOENT")return"missing";throw S}if($.onStep)await $.onStep("stale-marker-claimed");let R=_?await G1(N):void 0;return await z0(N,async()=>{if(!R)return!0;let S=await G1(N).catch((h)=>{if(h.code!=="ENOENT")throw h;return});return!!S&&s3(R,S)},V),"recovered"}async function b(V,M){try{if(!await n1(M))return!1}catch(S){if(S.code==="EEXIST"){if(_)try{await n(A,"directory",!0),await X0(I,!0)}catch(h){if(h.code!=="ENOENT")throw h}return!1}throw S}let N=!1,R;try{await V()}catch(S){N=!0,R=S}try{await I1(M)}catch(S){if(s(R,Z)&&s(S,A))throw R;throw S}if(N)throw R;return!0}async function V0(){for(let V=0;V<u;V++){if($.onStep)await $.onStep("relinquish-read");let M;try{M=await F()}catch(N){if(_)throw N;return}if(M?.ownerId!==z)return;try{await Q1(Z,{recursive:!0,force:!0});return}catch(N){if(_)throw N;await E()}}}function M$(){if(!$.renew||Q||Y)return;let V=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=C8(()=>{G=null;let M=(async()=>{let N=!Q;try{if(!await b(async()=>{let S=await F(),h=X();if(Q||Y){N=!1;return}if(S?.ownerId!==z){B("taken-over",S),N=!1;return}if(!(Number(S?.expiresAt)>h)){B("expired",S),N=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(Q||Y){N=!1;return}if(!await l())return;if($.onStep)await $.onStep("renewal-write-fenced");if(Q||Y){N=!1;return}if(!await l())return;if($.onStep)await $.onStep("renewal-write-ready");if(Q||Y){N=!1;return}if(await q(),$.onStep)await $.onStep("renewal-write-finished");if(!await l()){B("marker-lost"),N=!1,await V0();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(R){if(_&&R instanceof w)L=R,B("renewal-failed"),N=!1;try{let S=await F();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(N&&!Q&&!Y)M$()}})();C=M,M.finally(()=>{if(C===M)C=null})},V),"unref"in G)G.unref();K("scheduled")}function D$(){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 k0=await g();if(!k0)for(let V=0;V<u;V++){if(k0=await g(),k0)break;let M=await v();if(M.status==="live")return D$();if(M.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await n1()){await E();continue}}catch(N){if(N.code!=="EEXIST")throw N;if(await i0()==="fresh")return null;await E();continue}try{let N=await v();if(N.status==="live")return D$();if(!J0(M.identity,N))continue;if(!await l())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await l())return null;let R=await v(!1);if(!J0(M.identity,R))continue;if(await a(Z),!await l())return null;if($.onStep)await $.onStep("stale-lock-removed");if(k0=await g(),!k0)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await l())return await V0(),k0=!1,null;break}finally{await I1()}}if(!k0)return null;return M$(),{ownerId:z,whenLost:()=>H,hasLost:()=>Y!==void 0,assertOwned:async()=>{if(L)throw L;let V;try{let M=await F();if(V=M,!Q&&!Y&&M?.ownerId===z&&Number(M?.expiresAt)>X())return;B(M?.ownerId!==z?"taken-over":"expired",M)}catch(M){if(B("unreadable"),_&&M instanceof w)throw M}throw new D0({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,D(),await C;let M=performance.now()+m+1000,N=5,R;for(;;){try{let h=!1;if(await b(async()=>{let N$;try{N$=await F()}catch(L$){if(_&&L$.code==="ENOENT"){h=!0;return}throw L$}if(N$?.ownerId!==z){h=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await l())return;await a(Z),h=!0},M)){if(_&&!h)throw new w(Z,"release-not-confirmed",{code:"EIO"});W=h;return}if(V?.aborted)return;await i0(M)}catch(h){if(!s(h,Z)){if(_)throw h;return}R??=h}let S=M-performance.now();if(S<=0)break;if(await new Promise((h)=>setTimeout(h,Math.min(N,S))),_&&performance.now()>=M)break;N=Math.min(N*2,50)}if(_)throw R??new w(Z,"release-not-confirmed",{code:"ETIMEDOUT"})}}}import{ClaustrumCredentialError as I8}from"@cortexkit/claustrum-client";var i$=new WeakSet;function o$($){return i$.has($)}function c(){return process.env.CORTEXKIT_VAULT_HOST==="thalamus"}function i3($){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 I8(Z.code,Z.class,Z.action);if(Z.name==="ClaustrumUnreachableError"||typeof Z.code==="string"&&Y0(Object.assign(Error(),{code:Z.code}))==="unreachable")return new p;return $}function E1($){try{return $()}catch(Z){throw i3(Z)}}async function f0($){try{return await $()}catch(Z){throw i3(Z)}}function R8($){let Z=$.watchScoped?.bind($),J=$.reportUsageScoped?.bind($);return{listScoped:(...z)=>f0(()=>$.listScoped(...z)),getScoped:(...z)=>f0(()=>$.getScoped(...z)),reportAuthFailureScoped:(...z)=>f0(()=>$.reportAuthFailureScoped(...z)),close:()=>E1(()=>$.close()),...Z&&{watchScoped:(...z)=>{let X=E1(()=>Z(...z));return{stop:()=>E1(()=>X.stop()),closed:f0(async()=>{let G=await X.closed;return G.kind==="refused"||G.kind==="transport_lost"?{...G,error:i3(G.error)}:G})}}},...J&&{reportUsageScoped:(...z)=>f0(()=>J(...z))},...$.insula&&{insula:S8($.insula)}}}function S8($){let Z=$.watchUsage?.bind($);return{connectionFile:$.connectionFile,getUsage:()=>f0(()=>$.getUsage()),...Z&&{watchUsage:(...J)=>{let z=E1(()=>Z(...J));return{stop:()=>E1(()=>z.stop()),closed:f0(()=>z.closed)}}}}}function x0($){if(!c()||!$)throw new p;try{let Z=globalThis[Symbol.for("cortexkit.vault")];if(typeof Z!=="function")throw new p;let J=R8(Z($));return i$.add(J),J}catch{throw new p}}var w8=1,X3=16384,z2=30000,e3=/^[0-9a-f]{64}$/,X2="unknown_method",G2=new Set([X2,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),Q2=new Set(["pending_queue_full"]);function r3($){if(!($ instanceof h8))return;if(G2.has($.code))return{code:$.code,disposition:"terminal"};if(Q2.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function W2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function z3($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function Y2($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function b1(){return new O("invalid-state","invalid Claustrum enrollment state")}function $9($){if(!W2($)||$.version!==w8||typeof $.proposedName!=="string"||$.proposedName.length===0)throw b1();if($.phase==="pending"){if(!e3.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!z3($.createdAt)||!z3($.updatedAt))throw b1();return{version:1,phase:"pending",proposedName:$.proposedName,requestSecret:$.requestSecret,...$.requestId!==void 0&&{requestId:$.requestId},createdAt:$.createdAt,updatedAt:$.updatedAt}}if($.phase==="approved"){if($.approvedName!==void 0&&(typeof $.approvedName!=="string"||$.approvedName.length===0)||!Y2($.tokenGeneration)||!z3($.updatedAt))throw b1();return{version:1,phase:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration,updatedAt:$.updatedAt}}if($.phase==="denied"||$.phase==="blocked"){if($.errorCode!==void 0&&typeof $.errorCode!=="string"||!z3($.updatedAt))throw b1();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw b1()}function Z9($){if(!W2($)||!e3.test(String($.token??""))||!Y2($.token_generation))throw new O("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function H2($){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 t$($){try{return JSON.parse($)}catch{throw new O("invalid-state","Claustrum enrollment file is not valid JSON")}}async function v0($){if(_)try{await H0(g0($));let J=await X0($,!0);if(Buffer.byteLength(J)>X3)throw new O("unsafe-file","Claustrum enrollment file is too large");return t$(J)}catch(J){if(J.code==="ENOENT")return;throw J}let Z;try{Z=await Z2($,r$.O_RDONLY|r$.O_NOFOLLOW)}catch(J){if(J.code==="ENOENT")return;throw new O("unsafe-file","Claustrum enrollment file could not be opened safely")}try{H2(await Z.stat());let J=Buffer.alloc(X3+1),{bytesRead:z}=await Z.read(J,0,J.byteLength,0);if(z>X3)throw new O("unsafe-file","Claustrum enrollment file is too large");return t$(J.subarray(0,z).toString("utf8"))}finally{await Z.close()}}function e$($,Z){let J=[];for(let z of $.split(`
|
|
10
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 u8($,Z,J){try{let[z,X]=await Promise.all([o3(J.passwdPath??"/etc/passwd","utf8"),o3(J.groupPath??"/etc/group","utf8")]),G=e$(z,7),Q=e$(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 U=W[0]?.[0],H=Y[0]?.[3]??"";return(H===""||H.split(",").every((K)=>K===U))&&!G.some((K)=>Number(K[2])!==$&&Number(K[3])===Z)}catch{return!1}}function U2($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>o3(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 x8($)}catch{return}let G;for(;;){let Q=await J2(X).catch(()=>{return});if(Q&&(Q.mode&18)!==0&&(Q.mode&512)===0){if(G===void 0)G=z!==void 0&&await u8(J,z,Z);if((Q.mode&2)!==0||Q.uid!==J||Q.gid!==z||!G)throw new O("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${X}. Another user could replace it. Run: chmod g-w,o-w ${X}`)}let W=g0(X);if(W===X)return;X=W}}try{await j0($,U2(Z))}catch(J){if(!(J instanceof w))throw J;throw new O("unsafe-file",`Claustrum enrollment parent refused: ${J.path} (${J.reason??J.code}). Use a folder that other users cannot write or replace.`)}}async function Y1($,Z={},J="enrollment directory"){if(_){await H0($,!1,U2(Z));return}await f8($,{recursive:!0,mode:448});let z=await J2($),X=process.geteuid?.();if(X!==void 0&&z.uid!==X)throw new O("unsafe-file",`Claustrum ${J} must be owned by the current user`);if((z.mode&63)!==0)await b8($,448)}async function y0($,Z,J={}){let z=g0($);await Y1(z,J),await K2(z,J);let X=`${JSON.stringify(Z)}
|
|
11
11
|
`;if(Buffer.byteLength(X)>X3)throw new O("invalid-state","Claustrum enrollment state is too large");if(_)return Z1($,X);let G=v8(z,`.${g8($)}.${process.pid}.${E8()}.tmp`),Q,W=!1;try{Q=await Z2(G,"wx",384),W=!0,await Q.writeFile(X,"utf8"),await Q.chmod(384),await Q.sync(),await Q.close(),Q=void 0,await y8(G,$),W=!1}finally{if(await Q?.close().catch(()=>{}),W)await t3(G).catch(()=>{})}}var c8=new b0;async function G3($,Z){let J=_?await $2($,Z):await c8.read([$.tokenPath,$.statePath],async([X=$.tokenPath,G=$.statePath])=>$2({tokenPath:X,statePath:G},Z),(X)=>{for(let G of X)if(G!=="absent")H2(G)}),z={...J.status};if(J.usesProposedName&&z.state==="approved")z.proposedName=Z;return z}async function $2($,Z){let J=await v0($.tokenPath),z=J===void 0?void 0:Z9(J),X=await v0($.statePath),G=X===void 0?void 0:$9(X);if(z)return{usesProposedName:G===void 0,status:{state:"approved",proposedName:G?.proposedName??Z,...G?.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:z.token_generation}};if(!G)return{status:{state:"idle"},usesProposedName:!1};if(G.phase==="approved")return{usesProposedName:!1,status:{state:"blocked",proposedName:G.proposedName,code:"missing_token"}};return{status:A0(G),usesProposedName:!1}}async function _0($){let Z=await v0($);if(Z===void 0)throw new O("not-enrolled","Claustrum enrollment is not configured");return Z9(Z)}function A0($){if($.phase==="pending")return{state:"pending",proposedName:$.proposedName,...$.requestId!==void 0&&{requestId:$.requestId}};if($.phase==="approved")return{state:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration};if($.phase==="denied")return{state:"denied",proposedName:$.proposedName};return{state:"blocked",proposedName:$.proposedName,code:$.errorCode??"unknown"}}function q2(){return new O("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class J9{#$;#Z;#X;#Q;#G;#W;#z;constructor($){this.#z=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#X=$.proposedName,this.#Q=$.now??Date.now,this.#G=$.mintSecret??(()=>k8(32).toString("hex")),this.#W=$.writeTokenFile??m8}async status(){return G3(this.#Z,this.#X)}async resetTerminal(){return F2(this.#Z,this.#X)}async#J($,Z){let J={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#Q()};return await y0(this.#Z.statePath,J,this.#z),A0(J)}async reconcile(){await Y1(g0(this.#Z.statePath),this.#z);let $=await N0({name:"ceremony",path:this.#Z.statePath,ttlMs:z2,renew:!0});if(!$)return{state:"busy"};try{let Z=await v0(this.#Z.tokenPath),J=Z===void 0?void 0:Z9(Z),z=await v0(this.#Z.statePath),X=z===void 0?void 0:$9(z);if(X&&X.proposedName!==this.#X)throw q2();if(J){if(!X||X.phase==="pending"){let Q={version:1,phase:"approved",proposedName:X?.proposedName??this.#X,tokenGeneration:J.token_generation,updatedAt:this.#Q()};await y0(this.#Z.statePath,Q,this.#z),X=Q}return{state:"approved",proposedName:X.proposedName,...X.phase==="approved"&&X.approvedName!==void 0&&{approvedName:X.approvedName},tokenGeneration:J.token_generation}}if(X?.phase==="approved"){let Q={version:1,phase:"blocked",proposedName:X.proposedName,errorCode:"missing_token",updatedAt:this.#Q()};return await y0(this.#Z.statePath,Q,this.#z),A0(Q)}if(X&&X.phase!=="pending")return A0(X);if(!X){let Q=this.#Q();if(X={version:1,phase:"pending",proposedName:this.#X,requestSecret:this.#G(),createdAt:Q,updatedAt:Q},!e3.test(X.requestSecret))throw new O("invalid-state","invalid minted Claustrum enrollment secret");await y0(this.#Z.statePath,X,this.#z)}if(!X.requestId)try{let Q=T8("sha256").update(Buffer.from(X.requestSecret,"hex")).digest("hex"),W=await this.#$.enrollPropose({name:X.proposedName,requestSecretHash:Q});X={...X,requestId:W.requestId,updatedAt:this.#Q()},await y0(this.#Z.statePath,X,this.#z)}catch(Q){let W=r3(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,retryCode:W.code};if(W.code===X2)return await $.assertOwned(),await t3(this.#Z.statePath).catch((Y)=>{if(Y.code!=="ENOENT")throw Y}),{state:"unavailable",proposedName:X.proposedName,code:W.code};return this.#J(X,W.code)}let G=X.requestId;if(!G)return A0(X);try{let Q=await this.#$.enrollPoll({requestId:G,requestSecret:X.requestSecret});if(Q.status==="pending")return A0(X);if(Q.status==="denied"){let Y={version:1,phase:"denied",proposedName:X.proposedName,updatedAt:this.#Q()};return await y0(this.#Z.statePath,Y,this.#z),A0(Y)}await Y1(g0(this.#Z.tokenPath),this.#z),await K2(g0(this.#Z.tokenPath),this.#z),await this.#W(this.#Z.tokenPath,{token:Q.token,token_generation:Q.tokenGeneration});let W={version:1,phase:"approved",proposedName:X.proposedName,approvedName:Q.name,tokenGeneration:Q.tokenGeneration,updatedAt:this.#Q()};return await y0(this.#Z.statePath,W,this.#z),A0(W)}catch(Q){let W=r3(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,requestId:G,retryCode:W.code};return this.#J(X,W.code)}}finally{await $.release()}}}async function F2($,Z){await Y1(g0($.statePath));let J=await N0({name:"ceremony",path:$.statePath,ttlMs:z2,renew:!0});if(!J)return"busy";try{if(await v0($.tokenPath)!==void 0)return"refused-approved";let z=await v0($.statePath);if(z===void 0)return"idle";let X=$9(z);if(X.proposedName!==Z)throw q2();if(X.phase==="pending")return"refused-pending";return await J.assertOwned(),await t3($.statePath),"reset"}finally{await J.release()}}var z9="claustrum-tombstone:v1:";function H1($,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 U1($,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 p8}from"@cortexkit/claustrum-client";function B2($){return $!==null&&typeof $==="object"&&(Object.getPrototypeOf($)===Object.prototype||Object.getPrototypeOf($)===null)}class X9{options;#$=new Map;#Z=new Map;#X=new Set;#Q;#G;#W=!1;#z=!1;#J=0;constructor($){this.options=$}state(){return{pending:this.#$.size,inFlight:this.#G!==void 0,dropped:this.#J}}report($,Z){if(this.#W||!this.options.client.reportUsageScoped)return;try{if(!this.options.owns($)){this.#J++;return}if(!B2(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(!B2(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.#Q&&!this.#G)this.#Q=this.options.setTimeout(()=>{this.#Q=void 0,this.#V()},1000),this.#Q.unref?.()}catch{this.#J++}}forget($){if(this.#$.delete($))this.#J++;this.#Z.delete($)}#V(){if(this.#G||!this.#$.size||this.#z)return this.#G;let $=Promise.resolve().then(async()=>{while(!this.#z&&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.#z||!this.options.owns(J)){if(!this.#z)this.#J++;continue}await this.options.client.reportUsageScoped?.({credentialId:J,reading:z,enrollmentToken:X})}catch(X){if(!this.#z)this.#J++;this.#Y(X)}}});return this.#G=$,$.finally(()=>{this.#G=void 0}),$}#Y($){let Z="transport_error";try{if($ instanceof p8)Z=/^[a-z][a-z0-9_]{0,63}$/.test($.code)?$.code:Z;if(this.#X.has(Z))return;this.#X.add(Z),this.options.logger.debug("claustrum usage report dropped",{code:Z})}catch{}}close(){if(this.#W=!0,this.#Q)this.options.clearTimeout(this.#Q);return this.#Q=void 0,this.#V()}drop(){this.#z=!0,this.#J+=this.#$.size+(this.#G?1:0),this.#G=void 0,this.#$.clear(),this.#Z.clear()}}function M2($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function l8($,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 Q9=U0("claustrum");function j2($){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 I0=d8("common-auth.claustrum.phases");function Y9($,Z,J,z=Q9){let X=M2(Z,J);return z.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:J?.recordVersion??null,retry:X,reason:l8(Z,J)}),X}var W9=300000,D2=60000;function G9(){return new O("invalid-material","Claustrum returned invalid credential material")}function a8($){let Z=$.trim();if(Z.startsWith("{")){let J;try{J=JSON.parse(Z)}catch{throw G9()}if(!J||typeof J!=="object")throw G9();let z=J,X=z.access_token??z.access;Z=typeof X==="string"?X:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(z9))throw G9();return Z}function s8($,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=n8($),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 n8($){let Z=$;return{providerIds:Z.providerIds,authMethod:Z.authMethod}}function i8($){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 K1{#$;#Z;#X;#Q;#G;#W;#z;#J=new WeakMap;#V=new WeakMap;#Y=new Map;#H=new WeakMap;#U;#F=new Map;#K;#B;#D=!1;#C=new c;#P;#O=!1;#q=-1/0;#M=2000;#_=!1;#j;#L=new Set;#A=new Set;#R;#E;#N;constructor($){if(p()&&$.client&&!o$($.client))throw new c;let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>_0(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??x0($.pluginId),this.#Q=$.family,this.#G=$.parseIdentity,this.#W=$.requireAssertion??!1,this.#X=$.now??Date.now,this.#z=$.logger??Q9,this.#R=H1(this.#z),this.#K=$.setTimeoutImpl??setTimeout,this.#B=$.clearTimeoutImpl??clearTimeout,this.#U=new X9({client:this.#$,owns:(J)=>this.#F.has(J),token:async()=>p()?"":j2(await this.#Z()),logger:this.#z,setTimeout:this.#K,clearTimeout:this.#B})}transportLost($){if(this.#_||this.#D)return;this.#D=!0,this.#C=$ instanceof V2?$:new c,this.#z.warn("serving kept vault receipt",{reason:"unreachable"}),this.#S()}reachable(){if(this.#_||!this.#D)return;if(this.#D=!1,this.#P)this.#B(this.#P);this.#P=void 0,this.#M=2000;for(let $ of this.#Y.values())$.since=null;(this.#z.info??Q9.info)("vault receipt serving resumed",{reason:"reachable"})}#S(){if(this.#_||!this.#D||this.#P||this.#O)return;this.#P=this.#K(()=>{this.#P=void 0,this.#k(!0)},this.#M),this.#P.unref?.()}#k($=!1){if(this.#_||!this.#D||this.#O)return;if(this.#X()-this.#q<1000){this.#S();return}this.#q=this.#X(),this.#O=!0,this.#f().catch(()=>{if($&&this.#D)this.#M=Math.min(this.#M*2,30000)}).finally(()=>{this.#O=!1,this.#S()})}#I($){if(this.#_)throw new O("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#y($){if(this.#I($),p())return"";if(I0.hasSubscribers)I0.publish({logger:this.#z,phase:"token read begin"});let Z=this.#Z();this.#A.add(Z);let J;try{J=await Z}finally{if(this.#A.delete(Z),I0.hasSubscribers)I0.publish({logger:this.#z,phase:"token read end"})}return this.#I($),j2(J)}async#b($,Z){this.#I(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.#I(Z),Y0(X)==="unreachable")this.transportLost(X);else this.reachable();if(X instanceof V2)throw X;if(Y0(X)==="unreachable")throw new c;throw new O("unavailable","Claustrum scoped operation unavailable")}finally{z?.()}return this.#I(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.#Y.clear(),this.#g(),H}if(I0.hasSubscribers)I0.publish({logger:this.#z,phase:"list scoped begin"});try{Z=await this.#b(()=>this.#$.listScoped(J),$)}catch(H){throw this.listFailed(H),H}finally{if(I0.hasSubscribers)I0.publish({logger:this.#z,phase:"list scoped end"})}let z=[],X=[],G=0,Q=[],W=new Map;for(let H of Z.rows){let K=s8(H,this.#Q);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:D}of Q){let B;if(!H.id.trim())B="empty credential id";else if((W.get(H.id)??0)>1)B="duplicate credential id";else if(H.accountId!==void 0&&!H.accountId.trim())B="blank account identity";else if(!H.state.trim())B="empty state";if(B){z.push({...H.id.trim()&&{credentialId:H.id},...D!==void 0&&{member:D},reason:B});continue}Y.push(Object.freeze({credentialId:H.id,credentialType:K,...D!==void 0&&{member:D},...H.accountId!==void 0&&{accountIdentity:H.accountId},state:H.state,...H.email!==void 0&&{email:H.email},...H.orgName!==void 0&&{orgName:H.orgName}}))}for(let H of z)this.#z.warn("skipped malformed vault record",H);let U=i8(Z);return{view:Z.view,credentials:Object.freeze(Y),skipped:Object.freeze(z),..."classify"in this.#Q&&{refused:Object.freeze(X),notMine:G},...U&&{grantReach:U}}}listFailed($){if(Y0($)==="unreachable")this.transportLost($);else this.reachable(),this.#Y.clear(),this.#g()}forget($){this.#Y.delete($),this.#F.delete($),this.#U.forget($)}#g(){for(let $ of this.#F.keys())this.#U.forget($);this.#F.clear()}retain($){let Z=new Map($.map((J)=>[J.credentialId,J]));for(let[J,z]of this.#Y){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.#F){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.#Y){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.#X()>D2}async authorize($,Z,J="vault"){this.#I(Z);let{credentialId:z,credentialType:X,accountIdentity:G}=$,Q=this.#Y.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.#Y.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.#Y.set(z,{attempt:Y,routeId:J,since:null}),this.#F.set(z,{...$}),Y}catch(Y){if(this.#I(Z),Y0(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.#Y.get($)!==Z||!this.#x(Z.attempt))throw this.forget($),X;if(Z.since===null)Z.since=this.#X();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,client:this.#$}),this.#H.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.#W&&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:W9}}),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.#X()<W9))throw new O("insufficient-validity","Claustrum served credential has insufficient validity");let Y=a8(Q.material),U=Q.accountId?.trim()?Q.accountId:void 0;if(this.#W&&(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 D=K??G,L=Object.freeze(Object.defineProperty({credentialId:z,credentialType:X,...D!==void 0&&{accountIdentity:D},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,client:this.#$}),L}async reportFailure($,Z,J){if(Z!==401)return;this.#I();let z=this.#J.get($);if(!z)throw new O("no-receipt","Claustrum failure report requires an original dispatch receipt");let X=this.#H.get($);if(X!==void 0){this.forget($.credentialId),this.#z.debug("scoped 401 not reported",{routeId:X,reason:"kept-receipt"});return}let G=this.#Y.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let Q=this.#V.get($);if(Q)return Q;let W=this.#b(()=>z.client.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:z.token,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#V.set($,W);try{await W,this.#z.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:J})}catch(Y){throw this.#V.delete($),Y}}watchRoster($){this.#I();let Z=new r1({client:this.#$,enrollmentToken:()=>this.#y(),view:$.view??(()=>this.#j),discover:async(J)=>{await $.onView(J)},onRefused:(J)=>{this.listFailed(J),$.onRefused?.(J)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#z,now:this.#X,setTimeoutImpl:this.#K,clearTimeoutImpl:this.#B});return this.#L.add(Z),Z.start(),{get mode(){return Z.mode},close:()=>{this.#L.delete(Z),Z.stop()}}}reportUsage($){if(this.#_)return;try{this.#U.report($.credentialId,$.reading)}catch{}}usageReportState(){return this.#U.state()}close(){if(this.#_)return;if(this.#_=!0,this.#P)this.#B(this.#P);this.#P=void 0;for(let Z of this.#L)Z.stop();this.#L.clear(),this.#Y.clear();let $=this.#U.close();if($)this.#A.add($),$.then(()=>this.#A.delete($));else this.#$.close();this.#N=U1(this.#A,(Z)=>(this.#E??this.#R)(Z)).finally(()=>{if(this.#U.drop(),this.#F.clear(),$)this.#$.close()})}async dispose($=this.#R){this.#E=$,this.close(),await this.#N}}import{resolve as K3}from"node:path";var H9=30000,U9={now:()=>performance.now(),schedule($,Z){let J=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(J),unref:()=>J.unref?.()}}};var h0="all",o8=Object.freeze(["primary"]);function L2($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function F1($,Z){return JSON.stringify([$,Z])}function R0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function i($){return typeof $==="number"&&Number.isFinite($)}function N2($){return typeof $==="string"&&$.length>0}function o($,Z,J){return $[Z]===void 0||J($[Z])}function r8($){return i($)&&$>0}function K9($){return typeof $==="string"}function t8($){if(!R0($)||!N2($.scope)||!N2($.label))return!1;switch($.kind){case"reading":return i($.checkedAt)&&i($.usedPercent)&&o($,"resetsAt",K9)&&o($,"windowMinutes",r8);case"retired":return i($.retiredAt);case"absent":return i($.checkedAt);default:return!1}}function e8($){if(!R0($)||!i($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&o($,"remainingPercent",i)&&o($,"usedPercent",i)&&o($,"resetsAt",K9)&&o($,"limit",i)&&o($,"used",i)&&o($,"remaining",i)&&o($,"unit",K9)}function P2($){return R0($)&&i($.value)&&Number.isInteger($.value)&&$.value>=0&&i($.checkedAt)}function q9($){return R0($)&&Object.values($).every(P2)}function $6($){return typeof $==="boolean"}function B1($){return R0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&o($,"balance",i)&&o($,"overageLimitReached",$6)&&i($.checkedAt)}function C2($){if(!R0($))return;let Z=Object.entries($).filter(([,J])=>P2(J));return Z.length===0?void 0:Object.fromEntries(Z)}function m0($){if(q1($))return $;if(!R0($))return;let{counters:Z,credits:J,...z}=$;if(!q1(z))return;let X=C2(Z),G=B1(J)?J:void 0;return{...z,...X===void 0?{}:{counters:X},...G===void 0?{}:{credits:G}}}function q1($){if(!R0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!t8(J))return!1;let z=F1(J.scope,J.label);if(Z.has(z))return!1;Z.add(z)}return o($,"budget",e8)&&o($,"counters",q9)&&o($,"credits",B1)}class Q3 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function Y3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function W3($){return typeof $==="number"&&Number.isFinite($)}function O2($){return $===void 0||typeof $==="string"&&$!==""}function A2($){return typeof $==="string"&&$!==""}function f1($,Z){return $[Z]===void 0||W3($[Z])}function F9($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function Z6($){return Y3($)&&O2($.scope)&&A2($.label)&&W3($.usedPercent)&&F9($,"resetsAt")&&($.windowMinutes===void 0||W3($.windowMinutes)&&$.windowMinutes>0)}function J6($){return Y3($)&&O2($.scope)&&A2($.label)}function z6($){if(!Y3($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&f1($,"remainingPercent")&&f1($,"usedPercent")&&F9($,"resetsAt")&&f1($,"limit")&&f1($,"used")&&f1($,"remaining")&&F9($,"unit")}function V1($){if(!Y3($)||!W3($.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(!Z6(X))return!1;let G=F1(X.scope??h0,X.label);if(z.has(G))return!1;z.add(G)}if(!J.every(J6))return!1;return($.budget===void 0||z6($.budget))&&($.counters===void 0||q9($.counters))&&($.credits===void 0||B1($.credits))}function X6($,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 Q6($,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 W6($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function x1($,Z){let J=$===void 0?void 0:m0($);if($!==void 0&&J===void 0)throw new Q3("stored quota map is malformed");if(!V1(Z))throw new Q3("quota observation is malformed");let z=J??{limits:[]},X=Z.checkedAt,G=new Map;for(let A of z.limits)G.set(F1(A.scope,A.label),A);let Q=(A)=>{let I=G.get(A);return I===void 0||X>=L2(I)},W=new Set;for(let A of Z.readings??[]){let I=A.scope??h0,T=F1(I,A.label);if(W.add(T),!Q(T))continue;G.set(T,{scope:I,label:A.label,kind:"reading",checkedAt:X,usedPercent:A.usedPercent,...A.resetsAt===void 0?{}:{resetsAt:A.resetsAt},...A.windowMinutes===void 0?{}:{windowMinutes:A.windowMinutes}})}for(let A of Z.coverage??[]){let I=A.scope??h0,T=F1(I,A.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:A.label,kind:"absent",checkedAt:X}:{scope:I,label:A.label,kind:"retired",retiredAt:X})}let{limits:Y,budget:U,counters:H,credits:K,...D}=z,B=G6(z.budget,Z.budget,X),L=Q6(z.counters,Z.counters),C=W6(z.credits,Z.credits);return{...D,limits:[...G.values()].sort(X6),...B===void 0?{}:{budget:B},...L===void 0?{}:{counters:L},...C===void 0?{}:{credits:C}}}var Y6=Object.freeze({validate:q1,decode:m0,merge:x1});function _2($,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 q6}from"node:crypto";import{stat as F6}from"node:fs/promises";import{resolve as y1}from"node:path";function I2($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function B9($,Z,J){return $.some((z)=>I2(z,Z,J))}function V9($,Z,J){let z={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((X)=>X.credentialId!==Z||X.accountIdentity!==J),z]}function j9($,Z,J){return $.filter((z)=>!Z.some((X)=>I2(z,X,J)))}function D9($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>K0(Z).map((J)=>({credentialId:J,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function B6($,Z){let J=K0(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 U3="vault:";function V6($){return q6("sha256").update($).digest("hex")}function j6($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function M6($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function K0($){return[$.credentialId,...$.aliases??[]]}function T2($,Z,J={}){let z=J.now??Date.now(),X=J.routePrefix??U3,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((F)=>F.credentialId)),K=new Set(Z.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),D=Z.skipped.some((F)=>F.credentialId===void 0),B=(F)=>!H.has(F)&&(K.has(F)||D),L=new Map;for(let F of Q){if(F.accountIdentity===void 0)continue;for(let q of K0(F))if(!L.has(q))L.set(q,F.accountIdentity)}let C=new Map;for(let F of Z.credentials){let q=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:L.get(F.credentialId),claimed:!1},j=M6(q),P=C.get(j)??[];P.push(q),C.set(j,P)}let A=new Set,I=new Set(G),T=[],m=(F,q)=>F.credential.credentialId.localeCompare(q.credential.credentialId),u=[...C.values()].map((F)=>F.toSorted(m)).sort((F,q)=>F[0]&&q[0]?m(F[0],q[0]):0);for(let F of u){let q=F[0]?.identity,j=F.filter((b)=>b.credential.state==="active"),P=j.length?j:F,g=P.filter((b)=>b.claimed),E=g.length?g:P,v=new Set(F.map((b)=>b.credential.credentialId)),J0=Q.find((b)=>!A.has(b)&&K0(b).some((V0)=>v.has(V0))&&(b.accountIdentity===void 0||b.accountIdentity===q)),l=E.find((b)=>b.credential.credentialId===J0?.credentialId)??E[0];if(!l)continue;let a=l.credential,s=J0??(q===void 0?void 0:Q.find((b)=>!A.has(b)&&b.accountIdentity===q));if(s)A.add(s);let z0=s?.routeId;if(!z0||G.has(z0)){let b=`${X}${a.credentialId}${q===void 0?"":`~${V6(q).slice(0,10)}`}`;z0=b;for(let V0=2;I.has(z0);V0++)z0=`${b}~${V0}`}I.add(z0);let I1=s?K0(s).filter(B):[],R1=[...new Set([...F.map((b)=>b.credential.credentialId),...I1])].filter((b)=>b!==a.credentialId).sort((b,V0)=>b.localeCompare(V0)),n1=J.mapAccount?.(a)??{};T.push({previousIndex:s?Q.indexOf(s):1/0,row:{routeId:z0,credentialId:a.credentialId,credentialType:a.credentialType,...q!==void 0&&{accountIdentity:q},...R1.length&&{aliases:R1},state:a.state,label:n1.label?.trim()||j6(a),...a.email!==void 0&&{email:a.email},...a.orgName!==void 0&&{orgName:a.orgName},enabled:![a.credentialId,...R1].some((b)=>B9(Y,b,q)),addedAt:s?.addedAt??z,...s?.quota!==void 0&&{quota:s.quota},...!l.claimed&&q!==void 0&&{unclaimed:!0}}});let i0=T.at(-1);if(W&&i0)i0.previousIndex=B6(W,i0.row)}return Q.forEach((F,q)=>{if(A.has(F)||!K0(F).some(B))return;if(I.has(F.routeId))return;let[j,...P]=K0(F).filter((v)=>!H.has(v));if(j===void 0)return;I.add(F.routeId);let{aliases:g,...E}=F;T.push({previousIndex:q,row:{...E,credentialId:j,...P.length&&{aliases:P},stale:!0}})}),T.sort((F,q)=>F.previousIndex===q.previousIndex?F.row.credentialId.localeCompare(q.row.credentialId):F.previousIndex-q.previousIndex),{version:1,view:Z.view,...$?.limits!==void 0&&{limits:$.limits},complete:U,...!U&&{rejected:Z.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:T.map((F)=>F.row),declined:Y}}function N9($){return($?.rows??[]).filter((Z)=>Z.enabled&&Z.state==="active").map((Z)=>({id:Z.routeId,kind:Z.credentialType==="oauth"?"oauth":"api-key",...Z.quota!==void 0&&{quota:Z.quota}}))}function g1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function j1($){return $===void 0||typeof $==="string"}function D6($){let Z=g1($)?m0($.quota):void 0;if(!g1($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!j1($.accountIdentity)||!j1($.email)||!j1($.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 N6=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function R2($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!g1(J)||!j1(J.credentialId)||typeof J.reason!=="string"||!N6.has(J.reason))return;Z.push(J)}return Z}function k2($){if(!g1($)||$.version!==1||!j1($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!R2($.rejected))throw new O("invalid-state","Claustrum roster file is not valid");let Z=[];for(let X of $.rows){let G=D6(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(!g1(X)||typeof X.credentialId!=="string"||!j1(X.accountIdentity))throw new O("invalid-state","Claustrum roster file is not valid");J.push(X)}let z=R2($.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 L9($){return k2(JSON.parse(JSON.stringify($)))}var L6=new b0({followSymlinks:!0});async function d($){if(_)return M9($);let Z=await L6.read([$],([J=$])=>M9(J));return structuredClone(Z)}async function M9($){let Z;try{Z=await X0($,_)}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 k2(J)}var E2={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},b2={name:"claustrum-roster",ttlMs:30000};async function w0($,Z,J={}){return l3($,{...E2,signal:J.signal},async(z)=>{let X=await M9($),{next:G,result:Q}=await Z(X,{assertOwned:()=>z.assertOwned()});if(G){await z.assertOwned();try{await z1($,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 P9($,Z){return w0($,(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=V9(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 C9($,Z){return w0($,(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:j9(J.declined,K0(z),z.accountIdentity),rows:J.rows.map((X)=>X===z?{...X,enabled:!0}:X)},result:void 0}})}function P6($){return new O("invalid-order",$)}function C6($,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 O9($,Z,J={}){return w0($,(z)=>{let X=z?.rows??[],G=C6(X,Z);if(G)throw P6(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 O6($,Z){if(!K0($).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")&&K0($).length===1)return"bind";return"refuse"}async function A9($,Z){let{routeId:J,observation:z,...X}=Z;return f2($,{routeId:J,observation:z,accountIdentity:X.accountIdentity,receipt:X})}async function f2($,Z){if(!V1(Z.observation))return!1;let J=e($,await d($));if(!S0(J,Z).kept)return!1;return y2($,Z)}function _9($,Z){return f2($,Z)}function S0($,Z){let J=$?.rows.find((Q)=>Q.routeId===Z.routeId),z=!J?"refuse":Z.receipt?O6(J,Z.receipt):J.accountIdentity!==void 0&&J.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!J||z==="refuse")return{roster:$,kept:!1};let X=x1(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 H3=new Map;function v1($){H3.delete(y1($))}function x2($,Z){let J=y1($);if(Z instanceof O)return Z.kind==="roster-busy";if(Z instanceof O0||Z instanceof D0)return y1(Z.details.target)===J;if(Z instanceof w){let z=y1(Z.path);return[E2.name,b2.name].some((X)=>{let G=X1(J,X);return z===G||z.startsWith(`${G}.`)})}return!1}var A6=4;async function S2($){try{let{dev:Z,ino:J,size:z,mtimeMs:X}=await F6($);return{dev:Z,ino:J,size:z,mtimeMs:X}}catch{return}}function _6($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function I6($,Z,J){for(let z=0;z<A6;z++){let X=await S2($),G=await d($),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(!_6(X,await S2($)))continue;if(Y)return"commit";return g2($)?"commit":"unchanged"}return"commit"}async function h1($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){v1($.path);return}let J=await N0({...b2,path:$.path,renew:!0});if(!J){let Q=await d($.path);if($.signal?.throwIfAborted(),!Q?.view)throw new O("roster-busy","Claustrum account discovery is already in progress");return Q}let z=y1($.path),X=$.listedOver,G;try{let Q=await d($.path),W=X?void 0:H3.get(z);G=W&&(W.previousView===Q?.view||W.inventory.view===Q?.view)?W:{inventory:await $.custody.discover($.signal),previousView:Q?.view},H3.delete(z);let{inventory:Y}=G;$.onInventory?.(Y),$.signal?.throwIfAborted();let U=typeof $.projection==="function"?$.projection():$.projection,H=(B)=>T2(B,Y,U),K=async()=>{return $.signal?.throwIfAborted(),await J.assertOwned(),Z()};if(await I6($.path,(B)=>{if(X)return{target:B};let L=e($.path,B);return{target:B,...L!==B&&{local:L}}},H)==="unchanged"){if(!await K())return;return await d($.path)}return await w0($.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 L=H(B);return{...JSON.stringify(B)!==JSON.stringify(L)&&{next:L},result:L}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await J.assertOwned()}})}catch(Q){if(Q instanceof O0&&G&&!X&&!$.signal?.aborted&&await Z())H3.set(z,G);throw Q}finally{await J.release($.signal)}}var u0=new Map,R6=U0("claustrum"),h2=100;function m2($,Z=U9){let J=K3($),z=u0.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},u0.set(J,z);return z}function w2($,Z,J){let z=m2($,J);z.listeners.add(Z);let X;return()=>X??=(()=>{return z.listeners.delete(Z),z.listeners.size?Promise.resolve():I9($)})()}function S6($){return _2($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function y2($,Z){if(!V1(Z.observation))return Promise.resolve(!1);let J=m2($),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 S6(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 c2(J,h2),Promise.resolve(!0)}function u2($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,J)=>Z.order-J.order)}function e($,Z){let J=u0.get(K3($));if(J)for(let z of u2(J.pending)){if(z.priorReading)Z=S0(Z,z.priorReading).roster;Z=S0(Z,z.publication).roster}return Z}function g2($){return!!u0.get(K3($))?.pending.size}function c2($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let J=$.draining?0:($.committedAt??-1/0)+H9-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,J),()=>{return $.timer=void 0,p2($)}),!$.draining)$.timer.unref?.()}function v2($){$.timer?.cancel(),$.timer=void 0}function p2($){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 w0($.path,(z)=>{let X=z;for(let Q of u2(Z)){if(Q.priorReading)X=S0(X,Q.priorReading).roster;X=S0(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)R6.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()):h2;c2($,J)}})(),$.running}async function I9($,Z=1000){let J=K3($),z=u0.get(J);if(!z)return;z.draining=!0,v2(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)p2(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(),v2(z),z.pending.clear(),u0.get(J)===z)u0.delete(J)}}}var q3=1e4;function d2(){return new c}var R9;function a2($,Z){if(!R9)throw Error("ClaustrumConsumer is not initialized");return R9($,Z)}function l2(){return new O("not-active","Claustrum scoped custody is not active")}class S9{#$;#Z=new AbortController;#X;#Q;#G;#W;#z;#J;#V;#Y;#H=!1;#U=new Set;#F;#K;#B;#D;#C=new Map;#P;#O;#q;#M;#_=new WeakMap;static{R9=($,Z)=>{let J=new S9(Z);return J.#q=$,{consumer:J,hooks:J.#g()}}}constructor($){this.#$=$,this.#X=$.logger??U0("claustrum"),this.#Q=H1(this.#X,this.#Z.signal),this.#O=w2($.rosterPath,(Z)=>{this.#J=S0(this.#J,Z).roster})}#j($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#L($){return this.#U.add($),$.then(()=>this.#U.delete($),()=>this.#U.delete($)),$}async#A(){if(p())return!0;return await this.#$.isCustodyActive?.()??!0}#R($,Z){let J=E0([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.#W){let $={timedOut:!1};this.#W=this.#N($),this.#L(this.#W)}return this.#R(this.#W)}#N($){let Z=this.#$.setTimeoutImpl??setTimeout,J=this.#$.clearTimeoutImpl??clearTimeout,z=(!p()&&this.#$.connect?this.#$.connect():Promise.resolve().then(()=>x0(this.#$.pluginId))).then((Q)=>{if(this.#Z.signal.aborted||$.timedOut){if(Q.close(),!$.timedOut)this.#j();throw d2()}if(this.#G=new K1({client:Q,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#X,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&Q.insula)this.#K=m3(Q.insula,this.#$.tokenPath);return this.#G}),X,G=new Promise((Q,W)=>{X=Z(()=>{if($.timedOut=!0,this.#Z.signal.aborted)return;this.#X.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:this.#S()}),W(d2())},this.#S()),X.unref?.()});return Promise.race([z,G]).finally(()=>{if(X)J(X);this.#W=void 0})}#S(){return this.#$.connectTimeoutMs??q3}snapshot(){return this.#J}grantReach(){if(this.#q)return this.#q.grantReach(this.#J?.view);let $=this.#V;return $&&this.#J?.view===$.view?$.reach:void 0}watchState(){if(this.#q)return Object.freeze({vault:this.#q.watchMode()});return Object.freeze({vault:this.#B?.mode??"polling",...this.#$.insula&&{insula:this.#K?.source.watchMode()??"polling"}})}#k(){this.#B?.close(),this.#B=void 0,this.#D?.(),this.#D=void 0}keptReceiptState(){if(this.#q){let $=this.#M;return $&&this.#q.leaseLive($)?$.custody.keptReceiptState():this.#q.keptReceiptState()}return this.#G?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return N9(this.#J)}refresh(){if(this.#j(),this.#q)return this.#L(this.#x(this.#q));if(this.#z)return this.#z;return this.#z=(async()=>{if(!await this.#A()){if(this.#J=void 0,this.#V=void 0,this.#k(),this.#G)this.#G.close(),this.#L(this.#G.dispose(this.#Q));this.#G=void 0,this.#K?.release(),this.#K=void 0;return}let $=await this.#E(),Z,J=await h1({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.#V=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.#z=void 0}),this.#L(this.#z),this.#I(this.#z),this.#z}#I($){try{this.#$.onDiscovery?.($)}catch(Z){this.#$.onError?.(Z)}}start(){if(this.#H)return;if(this.#j(),this.#H=!0,this.#q){this.#q.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.#Y=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#Y=void 0,this.#L($())},Z),this.#Y.unref?.()};this.#L($())}async#y(){if(this.#B?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#P===void 0||$-this.#P>=r0)return!0;return!await this.#A()}#b(){let $=this.#G;if(this.#Z.signal.aborted||!$)return;if(this.#B??=$.watchRoster({view:()=>this.#J?.view,onView:()=>this.#L((async()=>{while(this.#z)await this.#z.catch(()=>{});if(this.#Z.signal.aborted)return;await this.refresh()})()),onRefused:(Z)=>this.#$.onError?.(Z),onError:(Z)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(Z)}}),this.#$.insula&&this.#K&&!this.#D)this.#D=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.#A())return;try{if(!p())await _0(this.#$.tokenPath);await this.#E(),await this.#K?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#A())return;try{if(!p())await _0(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 _0(this.#$.tokenPath);let J=e(this.#$.rosterPath,await d(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 _0(this.#$.tokenPath);let z=e(this.#$.rosterPath,await d(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.#C.get($)!==J.miss)this.#C.set($,J.miss),this.#X.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.#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.#q)return this.#h(this.#q,$,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.#K?.release(),this.#K=void 0,new O("not-active","Claustrum scoped custody is not active");let z=e(this.#$.rosterPath,await d(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=E0([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.#q;if(!Z||!this.#$.onDiscovery||this.#Z.signal.aborted)return;let J=this.#L($.then((z)=>this.#v(Z,z)));this.#I(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#h($,Z,J){if(this.#j(J),!this.#J)await this.#R($.refresh(),J);let z=this.#J;if(!await $.readAuthority())throw this.#T(),l2();if(this.#j(J),!z)throw new O("route-unavailable","Claustrum has no roster for this provider yet");let X=e(this.#$.rosterPath,await d(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=E0([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.#_.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 l2()}}}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.#q){if(this.#M&&this.#q.leaseLive(this.#M))this.#M.custody.reportUsage($)}else this.#G?.reportUsage($)}catch{}}usageReportState(){try{return(this.#q?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.#q){let z=this.#_.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(Y9(J.site,X,Q,this.#X))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 P9(this.#$.rosterPath,$),this.#J=e(this.#$.rosterPath,await d(this.#$.rosterPath)),this.#J)this.#q?.publishRoster(this.#J);if(this.#q)this.#q.retainUnion();else this.#G?.retain(this.#J?.rows??[])}async accept($){if(this.#j(),await C9(this.#$.rosterPath,$),this.#J=e(this.#$.rosterPath,await d(this.#$.rosterPath)),this.#J)this.#q?.publishRoster(this.#J)}async reorder($){this.#j();let Z=await O9(this.#$.rosterPath,$);if(this.#J=e(this.#$.rosterPath,await d(this.#$.rosterPath)),this.#J)this.#q?.publishRoster(this.#J);return Z}async recordQuota($,Z,J){return this.#j(),A9(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(),_9(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.#Y)(this.#$.clearTimeoutImpl??clearTimeout)(this.#Y);if(this.#Y=void 0,this.#k(),this.#G)this.#G.close(),this.#L(this.#G.dispose(this.#Q));this.#M?.release(),this.#M=void 0,this.#q?.detach(),this.#K?.release(),this.#K=void 0,this.#J=void 0,this.#V=void 0,this.#O(),v1(this.#$.rosterPath)}async dispose(){this.close(),this.#F??=Promise.all([U1(this.#U,this.#Q),this.#O()]).then(()=>{}),await this.#F}}import{createHash as T6}from"node:crypto";import{channel as k6}from"node:diagnostics_channel";import{readdir as E6,stat as b6}from"node:fs/promises";import{dirname as f6,join as M1,resolve as s2}from"node:path";var F3=new Map,x6=/^[a-z0-9][a-z0-9._-]{0,63}$/,y6=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,g6=/^[0-9a-f]{16}$/,n2=3;function k9($,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=k9($[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=k9($[G],J);if(Q===void 0)return;z.push(`${JSON.stringify(G)}:${Q}`)}return`{${z.join(",")}}`}function v6($,Z){let J=k9({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??U3,mapAccount:$.mapAccount?String($.mapAccount):null});if(J===void 0)throw new O("invalid-state","Claustrum hub classifierInput must be plain JSON");return T6("sha256").update(J).digest("hex").slice(0,16)}function i2($,Z){if(typeof $!=="string"||!x6.test($)||y6.test($))throw new O("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function T0($="Claustrum custody lease is closed"){return new O("closed",$)}function T9(){return new O("not-active","Claustrum scoped custody is not active")}function o2(){return new c}function h6($,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 r2($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class t2{#$;#Z;#X;#Q=new AbortController;#G=new Map;#W=new WeakMap;#z=0;#J;#V;#Y;#H;#U;#F;#K=0;#B;#D;#C;#P=!1;#O=new Set;#q;#M;#_;constructor($){if(!$.family||!("classify"in $.family))throw new O("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=i2($.hostGeneration,"host generation"),J=$.members.map((X)=>i2(X,"member"));if(new Set(J).size!==J.length)throw new O("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??U0("claustrum"),this.#X=H1(this.#Z,this.#Q.signal),this.#M=M1($.stateDir,"rosters",Z),this.#_=v6($,J);let z=M1(this.#M,this.#_);for(let X of J)this.#G.set(X,{provider:X,path:M1(z,`${X}.json`),closed:!1})}#j($){return this.#O.add($),$.then(()=>this.#O.delete($),()=>this.#O.delete($)),$}#L(){if(this.#Q.signal.aborted)throw T0("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.#L();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.#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.#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}=a2(z,X);J.hooks=Q;let W=s2(J.path),Y=F3.get(W)??new Set,U=(K)=>{if(J.closed||this.#F!==!0||!this.#J||!this.#N(this.#J)||!Q.roster()||this.#c(Q,K))return;if(J.seen=JSON.stringify(L9(K)),Q.install(K),K.view!==this.#B?.view)J.pending??={failures:0,wait:0};this.#w()};Y.add(U),J.receiveRoster=U,F3.set(W,Y);let H=!0;return J.releaseRoster=()=>{if(!H)return;if(H=!1,Y.delete(U),!Y.size)F3.delete(W)},G}#R($,Z){let J=this.#J;if($.closed||!J||!this.#N(J))return;$.seen=JSON.stringify(L9(Z)),$.hooks?.install(Z);for(let z of F3.get(s2($.path))??[]){if(!this.#N(J))return;if(z!==$.receiveRoster)z(Z)}}#E(){let $={id:++this.#z,count:0,ended:!1,controller:new AbortController};return this.#J=$,$}#N($){return!$.ended&&this.#J===$&&!this.#Q.signal.aborted}#S($){let Z=this.#W.get($);return!!Z&&!Z.released&&!Z.generation.ended}#k($,Z=T0()){if($.ended)return;if($.ended=!0,$.count=0,this.#J===$)this.#J=void 0;if(this.#Y&&this.#W.get(this.#Y)?.generation===$)this.#Y=void 0;if(this.#H?.generation===$)this.#H.watch.close(),this.#H=void 0;if($.controller.abort(Z),$.custody)$.custody.close(),this.#j($.custody.dispose(this.#X))}#I($){if($.ended)return;if($.count--,$.count<=0)this.#k($)}#y($){let Z=this.#V;if(Z?.generation===$&&Z.promise)return Z.promise;let J={generation:$,timedOut:!1},z=this.#$.connectTimeoutMs??q3,X,G=(!p()&&this.#$.connect?this.#$.connect():Promise.resolve().then(()=>x0(this.#$.pluginId))).then((Y)=>{if(J.timedOut)throw Y.close(),o2();if(!this.#N($)||$.count<=0)throw Y.close(),T0("Claustrum connection is no longer wanted");return $.custody=new K1({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.#N($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:z}),U(o2())},z),X.unref?.()});return J.promise=this.#j(Promise.race([G,Q]).finally(()=>{if(X)(this.#$.clearTimeoutImpl??clearTimeout)(X)})),J.promise.finally(()=>{if(this.#V===J)this.#V=void 0}).catch(()=>{}),this.#V=J,J.promise}acquire($){try{if(this.#L(),$?.throwIfAborted(),this.#F===!1)throw T9()}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=E0([$.controller.signal,...Z?[Z]:[]]);try{z=await h6(this.#y($),X.signal)}catch(G){if(!$.ended)throw this.#I($),G;return this.#f(Z,J)}finally{X.dispose()}}if($.ended)return this.#f(Z,J);if(Z?.aborted)throw this.#I($),Z.reason;return this.#g($,z)}#f($,Z){if($?.throwIfAborted(),this.#L(),this.#F===!1)throw T9();if(!Z)throw T0();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 T0()},X=Object.freeze({authorize:async(Q,W,Y)=>{z();let U=E0([$.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.#I($)}});return this.#W.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.#Q.signal.aborted)return!1;let Z=this.#F;if(this.#F=$,!$&&Z!==!1)this.#v();return $}#v(){this.#K++;let $=this.#J;if($)this.#k($,T9());this.#Y=void 0,this.#H?.watch.close(),this.#H=void 0,this.#B=void 0,this.#D=void 0;for(let Z of this.#G.values())Z.seen=void 0,Z.pending=void 0,Z.hooks?.reset(),v1(Z.path)}#T(){return[...this.#G.values()].filter(($)=>$.hooks&&!$.closed)}async#u(){let $=this.#Y,Z=$&&this.#W.get($);if($&&Z&&this.#S($))return Z;this.#Y=void 0;let J=await this.acquire(this.#Q.signal),z=this.#Y&&this.#W.get(this.#Y);if(this.#Y&&z&&this.#S(this.#Y))return J.release(),z;this.#Y=J;let X=this.#W.get(J);if(!X)throw T0();return X}#h(){try{this.#L()}catch(z){return Promise.reject(z)}let $=this.#U;if($&&!$.generation?.ended)return $.promise;let Z={},J=this.#j(this.#n(Z).finally(()=>{if(this.#U===Z)this.#U=void 0}));Z.promise=J,this.#U=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.#N(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 d(H.path).then((K)=>K?{file:K}:{},(K)=>K instanceof Error?K:Error(String(K)))])));if(!this.#N(J))return;let G;try{G=await Z.custody.discover(J.controller.signal)}catch(H){if(!this.#N(J))return;for(let K of this.#G.values())if(K.pending)this.#m(K);throw H}if(!this.#N(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.#N(J))return;let Y=new Map,U=!0;for(let[H,K]of Q.entries()){let D=K.hooks,B=W[H];if(!D||!B)continue;if("error"in B){let{error:C}=B;if(U=!1,this.#m(K),x2(K.path,C))this.#Z.debug("claustrum hub member commit refused",{member:K.provider});else Y.set(K.provider,C);continue}let{roster:L}=B;if(!this.#N(J))return;if(L?.view!==G.view)U=!1,this.#m(K);else K.pending=void 0;if(!L)continue;if(this.#c(D,L)){U=!1,this.#m(K);continue}this.#R(K,L)}if(!this.#N(J))return;if(this.#w(),U)this.#B=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 T0("Claustrum hub member has no base view");if(z instanceof Error)throw z;let Q;if(!z.file){let Y=k6("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 h1({path:$.path,custody:{discover:async()=>G},isActive:()=>this.#N(X)&&this.#F===!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[f6(this.#M),this.#M,M1(this.#M,this.#_)])await Y1($,{},"roster directory")}async#r($){let Z=`${$.provider}.json`,J=[M1(this.#M,Z)];try{for(let X of await E6(this.#M))if(X!==this.#_&&g6.test(X))J.push(M1(this.#M,X,Z))}catch{}let z;for(let X of J)try{let G=(await b6(X)).mtimeMs,Q=await d(X);if(Q&&(!z||G>z.modified))z={modified:G,roster:Q}}catch{}return z&&D9(z.roster)}#c($,Z){let J=$.projection().reservedRouteIds;return!!J?.size&&Z.rows.some((z)=>J.has(z.routeId))}#m($){let Z=($.pending?.failures??0)+1,J=Math.max(1,this.#$.pollIntervalMs??5000),z=Math.max(1,Math.ceil(r0/J)),X=Z<=n2?1:Math.min(2**(Z-n2),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.#K;for(let Z of this.#T()){let J;try{J=await d(Z.path)}catch(W){Z.hooks?.onError(W);continue}if($!==this.#K||this.#F!==!0)return;let z=Z.hooks;if(!J||!z||Z.closed)continue;let X=JSON.stringify(J);if(X===Z.seen)continue;let G=z.roster();if(!G||G.view!==J.view||this.#c(z,J)){Z.pending??={failures:0,wait:0};continue}let Q=r2(G);if(Z.seen=X,this.#R(Z,J),r2(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.#H?.watch.mode!=="watching"||$)return!0;let Z=(this.#$.now??Date.now)();return this.#D===void 0||Z-this.#D>=r0}#$0(){let $=this.#Y,Z=$&&this.#W.get($);if(!$||!Z||!this.#S($)||this.#F!==!0)return;let J=Z.generation;if(!this.#N(J)||this.#H?.generation===J)return;let z=Z.custody.watchRoster({view:()=>this.#B?.view,onView:()=>this.#j((async()=>{while(this.#U)await this.#U.promise.catch(()=>{});if(!this.#N(J))return;await this.#a()})()),onRefused:(X)=>this.#d(X),onError:(X)=>this.#p(X)});this.#H={generation:J,watch:z}}#p($){if(!this.#Q.signal.aborted)this.#$.onError?.($)}#d($){if(this.#Q.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.#h()}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.#Q.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.#L(),this.#P=!0,this.#j(this.#s())}async refresh(){this.#l(await this.#h())}refusals(){let $=this.#B;return $&&Object.freeze({view:$.view,refused:$.refused,notMine:$.notMine})}grantReach(){return this.#B?.reach}watchState(){let $=this.#H;return $&&this.#N($.generation)?$.watch.mode:"polling"}keptReceiptState(){return this.#J?.custody?.keptReceiptState()??Object.freeze({active:!1,since:null})}close(){if(this.#Q.signal.aborted)return;this.#Q.abort(T0("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.#Y=void 0,this.#H?.watch.close(),this.#H=void 0}async dispose(){this.close(),this.#q??=U1(this.#O,this.#X),await this.#q}}var p0={opencode:c6,pi:p6};function E9($,Z){let{tokenPath:J}=e2($,Z);return{stateDir:u6(J),host:$,override:J}}function b9($,Z){return d6($==="pi"?Z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0,$==="pi"?{...Z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:Z)}class c0 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 f9($,Z){let J=Z??p0[$];if(typeof J!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(J))throw new c0("permission-refused");return["auth","grant","--principal",`enrolled:${J}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"]}async function $7($,Z){try{await Z.processFence();let J=await G3(Z.paths??e2($,Z.env),p0[$]);if(J.state==="blocked")throw new c0("permission-refused");let z=J.state==="approved"?J.approvedName:void 0,X=f9($,z);if((await Z.runner.run(Z.ckBinary??"ck",X,{env:Z.env})).exitCode!==0)throw new c0("permission-refused");return z}catch{throw new c0("permission-refused")}}import{createHash as r6}from"node:crypto";import{lstat as t6,mkdir as e6,readFile as K7}from"node:fs/promises";import{dirname as $5}from"node:path";import{assertHostsStopped as Z5,canonicalPath as y9,createNativeAccountRuntime as J5,custodyTombstoneOAuth as z5,inspectNativeHostAuthEntry as q7,NativeMigrationError as d0,nativeJournalMayAdoptLaterHostLogin as X5,nativePoolHoldsAccountData as G5,prepareNativeMigration as Q5,readNativeEnrollmentMode as F7,readNativeMigrationJournal as W5,releaseNativeMigrationPreflight as Y5,requireNoSupervisedAuthContentSnapshot as H5,runNativeMigration as U5,writeNativeHostAuth as K5}from"@cortexkit/anthropic-auth-core";import{dirname as l6,join as Z7,resolve as x9}from"node:path";import{ACCOUNT_FILE_NAME as J7,ACCOUNT_STATE_FILE_NAME as a6,canonicalPath as z7,getStickyRoutingStatePath as s6,resolveLocalRoutingDestination as n6,resolveNativePoolPaths as i6}from"@cortexkit/anthropic-auth-core";async function L0($,Z){let J=$==="pi"?Q7(Z):X7(Z),z=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),X=x9(z||Z7(J,J7)),G=x9(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(X.endsWith(J7)?Z7(l6(X),a6):`${X}.state.json`)),Q=await i6(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"?W7(Z):G7(Z),routingSourcePath:x9(W||s6(X)),routingDestinationPath:n6($,Q,Z)}}async function Y7($){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 z7(G);if(z.has(Q)&&!(X===9&&Q===await z7(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 o6}from"node:util";var H7=new WeakMap;function U7($){return typeof $==="object"&&$!==null?H7.get($):void 0}function D1($){if(!$||typeof $!=="object"||o6.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",H7.set(this,$)}}var g9="OpenCode's separate Anthropic login is not used. Add that account through /claude Accounts if needed, or remove the separate login from OpenCode.";function B7($){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 v9($,Z){let J=[];for(let z of $)if(await F7(z,Z)!=="local")J.push(B7(z));if(J.length)throw new r(J.join(`
|
|
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 n8($){let Z=$;return{providerIds:Z.providerIds,authMethod:Z.authMethod}}function i8($){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 K1{#$;#Z;#X;#Q;#G;#W;#z;#J=new WeakMap;#V=new WeakMap;#Y=new Map;#H=new WeakMap;#U;#F=new Map;#K;#B;#D=!1;#C=new p;#P;#O=!1;#q=-1/0;#M=2000;#_=!1;#j;#L=new Set;#A=new Set;#R;#E;#N;constructor($){if(c()&&$.client&&!o$($.client))throw new p;let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>_0(Z);else if(c())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??x0($.pluginId),this.#Q=$.family,this.#G=$.parseIdentity,this.#W=$.requireAssertion??!1,this.#X=$.now??Date.now,this.#z=$.logger??Q9,this.#R=H1(this.#z),this.#K=$.setTimeoutImpl??setTimeout,this.#B=$.clearTimeoutImpl??clearTimeout,this.#U=new X9({client:this.#$,owns:(J)=>this.#F.has(J),token:async()=>c()?"":j2(await this.#Z()),logger:this.#z,setTimeout:this.#K,clearTimeout:this.#B})}transportLost($){if(this.#_||this.#D)return;this.#D=!0,this.#C=$ instanceof V2?$:new p,this.#z.warn("serving kept vault receipt",{reason:"unreachable"}),this.#S()}reachable(){if(this.#_||!this.#D)return;if(this.#D=!1,this.#P)this.#B(this.#P);this.#P=void 0,this.#M=2000;for(let $ of this.#Y.values())$.since=null;(this.#z.info??Q9.info)("vault receipt serving resumed",{reason:"reachable"})}#S(){if(this.#_||!this.#D||this.#P||this.#O)return;this.#P=this.#K(()=>{this.#P=void 0,this.#k(!0)},this.#M),this.#P.unref?.()}#k($=!1){if(this.#_||!this.#D||this.#O)return;if(this.#X()-this.#q<1000){this.#S();return}this.#q=this.#X(),this.#O=!0,this.#f().catch(()=>{if($&&this.#D)this.#M=Math.min(this.#M*2,30000)}).finally(()=>{this.#O=!1,this.#S()})}#I($){if(this.#_)throw new O("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#y($){if(this.#I($),c())return"";if(I0.hasSubscribers)I0.publish({logger:this.#z,phase:"token read begin"});let Z=this.#Z();this.#A.add(Z);let J;try{J=await Z}finally{if(this.#A.delete(Z),I0.hasSubscribers)I0.publish({logger:this.#z,phase:"token read end"})}return this.#I($),j2(J)}async#b($,Z){this.#I(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.#I(Z),Y0(X)==="unreachable")this.transportLost(X);else this.reachable();if(X instanceof V2)throw X;if(Y0(X)==="unreachable")throw new p;throw new O("unavailable","Claustrum scoped operation unavailable")}finally{z?.()}return this.#I(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.#Y.clear(),this.#g(),H}if(I0.hasSubscribers)I0.publish({logger:this.#z,phase:"list scoped begin"});try{Z=await this.#b(()=>this.#$.listScoped(J),$)}catch(H){throw this.listFailed(H),H}finally{if(I0.hasSubscribers)I0.publish({logger:this.#z,phase:"list scoped end"})}let z=[],X=[],G=0,Q=[],W=new Map;for(let H of Z.rows){let K=s8(H,this.#Q);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:D}of Q){let B;if(!H.id.trim())B="empty credential id";else if((W.get(H.id)??0)>1)B="duplicate credential id";else if(H.accountId!==void 0&&!H.accountId.trim())B="blank account identity";else if(!H.state.trim())B="empty state";if(B){z.push({...H.id.trim()&&{credentialId:H.id},...D!==void 0&&{member:D},reason:B});continue}Y.push(Object.freeze({credentialId:H.id,credentialType:K,...D!==void 0&&{member:D},...H.accountId!==void 0&&{accountIdentity:H.accountId},state:H.state,...H.email!==void 0&&{email:H.email},...H.orgName!==void 0&&{orgName:H.orgName}}))}for(let H of z)this.#z.warn("skipped malformed vault record",H);let U=i8(Z);return{view:Z.view,credentials:Object.freeze(Y),skipped:Object.freeze(z),..."classify"in this.#Q&&{refused:Object.freeze(X),notMine:G},...U&&{grantReach:U}}}listFailed($){if(Y0($)==="unreachable")this.transportLost($);else this.reachable(),this.#Y.clear(),this.#g()}forget($){this.#Y.delete($),this.#F.delete($),this.#U.forget($)}#g(){for(let $ of this.#F.keys())this.#U.forget($);this.#F.clear()}retain($){let Z=new Map($.map((J)=>[J.credentialId,J]));for(let[J,z]of this.#Y){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.#F){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.#Y){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.#X()>D2}async authorize($,Z,J="vault"){this.#I(Z);let{credentialId:z,credentialType:X,accountIdentity:G}=$,Q=this.#Y.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.#Y.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.#Y.set(z,{attempt:Y,routeId:J,since:null}),this.#F.set(z,{...$}),Y}catch(Y){if(this.#I(Z),Y0(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.#Y.get($)!==Z||!this.#x(Z.attempt))throw this.forget($),X;if(Z.since===null)Z.since=this.#X();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,client:this.#$}),this.#H.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.#W&&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:W9}}),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.#X()<W9))throw new O("insufficient-validity","Claustrum served credential has insufficient validity");let Y=a8(Q.material),U=Q.accountId?.trim()?Q.accountId:void 0;if(this.#W&&(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 D=K??G,L=Object.freeze(Object.defineProperty({credentialId:z,credentialType:X,...D!==void 0&&{accountIdentity:D},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,client:this.#$}),L}async reportFailure($,Z,J){if(Z!==401)return;this.#I();let z=this.#J.get($);if(!z)throw new O("no-receipt","Claustrum failure report requires an original dispatch receipt");let X=this.#H.get($);if(X!==void 0){this.forget($.credentialId),this.#z.debug("scoped 401 not reported",{routeId:X,reason:"kept-receipt"});return}let G=this.#Y.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let Q=this.#V.get($);if(Q)return Q;let W=this.#b(()=>z.client.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:z.token,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#V.set($,W);try{await W,this.#z.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:J})}catch(Y){throw this.#V.delete($),Y}}watchRoster($){this.#I();let Z=new r1({client:this.#$,enrollmentToken:()=>this.#y(),view:$.view??(()=>this.#j),discover:async(J)=>{await $.onView(J)},onRefused:(J)=>{this.listFailed(J),$.onRefused?.(J)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#z,now:this.#X,setTimeoutImpl:this.#K,clearTimeoutImpl:this.#B});return this.#L.add(Z),Z.start(),{get mode(){return Z.mode},close:()=>{this.#L.delete(Z),Z.stop()}}}reportUsage($){if(this.#_)return;try{this.#U.report($.credentialId,$.reading)}catch{}}usageReportState(){return this.#U.state()}close(){if(this.#_)return;if(this.#_=!0,this.#P)this.#B(this.#P);this.#P=void 0;for(let Z of this.#L)Z.stop();this.#L.clear(),this.#Y.clear();let $=this.#U.close();if($)this.#A.add($),$.then(()=>this.#A.delete($));else this.#$.close();this.#N=U1(this.#A,(Z)=>(this.#E??this.#R)(Z)).finally(()=>{if(this.#U.drop(),this.#F.clear(),$)this.#$.close()})}async dispose($=this.#R){this.#E=$,this.close(),await this.#N}}import{resolve as K3}from"node:path";var H9=30000,U9={now:()=>performance.now(),schedule($,Z){let J=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(J),unref:()=>J.unref?.()}}};var h0="all",o8=Object.freeze(["primary"]);function L2($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function F1($,Z){return JSON.stringify([$,Z])}function R0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function i($){return typeof $==="number"&&Number.isFinite($)}function N2($){return typeof $==="string"&&$.length>0}function o($,Z,J){return $[Z]===void 0||J($[Z])}function r8($){return i($)&&$>0}function K9($){return typeof $==="string"}function t8($){if(!R0($)||!N2($.scope)||!N2($.label))return!1;switch($.kind){case"reading":return i($.checkedAt)&&i($.usedPercent)&&o($,"resetsAt",K9)&&o($,"windowMinutes",r8);case"retired":return i($.retiredAt);case"absent":return i($.checkedAt);default:return!1}}function e8($){if(!R0($)||!i($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&o($,"remainingPercent",i)&&o($,"usedPercent",i)&&o($,"resetsAt",K9)&&o($,"limit",i)&&o($,"used",i)&&o($,"remaining",i)&&o($,"unit",K9)}function P2($){return R0($)&&i($.value)&&Number.isInteger($.value)&&$.value>=0&&i($.checkedAt)}function q9($){return R0($)&&Object.values($).every(P2)}function $6($){return typeof $==="boolean"}function B1($){return R0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&o($,"balance",i)&&o($,"overageLimitReached",$6)&&i($.checkedAt)}function C2($){if(!R0($))return;let Z=Object.entries($).filter(([,J])=>P2(J));return Z.length===0?void 0:Object.fromEntries(Z)}function m0($){if(q1($))return $;if(!R0($))return;let{counters:Z,credits:J,...z}=$;if(!q1(z))return;let X=C2(Z),G=B1(J)?J:void 0;return{...z,...X===void 0?{}:{counters:X},...G===void 0?{}:{credits:G}}}function q1($){if(!R0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!t8(J))return!1;let z=F1(J.scope,J.label);if(Z.has(z))return!1;Z.add(z)}return o($,"budget",e8)&&o($,"counters",q9)&&o($,"credits",B1)}class Q3 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function Y3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function W3($){return typeof $==="number"&&Number.isFinite($)}function O2($){return $===void 0||typeof $==="string"&&$!==""}function A2($){return typeof $==="string"&&$!==""}function f1($,Z){return $[Z]===void 0||W3($[Z])}function F9($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function Z6($){return Y3($)&&O2($.scope)&&A2($.label)&&W3($.usedPercent)&&F9($,"resetsAt")&&($.windowMinutes===void 0||W3($.windowMinutes)&&$.windowMinutes>0)}function J6($){return Y3($)&&O2($.scope)&&A2($.label)}function z6($){if(!Y3($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&f1($,"remainingPercent")&&f1($,"usedPercent")&&F9($,"resetsAt")&&f1($,"limit")&&f1($,"used")&&f1($,"remaining")&&F9($,"unit")}function V1($){if(!Y3($)||!W3($.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(!Z6(X))return!1;let G=F1(X.scope??h0,X.label);if(z.has(G))return!1;z.add(G)}if(!J.every(J6))return!1;return($.budget===void 0||z6($.budget))&&($.counters===void 0||q9($.counters))&&($.credits===void 0||B1($.credits))}function X6($,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 Q6($,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 W6($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function x1($,Z){let J=$===void 0?void 0:m0($);if($!==void 0&&J===void 0)throw new Q3("stored quota map is malformed");if(!V1(Z))throw new Q3("quota observation is malformed");let z=J??{limits:[]},X=Z.checkedAt,G=new Map;for(let A of z.limits)G.set(F1(A.scope,A.label),A);let Q=(A)=>{let I=G.get(A);return I===void 0||X>=L2(I)},W=new Set;for(let A of Z.readings??[]){let I=A.scope??h0,T=F1(I,A.label);if(W.add(T),!Q(T))continue;G.set(T,{scope:I,label:A.label,kind:"reading",checkedAt:X,usedPercent:A.usedPercent,...A.resetsAt===void 0?{}:{resetsAt:A.resetsAt},...A.windowMinutes===void 0?{}:{windowMinutes:A.windowMinutes}})}for(let A of Z.coverage??[]){let I=A.scope??h0,T=F1(I,A.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:A.label,kind:"absent",checkedAt:X}:{scope:I,label:A.label,kind:"retired",retiredAt:X})}let{limits:Y,budget:U,counters:H,credits:K,...D}=z,B=G6(z.budget,Z.budget,X),L=Q6(z.counters,Z.counters),C=W6(z.credits,Z.credits);return{...D,limits:[...G.values()].sort(X6),...B===void 0?{}:{budget:B},...L===void 0?{}:{counters:L},...C===void 0?{}:{credits:C}}}var Y6=Object.freeze({validate:q1,decode:m0,merge:x1});function _2($,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 q6}from"node:crypto";import{stat as F6}from"node:fs/promises";import{resolve as y1}from"node:path";function I2($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function B9($,Z,J){return $.some((z)=>I2(z,Z,J))}function V9($,Z,J){let z={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((X)=>X.credentialId!==Z||X.accountIdentity!==J),z]}function j9($,Z,J){return $.filter((z)=>!Z.some((X)=>I2(z,X,J)))}function D9($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>K0(Z).map((J)=>({credentialId:J,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function B6($,Z){let J=K0(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 U3="vault:";function V6($){return q6("sha256").update($).digest("hex")}function j6($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function M6($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function K0($){return[$.credentialId,...$.aliases??[]]}function T2($,Z,J={}){let z=J.now??Date.now(),X=J.routePrefix??U3,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((F)=>F.credentialId)),K=new Set(Z.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),D=Z.skipped.some((F)=>F.credentialId===void 0),B=(F)=>!H.has(F)&&(K.has(F)||D),L=new Map;for(let F of Q){if(F.accountIdentity===void 0)continue;for(let q of K0(F))if(!L.has(q))L.set(q,F.accountIdentity)}let C=new Map;for(let F of Z.credentials){let q=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:L.get(F.credentialId),claimed:!1},j=M6(q),P=C.get(j)??[];P.push(q),C.set(j,P)}let A=new Set,I=new Set(G),T=[],m=(F,q)=>F.credential.credentialId.localeCompare(q.credential.credentialId),u=[...C.values()].map((F)=>F.toSorted(m)).sort((F,q)=>F[0]&&q[0]?m(F[0],q[0]):0);for(let F of u){let q=F[0]?.identity,j=F.filter((b)=>b.credential.state==="active"),P=j.length?j:F,g=P.filter((b)=>b.claimed),E=g.length?g:P,v=new Set(F.map((b)=>b.credential.credentialId)),J0=Q.find((b)=>!A.has(b)&&K0(b).some((V0)=>v.has(V0))&&(b.accountIdentity===void 0||b.accountIdentity===q)),l=E.find((b)=>b.credential.credentialId===J0?.credentialId)??E[0];if(!l)continue;let a=l.credential,s=J0??(q===void 0?void 0:Q.find((b)=>!A.has(b)&&b.accountIdentity===q));if(s)A.add(s);let z0=s?.routeId;if(!z0||G.has(z0)){let b=`${X}${a.credentialId}${q===void 0?"":`~${V6(q).slice(0,10)}`}`;z0=b;for(let V0=2;I.has(z0);V0++)z0=`${b}~${V0}`}I.add(z0);let I1=s?K0(s).filter(B):[],R1=[...new Set([...F.map((b)=>b.credential.credentialId),...I1])].filter((b)=>b!==a.credentialId).sort((b,V0)=>b.localeCompare(V0)),n1=J.mapAccount?.(a)??{};T.push({previousIndex:s?Q.indexOf(s):1/0,row:{routeId:z0,credentialId:a.credentialId,credentialType:a.credentialType,...q!==void 0&&{accountIdentity:q},...R1.length&&{aliases:R1},state:a.state,label:n1.label?.trim()||j6(a),...a.email!==void 0&&{email:a.email},...a.orgName!==void 0&&{orgName:a.orgName},enabled:![a.credentialId,...R1].some((b)=>B9(Y,b,q)),addedAt:s?.addedAt??z,...s?.quota!==void 0&&{quota:s.quota},...!l.claimed&&q!==void 0&&{unclaimed:!0}}});let i0=T.at(-1);if(W&&i0)i0.previousIndex=B6(W,i0.row)}return Q.forEach((F,q)=>{if(A.has(F)||!K0(F).some(B))return;if(I.has(F.routeId))return;let[j,...P]=K0(F).filter((v)=>!H.has(v));if(j===void 0)return;I.add(F.routeId);let{aliases:g,...E}=F;T.push({previousIndex:q,row:{...E,credentialId:j,...P.length&&{aliases:P},stale:!0}})}),T.sort((F,q)=>F.previousIndex===q.previousIndex?F.row.credentialId.localeCompare(q.row.credentialId):F.previousIndex-q.previousIndex),{version:1,view:Z.view,...$?.limits!==void 0&&{limits:$.limits},complete:U,...!U&&{rejected:Z.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:T.map((F)=>F.row),declined:Y}}function N9($){return($?.rows??[]).filter((Z)=>Z.enabled&&Z.state==="active").map((Z)=>({id:Z.routeId,kind:Z.credentialType==="oauth"?"oauth":"api-key",...Z.quota!==void 0&&{quota:Z.quota}}))}function g1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function j1($){return $===void 0||typeof $==="string"}function D6($){let Z=g1($)?m0($.quota):void 0;if(!g1($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!j1($.accountIdentity)||!j1($.email)||!j1($.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 N6=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function R2($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!g1(J)||!j1(J.credentialId)||typeof J.reason!=="string"||!N6.has(J.reason))return;Z.push(J)}return Z}function k2($){if(!g1($)||$.version!==1||!j1($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!R2($.rejected))throw new O("invalid-state","Claustrum roster file is not valid");let Z=[];for(let X of $.rows){let G=D6(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(!g1(X)||typeof X.credentialId!=="string"||!j1(X.accountIdentity))throw new O("invalid-state","Claustrum roster file is not valid");J.push(X)}let z=R2($.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 L9($){return k2(JSON.parse(JSON.stringify($)))}var L6=new b0({followSymlinks:!0});async function d($){if(_)return M9($);let Z=await L6.read([$],([J=$])=>M9(J));return structuredClone(Z)}async function M9($){let Z;try{Z=await X0($,_)}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 k2(J)}var E2={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},b2={name:"claustrum-roster",ttlMs:30000};async function w0($,Z,J={}){return l3($,{...E2,signal:J.signal},async(z)=>{let X=await M9($),{next:G,result:Q}=await Z(X,{assertOwned:()=>z.assertOwned()});if(G){await z.assertOwned();try{await z1($,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 P9($,Z){return w0($,(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=V9(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 C9($,Z){return w0($,(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:j9(J.declined,K0(z),z.accountIdentity),rows:J.rows.map((X)=>X===z?{...X,enabled:!0}:X)},result:void 0}})}function P6($){return new O("invalid-order",$)}function C6($,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 O9($,Z,J={}){return w0($,(z)=>{let X=z?.rows??[],G=C6(X,Z);if(G)throw P6(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 O6($,Z){if(!K0($).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")&&K0($).length===1)return"bind";return"refuse"}async function A9($,Z){let{routeId:J,observation:z,...X}=Z;return f2($,{routeId:J,observation:z,accountIdentity:X.accountIdentity,receipt:X})}async function f2($,Z){if(!V1(Z.observation))return!1;let J=e($,await d($));if(!S0(J,Z).kept)return!1;return y2($,Z)}function _9($,Z){return f2($,Z)}function S0($,Z){let J=$?.rows.find((Q)=>Q.routeId===Z.routeId),z=!J?"refuse":Z.receipt?O6(J,Z.receipt):J.accountIdentity!==void 0&&J.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!J||z==="refuse")return{roster:$,kept:!1};let X=x1(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 H3=new Map;function v1($){H3.delete(y1($))}function x2($,Z){let J=y1($);if(Z instanceof O)return Z.kind==="roster-busy";if(Z instanceof O0||Z instanceof D0)return y1(Z.details.target)===J;if(Z instanceof w){let z=y1(Z.path);return[E2.name,b2.name].some((X)=>{let G=X1(J,X);return z===G||z.startsWith(`${G}.`)})}return!1}var A6=4;async function S2($){try{let{dev:Z,ino:J,size:z,mtimeMs:X}=await F6($);return{dev:Z,ino:J,size:z,mtimeMs:X}}catch{return}}function _6($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function I6($,Z,J){for(let z=0;z<A6;z++){let X=await S2($),G=await d($),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(!_6(X,await S2($)))continue;if(Y)return"commit";return g2($)?"commit":"unchanged"}return"commit"}async function h1($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){v1($.path);return}let J=await N0({...b2,path:$.path,renew:!0});if(!J){let Q=await d($.path);if($.signal?.throwIfAborted(),!Q?.view)throw new O("roster-busy","Claustrum account discovery is already in progress");return Q}let z=y1($.path),X=$.listedOver,G;try{let Q=await d($.path),W=X?void 0:H3.get(z);G=W&&(W.previousView===Q?.view||W.inventory.view===Q?.view)?W:{inventory:await $.custody.discover($.signal),previousView:Q?.view},H3.delete(z);let{inventory:Y}=G;$.onInventory?.(Y),$.signal?.throwIfAborted();let U=typeof $.projection==="function"?$.projection():$.projection,H=(B)=>T2(B,Y,U),K=async()=>{return $.signal?.throwIfAborted(),await J.assertOwned(),Z()};if(await I6($.path,(B)=>{if(X)return{target:B};let L=e($.path,B);return{target:B,...L!==B&&{local:L}}},H)==="unchanged"){if(!await K())return;return await d($.path)}return await w0($.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 L=H(B);return{...JSON.stringify(B)!==JSON.stringify(L)&&{next:L},result:L}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await J.assertOwned()}})}catch(Q){if(Q instanceof O0&&G&&!X&&!$.signal?.aborted&&await Z())H3.set(z,G);throw Q}finally{await J.release($.signal)}}var u0=new Map,R6=U0("claustrum"),h2=100;function m2($,Z=U9){let J=K3($),z=u0.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},u0.set(J,z);return z}function w2($,Z,J){let z=m2($,J);z.listeners.add(Z);let X;return()=>X??=(()=>{return z.listeners.delete(Z),z.listeners.size?Promise.resolve():I9($)})()}function S6($){return _2($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function y2($,Z){if(!V1(Z.observation))return Promise.resolve(!1);let J=m2($),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 S6(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 c2(J,h2),Promise.resolve(!0)}function u2($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,J)=>Z.order-J.order)}function e($,Z){let J=u0.get(K3($));if(J)for(let z of u2(J.pending)){if(z.priorReading)Z=S0(Z,z.priorReading).roster;Z=S0(Z,z.publication).roster}return Z}function g2($){return!!u0.get(K3($))?.pending.size}function c2($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let J=$.draining?0:($.committedAt??-1/0)+H9-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,J),()=>{return $.timer=void 0,p2($)}),!$.draining)$.timer.unref?.()}function v2($){$.timer?.cancel(),$.timer=void 0}function p2($){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 w0($.path,(z)=>{let X=z;for(let Q of u2(Z)){if(Q.priorReading)X=S0(X,Q.priorReading).roster;X=S0(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)R6.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()):h2;c2($,J)}})(),$.running}async function I9($,Z=1000){let J=K3($),z=u0.get(J);if(!z)return;z.draining=!0,v2(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)p2(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(),v2(z),z.pending.clear(),u0.get(J)===z)u0.delete(J)}}}var q3=1e4;function d2(){return new p}var R9;function a2($,Z){if(!R9)throw Error("ClaustrumConsumer is not initialized");return R9($,Z)}function l2(){return new O("not-active","Claustrum scoped custody is not active")}class S9{#$;#Z=new AbortController;#X;#Q;#G;#W;#z;#J;#V;#Y;#H=!1;#U=new Set;#F;#K;#B;#D;#C=new Map;#P;#O;#q;#M;#_=new WeakMap;static{R9=($,Z)=>{let J=new S9(Z);return J.#q=$,{consumer:J,hooks:J.#g()}}}constructor($){this.#$=$,this.#X=$.logger??U0("claustrum"),this.#Q=H1(this.#X,this.#Z.signal),this.#O=w2($.rosterPath,(Z)=>{this.#J=S0(this.#J,Z).roster})}#j($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#L($){return this.#U.add($),$.then(()=>this.#U.delete($),()=>this.#U.delete($)),$}async#A(){if(c())return!0;return await this.#$.isCustodyActive?.()??!0}#R($,Z){let J=E0([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.#W){let $={timedOut:!1};this.#W=this.#N($),this.#L(this.#W)}return this.#R(this.#W)}#N($){let Z=this.#$.setTimeoutImpl??setTimeout,J=this.#$.clearTimeoutImpl??clearTimeout,z=(!c()&&this.#$.connect?this.#$.connect():Promise.resolve().then(()=>x0(this.#$.pluginId))).then((Q)=>{if(this.#Z.signal.aborted||$.timedOut){if(Q.close(),!$.timedOut)this.#j();throw d2()}if(this.#G=new K1({client:Q,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#X,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&Q.insula)this.#K=m3(Q.insula,this.#$.tokenPath);return this.#G}),X,G=new Promise((Q,W)=>{X=Z(()=>{if($.timedOut=!0,this.#Z.signal.aborted)return;this.#X.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:this.#S()}),W(d2())},this.#S()),X.unref?.()});return Promise.race([z,G]).finally(()=>{if(X)J(X);this.#W=void 0})}#S(){return this.#$.connectTimeoutMs??q3}snapshot(){return this.#J}grantReach(){if(this.#q)return this.#q.grantReach(this.#J?.view);let $=this.#V;return $&&this.#J?.view===$.view?$.reach:void 0}watchState(){if(this.#q)return Object.freeze({vault:this.#q.watchMode()});return Object.freeze({vault:this.#B?.mode??"polling",...this.#$.insula&&{insula:this.#K?.source.watchMode()??"polling"}})}#k(){this.#B?.close(),this.#B=void 0,this.#D?.(),this.#D=void 0}keptReceiptState(){if(this.#q){let $=this.#M;return $&&this.#q.leaseLive($)?$.custody.keptReceiptState():this.#q.keptReceiptState()}return this.#G?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return N9(this.#J)}refresh(){if(this.#j(),this.#q)return this.#L(this.#x(this.#q));if(this.#z)return this.#z;return this.#z=(async()=>{if(!await this.#A()){if(this.#J=void 0,this.#V=void 0,this.#k(),this.#G)this.#G.close(),this.#L(this.#G.dispose(this.#Q));this.#G=void 0,this.#K?.release(),this.#K=void 0;return}let $=await this.#E(),Z,J=await h1({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.#V=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.#z=void 0}),this.#L(this.#z),this.#I(this.#z),this.#z}#I($){try{this.#$.onDiscovery?.($)}catch(Z){this.#$.onError?.(Z)}}start(){if(this.#H)return;if(this.#j(),this.#H=!0,this.#q){this.#q.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.#Y=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#Y=void 0,this.#L($())},Z),this.#Y.unref?.()};this.#L($())}async#y(){if(this.#B?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#P===void 0||$-this.#P>=r0)return!0;return!await this.#A()}#b(){let $=this.#G;if(this.#Z.signal.aborted||!$)return;if(this.#B??=$.watchRoster({view:()=>this.#J?.view,onView:()=>this.#L((async()=>{while(this.#z)await this.#z.catch(()=>{});if(this.#Z.signal.aborted)return;await this.refresh()})()),onRefused:(Z)=>this.#$.onError?.(Z),onError:(Z)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(Z)}}),this.#$.insula&&this.#K&&!this.#D)this.#D=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.#A())return;try{if(!c())await _0(this.#$.tokenPath);await this.#E(),await this.#K?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#A())return;try{if(!c())await _0(this.#$.tokenPath);return this.#f($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#A())return;try{if(!c())await _0(this.#$.tokenPath);let J=e(this.#$.rosterPath,await d(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(!c())await _0(this.#$.tokenPath);let z=e(this.#$.rosterPath,await d(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.#C.get($)!==J.miss)this.#C.set($,J.miss),this.#X.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.#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.#q)return this.#h(this.#q,$,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.#K?.release(),this.#K=void 0,new O("not-active","Claustrum scoped custody is not active");let z=e(this.#$.rosterPath,await d(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=E0([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.#q;if(!Z||!this.#$.onDiscovery||this.#Z.signal.aborted)return;let J=this.#L($.then((z)=>this.#v(Z,z)));this.#I(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#h($,Z,J){if(this.#j(J),!this.#J)await this.#R($.refresh(),J);let z=this.#J;if(!await $.readAuthority())throw this.#T(),l2();if(this.#j(J),!z)throw new O("route-unavailable","Claustrum has no roster for this provider yet");let X=e(this.#$.rosterPath,await d(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=E0([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.#_.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 l2()}}}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.#q){if(this.#M&&this.#q.leaseLive(this.#M))this.#M.custody.reportUsage($)}else this.#G?.reportUsage($)}catch{}}usageReportState(){try{return(this.#q?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.#q){let z=this.#_.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(Y9(J.site,X,Q,this.#X))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 P9(this.#$.rosterPath,$),this.#J=e(this.#$.rosterPath,await d(this.#$.rosterPath)),this.#J)this.#q?.publishRoster(this.#J);if(this.#q)this.#q.retainUnion();else this.#G?.retain(this.#J?.rows??[])}async accept($){if(this.#j(),await C9(this.#$.rosterPath,$),this.#J=e(this.#$.rosterPath,await d(this.#$.rosterPath)),this.#J)this.#q?.publishRoster(this.#J)}async reorder($){this.#j();let Z=await O9(this.#$.rosterPath,$);if(this.#J=e(this.#$.rosterPath,await d(this.#$.rosterPath)),this.#J)this.#q?.publishRoster(this.#J);return Z}async recordQuota($,Z,J){return this.#j(),A9(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(),_9(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.#Y)(this.#$.clearTimeoutImpl??clearTimeout)(this.#Y);if(this.#Y=void 0,this.#k(),this.#G)this.#G.close(),this.#L(this.#G.dispose(this.#Q));this.#M?.release(),this.#M=void 0,this.#q?.detach(),this.#K?.release(),this.#K=void 0,this.#J=void 0,this.#V=void 0,this.#O(),v1(this.#$.rosterPath)}async dispose(){this.close(),this.#F??=Promise.all([U1(this.#U,this.#Q),this.#O()]).then(()=>{}),await this.#F}}import{createHash as T6}from"node:crypto";import{channel as k6}from"node:diagnostics_channel";import{readdir as E6,stat as b6}from"node:fs/promises";import{dirname as f6,join as M1,resolve as s2}from"node:path";var F3=new Map,x6=/^[a-z0-9][a-z0-9._-]{0,63}$/,y6=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,g6=/^[0-9a-f]{16}$/,n2=3;function k9($,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=k9($[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=k9($[G],J);if(Q===void 0)return;z.push(`${JSON.stringify(G)}:${Q}`)}return`{${z.join(",")}}`}function v6($,Z){let J=k9({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??U3,mapAccount:$.mapAccount?String($.mapAccount):null});if(J===void 0)throw new O("invalid-state","Claustrum hub classifierInput must be plain JSON");return T6("sha256").update(J).digest("hex").slice(0,16)}function i2($,Z){if(typeof $!=="string"||!x6.test($)||y6.test($))throw new O("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function T0($="Claustrum custody lease is closed"){return new O("closed",$)}function T9(){return new O("not-active","Claustrum scoped custody is not active")}function o2(){return new p}function h6($,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 r2($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class t2{#$;#Z;#X;#Q=new AbortController;#G=new Map;#W=new WeakMap;#z=0;#J;#V;#Y;#H;#U;#F;#K=0;#B;#D;#C;#P=!1;#O=new Set;#q;#M;#_;constructor($){if(!$.family||!("classify"in $.family))throw new O("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=i2($.hostGeneration,"host generation"),J=$.members.map((X)=>i2(X,"member"));if(new Set(J).size!==J.length)throw new O("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??U0("claustrum"),this.#X=H1(this.#Z,this.#Q.signal),this.#M=M1($.stateDir,"rosters",Z),this.#_=v6($,J);let z=M1(this.#M,this.#_);for(let X of J)this.#G.set(X,{provider:X,path:M1(z,`${X}.json`),closed:!1})}#j($){return this.#O.add($),$.then(()=>this.#O.delete($),()=>this.#O.delete($)),$}#L(){if(this.#Q.signal.aborted)throw T0("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.#L();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.#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.#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}=a2(z,X);J.hooks=Q;let W=s2(J.path),Y=F3.get(W)??new Set,U=(K)=>{if(J.closed||this.#F!==!0||!this.#J||!this.#N(this.#J)||!Q.roster()||this.#c(Q,K))return;if(J.seen=JSON.stringify(L9(K)),Q.install(K),K.view!==this.#B?.view)J.pending??={failures:0,wait:0};this.#w()};Y.add(U),J.receiveRoster=U,F3.set(W,Y);let H=!0;return J.releaseRoster=()=>{if(!H)return;if(H=!1,Y.delete(U),!Y.size)F3.delete(W)},G}#R($,Z){let J=this.#J;if($.closed||!J||!this.#N(J))return;$.seen=JSON.stringify(L9(Z)),$.hooks?.install(Z);for(let z of F3.get(s2($.path))??[]){if(!this.#N(J))return;if(z!==$.receiveRoster)z(Z)}}#E(){let $={id:++this.#z,count:0,ended:!1,controller:new AbortController};return this.#J=$,$}#N($){return!$.ended&&this.#J===$&&!this.#Q.signal.aborted}#S($){let Z=this.#W.get($);return!!Z&&!Z.released&&!Z.generation.ended}#k($,Z=T0()){if($.ended)return;if($.ended=!0,$.count=0,this.#J===$)this.#J=void 0;if(this.#Y&&this.#W.get(this.#Y)?.generation===$)this.#Y=void 0;if(this.#H?.generation===$)this.#H.watch.close(),this.#H=void 0;if($.controller.abort(Z),$.custody)$.custody.close(),this.#j($.custody.dispose(this.#X))}#I($){if($.ended)return;if($.count--,$.count<=0)this.#k($)}#y($){let Z=this.#V;if(Z?.generation===$&&Z.promise)return Z.promise;let J={generation:$,timedOut:!1},z=this.#$.connectTimeoutMs??q3,X,G=(!c()&&this.#$.connect?this.#$.connect():Promise.resolve().then(()=>x0(this.#$.pluginId))).then((Y)=>{if(J.timedOut)throw Y.close(),o2();if(!this.#N($)||$.count<=0)throw Y.close(),T0("Claustrum connection is no longer wanted");return $.custody=new K1({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.#N($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:z}),U(o2())},z),X.unref?.()});return J.promise=this.#j(Promise.race([G,Q]).finally(()=>{if(X)(this.#$.clearTimeoutImpl??clearTimeout)(X)})),J.promise.finally(()=>{if(this.#V===J)this.#V=void 0}).catch(()=>{}),this.#V=J,J.promise}acquire($){try{if(this.#L(),$?.throwIfAborted(),this.#F===!1)throw T9()}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=E0([$.controller.signal,...Z?[Z]:[]]);try{z=await h6(this.#y($),X.signal)}catch(G){if(!$.ended)throw this.#I($),G;return this.#f(Z,J)}finally{X.dispose()}}if($.ended)return this.#f(Z,J);if(Z?.aborted)throw this.#I($),Z.reason;return this.#g($,z)}#f($,Z){if($?.throwIfAborted(),this.#L(),this.#F===!1)throw T9();if(!Z)throw T0();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 T0()},X=Object.freeze({authorize:async(Q,W,Y)=>{z();let U=E0([$.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.#I($)}});return this.#W.set(G,J),G}leaseState(){let $=this.#J;return Object.freeze({generation:$?.id,count:$?.count??0})}async#x(){let $=c()||(await this.#$.isCustodyActive?.()??!0);if(this.#Q.signal.aborted)return!1;let Z=this.#F;if(this.#F=$,!$&&Z!==!1)this.#v();return $}#v(){this.#K++;let $=this.#J;if($)this.#k($,T9());this.#Y=void 0,this.#H?.watch.close(),this.#H=void 0,this.#B=void 0,this.#D=void 0;for(let Z of this.#G.values())Z.seen=void 0,Z.pending=void 0,Z.hooks?.reset(),v1(Z.path)}#T(){return[...this.#G.values()].filter(($)=>$.hooks&&!$.closed)}async#u(){let $=this.#Y,Z=$&&this.#W.get($);if($&&Z&&this.#S($))return Z;this.#Y=void 0;let J=await this.acquire(this.#Q.signal),z=this.#Y&&this.#W.get(this.#Y);if(this.#Y&&z&&this.#S(this.#Y))return J.release(),z;this.#Y=J;let X=this.#W.get(J);if(!X)throw T0();return X}#h(){try{this.#L()}catch(z){return Promise.reject(z)}let $=this.#U;if($&&!$.generation?.ended)return $.promise;let Z={},J=this.#j(this.#n(Z).finally(()=>{if(this.#U===Z)this.#U=void 0}));Z.promise=J,this.#U=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.#N(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 d(H.path).then((K)=>K?{file:K}:{},(K)=>K instanceof Error?K:Error(String(K)))])));if(!this.#N(J))return;let G;try{G=await Z.custody.discover(J.controller.signal)}catch(H){if(!this.#N(J))return;for(let K of this.#G.values())if(K.pending)this.#m(K);throw H}if(!this.#N(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.#N(J))return;let Y=new Map,U=!0;for(let[H,K]of Q.entries()){let D=K.hooks,B=W[H];if(!D||!B)continue;if("error"in B){let{error:C}=B;if(U=!1,this.#m(K),x2(K.path,C))this.#Z.debug("claustrum hub member commit refused",{member:K.provider});else Y.set(K.provider,C);continue}let{roster:L}=B;if(!this.#N(J))return;if(L?.view!==G.view)U=!1,this.#m(K);else K.pending=void 0;if(!L)continue;if(this.#c(D,L)){U=!1,this.#m(K);continue}this.#R(K,L)}if(!this.#N(J))return;if(this.#w(),U)this.#B=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 T0("Claustrum hub member has no base view");if(z instanceof Error)throw z;let Q;if(!z.file){let Y=k6("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 h1({path:$.path,custody:{discover:async()=>G},isActive:()=>this.#N(X)&&this.#F===!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[f6(this.#M),this.#M,M1(this.#M,this.#_)])await Y1($,{},"roster directory")}async#r($){let Z=`${$.provider}.json`,J=[M1(this.#M,Z)];try{for(let X of await E6(this.#M))if(X!==this.#_&&g6.test(X))J.push(M1(this.#M,X,Z))}catch{}let z;for(let X of J)try{let G=(await b6(X)).mtimeMs,Q=await d(X);if(Q&&(!z||G>z.modified))z={modified:G,roster:Q}}catch{}return z&&D9(z.roster)}#c($,Z){let J=$.projection().reservedRouteIds;return!!J?.size&&Z.rows.some((z)=>J.has(z.routeId))}#m($){let Z=($.pending?.failures??0)+1,J=Math.max(1,this.#$.pollIntervalMs??5000),z=Math.max(1,Math.ceil(r0/J)),X=Z<=n2?1:Math.min(2**(Z-n2),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.#K;for(let Z of this.#T()){let J;try{J=await d(Z.path)}catch(W){Z.hooks?.onError(W);continue}if($!==this.#K||this.#F!==!0)return;let z=Z.hooks;if(!J||!z||Z.closed)continue;let X=JSON.stringify(J);if(X===Z.seen)continue;let G=z.roster();if(!G||G.view!==J.view||this.#c(z,J)){Z.pending??={failures:0,wait:0};continue}let Q=r2(G);if(Z.seen=X,this.#R(Z,J),r2(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.#H?.watch.mode!=="watching"||$)return!0;let Z=(this.#$.now??Date.now)();return this.#D===void 0||Z-this.#D>=r0}#$0(){let $=this.#Y,Z=$&&this.#W.get($);if(!$||!Z||!this.#S($)||this.#F!==!0)return;let J=Z.generation;if(!this.#N(J)||this.#H?.generation===J)return;let z=Z.custody.watchRoster({view:()=>this.#B?.view,onView:()=>this.#j((async()=>{while(this.#U)await this.#U.promise.catch(()=>{});if(!this.#N(J))return;await this.#a()})()),onRefused:(X)=>this.#d(X),onError:(X)=>this.#p(X)});this.#H={generation:J,watch:z}}#p($){if(!this.#Q.signal.aborted)this.#$.onError?.($)}#d($){if(this.#Q.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.#h()}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.#Q.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.#L(),this.#P=!0,this.#j(this.#s())}async refresh(){this.#l(await this.#h())}refusals(){let $=this.#B;return $&&Object.freeze({view:$.view,refused:$.refused,notMine:$.notMine})}grantReach(){return this.#B?.reach}watchState(){let $=this.#H;return $&&this.#N($.generation)?$.watch.mode:"polling"}keptReceiptState(){return this.#J?.custody?.keptReceiptState()??Object.freeze({active:!1,since:null})}close(){if(this.#Q.signal.aborted)return;this.#Q.abort(T0("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.#Y=void 0,this.#H?.watch.close(),this.#H=void 0}async dispose(){this.close(),this.#q??=U1(this.#O,this.#X),await this.#q}}var p0={opencode:c6,pi:p6};function E9($,Z){let{tokenPath:J}=e2($,Z);return{stateDir:u6(J),host:$,override:J}}function b9($,Z){return d6($==="pi"?Z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0,$==="pi"?{...Z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:Z)}class c0 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 f9($,Z){let J=Z??p0[$];if(typeof J!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(J))throw new c0("permission-refused");return["auth","grant","--principal",`enrolled:${J}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"]}async function $7($,Z){try{await Z.processFence();let J=await G3(Z.paths??e2($,Z.env),p0[$]);if(J.state==="blocked")throw new c0("permission-refused");let z=J.state==="approved"?J.approvedName:void 0,X=f9($,z);if((await Z.runner.run(Z.ckBinary??"ck",X,{env:Z.env})).exitCode!==0)throw new c0("permission-refused");return z}catch{throw new c0("permission-refused")}}import{createHash as r6}from"node:crypto";import{lstat as t6,mkdir as e6,readFile as K7}from"node:fs/promises";import{dirname as $5}from"node:path";import{assertHostsStopped as Z5,canonicalPath as y9,createNativeAccountRuntime as J5,custodyTombstoneOAuth as z5,inspectNativeHostAuthEntry as q7,NativeMigrationError as d0,nativeJournalMayAdoptLaterHostLogin as X5,nativePoolHoldsAccountData as G5,prepareNativeMigration as Q5,readNativeEnrollmentMode as F7,readNativeMigrationJournal as W5,releaseNativeMigrationPreflight as Y5,requireNoSupervisedAuthContentSnapshot as H5,runNativeMigration as U5,writeNativeHostAuth as K5}from"@cortexkit/anthropic-auth-core";import{dirname as l6,join as Z7,resolve as x9}from"node:path";import{ACCOUNT_FILE_NAME as J7,ACCOUNT_STATE_FILE_NAME as a6,canonicalPath as z7,getStickyRoutingStatePath as s6,resolveLocalRoutingDestination as n6,resolveNativePoolPaths as i6}from"@cortexkit/anthropic-auth-core";async function L0($,Z){let J=$==="pi"?Q7(Z):X7(Z),z=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),X=x9(z||Z7(J,J7)),G=x9(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(X.endsWith(J7)?Z7(l6(X),a6):`${X}.state.json`)),Q=await i6(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"?W7(Z):G7(Z),routingSourcePath:x9(W||s6(X)),routingDestinationPath:n6($,Q,Z)}}async function Y7($){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 z7(G);if(z.has(Q)&&!(X===9&&Q===await z7(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 o6}from"node:util";var H7=new WeakMap;function U7($){return typeof $==="object"&&$!==null?H7.get($):void 0}function D1($){if(!$||typeof $!=="object"||o6.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",H7.set(this,$)}}var g9="OpenCode's separate Anthropic login is not used. Add that account through /claude Accounts if needed, or remove the separate login from OpenCode.";function B7($){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 v9($,Z){let J=[];for(let z of $)if(await F7(z,Z)!=="local")J.push(B7(z));if(J.length)throw new r(J.join(`
|
|
13
13
|
`))}function l0($,Z){return async()=>{H5(Z.env);try{await Z5(Z.fence,Z.env)}catch(J){let z=D1(J);if(z)throw new r(z);throw J}await v9([$],Z.env)}}async function h9($){try{return r6("sha256").update(await K7($)).digest("hex")}catch(Z){if(Z.code==="ENOENT")return"absent";throw new d0("unsafe-source")}}async function m1($,Z){let J;try{J=JSON.parse(await K7(Z,"utf8"))}catch(G){if(G.code!=="ENOENT")throw new d0("unsafe-source")}let z=q7($,J),X=J?.anthropic;return{...z,realLogin:z.kind==="oauth"&&Boolean(X?.access&&X.refresh)}}async function B3($,Z){let{paths:J}=$,z=$.generation2?void 0:await m1(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(h9));return JSON.stringify([await F7(J.host,Z),z?.digest,...X])}async function m9($,Z,J){let z=Z.paths??await L0($,Z.env),X=l0($,Z);await X();let G=await W5(z.paths);if(G&&G.host!==$)throw new d0("invalid-source");let Q=G?.phase==="committed"||G?.phase==="retired";if(G&&G.kind!=="empty-init"&&(G.hostAuthPath!==await y9(z.hostAuthPath)||G.routingPaths.source!==await y9(z.routingSourcePath)||G.routingPaths.destination!==await y9(z.routingDestinationPath)))throw new d0("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 d0("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 U of Y){try{await t6(U)}catch(H){if(H.code==="ENOENT")continue;throw new d0("unsafe-source")}throw new d0("invalid-source")}}}else{W.slot=await m1($,z.hostAuthPath);let Y=X5(G,$)&&W.slot.kind==="oauth";W.poolPopulation=G?.kind==="empty-init"||Y?await G5({paths:z.paths}):"not-evaluated";let U=W.poolPopulation===!0;if($==="opencode"&&(U||Q&&G?.kind!=="empty-init"&&!Y&&W.slot.kind==="oauth"))W.action="skip",W.notice=W.slot.realLogin;else W.preflight=await Q5({...z,env:Z.env,processFence:X,removePiAnthropicAuth:Z.removePiAnthropicAuth})}return W.fingerprint=await B3(W,Z.env),W}async function N1($,Z){await l0($.paths.host,Z)();let J=await m9($.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)Y5(J.preflight)}}async function w9($,Z){if($.paths.host!=="opencode"||$.slot?.kind!=="absent")return;let J=l0("opencode",Z);await J(),await e6($5($.paths.hostAuthPath),{recursive:!0,mode:448}),await K5({host:"opencode",authPath:$.paths.hostAuthPath,sourceDigest:"absent",expectedDigest:q7("opencode",{anthropic:z5("anthropic")}).digest,env:Z.env,removePiAnthropicAuth:!1,processFence:J})}async function V7($,Z){let J={...Z.env},z=l0($,{...Z,env:J});await z();let X=Z.paths??await L0($,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 U5({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=J5({paths:X.paths,host:$,vault:{env:J},beforePoolWrite:z});try{if((await Q.read()).mode!=="local")throw new r(B7($));await z(),await Q.loginOAuth({routeId:"main",replace:!0,...G})}finally{await Q.close()}}if(Z.skipMigration){let Q=await m1($,X.hostAuthPath);await w9({paths:X,slot:Q},Z)}}var j7={opencode:"OpenCode",pi:"Pi"};function L5($,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`${j7[Z]} has no read grant in the vault, so setup cannot see any Claude login. Run ${["ck",...f9(Z,J)].join(" ")}, then rerun setup.`;case"grant-reaches-nothing":return`${j7[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 G0 extends Error{host;approvedName;code;constructor($,Z="opencode",J){super(L5($,Z,J));this.host=Z;this.approvedName=J;this.name="NativeVaultActivationError",this.code=$}}function P5($){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 c9($){try{return JSON.parse(await q5($,"utf8"))}catch(Z){if(Z.code==="ENOENT")return;throw new G0("host-auth-invalid")}}async function w1($,Z){if($==="opencode")return"opencode";let J=Z.paths??await L0($,Z.env),z=u9($,await c9(J.hostAuthPath)),X=p9({env:Z.env,authPath:J.hostAuthPath}),{stashPath:G}=M5({env:Z.env,authPath:J.hostAuthPath});return JSON.stringify([z.digest,await X.inspect(),await h9(G)])}async function M7($){try{N5($.env)}catch{throw new G0("auth-content-refused")}try{await F5($.fence,$.env)}catch(Z){let J=D1(Z);if(J)throw new r(J);throw Z}}async function D7($,Z){let J={...Z.env};await(()=>M7({...Z,env:J}))();let X=Z.paths??await L0($,J),G=$==="opencode"&&Z.inspectOpenCodeAuth!==!1&&u9("opencode",await c9(X.hostAuthPath)).kind==="oauth";if($==="pi"){let Q=u9("pi",await c9(X.hostAuthPath)),W=await p9({env:J,authPath:X.hostAuthPath}).inspect();if(W.slot==="placeholder"&&W.stash==="missing")throw new j5("missing-stash");if(Q.kind!=="absent"&&W.slot!=="placeholder"&&!Z.removePiAnthropicAuth)throw new G0("consent-required")}return{priorMode:await D5($,J),fingerprint:await w1($,{...Z,env:J}),separateOpenCodeLogin:G}}async function N7($,Z,J){let z={...Z.env},X=()=>M7({...Z,env:z});await X();let G=Z.paths??await L0($,z);if(await w1($,Z)!==J.fingerprint)throw new G0("host-auth-invalid");let Q=await $7($,{env:z,runner:Z.runner,processFence:X,ckBinary:Z.enrollment?.ckBinary,paths:Z.enrollment?.paths}),W=Z.discover??(()=>V5({paths:G.paths,host:$,env:$==="pi"?{...z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE}:z})),Y,U=async()=>{return Y=await W(),Y},H=B5({paths:G.paths,host:$,vault:{env:z,discover:U}});try{await X(),await H.vault.refresh();let K=await H.read(),D=K.accounts.find((B)=>B.id==="main");if(K.mode!=="claustrum"||!D?.accountIdentity||D.source!=="vault"){let B=P5(Y);throw B==="primary-unverified"?new G0(B):new G0(B,$,Q)}if(await X(),$==="pi")await p9({env:z,authPath:G.hostAuthPath}).enterVault();return J.priorMode==="claustrum"?"already-vault":"committed"}finally{await H.close()}}var C5=/(?:^|[/\\])(opencode|litecode|opencode2|pi)(?:\.exe)?(?=$|\s|")/i;class d9 extends Error{activeHosts;constructor($){let Z=$.map((z)=>({pid:z.pid,command:C5.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}
|