@cortexkit/opencode-anthropic-auth 2.4.13 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/billing-lineage.d.ts +1 -0
- package/dist/cli.js +45 -45
- package/dist/index-y6xse2x7.js +45 -0
- package/dist/index.js +1 -1
- package/dist/transform.d.ts +3 -0
- package/dist/v2/adapter.d.ts +8 -8
- package/dist/v2/install.d.ts +1 -0
- package/dist/v2/reload.d.ts +15 -0
- package/dist/v2/server.js +11 -11
- package/package.json +2 -2
- package/dist/index-e3wjv6pw.js +0 -45
package/dist/cli.js
CHANGED
|
@@ -1,58 +1,58 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{B as L3}from"./index-qqs4ec18.js";import{D as G7,E as Q7,F as u$,G as c$,H as p$,I as d$,J as W7}from"./index-a0jxsmac.js";import{la as a4,ma as yZ,na as E3}from"./index-n8xr16kr.js";var r9=yZ((Aq,p4)=>{var o9={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"},gZ={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},vZ={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?o9.up():"");if($)Z+=o9.left;return Z}};p4.exports={cursor:o9,scroll:gZ,erase:vZ,beep:"\x07"}});import{stdin as IJ,stdout as _J}from"node:process";import{createInterface as RJ}from"node:readline/promises";import{authorize as SJ,createNativeAccountRuntime as kJ,decideOpenCodeStateLayoutOnce as TJ,exchange as EJ,formatNativeAccountState as bJ,generateRelayToken as fJ,getAccountStoragePath as xJ,isValidApiBaseURL as yJ,readNativeEnrollmentMode as gJ,resolveNativePoolPaths as vJ,WORKER_SCRIPT as hJ}from"@cortexkit/anthropic-auth-core";import{randomUUID as o6}from"node:crypto";import{constants as G3}from"node:fs";import{lstat as r6,mkdir as t6,open as e6}from"node:fs/promises";import{homedir as $5}from"node:os";import{isAbsolute as Z5,join as Q4}from"node:path";import{types as f9}from"node:util";import{anthropicAuthStateRoot as J5,createProviderErrorRedactor as W4,createWindowsOwnerOnly as z5,ensureWindowsOwnerOnlyDirectory as X5,formatLogLine as G5,HOLDER_REGISTRATION_ERROR_MESSAGES as Q5,isOwnerOnly as W5,isSecretKey as H5,isStateLayoutRefusalCode as Y5,NativeMigrationError as U5,NativePiAuthSlotError as q5,PRIVATE_FILES_UNAVAILABLE_MESSAGE as H4,RELOCATED_MESSAGE as K5,STATE_LAYOUT_REFUSAL_CODES as F5,STATE_LAYOUT_REFUSAL_PUBLIC_MESSAGES as B5,setupEnrollment as V5,stateLayoutRefusalPublicMessage as j5}from"@cortexkit/anthropic-auth-core";import{readFile as m6}from"node:fs/promises";import{assertHostsStopped as w6,createNativeAccountRuntime as u6,discoverNativeVaultInventory as c6,inspectNativeHostAuthEntry as R9,NativePiAuthSlotError as p6,nativePiAuthSlotPaths as d6,openNativePiAuthSlot as k9,readNativeEnrollmentMode as l6,requireNoSupervisedAuthContentSnapshot as a6}from"@cortexkit/anthropic-auth-core";import{dirname as B6}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as V6,CLAUSTRUM_PI_ENROLLMENT_NAME as j6,getHostClaustrumEnrollmentPaths as g$,resolveClaustrumConnectionPath as M6}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as yQ}from"@cortexkit/claustrum-client";import{ClaustrumClient as BQ}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as F7}from"@cortexkit/claustrum-client";import{SocketClosedError as B7,SocketTimeoutError as V7,SubcCallError as j7}from"@cortexkit/subc-client";class O extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var _3=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class r extends O{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function N0($){if($ instanceof r||$ instanceof B7||$ instanceof V7)return"unreachable";let Z=$ instanceof F7||$ instanceof j7?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(_3,Z))return"answered";return _3[Z]}import{resolve as W2}from"node:path";import{storeIdentity as zz}from"@cortexkit/claustrum-client";import{SubcClient as Gz}from"@cortexkit/subc-client";var a0=300000,h1=300000,R3=1000;class D1{#$;#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 m1{#$;#Z;#J;#W=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#J}request(){if(this.#J)return this.#W=!0,this.#J;return this.#J=(async()=>{do{this.#W=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#W)})().finally(()=>{this.#J=void 0}),this.#J}}class w1{#$;#Z=new D1;#J;#W="polling";#G;#Q;#X=!1;#z;#D=!1;#H=0;constructor($){this.#$=$,this.#J=new m1(async()=>{let Z=this.#D;if(this.#D=!1,Z||this.#z!==this.#$.view())await this.#$.discover(this.#z??"")},(Z)=>{if(!this.#X)this.#$.onError?.(Z)})}get mode(){return this.#W}start(){if(this.#X||this.#G||this.#Q)return;if(typeof this.#$.client.watchScoped!=="function"){this.#Y("fallback","client-without-watch");return}this.#V(!1)}stop(){if(this.#X)return;if(this.#X=!0,this.#Q)(this.#$.clearTimeoutImpl??clearTimeout)(this.#Q);this.#Q=void 0;let $=this.#G;this.#G=void 0,$?.handle.stop()}#Y($,Z){if(this.#W===$)return;this.#W=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#K($,Z){this.#Q=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#Q=void 0,!this.#X)Z()},$),this.#Q.unref?.()}async#V($){let Z;try{Z=await this.#$.enrollmentToken()}catch(Q){if(this.#X)return;this.#$.onError?.(Q),this.#j("token-unreadable");return}let J=this.#$.client.watchScoped;if(this.#X||this.#G||!J)return;this.#Z.restart(),this.#D=$;let z,X;try{X=J.call(this.#$.client,(Q)=>{if(this.#X||!z||this.#G!==z)return;if(z.notices++,z.notices===1)this.#$.onReachable?.(),z.acceptedAt=(this.#$.now??Date.now)(),this.#Y("watching","accepted");if(!this.#Z.continuous(Q))this.#D=!0;this.#z=Q.view,this.#J.request()},{enrollmentToken:Z})}catch(Q){this.#$.onError?.(Q),this.#j("watch-failed");return}z={handle:X,notices:0},this.#G=z,this.#Y("polling",$?"resubscribing":"opening");let G=z;X.closed.then((Q)=>this.#U(G,Q),(Q)=>this.#U(G,{kind:"transport_lost",error:Q}))}#U($,Z){if(this.#X||this.#G!==$)return;if(this.#G=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#Y("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#j("refused");try{this.#$.onRefused(Z.error)}catch(J){this.#$.onError?.(J)}return}if($.notices>0){let J=(this.#$.now??Date.now)();if($.acceptedAt!==void 0&&J-$.acceptedAt>=300000)this.#H=0;let z=Math.min(1000*2**Math.min(this.#H,16),300000);this.#H++,this.#Y("polling","resubscribing"),this.#K(z,()=>void this.#V(!0));return}this.#j(Z.kind)}#j($){this.#Y("fallback",$),this.#K(300000,()=>void this.#V(!1))}}var c1=60000,H2=4*c1,M7=2*c1,S3=new Map,u1=new Map;function s0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function D7($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!s0(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 N7($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class Y2{transport;key;#$=[];#Z=!1;#J=new Set;#W=new Map;#G=new m1(async()=>{try{let $=await this.transport.getUsage();if(!s0($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>s0(Z)&&typeof Z.provider==="string"),this.#Z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#J=new Set(this.#Z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#J)this.#W.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#J.clear()}},()=>{});#Q=new D1;#X="polling";#z=0;#D=0;#H=new Map;#Y;#K;#V={};#U=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#G.running)return this.#G.running;if(this.#X==="watching")return Promise.resolve();for(let[J,z]of u1)if($-z>=c1)u1.delete(J);let Z=u1.get(this.key);if(Z!==void 0&&$-Z<c1)return Promise.resolve();return u1.set(this.key,$),this.#G.request()}watchMode(){return this.#X}watch($={}){this.#z++;let Z=$.provider;if(Z===void 0)this.#D++;else this.#H.set(Z,(this.#H.get(Z)??0)+1);if(this.#z===1)this.#V=$,this.#L();let J=!1;return()=>{if(J)return;if(J=!0,Z===void 0)this.#D--;else{let z=(this.#H.get(Z)??1)-1;if(z>0)this.#H.set(Z,z);else this.#H.delete(Z)}if(--this.#z===0)this.#j()}}#j(){if(this.#K)(this.#V.clearTimeoutImpl??clearTimeout)(this.#K);this.#K=void 0;let $=this.#Y;this.#Y=void 0,$?.handle?.stop(),this.#X="polling"}#M($){this.#K=(this.#V.setTimeoutImpl??setTimeout)(()=>{if(this.#K=void 0,this.#z>0&&!this.#Y)this.#L()},$),this.#K.unref?.()}#L(){let $=this.transport.watchUsage;if(!$){this.#X="fallback";return}this.#X="polling",this.#Q.restart();let Z={notices:0};this.#Y=Z;let J;try{J=$.call(this.transport,(z)=>this.#_(Z,z))}catch(z){this.#C(Z,z);return}Z.handle=J,J.closed.then(()=>this.#C(Z,void 0),(z)=>this.#C(Z,z))}#_($,Z){if(this.#Y!==$)return;if($.notices++,$.notices===1)this.#X="watching";if($.notices===2)this.#U=0;let J=D7(Z);if(!J)this.#Q.restart();if(!(J?this.#Q.continuous(J):!1)||J?.provider===void 0||this.#D>0||this.#H.has(J.provider))this.#G.request()}#C($,Z){if(this.#Y!==$)return;this.#Y=void 0;let J=N7(Z);if(J==="unknown_method"||J==="usage_watch_limit"){this.#X="fallback";return}if($.notices>0){let z=Math.min(R3*2**Math.min(this.#U,16),h1);this.#U++,this.#X="polling",this.#M(z);return}if(this.#X="fallback",this.#G.request(),Z===void 0||N0(Z)==="unreachable")this.#M(h1)}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||!s0(z.usage))continue;let X=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(X)||J-X>=H2)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(!s0(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&&(!s0(z.stale)||z.stale.class!=="local_source_unavailable"))return{miss:"upstream-failed",reading:W};return J>=Q+H2||z.stale!==void 0?{miss:"stale",reading:W}:{reading:W}}if(this.#J.has($))return{miss:"absent"};let G=this.#W.get($)??J;return this.#W.set($,G),{miss:J-G>=M7?"unreachable":"cold"}}}function k3($,Z){let J=JSON.stringify([W2($.connectionFile),W2(Z)]),z=S3.get(J);if(!z)z={source:new Y2($,J),refs:0},S3.set(J,z);z.refs++;let X=!1;return{source:z.source,release(){if(X)return;if(X=!0,--z.refs===0)S3.delete(J)}}}import{ClaustrumCredentialError as NQ}from"@cortexkit/claustrum-client";import{appendFileSync as b7,chmodSync as f7,existsSync as f3,renameSync as L2,statSync as x7}from"node:fs";import{open as y7}from"node:fs/promises";import{dirname as g7,resolve as v7}from"node:path";import{randomUUID as F2}from"node:crypto";import{lstat as B2,readFile as V2,rename as L7,unlink as U2}from"node:fs/promises";import{tmpdir as P7}from"node:os";import{dirname as L0,join as C7,resolve as t}from"node:path";var _=process.platform==="win32",q2=new Set;function T3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var K2;var j2="native-addon-unavailable";function M2($){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:$}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:j2})}function O7($,Z){return Z instanceof $.PrivateFilesUnavailableError||Z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function A7($){try{await $.verifyPrivatePath(C7(P7(),`.common-auth-private-files-probe-${F2()}`),"file")}catch(Z){if(O7($,Z))throw M2(Z)}}function n0(){return K2??=import("@cortexkit/private-files").then(async($)=>{if(_)await A7($);return $},($)=>{throw _?M2($):$}),K2}class m extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor($,Z,J){let z=J;super(z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"?`Private file refused at ${Z}: ${$} (${j2}). 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=T3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}async function i($,Z,J){try{return await J()}catch(z){if(z instanceof m)throw z;throw new m($,Z,z)}}var I7;async function F0($,Z){$=t($),Z??=I7,await i($,"safe-parent",async()=>{let J=await(await n0()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await B2($);throw new m(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function d($,Z,J=!1){if($=t($),Z==="directory")return F0($);await i($,"verify",async()=>{let z=await n0(),X=await z.verifyOwnerOnly($),G=!1;if(!X.ok){let{reason:Q}=X.refusal;if(Q==="io-error")await z.verifyPrivatePath($,Z);if(J&&[z.EXTRA_ACE,z.NOT_PROTECTED,z.NULL_DACL,z.EMPTY_DACL].includes(Q))await F0(L0($)),await z.securePrivatePath($,Z),G=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:Q,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await z.verifyPrivatePath($,Z),G&&!q2.has($))q2.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function G0($,Z=!1,J){$=t($),await i($,"directory",async()=>{let z=await n0();try{return await B2($),await F0($,J)}catch(G){if(T3(G)!=="ENOENT")throw G}let X=L0($);if(X===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await G0(X,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(T3(G)!=="EEXIST")throw G}await F0($,J)})}async function Z0($,Z=!1){if(!_)return V2($,"utf8");return(await _7($,Z)).toString("utf8")}async function _7($,Z=!1){if(!_)return V2($);if($=t($),Z)await F0(L0($)),await d($,"file",!0);return i($,"read",async()=>(await n0()).readOwnerOnly($))}async function i0($,Z){await F0(L0(t($))),await i($,"create",async()=>{await(await n0()).createPrivateFile(t($),Z)})}async function D2($){await F0(L0(t($))),await i($,"directory-create",async()=>{await(await n0()).createOwnerOnly(t($),{kind:"dir"})})}async function b3($,Z,J={}){$=t($),Z=t(Z);let z=J.now??(()=>performance.now()),X=z(),G=J.deadline??1/0,Q,W=[0,10,20,40,80,100],H,q=0;for(let U of W){let M=Math.min(Q??1/0,G);if(z()>=M)break;if(U)await(J.sleep??((L)=>new Promise((C)=>setTimeout(C,L))))(Math.min(U,Math.max(0,M-z())));if(z()>=M)break;let B=z();if(await J.beforeRename?.(),Q!==void 0)Q+=z()-B;if(z()>=G)break;q++;try{return await(J.rename??L7)($,Z),{attempts:q,elapsedMs:z()-X}}catch(L){H??=L;let C=L;if(!(C.win32Code!==void 0?C.win32Code===32||C.win32Code===33:["EBUSY","EPERM","EACCES"].includes(C.code??"")&&!C.reason))break;Q??=z()+500}}let Y=new m(Z,"rename",H??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw Y.attempts=q,Y.elapsedMs=z()-X,Y}async function o0($,Z,J={}){$=t($),await G0(L0($));try{await d($,"file",!0)}catch(q){if(q.code!=="ENOENT")throw q}let z=t(J.stagePath??`${$}.${F2()}.tmp`);if(L0(z)!==L0($))throw new m($,"stage-directory",{code:"EXDEV"});let X=!1,G=!1,Q={attempts:0,elapsedMs:0},W="stage-create",H=(q)=>{try{J.onOutcome?.({path:$,stage:q?.stage??"published",published:G,fileDurable:G,durabilityConfirmed:!1,attempts:q?.attempts??Q.attempts,elapsedMs:q?.elapsedMs??Q.elapsedMs,...q&&{code:q.code,win32Code:q.win32Code}})}catch{}};try{if(await i0(z,Z),X=!0,W="before-rename",Q=await b3(z,$,J),X=!1,G=!0,W="published-callback",J.onRenamed?.(),W="published-verify",await d($,"file"),J.durable&&J.durability!=="file-only-on-windows")throw new m($,"directory-sync-unsupported",{code:"ENOTSUP"});H()}catch(q){let Y=q instanceof m?q:new m($,W,q);if(Y.published=G,Y.fileDurable=G,G)Object.assign(Y,Q);if(X){try{await U2(z)}catch{Y.orphanPath=z}X=!1}throw H(Y),Y}finally{if(X)await U2(z).catch(()=>{})}}var R7=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,S7=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function k7($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function r0($={}){let Z=[S7,...$.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 R7.test(G)||Q.includes("apikey")||Q.endsWith("secret")||Q.endsWith("password")||Q.endsWith("token")&&!Q.endsWith("tokens")||!!$.extraSecretKeys?.(Q)}function z(G){let Q=G,W=[["name",G.name],["message",G.message],["stack",G.stack]];for(let q of["code","status","cause"])if(Q[q]!==void 0)W.push([q,Q[q]]);let H=new Set(W.map(([q])=>q));for(let q of Object.entries(G))if(!H.has(q[0]))W.push(q);return W}function X(G,Q,W,H=0){if(typeof G==="string")return Z.reduce((q,Y)=>q.replace(Y,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if(W.has(G))return"[Circular]";W.add(G);try{if(Array.isArray(G))return G.map((U)=>X(U,Q,W,H));let q=k7(G);if(q&&H>=8)return"[Truncated]";let Y=q?H+1:H;return Object.fromEntries((q?z(G):Object.entries(G)).map(([U,M])=>[U,Q&&J(U)?"***REDACTED***":X(M,Q,W,Y)]))}finally{W.delete(G)}}return{redact:(G)=>X(G,!0,new WeakSet),redactStrings:(G)=>X(G,!1,new WeakSet)}}var N2=r0(),T7=N2.redact,E7=N2.redactStrings;var p1={error:0,warn:1,info:2,debug:3,trace:4},C2=5242880,O2=3;function x3($){try{f7($,384)}catch{}}function h7($){try{if(!(f3($)&&x7($).size>=C2))return;for(let J=O2-1;J>=1;J--)if(f3(`${$}.${J}`)){let z=`${$}.${J+1}`;L2(`${$}.${J}`,z),x3(z)}let Z=`${$}.1`;L2($,Z),x3(Z)}catch{}}async function B0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await i(Z,"log-close",()=>J.close())}async function P2($,Z){await G0(g7(Z));try{await d(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await i0(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await d(Z,"file",!0)}}return $.handle=await i(Z,"log-open",()=>y7(Z,"a")),$.file=Z,$.handle}async function m7($,Z,J){Z=v7(Z);try{if($.file!==Z)await B0($);let z=$.handle??await P2($,Z);if((await i(Z,"log-stat",()=>z.stat())).size>=C2){await B0($);for(let G=O2-1;G>=0;G--){let Q=G===0?Z:`${Z}.${G}`,W=`${Z}.${G+1}`;try{await d(Q,"file",!0)}catch(H){if(H.code==="ENOENT")continue;throw H}try{await d(W,"file",!0)}catch(H){if(H.code!=="ENOENT")throw H}await b3(Q,W),await d(W,"file")}z=await P2($,Z)}await i(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await B0($).catch(()=>{}),z}}function w7($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function u7($){let Z,J,z,X=r0(),G,Q=[],W,H=Promise.resolve(),q,Y={};function U(F){let K=H.then(F);return H=K.catch((V)=>{q=V}),K}function M(F){if(_&&F.file!==Z)U(()=>B0(Y)).catch(()=>{});Z=F.file,J=F.level,X=r0(F),G=F.captureSink}function B(F){if(F===void 0||F in p1)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 p1)return F;return"info"}function A(F=!0){if(W)clearTimeout(W),W=void 0;if(!Q.length){if(_)return U(async()=>{if(F)await B0(Y);if(q)throw q});return}let K;try{K=L()}catch{if(Q=[],_&&F)return U(()=>B0(Y));return}let V=Q.join("");if(Q=[],!K){if(_&&F)return U(()=>B0(Y));return}if(_)return U(async()=>{try{await m7(Y,K,V)}finally{if(F)await B0(Y)}});try{if(h7(K),f3(K))x3(K);b7(K,V,{encoding:"utf8",mode:384})}catch{}}function I(){if(!W)W=setTimeout(()=>{W=void 0;let F=A(!1);if(F instanceof Promise)F.catch(()=>{})},500)}function R(F,K,V,P){if(Z===void 0&&G===void 0)return;try{if(p1[K]>p1[C()])return;let x=X.redactStrings(V),k;try{k=X.redact(P)}catch{k="[unserializable]"}let y=`[${new Date().toISOString()}] ${K.toUpperCase()} [${F}] ${x}`+(P===void 0?"":w7(k))+`
|
|
3
|
-
`;try{G?.({channel:F,level:K,message:
|
|
4
|
-
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??
|
|
5
|
-
`,"utf8"),await G.chmod(384),J.durable)try{await G.sync()}catch(W){throw new
|
|
6
|
-
`,{deadline:performance.now()+Math.max(0,
|
|
7
|
-
`,"utf8"),await
|
|
8
|
-
`;if(_)await
|
|
9
|
-
`;if(_)await
|
|
10
|
-
`)){if(z.trim()===""||z.startsWith("#"))continue;let X=z.split(":");if(X.length!==Z||!/^[^\s:,]+$/.test(X[0]??"")||!/^\d+$/.test(X[2]??"")||!Number.isSafeInteger(Number(X[2]))||Z===7&&(!/^\d+$/.test(X[3]??"")||!Number.isSafeInteger(Number(X[3])))||Z===4&&X[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(X[3]??""))return;J.push(X)}return J}async function
|
|
11
|
-
`;if(Buffer.byteLength(X)>n1)throw new O("invalid-state","Claustrum enrollment state is too large");if(_)return o0($,X);let G=F8(z,`.${K8($)}.${process.pid}.${W8()}.tmp`),Q,W=!1;try{Q=await w2(G,"wx",384),W=!0,await Q.writeFile(X,"utf8"),await Q.chmod(384),await Q.sync(),await Q.close(),Q=void 0,await q8(G,$),W=!1}finally{if(await Q?.close().catch(()=>{}),W)await w3(G).catch(()=>{})}}var D8=new N1;async function i1($,Z){let J=_?await m2($,Z):await D8.read([$.tokenPath,$.statePath],async([X=$.tokenPath,G=$.statePath])=>m2({tokenPath:X,statePath:G},Z),(X)=>{for(let G of X)if(G!=="absent")n2(G)}),z={...J.status};if(J.usesProposedName&&z.state==="approved")z.proposedName=Z;return z}async function m2($,Z){let J=await b0($.tokenPath),z=J===void 0?void 0:p3(J),X=await b0($.statePath),G=X===void 0?void 0:c3(X);if(z)return{usesProposedName:G===void 0,status:{state:"approved",proposedName:G?.proposedName??Z,...G?.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:z.token_generation}};if(!G)return{status:{state:"idle"},usesProposedName:!1};if(G.phase==="approved")return{usesProposedName:!1,status:{state:"blocked",proposedName:G.proposedName,code:"missing_token"}};return{status:C0(G),usesProposedName:!1}}async function O0($){let Z=await b0($);if(Z===void 0)throw new O("not-enrolled","Claustrum enrollment is not configured");return p3(Z)}function C0($){if($.phase==="pending")return{state:"pending",proposedName:$.proposedName,...$.requestId!==void 0&&{requestId:$.requestId}};if($.phase==="approved")return{state:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration};if($.phase==="denied")return{state:"denied",proposedName:$.proposedName};return{state:"blocked",proposedName:$.proposedName,code:$.errorCode??"unknown"}}function r2(){return new O("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class d3{#$;#Z;#J;#W;#G;#Q;#X;constructor($){this.#X=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#J=$.proposedName,this.#W=$.now??Date.now,this.#G=$.mintSecret??(()=>Q8(32).toString("hex")),this.#Q=$.writeTokenFile??V8}async status(){return i1(this.#Z,this.#J)}async resetTerminal(){return t2(this.#Z,this.#J)}async#z($,Z){let J={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#W()};return await T0(this.#Z.statePath,J,this.#X),C0(J)}async reconcile(){await e0(E0(this.#Z.statePath),this.#X);let $=await j0({name:"ceremony",path:this.#Z.statePath,ttlMs:c2,renew:!0});if(!$)return{state:"busy"};try{let Z=await b0(this.#Z.tokenPath),J=Z===void 0?void 0:p3(Z),z=await b0(this.#Z.statePath),X=z===void 0?void 0:c3(z);if(X&&X.proposedName!==this.#J)throw r2();if(J){if(!X||X.phase==="pending"){let Q={version:1,phase:"approved",proposedName:X?.proposedName??this.#J,tokenGeneration:J.token_generation,updatedAt:this.#W()};await T0(this.#Z.statePath,Q,this.#X),X=Q}return{state:"approved",proposedName:X.proposedName,...X.phase==="approved"&&X.approvedName!==void 0&&{approvedName:X.approvedName},tokenGeneration:J.token_generation}}if(X?.phase==="approved"){let Q={version:1,phase:"blocked",proposedName:X.proposedName,errorCode:"missing_token",updatedAt:this.#W()};return await T0(this.#Z.statePath,Q,this.#X),C0(Q)}if(X&&X.phase!=="pending")return C0(X);if(!X){let Q=this.#W();if(X={version:1,phase:"pending",proposedName:this.#J,requestSecret:this.#G(),createdAt:Q,updatedAt:Q},!u3.test(X.requestSecret))throw new O("invalid-state","invalid minted Claustrum enrollment secret");await T0(this.#Z.statePath,X,this.#X)}if(!X.requestId)try{let Q=G8("sha256").update(Buffer.from(X.requestSecret,"hex")).digest("hex"),W=await this.#$.enrollPropose({name:X.proposedName,requestSecretHash:Q});X={...X,requestId:W.requestId,updatedAt:this.#W()},await T0(this.#Z.statePath,X,this.#X)}catch(Q){let W=m3(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,retryCode:W.code};if(W.code===p2)return await $.assertOwned(),await w3(this.#Z.statePath).catch((H)=>{if(H.code!=="ENOENT")throw H}),{state:"unavailable",proposedName:X.proposedName,code:W.code};return this.#z(X,W.code)}let G=X.requestId;if(!G)return C0(X);try{let Q=await this.#$.enrollPoll({requestId:G,requestSecret:X.requestSecret});if(Q.status==="pending")return C0(X);if(Q.status==="denied"){let H={version:1,phase:"denied",proposedName:X.proposedName,updatedAt:this.#W()};return await T0(this.#Z.statePath,H,this.#X),C0(H)}await e0(E0(this.#Z.tokenPath),this.#X),await o2(E0(this.#Z.tokenPath),this.#X),await this.#Q(this.#Z.tokenPath,{token:Q.token,token_generation:Q.tokenGeneration});let W={version:1,phase:"approved",proposedName:X.proposedName,approvedName:Q.name,tokenGeneration:Q.tokenGeneration,updatedAt:this.#W()};return await T0(this.#Z.statePath,W,this.#X),C0(W)}catch(Q){let W=m3(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,requestId:G,retryCode:W.code};return this.#z(X,W.code)}}finally{await $.release()}}}async function t2($,Z){await e0(E0($.statePath));let J=await j0({name:"ceremony",path:$.statePath,ttlMs:c2,renew:!0});if(!J)return"busy";try{if(await b0($.tokenPath)!==void 0)return"refused-approved";let z=await b0($.statePath);if(z===void 0)return"idle";let X=c3(z);if(X.proposedName!==Z)throw r2();if(X.phase==="pending")return"refused-pending";return await J.assertOwned(),await w3($.statePath),"reset"}finally{await J.release()}}var l3="claustrum-tombstone:v1:";function $1($,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 Z1($,Z){if(!$.size)return;let J,z=!1,X=(async()=>{while(!z&&$.size)await Promise.allSettled([...$])})();try{if(await Promise.race([X,new Promise((G)=>{J=setTimeout(()=>{z=!0,G()},2000)})]),z&&$.size)Z($.size)}finally{z=!0,clearTimeout(J)}}function $$($,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 s3=Q0("claustrum"),A0=N8("common-auth.claustrum.phases");function i3($,Z,J,z=s3){let X=$$(Z,J);return z.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:J?.recordVersion??null,retry:X,reason:L8(Z,J)}),X}var n3=300000,Z$=60000;function a3(){return new O("invalid-material","Claustrum returned invalid credential material")}function P8($){let Z=$.trim();if(Z.startsWith("{")){let J;try{J=JSON.parse(Z)}catch{throw a3()}if(!J||typeof J!=="object")throw a3();let z=J,X=z.access_token??z.access;Z=typeof X==="string"?X:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(l3))throw a3();return Z}function C8($,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=O8($),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 O8($){let Z=$;return{providerIds:Z.providerIds,authMethod:Z.authMethod}}function A8($){let{grants:Z,grantTuples:J}=$;if(Z===void 0||J===void 0)return;return Object.freeze({grants:Z,tuples:Object.freeze(J.map(({selectorKind:z,selector:X,operation:G})=>Object.freeze({selectorKind:z,selector:X,operation:G})))})}class J1{#$;#Z;#J;#W;#G;#Q;#X;#z=new WeakMap;#D=new WeakMap;#H=new Map;#Y=new WeakMap;#K;#V;#U=!1;#j=new r;#M;#L=!1;#_=-1/0;#C=2000;#q=!1;#N;#A=new Set;#F=new Set;#P;#O;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>O0(Z);else throw new O("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#W=$.family,this.#G=$.parseIdentity,this.#Q=$.requireAssertion??!1,this.#J=$.now??Date.now,this.#X=$.logger??s3,this.#P=$1(this.#X),this.#K=$.setTimeoutImpl??setTimeout,this.#V=$.clearTimeoutImpl??clearTimeout}transportLost($){if(this.#q||this.#U)return;this.#U=!0,this.#j=$ instanceof e2?$:new r,this.#X.warn("serving kept vault receipt",{reason:"unreachable"}),this.#I()}reachable(){if(this.#q||!this.#U)return;if(this.#U=!1,this.#M)this.#V(this.#M);this.#M=void 0,this.#C=2000;for(let $ of this.#H.values())$.since=null;(this.#X.info??s3.info)("vault receipt serving resumed",{reason:"reachable"})}#I(){if(this.#q||!this.#U||this.#M||this.#L)return;this.#M=this.#K(()=>{this.#M=void 0,this.#k(!0)},this.#C),this.#M.unref?.()}#k($=!1){if(this.#q||!this.#U||this.#L)return;if(this.#J()-this.#_<1000){this.#I();return}this.#_=this.#J(),this.#L=!0,this.#T().catch(()=>{if($&&this.#U)this.#C=Math.min(this.#C*2,30000)}).finally(()=>{this.#L=!1,this.#I()})}#B($){if(this.#q)throw new O("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#R($){if(this.#B($),A0.hasSubscribers)A0.publish({logger:this.#X,phase:"token read begin"});let Z=this.#Z();this.#F.add(Z);let J;try{J=await Z}finally{if(this.#F.delete(Z),A0.hasSubscribers)A0.publish({logger:this.#X,phase:"token read end"})}if(this.#B($),!/^[0-9a-f]{64}$/.test(J.token)||!Number.isSafeInteger(J.token_generation)||J.token_generation<1)throw new O("invalid-token","Invalid Claustrum enrollment token");return J.token}async#S($,Z){this.#B(Z);let J,z;try{let X=$();J=Z?await Promise.race([X,new Promise((G,Q)=>{let W=()=>Q(Z.reason);if(Z.addEventListener("abort",W,{once:!0}),z=()=>Z.removeEventListener("abort",W),Z.aborted)W()})]):await X}catch(X){if(this.#B(Z),N0(X)==="unreachable")this.transportLost(X);else this.reachable();if(X instanceof e2)throw X;if(N0(X)==="unreachable")throw new r;throw new O("unavailable","Claustrum scoped operation unavailable")}finally{z?.()}return this.#B(Z),this.reachable(),J}async discover($){let Z=await this.#T($);return this.#N=Z.view,Z}async#T($){let Z,J;try{J=await this.#R($)}catch(Y){throw this.#H.clear(),Y}if(A0.hasSubscribers)A0.publish({logger:this.#X,phase:"list scoped begin"});try{Z=await this.#S(()=>this.#$.listScoped(J),$)}catch(Y){throw this.listFailed(Y),Y}finally{if(A0.hasSubscribers)A0.publish({logger:this.#X,phase:"list scoped end"})}let z=[],X=[],G=0,Q=[],W=new Map;for(let Y of Z.rows){let U=C8(Y,this.#W);if(U.kind==="not-mine"){G++;continue}if(U.kind==="refused"){X.push({...Y.id.trim()&&{credentialId:Y.id},code:U.code});continue}Q.push({row:Y,type:U.type,...U.member!==void 0&&{member:U.member}}),W.set(Y.id,(W.get(Y.id)??0)+1)}let H=[];for(let{row:Y,type:U,member:M}of Q){let B;if(!Y.id.trim())B="empty credential id";else if((W.get(Y.id)??0)>1)B="duplicate credential id";else if(Y.accountId!==void 0&&!Y.accountId.trim())B="blank account identity";else if(!Y.state.trim())B="empty state";if(B){z.push({...Y.id.trim()&&{credentialId:Y.id},...M!==void 0&&{member:M},reason:B});continue}H.push(Object.freeze({credentialId:Y.id,credentialType:U,...M!==void 0&&{member:M},...Y.accountId!==void 0&&{accountIdentity:Y.accountId},state:Y.state,...Y.email!==void 0&&{email:Y.email},...Y.orgName!==void 0&&{orgName:Y.orgName}}))}for(let Y of z)this.#X.warn("skipped malformed vault record",Y);let q=A8(Z);return{view:Z.view,credentials:Object.freeze(H),skipped:Object.freeze(z),..."classify"in this.#W&&{refused:Object.freeze(X),notMine:G},...q&&{grantReach:q}}}listFailed($){if(N0($)==="unreachable")this.transportLost($);else this.reachable(),this.#H.clear()}forget($){this.#H.delete($)}retain($){let Z=new Map($.map((J)=>[J.credentialId,J]));for(let[J,z]of this.#H){let X=Z.get(J);if(!X?.enabled||X.state!=="active"||X.credentialType!==z.attempt.credentialType||X.accountIdentity!==z.attempt.expectedAccountIdentity)this.forget(J)}}keptReceiptState(){let $=null;for(let[Z,J]of this.#H){if(!this.#x(J.attempt)){this.forget(Z);continue}if(J.since!==null)$=Math.min($??J.since,J.since)}return Object.freeze({active:$!==null,since:$})}#x($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#J()>Z$}async authorize($,Z,J="vault"){this.#B(Z);let{credentialId:z,credentialType:X,accountIdentity:G}=$,Q=this.#H.get(z);if(Q&&(Q.attempt.credentialType!==X||Q.attempt.expectedAccountIdentity!==G))this.forget(z),Q=void 0;let W;try{W=await this.#R(Z)}catch(H){throw this.#H.clear(),H}if(this.#U&&Q)return this.#k(),this.#b(z,Q,W,J);try{let H=await this.#f({credentialId:z,credentialType:X,accountIdentity:G},W,Z);return this.#H.set(z,{attempt:H,routeId:J,since:null}),H}catch(H){if(this.#B(Z),N0(H)!=="unreachable")throw this.forget(z),H;return this.#b(z,Q,W,J,H)}}#b($,Z,J,z,X=this.#j){if(!Z||this.#H.get($)!==Z||!this.#x(Z.attempt))throw this.forget($),X;if(Z.since===null)Z.since=this.#J();let G=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#z.set(G,J),this.#Y.set(G,z),G}async#f($,Z,J){if(!$.credentialId)throw new O("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:z,credentialType:X,accountIdentity:G}=$;if(this.#Q&&G===void 0)throw new O("identity-unasserted","Claustrum dispatch requires a known account identity");let Q=await this.#S(()=>this.#$.getScoped({credentialId:z,enrollmentToken:Z,...X==="oauth"&&{minTtlMs:n3}}),J);if(Q.credentialId!==void 0&&Q.credentialId!==z)throw new O("identity-changed","Claustrum served credential identity changed");let W=Q.expiresAtMs;if(!Number.isSafeInteger(Q.recordVersion)||Q.recordVersion<0||W===null&&X==="oauth"||W!==null&&(!Number.isFinite(W)||W-this.#J()<n3))throw new O("insufficient-validity","Claustrum served credential has insufficient validity");let H=P8(Q.material),q=Q.accountId?.trim()?Q.accountId:void 0;if(this.#Q&&(Q.credentialId===void 0||q===void 0))throw new O("identity-unasserted","Claustrum served credential did not assert its identity");let Y=q===void 0?this.#G?.(H):void 0,U=q??Y;if(G!==void 0&&U!==void 0&&U!==G)throw new O("identity-changed","Claustrum served credential identity changed");let M=U??G,L=Object.freeze(Object.defineProperty({credentialId:z,credentialType:X,...M!==void 0&&{accountIdentity:M},accountIdentitySource:q!==void 0?"asserted":Y!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...Q.credentialId!==void 0&&{assertedCredentialId:Q.credentialId},...q!==void 0&&{assertedAccountIdentity:q},...Q.projectId!==void 0&&{projectId:Q.projectId},recordVersion:Q.recordVersion,expiresAtMs:W},"accessToken",{value:H,enumerable:!1}));return this.#z.set(L,Z),L}async reportFailure($,Z,J){if(Z!==401)return;this.#B();let z=this.#z.get($);if(!z)throw new O("no-receipt","Claustrum failure report requires an original dispatch receipt");let X=this.#Y.get($);if(X!==void 0){this.forget($.credentialId),this.#X.debug("scoped 401 not reported",{routeId:X,reason:"kept-receipt"});return}let G=this.#H.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let Q=this.#D.get($);if(Q)return Q;let W=this.#S(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:z,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#D.set($,W);try{await W,this.#X.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:J})}catch(H){throw this.#D.delete($),H}}watchRoster($){this.#B();let Z=new w1({client:this.#$,enrollmentToken:()=>this.#R(),view:$.view??(()=>this.#N),discover:async(J)=>{await $.onView(J)},onRefused:(J)=>{this.listFailed(J),$.onRefused?.(J)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#X,now:this.#J,setTimeoutImpl:this.#K,clearTimeoutImpl:this.#V});return this.#A.add(Z),Z.start(),{get mode(){return Z.mode},close:()=>{this.#A.delete(Z),Z.stop()}}}close(){if(this.#q)return;if(this.#q=!0,this.#M)this.#V(this.#M);this.#M=void 0;for(let $ of this.#A)$.stop();this.#A.clear(),this.#H.clear(),this.#$.close()}async dispose($=this.#P){this.close(),this.#O??=Z1(this.#F,$),await this.#O}}import{resolve as Z3}from"node:path";var o3=30000,r3={now:()=>performance.now(),schedule($,Z){let J=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(J),unref:()=>J.unref?.()}}};var f0="all",I8=Object.freeze(["primary"]);function z$($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function X1($,Z){return JSON.stringify([$,Z])}function I0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function l($){return typeof $==="number"&&Number.isFinite($)}function J$($){return typeof $==="string"&&$.length>0}function s($,Z,J){return $[Z]===void 0||J($[Z])}function _8($){return l($)&&$>0}function t3($){return typeof $==="string"}function R8($){if(!I0($)||!J$($.scope)||!J$($.label))return!1;switch($.kind){case"reading":return l($.checkedAt)&&l($.usedPercent)&&s($,"resetsAt",t3)&&s($,"windowMinutes",_8);case"retired":return l($.retiredAt);case"absent":return l($.checkedAt);default:return!1}}function S8($){if(!I0($)||!l($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&s($,"remainingPercent",l)&&s($,"usedPercent",l)&&s($,"resetsAt",t3)&&s($,"limit",l)&&s($,"used",l)&&s($,"remaining",l)&&s($,"unit",t3)}function X$($){return I0($)&&l($.value)&&Number.isInteger($.value)&&$.value>=0&&l($.checkedAt)}function e3($){return I0($)&&Object.values($).every(X$)}function k8($){return typeof $==="boolean"}function G1($){return I0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&s($,"balance",l)&&s($,"overageLimitReached",k8)&&l($.checkedAt)}function G$($){if(!I0($))return;let Z=Object.entries($).filter(([,J])=>X$(J));return Z.length===0?void 0:Object.fromEntries(Z)}function x0($){if(z1($))return $;if(!I0($))return;let{counters:Z,credits:J,...z}=$;if(!z1(z))return;let X=G$(Z),G=G1(J)?J:void 0;return{...z,...X===void 0?{}:{counters:X},...G===void 0?{}:{credits:G}}}function z1($){if(!I0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!R8(J))return!1;let z=X1(J.scope,J.label);if(Z.has(z))return!1;Z.add(z)}return s($,"budget",S8)&&s($,"counters",e3)&&s($,"credits",G1)}class o1 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function t1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function r1($){return typeof $==="number"&&Number.isFinite($)}function Q$($){return $===void 0||typeof $==="string"&&$!==""}function W$($){return typeof $==="string"&&$!==""}function O1($,Z){return $[Z]===void 0||r1($[Z])}function $9($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function T8($){return t1($)&&Q$($.scope)&&W$($.label)&&r1($.usedPercent)&&$9($,"resetsAt")&&($.windowMinutes===void 0||r1($.windowMinutes)&&$.windowMinutes>0)}function E8($){return t1($)&&Q$($.scope)&&W$($.label)}function b8($){if(!t1($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&O1($,"remainingPercent")&&O1($,"usedPercent")&&$9($,"resetsAt")&&O1($,"limit")&&O1($,"used")&&O1($,"remaining")&&$9($,"unit")}function Q1($){if(!t1($)||!r1($.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(!T8(X))return!1;let G=X1(X.scope??f0,X.label);if(z.has(G))return!1;z.add(G)}if(!J.every(E8))return!1;return($.budget===void 0||b8($.budget))&&($.counters===void 0||e3($.counters))&&($.credits===void 0||G1($.credits))}function f8($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function x8($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function y8($,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 g8($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function A1($,Z){let J=$===void 0?void 0:x0($);if($!==void 0&&J===void 0)throw new o1("stored quota map is malformed");if(!Q1(Z))throw new o1("quota observation is malformed");let z=J??{limits:[]},X=Z.checkedAt,G=new Map;for(let A of z.limits)G.set(X1(A.scope,A.label),A);let Q=(A)=>{let I=G.get(A);return I===void 0||X>=z$(I)},W=new Set;for(let A of Z.readings??[]){let I=A.scope??f0,R=X1(I,A.label);if(W.add(R),!Q(R))continue;G.set(R,{scope:I,label:A.label,kind:"reading",checkedAt:X,usedPercent:A.usedPercent,...A.resetsAt===void 0?{}:{resetsAt:A.resetsAt},...A.windowMinutes===void 0?{}:{windowMinutes:A.windowMinutes}})}for(let A of Z.coverage??[]){let I=A.scope??f0,R=X1(I,A.label);if(W.has(R)||!Q(R))continue;let h=G.get(R);G.set(R,h===void 0||h.kind==="absent"?{scope:I,label:A.label,kind:"absent",checkedAt:X}:{scope:I,label:A.label,kind:"retired",retiredAt:X})}let{limits:H,budget:q,counters:Y,credits:U,...M}=z,B=x8(z.budget,Z.budget,X),L=y8(z.counters,Z.counters),C=g8(z.credits,Z.credits);return{...M,limits:[...G.values()].sort(f8),...B===void 0?{}:{budget:B},...L===void 0?{}:{counters:L},...C===void 0?{}:{credits:C}}}var v8=Object.freeze({validate:z1,decode:x0,merge:A1});function H$($,Z=""){let J=new Map,{observation:z}=$,X=(W,H,q)=>J.set(`${Z}:${W}`,{at:H,order:0,publication:{...$,observation:q}}),G=(W,H)=>JSON.stringify([W??"all",H]),Q=new Set;for(let W of z.readings??[]){let H=G(W.scope,W.label);Q.add(H),X(H,z.checkedAt,{checkedAt:z.checkedAt,readings:[{...W}]})}for(let W of z.coverage??[]){let H=G(W.scope,W.label);if(!Q.has(H))X(H,z.checkedAt,{checkedAt:z.checkedAt,coverage:[{...W}]})}if(z.budget)X("budget",z.checkedAt,{checkedAt:z.checkedAt,budget:{...z.budget}});for(let[W,H]of Object.entries(z.counters??{}))X(`counter:${W}`,H.checkedAt,{checkedAt:z.checkedAt,counters:{[W]:{...H}}});if(z.credits)X("credits",z.credits.checkedAt,{checkedAt:z.checkedAt,credits:{...z.credits}});if(!J.size)X("empty",z.checkedAt,{checkedAt:z.checkedAt});return J}import{createHash as u8}from"node:crypto";import{stat as c8}from"node:fs/promises";import{resolve as I1}from"node:path";function Y$($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function Z9($,Z,J){return $.some((z)=>Y$(z,Z,J))}function J9($,Z,J){let z={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((X)=>X.credentialId!==Z||X.accountIdentity!==J),z]}function z9($,Z,J){return $.filter((z)=>!Z.some((X)=>Y$(z,X,J)))}function X9($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>W0(Z).map((J)=>({credentialId:J,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function p8($,Z){let J=W0(Z),z=Z.accountIdentity===void 0?-1:$.order.findIndex((G)=>G.accountIdentity===Z.accountIdentity),X=z>=0?z:$.order.findIndex((G)=>J.includes(G.credentialId));return X>=0?X:1/0}var $3="vault:";function d8($){return u8("sha256").update($).digest("hex")}function l8($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function a8($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function W0($){return[$.credentialId,...$.aliases??[]]}function K$($,Z,J={}){let z=J.now??Date.now(),X=J.routePrefix??$3,G=J.reservedRouteIds??new Set,Q=$?.rows??[],W=$?void 0:J.seed,H=[...$?.declined??W?.declined??[]],q=Z.skipped.length===0,Y=new Set(Z.credentials.map((F)=>F.credentialId)),U=new Set(Z.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),M=Z.skipped.some((F)=>F.credentialId===void 0),B=(F)=>!Y.has(F)&&(U.has(F)||M),L=new Map;for(let F of Q){if(F.accountIdentity===void 0)continue;for(let K of W0(F))if(!L.has(K))L.set(K,F.accountIdentity)}let C=new Map;for(let F of Z.credentials){let K=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:L.get(F.credentialId),claimed:!1},V=a8(K),P=C.get(V)??[];P.push(K),C.set(V,P)}let A=new Set,I=new Set(G),R=[],h=(F,K)=>F.credential.credentialId.localeCompare(K.credential.credentialId),w=[...C.values()].map((F)=>F.toSorted(h)).sort((F,K)=>F[0]&&K[0]?h(F[0],K[0]):0);for(let F of w){let K=F[0]?.identity,V=F.filter((T)=>T.credential.state==="active"),P=V.length?V:F,x=P.filter((T)=>T.claimed),k=x.length?x:P,y=new Set(F.map((T)=>T.credential.credentialId)),$0=Q.find((T)=>!A.has(T)&&W0(T).some((K0)=>y.has(K0))&&(T.accountIdentity===void 0||T.accountIdentity===K)),p=k.find((T)=>T.credential.credentialId===$0?.credentialId)??k[0];if(!p)continue;let c=p.credential,a=$0??(K===void 0?void 0:Q.find((T)=>!A.has(T)&&T.accountIdentity===K));if(a)A.add(a);let q0=a?.routeId;if(!q0||G.has(q0)){let T=`${X}${c.credentialId}${K===void 0?"":`~${d8(K).slice(0,10)}`}`;q0=T;for(let K0=2;I.has(q0);K0++)q0=`${T}~${K0}`}I.add(q0);let g1=a?W0(a).filter(B):[],d0=[...new Set([...F.map((T)=>T.credential.credentialId),...g1])].filter((T)=>T!==c.credentialId).sort((T,K0)=>T.localeCompare(K0)),v1=J.mapAccount?.(c)??{};R.push({previousIndex:a?Q.indexOf(a):1/0,row:{routeId:q0,credentialId:c.credentialId,credentialType:c.credentialType,...K!==void 0&&{accountIdentity:K},...d0.length&&{aliases:d0},state:c.state,label:v1.label?.trim()||l8(c),...c.email!==void 0&&{email:c.email},...c.orgName!==void 0&&{orgName:c.orgName},enabled:![c.credentialId,...d0].some((T)=>Z9(H,T,K)),addedAt:a?.addedAt??z,...a?.quota!==void 0&&{quota:a.quota},...!p.claimed&&K!==void 0&&{unclaimed:!0}}});let l0=R.at(-1);if(W&&l0)l0.previousIndex=p8(W,l0.row)}return Q.forEach((F,K)=>{if(A.has(F)||!W0(F).some(B))return;if(I.has(F.routeId))return;let[V,...P]=W0(F).filter((y)=>!Y.has(y));if(V===void 0)return;I.add(F.routeId);let{aliases:x,...k}=F;R.push({previousIndex:K,row:{...k,credentialId:V,...P.length&&{aliases:P},stale:!0}})}),R.sort((F,K)=>F.previousIndex===K.previousIndex?F.row.credentialId.localeCompare(K.row.credentialId):F.previousIndex-K.previousIndex),{version:1,view:Z.view,complete:q,...!q&&{rejected:Z.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:R.map((F)=>F.row),declined:H}}function G9($){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 _1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function W1($){return $===void 0||typeof $==="string"}function s8($){let Z=_1($)?x0($.quota):void 0;if(!_1($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!W1($.accountIdentity)||!W1($.email)||!W1($.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 n8=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function U$($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!_1(J)||!W1(J.credentialId)||typeof J.reason!=="string"||!n8.has(J.reason))return;Z.push(J)}return Z}function F$($){if(!_1($)||$.version!==1||!W1($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!U$($.rejected))throw new O("invalid-state","Claustrum roster file is not valid");let Z=[];for(let X of $.rows){let G=s8(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(!_1(X)||typeof X.credentialId!=="string"||!W1(X.accountIdentity))throw new O("invalid-state","Claustrum roster file is not valid");J.push(X)}let z=U$($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...z&&{rejected:z},rows:Z,declined:J}}function Q9($){return F$(JSON.parse(JSON.stringify($)))}async function u($){let Z;try{Z=await Z0($,_)}catch(z){if(z.code==="ENOENT")return;throw z}let J;try{J=JSON.parse(Z)}catch{throw new O("invalid-state","Claustrum roster file is not valid")}return F$(J)}var B$={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},V$={name:"claustrum-roster",ttlMs:30000};async function y0($,Z,J={}){return y3($,{...B$,signal:J.signal},async(z)=>{let X=await u($),{next:G,result:Q}=await Z(X,{assertOwned:()=>z.assertOwned()});if(G)await z.assertOwned(),await L1($,G,{beforeRename:async()=>{await J.beforePublish?.(),J.signal?.throwIfAborted(),await z.assertOwned()}});return Q})}function W9($,Z){return y0($,(J)=>{let z=J?.rows.find((G)=>G.routeId===Z);if(!J||!z)throw new O("route-unavailable","Claustrum route is not in the roster");let X=J9(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 H9($,Z){return y0($,(J)=>{let z=J?.rows.find((X)=>X.routeId===Z);if(!J||!z)throw new O("route-unavailable","Claustrum route is not in the roster");return{next:{...J,declined:z9(J.declined,W0(z),z.accountIdentity),rows:J.rows.map((X)=>X===z?{...X,enabled:!0}:X)},result:void 0}})}function i8($){return new O("invalid-order",$)}function o8($,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 Y9($,Z,J={}){return y0($,(z)=>{let X=z?.rows??[],G=o8(X,Z);if(G)throw i8(G);let Q=new Map;for(let q of X){let Y=Q.get(q.routeId);if(Y)Y.push(q);else Q.set(q.routeId,[q])}let W=[...Z],H=W.flatMap((q)=>Q.get(q)??[]);if(!z||H.every((q,Y)=>q===X[Y]))return{result:{ids:W,outcome:"unchanged"}};return{next:{...z,rows:H},result:{ids:W,outcome:"reordered"}}},{...J.signal&&{signal:J.signal}})}function r8($,Z){if(!W0($).includes(Z.credentialId))return"refuse";if($.unclaimed&&(Z.accountIdentitySource==="expected"||Z.accountIdentitySource==="none"))return"refuse";if($.accountIdentity===Z.accountIdentity)return"hold";if($.accountIdentity===void 0&&Z.expectedAccountIdentity===void 0&&Z.accountIdentity!==void 0&&(Z.accountIdentitySource==="asserted"||Z.accountIdentitySource==="parsed")&&W0($).length===1)return"bind";return"refuse"}async function U9($,Z){let{routeId:J,observation:z,...X}=Z;return j$($,{routeId:J,observation:z,accountIdentity:X.accountIdentity,receipt:X})}async function j$($,Z){if(!Q1(Z.observation))return!1;let J=o($,await u($));if(!_0(J,Z).kept)return!1;return D$($,Z)}function q9($,Z){return j$($,Z)}function _0($,Z){let J=$?.rows.find((Q)=>Q.routeId===Z.routeId),z=!J?"refuse":Z.receipt?r8(J,Z.receipt):J.accountIdentity!==void 0&&J.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!J||z==="refuse")return{roster:$,kept:!1};let X=A1(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 e1=new Map;function R1($){e1.delete(I1($))}function M$($,Z){let J=I1($);if(Z instanceof O)return Z.kind==="roster-busy";if(Z instanceof P0||Z instanceof V0)return I1(Z.details.target)===J;if(Z instanceof m){let z=I1(Z.path);return[B$.name,V$.name].some((X)=>{let G=t0(J,X);return z===G||z.startsWith(`${G}.`)})}return!1}var t8=4;async function q$($){try{let{dev:Z,ino:J,size:z,mtimeMs:X}=await c8($);return{dev:Z,ino:J,size:z,mtimeMs:X}}catch{return}}function e8($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function $6($,Z,J){for(let z=0;z<t8;z++){let X=await q$($),G=await u($),Q,W,H;try{({target:Q,local:W}=Z(G));let q=JSON.stringify(J(Q));H=JSON.stringify(Q)!==q||W!==void 0&&JSON.stringify(W)!==q}catch{return"commit"}if(!e8(X,await q$($)))continue;if(H)return"commit";return N$($)?"commit":"unchanged"}return"commit"}async function S1($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){R1($.path);return}let J=await j0({...V$,path:$.path,renew:!0});if(!J){let Q=await u($.path);if($.signal?.throwIfAborted(),!Q?.view)throw new O("roster-busy","Claustrum account discovery is already in progress");return Q}let z=I1($.path),X=$.listedOver,G;try{let Q=await u($.path),W=X?void 0:e1.get(z);G=W&&(W.previousView===Q?.view||W.inventory.view===Q?.view)?W:{inventory:await $.custody.discover($.signal),previousView:Q?.view},e1.delete(z);let{inventory:H}=G;$.onInventory?.(H),$.signal?.throwIfAborted();let q=typeof $.projection==="function"?$.projection():$.projection,Y=(B)=>K$(B,H,q),U=async()=>{return $.signal?.throwIfAborted(),await J.assertOwned(),Z()};if(await $6($.path,(B)=>{if(X)return{target:B};let L=o($.path,B);return{target:B,...L!==B&&{local:L}}},Y)==="unchanged"){if(!await U())return;return await u($.path)}return await y0($.path,async(B)=>{if(!await Z())return{result:void 0};if($.signal?.throwIfAborted(),await J.assertOwned(),X&&B?.view!==X.view&&B?.view!==H.view)return{result:B};let L=Y(B);return{...JSON.stringify(B)!==JSON.stringify(L)&&{next:L},result:L}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await J.assertOwned()}})}catch(Q){if(Q instanceof P0&&G&&!X&&!$.signal?.aborted&&await Z())e1.set(z,G);throw Q}finally{await J.release($.signal)}}var g0=new Map,Z6=Q0("claustrum"),P$=100;function C$($,Z=r3){let J=Z3($),z=g0.get(J);if(!z)z={path:J,pending:new Map,listeners:new Set,wake:new Set,abort:new AbortController,clock:Z,failures:0,draining:!1,order:0},g0.set(J,z);return z}function O$($,Z,J){let z=C$($,J);z.listeners.add(Z);let X;return()=>X??=(()=>{return z.listeners.delete(Z),z.listeners.size?Promise.resolve():K9($)})()}function J6($){return H$($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function D$($,Z){if(!Q1(Z.observation))return Promise.resolve(!1);let J=C$($),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 J6(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 I$(J,P$),Promise.resolve(!0)}function A$($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,J)=>Z.order-J.order)}function o($,Z){let J=g0.get(Z3($));if(J)for(let z of A$(J.pending)){if(z.priorReading)Z=_0(Z,z.priorReading).roster;Z=_0(Z,z.publication).roster}return Z}function N$($){return!!g0.get(Z3($))?.pending.size}function I$($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let J=$.draining?0:($.committedAt??-1/0)+o3-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,J),()=>{return $.timer=void 0,_$($)}),!$.draining)$.timer.unref?.()}function L$($){$.timer?.cancel(),$.timer=void 0}function _$($){if($.running||$.abort.signal.aborted)return $.running??Promise.resolve();let Z=new Map([...$.pending].map(([J,z])=>[J,new Map(z)]));return $.running=(async()=>{try{if(await y0($.path,(z)=>{let X=z;for(let Q of A$(Z)){if(Q.priorReading)X=_0(X,Q.priorReading).roster;X=_0(X,Q.publication).roster}let G=JSON.stringify(X)!==JSON.stringify(z);return{...G&&{next:X},result:G}},{signal:$.abort.signal}))$.committedAt=$.clock.now();for(let[z,X]of Z){let G=$.pending.get(z);for(let[Q,W]of X)if(G?.get(Q)===W)G.delete(Q);if(!G?.size)$.pending.delete(z)}$.failures=0}catch(J){if(!$.abort.signal.aborted&&$.failures++===0)Z6.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()):P$;I$($,J)}})(),$.running}async function K9($,Z=1000){let J=Z3($),z=g0.get(J);if(!z)return;z.draining=!0,L$(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)_$(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(),L$(z),z.pending.clear(),g0.get(J)===z)g0.delete(J)}}}var J3=1e4;function R$(){return new r}var F9;function k$($,Z){if(!F9)throw Error("ClaustrumConsumer is not initialized");return F9($,Z)}function S$(){return new O("not-active","Claustrum scoped custody is not active")}class B9{#$;#Z=new AbortController;#J;#W;#G;#Q;#X;#z;#D;#H;#Y=!1;#K=new Set;#V;#U;#j;#M;#L=new Map;#_;#C;#q;#N;#A=new WeakMap;static{F9=($,Z)=>{let J=new B9(Z);return J.#q=$,{consumer:J,hooks:J.#w()}}}constructor($){this.#$=$,this.#J=$.logger??Q0("claustrum"),this.#W=$1(this.#J,this.#Z.signal),this.#C=O$($.rosterPath,(Z)=>{this.#z=_0(this.#z,Z).roster})}#F($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#P($){return this.#K.add($),$.then(()=>this.#K.delete($),()=>this.#K.delete($)),$}async#O(){return await this.#$.isCustodyActive?.()??!0}#I($,Z){let J=k0([this.#Z.signal,...Z?[Z]:[]]);return new Promise((z,X)=>{let G=()=>{J.signal.removeEventListener("abort",Q),J.dispose()},Q=()=>{G(),X(J.signal.reason)};if(J.signal.addEventListener("abort",Q,{once:!0}),$.then((W)=>{if(G(),J.signal.aborted)X(J.signal.reason);else z(W)},(W)=>{G(),X(W)}),J.signal.aborted)Q()})}async#k(){if(this.#F(),this.#G)return this.#G;if(!this.#Q){let $={timedOut:!1};this.#Q=this.#B($),this.#P(this.#Q)}return this.#I(this.#Q)}#B($){let Z=this.#$.setTimeoutImpl??setTimeout,J=this.#$.clearTimeoutImpl??clearTimeout,z=this.#$.connect().then((Q)=>{if(this.#Z.signal.aborted||$.timedOut){if(Q.close(),!$.timedOut)this.#F();throw R$()}if(this.#G=new J1({client:Q,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#J,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&Q.insula)this.#U=k3(Q.insula,this.#$.tokenPath);return this.#G}),X,G=new Promise((Q,W)=>{X=Z(()=>{if($.timedOut=!0,this.#Z.signal.aborted)return;this.#J.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:this.#R()}),W(R$())},this.#R()),X.unref?.()});return Promise.race([z,G]).finally(()=>{if(X)J(X);this.#Q=void 0})}#R(){return this.#$.connectTimeoutMs??J3}snapshot(){return this.#z}grantReach(){if(this.#q)return this.#q.grantReach(this.#z?.view);let $=this.#D;return $&&this.#z?.view===$.view?$.reach:void 0}watchState(){if(this.#q)return Object.freeze({vault:this.#q.watchMode()});return Object.freeze({vault:this.#j?.mode??"polling",...this.#$.insula&&{insula:this.#U?.source.watchMode()??"polling"}})}#S(){this.#j?.close(),this.#j=void 0,this.#M?.(),this.#M=void 0}keptReceiptState(){if(this.#q){let $=this.#N;return $&&this.#q.leaseLive($)?$.custody.keptReceiptState():this.#q.keptReceiptState()}return this.#G?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return G9(this.#z)}refresh(){if(this.#F(),this.#q)return this.#P(this.#y(this.#q));if(this.#X)return this.#X;return this.#X=(async()=>{if(!await this.#O()){if(this.#z=void 0,this.#D=void 0,this.#S(),this.#G)this.#G.close(),this.#P(this.#G.dispose(this.#W));this.#G=void 0,this.#U?.release(),this.#U=void 0;return}let $=await this.#k(),Z,J=await S1({path:this.#$.rosterPath,custody:$,onInventory:(X)=>{Z=X},isActive:()=>this.#O(),signal:this.#Z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#F();let z=J?.view!==this.#z?.view;if(this.#z=o(this.#$.rosterPath,J),$.retain(J?.rows??[]),Z&&J?.view!==void 0)this.#D=Z.grantReach?{view:J.view,reach:Z.grantReach}:void 0;if(J&&z)this.#$.onRoster?.(J);return this.#_=(this.#$.now??Date.now)(),J})().finally(()=>{this.#X=void 0}),this.#P(this.#X),this.#T(this.#X),this.#X}#T($){try{this.#$.onDiscovery?.($)}catch(Z){this.#$.onError?.(Z)}}start(){if(this.#Y)return;if(this.#F(),this.#Y=!0,this.#q){this.#q.start();return}let $=async()=>{try{if(await this.#x())await this.refresh();await this.refreshInsulaQuota(),this.#b()}catch(J){if(!this.#Z.signal.aborted)this.#$.onError?.(J)}if(this.#Z.signal.aborted)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#H=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#H=void 0,this.#P($())},Z),this.#H.unref?.()};this.#P($())}async#x(){if(this.#j?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#_===void 0||$-this.#_>=a0)return!0;return!await this.#O()}#b(){let $=this.#G;if(this.#Z.signal.aborted||!$)return;if(this.#j??=$.watchRoster({view:()=>this.#z?.view,onView:()=>this.#P((async()=>{while(this.#X)await this.#X.catch(()=>{});if(this.#Z.signal.aborted)return;await this.refresh()})()),onRefused:(Z)=>this.#$.onError?.(Z),onError:(Z)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(Z)}}),this.#$.insula&&this.#U&&!this.#M)this.#M=this.#U.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#O())return;try{await O0(this.#$.tokenPath),await this.#k(),await this.#U?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#O())return;try{return await O0(this.#$.tokenPath),this.#f($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#O())return;try{await O0(this.#$.tokenPath);let J=o(this.#$.rosterPath,await u(this.#$.rosterPath))?.rows.find((z)=>z.routeId===$);return this.#f(J?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute($){let Z=this.#$.insula;if(!Z||this.#Z.signal.aborted||!await this.#O())return{miss:"unreachable"};try{await O0(this.#$.tokenPath);let z=o(this.#$.rosterPath,await u(this.#$.rosterPath))?.rows.find((Q)=>Q.routeId===$)?.accountIdentity;if(!z||!this.#U)return{miss:"unreachable"};let X=this.#U.source.lookup(Z.provider,z,(this.#$.now??Date.now)()),G=X.reading&&Z.normalize(X.reading.entry,X.reading.context);if(X.miss)return{miss:X.miss,...G!==void 0&&{reading:G}};return G===void 0?{miss:"unreachable"}:{reading:G}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute($,Z){let J=await this.lookupInsulaQuotaForRoute($);if(J.miss==="cold"||J.miss==="upstream-failed"){if(this.#L.get($)!==J.miss)this.#L.set($,J.miss),this.#J.warn("skipped insula provider poll",{reason:J.miss});return}return this.#L.delete($),J.miss?Z():J.reading}#f($){if(!this.#$.insula||!$)return;let Z=this.#U?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){if(this.#q)return this.#g(this.#q,$,Z);this.#F(Z);let J=this.#z??await this.#I(this.refresh(),Z);if(!J||!await this.#O())throw this.#G?.close(),this.#G=void 0,this.#S(),this.#U?.release(),this.#U=void 0,new O("not-active","Claustrum scoped custody is not active");let z=o(this.#$.rosterPath,await u(this.#$.rosterPath));this.#F(Z);let X=J.rows.find((H)=>H.routeId===$),G=z?.rows.find((H)=>H.routeId===$);if(G&&!G.enabled){if(X)this.#G?.forget(X.credentialId);throw new O("route-declined","Claustrum route is disabled")}if(!X||!G||G.state!=="active"||G.credentialId!==X.credentialId||G.accountIdentity!==X.accountIdentity||G.credentialType!==X.credentialType){if(X)this.#G?.forget(X.credentialId);throw new O("route-unavailable","Claustrum route is disabled, removed or changed")}let Q=await this.#I(this.#k(),Z),W=k0([this.#Z.signal,...Z?[Z]:[]]);try{return await Q.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},W.signal,$)}finally{W.dispose()}}#w(){return{discovery:($)=>{let Z=this.#q;if(!Z||!this.#$.onDiscovery||this.#Z.signal.aborted)return;let J=this.#P($.then((z)=>this.#v(Z,z)));this.#T(J)},install:($)=>{if(this.#Z.signal.aborted)return;let Z=$.view!==this.#z?.view;if(this.#z=o(this.#$.rosterPath,$),Z)try{this.#$.onRoster?.($)}catch(J){this.#$.onError?.(J)}},reset:()=>{this.#z=void 0},roster:()=>this.#z,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()}),onError:($)=>{if(!this.#Z.signal.aborted)this.#$.onError?.($)}}}async#y($){let Z=await $.refresh();return this.#v($,Z)}#v($,Z){if(this.#F(),!Z)return;if(Z.errors.has($.provider))throw Z.errors.get($.provider);return this.#z}#E($){if($&&this.#N!==$)return;this.#N?.release(),this.#N=void 0}async#u($,Z){let J=this.#N;if(J&&$.leaseLive(J))return J;this.#E();let z=await $.acquire(Z);if(this.#Z.signal.aborted)z.release(),this.#F();let X=this.#N;if(X&&$.leaseLive(X))return z.release(),X;return this.#N=z,z}async#g($,Z,J){if(this.#F(J),!this.#z)await this.#I($.refresh(),J);let z=this.#z;if(!await $.readAuthority())throw this.#E(),S$();if(this.#F(J),!z)throw new O("route-unavailable","Claustrum has no roster for this provider yet");let X=o(this.#$.rosterPath,await u(this.#$.rosterPath));this.#F(J);let G=z.rows.find((q)=>q.routeId===Z),Q=X?.rows.find((q)=>q.routeId===Z);if(Q&&!Q.enabled){if(G)$.forget(G.credentialId);throw new O("route-declined","Claustrum route is disabled")}if(!G||!Q||Q.state!=="active"||Q.credentialId!==G.credentialId||Q.accountIdentity!==G.accountIdentity||Q.credentialType!==G.credentialType){if(G)$.forget(G.credentialId);throw new O("route-unavailable","Claustrum route is disabled, removed or changed")}let W={credentialId:Q.credentialId,credentialType:Q.credentialType,...Q.accountIdentity!==void 0&&{accountIdentity:Q.accountIdentity}},H=k0([this.#Z.signal,...J?[J]:[]]);try{for(let q=0;;q++){let Y=await this.#u($,H.signal);try{let U=await Y.custody.authorize(W,H.signal,Z);return this.#A.set(U,Y),U}catch(U){if(q>0||H.signal.aborted||$.leaseLive(Y)||!(U instanceof O)||U.kind!=="closed")throw U;if(this.#E(Y),!await $.readAuthority())throw S$()}}}finally{H.dispose()}}async reportFailure($,Z,J){if(this.#F(),this.#q){let z=this.#A.get($);if(!z)throw new O("no-receipt","Claustrum dispatch receipt has no active owner");await z.custody.reportFailure($,Z,J);return}if(!this.#G)throw new O("no-receipt","Claustrum dispatch receipt has no active owner");await this.#G.reportFailure($,Z,J)}async send($,Z,J){let z=J.signal,X=await this.authorize($,z),G=await Z(X,z);if(G.status===401&&X.fromKeptReceipt)return await this.reportFailure(X,401,J.reporterSource??"direct"),G;if(G.status===401&&!z?.aborted){let Q;try{Q=await this.authorize($,z),z?.throwIfAborted()}catch(W){if(z?.aborted)throw W}if(i3(J.site,X,Q,this.#J))await G.body?.cancel().catch(()=>{}),X=Q,G=await Z(Q,z)}if(G.status===401)await this.reportFailure(X,401,J.reporterSource??"direct").catch((Q)=>this.#$.onError?.(Q)),Promise.resolve().then(()=>this.refresh()).catch((Q)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(Q)});return G}async decline($){if(this.#F(),await W9(this.#$.rosterPath,$),this.#z=o(this.#$.rosterPath,await u(this.#$.rosterPath)),this.#z)this.#q?.publishRoster(this.#z);if(this.#q)this.#q.retainUnion();else this.#G?.retain(this.#z?.rows??[])}async accept($){if(this.#F(),await H9(this.#$.rosterPath,$),this.#z=o(this.#$.rosterPath,await u(this.#$.rosterPath)),this.#z)this.#q?.publishRoster(this.#z)}async reorder($){this.#F();let Z=await Y9(this.#$.rosterPath,$);if(this.#z=o(this.#$.rosterPath,await u(this.#$.rosterPath)),this.#z)this.#q?.publishRoster(this.#z);return Z}async recordQuota($,Z,J){return this.#F(),U9(this.#$.rosterPath,{routeId:$,observation:Z,credentialId:J.credentialId,accountIdentitySource:J.accountIdentitySource,...J.accountIdentity!==void 0&&{accountIdentity:J.accountIdentity},...J.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:J.expectedAccountIdentity}})}async recordAccountQuota($,Z,J){return this.#F(),q9(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:J})}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new O("closed","Claustrum consumer is closed")),this.#H)(this.#$.clearTimeoutImpl??clearTimeout)(this.#H);if(this.#H=void 0,this.#S(),this.#G)this.#G.close(),this.#P(this.#G.dispose(this.#W));this.#N?.release(),this.#N=void 0,this.#q?.detach(),this.#U?.release(),this.#U=void 0,this.#z=void 0,this.#D=void 0,this.#C(),R1(this.#$.rosterPath)}async dispose(){this.close(),this.#V??=Promise.all([Z1(this.#K,this.#W),this.#C()]).then(()=>{}),await this.#V}}import{createHash as z6}from"node:crypto";import{channel as X6}from"node:diagnostics_channel";import{readdir as G6,stat as Q6}from"node:fs/promises";import{dirname as W6,join as H1,resolve as T$}from"node:path";var z3=new Map,H6=/^[a-z0-9][a-z0-9._-]{0,63}$/,Y6=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,U6=/^[0-9a-f]{16}$/,E$=3;function j9($,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=j9($[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=j9($[G],J);if(Q===void 0)return;z.push(`${JSON.stringify(G)}:${Q}`)}return`{${z.join(",")}}`}function q6($,Z){let J=j9({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??$3,mapAccount:$.mapAccount?String($.mapAccount):null});if(J===void 0)throw new O("invalid-state","Claustrum hub classifierInput must be plain JSON");return z6("sha256").update(J).digest("hex").slice(0,16)}function b$($,Z){if(typeof $!=="string"||!H6.test($)||Y6.test($))throw new O("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function R0($="Claustrum custody lease is closed"){return new O("closed",$)}function V9(){return new O("not-active","Claustrum scoped custody is not active")}function f$(){return new r}function K6($,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 x$($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class y${#$;#Z;#J;#W=new AbortController;#G=new Map;#Q=new WeakMap;#X=0;#z;#D;#H;#Y;#K;#V;#U=0;#j;#M;#L;#_=!1;#C=new Set;#q;#N;#A;constructor($){if(!$.family||!("classify"in $.family))throw new O("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=b$($.hostGeneration,"host generation"),J=$.members.map((X)=>b$(X,"member"));if(new Set(J).size!==J.length)throw new O("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??Q0("claustrum"),this.#J=$1(this.#Z,this.#W.signal),this.#N=H1($.stateDir,"rosters",Z),this.#A=q6($,J);let z=H1(this.#N,this.#A);for(let X of J)this.#G.set(X,{provider:X,path:H1(z,`${X}.json`),closed:!1})}#F($){return this.#C.add($),$.then(()=>this.#C.delete($),()=>this.#C.delete($)),$}#P(){if(this.#W.signal.aborted)throw R0("Claustrum discovery hub is closed")}#O($){let Z=this.#G.get($);if(!Z)throw new O("wrong-consumer","Claustrum hub has no such member");return Z}rosterPath($){return this.#O($).path}member($,Z){this.#P();let J=this.#O($);if(J.hooks)throw new O("wrong-consumer","Claustrum hub member was already built");for(let U of["rosterPath","tokenPath","family","connect","isCustodyActive","insula","pollIntervalMs","routePrefix","mapAccount"])if(U in Z)throw new O("wrong-consumer",`Claustrum hub members cannot take ${U}`);let z={provider:J.provider,start:()=>this.start(),refresh:()=>this.#g(),readAuthority:()=>this.#y(),acquire:(U)=>this.acquire(U),leaseLive:(U)=>this.#R(U),grantReach:(U)=>U!==void 0&&this.#j?.view===U?this.#j.reach:void 0,watchMode:()=>this.watchState(),keptReceiptState:()=>this.keptReceiptState(),retainUnion:()=>this.#m(),publishRoster:(U)=>this.#I(J,U),forget:(U)=>this.#z?.custody?.forget(U),detach:()=>{J.closed=!0,J.releaseRoster?.()}},X={rosterPath:J.path,...Z.reservedRouteIds&&{reservedRouteIds:Z.reservedRouteIds},...this.#$.routePrefix!==void 0&&{routePrefix:this.#$.routePrefix},...this.#$.mapAccount&&{mapAccount:this.#$.mapAccount},...Z.onRoster&&{onRoster:Z.onRoster},...Z.onDiscovery&&{onDiscovery:Z.onDiscovery},...Z.onError&&{onError:Z.onError},logger:Z.logger??this.#Z,...this.#$.now&&{now:this.#$.now}},{consumer:G,hooks:Q}=k$(z,X);J.hooks=Q;let W=T$(J.path),H=z3.get(W)??new Set,q=(U)=>{if(J.closed||this.#V!==!0||!this.#z||!this.#B(this.#z)||!Q.roster()||this.#c(Q,U))return;if(J.seen=JSON.stringify(Q9(U)),Q.install(U),U.view!==this.#j?.view)J.pending??={failures:0,wait:0};this.#m()};H.add(q),J.receiveRoster=q,z3.set(W,H);let Y=!0;return J.releaseRoster=()=>{if(!Y)return;if(Y=!1,H.delete(q),!H.size)z3.delete(W)},G}#I($,Z){let J=this.#z;if($.closed||!J||!this.#B(J))return;$.seen=JSON.stringify(Q9(Z)),$.hooks?.install(Z);for(let z of z3.get(T$($.path))??[]){if(!this.#B(J))return;if(z!==$.receiveRoster)z(Z)}}#k(){let $={id:++this.#X,count:0,ended:!1,controller:new AbortController};return this.#z=$,$}#B($){return!$.ended&&this.#z===$&&!this.#W.signal.aborted}#R($){let Z=this.#Q.get($);return!!Z&&!Z.released&&!Z.generation.ended}#S($,Z=R0()){if($.ended)return;if($.ended=!0,$.count=0,this.#z===$)this.#z=void 0;if(this.#H&&this.#Q.get(this.#H)?.generation===$)this.#H=void 0;if(this.#Y?.generation===$)this.#Y.watch.close(),this.#Y=void 0;if($.controller.abort(Z),$.custody)$.custody.close(),this.#F($.custody.dispose(this.#J))}#T($){if($.ended)return;if($.count--,$.count<=0)this.#S($)}#x($){let Z=this.#D;if(Z?.generation===$&&Z.promise)return Z.promise;let J={generation:$,timedOut:!1},z=this.#$.connectTimeoutMs??J3,X,G=this.#$.connect().then((H)=>{if(J.timedOut)throw H.close(),f$();if(!this.#B($)||$.count<=0)throw H.close(),R0("Claustrum connection is no longer wanted");return $.custody=new J1({client:H,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Z,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),$.custody}),Q=new Promise((H,q)=>{X=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(J.timedOut=!0,!this.#B($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:z}),q(f$())},z),X.unref?.()});return J.promise=this.#F(Promise.race([G,Q]).finally(()=>{if(X)(this.#$.clearTimeoutImpl??clearTimeout)(X)})),J.promise.finally(()=>{if(this.#D===J)this.#D=void 0}).catch(()=>{}),this.#D=J,J.promise}acquire($){try{if(this.#P(),$?.throwIfAborted(),this.#V===!1)throw V9()}catch(J){return Promise.reject(J)}let Z=this.#z??this.#k();return Z.count++,this.#b(Z,$,!0)}async#b($,Z,J){let z=$.custody;if(!z){let X=k0([$.controller.signal,...Z?[Z]:[]]);try{z=await K6(this.#x($),X.signal)}catch(G){if(!$.ended)throw this.#T($),G;return this.#f(Z,J)}finally{X.dispose()}}if($.ended)return this.#f(Z,J);if(Z?.aborted)throw this.#T($),Z.reason;return this.#w($,z)}#f($,Z){if($?.throwIfAborted(),this.#P(),this.#V===!1)throw V9();if(!Z)throw R0();let J=this.#z??this.#k();return J.count++,this.#b(J,$,!1)}#w($,Z){let J={generation:$,custody:Z,released:!1},z=()=>{if(J.released||$.ended)throw R0()},X=Object.freeze({authorize:async(Q,W,H)=>{z();let q=k0([$.controller.signal,...W?[W]:[]]);try{return await Z.authorize(Q,q.signal,H)}finally{q.dispose()}},reportFailure:async(Q,W,H)=>{return z(),Z.reportFailure(Q,W,H)},forget:(Q)=>{z(),Z.forget(Q)},keptReceiptState:()=>{return z(),Z.keptReceiptState()}}),G=Object.freeze({custody:X,generation:$.id,release:()=>{if(J.released)return;J.released=!0,this.#T($)}});return this.#Q.set(G,J),G}leaseState(){let $=this.#z;return Object.freeze({generation:$?.id,count:$?.count??0})}async#y(){let $=await this.#$.isCustodyActive?.()??!0;if(this.#W.signal.aborted)return!1;let Z=this.#V;if(this.#V=$,!$&&Z!==!1)this.#v();return $}#v(){this.#U++;let $=this.#z;if($)this.#S($,V9());this.#H=void 0,this.#Y?.watch.close(),this.#Y=void 0,this.#j=void 0,this.#M=void 0;for(let Z of this.#G.values())Z.seen=void 0,Z.pending=void 0,Z.hooks?.reset(),R1(Z.path)}#E(){return[...this.#G.values()].filter(($)=>$.hooks&&!$.closed)}async#u(){let $=this.#H,Z=$&&this.#Q.get($);if($&&Z&&this.#R($))return Z;this.#H=void 0;let J=await this.acquire(this.#W.signal),z=this.#H&&this.#Q.get(this.#H);if(this.#H&&z&&this.#R(this.#H))return J.release(),z;this.#H=J;let X=this.#Q.get(J);if(!X)throw R0();return X}#g(){try{this.#P()}catch(z){return Promise.reject(z)}let $=this.#K;if($&&!$.generation?.ended)return $.promise;let Z={},J=this.#F(this.#n(Z).finally(()=>{if(this.#K===Z)this.#K=void 0}));Z.promise=J,this.#K=Z;for(let z of this.#E())z.hooks?.discovery(J);return J}async#n($){if(!await this.#y())return;let Z=await this.#u(),J=Z.generation;if($.generation=J,!this.#B(J))return;let z=await this.#o().then(()=>{return},(Y)=>Y instanceof Error?Y:Error(String(Y))),X=new Map(await Promise.all([...this.#G.values()].map(async(Y)=>[Y,await u(Y.path).then((U)=>U?{file:U}:{},(U)=>U instanceof Error?U:Error(String(U)))])));if(!this.#B(J))return;let G;try{G=await Z.custody.discover(J.controller.signal)}catch(Y){if(!this.#B(J))return;for(let U of this.#G.values())if(U.pending)this.#h(U);throw Y}if(!this.#B(J))return;let Q=this.#E(),W=await Promise.all(Q.map((Y)=>Y.hooks&&!Y.closed?this.#i(Y,Y.hooks,G,z??X.get(Y),J):void 0));if(!this.#B(J))return;let H=new Map,q=!0;for(let[Y,U]of Q.entries()){let M=U.hooks,B=W[Y];if(!M||!B)continue;if("error"in B){let{error:C}=B;if(q=!1,this.#h(U),M$(U.path,C))this.#Z.debug("claustrum hub member commit refused",{member:U.provider});else H.set(U.provider,C);continue}let{roster:L}=B;if(!this.#B(J))return;if(L?.view!==G.view)q=!1,this.#h(U);else U.pending=void 0;if(!L)continue;if(this.#c(M,L)){q=!1,this.#h(U);continue}this.#I(U,L)}if(!this.#B(J))return;if(this.#m(),q)this.#j=Object.freeze({view:G.view,...G.grantReach&&{reach:G.grantReach},refused:Object.freeze([...G.refused??[]]),notMine:G.notMine??0});return this.#M=(this.#$.now??Date.now)(),{errors:H}}async#i($,Z,J,z,X){let G={...J,credentials:J.credentials.filter((Q)=>Q.member===$.provider),skipped:J.skipped.filter((Q)=>Q.member===$.provider)};try{if(!z)throw R0("Claustrum hub member has no base view");if(z instanceof Error)throw z;let Q;if(!z.file){let H=X6("common-auth.claustrum.phases");if(H.hasSubscribers)H.publish({logger:this.#Z,phase:`seed read ${$.provider} begin`});try{Q=await this.#r($)}finally{if(H.hasSubscribers)H.publish({logger:this.#Z,phase:`seed read ${$.provider} end`})}}return{roster:await S1({path:$.path,custody:{discover:async()=>G},isActive:()=>this.#B(X)&&this.#V===!0,signal:X.controller.signal,projection:()=>({...Z.projection(),...Q&&{seed:Q}}),listedOver:{view:z.file?.view}})}}catch(Q){return{error:Q}}}async#o(){for(let $ of[W6(this.#N),this.#N,H1(this.#N,this.#A)])await e0($,{},"roster directory")}async#r($){let Z=`${$.provider}.json`,J=[H1(this.#N,Z)];try{for(let X of await G6(this.#N))if(X!==this.#A&&U6.test(X))J.push(H1(this.#N,X,Z))}catch{}let z;for(let X of J)try{let G=(await Q6(X)).mtimeMs,Q=await u(X);if(Q&&(!z||G>z.modified))z={modified:G,roster:Q}}catch{}return z&&X9(z.roster)}#c($,Z){let J=$.projection().reservedRouteIds;return!!J?.size&&Z.rows.some((z)=>J.has(z.routeId))}#h($){let Z=($.pending?.failures??0)+1,J=Math.max(1,this.#$.pollIntervalMs??5000),z=Math.max(1,Math.ceil(a0/J)),X=Z<=E$?1:Math.min(2**(Z-E$),z);$.pending={failures:Z,wait:X-1}}#m(){let $=this.#z?.custody;if(!$)return;$.retain(this.#E().flatMap((Z)=>Z.hooks?.roster()?.rows??[]))}async#t(){let $=this.#U;for(let Z of this.#E()){let J;try{J=await u(Z.path)}catch(W){Z.hooks?.onError(W);continue}if($!==this.#U||this.#V!==!0)return;let z=Z.hooks;if(!J||!z||Z.closed)continue;let X=JSON.stringify(J);if(X===Z.seen)continue;let G=z.roster();if(!G||G.view!==J.view||this.#c(z,J)){Z.pending??={failures:0,wait:0};continue}let Q=x$(G);if(Z.seen=X,this.#I(Z,J),x$(z.roster())!==Q)this.#m()}}#e(){let $=!1;for(let J of this.#G.values()){if(!J.pending)continue;if(J.pending.wait<=0)$=!0;else J.pending.wait--}if(this.#Y?.watch.mode!=="watching"||$)return!0;let Z=(this.#$.now??Date.now)();return this.#M===void 0||Z-this.#M>=a0}#$0(){let $=this.#H,Z=$&&this.#Q.get($);if(!$||!Z||!this.#R($)||this.#V!==!0)return;let J=Z.generation;if(!this.#B(J)||this.#Y?.generation===J)return;let z=Z.custody.watchRoster({view:()=>this.#j?.view,onView:()=>this.#F((async()=>{while(this.#K)await this.#K.promise.catch(()=>{});if(!this.#B(J))return;await this.#a()})()),onRefused:(X)=>this.#d(X),onError:(X)=>this.#p(X)});this.#Y={generation:J,watch:z}}#p($){if(!this.#W.signal.aborted)this.#$.onError?.($)}#d($){if(this.#W.signal.aborted)return;this.#$.onError?.($);for(let Z of this.#E())Z.hooks?.onError($)}#l($){for(let[Z,J]of $?.errors??[])this.#G.get(Z)?.hooks?.onError(J)}async#a(){let $;try{$=await this.#g()}catch(Z){this.#d(Z);return}this.#l($)}async#s(){try{if(await this.#y()){if(await this.#t(),this.#e())await this.#a();this.#$0()}}catch(Z){this.#p(Z)}if(this.#W.signal.aborted)return;let $=this.#$.pollIntervalMs??5000;if($<=0)return;this.#L=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#L=void 0,this.#F(this.#s())},$),this.#L.unref?.()}start(){if(this.#_)return;this.#P(),this.#_=!0,this.#F(this.#s())}async refresh(){this.#l(await this.#g())}refusals(){let $=this.#j;return $&&Object.freeze({view:$.view,refused:$.refused,notMine:$.notMine})}grantReach(){return this.#j?.reach}watchState(){let $=this.#Y;return $&&this.#B($.generation)?$.watch.mode:"polling"}keptReceiptState(){return this.#z?.custody?.keptReceiptState()??Object.freeze({active:!1,since:null})}close(){if(this.#W.signal.aborted)return;this.#W.abort(R0("Claustrum discovery hub is closed"));for(let Z of this.#G.values())Z.releaseRoster?.();if(this.#L)(this.#$.clearTimeoutImpl??clearTimeout)(this.#L);this.#L=void 0;let $=this.#z;if($)this.#S($);this.#H=void 0,this.#Y?.watch.close(),this.#Y=void 0}async dispose(){this.close(),this.#q??=Z1(this.#C,this.#J),await this.#q}}var h0={opencode:V6,pi:j6};function M9($,Z){let{tokenPath:J}=g$($,Z);return{stateDir:B6(J),host:$,override:J}}function D9($,Z){return M6($==="pi"?Z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0,$==="pi"?{...Z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:Z)}class v0 extends Error{code;constructor($){super($==="permission-refused"?"Native vault setup: permission-refused. Could not grant this host read access to native Claude accounts. An older ck may refuse a grant that already exists. Update CortexKit tools and run setup again.":`Native vault setup: ${$}`);this.code=$;this.name="NativeVaultEnrollmentError"}}function N9($,Z){let J=Z??h0[$];if(typeof J!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(J))throw new v0("permission-refused");return["auth","grant","--principal",`enrolled:${J}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"]}async function v$($,Z){try{await Z.processFence();let J=await i1(Z.paths??g$($,Z.env),h0[$]);if(J.state==="blocked")throw new v0("permission-refused");let z=J.state==="approved"?J.approvedName:void 0,X=N9($,z);if((await Z.runner.run(Z.ckBinary??"ck",X,{env:Z.env})).exitCode!==0)throw new v0("permission-refused");return z}catch{throw new v0("permission-refused")}}import{createHash as A6}from"node:crypto";import{lstat as I6,mkdir as _6,readFile as n$}from"node:fs/promises";import{dirname as R6}from"node:path";import{assertHostsStopped as S6,canonicalPath as P9,createNativeAccountRuntime as k6,custodyTombstoneOAuth as T6,inspectNativeHostAuthEntry as i$,NativeMigrationError as m0,nativeJournalMayAdoptLaterHostLogin as E6,nativePoolHoldsAccountData as b6,prepareNativeMigration as f6,readNativeEnrollmentMode as o$,readNativeMigrationJournal as x6,releaseNativeMigrationPreflight as y6,requireNoSupervisedAuthContentSnapshot as g6,runNativeMigration as v6,writeNativeHostAuth as h6}from"@cortexkit/anthropic-auth-core";import{dirname as D6,join as h$,resolve as L9}from"node:path";import{ACCOUNT_FILE_NAME as m$,ACCOUNT_STATE_FILE_NAME as N6,canonicalPath as w$,getStickyRoutingStatePath as L6,resolveLocalRoutingDestination as P6,resolveNativePoolPaths as C6}from"@cortexkit/anthropic-auth-core";async function M0($,Z){let J=$==="pi"?p$(Z):u$(Z),z=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),X=L9(z||h$(J,m$)),G=L9(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(X.endsWith(m$)?h$(D6(X),N6):`${X}.state.json`)),Q=await C6(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"?d$(Z):c$(Z),routingSourcePath:L9(W||L6(X)),routingDestinationPath:P6($,Q,Z)}}async function l$($){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 w$(G);if(z.has(Q)&&!(X===9&&Q===await w$(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 a$=new WeakMap;function s$($){return typeof $==="object"&&$!==null?a$.get($):void 0}function Y1($){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 n extends Error{constructor($){super($);this.name="SetupRefusal",a$.set(this,$)}}var C9="OpenCode's separate Anthropic login is not used. Add that account through /claude Accounts if needed, or remove the separate login from OpenCode.";function r$($){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 O9($,Z){let J=[];for(let z of $)if(await o$(z,Z)!=="local")J.push(r$(z));if(J.length)throw new n(J.join(`
|
|
13
|
-
`))}function
|
|
2
|
+
import{B as _3}from"./index-qqs4ec18.js";import{D as V7,E as j7,F as i$,G as o$,H as r$,I as t$,J as M7}from"./index-a0jxsmac.js";import{la as J7,ma as dZ,na as g3}from"./index-n8xr16kr.js";var Z2=dZ((aq,e4)=>{var $2={to($,Z){if(!Z)return`\x1B[${$+1}G`;return`\x1B[${Z+1};${$+1}H`},move($,Z){let J="";if($<0)J+=`\x1B[${-$}D`;else if($>0)J+=`\x1B[${$}C`;if(Z<0)J+=`\x1B[${-Z}A`;else if(Z>0)J+=`\x1B[${Z}B`;return J},up:($=1)=>`\x1B[${$}A`,down:($=1)=>`\x1B[${$}B`,forward:($=1)=>`\x1B[${$}C`,backward:($=1)=>`\x1B[${$}D`,nextLine:($=1)=>"\x1B[E".repeat($),prevLine:($=1)=>"\x1B[F".repeat($),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},lZ={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},aZ={screen:"\x1B[2J",up:($=1)=>"\x1B[1J".repeat($),down:($=1)=>"\x1B[J".repeat($),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines($){let Z="";for(let J=0;J<$;J++)Z+=this.line+(J<$-1?$2.up():"");if($)Z+=$2.left;return Z}};e4.exports={cursor:$2,scroll:lZ,erase:aZ,beep:"\x07"}});import{stdin as xJ,stdout as yJ}from"node:process";import{createInterface as gJ}from"node:readline/promises";import{authorize as vJ,createNativeAccountRuntime as hJ,decideOpenCodeStateLayoutOnce as mJ,exchange as wJ,formatNativeAccountState as uJ,generateRelayToken as cJ,getAccountStoragePath as pJ,isValidApiBaseURL as dJ,readNativeEnrollmentMode as lJ,resolveNativePoolPaths as aJ,WORKER_SCRIPT as sJ}from"@cortexkit/anthropic-auth-core";import{randomUUID as Q5}from"node:crypto";import{constants as U3}from"node:fs";import{lstat as W5,mkdir as H5,open as Y5}from"node:fs/promises";import{homedir as U5}from"node:os";import{isAbsolute as q5,join as B4}from"node:path";import{types as m9}from"node:util";import{anthropicAuthStateRoot as K5,createProviderErrorRedactor as V4,createWindowsOwnerOnly as F5,ensureWindowsOwnerOnlyDirectory as B5,formatLogLine as V5,HOLDER_REGISTRATION_ERROR_MESSAGES as j5,isOwnerOnly as M5,isSecretKey as D5,isStateLayoutRefusalCode as N5,NativeMigrationError as L5,NativePiAuthSlotError as P5,PRIVATE_FILES_UNAVAILABLE_MESSAGE as j4,RELOCATED_MESSAGE as C5,STATE_LAYOUT_REFUSAL_CODES as O5,STATE_LAYOUT_REFUSAL_PUBLIC_MESSAGES as A5,setupEnrollment as _5,stateLayoutRefusalPublicMessage as I5}from"@cortexkit/anthropic-auth-core";import{readFile as i6}from"node:fs/promises";import{assertHostsStopped as o6,createNativeAccountRuntime as r6,discoverNativeVaultInventory as t6,inspectNativeHostAuthEntry as f9,NativePiAuthSlotError as e6,nativePiAuthSlotPaths as $5,openNativePiAuthSlot as y9,readNativeEnrollmentMode as Z5,requireNoSupervisedAuthContentSnapshot as J5}from"@cortexkit/anthropic-auth-core";import{dirname as A6}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as _6,CLAUSTRUM_PI_ENROLLMENT_NAME as I6,getHostClaustrumEnrollmentPaths as d$,resolveClaustrumConnectionPath as R6}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as sQ}from"@cortexkit/claustrum-client";import{ClaustrumClient as IQ}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as O7}from"@cortexkit/claustrum-client";import{SocketClosedError as A7,SocketTimeoutError as _7,SubcCallError as I7}from"@cortexkit/subc-client";class A extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var E3=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class t extends A{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function L0($){if($ instanceof t||$ instanceof A7||$ instanceof _7)return"unreachable";let Z=$ instanceof O7||$ instanceof I7?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(E3,Z))return"answered";return E3[Z]}import{resolve as F2}from"node:path";import{storeIdentity as Kz}from"@cortexkit/claustrum-client";import{SubcClient as Bz}from"@cortexkit/subc-client";var s0=300000,p1=300000,b3=1000;class C1{#$;#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 d1{#$;#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 l1{#$;#Z=new C1;#X;#Q="polling";#G;#W;#z=!1;#J;#V=!1;#H=0;constructor($){this.#$=$,this.#X=new d1(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.#Y("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()}#Y($,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.#Y("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.#Y("polling",$?"resubscribing":"opening");let G=z;X.closed.then((Q)=>this.#q(G,Q),(Q)=>this.#q(G,{kind:"transport_lost",error:Q}))}#q($,Z){if(this.#z||this.#G!==$)return;if(this.#G=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#Y("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#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.#H=0;let z=Math.min(1000*2**Math.min(this.#H,16),300000);this.#H++,this.#Y("polling","resubscribing"),this.#U(z,()=>void this.#F(!0));return}this.#B(Z.kind)}#B($){this.#Y("fallback",$),this.#U(300000,()=>void this.#F(!1))}}var s1=60000,B2=4*s1,R7=2*s1,f3=new Map,a1=new Map;function n0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function S7($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!n0(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 T7($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class V2{transport;key;#$=[];#Z=!1;#X=new Set;#Q=new Map;#G=new d1(async()=>{try{let $=await this.transport.getUsage();if(!n0($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>n0(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 C1;#z="polling";#J=0;#V=0;#H=new Map;#Y;#U;#F={};#q=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 a1)if($-z>=s1)a1.delete(J);let Z=a1.get(this.key);if(Z!==void 0&&$-Z<s1)return Promise.resolve();return a1.set(this.key,$),this.#G.request()}watchMode(){return this.#z}watch($={}){this.#J++;let Z=$.provider;if(Z===void 0)this.#V++;else this.#H.set(Z,(this.#H.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.#H.get(Z)??1)-1;if(z>0)this.#H.set(Z,z);else this.#H.delete(Z)}if(--this.#J===0)this.#B()}}#B(){if(this.#U)(this.#F.clearTimeoutImpl??clearTimeout)(this.#U);this.#U=void 0;let $=this.#Y;this.#Y=void 0,$?.handle?.stop(),this.#z="polling"}#D($){this.#U=(this.#F.setTimeoutImpl??setTimeout)(()=>{if(this.#U=void 0,this.#J>0&&!this.#Y)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.#Y=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.#Y!==$)return;if($.notices++,$.notices===1)this.#z="watching";if($.notices===2)this.#q=0;let J=S7(Z);if(!J)this.#W.restart();if(!(J?this.#W.continuous(J):!1)||J?.provider===void 0||this.#V>0||this.#H.has(J.provider))this.#G.request()}#O($,Z){if(this.#Y!==$)return;this.#Y=void 0;let J=T7(Z);if(J==="unknown_method"||J==="usage_watch_limit"){this.#z="fallback";return}if($.notices>0){let z=Math.min(b3*2**Math.min(this.#q,16),p1);this.#q++,this.#z="polling",this.#D(z);return}if(this.#z="fallback",this.#G.request(),Z===void 0||L0(Z)==="unreachable")this.#D(p1)}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||!n0(z.usage))continue;let X=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(X)||J-X>=B2)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(!n0(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&&(!n0(z.stale)||z.stale.class!=="local_source_unavailable"))return{miss:"upstream-failed",reading:W};return J>=Q+B2||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>=R7?"unreachable":"cold"}}}function x3($,Z){let J=JSON.stringify([F2($.connectionFile),F2(Z)]),z=f3.get(J);if(!z)z={source:new V2($,J),refs:0},f3.set(J,z);z.refs++;let X=!1;return{source:z.source,release(){if(X)return;if(X=!0,--z.refs===0)f3.delete(J)}}}import{ClaustrumCredentialError as EQ}from"@cortexkit/claustrum-client";import{appendFileSync as c7,chmodSync as p7,existsSync as h3,renameSync as I2,statSync as d7}from"node:fs";import{open as l7}from"node:fs/promises";import{dirname as a7,resolve as s7}from"node:path";import{randomUUID as N2}from"node:crypto";import{lstat as L2,readFile as P2,rename as k7,unlink as j2}from"node:fs/promises";import{tmpdir as E7}from"node:os";import{dirname as P0,join as b7,resolve as e}from"node:path";var _=process.platform==="win32",M2=new Set;function y3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var D2;var C2="native-addon-unavailable";function O2($){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:$}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:C2})}function f7($,Z){return Z instanceof $.PrivateFilesUnavailableError||Z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function x7($){try{await $.verifyPrivatePath(b7(E7(),`.common-auth-private-files-probe-${N2()}`),"file")}catch(Z){if(f7($,Z))throw O2(Z)}}function i0(){return D2??=import("@cortexkit/private-files").then(async($)=>{if(_)await x7($);return $},($)=>{throw _?O2($):$}),D2}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}: ${$} (${C2}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`:`Private file refused at ${Z}: ${$} (${z?.reason??z?.code??"io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`,{cause:J});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=y3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}function n1($){return _&&$ instanceof w&&$.reason==="io-error"&&($.win32Code===32||$.win32Code===303)}async function o($,Z,J){try{return await J()}catch(z){if(z instanceof w)throw z;throw new w($,Z,z)}}var y7;async function B0($,Z){$=e($),Z??=y7,await o($,"safe-parent",async()=>{let J=await(await i0()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await L2($);throw new w(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function a($,Z,J=!1){if($=e($),Z==="directory")return B0($);await o($,"verify",async()=>{let z=await i0(),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 B0(P0($)),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&&!M2.has($))M2.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function W0($,Z=!1,J){$=e($),await o($,"directory",async()=>{let z=await i0();try{return await L2($),await B0($,J)}catch(G){if(y3(G)!=="ENOENT")throw G}let X=P0($);if(X===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await W0(X,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(y3(G)!=="EEXIST")throw G}await B0($,J)})}async function z0($,Z=!1){if(!_)return P2($,"utf8");return(await g7($,Z)).toString("utf8")}async function g7($,Z=!1){if(!_)return P2($);if($=e($),Z)await B0(P0($)),await a($,"file",!0);return o($,"read",async()=>(await i0()).readOwnerOnly($))}async function o0($,Z){await B0(P0(e($))),await o($,"create",async()=>{await(await i0()).createPrivateFile(e($),Z)})}async function A2($){await B0(P0(e($))),await o($,"directory-create",async()=>{await(await i0()).createOwnerOnly(e($),{kind:"dir"})})}async function v3($,Z,J={}){$=e($),Z=e(Z);let z=J.now??(()=>performance.now()),X=z(),G=J.deadline??1/0,Q,W=[0,10,20,40,80,100],H,q=0;for(let U of W){let D=Math.min(Q??1/0,G);if(z()>=D)break;if(U)await(J.sleep??((L)=>new Promise((C)=>setTimeout(C,L))))(Math.min(U,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;q++;try{return await(J.rename??k7)($,Z),{attempts:q,elapsedMs:z()-X}}catch(L){H??=L;let C=L;if(!(C.win32Code!==void 0?C.win32Code===32||C.win32Code===33:["EBUSY","EPERM","EACCES"].includes(C.code??"")&&!C.reason))break;Q??=z()+500}}let Y=new w(Z,"rename",H??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw Y.attempts=q,Y.elapsedMs=z()-X,Y}async function r0($,Z,J={}){$=e($),await W0(P0($));try{await a($,"file",!0)}catch(q){if(q.code!=="ENOENT")throw q}let z=e(J.stagePath??`${$}.${N2()}.tmp`);if(P0(z)!==P0($))throw new w($,"stage-directory",{code:"EXDEV"});let X=!1,G=!1,Q={attempts:0,elapsedMs:0},W="stage-create",H=(q)=>{try{J.onOutcome?.({path:$,stage:q?.stage??"published",published:G,fileDurable:G,durabilityConfirmed:!1,attempts:q?.attempts??Q.attempts,elapsedMs:q?.elapsedMs??Q.elapsedMs,...q&&{code:q.code,win32Code:q.win32Code}})}catch{}};try{if(await o0(z,Z),X=!0,W="before-rename",Q=await v3(z,$,J),X=!1,G=!0,W="published-callback",J.onRenamed?.(),W="published-verify",await a($,"file"),J.durable&&J.durability!=="file-only-on-windows")throw new w($,"directory-sync-unsupported",{code:"ENOTSUP"});H()}catch(q){let Y=q instanceof w?q:new w($,W,q);if(Y.published=G,Y.fileDurable=G,G)Object.assign(Y,Q);if(X){try{await j2(z)}catch{Y.orphanPath=z}X=!1}throw H(Y),Y}finally{if(X)await j2(z).catch(()=>{})}}var v7=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,h7=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function m7($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function t0($={}){let Z=[h7,...$.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 v7.test(G)||Q.includes("apikey")||Q.endsWith("secret")||Q.endsWith("password")||Q.endsWith("token")&&!Q.endsWith("tokens")||!!$.extraSecretKeys?.(Q)}function z(G){let Q=G,W=[["name",G.name],["message",G.message],["stack",G.stack]];for(let q of["code","status","cause"])if(Q[q]!==void 0)W.push([q,Q[q]]);let H=new Set(W.map(([q])=>q));for(let q of Object.entries(G))if(!H.has(q[0]))W.push(q);return W}function X(G,Q,W,H=0){if(typeof G==="string")return Z.reduce((q,Y)=>q.replace(Y,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if(W.has(G))return"[Circular]";W.add(G);try{if(Array.isArray(G))return G.map((U)=>X(U,Q,W,H));let q=m7(G);if(q&&H>=8)return"[Truncated]";let Y=q?H+1:H;return Object.fromEntries((q?z(G):Object.entries(G)).map(([U,D])=>[U,Q&&J(U)?"***REDACTED***":X(D,Q,W,Y)]))}finally{W.delete(G)}}return{redact:(G)=>X(G,!0,new WeakSet),redactStrings:(G)=>X(G,!1,new WeakSet)}}var _2=t0(),w7=_2.redact,u7=_2.redactStrings;var i1={error:0,warn:1,info:2,debug:3,trace:4},S2=5242880,T2=3;function m3($){try{p7($,384)}catch{}}function n7($){try{if(!(h3($)&&d7($).size>=S2))return;for(let J=T2-1;J>=1;J--)if(h3(`${$}.${J}`)){let z=`${$}.${J+1}`;I2(`${$}.${J}`,z),m3(z)}let Z=`${$}.1`;I2($,Z),m3(Z)}catch{}}async function V0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await o(Z,"log-close",()=>J.close())}async function R2($,Z){await W0(a7(Z));try{await a(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await o0(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await a(Z,"file",!0)}}return $.handle=await o(Z,"log-open",()=>l7(Z,"a")),$.file=Z,$.handle}async function i7($,Z,J){Z=s7(Z);try{if($.file!==Z)await V0($);let z=$.handle??await R2($,Z);if((await o(Z,"log-stat",()=>z.stat())).size>=S2){await V0($);for(let G=T2-1;G>=0;G--){let Q=G===0?Z:`${Z}.${G}`,W=`${Z}.${G+1}`;try{await a(Q,"file",!0)}catch(H){if(H.code==="ENOENT")continue;throw H}try{await a(W,"file",!0)}catch(H){if(H.code!=="ENOENT")throw H}await v3(Q,W),await a(W,"file")}z=await R2($,Z)}await o(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await V0($).catch(()=>{}),z}}function o7($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function r7($){let Z,J,z,X=t0(),G,Q=[],W,H=Promise.resolve(),q,Y={};function U(F){let K=H.then(F);return H=K.catch((j)=>{q=j}),K}function D(F){if(_&&F.file!==Z)U(()=>V0(Y)).catch(()=>{});Z=F.file,J=F.level,X=t0(F),G=F.captureSink}function B(F){if(F===void 0||F in i1)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 i1)return F;return"info"}function O(F=!0){if(W)clearTimeout(W),W=void 0;if(!Q.length){if(_)return U(async()=>{if(F)await V0(Y);if(q)throw q});return}let K;try{K=L()}catch{if(Q=[],_&&F)return U(()=>V0(Y));return}let j=Q.join("");if(Q=[],!K){if(_&&F)return U(()=>V0(Y));return}if(_)return U(async()=>{try{await i7(Y,K,j)}finally{if(F)await V0(Y)}});try{if(n7(K),h3(K))m3(K);c7(K,j,{encoding:"utf8",mode:384})}catch{}}function I(){if(!W)W=setTimeout(()=>{W=void 0;let F=O(!1);if(F instanceof Promise)F.catch(()=>{})},500)}function T(F,K,j,P){if(Z===void 0&&G===void 0)return;try{if(i1[K]>i1[C()])return;let g=X.redactStrings(j),E;try{E=X.redact(P)}catch{E="[unserializable]"}let v=`[${new Date().toISOString()}] ${K.toUpperCase()} [${F}] ${g}`+(P===void 0?"":o7(E))+`
|
|
3
|
+
`;try{G?.({channel:F,level:K,message:g,data:E})}catch{}if(Z===void 0)return;if(Q.push(v),Q.length>=50){let Z0=O(!1);if(Z0 instanceof Promise)Z0.catch(()=>{})}else I()}catch{}}function m(F){return{error:(K,j)=>T(F,"error",K,j),warn:(K,j)=>T(F,"warn",K,j),info:(K,j)=>T(F,"info",K,j),debug:(K,j)=>T(F,"debug",K,j),trace:(K,j)=>T(F,"trace",K,j)}}function u(){if(_)U(()=>V0(Y)).catch(()=>{});if(q=void 0,Q=[],W)clearTimeout(W),W=void 0;Z=void 0,J=void 0,z=void 0,X=t0(),G=void 0}if($)D($);return{configure:D,createLogger:m,setLogLevel:B,flushLogs:O,reset:u}}var t7=r7();function H0($){return t7.createLogger($)}function k0($){let Z=new AbortController,J=[],z=!1,X=()=>{if(z)return;z=!0;for(let{source:W,listener:H}of J)W.removeEventListener("abort",H);J.length=0},G=(W)=>{if(z||Z.signal.aborted)return;Z.abort(W),X()},Q=$.find((W)=>W.aborted);if(Q)return Z.abort(Q.reason),{signal:Z.signal,dispose:X};for(let W of $){if(Z.signal.aborted)break;let H=()=>G(W.reason);if(J.push({source:W,listener:H}),W.addEventListener("abort",H,{once:!0}),W.aborted)G(W.reason)}return{signal:Z.signal,dispose:X}}import{channel as T8}from"node:diagnostics_channel";import{ClaustrumCredentialError as Q$}from"@cortexkit/claustrum-client";import{createHash as B8,randomBytes as V8,randomUUID as j8}from"node:crypto";import{constants as c2}from"node:fs";import{chmod as M8,mkdir as D8,open as a2,readFile as p3,realpath as N8,rename as L8,stat as s2,unlink as l3}from"node:fs/promises";import{basename as P8,dirname as b0,extname as DX,isAbsolute as NX,join as C8,resolve as LX}from"node:path";import{ClaustrumCredentialError as O8,ClaustrumClient as CX,writeEnrollmentTokenFile as A8}from"@cortexkit/claustrum-client";import{lstat as e7}from"node:fs/promises";import{resolve as $8}from"node:path";async function Z8($){try{let Z=await e7($);return Z.isFile()?Z:void 0}catch(Z){return Z.code==="ENOENT"?"absent":void 0}}function J8($,Z){if($==="absent"||Z==="absent")return $===Z;return $.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs&&$.ctimeMs===Z.ctimeMs}class O1{#$=new Map;async read($,Z,J){let z=$.map((q)=>$8(q)),X=JSON.stringify(z),G=await Promise.all(z.map(Z8)),Q=G.every((q)=>q!==void 0)?G:void 0,W=this.#$.get(X);if(Q&&W&&Q.every((q,Y)=>{let U=W.identities[Y];return U!==void 0&&J8(q,U)}))return J?.(Q),W.value;this.#$.delete(X);let H=await Z(z);if(Q){if(this.#$.size>=64){let q=this.#$.keys().next().value;if(q!==void 0)this.#$.delete(q)}this.#$.set(X,{identities:Q,value:H})}return H}}import{randomUUID as k2}from"node:crypto";import{mkdir as z8,open as E2,rename as X8,rm as G8}from"node:fs/promises";import{dirname as b2}from"node:path";class o1 extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function e0($,Z,J={}){await f2($,Z,J)}async function f2($,Z,J,z){if(_)return r0($,J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
4
|
+
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??k2)()}.tmp`,onRenamed:z,durable:J.durable,durability:J.durability,onOutcome:J.onOutcome});await z8(b2($),{recursive:!0});let X=`${$}.${(J.stageName??k2)()}.tmp`,G,Q=!1;try{if(G=await E2(X,"wx",384),Q=!0,await G.writeFile(J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
5
|
+
`,"utf8"),await G.chmod(384),J.durable)try{await G.sync()}catch(W){throw new o1(W)}if(await G.close(),G=void 0,await J.beforeRename?.(),await X8(X,$),Q=!1,z?.(),J.durable){let W=await E2(b2($),"r");try{await W.sync()}catch(H){throw new o1(H)}finally{await W.close()}}}finally{if(await G?.close().catch(()=>{}),Q)await G8(X,{force:!0}).catch(()=>{})}}var Q8=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 r1}from"node:crypto";import{lstat as Z1,mkdir as x2,open as w2,readFile as y2,rename as g2,rm as _1,stat as A1}from"node:fs/promises";import{dirname as u3,join as v2}from"node:path";import{join as W8,resolve as H8}from"node:path";function $1($,Z){return`${$}.${Z}.lock`}class C0 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class j0 extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}function Y8($,Z,J){if(!n1($)||$.stage!=="read"&&$.stage!=="verify")return!1;let z=H8($1(Z,J));return $.path===z||$.path===W8(z,"owner.json")}async function w3($,Z,J){let z=performance.now();for(;;){Z.signal?.throwIfAborted();let X,G;try{X=await M0({path:$,name:Z.name,ttlMs:Z.ttlMs,renew:Z.renew??!1,...Z.onStep?{onStep:Z.onStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}})}catch(W){if(!Y8(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 C0({target:$,name:Z.name,timeoutMs:Z.timeoutMs})}await new Promise((W)=>setTimeout(W,Math.min(25,Math.ceil(Q))))}}async function h2($,Z){let J=await w2($,"wx",384),z;try{z=await J.stat()}catch{z=void 0}try{await J.writeFile(Z,"utf8")}catch(X){try{let G=await Z1($).catch(()=>{return});if(z&&G&&G.dev===z.dev&&G.ino===z.ino)await _1($,{force:!0}).catch(()=>{})}catch{}throw X}finally{await J.close()}}var U8=globalThis.setTimeout.bind(globalThis),q8=globalThis.clearTimeout.bind(globalThis);function u2($){let Z=$?.code;return Z==="ENOENT"||!_&&(Z==="EINVAL"||Z==="ENOTDIR")}var m2;function c3($,Z){if($.dev!==Z.dev||$.ino!==Z.ino)return!1;if($.ino===0&&$.birthtimeMs!==Z.birthtimeMs)return!1;return!0}var K8=1000;function M0($){return F8({...$,now:Date.now})}async function F8($){let Z=$1($.path,$.name),J=v2(Z,"owner.json"),z=r1(),X=$.now??Date.now,G=null,Q=!1,W=!1,H,q,Y=new Promise((V)=>{q=V});function U(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;q8(G),G=null,U("cancelled")}function B(V,M){if(H||Q)return;H=Object.freeze({reason:V,expectedOwnerId:z,...typeof M?.ownerId==="string"?{observedOwnerId:M.ownerId}:{},...typeof M?.expiresAt==="number"?{observedExpiresAt:M.expiresAt}:{}}),D(),q(H)}let L,C=null,O=`${Z}.evicting`,I=v2(O,"owner.json"),T=r1(),m=5000,u=8;async function F(){if(_)try{return JSON.parse(await z0(Z,!0))}catch(V){if(V.code!=="EISDIR"&&V.reason!=="wrong-kind")throw V;return await a(Z,"directory",!0),JSON.parse(await z0(J,!0))}try{return JSON.parse(await y2(Z,"utf8"))}catch(V){if(V.code!=="EISDIR")throw V;return JSON.parse(await y2(J,"utf8"))}}async function K(){if(_){let R=await F(),S=Number(R?.expiresAt)-X();await r0(Z,`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
6
|
+
`,{deadline:performance.now()+Math.max(0,S),beforeRename:async()=>{let h=await F();if(h?.ownerId!==z||!(Number(h?.expiresAt)>X())||!await p())throw new j0({target:$.path,name:$.name})}});return}let V=`${Z}.${r1()}.tmp`,M,N=!1;try{M=await w2(V,"wx",384),N=!0,await M.writeFile(`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
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 p())throw new j0({target:$.path,name:$.name});await g2(V,Z),N=!1}finally{if(await M?.close().catch(()=>{}),N)await _1(V,{force:!0}).catch(()=>{})}}async function j(){let V=`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
8
|
+
`;if(_)await o0(Z,V);else await h2(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 a(Z,"directory",!0),await z0(J,!0);else await F()}catch(N){if(N.code!=="ENOENT")throw N}}return!0}async function g(){if(_)await W0(u3(Z));try{return await j(),!0}catch(V){let M=V.code;if(await P(V))return!1;if(M==="ENOENT"){if(_)await W0(u3(Z));else await x2(u3(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 A1(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 Z0(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 p(){try{return JSON.parse(await z0(I,_))?.ownerId===T}catch(V){if(_&&V.code!=="ENOENT")throw V;return!1}}async function d(V){if(_)await o(V,"remove",()=>_1(V,{recursive:!0,force:!0}));else await _1(V,{recursive:!0,force:!0}).catch(()=>{})}function l(V,M){if(!_||!(V instanceof w)||V.stage!=="remove"||V.path!==M)return!1;return n1(V)||V.win32Code===void 0&&V.reason===void 0&&(V.code==="EBUSY"||V.code==="EPERM")}async function J0(V,M,N=performance.now()+m+1000){let R,S=5;while(await M()){try{await d(V);return}catch(a0){if(!l(a0,V))throw a0;R??=a0}let h=N-performance.now();if(h<=0)throw R;if(await new Promise((a0)=>setTimeout(a0,Math.min(S,h))),performance.now()>=N)throw R;S=Math.min(S*2,50)}}async function L1(V){let M;await J0(O,async()=>{if(!_)return p();let N=await Z1(O).catch((R)=>{if(R.code!=="ENOENT")throw R;return});if(!N||M&&!c3(M,N))return!1;if(await p())return M=N,!0;if(!M)return!1;try{return await A1(I),!1}catch(R){if(R.code!=="ENOENT")throw R;return!0}},V)}async function P1(V,M){if(!V)return!1;let N=!1;try{await J0(O,async()=>{N=!1;let R=await Z1(O).catch(()=>{return});if(!R||!c3(V,R))return!1;N=!0;try{return await A1(I),!1}catch(S){return S.code==="ENOENT"}},M)}catch{}return N}async function c1(V){if(_)await A2(O);else await x2(O);let M;try{let N=await Z1(O);M={dev:N.dev,ino:N.ino,birthtimeMs:N.birthtimeMs}}catch{M=void 0}try{await m2?.beforeOwnerWrite?.(O,I);let N=await m2?.failOwnerWrite?.(O,I);if(N!==void 0)throw N;let R=`${JSON.stringify({ownerId:T,createdAt:X()})}
|
|
9
|
+
`;if(_)await o0(I,R);else await h2(I,R)}catch(N){let R=await P1(M,V);if(u2(N)&&!R)return!1;try{await L1(V)}catch{}throw N}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function l0(V){let M;try{M=await A1(O)}catch(S){if(S.code==="ENOENT")return"missing";throw S}if(_)try{await a(O,"directory",!0)}catch(S){if(S.code==="ENOENT")return"missing";throw S}if(M.mtimeMs+m>X()){let S=!0;try{await A1(I)}catch(h){if(h.code==="ENOENT")S=!1;else return"fresh"}if(S)return"fresh";if(M.mtimeMs+K8>X())return"fresh"}if($.onStep)await $.onStep("stale-marker-stat");let N=`${O}.${r1()}`;try{await g2(O,N)}catch(S){if(S.code==="ENOENT")return"missing";throw S}if($.onStep)await $.onStep("stale-marker-claimed");let R=_?await Z1(N):void 0;return await J0(N,async()=>{if(!R)return!0;let S=await Z1(N).catch((h)=>{if(h.code!=="ENOENT")throw h;return});return!!S&&c3(R,S)},V),"recovered"}async function b(V,M){try{if(!await c1(M))return!1}catch(S){if(S.code==="EEXIST"){if(_)try{await a(O,"directory",!0),await z0(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 L1(M)}catch(S){if(l(R,Z)&&l(S,O))throw R;throw S}if(N)throw R;return!0}async function F0(){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 _1(Z,{recursive:!0,force:!0});return}catch(N){if(_)throw N;await E()}}}function Y2(){if(!$.renew||Q||H)return;let V=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=U8(()=>{G=null;let M=(async()=>{let N=!Q;try{if(!await b(async()=>{let S=await F(),h=X();if(Q||H){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||H){N=!1;return}if(!await p())return;if($.onStep)await $.onStep("renewal-write-fenced");if(Q||H){N=!1;return}if(!await p())return;if($.onStep)await $.onStep("renewal-write-ready");if(Q||H){N=!1;return}if(await K(),$.onStep)await $.onStep("renewal-write-finished");if(!await p()){B("marker-lost"),N=!1,await F0();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&&!H)Y2()}})();C=M,M.finally(()=>{if(C===M)C=null})},V),"unref"in G)G.unref();U("scheduled")}function U2(){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 T0=await g();if(!T0)for(let V=0;V<u;V++){if(T0=await g(),T0)break;let M=await v();if(M.status==="live")return U2();if(M.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await c1()){await E();continue}}catch(N){if(N.code!=="EEXIST")throw N;if(await l0()==="fresh")return null;await E();continue}try{let N=await v();if(N.status==="live")return U2();if(!Z0(M.identity,N))continue;if(!await p())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await p())return null;let R=await v(!1);if(!Z0(M.identity,R))continue;if(await d(Z),!await p())return null;if($.onStep)await $.onStep("stale-lock-removed");if(T0=await g(),!T0)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await p())return await F0(),T0=!1,null;break}finally{await L1()}}if(!T0)return null;return Y2(),{ownerId:z,whenLost:()=>Y,hasLost:()=>H!==void 0,assertOwned:async()=>{if(L)throw L;let V;try{let M=await F();if(V=M,!Q&&!H&&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 j0({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 q2;try{q2=await F()}catch(K2){if(_&&K2.code==="ENOENT"){h=!0;return}throw K2}if(q2?.ownerId!==z){h=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await p())return;await d(Z),h=!0},M)){if(_&&!h)throw new w(Z,"release-not-confirmed",{code:"EIO"});W=h;return}if(V?.aborted)return;await l0(M)}catch(h){if(!l(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"})}}}var _8=1,e1=16384,n2=30000,a3=/^[0-9a-f]{64}$/,i2="unknown_method",o2=new Set([i2,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),r2=new Set(["pending_queue_full"]);function d3($){if(!($ instanceof O8))return;if(o2.has($.code))return{code:$.code,disposition:"terminal"};if(r2.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function t2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function t1($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function e2($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function I1(){return new A("invalid-state","invalid Claustrum enrollment state")}function s3($){if(!t2($)||$.version!==_8||typeof $.proposedName!=="string"||$.proposedName.length===0)throw I1();if($.phase==="pending"){if(!a3.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!t1($.createdAt)||!t1($.updatedAt))throw I1();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)||!e2($.tokenGeneration)||!t1($.updatedAt))throw I1();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"||!t1($.updatedAt))throw I1();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw I1()}function n3($){if(!t2($)||!a3.test(String($.token??""))||!e2($.token_generation))throw new A("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function $$($){if(!$.isFile())throw new A("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new A("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new A("unsafe-file","Claustrum enrollment file must be owned by the current user")}function p2($){try{return JSON.parse($)}catch{throw new A("invalid-state","Claustrum enrollment file is not valid JSON")}}async function f0($){if(_)try{await W0(b0($));let J=await z0($,!0);if(Buffer.byteLength(J)>e1)throw new A("unsafe-file","Claustrum enrollment file is too large");return p2(J)}catch(J){if(J.code==="ENOENT")return;throw J}let Z;try{Z=await a2($,c2.O_RDONLY|c2.O_NOFOLLOW)}catch(J){if(J.code==="ENOENT")return;throw new A("unsafe-file","Claustrum enrollment file could not be opened safely")}try{$$(await Z.stat());let J=Buffer.alloc(e1+1),{bytesRead:z}=await Z.read(J,0,J.byteLength,0);if(z>e1)throw new A("unsafe-file","Claustrum enrollment file is too large");return p2(J.subarray(0,z).toString("utf8"))}finally{await Z.close()}}function d2($,Z){let J=[];for(let z of $.split(`
|
|
10
|
+
`)){if(z.trim()===""||z.startsWith("#"))continue;let X=z.split(":");if(X.length!==Z||!/^[^\s:,]+$/.test(X[0]??"")||!/^\d+$/.test(X[2]??"")||!Number.isSafeInteger(Number(X[2]))||Z===7&&(!/^\d+$/.test(X[3]??"")||!Number.isSafeInteger(Number(X[3])))||Z===4&&X[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(X[3]??""))return;J.push(X)}return J}async function I8($,Z,J){try{let[z,X]=await Promise.all([p3(J.passwdPath??"/etc/passwd","utf8"),p3(J.groupPath??"/etc/group","utf8")]),G=d2(z,7),Q=d2(X,4);if(!G||!Q)return!1;let W=G.filter((U)=>Number(U[2])===$),H=Q.filter((U)=>Number(U[2])===Z);if(W.length!==1||H.length!==1)return!1;let q=W[0]?.[0],Y=H[0]?.[3]??"";return(Y===""||Y.split(",").every((U)=>U===q))&&!G.some((U)=>Number(U[2])!==$&&Number(U[3])===Z)}catch{return!1}}function Z$($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>p3(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function J$($,Z={}){if(!_){let J=process.geteuid?.();if(J===void 0)return;let z=process.getegid?.(),X;try{X=await N8($)}catch{return}let G;for(;;){let Q=await s2(X).catch(()=>{return});if(Q&&(Q.mode&18)!==0&&(Q.mode&512)===0){if(G===void 0)G=z!==void 0&&await I8(J,z,Z);if((Q.mode&2)!==0||Q.uid!==J||Q.gid!==z||!G)throw new A("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${X}. Another user could replace it. Run: chmod g-w,o-w ${X}`)}let W=b0(X);if(W===X)return;X=W}}try{await B0($,Z$(Z))}catch(J){if(!(J instanceof w))throw J;throw new A("unsafe-file",`Claustrum enrollment parent refused: ${J.path} (${J.reason??J.code}). Use a folder that other users cannot write or replace.`)}}async function J1($,Z={},J="enrollment directory"){if(_){await W0($,!1,Z$(Z));return}await D8($,{recursive:!0,mode:448});let z=await s2($),X=process.geteuid?.();if(X!==void 0&&z.uid!==X)throw new A("unsafe-file",`Claustrum ${J} must be owned by the current user`);if((z.mode&63)!==0)await M8($,448)}async function E0($,Z,J={}){let z=b0($);await J1(z,J),await J$(z,J);let X=`${JSON.stringify(Z)}
|
|
11
|
+
`;if(Buffer.byteLength(X)>e1)throw new A("invalid-state","Claustrum enrollment state is too large");if(_)return r0($,X);let G=C8(z,`.${P8($)}.${process.pid}.${j8()}.tmp`),Q,W=!1;try{Q=await a2(G,"wx",384),W=!0,await Q.writeFile(X,"utf8"),await Q.chmod(384),await Q.sync(),await Q.close(),Q=void 0,await L8(G,$),W=!1}finally{if(await Q?.close().catch(()=>{}),W)await l3(G).catch(()=>{})}}var R8=new O1;async function $3($,Z){let J=_?await l2($,Z):await R8.read([$.tokenPath,$.statePath],async([X=$.tokenPath,G=$.statePath])=>l2({tokenPath:X,statePath:G},Z),(X)=>{for(let G of X)if(G!=="absent")$$(G)}),z={...J.status};if(J.usesProposedName&&z.state==="approved")z.proposedName=Z;return z}async function l2($,Z){let J=await f0($.tokenPath),z=J===void 0?void 0:n3(J),X=await f0($.statePath),G=X===void 0?void 0:s3(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:O0(G),usesProposedName:!1}}async function A0($){let Z=await f0($);if(Z===void 0)throw new A("not-enrolled","Claustrum enrollment is not configured");return n3(Z)}function O0($){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 z$(){return new A("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class i3{#$;#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??(()=>V8(32).toString("hex")),this.#W=$.writeTokenFile??A8}async status(){return $3(this.#Z,this.#X)}async resetTerminal(){return X$(this.#Z,this.#X)}async#J($,Z){let J={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#Q()};return await E0(this.#Z.statePath,J,this.#z),O0(J)}async reconcile(){await J1(b0(this.#Z.statePath),this.#z);let $=await M0({name:"ceremony",path:this.#Z.statePath,ttlMs:n2,renew:!0});if(!$)return{state:"busy"};try{let Z=await f0(this.#Z.tokenPath),J=Z===void 0?void 0:n3(Z),z=await f0(this.#Z.statePath),X=z===void 0?void 0:s3(z);if(X&&X.proposedName!==this.#X)throw z$();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 E0(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 E0(this.#Z.statePath,Q,this.#z),O0(Q)}if(X&&X.phase!=="pending")return O0(X);if(!X){let Q=this.#Q();if(X={version:1,phase:"pending",proposedName:this.#X,requestSecret:this.#G(),createdAt:Q,updatedAt:Q},!a3.test(X.requestSecret))throw new A("invalid-state","invalid minted Claustrum enrollment secret");await E0(this.#Z.statePath,X,this.#z)}if(!X.requestId)try{let Q=B8("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 E0(this.#Z.statePath,X,this.#z)}catch(Q){let W=d3(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,retryCode:W.code};if(W.code===i2)return await $.assertOwned(),await l3(this.#Z.statePath).catch((H)=>{if(H.code!=="ENOENT")throw H}),{state:"unavailable",proposedName:X.proposedName,code:W.code};return this.#J(X,W.code)}let G=X.requestId;if(!G)return O0(X);try{let Q=await this.#$.enrollPoll({requestId:G,requestSecret:X.requestSecret});if(Q.status==="pending")return O0(X);if(Q.status==="denied"){let H={version:1,phase:"denied",proposedName:X.proposedName,updatedAt:this.#Q()};return await E0(this.#Z.statePath,H,this.#z),O0(H)}await J1(b0(this.#Z.tokenPath),this.#z),await J$(b0(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 E0(this.#Z.statePath,W,this.#z),O0(W)}catch(Q){let W=d3(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 X$($,Z){await J1(b0($.statePath));let J=await M0({name:"ceremony",path:$.statePath,ttlMs:n2,renew:!0});if(!J)return"busy";try{if(await f0($.tokenPath)!==void 0)return"refused-approved";let z=await f0($.statePath);if(z===void 0)return"idle";let X=s3(z);if(X.proposedName!==Z)throw z$();if(X.phase==="pending")return"refused-pending";return await J.assertOwned(),await l3($.statePath),"reset"}finally{await J.release()}}var o3="claustrum-tombstone:v1:";function z1($,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 X1($,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 S8}from"@cortexkit/claustrum-client";function G$($){return $!==null&&typeof $==="object"&&(Object.getPrototypeOf($)===Object.prototype||Object.getPrototypeOf($)===null)}class r3{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(!G$(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(!G$(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.#H(X)}}});return this.#G=$,$.finally(()=>{this.#G=void 0}),$}#H($){let Z="transport_error";try{if($ instanceof S8)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 H$($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function k8($,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 e3=H0("claustrum");function W$($){if(!/^[0-9a-f]{64}$/.test($.token)||!Number.isSafeInteger($.token_generation)||$.token_generation<1)throw new A("invalid-token","Invalid Claustrum enrollment token");return $.token}var _0=T8("common-auth.claustrum.phases");function Z9($,Z,J,z=e3){let X=H$(Z,J);return z.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:J?.recordVersion??null,retry:X,reason:k8(Z,J)}),X}var $9=300000,Y$=60000;function t3(){return new A("invalid-material","Claustrum returned invalid credential material")}function E8($){let Z=$.trim();if(Z.startsWith("{")){let J;try{J=JSON.parse(Z)}catch{throw t3()}if(!J||typeof J!=="object")throw t3();let z=J,X=z.access_token??z.access;Z=typeof X==="string"?X:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(o3))throw t3();return Z}function b8($,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=f8($),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 f8($){let Z=$;return{providerIds:Z.providerIds,authMethod:Z.authMethod}}function x8($){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 G1{#$;#Z;#X;#Q;#G;#W;#z;#J=new WeakMap;#V=new WeakMap;#H=new Map;#Y=new WeakMap;#U;#F=new Map;#q;#B;#D=!1;#C=new t;#P;#O=!1;#K=-1/0;#M=2000;#_=!1;#j;#L=new Set;#A=new Set;#R;#E;#N;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>A0(Z);else throw new A("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#Q=$.family,this.#G=$.parseIdentity,this.#W=$.requireAssertion??!1,this.#X=$.now??Date.now,this.#z=$.logger??e3,this.#R=z1(this.#z),this.#q=$.setTimeoutImpl??setTimeout,this.#B=$.clearTimeoutImpl??clearTimeout,this.#U=new r3({client:this.#$,owns:(J)=>this.#F.has(J),token:async()=>W$(await this.#Z()),logger:this.#z,setTimeout:this.#q,clearTimeout:this.#B})}transportLost($){if(this.#_||this.#D)return;this.#D=!0,this.#C=$ instanceof Q$?$:new t,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.#H.values())$.since=null;(this.#z.info??e3.info)("vault receipt serving resumed",{reason:"reachable"})}#S(){if(this.#_||!this.#D||this.#P||this.#O)return;this.#P=this.#q(()=>{this.#P=void 0,this.#k(!0)},this.#M),this.#P.unref?.()}#k($=!1){if(this.#_||!this.#D||this.#O)return;if(this.#X()-this.#K<1000){this.#S();return}this.#K=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 A("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#y($){if(this.#I($),_0.hasSubscribers)_0.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),_0.hasSubscribers)_0.publish({logger:this.#z,phase:"token read end"})}return this.#I($),W$(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),L0(X)==="unreachable")this.transportLost(X);else this.reachable();if(X instanceof Q$)throw X;if(L0(X)==="unreachable")throw new t;throw new A("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(Y){throw this.#H.clear(),this.#g(),Y}if(_0.hasSubscribers)_0.publish({logger:this.#z,phase:"list scoped begin"});try{Z=await this.#b(()=>this.#$.listScoped(J),$)}catch(Y){throw this.listFailed(Y),Y}finally{if(_0.hasSubscribers)_0.publish({logger:this.#z,phase:"list scoped end"})}let z=[],X=[],G=0,Q=[],W=new Map;for(let Y of Z.rows){let U=b8(Y,this.#Q);if(U.kind==="not-mine"){G++;continue}if(U.kind==="refused"){X.push({...Y.id.trim()&&{credentialId:Y.id},code:U.code});continue}Q.push({row:Y,type:U.type,...U.member!==void 0&&{member:U.member}}),W.set(Y.id,(W.get(Y.id)??0)+1)}let H=[];for(let{row:Y,type:U,member:D}of Q){let B;if(!Y.id.trim())B="empty credential id";else if((W.get(Y.id)??0)>1)B="duplicate credential id";else if(Y.accountId!==void 0&&!Y.accountId.trim())B="blank account identity";else if(!Y.state.trim())B="empty state";if(B){z.push({...Y.id.trim()&&{credentialId:Y.id},...D!==void 0&&{member:D},reason:B});continue}H.push(Object.freeze({credentialId:Y.id,credentialType:U,...D!==void 0&&{member:D},...Y.accountId!==void 0&&{accountIdentity:Y.accountId},state:Y.state,...Y.email!==void 0&&{email:Y.email},...Y.orgName!==void 0&&{orgName:Y.orgName}}))}for(let Y of z)this.#z.warn("skipped malformed vault record",Y);let q=x8(Z);return{view:Z.view,credentials:Object.freeze(H),skipped:Object.freeze(z),..."classify"in this.#Q&&{refused:Object.freeze(X),notMine:G},...q&&{grantReach:q}}}listFailed($){if(L0($)==="unreachable")this.transportLost($);else this.reachable(),this.#H.clear(),this.#g()}forget($){this.#H.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.#H){let X=Z.get(J);if(!X?.enabled||X.state!=="active"||X.credentialType!==z.attempt.credentialType||X.accountIdentity!==z.attempt.expectedAccountIdentity)this.forget(J)}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.#H){if(!this.#x(J.attempt)){this.forget(Z);continue}if(J.since!==null)$=Math.min($??J.since,J.since)}return Object.freeze({active:$!==null,since:$})}#x($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#X()>Y$}async authorize($,Z,J="vault"){this.#I(Z);let{credentialId:z,credentialType:X,accountIdentity:G}=$,Q=this.#H.get(z);if(Q&&(Q.attempt.credentialType!==X||Q.attempt.expectedAccountIdentity!==G))this.forget(z),Q=void 0;let W;try{W=await this.#y(Z)}catch(H){throw this.#H.clear(),this.#g(),H}if(this.#D&&Q)return this.#k(),this.#v(z,Q,W,J);try{let H=await this.#T({credentialId:z,credentialType:X,accountIdentity:G},W,Z);return this.#H.set(z,{attempt:H,routeId:J,since:null}),this.#F.set(z,{...$}),H}catch(H){if(this.#I(Z),L0(H)!=="unreachable")throw this.forget(z),H;return this.#v(z,Q,W,J,H)}}#v($,Z,J,z,X=this.#C){if(!Z||this.#H.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,J),this.#Y.set(G,z),G}async#T($,Z,J){if(!$.credentialId)throw new A("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:z,credentialType:X,accountIdentity:G}=$;if(this.#W&&G===void 0)throw new A("identity-unasserted","Claustrum dispatch requires a known account identity");let Q=await this.#b(()=>this.#$.getScoped({credentialId:z,enrollmentToken:Z,...X==="oauth"&&{minTtlMs:$9}}),J);if(Q.credentialId!==void 0&&Q.credentialId!==z)throw new A("identity-changed","Claustrum served credential identity changed");let W=Q.expiresAtMs;if(!Number.isSafeInteger(Q.recordVersion)||Q.recordVersion<0||W===null&&X==="oauth"||W!==null&&(!Number.isFinite(W)||W-this.#X()<$9))throw new A("insufficient-validity","Claustrum served credential has insufficient validity");let H=E8(Q.material),q=Q.accountId?.trim()?Q.accountId:void 0;if(this.#W&&(Q.credentialId===void 0||q===void 0))throw new A("identity-unasserted","Claustrum served credential did not assert its identity");let Y=q===void 0?this.#G?.(H):void 0,U=q??Y;if(G!==void 0&&U!==void 0&&U!==G)throw new A("identity-changed","Claustrum served credential identity changed");let D=U??G,L=Object.freeze(Object.defineProperty({credentialId:z,credentialType:X,...D!==void 0&&{accountIdentity:D},accountIdentitySource:q!==void 0?"asserted":Y!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...Q.credentialId!==void 0&&{assertedCredentialId:Q.credentialId},...q!==void 0&&{assertedAccountIdentity:q},...Q.projectId!==void 0&&{projectId:Q.projectId},recordVersion:Q.recordVersion,expiresAtMs:W},"accessToken",{value:H,enumerable:!1}));return this.#J.set(L,Z),L}async reportFailure($,Z,J){if(Z!==401)return;this.#I();let z=this.#J.get($);if(!z)throw new A("no-receipt","Claustrum failure report requires an original dispatch receipt");let X=this.#Y.get($);if(X!==void 0){this.forget($.credentialId),this.#z.debug("scoped 401 not reported",{routeId:X,reason:"kept-receipt"});return}let G=this.#H.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let Q=this.#V.get($);if(Q)return Q;let W=this.#b(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:z,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(H){throw this.#V.delete($),H}}watchRoster($){this.#I();let Z=new l1({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.#q,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.#H.clear();let $=this.#U.close();if($)this.#A.add($),$.then(()=>this.#A.delete($));else this.#$.close();this.#N=X1(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 Q3}from"node:path";var J9=30000,z9={now:()=>performance.now(),schedule($,Z){let J=setTimeout(()=>void Z(),$);return{cancel:()=>clearTimeout(J),unref:()=>J.unref?.()}}};var x0="all",y8=Object.freeze(["primary"]);function q$($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function W1($,Z){return JSON.stringify([$,Z])}function I0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function s($){return typeof $==="number"&&Number.isFinite($)}function U$($){return typeof $==="string"&&$.length>0}function n($,Z,J){return $[Z]===void 0||J($[Z])}function g8($){return s($)&&$>0}function X9($){return typeof $==="string"}function v8($){if(!I0($)||!U$($.scope)||!U$($.label))return!1;switch($.kind){case"reading":return s($.checkedAt)&&s($.usedPercent)&&n($,"resetsAt",X9)&&n($,"windowMinutes",g8);case"retired":return s($.retiredAt);case"absent":return s($.checkedAt);default:return!1}}function h8($){if(!I0($)||!s($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&n($,"remainingPercent",s)&&n($,"usedPercent",s)&&n($,"resetsAt",X9)&&n($,"limit",s)&&n($,"used",s)&&n($,"remaining",s)&&n($,"unit",X9)}function K$($){return I0($)&&s($.value)&&Number.isInteger($.value)&&$.value>=0&&s($.checkedAt)}function G9($){return I0($)&&Object.values($).every(K$)}function m8($){return typeof $==="boolean"}function H1($){return I0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&n($,"balance",s)&&n($,"overageLimitReached",m8)&&s($.checkedAt)}function F$($){if(!I0($))return;let Z=Object.entries($).filter(([,J])=>K$(J));return Z.length===0?void 0:Object.fromEntries(Z)}function y0($){if(Q1($))return $;if(!I0($))return;let{counters:Z,credits:J,...z}=$;if(!Q1(z))return;let X=F$(Z),G=H1(J)?J:void 0;return{...z,...X===void 0?{}:{counters:X},...G===void 0?{}:{credits:G}}}function Q1($){if(!I0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!v8(J))return!1;let z=W1(J.scope,J.label);if(Z.has(z))return!1;Z.add(z)}return n($,"budget",h8)&&n($,"counters",G9)&&n($,"credits",H1)}class Z3 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function z3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function J3($){return typeof $==="number"&&Number.isFinite($)}function B$($){return $===void 0||typeof $==="string"&&$!==""}function V$($){return typeof $==="string"&&$!==""}function R1($,Z){return $[Z]===void 0||J3($[Z])}function Q9($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function w8($){return z3($)&&B$($.scope)&&V$($.label)&&J3($.usedPercent)&&Q9($,"resetsAt")&&($.windowMinutes===void 0||J3($.windowMinutes)&&$.windowMinutes>0)}function u8($){return z3($)&&B$($.scope)&&V$($.label)}function c8($){if(!z3($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&R1($,"remainingPercent")&&R1($,"usedPercent")&&Q9($,"resetsAt")&&R1($,"limit")&&R1($,"used")&&R1($,"remaining")&&Q9($,"unit")}function Y1($){if(!z3($)||!J3($.checkedAt))return!1;let Z=$.readings??[],J=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(J))return!1;let z=new Set;for(let X of Z){if(!w8(X))return!1;let G=W1(X.scope??x0,X.label);if(z.has(G))return!1;z.add(G)}if(!J.every(u8))return!1;return($.budget===void 0||c8($.budget))&&($.counters===void 0||G9($.counters))&&($.credits===void 0||H1($.credits))}function p8($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function d8($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function l8($,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 a8($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function S1($,Z){let J=$===void 0?void 0:y0($);if($!==void 0&&J===void 0)throw new Z3("stored quota map is malformed");if(!Y1(Z))throw new Z3("quota observation is malformed");let z=J??{limits:[]},X=Z.checkedAt,G=new Map;for(let O of z.limits)G.set(W1(O.scope,O.label),O);let Q=(O)=>{let I=G.get(O);return I===void 0||X>=q$(I)},W=new Set;for(let O of Z.readings??[]){let I=O.scope??x0,T=W1(I,O.label);if(W.add(T),!Q(T))continue;G.set(T,{scope:I,label:O.label,kind:"reading",checkedAt:X,usedPercent:O.usedPercent,...O.resetsAt===void 0?{}:{resetsAt:O.resetsAt},...O.windowMinutes===void 0?{}:{windowMinutes:O.windowMinutes}})}for(let O of Z.coverage??[]){let I=O.scope??x0,T=W1(I,O.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:O.label,kind:"absent",checkedAt:X}:{scope:I,label:O.label,kind:"retired",retiredAt:X})}let{limits:H,budget:q,counters:Y,credits:U,...D}=z,B=d8(z.budget,Z.budget,X),L=l8(z.counters,Z.counters),C=a8(z.credits,Z.credits);return{...D,limits:[...G.values()].sort(p8),...B===void 0?{}:{budget:B},...L===void 0?{}:{counters:L},...C===void 0?{}:{credits:C}}}var s8=Object.freeze({validate:Q1,decode:y0,merge:S1});function j$($,Z=""){let J=new Map,{observation:z}=$,X=(W,H,q)=>J.set(`${Z}:${W}`,{at:H,order:0,publication:{...$,observation:q}}),G=(W,H)=>JSON.stringify([W??"all",H]),Q=new Set;for(let W of z.readings??[]){let H=G(W.scope,W.label);Q.add(H),X(H,z.checkedAt,{checkedAt:z.checkedAt,readings:[{...W}]})}for(let W of z.coverage??[]){let H=G(W.scope,W.label);if(!Q.has(H))X(H,z.checkedAt,{checkedAt:z.checkedAt,coverage:[{...W}]})}if(z.budget)X("budget",z.checkedAt,{checkedAt:z.checkedAt,budget:{...z.budget}});for(let[W,H]of Object.entries(z.counters??{}))X(`counter:${W}`,H.checkedAt,{checkedAt:z.checkedAt,counters:{[W]:{...H}}});if(z.credits)X("credits",z.credits.checkedAt,{checkedAt:z.checkedAt,credits:{...z.credits}});if(!J.size)X("empty",z.checkedAt,{checkedAt:z.checkedAt});return J}import{createHash as r8}from"node:crypto";import{stat as t8}from"node:fs/promises";import{resolve as T1}from"node:path";function M$($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function W9($,Z,J){return $.some((z)=>M$(z,Z,J))}function H9($,Z,J){let z={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((X)=>X.credentialId!==Z||X.accountIdentity!==J),z]}function Y9($,Z,J){return $.filter((z)=>!Z.some((X)=>M$(z,X,J)))}function U9($){return{declined:$.declined.map((Z)=>({...Z})),order:$.rows.flatMap((Z)=>Y0(Z).map((J)=>({credentialId:J,...Z.accountIdentity!==void 0&&{accountIdentity:Z.accountIdentity}})))}}function e8($,Z){let J=Y0(Z),z=Z.accountIdentity===void 0?-1:$.order.findIndex((G)=>G.accountIdentity===Z.accountIdentity),X=z>=0?z:$.order.findIndex((G)=>J.includes(G.credentialId));return X>=0?X:1/0}var G3="vault:";function $6($){return r8("sha256").update($).digest("hex")}function Z6($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function J6($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function Y0($){return[$.credentialId,...$.aliases??[]]}function L$($,Z,J={}){let z=J.now??Date.now(),X=J.routePrefix??G3,G=J.reservedRouteIds??new Set,Q=$?.rows??[],W=$?void 0:J.seed,H=[...$?.declined??W?.declined??[]],q=Z.skipped.length===0,Y=new Set(Z.credentials.map((F)=>F.credentialId)),U=new Set(Z.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),D=Z.skipped.some((F)=>F.credentialId===void 0),B=(F)=>!Y.has(F)&&(U.has(F)||D),L=new Map;for(let F of Q){if(F.accountIdentity===void 0)continue;for(let K of Y0(F))if(!L.has(K))L.set(K,F.accountIdentity)}let C=new Map;for(let F of Z.credentials){let K=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:L.get(F.credentialId),claimed:!1},j=J6(K),P=C.get(j)??[];P.push(K),C.set(j,P)}let O=new Set,I=new Set(G),T=[],m=(F,K)=>F.credential.credentialId.localeCompare(K.credential.credentialId),u=[...C.values()].map((F)=>F.toSorted(m)).sort((F,K)=>F[0]&&K[0]?m(F[0],K[0]):0);for(let F of u){let K=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)),Z0=Q.find((b)=>!O.has(b)&&Y0(b).some((F0)=>v.has(F0))&&(b.accountIdentity===void 0||b.accountIdentity===K)),p=E.find((b)=>b.credential.credentialId===Z0?.credentialId)??E[0];if(!p)continue;let d=p.credential,l=Z0??(K===void 0?void 0:Q.find((b)=>!O.has(b)&&b.accountIdentity===K));if(l)O.add(l);let J0=l?.routeId;if(!J0||G.has(J0)){let b=`${X}${d.credentialId}${K===void 0?"":`~${$6(K).slice(0,10)}`}`;J0=b;for(let F0=2;I.has(J0);F0++)J0=`${b}~${F0}`}I.add(J0);let L1=l?Y0(l).filter(B):[],P1=[...new Set([...F.map((b)=>b.credential.credentialId),...L1])].filter((b)=>b!==d.credentialId).sort((b,F0)=>b.localeCompare(F0)),c1=J.mapAccount?.(d)??{};T.push({previousIndex:l?Q.indexOf(l):1/0,row:{routeId:J0,credentialId:d.credentialId,credentialType:d.credentialType,...K!==void 0&&{accountIdentity:K},...P1.length&&{aliases:P1},state:d.state,label:c1.label?.trim()||Z6(d),...d.email!==void 0&&{email:d.email},...d.orgName!==void 0&&{orgName:d.orgName},enabled:![d.credentialId,...P1].some((b)=>W9(H,b,K)),addedAt:l?.addedAt??z,...l?.quota!==void 0&&{quota:l.quota},...!p.claimed&&K!==void 0&&{unclaimed:!0}}});let l0=T.at(-1);if(W&&l0)l0.previousIndex=e8(W,l0.row)}return Q.forEach((F,K)=>{if(O.has(F)||!Y0(F).some(B))return;if(I.has(F.routeId))return;let[j,...P]=Y0(F).filter((v)=>!Y.has(v));if(j===void 0)return;I.add(F.routeId);let{aliases:g,...E}=F;T.push({previousIndex:K,row:{...E,credentialId:j,...P.length&&{aliases:P},stale:!0}})}),T.sort((F,K)=>F.previousIndex===K.previousIndex?F.row.credentialId.localeCompare(K.row.credentialId):F.previousIndex-K.previousIndex),{version:1,view:Z.view,...$?.limits!==void 0&&{limits:$.limits},complete:q,...!q&&{rejected:Z.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:T.map((F)=>F.row),declined:H}}function q9($){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 k1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function U1($){return $===void 0||typeof $==="string"}function z6($){let Z=k1($)?y0($.quota):void 0;if(!k1($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!U1($.accountIdentity)||!U1($.email)||!U1($.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 X6=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function D$($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!k1(J)||!U1(J.credentialId)||typeof J.reason!=="string"||!X6.has(J.reason))return;Z.push(J)}return Z}function P$($){if(!k1($)||$.version!==1||!U1($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!D$($.rejected))throw new A("invalid-state","Claustrum roster file is not valid");let Z=[];for(let X of $.rows){let G=z6(X);if(!G)throw new A("invalid-state","Claustrum roster file is not valid");Z.push(G)}let J=[];for(let X of $.declined){if(!k1(X)||typeof X.credentialId!=="string"||!U1(X.accountIdentity))throw new A("invalid-state","Claustrum roster file is not valid");J.push(X)}let z=D$($.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 K9($){return P$(JSON.parse(JSON.stringify($)))}async function c($){let Z;try{Z=await z0($,_)}catch(z){if(z.code==="ENOENT")return;throw z}let J;try{J=JSON.parse(Z)}catch{throw new A("invalid-state","Claustrum roster file is not valid")}return P$(J)}var C$={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},O$={name:"claustrum-roster",ttlMs:30000};async function g0($,Z,J={}){return w3($,{...C$,signal:J.signal},async(z)=>{let X=await c($),{next:G,result:Q}=await Z(X,{assertOwned:()=>z.assertOwned()});if(G)await z.assertOwned(),await e0($,G,{beforeRename:async()=>{await J.beforePublish?.(),J.signal?.throwIfAborted(),await z.assertOwned()}});return Q})}function F9($,Z){return g0($,(J)=>{let z=J?.rows.find((G)=>G.routeId===Z);if(!J||!z)throw new A("route-unavailable","Claustrum route is not in the roster");let X=H9(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 B9($,Z){return g0($,(J)=>{let z=J?.rows.find((X)=>X.routeId===Z);if(!J||!z)throw new A("route-unavailable","Claustrum route is not in the roster");return{next:{...J,declined:Y9(J.declined,Y0(z),z.accountIdentity),rows:J.rows.map((X)=>X===z?{...X,enabled:!0}:X)},result:void 0}})}function G6($){return new A("invalid-order",$)}function Q6($,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 V9($,Z,J={}){return g0($,(z)=>{let X=z?.rows??[],G=Q6(X,Z);if(G)throw G6(G);let Q=new Map;for(let q of X){let Y=Q.get(q.routeId);if(Y)Y.push(q);else Q.set(q.routeId,[q])}let W=[...Z],H=W.flatMap((q)=>Q.get(q)??[]);if(!z||H.every((q,Y)=>q===X[Y]))return{result:{ids:W,outcome:"unchanged"}};return{next:{...z,rows:H},result:{ids:W,outcome:"reordered"}}},{...J.signal&&{signal:J.signal}})}function W6($,Z){if(!Y0($).includes(Z.credentialId))return"refuse";if($.unclaimed&&(Z.accountIdentitySource==="expected"||Z.accountIdentitySource==="none"))return"refuse";if($.accountIdentity===Z.accountIdentity)return"hold";if($.accountIdentity===void 0&&Z.expectedAccountIdentity===void 0&&Z.accountIdentity!==void 0&&(Z.accountIdentitySource==="asserted"||Z.accountIdentitySource==="parsed")&&Y0($).length===1)return"bind";return"refuse"}async function j9($,Z){let{routeId:J,observation:z,...X}=Z;return A$($,{routeId:J,observation:z,accountIdentity:X.accountIdentity,receipt:X})}async function A$($,Z){if(!Y1(Z.observation))return!1;let J=r($,await c($));if(!R0(J,Z).kept)return!1;return I$($,Z)}function M9($,Z){return A$($,Z)}function R0($,Z){let J=$?.rows.find((Q)=>Q.routeId===Z.routeId),z=!J?"refuse":Z.receipt?W6(J,Z.receipt):J.accountIdentity!==void 0&&J.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!J||z==="refuse")return{roster:$,kept:!1};let X=S1(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 X3=new Map;function E1($){X3.delete(T1($))}function _$($,Z){let J=T1($);if(Z instanceof A)return Z.kind==="roster-busy";if(Z instanceof C0||Z instanceof j0)return T1(Z.details.target)===J;if(Z instanceof w){let z=T1(Z.path);return[C$.name,O$.name].some((X)=>{let G=$1(J,X);return z===G||z.startsWith(`${G}.`)})}return!1}var H6=4;async function N$($){try{let{dev:Z,ino:J,size:z,mtimeMs:X}=await t8($);return{dev:Z,ino:J,size:z,mtimeMs:X}}catch{return}}function Y6($,Z){return $!==void 0&&Z!==void 0&&$.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs}async function U6($,Z,J){for(let z=0;z<H6;z++){let X=await N$($),G=await c($),Q,W,H;try{({target:Q,local:W}=Z(G));let q=JSON.stringify(J(Q));H=JSON.stringify(Q)!==q||W!==void 0&&JSON.stringify(W)!==q}catch{return"commit"}if(!Y6(X,await N$($)))continue;if(H)return"commit";return R$($)?"commit":"unchanged"}return"commit"}async function b1($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){E1($.path);return}let J=await M0({...O$,path:$.path,renew:!0});if(!J){let Q=await c($.path);if($.signal?.throwIfAborted(),!Q?.view)throw new A("roster-busy","Claustrum account discovery is already in progress");return Q}let z=T1($.path),X=$.listedOver,G;try{let Q=await c($.path),W=X?void 0:X3.get(z);G=W&&(W.previousView===Q?.view||W.inventory.view===Q?.view)?W:{inventory:await $.custody.discover($.signal),previousView:Q?.view},X3.delete(z);let{inventory:H}=G;$.onInventory?.(H),$.signal?.throwIfAborted();let q=typeof $.projection==="function"?$.projection():$.projection,Y=(B)=>L$(B,H,q),U=async()=>{return $.signal?.throwIfAborted(),await J.assertOwned(),Z()};if(await U6($.path,(B)=>{if(X)return{target:B};let L=r($.path,B);return{target:B,...L!==B&&{local:L}}},Y)==="unchanged"){if(!await U())return;return await c($.path)}return await g0($.path,async(B)=>{if(!await Z())return{result:void 0};if($.signal?.throwIfAborted(),await J.assertOwned(),X&&B?.view!==X.view&&B?.view!==H.view)return{result:B};let L=Y(B);return{...JSON.stringify(B)!==JSON.stringify(L)&&{next:L},result:L}},{signal:$.signal,beforePublish:async()=>{$.signal?.throwIfAborted(),await J.assertOwned()}})}catch(Q){if(Q instanceof C0&&G&&!X&&!$.signal?.aborted&&await Z())X3.set(z,G);throw Q}finally{await J.release($.signal)}}var v0=new Map,q6=H0("claustrum"),T$=100;function k$($,Z=z9){let J=Q3($),z=v0.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},v0.set(J,z);return z}function E$($,Z,J){let z=k$($,J);z.listeners.add(Z);let X;return()=>X??=(()=>{return z.listeners.delete(Z),z.listeners.size?Promise.resolve():D9($)})()}function K6($){return j$($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function I$($,Z){if(!Y1(Z.observation))return Promise.resolve(!1);let J=k$($),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 K6(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 f$(J,T$),Promise.resolve(!0)}function b$($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,J)=>Z.order-J.order)}function r($,Z){let J=v0.get(Q3($));if(J)for(let z of b$(J.pending)){if(z.priorReading)Z=R0(Z,z.priorReading).roster;Z=R0(Z,z.publication).roster}return Z}function R$($){return!!v0.get(Q3($))?.pending.size}function f$($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;let J=$.draining?0:($.committedAt??-1/0)+J9-$.clock.now();if($.timer=$.clock.schedule(Math.max(Z,J),()=>{return $.timer=void 0,x$($)}),!$.draining)$.timer.unref?.()}function S$($){$.timer?.cancel(),$.timer=void 0}function x$($){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 g0($.path,(z)=>{let X=z;for(let Q of b$(Z)){if(Q.priorReading)X=R0(X,Q.priorReading).roster;X=R0(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)q6.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()):T$;f$($,J)}})(),$.running}async function D9($,Z=1000){let J=Q3($),z=v0.get(J);if(!z)return;z.draining=!0,S$(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)x$(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(),S$(z),z.pending.clear(),v0.get(J)===z)v0.delete(J)}}}var W3=1e4;function y$(){return new t}var N9;function v$($,Z){if(!N9)throw Error("ClaustrumConsumer is not initialized");return N9($,Z)}function g$(){return new A("not-active","Claustrum scoped custody is not active")}class L9{#$;#Z=new AbortController;#X;#Q;#G;#W;#z;#J;#V;#H;#Y=!1;#U=new Set;#F;#q;#B;#D;#C=new Map;#P;#O;#K;#M;#_=new WeakMap;static{N9=($,Z)=>{let J=new L9(Z);return J.#K=$,{consumer:J,hooks:J.#g()}}}constructor($){this.#$=$,this.#X=$.logger??H0("claustrum"),this.#Q=z1(this.#X,this.#Z.signal),this.#O=E$($.rosterPath,(Z)=>{this.#J=R0(this.#J,Z).roster})}#j($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#L($){return this.#U.add($),$.then(()=>this.#U.delete($),()=>this.#U.delete($)),$}async#A(){return await this.#$.isCustodyActive?.()??!0}#R($,Z){let J=k0([this.#Z.signal,...Z?[Z]:[]]);return new Promise((z,X)=>{let G=()=>{J.signal.removeEventListener("abort",Q),J.dispose()},Q=()=>{G(),X(J.signal.reason)};if(J.signal.addEventListener("abort",Q,{once:!0}),$.then((W)=>{if(G(),J.signal.aborted)X(J.signal.reason);else z(W)},(W)=>{G(),X(W)}),J.signal.aborted)Q()})}async#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=this.#$.connect().then((Q)=>{if(this.#Z.signal.aborted||$.timedOut){if(Q.close(),!$.timedOut)this.#j();throw y$()}if(this.#G=new G1({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.#q=x3(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(y$())},this.#S()),X.unref?.()});return Promise.race([z,G]).finally(()=>{if(X)J(X);this.#W=void 0})}#S(){return this.#$.connectTimeoutMs??W3}snapshot(){return this.#J}grantReach(){if(this.#K)return this.#K.grantReach(this.#J?.view);let $=this.#V;return $&&this.#J?.view===$.view?$.reach:void 0}watchState(){if(this.#K)return Object.freeze({vault:this.#K.watchMode()});return Object.freeze({vault:this.#B?.mode??"polling",...this.#$.insula&&{insula:this.#q?.source.watchMode()??"polling"}})}#k(){this.#B?.close(),this.#B=void 0,this.#D?.(),this.#D=void 0}keptReceiptState(){if(this.#K){let $=this.#M;return $&&this.#K.leaseLive($)?$.custody.keptReceiptState():this.#K.keptReceiptState()}return this.#G?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return q9(this.#J)}refresh(){if(this.#j(),this.#K)return this.#L(this.#x(this.#K));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.#q?.release(),this.#q=void 0;return}let $=await this.#E(),Z,J=await b1({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=r(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.#Y)return;if(this.#j(),this.#Y=!0,this.#K){this.#K.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.#H=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#H=void 0,this.#L($())},Z),this.#H.unref?.()};this.#L($())}async#y(){if(this.#B?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#P===void 0||$-this.#P>=s0)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.#q&&!this.#D)this.#D=this.#q.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#A())return;try{await A0(this.#$.tokenPath),await this.#E(),await this.#q?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#A())return;try{return await A0(this.#$.tokenPath),this.#f($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#A())return;try{await A0(this.#$.tokenPath);let J=r(this.#$.rosterPath,await c(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{await A0(this.#$.tokenPath);let z=r(this.#$.rosterPath,await c(this.#$.rosterPath))?.rows.find((Q)=>Q.routeId===$)?.accountIdentity;if(!z||!this.#q)return{miss:"unreachable"};let X=this.#q.source.lookup(Z.provider,z,(this.#$.now??Date.now)()),G=X.reading&&Z.normalize(X.reading.entry,X.reading.context);if(X.miss)return{miss:X.miss,...G!==void 0&&{reading:G}};return G===void 0?{miss:"unreachable"}:{reading:G}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute($,Z){let J=await this.lookupInsulaQuotaForRoute($);if(J.miss==="cold"||J.miss==="upstream-failed"){if(this.#C.get($)!==J.miss)this.#C.set($,J.miss),this.#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.#q?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){if(this.#K)return this.#h(this.#K,$,Z);this.#j(Z);let J=this.#J??await this.#R(this.refresh(),Z);if(!J||!await this.#A())throw this.#G?.close(),this.#G=void 0,this.#k(),this.#q?.release(),this.#q=void 0,new A("not-active","Claustrum scoped custody is not active");let z=r(this.#$.rosterPath,await c(this.#$.rosterPath));this.#j(Z);let X=J.rows.find((H)=>H.routeId===$),G=z?.rows.find((H)=>H.routeId===$);if(G&&!G.enabled){if(X)this.#G?.forget(X.credentialId);throw new A("route-declined","Claustrum route is disabled")}if(!X||!G||G.state!=="active"||G.credentialId!==X.credentialId||G.accountIdentity!==X.accountIdentity||G.credentialType!==X.credentialType){if(X)this.#G?.forget(X.credentialId);throw new A("route-unavailable","Claustrum route is disabled, removed or changed")}let Q=await this.#R(this.#E(),Z),W=k0([this.#Z.signal,...Z?[Z]:[]]);try{return await Q.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},W.signal,$)}finally{W.dispose()}}#g(){return{discovery:($)=>{let Z=this.#K;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=r(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(),g$();if(this.#j(J),!z)throw new A("route-unavailable","Claustrum has no roster for this provider yet");let X=r(this.#$.rosterPath,await c(this.#$.rosterPath));this.#j(J);let G=z.rows.find((q)=>q.routeId===Z),Q=X?.rows.find((q)=>q.routeId===Z);if(Q&&!Q.enabled){if(G)$.forget(G.credentialId);throw new A("route-declined","Claustrum route is disabled")}if(!G||!Q||Q.state!=="active"||Q.credentialId!==G.credentialId||Q.accountIdentity!==G.accountIdentity||Q.credentialType!==G.credentialType){if(G)$.forget(G.credentialId);throw new A("route-unavailable","Claustrum route is disabled, removed or changed")}let W={credentialId:Q.credentialId,credentialType:Q.credentialType,...Q.accountIdentity!==void 0&&{accountIdentity:Q.accountIdentity}},H=k0([this.#Z.signal,...J?[J]:[]]);try{for(let q=0;;q++){let Y=await this.#u($,H.signal);try{let U=await Y.custody.authorize(W,H.signal,Z);return this.#_.set(U,Y),U}catch(U){if(q>0||H.signal.aborted||$.leaseLive(Y)||!(U instanceof A)||U.kind!=="closed")throw U;if(this.#T(Y),!await $.readAuthority())throw g$()}}}finally{H.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.#K){if(this.#M&&this.#K.leaseLive(this.#M))this.#M.custody.reportUsage($)}else this.#G?.reportUsage($)}catch{}}usageReportState(){try{return(this.#K?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.#K){let z=this.#_.get($);if(!z)throw new A("no-receipt","Claustrum dispatch receipt has no active owner");await z.custody.reportFailure($,Z,J);return}if(!this.#G)throw new A("no-receipt","Claustrum dispatch receipt has no active owner");await this.#G.reportFailure($,Z,J)}async send($,Z,J){let z=J.signal,X=await this.authorize($,z),G=await Z(X,z);if(G.status===401&&X.fromKeptReceipt)return await this.reportFailure(X,401,J.reporterSource??"direct"),G;if(G.status===401&&!z?.aborted){let Q;try{Q=await this.authorize($,z),z?.throwIfAborted()}catch(W){if(z?.aborted)throw W}if(Z9(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 F9(this.#$.rosterPath,$),this.#J=r(this.#$.rosterPath,await c(this.#$.rosterPath)),this.#J)this.#K?.publishRoster(this.#J);if(this.#K)this.#K.retainUnion();else this.#G?.retain(this.#J?.rows??[])}async accept($){if(this.#j(),await B9(this.#$.rosterPath,$),this.#J=r(this.#$.rosterPath,await c(this.#$.rosterPath)),this.#J)this.#K?.publishRoster(this.#J)}async reorder($){this.#j();let Z=await V9(this.#$.rosterPath,$);if(this.#J=r(this.#$.rosterPath,await c(this.#$.rosterPath)),this.#J)this.#K?.publishRoster(this.#J);return Z}async recordQuota($,Z,J){return this.#j(),j9(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(),M9(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:J})}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new A("closed","Claustrum consumer is closed")),this.#H)(this.#$.clearTimeoutImpl??clearTimeout)(this.#H);if(this.#H=void 0,this.#k(),this.#G)this.#G.close(),this.#L(this.#G.dispose(this.#Q));this.#M?.release(),this.#M=void 0,this.#K?.detach(),this.#q?.release(),this.#q=void 0,this.#J=void 0,this.#V=void 0,this.#O(),E1(this.#$.rosterPath)}async dispose(){this.close(),this.#F??=Promise.all([X1(this.#U,this.#Q),this.#O()]).then(()=>{}),await this.#F}}import{createHash as F6}from"node:crypto";import{channel as B6}from"node:diagnostics_channel";import{readdir as V6,stat as j6}from"node:fs/promises";import{dirname as M6,join as q1,resolve as h$}from"node:path";var H3=new Map,D6=/^[a-z0-9][a-z0-9._-]{0,63}$/,N6=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/,L6=/^[0-9a-f]{16}$/,m$=3;function C9($,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=C9($[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=C9($[G],J);if(Q===void 0)return;z.push(`${JSON.stringify(G)}:${Q}`)}return`{${z.join(",")}}`}function P6($,Z){let J=C9({format:1,classifier:$.classifierInput,members:[...Z].sort(),routePrefix:$.routePrefix??G3,mapAccount:$.mapAccount?String($.mapAccount):null});if(J===void 0)throw new A("invalid-state","Claustrum hub classifierInput must be plain JSON");return F6("sha256").update(J).digest("hex").slice(0,16)}function w$($,Z){if(typeof $!=="string"||!D6.test($)||N6.test($))throw new A("invalid-state",`Claustrum hub ${Z} must be a lowercase file-safe id`);return $}function S0($="Claustrum custody lease is closed"){return new A("closed",$)}function P9(){return new A("not-active","Claustrum scoped custody is not active")}function u$(){return new t}function C6($,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 c$($){return JSON.stringify(($?.rows??[]).map((Z)=>[Z.credentialId,Z.enabled]))}class p${#$;#Z;#X;#Q=new AbortController;#G=new Map;#W=new WeakMap;#z=0;#J;#V;#H;#Y;#U;#F;#q=0;#B;#D;#C;#P=!1;#O=new Set;#K;#M;#_;constructor($){if(!$.family||!("classify"in $.family))throw new A("wrong-consumer","Claustrum discovery hub requires a classifying family");let Z=w$($.hostGeneration,"host generation"),J=$.members.map((X)=>w$(X,"member"));if(new Set(J).size!==J.length)throw new A("invalid-state","Claustrum hub members must be distinct");this.#$=$,this.#Z=$.logger??H0("claustrum"),this.#X=z1(this.#Z,this.#Q.signal),this.#M=q1($.stateDir,"rosters",Z),this.#_=P6($,J);let z=q1(this.#M,this.#_);for(let X of J)this.#G.set(X,{provider:X,path:q1(z,`${X}.json`),closed:!1})}#j($){return this.#O.add($),$.then(()=>this.#O.delete($),()=>this.#O.delete($)),$}#L(){if(this.#Q.signal.aborted)throw S0("Claustrum discovery hub is closed")}#A($){let Z=this.#G.get($);if(!Z)throw new A("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 A("wrong-consumer","Claustrum hub member was already built");for(let U of["rosterPath","tokenPath","family","connect","isCustodyActive","insula","pollIntervalMs","routePrefix","mapAccount"])if(U in Z)throw new A("wrong-consumer",`Claustrum hub members cannot take ${U}`);let z={provider:J.provider,start:()=>this.start(),refresh:()=>this.#h(),readAuthority:()=>this.#x(),acquire:(U)=>this.acquire(U),leaseLive:(U)=>this.#S(U),grantReach:(U)=>U!==void 0&&this.#B?.view===U?this.#B.reach:void 0,watchMode:()=>this.watchState(),keptReceiptState:()=>this.keptReceiptState(),retainUnion:()=>this.#w(),publishRoster:(U)=>this.#R(J,U),forget:(U)=>this.#J?.custody?.forget(U),detach:()=>{J.closed=!0,J.releaseRoster?.()}},X={rosterPath:J.path,...Z.reservedRouteIds&&{reservedRouteIds:Z.reservedRouteIds},...this.#$.routePrefix!==void 0&&{routePrefix:this.#$.routePrefix},...this.#$.mapAccount&&{mapAccount:this.#$.mapAccount},...Z.onRoster&&{onRoster:Z.onRoster},...Z.onDiscovery&&{onDiscovery:Z.onDiscovery},...Z.onError&&{onError:Z.onError},logger:Z.logger??this.#Z,...this.#$.now&&{now:this.#$.now}},{consumer:G,hooks:Q}=v$(z,X);J.hooks=Q;let W=h$(J.path),H=H3.get(W)??new Set,q=(U)=>{if(J.closed||this.#F!==!0||!this.#J||!this.#N(this.#J)||!Q.roster()||this.#c(Q,U))return;if(J.seen=JSON.stringify(K9(U)),Q.install(U),U.view!==this.#B?.view)J.pending??={failures:0,wait:0};this.#w()};H.add(q),J.receiveRoster=q,H3.set(W,H);let Y=!0;return J.releaseRoster=()=>{if(!Y)return;if(Y=!1,H.delete(q),!H.size)H3.delete(W)},G}#R($,Z){let J=this.#J;if($.closed||!J||!this.#N(J))return;$.seen=JSON.stringify(K9(Z)),$.hooks?.install(Z);for(let z of H3.get(h$($.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=S0()){if($.ended)return;if($.ended=!0,$.count=0,this.#J===$)this.#J=void 0;if(this.#H&&this.#W.get(this.#H)?.generation===$)this.#H=void 0;if(this.#Y?.generation===$)this.#Y.watch.close(),this.#Y=void 0;if($.controller.abort(Z),$.custody)$.custody.close(),this.#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??W3,X,G=this.#$.connect().then((H)=>{if(J.timedOut)throw H.close(),u$();if(!this.#N($)||$.count<=0)throw H.close(),S0("Claustrum connection is no longer wanted");return $.custody=new G1({client:H,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Z,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),$.custody}),Q=new Promise((H,q)=>{X=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(J.timedOut=!0,!this.#N($))return;this.#Z.warn("vault connect timed out",{reason:"unreachable",connectTimeoutMs:z}),q(u$())},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 P9()}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=k0([$.controller.signal,...Z?[Z]:[]]);try{z=await C6(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 P9();if(!Z)throw S0();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 S0()},X=Object.freeze({authorize:async(Q,W,H)=>{z();let q=k0([$.controller.signal,...W?[W]:[]]);try{return await Z.authorize(Q,q.signal,H)}finally{q.dispose()}},reportFailure:async(Q,W,H)=>{return z(),Z.reportFailure(Q,W,H)},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 $=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.#q++;let $=this.#J;if($)this.#k($,P9());this.#H=void 0,this.#Y?.watch.close(),this.#Y=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(),E1(Z.path)}#T(){return[...this.#G.values()].filter(($)=>$.hooks&&!$.closed)}async#u(){let $=this.#H,Z=$&&this.#W.get($);if($&&Z&&this.#S($))return Z;this.#H=void 0;let J=await this.acquire(this.#Q.signal),z=this.#H&&this.#W.get(this.#H);if(this.#H&&z&&this.#S(this.#H))return J.release(),z;this.#H=J;let X=this.#W.get(J);if(!X)throw S0();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},(Y)=>Y instanceof Error?Y:Error(String(Y))),X=new Map(await Promise.all([...this.#G.values()].map(async(Y)=>[Y,await c(Y.path).then((U)=>U?{file:U}:{},(U)=>U instanceof Error?U:Error(String(U)))])));if(!this.#N(J))return;let G;try{G=await Z.custody.discover(J.controller.signal)}catch(Y){if(!this.#N(J))return;for(let U of this.#G.values())if(U.pending)this.#m(U);throw Y}if(!this.#N(J))return;let Q=this.#T(),W=await Promise.all(Q.map((Y)=>Y.hooks&&!Y.closed?this.#i(Y,Y.hooks,G,z??X.get(Y),J):void 0));if(!this.#N(J))return;let H=new Map,q=!0;for(let[Y,U]of Q.entries()){let D=U.hooks,B=W[Y];if(!D||!B)continue;if("error"in B){let{error:C}=B;if(q=!1,this.#m(U),_$(U.path,C))this.#Z.debug("claustrum hub member commit refused",{member:U.provider});else H.set(U.provider,C);continue}let{roster:L}=B;if(!this.#N(J))return;if(L?.view!==G.view)q=!1,this.#m(U);else U.pending=void 0;if(!L)continue;if(this.#c(D,L)){q=!1,this.#m(U);continue}this.#R(U,L)}if(!this.#N(J))return;if(this.#w(),q)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:H}}async#i($,Z,J,z,X){let G={...J,credentials:J.credentials.filter((Q)=>Q.member===$.provider),skipped:J.skipped.filter((Q)=>Q.member===$.provider)};try{if(!z)throw S0("Claustrum hub member has no base view");if(z instanceof Error)throw z;let Q;if(!z.file){let H=B6("common-auth.claustrum.phases");if(H.hasSubscribers)H.publish({logger:this.#Z,phase:`seed read ${$.provider} begin`});try{Q=await this.#r($)}finally{if(H.hasSubscribers)H.publish({logger:this.#Z,phase:`seed read ${$.provider} end`})}}return{roster:await b1({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[M6(this.#M),this.#M,q1(this.#M,this.#_)])await J1($,{},"roster directory")}async#r($){let Z=`${$.provider}.json`,J=[q1(this.#M,Z)];try{for(let X of await V6(this.#M))if(X!==this.#_&&L6.test(X))J.push(q1(this.#M,X,Z))}catch{}let z;for(let X of J)try{let G=(await j6(X)).mtimeMs,Q=await c(X);if(Q&&(!z||G>z.modified))z={modified:G,roster:Q}}catch{}return z&&U9(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(s0/J)),X=Z<=m$?1:Math.min(2**(Z-m$),z);$.pending={failures:Z,wait:X-1}}#w(){let $=this.#J?.custody;if(!$)return;$.retain(this.#T().flatMap((Z)=>Z.hooks?.roster()?.rows??[]))}async#t(){let $=this.#q;for(let Z of this.#T()){let J;try{J=await c(Z.path)}catch(W){Z.hooks?.onError(W);continue}if($!==this.#q||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=c$(G);if(Z.seen=X,this.#R(Z,J),c$(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.#Y?.watch.mode!=="watching"||$)return!0;let Z=(this.#$.now??Date.now)();return this.#D===void 0||Z-this.#D>=s0}#$0(){let $=this.#H,Z=$&&this.#W.get($);if(!$||!Z||!this.#S($)||this.#F!==!0)return;let J=Z.generation;if(!this.#N(J)||this.#Y?.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.#Y={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.#Y;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(S0("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.#H=void 0,this.#Y?.watch.close(),this.#Y=void 0}async dispose(){this.close(),this.#K??=X1(this.#O,this.#X),await this.#K}}var m0={opencode:_6,pi:I6};function O9($,Z){let{tokenPath:J}=d$($,Z);return{stateDir:A6(J),host:$,override:J}}function A9($,Z){return R6($==="pi"?Z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0,$==="pi"?{...Z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:Z)}class h0 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 _9($,Z){let J=Z??m0[$];if(typeof J!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(J))throw new h0("permission-refused");return["auth","grant","--principal",`enrolled:${J}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"]}async function l$($,Z){try{await Z.processFence();let J=await $3(Z.paths??d$($,Z.env),m0[$]);if(J.state==="blocked")throw new h0("permission-refused");let z=J.state==="approved"?J.approvedName:void 0,X=_9($,z);if((await Z.runner.run(Z.ckBinary??"ck",X,{env:Z.env})).exitCode!==0)throw new h0("permission-refused");return z}catch{throw new h0("permission-refused")}}import{createHash as x6}from"node:crypto";import{lstat as y6,mkdir as g6,readFile as J4}from"node:fs/promises";import{dirname as v6}from"node:path";import{assertHostsStopped as h6,canonicalPath as R9,createNativeAccountRuntime as m6,custodyTombstoneOAuth as w6,inspectNativeHostAuthEntry as z4,NativeMigrationError as w0,nativeJournalMayAdoptLaterHostLogin as u6,nativePoolHoldsAccountData as c6,prepareNativeMigration as p6,readNativeEnrollmentMode as X4,readNativeMigrationJournal as d6,releaseNativeMigrationPreflight as l6,requireNoSupervisedAuthContentSnapshot as a6,runNativeMigration as s6,writeNativeHostAuth as n6}from"@cortexkit/anthropic-auth-core";import{dirname as S6,join as a$,resolve as I9}from"node:path";import{ACCOUNT_FILE_NAME as s$,ACCOUNT_STATE_FILE_NAME as T6,canonicalPath as n$,getStickyRoutingStatePath as k6,resolveLocalRoutingDestination as E6,resolveNativePoolPaths as b6}from"@cortexkit/anthropic-auth-core";async function D0($,Z){let J=$==="pi"?r$(Z):i$(Z),z=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),X=I9(z||a$(J,s$)),G=I9(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(X.endsWith(s$)?a$(S6(X),T6):`${X}.state.json`)),Q=await b6(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"?t$(Z):o$(Z),routingSourcePath:I9(W||k6(X)),routingDestinationPath:E6($,Q,Z)}}async function e$($){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 n$(G);if(z.has(Q)&&!(X===9&&Q===await n$(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 f6}from"node:util";var $4=new WeakMap;function Z4($){return typeof $==="object"&&$!==null?$4.get($):void 0}function K1($){if(!$||typeof $!=="object"||f6.isProxy($))return;if(Object.getOwnPropertyDescriptor($,"name")?.value==="ProcessInspectionError"&&Object.getOwnPropertyDescriptor($,"code")?.value==="process-inspection-failed")return"Process inspection failed; setup cannot prove hosts are stopped.";return}class i extends Error{constructor($){super($);this.name="SetupRefusal",$4.set(this,$)}}var S9="OpenCode's separate Anthropic login is not used. Add that account through /claude Accounts if needed, or remove the separate login from OpenCode.";function G4($){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 T9($,Z){let J=[];for(let z of $)if(await X4(z,Z)!=="local")J.push(G4(z));if(J.length)throw new i(J.join(`
|
|
13
|
+
`))}function u0($,Z){return async()=>{a6(Z.env);try{await h6(Z.fence,Z.env)}catch(J){let z=K1(J);if(z)throw new i(z);throw J}await T9([$],Z.env)}}async function k9($){try{return x6("sha256").update(await J4($)).digest("hex")}catch(Z){if(Z.code==="ENOENT")return"absent";throw new w0("unsafe-source")}}async function f1($,Z){let J;try{J=JSON.parse(await J4(Z,"utf8"))}catch(G){if(G.code!=="ENOENT")throw new w0("unsafe-source")}let z=z4($,J),X=J?.anthropic;return{...z,realLogin:z.kind==="oauth"&&Boolean(X?.access&&X.refresh)}}async function Y3($,Z){let{paths:J}=$,z=$.generation2?void 0:await f1(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(k9));return JSON.stringify([await X4(J.host,Z),z?.digest,...X])}async function E9($,Z,J){let z=Z.paths??await D0($,Z.env),X=u0($,Z);await X();let G=await d6(z.paths);if(G&&G.host!==$)throw new w0("invalid-source");let Q=G?.phase==="committed"||G?.phase==="retired";if(G&&G.kind!=="empty-init"&&(G.hostAuthPath!==await R9(z.hostAuthPath)||G.routingPaths.source!==await R9(z.routingSourcePath)||G.routingPaths.destination!==await R9(z.routingDestinationPath)))throw new w0("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 w0("invalid-source");if(W.action=G?"reuse":"empty-init",!G){let H=[z.paths.config,z.paths.state,z.paths.runtime,z.paths.roster];if(!Z.env.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE)H.push(z.routingDestinationPath);for(let q of H){try{await y6(q)}catch(Y){if(Y.code==="ENOENT")continue;throw new w0("unsafe-source")}throw new w0("invalid-source")}}}else{W.slot=await f1($,z.hostAuthPath);let H=u6(G,$)&&W.slot.kind==="oauth";W.poolPopulation=G?.kind==="empty-init"||H?await c6({paths:z.paths}):"not-evaluated";let q=W.poolPopulation===!0;if($==="opencode"&&(q||Q&&G?.kind!=="empty-init"&&!H&&W.slot.kind==="oauth"))W.action="skip",W.notice=W.slot.realLogin;else W.preflight=await p6({...z,env:Z.env,processFence:X,removePiAnthropicAuth:Z.removePiAnthropicAuth})}return W.fingerprint=await Y3(W,Z.env),W}async function F1($,Z){await u0($.paths.host,Z)();let J=await E9($.paths.host,{...Z,paths:$.paths},$.generation2);try{if(J.fingerprint!==$.fingerprint||J.action!==$.action)throw new i("Setup inputs changed. Rerun setup with all hosts stopped.")}finally{if(J.preflight)l6(J.preflight)}}async function b9($,Z){if($.paths.host!=="opencode"||$.slot?.kind!=="absent")return;let J=u0("opencode",Z);await J(),await g6(v6($.paths.hostAuthPath),{recursive:!0,mode:448}),await n6({host:"opencode",authPath:$.paths.hostAuthPath,sourceDigest:"absent",expectedDigest:z4("opencode",{anthropic:w6("anthropic")}).digest,env:Z.env,removePiAnthropicAuth:!1,processFence:J})}async function Q4($,Z){let J={...Z.env},z=u0($,{...Z,env:J});await z();let X=Z.paths??await D0($,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 s6({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=m6({paths:X.paths,host:$,vault:{env:J},beforePoolWrite:z});try{if((await Q.read()).mode!=="local")throw new i(G4($));await z(),await Q.loginOAuth({routeId:"main",replace:!0,...G})}finally{await Q.close()}}if(Z.skipMigration){let Q=await f1($,X.hostAuthPath);await b9({paths:X,slot:Q},Z)}}var W4={opencode:"OpenCode",pi:"Pi"};function z5($,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`${W4[Z]} has no read grant in the vault, so setup cannot see any Claude login. Run ${["ck",..._9(Z,J)].join(" ")}, then rerun setup.`;case"grant-reaches-nothing":return`${W4[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 X0 extends Error{host;approvedName;code;constructor($,Z="opencode",J){super(z5($,Z,J));this.host=Z;this.approvedName=J;this.name="NativeVaultActivationError",this.code=$}}function X5($){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 x9($){try{return JSON.parse(await i6($,"utf8"))}catch(Z){if(Z.code==="ENOENT")return;throw new X0("host-auth-invalid")}}async function x1($,Z){if($==="opencode")return"opencode";let J=Z.paths??await D0($,Z.env),z=f9($,await x9(J.hostAuthPath)),X=y9({env:Z.env,authPath:J.hostAuthPath}),{stashPath:G}=$5({env:Z.env,authPath:J.hostAuthPath});return JSON.stringify([z.digest,await X.inspect(),await k9(G)])}async function H4($){try{J5($.env)}catch{throw new X0("auth-content-refused")}try{await o6($.fence,$.env)}catch(Z){let J=K1(Z);if(J)throw new i(J);throw Z}}async function Y4($,Z){let J={...Z.env};await(()=>H4({...Z,env:J}))();let X=Z.paths??await D0($,J),G=$==="opencode"&&Z.inspectOpenCodeAuth!==!1&&f9("opencode",await x9(X.hostAuthPath)).kind==="oauth";if($==="pi"){let Q=f9("pi",await x9(X.hostAuthPath)),W=await y9({env:J,authPath:X.hostAuthPath}).inspect();if(W.slot==="placeholder"&&W.stash==="missing")throw new e6("missing-stash");if(Q.kind!=="absent"&&W.slot!=="placeholder"&&!Z.removePiAnthropicAuth)throw new X0("consent-required")}return{priorMode:await Z5($,J),fingerprint:await x1($,{...Z,env:J}),separateOpenCodeLogin:G}}async function U4($,Z,J){let z={...Z.env},X=()=>H4({...Z,env:z});await X();let G=Z.paths??await D0($,z);if(await x1($,Z)!==J.fingerprint)throw new X0("host-auth-invalid");let Q=await l$($,{env:z,runner:Z.runner,processFence:X,ckBinary:Z.enrollment?.ckBinary,paths:Z.enrollment?.paths}),W=Z.discover??(()=>t6({paths:G.paths,host:$,env:$==="pi"?{...z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE}:z})),H,q=async()=>{return H=await W(),H},Y=r6({paths:G.paths,host:$,vault:{env:z,discover:q}});try{await X(),await Y.vault.refresh();let U=await Y.read(),D=U.accounts.find((B)=>B.id==="main");if(U.mode!=="claustrum"||!D?.accountIdentity||D.source!=="vault"){let B=X5(H);throw B==="primary-unverified"?new X0(B):new X0(B,$,Q)}if(await X(),$==="pi")await y9({env:z,authPath:G.hostAuthPath}).enterVault();return J.priorMode==="claustrum"?"already-vault":"committed"}finally{await Y.close()}}var G5=/(?:^|[/\\])(opencode|litecode|opencode2|pi)(?:\.exe)?(?=$|\s|")/i;class g9 extends Error{activeHosts;constructor($){let Z=$.map((z)=>({pid:z.pid,command:G5.exec(z.command)?.[1]??"host"})),J=Z.map((z)=>` - PID ${z.pid}: ${z.command}`).join(`
|
|
14
14
|
`);super(`OpenCode or Pi processes are currently running:
|
|
15
15
|
${J}
|
|
16
16
|
|
|
17
|
-
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=Z,this.name="ProcessFenceViolationError"}}var
|
|
18
|
-
`,$.length-
|
|
19
|
-
`,
|
|
17
|
+
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=Z,this.name="ProcessFenceViolationError"}}var R5={"setup-activation":"Vault custody setup","setup-opencode-config":"OpenCode configuration","setup-pi-install":"Pi extension installation","setup-pi":"Pi setup","setup-process-check":"Host process check","cli-setup":"Setup","cli-login":"Login","cli-api-add":"API route setup","cli-list":"Account listing","cli-relay-setup":"Relay setup","cli-relay-workers-dev":"Workers.dev enablement","cli-command":"Command"};function y1(){return($)=>$}var h9=["opencode","pi"],S5=new Set(["enrolled","not-enrolled","unknown"]),M4=y1()(["auth-content-refused","host-auth-invalid","primary-conflict","consent-required","primary-unverified","no-read-grant","grant-reaches-nothing"]),D4=y1()(["enrollment-refused","enrollment-reset","approval-refused","permission-refused"]),N4=y1()(["invalid-source","unsafe-source","consent-required","primary-unverified","migration-busy","ownership-lost","retirement-refused","pool-populated","host-login-present","settings-changed"]),L4=y1()(["invalid-options","invalid-auth","invalid-stash","unsafe-path","missing-stash","conflict","lock-timeout","lock-compromised","io"]),P4=y1()(["closed","not-enrolled","invalid-token","unavailable","identity-changed","identity-unasserted","insufficient-validity","invalid-material","not-active","route-unavailable","route-declined","no-receipt","unsafe-file","invalid-state","wrong-consumer","roster-busy","host-slot-login","host-slot-placeholder","placeholder-refresh","invalid-order"]),T5={name:new Set(["Error","TypeError","SyntaxError","RangeError","AggregateError","AbortError","PrivateFileError","PrivateFilesUnavailableError","DiagnosticFileError","NativeRuntimeError","NativeAuthorityError","NativeMigrationError","NativeMigrationSourceError","NativeHostAuthError","NativeHostAuthWriteError","NativePiAuthSlotError","NativeCustodyError","NativeVaultActivationError","NativeVaultEnrollmentError","SetupCommandError","HostNotEnrolledError","ProcessFenceViolationError","ProcessInspectionError","LockOwnershipError","LockContentionError","ClaustrumConsumerError","ClaustrumCredentialError","RelocatedError","HolderRegistrationError","StateLayoutRefusalError"]),code:new Set([...M4,...D4,...N4,...L4,...P4,"EACCES","EPERM","ENOENT","EEXIST","ENOTDIR","EISDIR","ENOTEMPTY","EBUSY","ETIMEDOUT","ECONNREFUSED","ECONNRESET","ECANCELED","EIO","EINVAL","ENOTSUP","ENOSYS","ENOMEM","EMFILE","ENFILE","ELOOP","EROFS","EXDEV","ENAMETOOLONG","EBADF","EPIPE","ENOSPC","EINTR","ERR_INVALID_ARG_TYPE","ERR_INVALID_ARG_VALUE","ERR_OUT_OF_RANGE","ERR_FEATURE_UNAVAILABLE_ON_PLATFORM","ERR_PRIVATE_FILES_SECURITY","ERR_PRIVATE_FILES_UNAVAILABLE","ERR_PRIVATE_FILE","ERR_DIAGNOSTICS_DIRECTORY_UNAVAILABLE","ERR_DIAGNOSTICS_NOT_DIRECTORY","ERR_DIAGNOSTICS_NOT_OWNER_ONLY","unsafe-runtime","invalid-runtime","runtime-io","runtime-conflict","publication-refused","invalid-journal","source-io","source-changed","source-too-large","write-io","relocated","lock-timeout","managed-folder","malformed",...O5]),stage:new Set(["safe-parent","verify","directory","read","create","directory-create","rename","stage-directory","stage-create","before-rename","published-callback","published-verify","directory-sync-unsupported"]),reason:new Set(["wrong-owner","extra-ace","not-protected","null-dacl","empty-dacl","reparse-point","unsupported-filesystem","native-addon-unavailable","unsafe-ancestor","wrong-kind","io-error","mode","writable-by-others"])},k5=new Set([...M4.flatMap(($)=>$==="no-read-grant"||$==="grant-reaches-nothing"?h9.map((Z)=>new X0($,Z).message):[new X0($).message]),...D4.map(($)=>new h0($).message),...N4.map(($)=>new L5($).message),...L4.map(($)=>new P5($).message),...P4.map(($)=>`Native custody refused: ${$}`),j4,C5,...j5,...A5,"Disconnect from the vault first.","Native account changes require offline setup without OPENCODE_AUTH_CONTENT","Local login cannot be verified while OPENCODE_AUTH_CONTENT is set","Authentication failed","API fallback base URL must be an http(s) URL without embedded credentials","API key is required","Vault routes cannot be replaced with a local API key","Cloudflare API token is required","Cloudflare account ID is required","Relay Worker URL is required","--claustrum and --no-claustrum cannot be used together.","Setup requires a TTY or --yes.","Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.","Claustrum is not available. Start ck, or omit vault-only flags and use --no-claustrum for local sign-in.","Claude sign-in did not establish an account UUID","Native setup storage paths overlap between selected hosts","Anthropic account storage paths overlap; migration requires separate files","Anthropic account migration is required. Stop OpenCode, LiteCode and Pi, then run npx @cortexkit/opencode-anthropic-auth setup","Anthropic account migration is incomplete; resume setup","Anthropic account migration journal is invalid","Anthropic account migration journal changed","Anthropic runtime state is invalid","Anthropic runtime file is not owner-only regular storage","Anthropic runtime storage is unavailable","Anthropic runtime observation is older than persisted state","Anthropic runtime publication was refused","Claustrum connection failed; start ck and rerun setup.","Claustrum enrollment refused; inspect its status with ck before rerunning setup.","Invalid enrollment request id.","This Claustrum vault does not support connecting plugins yet, so setup cannot connect to it. Run setup without --claustrum to use local accounts.",'This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or run setup without --claustrum to use local accounts.',"OAuth metadata read failed"]),E5=Object.values(m0).join("|"),b5="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",f5=[new RegExp(`^Claustrum approval is still pending\\. In another terminal, run: ck auth enroll approve --request-id [A-Za-z0-9_-]{1,128} --name (?:${E5}) and then rerun setup\\.$`),/^The vault never created the enrollment request \(last error: [a-z][a-z0-9_]{0,63}\)\. Check that ck is running, then rerun setup\.$/],x5=new Set(["opencode","litecode","opencode2","pi","host"]),y5=64,g5=256,v5=4096,v9=65536,h5=4096,m5=3,q4="[output beyond the diagnostic limit omitted]",w5="[output withheld: no line break within the inspected window]",u5="[detail withheld: the known credentials could not be read safely]",w9=new TextEncoder,C4=new TextDecoder;function f($,Z){let J=Object.getOwnPropertyDescriptor($,Z);return J!==void 0&&"value"in J?J.value:void 0}function N0($){return $!==null&&(typeof $==="object"||typeof $==="function")&&!m9.isProxy($)}function u9($,Z){if(!N0($)||!Array.isArray($))return;let J=f($,"length");if(typeof J!=="number"||J>Z)return;let z=[];for(let X=0;X<J;X+=1){let G=Object.getOwnPropertyDescriptor($,String(X));if(G===void 0||!("value"in G))return;z.push(G.value)}return z}function c5($){let Z=u9($,y5);if(Z===void 0||Z.length===0)return;let J=[];for(let z of Z){if(!N0(z))return;let X=f(z,"pid"),G=f(z,"command");if(typeof X!=="number"||!Number.isSafeInteger(X)||X<0)return;if(typeof G!=="string"||!x5.has(G.toLowerCase()))return;J.push({pid:X,command:G})}return J}function g1($){try{if(!N0($))return;if(f($,"name")==="ProcessInspectionError")return"";let Z=f($,"message");if(typeof Z!=="string")return;if(f($,"name")==="HostNotEnrolledError"&&Z===b5)return Z;if(k5.has(Z))return Z;if(f($,"name")==="StateLayoutRefusalError"){let X=f($,"code");if(N5(X))return I5(X)}if(f($,"name")==="NativeVaultActivationError"&&f($,"code")==="no-read-grant"){let X=f($,"host"),G=f($,"approvedName");if((X==="opencode"||X==="pi")&&typeof G==="string"){let Q=new X0("no-read-grant",X,G).message;if(Z===Q)return Q}}if(Z.startsWith("Unknown setup argument: "))return Z;if(f($,"name")==="HostNotEnrolledError"&&f5.some((X)=>X.test(Z)))return Z;if(f($,"code")==="ERR_PRIVATE_FILES_UNAVAILABLE")return j4;let J=f($,"status");if(typeof J==="number"&&Number.isInteger(J)&&J>=100&&J<=599&&Z===`OAuth metadata read failed: ${J}`)return Z;let z=c5(f($,"activeHosts"));if(z){let X=new g9(z).message;if(Z===X)return X}}catch{}return}function O4($){try{if(!N0($))return;let Z=u9(_5($),h9.length);if(Z===void 0)return;let J=[];for(let z of Z){if(!N0(z))return;let X=h9.find((Q)=>Q===f(z,"host")),G=f(z,"outcome");if(X===void 0||!S5.has(G))return;J.push({host:X,outcome:G})}return J}catch{return}}function p5($,Z=[]){try{let J=new Set,z=u9(Z,g5);if(z===void 0)return;for(let G of z){if(typeof G!=="string")return;if(G!=="")J.add(G)}if(!N0($))return;let X=Reflect.ownKeys($);if(X.length>v5)return;for(let G of X){if(typeof G!=="string"||!D5(G))continue;let Q=Object.getOwnPropertyDescriptor($,G);if(Q===void 0)continue;if(!("value"in Q))return;if(Q.value===void 0||Q.value==="")continue;if(typeof Q.value!=="string")return;J.add(Q.value)}return[...J]}catch{return}}function d5($,Z){let J=w9.encode($);if(J.length<=Z)return $;let z=Math.max(0,Z);while(z>0&&((J[z]??0)&192)===128)z-=1;return C4.decode(J.subarray(0,z))}function l5($,Z){let J=w9.encode($);if(J.length<=Z)return $;let z=J.length-Math.max(0,Z);while(z<J.length&&((J[z]??0)&192)===128)z+=1;return C4.decode(J.subarray(z))}function a5($,Z,J){let z=$,X=!1;if($.length>v9){if(X=!0,J==="tail"){let H=$.indexOf(`
|
|
18
|
+
`,$.length-v9);z=H===-1?"":$.slice(H+1)}else{let H=$.lastIndexOf(`
|
|
19
|
+
`,v9);z=H===-1?"":$.slice(0,H)}if(z==="")return[w5]}let G=Z.redactText(z).split(/\r?\n/);if(G.length>1&&G[G.length-1]==="")G.pop();if(J==="tail")G.reverse();let Q=[],W=h5;for(let H of G){let q=w9.encode(H).length+1;if(q<=W){Q.push(H),W-=q;continue}if(Q.length===0)Q.push(J==="tail"?l5(H,W-1):d5(H,W-1));X=!0;break}if(J==="tail")Q.reverse();if(X)if(J==="tail")Q.unshift(q4);else Q.push(q4);return Q}function A4($){let Z=$;for(let J=0;Z!==null&&J<8;J+=1){if(m9.isProxy(Z))break;let z=f(Z,"name");if(typeof z==="string")return z;Z=Object.getPrototypeOf(Z)}return"object"}function K4($,Z){let J={};if(Z===void 0)return J;try{if(!N0($))return J;let z=V4(Z);try{for(let X of["name","code","stage","reason"]){let G=X==="name"?A4($):f($,X);if(typeof G==="string"&&T5[X].has(G)&&z.redactText(G)===G)J[X]=G}}finally{z.dispose()}}catch{return{}}return J}function s5($){if(!N0($))return;let Z=f($,"step"),J=f($,"exitCode"),z=f($,"signal"),X=f($,"stderrTail");if(typeof Z!=="string"||Z.length===0||!(J===null||typeof J==="number"&&Number.isInteger(J))||!(z===null||typeof z==="string")||typeof X!=="string")return;return{step:Z,exitCode:J,signal:z,stderrTail:X}}function _4($,Z){if($===null||typeof $!=="object"&&typeof $!=="function")return[`thrown ${typeof $}: ${String($)}`];if(m9.isProxy($))return["thrown proxy (not inspected)"];let J=[],z=A4($),X=f($,"message");J.push(typeof X==="string"?`${z}: ${X}`:`${z} (no message)`);let G=f($,"code");if(typeof G==="string"||typeof G==="number")J.push(`code: ${G}`);let Q=f($,"stack");if(typeof Q==="string")J.push(Q);let W=f($,"cause");if(W!==void 0)if(Z>=m5)J.push("caused by: [not described]");else J.push("caused by:",..._4(W,Z+1));return J}function F4($,Z){let J=f($,Z);return typeof J==="string"&&J!==""?J:void 0}function n5($){if(!N0($))return;let Z=F4($,"HOME"),J=K5({xdgStateHome:F4($,"XDG_STATE_HOME"),home:Z&&q5(Z)?Z:U5()});return B4(J,"diagnostics")}async function i5($,Z,J,z={}){let X=(G)=>({error:{name:"DiagnosticFileError",code:G}});try{let G=n5($);if(G===void 0)return X("ERR_DIAGNOSTICS_DIRECTORY_UNAVAILABLE");if(!await B5(G,z)){await H5(G,{recursive:!0,mode:448});let H=await W5(G);if(!H.isDirectory())return X("ERR_DIAGNOSTICS_NOT_DIRECTORY");if(!await M5(G,()=>(H.mode&63)===0&&H.uid===process.getuid?.(),z))return X("ERR_DIAGNOSTICS_NOT_OWNER_ONLY")}let Q=B4(G,`${Z}-${Date.now()}-${process.pid}-${Q5()}.log`);if(await F5(Q,J,z))return{path:Q};let W=await Y5(Q,U3.O_WRONLY|U3.O_CREAT|U3.O_EXCL|(U3.O_NOFOLLOW??0),384);try{await W.writeFile(J,"utf8")}finally{await W.close()}return{path:Q}}catch(G){return{error:G}}}async function o5($,Z,J,z,X,G,Q,W={}){let H,q=p5(J,z);if(q===void 0)H=[u5];else try{let L=V4(q);try{let{text:C,keep:O}=G();H=a5(C,L,O)}finally{L.dispose()}}catch{H=["[failure detail could not be recorded]"]}let Y=R5[$],U=V5("error","cli",`${Y} failed`,{stage:$,code:Z,...X}),D=await i5(J,$,`${[U,...H].join(`
|
|
20
20
|
`)}
|
|
21
|
-
`,W.ownership),B=
|
|
22
|
-
`)}catch{}}return B===void 0?`${Y} failed (${Z}). Details could not be saved to a private diagnostics file.`:`${Y} failed (${Z}). Details were written to ${B}`}async function
|
|
21
|
+
`,W.ownership),B=D.path;if(B===void 0){let L={error:K4(Q,q),saveError:K4(D.error,q)};try{(W.stderr??((O)=>process.stderr.write(O)))(`CLI failure metadata: ${JSON.stringify(L)}
|
|
22
|
+
`)}catch{}}return B===void 0?`${Y} failed (${Z}). Details could not be saved to a private diagnostics file.`:`${Y} failed (${Z}). Details were written to ${B}`}async function c0($,Z,J,z=[],X={}){let G=g1(Z);if(G!==void 0)return G;let Q=s5(Z);return o5($,`${$}/unexpected-error`,J,z,{},()=>({text:[...Q?[`step: ${Q.step}`,`exitCode: ${Q.exitCode}`,`signal: ${Q.signal}`]:[],..._4(Z,0),...Q?[`stderrTail:
|
|
23
23
|
${Q.stderrTail}`]:[]].join(`
|
|
24
|
-
`),keep:"head"}),Z,X)}import{assertHostsStopped as
|
|
25
|
-
`)J.push("enter");else if(X==="\x03")J.push("escape");else if(X&&X>=" ")J.push("char");z+=1}return J}var
|
|
26
|
-
`),L+=1},
|
|
27
|
-
`),Y=!1;for(let U=0;U<q.length;U++){let
|
|
28
|
-
`){if(G)z+=
|
|
29
|
-
`){if(X&&
|
|
30
|
-
`)}var
|
|
31
|
-
`),G=0,Q=$;for(let H of X){if(Q<=H.length)break;Q-=H.length+1,G++}for(G=Math.max(0,Math.min(X.length-1,G+J)),Q=Math.min(Q,X[G].length)+Z;Q<0&&G>0;)G--,Q+=X[G].length+1;for(;Q>X[G].length&&G<X.length-1;)Q-=X[G].length+1,G++;Q=Math.max(0,Math.min(X[G].length,Q));let W=0;for(let H=0;H<G;H++)W+=X[H].length+1;return W+Q}var
|
|
24
|
+
`),keep:"head"}),Z,X)}import{assertHostsStopped as DJ,createProcessFence as D7,decideOpenCodeStateLayoutOnce as NJ,decidePiStateLayout as LJ,NativePiAuthSlotError as PJ,openNativePiAuthSlot as CJ,publishNativeEmptyInit as OJ,readNativeEnrollmentMode as AJ,releaseNativeMigrationPreflight as _J,requireNoSupervisedAuthContentSnapshot as IJ,restoreLegacyLayout as RJ,runSetup as SJ,StateLayoutRefusalError as TJ,setupUsage as kJ}from"@cortexkit/anthropic-auth-core";import{AsyncLocalStorage as I4}from"node:async_hooks";var fW=new I4,xW=new I4;var R4=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});var B1="commonAuthPool";var DZ=Object.freeze(["version","accounts",B1]);var aY=new O1;var k={hide:"\x1B[?25l",show:"\x1B[?25h",up:($=1)=>`\x1B[${$}A`,clearLine:"\x1B[2K",clearScreen:"\x1B[2J",moveTo:($,Z)=>`\x1B[${$};${Z}H`,cyan:"\x1B[36m",green:"\x1B[32m",red:"\x1B[31m",dim:"\x1B[2m",reset:"\x1B[0m"};function i9($){let Z=$.toString(),J=[];for(let z=0;z<Z.length;){let X=Z[z];if(X==="\x1B"){let G=Z.slice(z,z+3),Q=G[1]==="["||G[1]==="O"?G[2]:void 0;if(Q&&"ABCD".includes(Q)){let H={A:"up",B:"down",C:"right",D:"left"}[Q];if(H)J.push(H);z+=3}else if(z+1===Z.length){if(z===0)J.push("escape-start");z+=1}else if((Z[z+1]==="["||Z[z+1]==="O")&&z+2>=Z.length)break;else z+=1;continue}if(X==="\r"||X===`
|
|
25
|
+
`)J.push("enter");else if(X==="\x03")J.push("escape");else if(X&&X>=" ")J.push("char");z+=1}return J}var v4=`${String.fromCharCode(27)}\\[[0-9;]*m`,NZ=new RegExp(v4,"g"),LZ=new RegExp(`^${v4}`);function h4($){return $.replace(NZ,"")}function p0($,Z){if(Z<=0)return"";if(h4($).length<=Z)return $;let J=Z>=3?"...":".".repeat(Z),z=Math.max(0,Z-J.length),X="",G=0,Q=0;while(G<$.length&&Q<z){if($[G]==="\x1B"){let W=$.slice(G).match(LZ);if(W){X+=W[0],G+=W[0].length;continue}}X+=$[G],G+=1,Q+=1}return X.includes("\x1B[")?`${X}${k.reset}${J}`:X+J}function M1($){return $.input.isTTY===!0}var PZ=50;function CZ($){if($==="red")return k.red;if($==="cyan")return k.cyan;return""}async function V3($,Z,J){if(!M1($))throw Error("Interactive select requires a TTY terminal");if(Z.length===0)throw Error("No menu items provided");let{input:z,output:X,signals:G}=$,Q=0,W=null,H=!1,q=0,Y=()=>{let U=X.columns??80,D=X.rows??24,B=q;if(J.clearScreen)X.write(k.clearScreen+k.moveTo(1,1));else if(B>0)X.write(k.up(B));let L=0,C=(K)=>{X.write(`${k.clearLine}${K}
|
|
26
|
+
`),L+=1},O=J.lines??[],I=1+(J.subtitle?3:0)+O.length+(O.length?1:0),T=Math.max(1,Math.min(Z.length,D-I-2-1)),m=Math.max(0,Math.min(Q-Math.floor(T/2),Math.max(0,Z.length-T))),u=Z.slice(m,m+T);if(C(`${k.dim}┌ ${k.reset}${p0(J.message,Math.max(1,U-4))}`),J.subtitle)C(`${k.dim}│${k.reset}`),C(`${k.cyan}◆${k.reset} ${p0(J.subtitle,Math.max(1,U-4))}`),C("");for(let K of O)C(`${k.cyan}│${k.reset} ${p0(K,Math.max(1,U-4))}`);if(O.length)C(`${k.cyan}│${k.reset}`);for(let K=0;K<u.length;K++){let j=u[K];if(!j)continue;let P=m+K===Q,g=CZ(j.color),E=g?`${P?"":k.dim}${g}${j.label}${k.reset}`:P?j.label:`${k.dim}${j.label}${k.reset}`;if(j.hint)E+=` ${k.dim}${j.hint}${k.reset}`;E=p0(E,Math.max(1,U-8)),C(P?`${k.cyan}│${k.reset} ${k.green}●${k.reset} ${E}`:`${k.cyan}│${k.reset} ${k.dim}○${k.reset} ${E}`)}let F=u.length<Z.length?` (${m+1}-${m+u.length}/${Z.length})`:"";C(`${k.cyan}│${k.reset} ${k.dim}${p0(`Up/Down to select | Enter: confirm | Esc: back${F}`,Math.max(1,U-6))}${k.reset}`),C(`${k.cyan}└${k.reset}`);for(let K=L;K<B;K++)C("");q=L};return new Promise((U)=>{let D=z.isRaw??!1,B=()=>{if(H)return;if(H=!0,W)clearTimeout(W);z.removeListener("data",O);try{z.setRawMode(D),z.pause(),X.write(k.show)}catch{}G?.removeListener("SIGINT",C),G?.removeListener("SIGTERM",C)},L=(I)=>{B(),U(I)},C=()=>L(null),O=(I)=>{for(let T of i9(I)){if(H)break;if(W)clearTimeout(W),W=null;switch(T){case"up":Q=(Q-1+Z.length)%Z.length,Y();break;case"down":Q=(Q+1)%Z.length,Y();break;case"enter":L(Z[Q]?.value??null);break;case"escape":L(null);break;case"escape-start":W=setTimeout(()=>L(null),PZ);break;default:break}}};G?.once("SIGINT",C),G?.once("SIGTERM",C);try{z.setRawMode(!0)}catch{B(),U(null);return}z.resume(),X.write(k.hide),Y(),z.on("data",O)})}async function j3($,Z,J=!1){if(!M1($))return!1;return await V3($,J?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:Z})??!1}import{execFile as SZ}from"node:child_process";import{promisify as TZ}from"node:util";var kZ=TZ(SZ),o9={async run($,Z,J={}){try{let z=J.env?{...process.env,...J.env}:process.env,{stdout:X,stderr:G}=await kZ($,Z,{env:z,timeout:J.timeoutMs??15000,maxBuffer:10485760});return{exitCode:0,stdout:typeof X==="string"?X:String(X),stderr:typeof G==="string"?G:String(G)}}catch(z){let X=z;return{exitCode:typeof X?.code==="number"?X.code:1,signal:typeof X?.signal==="string"?X.signal:null,...typeof X?.syscall==="string"&&(X.syscall==="spawn"||X.syscall.startsWith("spawn "))?{spawnError:!0}:{},stdout:typeof X?.stdout==="string"?X.stdout:X?.stdout!=null?String(X.stdout):"",stderr:typeof X?.stderr==="string"?X.stderr:X?.stderr!=null?String(X.stderr):String(X?.message??z)}}}};import{styleText as C3}from"node:util";import{stdout as sZ,stdin as nZ}from"node:process";import iZ from"node:readline";var m4=(()=>{let $=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(Z)=>{let J=0;$.lastIndex=0;while($.test(Z))J+=1;return Z.length-J}})(),w4=($)=>{return $===12288||$>=65281&&$<=65376||$>=65504&&$<=65510},u4=($)=>{return $===8987||$===9001||$>=12272&&$<=12287||$>=12289&&$<=12350||$>=12441&&$<=12543||$>=12549&&$<=12591||$>=12593&&$<=12686||$>=12688&&$<=12771||$>=12783&&$<=12830||$>=12832&&$<=12871||$>=12880&&$<=19903||$>=65040&&$<=65049||$>=65072&&$<=65106||$>=65108&&$<=65126||$>=65128&&$<=65131||$>=127488&&$<=127490||$>=127504&&$<=127547||$>=127552&&$<=127560||$>=131072&&$<=196605||$>=196608&&$<=262141};var EZ=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,bZ=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,c4=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,fZ=/\t{1,1000}/y,p4=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,xZ=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,yZ=/\p{M}+/gu,gZ={limit:1/0,ellipsis:""},d4=($,Z={},J={})=>{let z=Z.limit??1/0,X=Z.ellipsis??"",G=Z?.ellipsisWidth??(X?d4(X,gZ,J).width:0),Q=0,W=J.controlWidth??0,H=J.tabWidth??8,q=J.emojiWidth??2,Y=2,U=J.regularWidth??1,D=J.wideWidth??2,B=[[xZ,U],[EZ,0],[bZ,W],[fZ,H],[p4,q],[c4,D]],L=0,C=0,O=$.length,I=0,T=!1,m=O,u=Math.max(0,z-G),F=0,K=0,j=0,P=0;$:while(!0){if(K>F||C>=O&&C>L){let g=$.slice(F,K)||$.slice(L,C);I=0;for(let E of g.replaceAll(yZ,"")){let v=E.codePointAt(0)||0;if(w4(v))P=2;else if(u4(v))P=D;else P=U;if(j+P>u)m=Math.min(m,Math.max(F,L)+I);if(j+P>z){T=!0;break $}I+=E.length,j+=P}F=K=0}if(C>=O)break $;for(let g=0,E=B.length;g<E;g++){let[v,Z0]=B[g];if(v.lastIndex=C,v.test($)){if(I=v===c4?m4($.slice(C,v.lastIndex)):v===p4?1:v.lastIndex-C,P=I*Z0,j+P>u)m=Math.min(m,C+Math.floor((u-j)/Z0));if(j+P>z){T=!0;break $}j+=P,F=L,K=C,C=L=v.lastIndex;continue $}}C+=1}return{width:T?u:j,index:T?m:O,truncated:T,ellipsed:T&&z>=G}},l4=d4;var vZ={limit:1/0,ellipsis:"",ellipsisWidth:0},hZ=($,Z={})=>{return l4($,vZ,Z).width},q0=hZ;var M3="\x1B",o4="",mZ=39,t9="\x07",r4="[",wZ="]",t4="m",e9=`${wZ}8;;`,a4=new RegExp(`(?:\\${r4}(?<code>\\d+)m|\\${e9}(?<uri>.*)${t9})`,"y"),s4=($)=>{if($>=30&&$<=37)return 39;if($>=90&&$<=97)return 39;if($>=40&&$<=47)return 49;if($>=100&&$<=107)return 49;if($===1||$===2)return 22;if($===3)return 23;if($===4)return 24;if($===7)return 27;if($===8)return 28;if($===9)return 29;if($===0)return 0;return},n4=($)=>`${M3}${r4}${$}${t4}`,i4=($)=>`${M3}${e9}${$}${t9}`,r9=($,Z,J)=>{let z=Z[Symbol.iterator](),X=!1,G=!1,Q=$.at(-1),W=Q===void 0?0:q0(Q),H=z.next(),q=z.next(),Y=0;while(!H.done){let U=H.value,D=q0(U);if(W+D<=J)$[$.length-1]+=U;else $.push(U),W=0;if(U===M3||U===o4)X=!0,G=Z.startsWith(e9,Y+1);if(X){if(G){if(U===t9)X=!1,G=!1}else if(U===t4)X=!1}else if(W+=D,W===J&&!q.done)$.push(""),W=0;H=q,q=z.next(),Y+=U.length}if(Q=$.at(-1),!W&&Q!==void 0&&Q.length&&$.length>1)$[$.length-2]+=$.pop()},uZ=($)=>{let Z=$.split(" "),J=Z.length;while(J){if(q0(Z[J-1]))break;J--}if(J===Z.length)return $;return Z.slice(0,J).join(" ")+Z.slice(J).join("")},cZ=($,Z,J={})=>{if(J.trim!==!1&&$.trim()==="")return"";let z="",X,G,Q=$.split(" "),W=[""],H=0;for(let U=0;U<Q.length;U++){let D=Q[U];if(J.trim!==!1){let L=W.at(-1)??"",C=L.trimStart();if(L.length!==C.length)W[W.length-1]=C,H=q0(C)}if(U!==0){if(H>=Z&&(J.wordWrap===!1||J.trim===!1))W.push(""),H=0;if(H||J.trim===!1)W[W.length-1]+=" ",H++}let B=q0(D);if(J.hard&&B>Z){let L=Z-H,C=1+Math.floor((B-L-1)/Z);if(Math.floor((B-1)/Z)<C)W.push("");r9(W,D,Z),H=q0(W.at(-1)??"");continue}if(H+B>Z&&H&&B){if(J.wordWrap===!1&&H<Z){r9(W,D,Z),H=q0(W.at(-1)??"");continue}W.push(""),H=0}if(H+B>Z&&J.wordWrap===!1){r9(W,D,Z),H=q0(W.at(-1)??"");continue}W[W.length-1]+=D,H+=B}if(J.trim!==!1)W=W.map((U)=>uZ(U));let q=W.join(`
|
|
27
|
+
`),Y=!1;for(let U=0;U<q.length;U++){let D=q[U];if(z+=D,!Y){if(Y=D>="\uD800"&&D<="\uDBFF",Y)continue}else Y=!1;if(D===M3||D===o4){a4.lastIndex=U+1;let L=a4.exec(q)?.groups;if(L?.code!==void 0){let C=Number.parseFloat(L.code);X=C===mZ?void 0:C}else if(L?.uri!==void 0)G=L.uri.length===0?void 0:L.uri}if(q[U+1]===`
|
|
28
|
+
`){if(G)z+=i4("");let B=X?s4(X):void 0;if(X&&B)z+=n4(B)}else if(D===`
|
|
29
|
+
`){if(X&&s4(X))z+=n4(X);if(G)z+=i4(G)}}return z},pZ=/\r?\n/;function D3($,Z,J){return String($).normalize().split(pZ).map((z)=>cZ(z,Z,J)).join(`
|
|
30
|
+
`)}var $0=J7(Z2(),1);function z2($,Z,J){if(!J.some((Q)=>!Q.disabled))return $;let z=$+Z,X=Math.max(J.length-1,0),G=z<0?X:z>X?0:z;return J[G]?.disabled?z2(G,Z<0?-1:1,J):G}function N3($,Z,J,z){let X=z.split(`
|
|
31
|
+
`),G=0,Q=$;for(let H of X){if(Q<=H.length)break;Q-=H.length+1,G++}for(G=Math.max(0,Math.min(X.length-1,G+J)),Q=Math.min(Q,X[G].length)+Z;Q<0&&G>0;)G--,Q+=X[G].length+1;for(;Q>X[G].length&&G<X.length-1;)Q-=X[G].length+1,G++;Q=Math.max(0,Math.min(X[G].length,Q));let W=0;for(let H=0;H<G;H++)W+=X[H].length+1;return W+Q}var oZ=["up","down","left","right","space","enter","cancel"],rZ=["January","February","March","April","May","June","July","August","September","October","November","December"],G0={actions:new Set(oZ),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,accessible:void 0,date:{monthNames:[...rZ],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:($,Z)=>`There are only ${$} days in ${Z}`,afterMin:($)=>`Date must be on or after ${$.toISOString().slice(0,10)}`,beforeMax:($)=>`Date must be on or before ${$.toISOString().slice(0,10)}`}}};function tZ($){if($!==void 0)return $;if(G0.accessible!==void 0)return G0.accessible;let Z=process.env.ACCESSIBLE;return Z!==void 0&&Z!==""&&Z!=="0"&&Z!=="false"}function z7($,Z){if(typeof $=="string")return G0.aliases.get($)===Z;for(let J of $)if(J!==void 0&&z7(J,Z))return!0;return!1}function eZ($,Z){if($===Z)return;let J=$.split(`
|
|
32
32
|
`),z=Z.split(`
|
|
33
|
-
`),X=Math.max(J.length,z.length),G=[];for(let Q=0;Q<X;Q++)J[Q]!==z[Q]&&G.push(Q);return{lines:G,numLinesBefore:J.length,numLinesAfter:z.length,numLines:X}}var
|
|
34
|
-
`),
|
|
35
|
-
`).length-1;this.output.write(
|
|
36
|
-
`);this.output.write(Q[G]),this._prevFrame=$,this.output.write(
|
|
33
|
+
`),X=Math.max(J.length,z.length),G=[];for(let Q=0;Q<X;Q++)J[Q]!==z[Q]&&G.push(Q);return{lines:G,numLinesBefore:J.length,numLinesAfter:z.length,numLines:X}}var rq=globalThis.process.platform.startsWith("win"),O3=Symbol("clack:cancel");function A3($){return $===O3}function L3($,Z){let J=$;J.isTTY&&J.setRawMode(Z)}var X7=($)=>("rows"in $)&&typeof $.rows=="number"?$.rows:20;function G7($,Z){if("~standard"in $){let J=$["~standard"].validate(Z);return J instanceof Promise?J.then((z)=>z.issues?.at(0)?.message):J.issues?.at(0)?.message}return $(Z)}class D1{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return tZ(this.opts.accessible)}constructor($,Z=!0){let{input:J=nZ,output:z=sZ,render:X,signal:G,...Q}=$;this.opts=Q,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=X.bind(this),this._track=Z,this._abortSignal=G,this.input=J,this.output=z}unsubscribe(){this._subscribers.clear()}setSubscriber($,Z){let J=this._subscribers.get($)??[];J.push(Z),this._subscribers.set($,J)}on($,Z){this.setSubscriber($,{cb:Z})}once($,Z){this.setSubscriber($,{cb:Z,once:!0})}emit($,...Z){let J=this._subscribers.get($)??[],z=[];for(let X of J)X.cb(...Z),X.once&&z.push(()=>J.splice(J.indexOf(X),1));for(let X of z)X()}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(O3);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=iZ.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),L3(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write($0.cursor.show),this.output.off("resize",this.render),L3(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write($0.cursor.show),this.output.off("resize",this.render),L3(this.input,!1),$(O3)})})}_isActionKey($,Z){return $==="\t"}_shouldSubmit($,Z){return!0}_setValue($){this.value=$,this.emit("value",this.value)}_setUserInput($,Z){this.userInput=$??"",this.emit("userInput",this.userInput),Z&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}async onKeypress($,Z){if(this.state!=="validating"){if(this._track&&Z.name!=="return"&&(Z.name&&this._isActionKey($,Z)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),Z?.name&&(!this._track&&G0.aliases.has(Z.name)&&this.emit("cursor",G0.aliases.get(Z.name)),G0.actions.has(Z.name)&&this.emit("cursor",Z.name)),$&&($.toLowerCase()==="y"||$.toLowerCase()==="n")&&this.emit("confirm",$.toLowerCase()==="y"),this.emit("key",$,Z),Z?.name==="return"&&this._shouldSubmit($,Z)){if(this.opts.validate){let J=G7(this.opts.validate,this.value),z;J instanceof Promise?(this.state="validating",this.render(),z=await J):z=J,z&&(this.error=z instanceof Error?z.message:z,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}z7([$,Z?.name,Z?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
34
|
+
`),L3(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let $=D3(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
35
|
+
`).length-1;this.output.write($0.cursor.move(-999,$*-1))}render(){let $=D3(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if($!==this._prevFrame){if(this.state==="initial")this.output.write($0.cursor.hide);else{let Z=eZ(this._prevFrame,$),J=X7(this.output);if(this.restoreCursor(),Z){let z=Math.max(0,Z.numLinesAfter-J),X=Math.max(0,Z.numLinesBefore-J),G=Z.lines.find((Q)=>Q>=z);if(G===void 0){this._prevFrame=$;return}if(Z.lines.length===1){this.output.write($0.cursor.move(0,G-X)),this.output.write($0.erase.lines(1));let Q=$.split(`
|
|
36
|
+
`);this.output.write(Q[G]),this._prevFrame=$,this.output.write($0.cursor.move(0,Q.length-G-1));return}else if(Z.lines.length>1){if(z<X)G=z;else{let W=G-X;W>0&&this.output.write($0.cursor.move(0,W))}this.output.write($0.erase.down());let Q=$.split(`
|
|
37
37
|
`).slice(G);this.output.write(Q.join(`
|
|
38
|
-
`)),this._prevFrame=$;return}}this.output.write(e.erase.down())}this.output.write($),this.state==="initial"&&(this.state="active"),this._prevFrame=$}}}function lZ($,Z){if($===void 0||Z.length===0)return 0;let J=Z.findIndex((z)=>z.value===$);return J!==-1?J:0}function aZ($,Z){return(Z.label??String(Z.value)).toLowerCase().includes($.toLowerCase())}function sZ($,Z){if(Z)return $?Z:Z[0]}var nZ=class extends V1{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Z="";#J;#W;#G;#Q;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return M3(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let Z=this.userInput.slice(0,this.cursor),J=this.userInput.slice(this.cursor,this.cursor+1),z=this.userInput.slice(this.cursor+1);return`${Z}${M3("inverse",J)}${z}`}get options(){return typeof this.#W=="function"?this.#W():this.#W}constructor(Z){super(Z),this.#W=Z.options,this.#G=Z.placeholder,this.#Q=Z.completeOnTab===!0;let J=this.options;this.filteredOptions=[...J],this.multiple=Z.multiple===!0,this.#J=typeof Z.options=="function"?Z.filter:Z.filter??aZ;let z;if(Z.initialValue&&Array.isArray(Z.initialValue)?this.multiple?z=Z.initialValue:z=Z.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(z=[this.options[0]?.value]),z)for(let X of z){let G=J.findIndex((Q)=>Q.value===X);G!==-1&&(this.toggleSelected(X),this.#$=G)}this.focusedValue=this.options[this.#$]?.value,this.on("key",(X,G)=>this.#X(X,G)),this.on("userInput",(X)=>this.#z(X))}_isActionKey(Z,J){return Z==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&Z!==void 0&&Z!==""}#X(Z,J){let z=J.name==="up",X=J.name==="down",G=J.name==="return",Q=this.userInput===""||this.userInput==="\t",W=this.#G,H=this.options,q=W!==void 0&&W!==""&&H.some((Y)=>!Y.disabled&&(this.#J?this.#J(W,Y):!0));if(J.name==="tab"&&Q&&q){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(W,!0),this.isNavigating=!1;return}if(J.name==="tab"&&this.#Q&&!this.multiple&&this.focusedValue!==void 0){let Y=String(this.focusedValue);this._clearUserInput(),this._setUserInput(Y,!0),this.isNavigating=!1;return}z||X?(this.#$=e9(this.#$,z?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):G?this.value=sZ(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(Z){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(Z)?this.selectedValues=this.selectedValues.filter((J)=>J!==Z):this.selectedValues=[...this.selectedValues,Z]:this.selectedValues=[Z])}#z(Z){if(Z!==this.#Z){this.#Z=Z;let J=this.options;Z&&this.#J?this.filteredOptions=J.filter((G)=>this.#J?.(Z,G)):this.filteredOptions=[...J];let z=lZ(this.focusedValue,this.filteredOptions);this.#$=e9(z,0,this.filteredOptions);let X=this.filteredOptions[this.#$];X&&!X.disabled?this.focusedValue=X.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};var iZ={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function d4($){return[...$].map((Z)=>iZ[Z])}function oZ($){let Z=new Intl.DateTimeFormat($,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),J=[],z="/";for(let X of Z)X.type==="literal"?z=X.value.trim()||X.value:(X.type==="year"||X.type==="month"||X.type==="day")&&J.push({type:X.type,len:X.type==="year"?4:2});return{segments:J,separator:z}}function t9($){return Number.parseInt(($||"0").replace(/_/g,"0"),10)||0}function j3($){return{year:t9($.year),month:t9($.month),day:t9($.day)}}function $2($,Z){return new Date($||2001,Z||1,0).getDate()}function o4($){let{year:Z,month:J,day:z}=j3($);if(!Z||Z<0||Z>9999||!J||J<1||J>12||!z||z<1)return;let X=new Date(Date.UTC(Z,J-1,z));if(!(X.getUTCFullYear()!==Z||X.getUTCMonth()!==J-1||X.getUTCDate()!==z))return{year:Z,month:J,day:z}}function l4($){let Z=o4($);return Z?new Date(Date.UTC(Z.year,Z.month-1,Z.day)):void 0}function rZ($,Z,J,z){let X=J?{year:J.getUTCFullYear(),month:J.getUTCMonth()+1,day:J.getUTCDate()}:null,G=z?{year:z.getUTCFullYear(),month:z.getUTCMonth()+1,day:z.getUTCDate()}:null;return $==="year"?{min:X?.year??1,max:G?.year??9999}:$==="month"?{min:X&&Z.year===X.year?X.month:1,max:G&&Z.year===G.year?G.month:12}:{min:X&&Z.year===X.year&&Z.month===X.month?X.day:1,max:G&&Z.year===G.year&&Z.month===G.month?G.day:$2(Z.year,Z.month)}}class r4 extends V1{#$;#Z;#J;#W;#G;#Q={segmentIndex:0,positionInSegment:0};#X=!0;#z=null;inlineError="";get segmentCursor(){return{...this.#Q}}get segmentValues(){return{...this.#J}}get segments(){return this.#$}get separator(){return this.#Z}get formattedValue(){return this.#D(this.#J)}#D($){return this.#$.map((Z)=>$[Z.type]).join(this.#Z)}#H(){this._setUserInput(this.#D(this.#J)),this._setValue(l4(this.#J)??void 0)}constructor($){let Z=$.format?{segments:d4($.format),separator:$.separator??"/"}:oZ($.locale),J=$.separator??Z.separator,z=$.format?d4($.format):Z.segments,X=$.initialValue??$.defaultValue,G=X?{year:String(X.getUTCFullYear()).padStart(4,"0"),month:String(X.getUTCMonth()+1).padStart(2,"0"),day:String(X.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},Q=z.map((W)=>G[W.type]).join(J);super({...$,initialUserInput:Q},!1),this.#$=z,this.#Z=J,this.#J=G,this.#W=$.minDate,this.#G=$.maxDate,this.#H(),this.on("cursor",(W)=>this.#U(W)),this.on("key",(W,H)=>this.#j(W,H)),this.on("finalize",()=>this.#L($))}#Y(){let $=Math.max(0,Math.min(this.#Q.segmentIndex,this.#$.length-1)),Z=this.#$[$];if(Z)return this.#Q.positionInSegment=Math.max(0,Math.min(this.#Q.positionInSegment,Z.len-1)),{segment:Z,index:$}}#K($){this.inlineError="",this.#z=null;let Z=this.#Y();Z&&(this.#Q.segmentIndex=Math.max(0,Math.min(this.#$.length-1,Z.index+$)),this.#Q.positionInSegment=0,this.#X=!0)}#V($){let Z=this.#Y();if(!Z)return;let{segment:J}=Z,z=this.#J[J.type],X=!z||z.replace(/_/g,"")==="",G=Number.parseInt((z||"0").replace(/_/g,"0"),10)||0,Q=rZ(J.type,j3(this.#J),this.#W,this.#G),W;X?W=$===1?Q.min:Q.max:W=Math.max(Math.min(Q.max,G+$),Q.min),this.#J={...this.#J,[J.type]:W.toString().padStart(J.len,"0")},this.#X=!0,this.#z=null,this.#H()}#U($){if($)switch($){case"right":return this.#K(1);case"left":return this.#K(-1);case"up":return this.#V(1);case"down":return this.#V(-1)}}#j($,Z){if(Z?.name==="backspace"||Z?.sequence===""||Z?.sequence==="\b"||$===""||$==="\b"){this.inlineError="";let J=this.#Y();if(!J)return;if(!this.#J[J.segment.type].replace(/_/g,"")){this.#K(-1);return}this.#J[J.segment.type]="_".repeat(J.segment.len),this.#X=!0,this.#Q.positionInSegment=0,this.#H();return}if(Z?.name==="tab"){this.inlineError="";let J=this.#Y();if(!J)return;let z=Z.shift?-1:1,X=J.index+z;X>=0&&X<this.#$.length&&(this.#Q.segmentIndex=X,this.#Q.positionInSegment=0,this.#X=!0);return}if($&&/^[0-9]$/.test($)){let J=this.#Y();if(!J)return;let{segment:z}=J,X=!this.#J[z.type].replace(/_/g,"");if(this.#X&&this.#z!==null&&!X){let M=this.#z+$,B={...this.#J,[z.type]:M},L=this.#M(B,z);if(L){this.inlineError=L,this.#z=null,this.#X=!1;return}this.inlineError="",this.#J[z.type]=M,this.#z=null,this.#X=!1,this.#H(),J.index<this.#$.length-1&&(this.#Q.segmentIndex=J.index+1,this.#Q.positionInSegment=0,this.#X=!0);return}this.#X&&!X&&(this.#J[z.type]="_".repeat(z.len),this.#Q.positionInSegment=0),this.#X=!1,this.#z=null;let G=this.#J[z.type],Q=G.indexOf("_"),W=Q>=0?Q:Math.min(this.#Q.positionInSegment,z.len-1);if(W<0||W>=z.len)return;let H=G.slice(0,W)+$+G.slice(W+1),q=!1;if(W===0&&G==="__"&&(z.type==="month"||z.type==="day")){let M=Number.parseInt($,10);H=`0${$}`,q=M<=(z.type==="month"?1:2)}if(z.type==="year"&&(H=(G.replace(/_/g,"")+$).padStart(z.len,"_")),!H.includes("_")){let M={...this.#J,[z.type]:H},B=this.#M(M,z);if(B){this.inlineError=B;return}}this.inlineError="",this.#J[z.type]=H;let Y=H.includes("_")?void 0:o4(this.#J);if(Y){let{year:M,month:B}=Y,L=$2(M,B);this.#J={year:String(Math.max(0,Math.min(9999,M))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,B))).padStart(2,"0"),day:String(Math.max(1,Math.min(L,Y.day))).padStart(2,"0")}}this.#H();let U=H.indexOf("_");q?(this.#X=!0,this.#z=$):U>=0?this.#Q.positionInSegment=U:Q>=0&&J.index<this.#$.length-1?(this.#Q.segmentIndex=J.index+1,this.#Q.positionInSegment=0,this.#X=!0):this.#Q.positionInSegment=Math.min(W+1,z.len-1)}}#M($,Z){let{month:J,day:z}=j3($);if(Z.type==="month"&&(J<0||J>12))return z0.date.messages.invalidMonth;if(Z.type==="day"&&(z<0||z>31))return z0.date.messages.invalidDay(31,"any month")}#L($){let{year:Z,month:J,day:z}=j3(this.#J);if(Z&&J&&z){let X=$2(Z,J);this.#J={...this.#J,day:String(Math.min(z,X)).padStart(2,"0")}}this.value=l4(this.#J)??$.defaultValue??void 0}}var tZ=class extends V1{options;cursor=0;#$;getGroupItems(Z){return this.options.filter((J)=>J.group===Z)}isGroupSelected(Z){let J=this.getGroupItems(Z),z=this.value;return z===void 0?!1:J.every((X)=>z.includes(X.value))}toggleValue(){let Z=this.options[this.cursor];if(Z!==void 0)if(this.value===void 0&&(this.value=[]),Z.group===!0){let J=Z.value,z=this.getGroupItems(J);this.isGroupSelected(J)?this.value=this.value.filter((X)=>z.findIndex((G)=>G.value===X)===-1):this.value=[...this.value,...z.map((X)=>X.value)],this.value=Array.from(new Set(this.value))}else{let J=this.value.includes(Z.value);this.value=J?this.value.filter((z)=>z!==Z.value):[...this.value,Z.value]}}constructor(Z){super(Z,!1);let{options:J}=Z;this.#$=Z.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([z,X])=>[{value:z,group:!0,label:z},...X.map((G)=>({...G,group:z}))]),this.value=[...Z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:z})=>z===Z.cursorAt),this.#$?0:1),this.on("cursor",(z)=>{switch(z){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let X=this.options[this.cursor]?.group===!0;!this.#$&&X&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let X=this.options[this.cursor]?.group===!0;!this.#$&&X&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},eZ=new Set(["up","down","left","right"]);class t4 extends V1{#$=!1;#Z;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let $=this.userInput;if(this.cursor>=$.length)return`${$}█`;let Z=$.slice(0,this.cursor),J=$.slice(this.cursor,this.cursor+1),z=$.slice(this.cursor+1);return J===`
|
|
38
|
+
`)),this._prevFrame=$;return}}this.output.write($0.erase.down())}this.output.write($),this.state==="initial"&&(this.state="active"),this._prevFrame=$}}}function $J($,Z){if($===void 0||Z.length===0)return 0;let J=Z.findIndex((z)=>z.value===$);return J!==-1?J:0}function ZJ($,Z){return(Z.label??String(Z.value)).toLowerCase().includes($.toLowerCase())}function JJ($,Z){if(Z)return $?Z:Z[0]}var zJ=class extends D1{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Z="";#X;#Q;#G;#W;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return C3(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let Z=this.userInput.slice(0,this.cursor),J=this.userInput.slice(this.cursor,this.cursor+1),z=this.userInput.slice(this.cursor+1);return`${Z}${C3("inverse",J)}${z}`}get options(){return typeof this.#Q=="function"?this.#Q():this.#Q}constructor(Z){super(Z),this.#Q=Z.options,this.#G=Z.placeholder,this.#W=Z.completeOnTab===!0;let J=this.options;this.filteredOptions=[...J],this.multiple=Z.multiple===!0,this.#X=typeof Z.options=="function"?Z.filter:Z.filter??ZJ;let z;if(Z.initialValue&&Array.isArray(Z.initialValue)?this.multiple?z=Z.initialValue:z=Z.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(z=[this.options[0]?.value]),z)for(let X of z){let G=J.findIndex((Q)=>Q.value===X);G!==-1&&(this.toggleSelected(X),this.#$=G)}this.focusedValue=this.options[this.#$]?.value,this.on("key",(X,G)=>this.#z(X,G)),this.on("userInput",(X)=>this.#J(X))}_isActionKey(Z,J){return Z==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&Z!==void 0&&Z!==""}#z(Z,J){let z=J.name==="up",X=J.name==="down",G=J.name==="return",Q=this.userInput===""||this.userInput==="\t",W=this.#G,H=this.options,q=W!==void 0&&W!==""&&H.some((Y)=>!Y.disabled&&(this.#X?this.#X(W,Y):!0));if(J.name==="tab"&&Q&&q){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(W,!0),this.isNavigating=!1;return}if(J.name==="tab"&&this.#W&&!this.multiple&&this.focusedValue!==void 0){let Y=String(this.focusedValue);this._clearUserInput(),this._setUserInput(Y,!0),this.isNavigating=!1;return}z||X?(this.#$=z2(this.#$,z?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):G?this.value=JJ(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(Z){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(Z)?this.selectedValues=this.selectedValues.filter((J)=>J!==Z):this.selectedValues=[...this.selectedValues,Z]:this.selectedValues=[Z])}#J(Z){if(Z!==this.#Z){this.#Z=Z;let J=this.options;Z&&this.#X?this.filteredOptions=J.filter((G)=>this.#X?.(Z,G)):this.filteredOptions=[...J];let z=$J(this.focusedValue,this.filteredOptions);this.#$=z2(z,0,this.filteredOptions);let X=this.filteredOptions[this.#$];X&&!X.disabled?this.focusedValue=X.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};var XJ={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function $7($){return[...$].map((Z)=>XJ[Z])}function GJ($){let Z=new Intl.DateTimeFormat($,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),J=[],z="/";for(let X of Z)X.type==="literal"?z=X.value.trim()||X.value:(X.type==="year"||X.type==="month"||X.type==="day")&&J.push({type:X.type,len:X.type==="year"?4:2});return{segments:J,separator:z}}function J2($){return Number.parseInt(($||"0").replace(/_/g,"0"),10)||0}function P3($){return{year:J2($.year),month:J2($.month),day:J2($.day)}}function X2($,Z){return new Date($||2001,Z||1,0).getDate()}function Q7($){let{year:Z,month:J,day:z}=P3($);if(!Z||Z<0||Z>9999||!J||J<1||J>12||!z||z<1)return;let X=new Date(Date.UTC(Z,J-1,z));if(!(X.getUTCFullYear()!==Z||X.getUTCMonth()!==J-1||X.getUTCDate()!==z))return{year:Z,month:J,day:z}}function Z7($){let Z=Q7($);return Z?new Date(Date.UTC(Z.year,Z.month-1,Z.day)):void 0}function QJ($,Z,J,z){let X=J?{year:J.getUTCFullYear(),month:J.getUTCMonth()+1,day:J.getUTCDate()}:null,G=z?{year:z.getUTCFullYear(),month:z.getUTCMonth()+1,day:z.getUTCDate()}:null;return $==="year"?{min:X?.year??1,max:G?.year??9999}:$==="month"?{min:X&&Z.year===X.year?X.month:1,max:G&&Z.year===G.year?G.month:12}:{min:X&&Z.year===X.year&&Z.month===X.month?X.day:1,max:G&&Z.year===G.year&&Z.month===G.month?G.day:X2(Z.year,Z.month)}}class W7 extends D1{#$;#Z;#X;#Q;#G;#W={segmentIndex:0,positionInSegment:0};#z=!0;#J=null;inlineError="";get segmentCursor(){return{...this.#W}}get segmentValues(){return{...this.#X}}get segments(){return this.#$}get separator(){return this.#Z}get formattedValue(){return this.#V(this.#X)}#V($){return this.#$.map((Z)=>$[Z.type]).join(this.#Z)}#H(){this._setUserInput(this.#V(this.#X)),this._setValue(Z7(this.#X)??void 0)}constructor($){let Z=$.format?{segments:$7($.format),separator:$.separator??"/"}:GJ($.locale),J=$.separator??Z.separator,z=$.format?$7($.format):Z.segments,X=$.initialValue??$.defaultValue,G=X?{year:String(X.getUTCFullYear()).padStart(4,"0"),month:String(X.getUTCMonth()+1).padStart(2,"0"),day:String(X.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},Q=z.map((W)=>G[W.type]).join(J);super({...$,initialUserInput:Q},!1),this.#$=z,this.#Z=J,this.#X=G,this.#Q=$.minDate,this.#G=$.maxDate,this.#H(),this.on("cursor",(W)=>this.#q(W)),this.on("key",(W,H)=>this.#B(W,H)),this.on("finalize",()=>this.#C($))}#Y(){let $=Math.max(0,Math.min(this.#W.segmentIndex,this.#$.length-1)),Z=this.#$[$];if(Z)return this.#W.positionInSegment=Math.max(0,Math.min(this.#W.positionInSegment,Z.len-1)),{segment:Z,index:$}}#U($){this.inlineError="",this.#J=null;let Z=this.#Y();Z&&(this.#W.segmentIndex=Math.max(0,Math.min(this.#$.length-1,Z.index+$)),this.#W.positionInSegment=0,this.#z=!0)}#F($){let Z=this.#Y();if(!Z)return;let{segment:J}=Z,z=this.#X[J.type],X=!z||z.replace(/_/g,"")==="",G=Number.parseInt((z||"0").replace(/_/g,"0"),10)||0,Q=QJ(J.type,P3(this.#X),this.#Q,this.#G),W;X?W=$===1?Q.min:Q.max:W=Math.max(Math.min(Q.max,G+$),Q.min),this.#X={...this.#X,[J.type]:W.toString().padStart(J.len,"0")},this.#z=!0,this.#J=null,this.#H()}#q($){if($)switch($){case"right":return this.#U(1);case"left":return this.#U(-1);case"up":return this.#F(1);case"down":return this.#F(-1)}}#B($,Z){if(Z?.name==="backspace"||Z?.sequence===""||Z?.sequence==="\b"||$===""||$==="\b"){this.inlineError="";let J=this.#Y();if(!J)return;if(!this.#X[J.segment.type].replace(/_/g,"")){this.#U(-1);return}this.#X[J.segment.type]="_".repeat(J.segment.len),this.#z=!0,this.#W.positionInSegment=0,this.#H();return}if(Z?.name==="tab"){this.inlineError="";let J=this.#Y();if(!J)return;let z=Z.shift?-1:1,X=J.index+z;X>=0&&X<this.#$.length&&(this.#W.segmentIndex=X,this.#W.positionInSegment=0,this.#z=!0);return}if($&&/^[0-9]$/.test($)){let J=this.#Y();if(!J)return;let{segment:z}=J,X=!this.#X[z.type].replace(/_/g,"");if(this.#z&&this.#J!==null&&!X){let D=this.#J+$,B={...this.#X,[z.type]:D},L=this.#D(B,z);if(L){this.inlineError=L,this.#J=null,this.#z=!1;return}this.inlineError="",this.#X[z.type]=D,this.#J=null,this.#z=!1,this.#H(),J.index<this.#$.length-1&&(this.#W.segmentIndex=J.index+1,this.#W.positionInSegment=0,this.#z=!0);return}this.#z&&!X&&(this.#X[z.type]="_".repeat(z.len),this.#W.positionInSegment=0),this.#z=!1,this.#J=null;let G=this.#X[z.type],Q=G.indexOf("_"),W=Q>=0?Q:Math.min(this.#W.positionInSegment,z.len-1);if(W<0||W>=z.len)return;let H=G.slice(0,W)+$+G.slice(W+1),q=!1;if(W===0&&G==="__"&&(z.type==="month"||z.type==="day")){let D=Number.parseInt($,10);H=`0${$}`,q=D<=(z.type==="month"?1:2)}if(z.type==="year"&&(H=(G.replace(/_/g,"")+$).padStart(z.len,"_")),!H.includes("_")){let D={...this.#X,[z.type]:H},B=this.#D(D,z);if(B){this.inlineError=B;return}}this.inlineError="",this.#X[z.type]=H;let Y=H.includes("_")?void 0:Q7(this.#X);if(Y){let{year:D,month:B}=Y,L=X2(D,B);this.#X={year:String(Math.max(0,Math.min(9999,D))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,B))).padStart(2,"0"),day:String(Math.max(1,Math.min(L,Y.day))).padStart(2,"0")}}this.#H();let U=H.indexOf("_");q?(this.#z=!0,this.#J=$):U>=0?this.#W.positionInSegment=U:Q>=0&&J.index<this.#$.length-1?(this.#W.segmentIndex=J.index+1,this.#W.positionInSegment=0,this.#z=!0):this.#W.positionInSegment=Math.min(W+1,z.len-1)}}#D($,Z){let{month:J,day:z}=P3($);if(Z.type==="month"&&(J<0||J>12))return G0.date.messages.invalidMonth;if(Z.type==="day"&&(z<0||z>31))return G0.date.messages.invalidDay(31,"any month")}#C($){let{year:Z,month:J,day:z}=P3(this.#X);if(Z&&J&&z){let X=X2(Z,J);this.#X={...this.#X,day:String(Math.min(z,X)).padStart(2,"0")}}this.value=Z7(this.#X)??$.defaultValue??void 0}}var WJ=class extends D1{options;cursor=0;#$;getGroupItems(Z){return this.options.filter((J)=>J.group===Z)}isGroupSelected(Z){let J=this.getGroupItems(Z),z=this.value;return z===void 0?!1:J.every((X)=>z.includes(X.value))}toggleValue(){let Z=this.options[this.cursor];if(Z!==void 0)if(this.value===void 0&&(this.value=[]),Z.group===!0){let J=Z.value,z=this.getGroupItems(J);this.isGroupSelected(J)?this.value=this.value.filter((X)=>z.findIndex((G)=>G.value===X)===-1):this.value=[...this.value,...z.map((X)=>X.value)],this.value=Array.from(new Set(this.value))}else{let J=this.value.includes(Z.value);this.value=J?this.value.filter((z)=>z!==Z.value):[...this.value,Z.value]}}constructor(Z){super(Z,!1);let{options:J}=Z;this.#$=Z.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([z,X])=>[{value:z,group:!0,label:z},...X.map((G)=>({...G,group:z}))]),this.value=[...Z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:z})=>z===Z.cursorAt),this.#$?0:1),this.on("cursor",(z)=>{switch(z){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let X=this.options[this.cursor]?.group===!0;!this.#$&&X&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let X=this.options[this.cursor]?.group===!0;!this.#$&&X&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},HJ=new Set(["up","down","left","right"]);class H7 extends D1{#$=!1;#Z;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let $=this.userInput;if(this.cursor>=$.length)return`${$}█`;let Z=$.slice(0,this.cursor),J=$.slice(this.cursor,this.cursor+1),z=$.slice(this.cursor+1);return J===`
|
|
39
39
|
`?`${Z}█
|
|
40
|
-
${z}`:`${Z}${
|
|
40
|
+
${z}`:`${Z}${C3("inverse",J)}${z}`}get cursor(){return this._cursor}#X($){if(this.userInput.length===0){this._setUserInput($);return}this._setUserInput(this.userInput.slice(0,this.cursor)+$+this.userInput.slice(this.cursor))}#Q($){let Z=this.value??"";switch($){case"up":this._cursor=N3(this._cursor,0,-1,Z);return;case"down":this._cursor=N3(this._cursor,0,1,Z);return;case"left":this._cursor=N3(this._cursor,-1,0,Z);return;case"right":this._cursor=N3(this._cursor,1,0,Z);return}}_shouldSubmit($,Z){if(this.#Z)return this.focused==="submit"?!0:(this.#X(`
|
|
41
41
|
`),this._cursor++,!1);let J=this.#$;return this.#$=!0,J&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
|
|
42
|
-
`&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#
|
|
43
|
-
`),this._cursor++,!1)}constructor($){let Z=$.initialUserInput??$.initialValue;super({...$,initialUserInput:Z},!1),Z!==void 0&&(this._cursor=Z.length),this.#Z=$.showSubmit??!1,this.on("key",(J,z)=>{if(z?.name&&
|
|
44
|
-
`:""}${
|
|
45
|
-
`,z=$.placeholder&&$.placeholder.length>0?
|
|
42
|
+
`&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#X(`
|
|
43
|
+
`),this._cursor++,!1)}constructor($){let Z=$.initialUserInput??$.initialValue;super({...$,initialUserInput:Z},!1),Z!==void 0&&(this._cursor=Z.length),this.#Z=$.showSubmit??!1,this.on("key",(J,z)=>{if(z?.name&&HJ.has(z.name)){this.#$=!1,this.#Q(z.name);return}if(J==="\t"&&this.#Z){this.focused=this.focused==="editor"?"submit":"editor";return}if(z?.name!=="return"){if(this.#$=!1,z?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(z?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}J&&(this.#Z&&this.focused==="submit"&&(this.focused="editor"),this.#X(J??""),this._cursor++)}}),this.on("userInput",(J)=>{this._setValue(J)}),this.on("finalize",()=>{this.value||(this.value=$.defaultValue),this.value===void 0&&(this.value="")})}}class G2 extends D1{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let $=this.userInput;if(this.cursor>=$.length)return`${this.userInput}█`;let Z=$.slice(0,this.cursor),J=$.slice(this.cursor,this.cursor+1),z=$.slice(this.cursor+1);return`${Z}${C3("inverse",J)}${z}`}get cursor(){return this._cursor}constructor($){super({...$,initialUserInput:$.initialUserInput??$.initialValue}),this.on("userInput",(Z)=>{this._setValue(Z)}),this.on("finalize",()=>{this.value||(this.value=$.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as x,stripVTControlCharacters as UK}from"node:util";import Q0 from"node:process";var U7=J7(Z2(),1);function YJ(){if(Q0.platform!=="win32")return Q0.env.TERM!=="linux";return Boolean(Q0.env.CI)||Boolean(Q0.env.WT_SESSION)||Boolean(Q0.env.TERMINUS_SUBLIME)||Q0.env.ConEmuTask==="{cmd::Cmder}"||Q0.env.TERM_PROGRAM==="Terminus-Sublime"||Q0.env.TERM_PROGRAM==="vscode"||Q0.env.TERM==="xterm-256color"||Q0.env.TERM==="alacritty"||Q0.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var UJ=YJ();var y=($,Z)=>UJ?$:Z,Y7=y("◆","*"),qJ=y("■","x"),KJ=y("▲","x"),FJ=y("◇","o"),BK=y("┌","T"),d0=y("│","|"),Q2=y("└","—"),VK=y("┐","T"),jK=y("┘","—"),MK=y("●",">"),DK=y("○"," "),NK=y("◻","[•]"),LK=y("◼","[+]"),PK=y("◻","[ ]"),CK=y("▪","•"),OK=y("─","-"),AK=y("╮","+"),_K=y("├","+"),IK=y("╯","+"),RK=y("╰","+"),SK=y("╭","+"),TK=y("●","•"),kK=y("◆","*"),EK=y("▲","!"),bK=y("■","x"),BJ=($)=>{switch($){case"initial":case"active":return x("cyan",Y7);case"cancel":return x("red",qJ);case"error":return x("yellow",KJ);case"submit":return x("green",FJ);case"validating":return x("dim",Y7)}};var fK=[`${x("dim","↑/↓")} to navigate`,`${x("dim","Space:")} select`,`${x("dim","Enter:")} confirm`];var xK={light:y("─","-"),heavy:y("━","="),block:y("█","#")};var yK=[`${x("dim","↑/↓")} to navigate`,`${x("dim","Enter:")} confirm`];var gK=`${x("gray",d0)} `;var q7=($)=>new G2({validate:$.validate,placeholder:$.placeholder,defaultValue:$.defaultValue,initialValue:$.initialValue,output:$.output,signal:$.signal,input:$.input,render(){let Z=$?.withGuide??G0.withGuide,J=`${`${Z?`${x("gray",d0)}
|
|
44
|
+
`:""}${BJ(this.state)} `}${$.message}
|
|
45
|
+
`,z=$.placeholder&&$.placeholder.length>0?x("inverse",$.placeholder[0])+x("dim",$.placeholder.slice(1)):x(["inverse","hidden"],"_"),X=this.userInput?this.userInputWithCursor:z,G=this.value??"";switch(this.state){case"validating":{let Q=Z?`${x("cyan",d0)} `:"",W=Z?x("cyan",Q2):"",H=x("dim",X),q=x("dim","Validating...");return`${J}${Q}${H}
|
|
46
46
|
${W} ${q}
|
|
47
|
-
`}case"error":{let Q=this.error?` ${
|
|
47
|
+
`}case"error":{let Q=this.error?` ${x("yellow",this.error)}`:"",W=Z?`${x("yellow",d0)} `:"",H=Z?x("yellow",Q2):"";return`${J.trim()}
|
|
48
48
|
${W}${X}
|
|
49
49
|
${H}${Q}
|
|
50
|
-
`}case"submit":{let Q=G?`${Z?" ":""}${
|
|
51
|
-
${W}`:""}`}default:{let Q=Z?`${
|
|
50
|
+
`}case"submit":{let Q=G?`${Z?" ":""}${x("dim",G)}`:"",W=Z?x("gray",d0):"";return`${J}${W}${Q}`}case"cancel":{let Q=G?` ${x(["strikethrough","dim"],G)}`:"",W=Z?x("gray",d0):"";return`${J}${W}${Q}${G.trim()?`
|
|
51
|
+
${W}`:""}`}default:{let Q=Z?`${x("cyan",d0)} `:"",W=Z?x("cyan",Q2):"";return`${J}${Q}${X}
|
|
52
52
|
${W}
|
|
53
|
-
`}}}}).prompt();import{authorize as
|
|
54
|
-
`)}function
|
|
55
|
-
`);if($.some((K)=>
|
|
53
|
+
`}}}}).prompt();import{authorize as VJ,exchange as jJ,resolveClaudeCodeIdentity as MJ}from"@cortexkit/anthropic-auth-core";async function K7($,Z={authorize:VJ,exchange:jJ,resolveClaudeCodeIdentity:MJ,text:q7,isCancel:A3,print:console.log}){let J=await Z.authorize("max");Z.print(`Claude sign-in for ${$==="pi"?"Pi":"OpenCode"}`),Z.print(J.url);let z=await Z.text({message:"Paste the Claude callback URL or authorization code:"});if(Z.isCancel(z))throw Error("Claude sign-in cancelled");let X=await Z.exchange(z,J.verifier,J.redirectUri,J.state);if(X.type!=="success")throw Error("Claude sign-in failed");let G=await Z.resolveClaudeCodeIdentity(X.access,void 0,void 0);if(!G.accountUuid)throw Error("Claude sign-in did not establish an account UUID");return{accountIdentity:G.accountUuid,credential:{type:"oauth",access:X.access,refresh:X.refresh,expires:X.expires}}}var F7='Warning: OpenCode holds a separate Anthropic OAuth login. Remove the separate OpenCode Anthropic login, then choose "Claude via credential vault". Setup has left that login unchanged.',EJ="npx @cortexkit/opencode-anthropic-auth setup",W2="--remove-pi-auth",I3="--restore-legacy",N7="-y",L7=["--help","-h"],B7=[{label:W2,description:"Agree in advance to move a stored Pi Anthropic login out of the way: into the local account pool, or aside privately for vault use (restored on disconnect)."},{label:I3,description:"Move anthropic-auth's state from the CortexKit state folder back into OpenCode's config folder, for example before going back to an older version. Close every OpenCode, OpenCode 2 server and Pi first. Use it on its own."},{label:N7,description:"Same as --yes."},{label:L7.join(", "),description:"Show this help."}];function bJ(){let $=Math.max(...B7.map((Z)=>Z.label.length));return[kJ({command:EJ}),"","Also accepted by this command:",...B7.map((Z)=>` ${Z.label.padEnd($)} ${Z.description}`),"","--login cannot be combined with --claustrum, or with --opencode=2: for OpenCode 2, sign in from OpenCode itself."].join(`
|
|
54
|
+
`)}function K0($,Z){let J=$.get(Z);if(!J)throw Error("Missing setup plan");return J}async function P7($=[],Z={}){let J={...Z.env??process.env},z=Z.terminal??{input:process.stdin,output:process.stdout,signals:process},X=(K)=>z.output.write(`${K}
|
|
55
|
+
`);if($.some((K)=>L7.includes(K)))return X(bJ()),0;if($.includes(I3))return fJ($,Z,J,X);let G=$.filter((K)=>K!==W2).map((K)=>K===N7?"--yes":K),Q=G.includes("--login");if(Q&&G.includes("--claustrum"))return X("Local sign-in and vault setup are two separate choices. Use --login or --claustrum, not both."),1;if(Q&&G.includes("--opencode=2"))return X(_3),1;let W=Z.runner??o9,H=Z.fence??D7(W,{platform:Z.platform}),q=Z.migrateLocal??Q4,Y=new Map,U=new Map,D=new Map,B=new Map,L=[],C=!1,O="setup-process-check",I=(K)=>({env:J,fence:H,paths:D.get(K),removePiAnthropicAuth:B.get(K)??!1}),T=(K)=>({...I(K),runner:W});async function m(K){if(!K.hosts.includes("pi"))return;let j=K0(D,"pi");if((await f1("pi",j.hostAuthPath)).kind==="absent")return;{let v=await CJ({env:J,authPath:j.hostAuthPath}).inspect();if(v.slot==="placeholder"&&v.stash==="missing")throw new PJ("missing-stash");if(K.mode==="claustrum"){if(v.slot==="placeholder")return}}if($.includes(W2)){B.set("pi",!0);return}let g=K.mode==="claustrum"?"Pi has stored Anthropic authentication. Rerun with --remove-pi-auth to preserve it privately during vault use and restore it on disconnect.":"Pi has a stored Anthropic login. Rerun with --remove-pi-auth to move it into the native account pool.";if(G.includes("--yes")||!z.input.isTTY)throw new i(g);if(!await j3(z,K.mode==="claustrum"?"Move Pi authentication aside privately for vault use, then restore it on disconnect?":"Move the Pi Anthropic OAuth login into the native account pool and remove its stored copy?"))throw new i("Native account-pool setup cannot finish while the stored Pi OAuth token takes precedence.");B.set("pi",!0)}async function u(K,j){let P=K0(U,K);if(await AJ(K,J)!==(j?"claustrum":P.priorMode)||await x1(K,T(K))!==P.fingerprint)throw new i("Setup inputs changed. Rerun setup with all hosts stopped.")}let F={packages:{opencode:V7,pi:j7},version:await M7(),displayName:"CortexKit Anthropic Auth",slashCommand:"/claude",vault:{connectionFile:A9(J.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE&&!J.OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE?"pi":"opencode",J),hosts:{opencode:{name:m0.opencode,paths:O9("opencode",J)},pi:{name:m0.pi,paths:O9("pi",J)}}},async beforeSignIn(K,j){if(O=j.mode==="claustrum"?"setup-activation":"cli-setup",!C){if(IJ(J),j.hosts.includes("opencode")){let P=await NJ({role:"setup",env:J});if(P.kind!=="state-home"&&P.registration)L.push(P.registration)}for(let P of j.hosts)D.set(P,await D0(P,J));if(await e$([...D.values()]),j.hosts.includes("pi"))L.push((await LJ({paths:K0(D,"pi").paths,role:"setup"})).registration);if(j.mode==="claustrum"){let P=j.hosts.map((E)=>A9(E,J)),g=P[0];if(new Set(P).size!==1||!g)throw new i("Selected hosts use different vault connection files.");F.vault.connectionFile=g}if(j.mode==="local"&&Q&&j.hosts.includes("opencode")&&j.opencodeGeneration==="2")throw new i(_3);if(j.mode==="local"){await T9(j.hosts,J);for(let P of j.hosts)await u0(P,I(P))()}await m(j);for(let P of j.hosts)if(j.mode==="claustrum"){if(U.set(P,await(Z.vaultPreflight??Y4)(P,{...T(P),inspectOpenCodeAuth:j.opencodeGeneration!=="2"})),K0(U,P).separateOpenCodeLogin)X(F7)}else Y.set(P,await E9(P,I(P),P==="opencode"&&j.opencodeGeneration==="2"));C=!0}else if(j.mode==="claustrum")await u(K,!1);else await F1(K0(Y,K),I(K))},async signInLocal(K){let j=K0(Y,K);if(!Q){if(j.generation2)X(_3);return}if(await F1(j,I(K)),await q(K,{...I(K),login:Z.localLogin??K7,preflight:j.preflight,skipMigration:j.action==="skip",beforeCommit:()=>F1(j,I(K))}),j.fingerprint=await Y3(j,J),j.notice)X(S9)},async beforeRegister(K,j){if(j==="local")await F1(K0(Y,K),I(K));else await u(K,!0),await(Z.vaultActivate??U4)(K,T(K),K0(U,K)),K0(U,K).fingerprint=await x1(K,T(K))},async migrate(K,j){if(j.mode==="claustrum"){if(await u(K,!0),K===j.hosts.at(-1)&&U.get("opencode")?.separateOpenCodeLogin)X(F7);return}let P=K0(Y,K);if(await F1(P,I(K)),Q)return;if(P.action==="migration")await q(K,{...I(K),preflight:P.preflight});else if(P.action==="empty-init")await OJ({paths:P.paths.paths,routingDestinationPath:P.paths.routingDestinationPath,env:J,processFence:u0(K,I(K))});else if(P.action==="skip"){if(await b9(P,I(K)),P.notice)X(S9)}P.fingerprint=await Y3(P,J)}};try{return await SJ(F,G,{...Z,env:J,terminal:z,runner:W,fence:H}),0}catch(K){let P=Z4(K)??g1(K)??await c0(O,K,J);if(P)X(P);for(let{host:g,outcome:E}of O4(K)??[]){if(E!=="enrolled")continue;let v=g==="opencode"?"OpenCode":"Pi";X(`${v} stays connected to the vault. In ${v}, run /claude → Accounts → Disconnect from the vault to undo it. Or run setup again to finish connecting.`)}return 1}finally{for(let K of L)K.close();for(let K of Y.values())if(K.preflight)_J(K.preflight)}}async function fJ($,Z,J,z){if($.some((Q)=>Q!==I3))return z(`${I3} runs on its own; run it without other options.`),1;let X=Z.runner??o9,G=Z.fence??D7(X,{platform:Z.platform});try{await DJ(G,J)}catch(Q){let W=K1(Q)??g1(Q);return z(W??await c0("setup-process-check",Q,J)),1}try{let Q=await(Z.restoreLegacy??RJ)({env:J});if(Q.status==="not-moved")return z(`Nothing to restore: ${Q.reason}.`),0;z(`anthropic-auth's state is back in ${Q.oldDir}.`);for(let W of Q.kept)z(`${W} changed after it was copied back and was left in place; delete it once you have checked it.`);return 0}catch(Q){if(Q instanceof TJ)return z(Q.message),1;return z(g1(Q)??await c0("cli-setup",Q,J)),1}}async function N1($){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Native account changes require offline setup without OPENCODE_AUTH_CONTENT");let Z=await mJ({role:"cli"}),J=await aJ(void 0,void 0,Z.layout),z=hJ({paths:J,host:"opencode"});try{return await z.read(),await $(z)}finally{if(Z.kind!=="state-home")Z.registration?.close();await z.close()}}async function R3(){if(await lJ("opencode",process.env)!=="local")throw Error("Disconnect from the vault first.")}function C7(){console.log(`Usage:
|
|
56
56
|
opencode-anthropic-auth setup [--yes] [--dry-run]
|
|
57
57
|
opencode-anthropic-auth login [label]
|
|
58
58
|
opencode-anthropic-auth api add [label]
|
|
@@ -63,9 +63,9 @@ Setup --yes selects every found host, including Pi. Run setup without --yes to c
|
|
|
63
63
|
Run setup --help to list every setup option.
|
|
64
64
|
Native credentials are managed by the offline setup migration.
|
|
65
65
|
Legacy import source:
|
|
66
|
-
${
|
|
66
|
+
${pJ()}`)}function H2($,Z){let J=$?.trim();if(!J)throw Error(`${Z} is required`);return J}async function k3($){let J=await($.fetchImpl??fetch)(`https://api.cloudflare.com/client/v4${$.path}`,{method:$.method,headers:{authorization:`Bearer ${$.token}`,...$.body instanceof FormData?{}:{"content-type":"application/json"},...$.headers},body:$.body}),z=await J.text(),X;try{X=JSON.parse(z)}catch{throw Error(`Cloudflare API returned ${J.status}: ${z}`)}if(!J.ok||X.success===!1){let G=X.errors?.map((Q)=>Q.message).filter(Boolean).join("; ");throw Error(G||`Cloudflare API returned ${J.status}`)}return X.result}async function nJ($,Z,J,z){return k3({token:$,method:"POST",path:`/accounts/${Z}/storage/kv/namespaces`,body:JSON.stringify({title:J}),fetchImpl:z})}async function iJ($){let Z={main_module:"worker.js",compatibility_date:"2026-04-28",bindings:[{type:"kv_namespace",name:"RELAY_STATE",namespace_id:$.kvNamespaceId},{type:"secret_text",name:"RELAY_TOKEN",text:$.relayToken}]},J=new FormData;return J.set("metadata",JSON.stringify(Z)),J.set("worker.js",new Blob([sJ],{type:"application/javascript+module"}),"worker.js"),k3({token:$.token,method:"PUT",path:`/accounts/${$.accountId}/workers/scripts/${$.scriptName}`,body:J,fetchImpl:$.fetchImpl})}async function oJ($,Z,J,z){await k3({token:$,method:"POST",path:`/accounts/${Z}/workers/scripts/${J}/subdomain`,body:JSON.stringify({enabled:!0,previews_enabled:!1}),fetchImpl:z})}async function rJ($,Z,J){return k3({token:$,method:"GET",path:`/accounts/${Z}/workers/subdomain`,fetchImpl:J}).catch(()=>null)}async function tJ($={}){await N1((B)=>B.read());let Z=$.fetchImpl??fetch,J=$.prompt??T3,z=$.warn??((B)=>console.warn(B)),X=H2(process.env.CLOUDFLARE_API_TOKEN?.trim()||await J("Cloudflare API token: "),"Cloudflare API token");$.secrets?.push(X);let G=H2(process.env.CLOUDFLARE_ACCOUNT_ID||await J("Cloudflare account ID: "),"Cloudflare account ID"),Q=await J("Worker name [opencode-anthropic-relay]: ")||"opencode-anthropic-relay",W=`${Q}-state`,H=cJ();$.secrets?.push(H),console.log("Creating Cloudflare KV namespace...");let q=await nJ(X,G,W,Z);console.log("Uploading relay Worker..."),await iJ({token:X,accountId:G,scriptName:Q,kvNamespaceId:q.id,relayToken:H,fetchImpl:Z}),await oJ(X,G,Q,Z).catch(async(B)=>{z(await c0("cli-relay-workers-dev",B,process.env,[X,H]))});let Y=await rJ(X,G,Z),D=(Y?.subdomain?`https://${Q}.${Y.subdomain}.workers.dev`:"")||H2(await T3("Relay Worker URL: "),"Relay Worker URL");await N1((B)=>B.updateRelay({enabled:!0,url:D,token:H,fallbackToDirect:!0,transport:"http"})),console.log(`Relay enabled at ${D}`),console.log("Relay settings saved to the native account store.")}var S3=null;async function T3($){return S3??=gJ({input:xJ,output:yJ}),(await S3.question($)).trim()}function eJ(){S3?.close(),S3=null}async function $z($,Z={}){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Local login cannot be verified while OPENCODE_AUTH_CONTENT is set");let J=Z.prompt??T3,z=Z.authorize??vJ,X=Z.exchange??wJ;await R3(),await N1(async(G)=>{let Q=await G.read(),W=$?.trim()||await J("Fallback account label (optional): "),H=await z("max");console.log(`
|
|
67
67
|
Open this URL in your browser and complete Claude sign-in:
|
|
68
68
|
`),console.log(`${H.url}
|
|
69
|
-
`);let q=await J("Paste the full callback URL or authorization code here: ");Z.secrets?.push(q);let Y=await X(q,H.verifier,H.redirectUri,H.state);if(Y.type==="failed")throw Error("Authentication failed");if(Z.secrets?.push(Y.access,Y.refresh),process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Local login cannot be verified while OPENCODE_AUTH_CONTENT is set");await
|
|
70
|
-
Saved native fallback account${W?` "${W}"`:""}.`)})}async function
|
|
71
|
-
Saved API fallback route${z?` "${z}"`:""} (${X}).`)}async function
|
|
69
|
+
`);let q=await J("Paste the full callback URL or authorization code here: ");Z.secrets?.push(q);let Y=await X(q,H.verifier,H.redirectUri,H.state);if(Y.type==="failed")throw Error("Authentication failed");if(Z.secrets?.push(Y.access,Y.refresh),process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Local login cannot be verified while OPENCODE_AUTH_CONTENT is set");await R3();let U=W&&W!=="main"?W:crypto.randomUUID(),D=Q.accounts.some((B)=>B.id===U&&B.source==="local");await G.loginOAuth({routeId:U,replace:D,label:W||void 0,credential:{access:Y.access,refresh:Y.refresh,expires:Y.expires}}),console.log(`
|
|
70
|
+
Saved native fallback account${W?` "${W}"`:""}.`)})}async function Zz($,Z={}){await R3(),await N1((H)=>H.read());let J=Z.prompt??T3,z=$?.trim()||await J("API fallback label (optional): "),X=process.env.OPENCODE_ANTHROPIC_AUTH_API_BASE_URL?.trim()||(await J("Anthropic-compatible base URL [https://api.kie.ai/claude]: ")).trim()||"https://api.kie.ai/claude";if(!dJ(X))throw Error("API fallback base URL must be an http(s) URL without embedded credentials");let G=process.env.OPENCODE_ANTHROPIC_AUTH_API_KEY?.trim()||await J("API key: ");if(!G.trim())throw Error("API key is required");Z.secrets?.push(G.trim());let W=(process.env.OPENCODE_ANTHROPIC_AUTH_API_AUTH_HEADER?.trim()||await J("Auth header [authorization-bearer|x-api-key] (default authorization-bearer): ")).trim().toLowerCase()==="x-api-key"?"x-api-key":"authorization-bearer";await N1(async(H)=>{await R3();let q=await H.read(),Y=z&&z!=="main"?z:crypto.randomUUID(),U=q.accounts.find((D)=>D.id===Y);if(U?.source==="vault")throw Error("Vault routes cannot be replaced with a local API key");await H.addApi({routeId:Y,replace:Boolean(U),label:z||void 0,apiKey:G.trim(),baseURL:X,authHeader:W})}),console.log(`
|
|
71
|
+
Saved API fallback route${z?` "${z}"`:""} (${X}).`)}async function Jz(){await N1(async($)=>{let Z=(await $.read()).accounts.filter((J)=>J.id!=="main");if(!Z.length){console.log("No native fallback accounts found.");return}for(let[J,z]of Z.entries()){let X=z.label||z.id,G=z.enabled?"enabled":"disabled";if(z.type==="api"){console.log(`${J+1}. ${X} (${G}) — API route ${z.baseURL}`);continue}let Q=z.quota?.five_hour?.remainingPercent,W=z.quota?.seven_day?.remainingPercent,H=Q===void 0&&W===void 0?"quota unknown":`5h ${Q??"?"}%, 1w ${W??"?"}% remaining`;console.log(`${J+1}. ${X} (${G}) — ${H}${z.state?` — ${uJ(z)}`:""}`)}})}async function zz($){let[Z,J,z]=process.argv.slice(2);if(!Z||Z==="help"||Z==="--help"||Z==="-h"){C7();return}if(Z==="setup"){$.stage="cli-setup";let X=await P7(process.argv.slice(3));if(X!==0)process.exitCode=X;return}if(Z==="login"){$.stage="cli-login",await $z(J,{secrets:$.secrets});return}if(Z==="api"&&J==="add"){$.stage="cli-api-add",await Zz(z,{secrets:$.secrets});return}if(Z==="list"){$.stage="cli-list",await Jz();return}if(Z==="relay"&&J==="setup"){$.stage="cli-relay-setup",await tJ({secrets:$.secrets});return}C7(),process.exitCode=1}if(g3.main==g3.module){let $={stage:"cli-command",secrets:[]};try{await zz($)}catch(Z){console.error(await c0($.stage,Z,process.env,$.secrets)),process.exitCode=1}finally{eJ()}}export{P7 as runSetupCommand,tJ as relaySetup,$z as login,Zz as addApiRoute};
|