@cortexkit/opencode-anthropic-auth 2.2.0 → 2.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +46 -46
- package/dist/index-20d6rmjj.js +2 -0
- package/dist/{index-ccrq4mra.js → index-320dcnzq.js} +1 -1
- package/dist/{index-f2ne65w4.js → index-62x1p34p.js} +1 -1
- package/dist/{index-ah5s0bew.js → index-ppdrzs41.js} +1 -1
- package/dist/{index-pden7a7y.js → index-t8aeswxz.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.d.ts +50 -0
- package/dist/sidebar-state.js +1 -1
- package/dist/tui/claude-sidebar.d.ts +5 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.js +3 -3
- package/dist/v2/tui.js +1 -1
- package/package.json +2 -2
- package/src/sidebar-state.ts +117 -0
- package/src/tui/claude-sidebar.tsx +164 -93
- package/src/tui-compiled/sidebar-state.ts +117 -0
- package/src/tui-compiled/tui/claude-sidebar.tsx +288 -231
- package/dist/index-czyrqpxc.js +0 -2
package/dist/cli.js
CHANGED
|
@@ -1,56 +1,56 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{x as s1}from"./index-0kxy8k2c.js";import{A as n9,B as R2,C as S2,D as k2,E as E2,F as i9,z as s9}from"./index-b1dvkp15.js";import{ca as x9,da as T8,ea as Q3}from"./index-f2ne65w4.js";var j$=T8((zH,T9)=>{var K$={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"},f8={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},g8={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?K$.up():"");if($)Z+=K$.left;return Z}};T9.exports={cursor:K$,scroll:f8,erase:g8,beep:"\x07"}});import{stdin as j5,stdout as M5}from"node:process";import{createInterface as F5}from"node:readline/promises";import{authorize as B5,createNativeAccountRuntime as D5,exchange as L5,formatNativeAccountState as N5,generateRelayToken as C5,getAccountStoragePath as P5,isValidApiBaseURL as O5,readNativeEnrollmentMode as _5,resolveNativePoolPaths as I5,WORKER_SCRIPT as A5}from"@cortexkit/anthropic-auth-core";import{randomUUID as z6}from"node:crypto";import{constants as E1}from"node:fs";import{lstat as Q6,mkdir as G6,open as X6}from"node:fs/promises";import{homedir as W6}from"node:os";import{isAbsolute as d2,join as o3}from"node:path";import{types as e3}from"node:util";import{createProviderErrorRedactor as n2,createWindowsOwnerOnly as H6,ensureWindowsOwnerOnlyDirectory as U6,formatLogLine as Y6,isOwnerOnly as q6,isSecretKey as V6,NativeMigrationError as K6,NativePiAuthSlotError as j6,setupEnrollment as M6}from"@cortexkit/anthropic-auth-core";import{readFile as a7}from"node:fs/promises";import{assertHostsStopped as s7,createNativeAccountRuntime as n7,discoverNativeVaultInventory as i7,inspectNativeHostAuthEntry as a3,NativePiAuthSlotError as r7,nativePiAuthSlotPaths as o7,openNativePiAuthSlot as n3,readNativeEnrollmentMode as t7,requireNoSupervisedAuthContentSnapshot as e7}from"@cortexkit/anthropic-auth-core";import{dirname as C7}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as P7,CLAUSTRUM_PI_ENROLLMENT_NAME as O7,getHostClaustrumEnrollmentPaths as _7,resolveClaustrumConnectionPath as I7}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as Tz}from"@cortexkit/claustrum-client";import{ClaustrumClient as jz}from"@cortexkit/claustrum-client";import{resolve as P$}from"node:path";import{storeIdentity as l5}from"@cortexkit/claustrum-client";import{SubcClient as s5}from"@cortexkit/subc-client";import{ClaustrumCredentialError as t9}from"@cortexkit/claustrum-client";import{SocketClosedError as e9,SocketTimeoutError as $4,SubcCallError as Z4}from"@cortexkit/subc-client";class _ extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var t1=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 L0 extends _{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function K0($){if($ instanceof L0||$ instanceof e9||$ instanceof $4)return"unreachable";let Z=$ instanceof t9||$ instanceof Z4?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(t1,Z))return"answered";return t1[Z]}var e1=300000,V1=300000,$3=1000;class s0{#$;#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 K1{#$;#z;#Z;#Q=!1;constructor($,Z){this.#$=$,this.#z=Z}get running(){return this.#Z}request(){if(this.#Z)return this.#Q=!0,this.#Z;return this.#Z=(async()=>{do{this.#Q=!1;try{await this.#$()}catch($){this.#z($)}}while(this.#Q)})().finally(()=>{this.#Z=void 0}),this.#Z}}class j1{#$;#z=new s0;#Z;#Q="polling";#H;#G;#J=!1;#U;#V=!1;#W=0;constructor($){this.#$=$,this.#Z=new K1(async()=>{let Z=this.#V;if(this.#V=!1,Z||this.#U!==this.#$.view())await this.#$.discover(this.#U??"")},(Z)=>{if(!this.#J)this.#$.onError?.(Z)})}get mode(){return this.#Q}start(){if(this.#J||this.#H||this.#G)return;if(typeof this.#$.client.watchScoped!=="function"){this.#X("fallback","client-without-watch");return}this.#j(!1)}stop(){if(this.#J)return;if(this.#J=!0,this.#G)(this.#$.clearTimeoutImpl??clearTimeout)(this.#G);this.#G=void 0;let $=this.#H;this.#H=void 0,$?.handle.stop()}#X($,Z){if(this.#Q===$)return;this.#Q=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#q($,Z){this.#G=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#G=void 0,!this.#J)Z()},$),this.#G.unref?.()}async#j($){let Z;try{Z=await this.#$.enrollmentToken()}catch(X){if(this.#J)return;this.#$.onError?.(X),this.#F("token-unreadable");return}let J=this.#$.client.watchScoped;if(this.#J||this.#H||!J)return;this.#z.restart(),this.#V=$;let z,Q;try{Q=J.call(this.#$.client,(X)=>{if(this.#J||!z||this.#H!==z)return;if(z.notices++,z.notices===1)this.#$.onReachable?.(),z.acceptedAt=(this.#$.now??Date.now)(),this.#X("watching","accepted");if(!this.#z.continuous(X))this.#V=!0;this.#U=X.view,this.#Z.request()},{enrollmentToken:Z})}catch(X){this.#$.onError?.(X),this.#F("watch-failed");return}z={handle:Q,notices:0},this.#H=z,this.#X("polling",$?"resubscribing":"opening");let G=z;Q.closed.then((X)=>this.#K(G,X),(X)=>this.#K(G,{kind:"transport_lost",error:X}))}#K($,Z){if(this.#J||this.#H!==$)return;if(this.#H=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#X("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#F("refused");try{this.#$.onRefused(Z.error)}catch(J){this.#$.onError?.(J)}return}if($.notices>0){let J=(this.#$.now??Date.now)();if($.acceptedAt!==void 0&&J-$.acceptedAt>=300000)this.#W=0;let z=Math.min(1000*2**Math.min(this.#W,16),300000);this.#W++,this.#X("polling","resubscribing"),this.#q(z,()=>void this.#j(!0));return}this.#F(Z.kind)}#F($){this.#X("fallback",$),this.#q(300000,()=>void this.#j(!1))}}var F1=60000,O$=4*F1,J4=2*F1,Z3=new Map,M1=new Map;function n0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function z4($){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 Q4($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class _${transport;key;#$=[];#z=!1;#Z=new Set;#Q=new Map;#H=new K1(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.#Z=new Set(this.#z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#Z)this.#Q.delete(Z)}catch{this.#$=[],this.#z=!1,this.#Z.clear()}},()=>{});#G=new s0;#J="polling";#U=0;#V=0;#W=new Map;#X;#q;#j={};#K=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#H.running)return this.#H.running;if(this.#J==="watching")return Promise.resolve();for(let[J,z]of M1)if($-z>=F1)M1.delete(J);let Z=M1.get(this.key);if(Z!==void 0&&$-Z<F1)return Promise.resolve();return M1.set(this.key,$),this.#H.request()}watchMode(){return this.#J}watch($={}){this.#U++;let Z=$.provider;if(Z===void 0)this.#V++;else this.#W.set(Z,(this.#W.get(Z)??0)+1);if(this.#U===1)this.#j=$,this.#M();let J=!1;return()=>{if(J)return;if(J=!0,Z===void 0)this.#V--;else{let z=(this.#W.get(Z)??1)-1;if(z>0)this.#W.set(Z,z);else this.#W.delete(Z)}if(--this.#U===0)this.#F()}}#F(){if(this.#q)(this.#j.clearTimeoutImpl??clearTimeout)(this.#q);this.#q=void 0;let $=this.#X;this.#X=void 0,$?.handle?.stop(),this.#J="polling"}#Y($){this.#q=(this.#j.setTimeoutImpl??setTimeout)(()=>{if(this.#q=void 0,this.#U>0&&!this.#X)this.#M()},$),this.#q.unref?.()}#M(){let $=this.transport.watchUsage;if(!$){this.#J="fallback";return}this.#J="polling",this.#G.restart();let Z={notices:0};this.#X=Z;let J;try{J=$.call(this.transport,(z)=>this.#N(Z,z))}catch(z){this.#B(Z,z);return}Z.handle=J,J.closed.then(()=>this.#B(Z,void 0),(z)=>this.#B(Z,z))}#N($,Z){if(this.#X!==$)return;if($.notices++,$.notices===1)this.#J="watching";if($.notices===2)this.#K=0;let J=z4(Z);if(!J)this.#G.restart();if(!(J?this.#G.continuous(J):!1)||J?.provider===void 0||this.#V>0||this.#W.has(J.provider))this.#H.request()}#B($,Z){if(this.#X!==$)return;this.#X=void 0;let J=Q4(Z);if(J==="unknown_method"||J==="usage_watch_limit"){this.#J="fallback";return}if($.notices>0){let z=Math.min($3*2**Math.min(this.#K,16),V1);this.#K++,this.#J="polling",this.#Y(z);return}if(this.#J="fallback",this.#H.request(),Z===void 0||K0(Z)==="unreachable")this.#Y(V1)}current($,Z,J){for(let z of this.#$){if(z.provider!==$||typeof z.account!=="string"||z.account.trim()!==Z)continue;if(z.stale!==void 0||z.errorClass!==void 0||!n0(z.usage))continue;let Q=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(Q)||J-Q>=O$)continue;return{entry:z,context:{fetchedAt:Q,...typeof z.source==="string"&&{source:z.source}}}}return}lookup($,Z,J){if(!this.#z)return{miss:"unreachable"};let z=this.#$.find((X)=>X.provider===$&&typeof X.account==="string"&&X.account.trim()===Z),Q=(z??this.#$.find((X)=>X.provider===$&&X.account===void 0&&X.errorClass!==void 0))?.errorClass;if(Q==="upstream_failed")return{miss:"upstream-failed"};if(Q==="credential_absent"||Q==="credential_unusable"||Q==="credential_rejected")return{miss:"credential"};if(Q!==void 0)return{miss:"unreachable"};if(z){let X=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!n0(z.usage)||!Number.isFinite(X))return{miss:"unreachable"};let W={entry:z,context:{fetchedAt:X,...typeof z.source==="string"&&{source:z.source}}};return J>=X+O$||z.stale!==void 0?{miss:"stale",reading:W}:{reading:W}}if(this.#Z.has($))return{miss:"absent"};let G=this.#Q.get($)??J;return this.#Q.set($,G),{miss:J-G>=J4?"unreachable":"cold"}}}function J3($,Z){let J=JSON.stringify([P$($.connectionFile),P$(Z)]),z=Z3.get(J);if(!z)z={source:new _$($,J),refs:0},Z3.set(J,z);z.refs++;let Q=!1;return{source:z.source,release(){if(Q)return;if(Q=!0,--z.refs===0)Z3.delete(J)}}}import{ClaustrumCredentialError as Dz}from"@cortexkit/claustrum-client";import{appendFileSync as j4,chmodSync as M4,existsSync as X3,renameSync as T$,statSync as F4}from"node:fs";import{open as B4}from"node:fs/promises";import{dirname as D4,resolve as L4}from"node:path";import{randomUUID as G4}from"node:crypto";import{lstat as R$,readFile as S$,rename as X4,unlink as I$}from"node:fs/promises";import{dirname as j0,resolve as n}from"node:path";var I=process.platform==="win32",A$=new Set;function z3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var b$;function T0(){return b$??=import("@cortexkit/private-files"),b$}class u extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor($,Z,J){let z=J;super(`Private file refused at ${Z}: ${$} (${z?.reason??z?.code??"io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`,{cause:J});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=z3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}async function l($,Z,J){try{return await J()}catch(z){if(z instanceof u)throw z;throw new u($,Z,z)}}var W4;async function X0($,Z){$=n($),Z??=W4,await l($,"safe-parent",async()=>{let J=await(await T0()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await R$($);throw new u(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function p($,Z,J=!1){if($=n($),Z==="directory")return X0($);await l($,"verify",async()=>{let z=await T0(),Q=await z.verifyOwnerOnly($),G=!1;if(!Q.ok){let{reason:X}=Q.refusal;if(X==="io-error")await z.verifyPrivatePath($,Z);if(J&&[z.EXTRA_ACE,z.NOT_PROTECTED,z.NULL_DACL,z.EMPTY_DACL].includes(X))await X0(j0($)),await z.securePrivatePath($,Z),G=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:X,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await z.verifyPrivatePath($,Z),G&&!A$.has($))A$.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function J0($,Z=!1,J){$=n($),await l($,"directory",async()=>{let z=await T0();try{return await R$($),await X0($,J)}catch(G){if(z3(G)!=="ENOENT")throw G}let Q=j0($);if(Q===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await J0(Q,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(z3(G)!=="EEXIST")throw G}await X0($,J)})}async function o($,Z=!1){if(!I)return S$($,"utf8");return(await H4($,Z)).toString("utf8")}async function H4($,Z=!1){if(!I)return S$($);if($=n($),Z)await X0(j0($)),await p($,"file",!0);return l($,"read",async()=>(await T0()).readOwnerOnly($))}async function f0($,Z){await X0(j0(n($))),await l($,"create",async()=>{await(await T0()).createPrivateFile(n($),Z)})}async function k$($){await X0(j0(n($))),await l($,"directory-create",async()=>{await(await T0()).createOwnerOnly(n($),{kind:"dir"})})}async function G3($,Z,J={}){$=n($),Z=n(Z);let z=J.now??(()=>performance.now()),Q=z(),G=J.deadline??1/0,X,W=[0,10,20,40,80,100],H,Y=0;for(let V of W){let B=Math.min(X??1/0,G);if(z()>=B)break;if(V)await(J.sleep??((F)=>new Promise((D)=>setTimeout(D,F))))(Math.min(V,Math.max(0,B-z())));if(z()>=B)break;let L=z();if(await J.beforeRename?.(),X!==void 0)X+=z()-L;if(z()>=G)break;Y++;try{return await(J.rename??X4)($,Z),{attempts:Y,elapsedMs:z()-Q}}catch(F){H??=F;let D=F;if(!(D.win32Code!==void 0?D.win32Code===32||D.win32Code===33:["EBUSY","EPERM","EACCES"].includes(D.code??"")&&!D.reason))break;X??=z()+500}}let q=new u(Z,"rename",H??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw q.attempts=Y,q.elapsedMs=z()-Q,q}async function g0($,Z,J={}){$=n($),await J0(j0($));try{await p($,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}let z=n(J.stagePath??`${$}.${G4()}.tmp`);if(j0(z)!==j0($))throw new u($,"stage-directory",{code:"EXDEV"});let Q=!1,G=!1,X={attempts:0,elapsedMs:0},W="stage-create",H=(Y)=>{try{J.onOutcome?.({path:$,stage:Y?.stage??"published",published:G,fileDurable:G,durabilityConfirmed:!1,attempts:Y?.attempts??X.attempts,elapsedMs:Y?.elapsedMs??X.elapsedMs,...Y&&{code:Y.code,win32Code:Y.win32Code}})}catch{}};try{if(await f0(z,Z),Q=!0,W="before-rename",X=await G3(z,$,J),Q=!1,G=!0,W="published-callback",J.onRenamed?.(),W="published-verify",await p($,"file"),J.durable&&J.durability!=="file-only-on-windows")throw new u($,"directory-sync-unsupported",{code:"ENOTSUP"});H()}catch(Y){let q=Y instanceof u?Y:new u($,W,Y);if(q.published=G,q.fileDurable=G,G)Object.assign(q,X);if(Q){try{await I$(z)}catch{q.orphanPath=z}Q=!1}throw H(q),q}finally{if(Q)await I$(z).catch(()=>{})}}var U4=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,Y4=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function q4($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function x0($={}){let Z=[Y4,...$.extraValuePatterns??[]].map((G)=>new RegExp(G.source,G.flags.includes("g")?G.flags:`${G.flags}g`));function J(G){let X=G.toLowerCase().replace(/[-_]/g,"");return U4.test(G)||X.includes("apikey")||X.endsWith("secret")||X.endsWith("password")||X.endsWith("token")&&!X.endsWith("tokens")||!!$.extraSecretKeys?.(X)}function z(G){let X=G,W=[["name",G.name],["message",G.message],["stack",G.stack]];for(let Y of["code","status","cause"])if(X[Y]!==void 0)W.push([Y,X[Y]]);let H=new Set(W.map(([Y])=>Y));for(let Y of Object.entries(G))if(!H.has(Y[0]))W.push(Y);return W}function Q(G,X,W,H=0){if(typeof G==="string")return Z.reduce((Y,q)=>Y.replace(q,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if(W.has(G))return"[Circular]";W.add(G);try{if(Array.isArray(G))return G.map((V)=>Q(V,X,W,H));let Y=q4(G);if(Y&&H>=8)return"[Truncated]";let q=Y?H+1:H;return Object.fromEntries((Y?z(G):Object.entries(G)).map(([V,B])=>[V,X&&J(V)?"***REDACTED***":Q(B,X,W,q)]))}finally{W.delete(G)}}return{redact:(G)=>Q(G,!0,new WeakSet),redactStrings:(G)=>Q(G,!1,new WeakSet)}}var E$=x0(),V4=E$.redact,K4=E$.redactStrings;var B1={error:0,warn:1,info:2,debug:3,trace:4},g$=5242880,x$=3;function W3($){try{M4($,384)}catch{}}function N4($){try{if(!(X3($)&&F4($).size>=g$))return;for(let J=x$-1;J>=1;J--)if(X3(`${$}.${J}`)){let z=`${$}.${J+1}`;T$(`${$}.${J}`,z),W3(z)}let Z=`${$}.1`;T$($,Z),W3(Z)}catch{}}async function W0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await l(Z,"log-close",()=>J.close())}async function f$($,Z){await J0(D4(Z));try{await p(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await f0(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await p(Z,"file",!0)}}return $.handle=await l(Z,"log-open",()=>B4(Z,"a")),$.file=Z,$.handle}async function C4($,Z,J){Z=L4(Z);try{if($.file!==Z)await W0($);let z=$.handle??await f$($,Z);if((await l(Z,"log-stat",()=>z.stat())).size>=g$){await W0($);for(let G=x$-1;G>=0;G--){let X=G===0?Z:`${Z}.${G}`,W=`${Z}.${G+1}`;try{await p(X,"file",!0)}catch(H){if(H.code==="ENOENT")continue;throw H}try{await p(W,"file",!0)}catch(H){if(H.code!=="ENOENT")throw H}await G3(X,W),await p(W,"file")}z=await f$($,Z)}await l(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await W0($).catch(()=>{}),z}}function P4($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function O4($){let Z,J,z,Q=x0(),G,X=[],W,H=Promise.resolve(),Y,q={};function V(U){let K=H.then(U);return H=K.catch((j)=>{Y=j}),K}function B(U){if(I&&U.file!==Z)V(()=>W0(q)).catch(()=>{});Z=U.file,J=U.level,Q=x0(U),G=U.captureSink}function L(U){if(U===void 0||U in B1)z=U}function F(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function D(){if(z)return z;let U=typeof J==="function"?J():J;if(U&&U in B1)return U;return"info"}function P(U=!0){if(W)clearTimeout(W),W=void 0;if(!X.length){if(I)return V(async()=>{if(U)await W0(q);if(Y)throw Y});return}let K;try{K=F()}catch{if(X=[],I&&U)return V(()=>W0(q));return}let j=X.join("");if(X=[],!K){if(I&&U)return V(()=>W0(q));return}if(I)return V(async()=>{try{await C4(q,K,j)}finally{if(U)await W0(q)}});try{if(N4(K),X3(K))W3(K);j4(K,j,{encoding:"utf8",mode:384})}catch{}}function R(){if(!W)W=setTimeout(()=>{W=void 0;let U=P(!1);if(U instanceof Promise)U.catch(()=>{})},500)}function f(U,K,j,b){if(Z===void 0&&G===void 0)return;try{if(B1[K]>B1[D()])return;let g=Q.redactStrings(j),S;try{S=Q.redact(b)}catch{S="[unserializable]"}let m=`[${new Date().toISOString()}] ${K.toUpperCase()} [${U}] ${g}`+(b===void 0?"":P4(S))+`
|
|
3
|
-
`;try{
|
|
4
|
-
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??
|
|
5
|
-
`,"utf8"),await
|
|
6
|
-
`,{deadline:performance.now()+Math.max(0,w),beforeRename:async()=>{let
|
|
7
|
-
`,"utf8"),await
|
|
8
|
-
`;if(
|
|
9
|
-
`;if(
|
|
10
|
-
`)){if(z.trim()===""||z.startsWith("#"))continue;let
|
|
11
|
-
`;if(Buffer.byteLength(Q)>P1)throw new _("invalid-state","Claustrum enrollment state is too large");if(I)return g0($,Q);let G=w4(z,`.${m4($)}.${process.pid}.${g4()}.tmp`),X,W=!1;try{X=await o$(G,"wx",384),W=!0,await X.writeFile(Q,"utf8"),await X.chmod(384),await X.sync(),await X.close(),X=void 0,await h4(G,$),W=!1}finally{if(await X?.close().catch(()=>{}),W)await e$(G).catch(()=>{})}}async function B3($,Z){let J=await O0($.tokenPath),z=J===void 0?void 0:F3(J),Q=await O0($.statePath),G=Q===void 0?void 0:M3(Q);if(z)return{state:"approved",proposedName:G?.proposedName??Z,...G?.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:z.token_generation};if(!G)return{state:"idle"};if(G.phase==="approved")return{state:"blocked",proposedName:G.proposedName,code:"missing_token"};return M0(G)}async function F0($){let Z=await O0($);if(Z===void 0)throw new _("not-enrolled","Claustrum enrollment is not configured");return F3(Z)}function M0($){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 W2(){return new _("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class D3{#$;#z;#Z;#Q;#H;#G;#J;constructor($){this.#J=$.ancestorOptions??{},this.#$=$.client,this.#z=$.paths,this.#Z=$.proposedName,this.#Q=$.now??Date.now,this.#H=$.mintSecret??(()=>f4(32).toString("hex")),this.#G=$.writeTokenFile??c4}async status(){return B3(this.#z,this.#Z)}async resetTerminal(){return H2(this.#z,this.#Z)}async#U($,Z){let J={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#Q()};return await C0(this.#z.statePath,J,this.#J),M0(J)}async reconcile(){await O1(P0(this.#z.statePath),this.#J);let $=await H0({name:"ceremony",path:this.#z.statePath,ttlMs:$2,renew:!0});if(!$)return{state:"busy"};try{let Z=await O0(this.#z.tokenPath),J=Z===void 0?void 0:F3(Z),z=await O0(this.#z.statePath),Q=z===void 0?void 0:M3(z);if(Q&&Q.proposedName!==this.#Z)throw W2();if(J){if(!Q||Q.phase==="pending"){let X={version:1,phase:"approved",proposedName:Q?.proposedName??this.#Z,tokenGeneration:J.token_generation,updatedAt:this.#Q()};await C0(this.#z.statePath,X,this.#J),Q=X}return{state:"approved",proposedName:Q.proposedName,...Q.phase==="approved"&&Q.approvedName!==void 0&&{approvedName:Q.approvedName},tokenGeneration:J.token_generation}}if(Q?.phase==="approved"){let X={version:1,phase:"blocked",proposedName:Q.proposedName,errorCode:"missing_token",updatedAt:this.#Q()};return await C0(this.#z.statePath,X,this.#J),M0(X)}if(Q&&Q.phase!=="pending")return M0(Q);if(!Q){let X=this.#Q();if(Q={version:1,phase:"pending",proposedName:this.#Z,requestSecret:this.#H(),createdAt:X,updatedAt:X},!j3.test(Q.requestSecret))throw new _("invalid-state","invalid minted Claustrum enrollment secret");await C0(this.#z.statePath,Q,this.#J)}if(!Q.requestId)try{let X=T4("sha256").update(Buffer.from(Q.requestSecret,"hex")).digest("hex"),W=await this.#$.enrollPropose({name:Q.proposedName,requestSecretHash:X});Q={...Q,requestId:W.requestId,updatedAt:this.#Q()},await C0(this.#z.statePath,Q,this.#J)}catch(X){let W=K3(X);if(!W)throw X;if(W.disposition==="retry")return{state:"pending",proposedName:Q.proposedName,retryCode:W.code};return this.#U(Q,W.code)}let G=Q.requestId;if(!G)return M0(Q);try{let X=await this.#$.enrollPoll({requestId:G,requestSecret:Q.requestSecret});if(X.status==="pending")return M0(Q);if(X.status==="denied"){let H={version:1,phase:"denied",proposedName:Q.proposedName,updatedAt:this.#Q()};return await C0(this.#z.statePath,H,this.#J),M0(H)}await O1(P0(this.#z.tokenPath),this.#J),await X2(P0(this.#z.tokenPath),this.#J),await this.#G(this.#z.tokenPath,{token:X.token,token_generation:X.tokenGeneration});let W={version:1,phase:"approved",proposedName:Q.proposedName,approvedName:X.name,tokenGeneration:X.tokenGeneration,updatedAt:this.#Q()};return await C0(this.#z.statePath,W,this.#J),M0(W)}catch(X){let W=K3(X);if(!W)throw X;if(W.disposition==="retry")return{state:"pending",proposedName:Q.proposedName,requestId:G,retryCode:W.code};return this.#U(Q,W.code)}}finally{await $.release()}}}async function H2($,Z){await O1(P0($.statePath));let J=await H0({name:"ceremony",path:$.statePath,ttlMs:$2,renew:!0});if(!J)return"busy";try{if(await O0($.tokenPath)!==void 0)return"refused-approved";let z=await O0($.statePath);if(z===void 0)return"idle";let Q=M3(z);if(Q.proposedName!==Z)throw W2();if(Q.phase==="pending")return"refused-pending";return await J.assertOwned(),await e$($.statePath),"reset"}finally{await J.release()}}var L3="claustrum-tombstone:v1:";function Y2($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function a4($,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 C3=i0("claustrum");function O3($,Z,J,z=C3){let Q=Y2(Z,J);return z.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:J?.recordVersion??null,retry:Q,reason:a4(Z,J)}),Q}var P3=300000,q2=60000;function N3(){return new _("invalid-material","Claustrum returned invalid credential material")}function s4($){let Z=$.trim();if(Z.startsWith("{")){let J;try{J=JSON.parse(Z)}catch{throw N3()}if(!J||typeof J!=="object")throw N3();let z=J,Q=z.access_token??z.access;Z=typeof Q==="string"?Q:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(L3))throw N3();return Z}function n4($,Z){if(!$.operations.includes("read"))return;if(!$.categories.includes(Z.category))return;if($.credentialType==="oauth")return $.refreshAdapter===Z.refreshAdapter?"oauth":void 0;if($.credentialType==="api_key"&&Z.apiKeys)return $.refreshAdapter===void 0?"api_key":void 0;return}function i4($){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:Q,operation:G})=>Object.freeze({selectorKind:z,selector:Q,operation:G})))})}class _1{#$;#z;#Z;#Q;#H;#G;#J;#U=new WeakMap;#V=new WeakMap;#W=new Map;#X=new WeakMap;#q;#j;#K=!1;#F=new L0;#Y;#M=!1;#N=-1/0;#B=2000;#D=!1;#O;#C=new Set;constructor($){let Z=$.tokenPath;if($.readToken)this.#z=$.readToken;else if(Z)this.#z=()=>F0(Z);else throw new _("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#Q=$.family,this.#H=$.parseIdentity,this.#G=$.requireAssertion??!1,this.#Z=$.now??Date.now,this.#J=$.logger??C3,this.#q=$.setTimeoutImpl??setTimeout,this.#j=$.clearTimeoutImpl??clearTimeout}transportLost($){if(this.#D||this.#K)return;this.#K=!0,this.#F=$ instanceof U2?$:new L0,this.#J.warn("serving kept vault receipt",{reason:"unreachable"}),this.#P()}reachable(){if(this.#D||!this.#K)return;if(this.#K=!1,this.#Y)this.#j(this.#Y);this.#Y=void 0,this.#B=2000;for(let $ of this.#W.values())$.since=null;(this.#J.info??C3.info)("vault receipt serving resumed",{reason:"reachable"})}#P(){if(this.#D||!this.#K||this.#Y||this.#M)return;this.#Y=this.#q(()=>{this.#Y=void 0,this.#A(!0)},this.#B),this.#Y.unref?.()}#A($=!1){if(this.#D||!this.#K||this.#M)return;if(this.#Z()-this.#N<1000){this.#P();return}this.#N=this.#Z(),this.#M=!0,this.#b().catch(()=>{if($&&this.#K)this.#B=Math.min(this.#B*2,30000)}).finally(()=>{this.#M=!1,this.#P()})}#L($){if(this.#D)throw new _("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#_($){this.#L($);let Z=await this.#z();if(this.#L($),!/^[0-9a-f]{64}$/.test(Z.token)||!Number.isSafeInteger(Z.token_generation)||Z.token_generation<1)throw new _("invalid-token","Invalid Claustrum enrollment token");return Z.token}async#I($,Z){this.#L(Z);let J,z;try{let Q=$();J=Z?await Promise.race([Q,new Promise((G,X)=>{let W=()=>X(Z.reason);if(Z.addEventListener("abort",W,{once:!0}),z=()=>Z.removeEventListener("abort",W),Z.aborted)W()})]):await Q}catch(Q){if(this.#L(Z),K0(Q)==="unreachable")this.transportLost(Q);else this.reachable();if(Q instanceof U2)throw Q;if(K0(Q)==="unreachable")throw new L0;throw new _("unavailable","Claustrum scoped operation unavailable")}finally{z?.()}return this.#L(Z),this.reachable(),J}async discover($){let Z=await this.#b($);return this.#O=Z.view,Z}async#b($){let Z,J;try{J=await this.#_($)}catch(H){throw this.#W.clear(),H}try{Z=await this.#I(()=>this.#$.listScoped(J),$)}catch(H){throw this.listFailed(H),H}let z=[],Q=[],G=new Map;for(let H of Z.rows){let Y=n4(H,this.#Q);if(!Y)continue;Q.push({row:H,type:Y}),G.set(H.id,(G.get(H.id)??0)+1)}let X=[];for(let{row:H,type:Y}of Q){let q;if(!H.id.trim())q="empty credential id";else if((G.get(H.id)??0)>1)q="duplicate credential id";else if(H.accountId!==void 0&&!H.accountId.trim())q="blank account identity";else if(!H.state.trim())q="empty state";if(q){z.push({...H.id.trim()&&{credentialId:H.id},reason:q});continue}X.push(Object.freeze({credentialId:H.id,credentialType:Y,...H.accountId!==void 0&&{accountIdentity:H.accountId},state:H.state,...H.email!==void 0&&{email:H.email},...H.orgName!==void 0&&{orgName:H.orgName}}))}for(let H of z)this.#J.warn("skipped malformed vault record",H);let W=i4(Z);return{view:Z.view,credentials:Object.freeze(X),skipped:Object.freeze(z),...W&&{grantReach:W}}}listFailed($){if(K0($)==="unreachable")this.transportLost($);else this.reachable(),this.#W.clear()}forget($){this.#W.delete($)}retain($){let Z=new Map($.map((J)=>[J.credentialId,J]));for(let[J,z]of this.#W){let Q=Z.get(J);if(!Q?.enabled||Q.state!=="active"||Q.credentialType!==z.attempt.credentialType||Q.accountIdentity!==z.attempt.expectedAccountIdentity)this.forget(J)}}keptReceiptState(){let $=null;for(let[Z,J]of this.#W){if(!this.#R(J.attempt)){this.forget(Z);continue}if(J.since!==null)$=Math.min($??J.since,J.since)}return Object.freeze({active:$!==null,since:$})}#R($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#Z()>q2}async authorize($,Z,J="vault"){this.#L(Z);let{credentialId:z,credentialType:Q,accountIdentity:G}=$,X=this.#W.get(z);if(X&&(X.attempt.credentialType!==Q||X.attempt.expectedAccountIdentity!==G))this.forget(z),X=void 0;let W;try{W=await this.#_(Z)}catch(H){throw this.#W.clear(),H}if(this.#K&&X)return this.#A(),this.#S(z,X,W,J);try{let H=await this.#k({credentialId:z,credentialType:Q,accountIdentity:G},W,Z);return this.#W.set(z,{attempt:H,routeId:J,since:null}),H}catch(H){if(this.#L(Z),K0(H)!=="unreachable")throw this.forget(z),H;return this.#S(z,X,W,J,H)}}#S($,Z,J,z,Q=this.#F){if(!Z||this.#W.get($)!==Z||!this.#R(Z.attempt))throw this.forget($),Q;if(Z.since===null)Z.since=this.#Z();let G=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#U.set(G,J),this.#X.set(G,z),G}async#k($,Z,J){if(!$.credentialId)throw new _("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:z,credentialType:Q,accountIdentity:G}=$;if(this.#G&&G===void 0)throw new _("identity-unasserted","Claustrum dispatch requires a known account identity");let X=await this.#I(()=>this.#$.getScoped({credentialId:z,enrollmentToken:Z,...Q==="oauth"&&{minTtlMs:P3}}),J);if(X.credentialId!==void 0&&X.credentialId!==z)throw new _("identity-changed","Claustrum served credential identity changed");let W=X.expiresAtMs;if(!Number.isSafeInteger(X.recordVersion)||X.recordVersion<0||W===null&&Q==="oauth"||W!==null&&(!Number.isFinite(W)||W-this.#Z()<P3))throw new _("insufficient-validity","Claustrum served credential has insufficient validity");let H=s4(X.material),Y=X.accountId?.trim()?X.accountId:void 0;if(this.#G&&(X.credentialId===void 0||Y===void 0))throw new _("identity-unasserted","Claustrum served credential did not assert its identity");let q=Y===void 0?this.#H?.(H):void 0,V=Y??q;if(G!==void 0&&V!==void 0&&V!==G)throw new _("identity-changed","Claustrum served credential identity changed");let B=V??G,F=Object.freeze(Object.defineProperty({credentialId:z,credentialType:Q,...B!==void 0&&{accountIdentity:B},accountIdentitySource:Y!==void 0?"asserted":q!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...X.credentialId!==void 0&&{assertedCredentialId:X.credentialId},...Y!==void 0&&{assertedAccountIdentity:Y},...X.projectId!==void 0&&{projectId:X.projectId},recordVersion:X.recordVersion,expiresAtMs:W},"accessToken",{value:H,enumerable:!1}));return this.#U.set(F,Z),F}async reportFailure($,Z,J){if(Z!==401)return;this.#L();let z=this.#U.get($);if(!z)throw new _("no-receipt","Claustrum failure report requires an original dispatch receipt");let Q=this.#X.get($);if(Q!==void 0){this.forget($.credentialId),this.#J.debug("scoped 401 not reported",{routeId:Q,reason:"kept-receipt"});return}let G=this.#W.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let X=this.#V.get($);if(X)return X;let W=this.#I(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:z,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#V.set($,W);try{await W,this.#J.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:J})}catch(H){throw this.#V.delete($),H}}watchRoster($){this.#L();let Z=new j1({client:this.#$,enrollmentToken:()=>this.#_(),view:$.view??(()=>this.#O),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.#J,now:this.#Z,setTimeoutImpl:this.#q,clearTimeoutImpl:this.#j});return this.#C.add(Z),Z.start(),{get mode(){return Z.mode},close:()=>{this.#C.delete(Z),Z.stop()}}}close(){if(this.#D)return;if(this.#D=!0,this.#Y)this.#j(this.#Y);this.#Y=void 0;for(let $ of this.#C)$.stop();this.#C.clear(),this.#W.clear(),this.#$.close()}}import{createHash as Y7}from"node:crypto";var _0="all",r4=Object.freeze(["primary"]);function K2($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function v0($,Z){return JSON.stringify([$,Z])}function I0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function a($){return typeof $==="number"&&Number.isFinite($)}function V2($){return typeof $==="string"&&$.length>0}function t($,Z,J){return $[Z]===void 0||J($[Z])}function o4($){return a($)&&$>0}function _3($){return typeof $==="string"}function t4($){if(!I0($)||!V2($.scope)||!V2($.label))return!1;switch($.kind){case"reading":return a($.checkedAt)&&a($.usedPercent)&&t($,"resetsAt",_3)&&t($,"windowMinutes",o4);case"retired":return a($.retiredAt);case"absent":return a($.checkedAt);default:return!1}}function e4($){if(!I0($)||!a($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&t($,"remainingPercent",a)&&t($,"usedPercent",a)&&t($,"resetsAt",_3)&&t($,"limit",a)&&t($,"used",a)&&t($,"remaining",a)&&t($,"unit",_3)}function j2($){return I0($)&&a($.value)&&Number.isInteger($.value)&&$.value>=0&&a($.checkedAt)}function I3($){return I0($)&&Object.values($).every(j2)}function M2($){if(!I0($))return;let Z=Object.entries($).filter(([,J])=>j2(J));return Z.length===0?void 0:Object.fromEntries(Z)}function A0($){if(y0($))return $;if(!I0($))return;let{counters:Z,...J}=$;if(!y0(J))return;let z=M2(Z);return{...J,...z===void 0?{}:{counters:z}}}function y0($){if(!I0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!t4(J))return!1;let z=v0(J.scope,J.label);if(Z.has(z))return!1;Z.add(z)}return t($,"budget",e4)&&t($,"counters",I3)}class I1 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function b1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function A1($){return typeof $==="number"&&Number.isFinite($)}function F2($){return $===void 0||typeof $==="string"&&$!==""}function B2($){return typeof $==="string"&&$!==""}function e0($,Z){return $[Z]===void 0||A1($[Z])}function A3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function $7($){return b1($)&&F2($.scope)&&B2($.label)&&A1($.usedPercent)&&A3($,"resetsAt")&&($.windowMinutes===void 0||A1($.windowMinutes)&&$.windowMinutes>0)}function Z7($){return b1($)&&F2($.scope)&&B2($.label)}function J7($){if(!b1($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&e0($,"remainingPercent")&&e0($,"usedPercent")&&A3($,"resetsAt")&&e0($,"limit")&&e0($,"used")&&e0($,"remaining")&&A3($,"unit")}function D2($){if(!b1($)||!A1($.checkedAt))return!1;let Z=$.readings??[],J=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(J))return!1;let z=new Set;for(let Q of Z){if(!$7(Q))return!1;let G=v0(Q.scope??_0,Q.label);if(z.has(G))return!1;z.add(G)}if(!J.every(Z7))return!1;return($.budget===void 0||J7($.budget))&&($.counters===void 0||I3($.counters))}function z7($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function Q7($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function G7($,Z){let J=new Map(Object.entries($??{}));for(let[z,Q]of Object.entries(Z??{})){let G=J.get(z);if(G===void 0||Q.checkedAt>=G.checkedAt)J.set(z,Q)}return J.size===0?void 0:Object.fromEntries(J)}function h0($,Z){let J=$===void 0?void 0:A0($);if($!==void 0&&J===void 0)throw new I1("stored quota map is malformed");if(!D2(Z))throw new I1("quota observation is malformed");let z=J??{limits:[]},Q=Z.checkedAt,G=new Map;for(let F of z.limits)G.set(v0(F.scope,F.label),F);let X=(F)=>{let D=G.get(F);return D===void 0||Q>=K2(D)},W=new Set;for(let F of Z.readings??[]){let D=F.scope??_0,P=v0(D,F.label);if(W.add(P),!X(P))continue;G.set(P,{scope:D,label:F.label,kind:"reading",checkedAt:Q,usedPercent:F.usedPercent,...F.resetsAt===void 0?{}:{resetsAt:F.resetsAt},...F.windowMinutes===void 0?{}:{windowMinutes:F.windowMinutes}})}for(let F of Z.coverage??[]){let D=F.scope??_0,P=v0(D,F.label);if(W.has(P)||!X(P))continue;let R=G.get(P);G.set(P,R===void 0||R.kind==="absent"?{scope:D,label:F.label,kind:"absent",checkedAt:Q}:{scope:D,label:F.label,kind:"retired",retiredAt:Q})}let{limits:H,budget:Y,counters:q,...V}=z,B=Q7(z.budget,Z.budget,Q),L=G7(z.counters,Z.counters);return{...V,limits:[...G.values()].sort(z7),...B===void 0?{}:{budget:B},...L===void 0?{}:{counters:L}}}var X7=Object.freeze({validate:y0,decode:A0,merge:h0});function L2($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function b3($,Z,J){return $.some((z)=>L2(z,Z,J))}function R3($,Z,J){let z={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((Q)=>Q.credentialId!==Z||Q.accountIdentity!==J),z]}function S3($,Z,J){return $.filter((z)=>!Z.some((Q)=>L2(z,Q,J)))}var C2="vault:";function q7($){return Y7("sha256").update($).digest("hex")}function V7($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function K7($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function B0($){return[$.credentialId,...$.aliases??[]]}function P2($,Z,J={}){let z=J.now??Date.now(),Q=J.routePrefix??C2,G=J.reservedRouteIds??new Set,X=$?.rows??[],W=[...$?.declined??[]],H=Z.skipped.length===0,Y=new Set(Z.credentials.map((N)=>N.credentialId)),q=new Set(Z.skipped.flatMap((N)=>N.credentialId===void 0?[]:[N.credentialId])),V=Z.skipped.some((N)=>N.credentialId===void 0),B=(N)=>!Y.has(N)&&(q.has(N)||V),L=new Map;for(let N of X){if(N.accountIdentity===void 0)continue;for(let U of B0(N))if(!L.has(U))L.set(U,N.accountIdentity)}let F=new Map;for(let N of Z.credentials){let U=N.accountIdentity!==void 0?{credential:N,identity:N.accountIdentity,claimed:!0}:{credential:N,identity:L.get(N.credentialId),claimed:!1},K=K7(U),j=F.get(K)??[];j.push(U),F.set(K,j)}let D=new Set,P=new Set(G),R=[],f=(N,U)=>N.credential.credentialId.localeCompare(U.credential.credentialId),v=[...F.values()].map((N)=>N.toSorted(f)).sort((N,U)=>N[0]&&U[0]?f(N[0],U[0]):0);for(let N of v){let U=N[0]?.identity,K=N.filter((k)=>k.credential.state==="active"),j=K.length?K:N,b=j.filter((k)=>k.claimed),g=b.length?b:j,S=new Set(N.map((k)=>k.credential.credentialId)),m=X.find((k)=>!D.has(k)&&B0(k).some((G0)=>S.has(G0))&&(k.accountIdentity===void 0||k.accountIdentity===U)),s=g.find((k)=>k.credential.credentialId===m?.credentialId)??g[0];if(!s)continue;let y=s.credential,c=m??(U===void 0?void 0:X.find((k)=>!D.has(k)&&k.accountIdentity===U));if(c)D.add(c);let r=c?.routeId;if(!r||G.has(r)){let k=`${Q}${y.credentialId}${U===void 0?"":`~${q7(U).slice(0,10)}`}`;r=k;for(let G0=2;P.has(r);G0++)r=`${k}~${G0}`}P.add(r);let U1=c?B0(c).filter(B):[],E0=[...new Set([...N.map((k)=>k.credential.credentialId),...U1])].filter((k)=>k!==y.credentialId).sort((k,G0)=>k.localeCompare(G0)),Y1=J.mapAccount?.(y)??{};R.push({previousIndex:c?X.indexOf(c):1/0,row:{routeId:r,credentialId:y.credentialId,credentialType:y.credentialType,...U!==void 0&&{accountIdentity:U},...E0.length&&{aliases:E0},state:y.state,label:Y1.label?.trim()||V7(y),...y.email!==void 0&&{email:y.email},...y.orgName!==void 0&&{orgName:y.orgName},enabled:![y.credentialId,...E0].some((k)=>b3(W,k,U)),addedAt:c?.addedAt??z,...c?.quota!==void 0&&{quota:c.quota},...!s.claimed&&U!==void 0&&{unclaimed:!0}}})}return X.forEach((N,U)=>{if(D.has(N)||!B0(N).some(B))return;if(P.has(N.routeId))return;let[K,...j]=B0(N).filter((S)=>!Y.has(S));if(K===void 0)return;P.add(N.routeId);let{aliases:b,...g}=N;R.push({previousIndex:U,row:{...g,credentialId:K,...j.length&&{aliases:j},stale:!0}})}),R.sort((N,U)=>N.previousIndex===U.previousIndex?N.row.credentialId.localeCompare(U.row.credentialId):N.previousIndex-U.previousIndex),{version:1,view:Z.view,complete:H,...!H&&{rejected:Z.skipped.map((N)=>({...N.credentialId!==void 0&&{credentialId:N.credentialId},reason:N.reason}))},rows:R.map((N)=>N.row),declined:W}}function k3($){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 m0($){return $===void 0||typeof $==="string"}function j7($){let Z=$1($)?A0($.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"||!m0($.accountIdentity)||!m0($.email)||!m0($.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 M7=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function N2($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!$1(J)||!m0(J.credentialId)||typeof J.reason!=="string"||!M7.has(J.reason))return;Z.push(J)}return Z}function F7($){if(!$1($)||$.version!==1||!m0($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!N2($.rejected))throw new _("invalid-state","Claustrum roster file is not valid");let Z=[];for(let Q of $.rows){let G=j7(Q);if(!G)throw new _("invalid-state","Claustrum roster file is not valid");Z.push(G)}let J=[];for(let Q of $.declined){if(!$1(Q)||typeof Q.credentialId!=="string"||!m0(Q.accountIdentity))throw new _("invalid-state","Claustrum roster file is not valid");J.push(Q)}let z=N2($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...z&&{rejected:z},rows:Z,declined:J}}async function e($){let Z;try{Z=await o($,I)}catch(z){if(z.code==="ENOENT")return;throw z}let J;try{J=JSON.parse(Z)}catch{throw new _("invalid-state","Claustrum roster file is not valid")}return F7(J)}var B7={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000},D7={name:"claustrum-roster",ttlMs:30000};async function w0($,Z,J={}){return Y3($,B7,async(z)=>{let Q=await e($),{next:G,result:X}=await Z(Q,{assertOwned:()=>z.assertOwned()});if(G)await z.assertOwned(),await r0($,G,{beforeRename:async()=>{await J.beforePublish?.(),await z.assertOwned()}});return X})}function E3($,Z){return w0($,(J)=>{let z=J?.rows.find((G)=>G.routeId===Z);if(!J||!z)throw new _("route-unavailable","Claustrum route is not in the roster");let Q=R3(J.declined,z.credentialId,z.accountIdentity);return{next:{...J,declined:Q,rows:J.rows.map((G)=>G===z?{...G,enabled:!1}:G)},result:void 0}})}function T3($,Z){return w0($,(J)=>{let z=J?.rows.find((Q)=>Q.routeId===Z);if(!J||!z)throw new _("route-unavailable","Claustrum route is not in the roster");return{next:{...J,declined:S3(J.declined,B0(z),z.accountIdentity),rows:J.rows.map((Q)=>Q===z?{...Q,enabled:!0}:Q)},result:void 0}})}function L7($,Z){if(!B0($).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")&&B0($).length===1)return"bind";return"refuse"}function f3($,Z){return w0($,(J)=>{let z=J?.rows.find((W)=>W.routeId===Z.routeId),Q=!J||!z?"refuse":L7(z,Z);if(!J||!z||Q==="refuse")return{result:!1};let G=h0(z.quota,Z.observation),X=Q==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{next:{...J,rows:J.rows.map((W)=>W===z?{...W,...X,quota:G}:W)},result:!0}})}function g3($,Z){return w0($,(J)=>{let z=J?.rows.find((G)=>G.routeId===Z.routeId);if(!J||!z||z.accountIdentity===void 0||z.accountIdentity!==Z.accountIdentity)return{result:!1};let Q=h0(z.quota,Z.observation);return{next:{...J,rows:J.rows.map((G)=>G===z?{...G,quota:Q}:G)},result:!0}})}async function x3($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z())return;let J=await H0({...D7,path:$.path,renew:!0});if(!J){let z=await e($.path);if($.signal?.throwIfAborted(),!z?.view)throw new _("roster-busy","Claustrum account discovery is already in progress");return z}try{let z=await $.custody.discover($.signal);return $.signal?.throwIfAborted(),await w0($.path,async(Q)=>{if(!await Z())return{result:void 0};$.signal?.throwIfAborted(),await J.assertOwned();let G=typeof $.projection==="function"?$.projection():$.projection,X=P2(Q,z,G);return{...JSON.stringify(Q)!==JSON.stringify(X)&&{next:X},result:X}})}finally{await J.release()}}class O2{#$;#z=new AbortController;#Z;#Q;#H;#G;#J;#U;#V;#W=!1;#X;#q;#j;#K=new Map;#F;constructor($){this.#$=$,this.#Z=$.logger??i0("claustrum")}#Y($){this.#z.signal.throwIfAborted(),$?.throwIfAborted()}async#M(){return await this.#$.isCustodyActive?.()??!0}#N($,Z){let J=H3([this.#z.signal,...Z?[Z]:[]]);return new Promise((z,Q)=>{let G=()=>{J.signal.removeEventListener("abort",X),J.dispose()},X=()=>{G(),Q(J.signal.reason)};if(J.signal.addEventListener("abort",X,{once:!0}),$.then((W)=>{if(G(),J.signal.aborted)Q(J.signal.reason);else z(W)},(W)=>{G(),Q(W)}),J.signal.aborted)X()})}async#B(){if(this.#Y(),this.#Q)return this.#Q;if(!this.#H)this.#H=this.#$.connect().then(($)=>{if(this.#z.signal.aborted)$.close(),this.#Y();if(this.#Q=new _1({client:$,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Z,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&$.insula)this.#X=J3($.insula,this.#$.tokenPath);return this.#Q}).finally(()=>{this.#H=void 0});return this.#N(this.#H)}snapshot(){return this.#J}grantReach(){let $=this.#U;return $&&this.#J?.view===$.view?$.reach:void 0}watchState(){return Object.freeze({vault:this.#q?.mode??"polling",...this.#$.insula&&{insula:this.#X?.source.watchMode()??"polling"}})}#D(){this.#q?.close(),this.#q=void 0,this.#j?.(),this.#j=void 0}keptReceiptState(){return this.#Q?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return k3(this.#J)}refresh(){if(this.#Y(),this.#G)return this.#G;return this.#G=(async()=>{if(!await this.#M()){this.#J=void 0,this.#U=void 0,this.#D(),this.#Q?.close(),this.#Q=void 0,this.#X?.release(),this.#X=void 0;return}let $=await this.#B(),Z,J=await x3({path:this.#$.rosterPath,custody:{discover:async(Q)=>{return Z=await $.discover(Q),Z}},isActive:()=>this.#M(),signal:this.#z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#Y();let z=J?.view!==this.#J?.view;if(this.#J=J,$.retain(J?.rows??[]),Z&&J?.view!==void 0)this.#U=Z.grantReach?{view:J.view,reach:Z.grantReach}:void 0;if(J&&z)this.#$.onRoster?.(J);return this.#F=(this.#$.now??Date.now)(),J})().finally(()=>{this.#G=void 0}),this.#G}start(){if(this.#W)return;this.#Y(),this.#W=!0;let $=async()=>{try{if(await this.#O())await this.refresh();await this.refreshInsulaQuota(),this.#C()}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.#V=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#V=void 0,$()},Z),this.#V.unref?.()};$()}async#O(){if(this.#q?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#F===void 0||$-this.#F>=e1)return!0;return!await this.#M()}#C(){let $=this.#Q;if(this.#z.signal.aborted||!$)return;if(this.#q??=$.watchRoster({view:()=>this.#J?.view,onView:async()=>{while(this.#G)await this.#G.catch(()=>{});await this.refresh()},onRefused:(Z)=>this.#$.onError?.(Z),onError:(Z)=>{if(!this.#z.signal.aborted)this.#$.onError?.(Z)}}),this.#$.insula&&this.#X&&!this.#j)this.#j=this.#X.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#z.signal.aborted||!await this.#M())return;try{await F0(this.#$.tokenPath),await this.#B(),await this.#X?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#z.signal.aborted||!await this.#M())return;try{return await F0(this.#$.tokenPath),this.#P($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#z.signal.aborted||!await this.#M())return;try{await F0(this.#$.tokenPath);let J=(await e(this.#$.rosterPath))?.rows.find((z)=>z.routeId===$);return this.#P(J?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute($){let Z=this.#$.insula;if(!Z||this.#z.signal.aborted||!await this.#M())return{miss:"unreachable"};try{await F0(this.#$.tokenPath);let z=(await e(this.#$.rosterPath))?.rows.find((X)=>X.routeId===$)?.accountIdentity;if(!z||!this.#X)return{miss:"unreachable"};let Q=this.#X.source.lookup(Z.provider,z,(this.#$.now??Date.now)()),G=Q.reading&&Z.normalize(Q.reading.entry,Q.reading.context);if(Q.miss)return{miss:Q.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.#K.get($)!==J.miss)this.#K.set($,J.miss),this.#Z.warn("skipped insula provider poll",{reason:J.miss});return}return this.#K.delete($),J.miss?Z():J.reading}#P($){if(!this.#$.insula||!$)return;let Z=this.#X?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){this.#Y(Z);let J=this.#J??await this.#N(this.refresh(),Z);if(!J||!await this.#M())throw this.#Q?.close(),this.#Q=void 0,this.#D(),this.#X?.release(),this.#X=void 0,new _("not-active","Claustrum scoped custody is not active");let z=await e(this.#$.rosterPath);this.#Y(Z);let Q=J.rows.find((H)=>H.routeId===$),G=z?.rows.find((H)=>H.routeId===$);if(G&&!G.enabled){if(Q)this.#Q?.forget(Q.credentialId);throw new _("route-declined","Claustrum route is disabled")}if(!Q||!G||G.state!=="active"||G.credentialId!==Q.credentialId||G.accountIdentity!==Q.accountIdentity||G.credentialType!==Q.credentialType){if(Q)this.#Q?.forget(Q.credentialId);throw new _("route-unavailable","Claustrum route is disabled, removed or changed")}let X=await this.#N(this.#B(),Z),W=H3([this.#z.signal,...Z?[Z]:[]]);try{return await X.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},W.signal,$)}finally{W.dispose()}}async reportFailure($,Z,J){if(this.#Y(),!this.#Q)throw new _("no-receipt","Claustrum dispatch receipt has no active owner");await this.#Q.reportFailure($,Z,J)}async send($,Z,J){let z=J.signal,Q=await this.authorize($,z),G=await Z(Q,z);if(G.status===401&&Q.fromKeptReceipt)return await this.reportFailure(Q,401,J.reporterSource??"direct"),G;if(G.status===401&&!z?.aborted){let X;try{X=await this.authorize($,z)}catch{}if(O3(J.site,Q,X,this.#Z))await G.body?.cancel().catch(()=>{}),Q=X,G=await Z(X,z)}if(G.status===401)await this.reportFailure(Q,401,J.reporterSource??"direct").catch((X)=>this.#$.onError?.(X)),Promise.resolve().then(()=>this.refresh()).catch((X)=>{if(!this.#z.signal.aborted)this.#$.onError?.(X)});return G}async decline($){this.#Y(),await E3(this.#$.rosterPath,$),this.#J=await e(this.#$.rosterPath),this.#Q?.retain(this.#J?.rows??[])}async accept($){this.#Y(),await T3(this.#$.rosterPath,$),this.#J=await e(this.#$.rosterPath)}async recordQuota($,Z,J){this.#Y();let z=await f3(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}});if(z)this.#J=await e(this.#$.rosterPath);return z}async recordAccountQuota($,Z,J){this.#Y();let z=await g3(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:J});if(z)this.#J=await e(this.#$.rosterPath);return z}close(){if(this.#z.signal.aborted)return;if(this.#z.abort(new _("closed","Claustrum consumer is closed")),this.#V)(this.#$.clearTimeoutImpl??clearTimeout)(this.#V);this.#V=void 0,this.#D(),this.#Q?.close(),this.#X?.release(),this.#X=void 0,this.#J=void 0,this.#U=void 0}}var R1={opencode:P7,pi:O7};function y3($,Z){let{tokenPath:J}=_7($,Z);return{stateDir:C7(J),host:$,override:J}}function v3($,Z){return I7($==="pi"?Z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0,$==="pi"?{...Z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:Z)}class Z1 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 h3($){return["auth","grant","--principal",`enrolled:${R1[$]}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"]}async function _2($,Z){try{if(await Z.processFence(),(await Z.runner.run(Z.ckBinary??"ck",h3($),{env:Z.env})).exitCode!==0)throw new Z1("permission-refused")}catch{throw new Z1("permission-refused")}}import{createHash as T7}from"node:crypto";import{lstat as f7,mkdir as g7,readFile as x2}from"node:fs/promises";import{dirname as x7}from"node:path";import{assertHostsStopped as y7,canonicalPath as w3,createNativeAccountRuntime as v7,custodyTombstoneOAuth as h7,inspectNativeHostAuthEntry as y2,NativeMigrationError as b0,nativePoolHoldsAccountData as m7,prepareNativeMigration as w7,readNativeEnrollmentMode as v2,readNativeMigrationJournal as u7,releaseNativeMigrationPreflight as c7,requireNoSupervisedAuthContentSnapshot as p7,runNativeMigration as d7,writeNativeHostAuth as l7}from"@cortexkit/anthropic-auth-core";import{dirname as A7,join as I2,resolve as m3}from"node:path";import{ACCOUNT_FILE_NAME as A2,ACCOUNT_STATE_FILE_NAME as b7,canonicalPath as b2,getStickyRoutingStatePath as R7,resolveLocalRoutingDestination as S7,resolveNativePoolPaths as k7}from"@cortexkit/anthropic-auth-core";async function U0($,Z){let J=$==="pi"?k2(Z):R2(Z),z=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),Q=m3(z||I2(J,A2)),G=m3(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(Q.endsWith(A2)?I2(A7(Q),b7):`${Q}.state.json`)),X=await k7(Q,G),W=$==="pi"?Z.PI_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim();return{host:$,paths:X,legacyConfigPath:Q,legacyStatePath:G,hostAuthPath:$==="pi"?E2(Z):S2(Z),routingSourcePath:m3(W||R7(Q)),routingDestinationPath:S7($,X,Z)}}async function T2($){let Z=new Map;for(let J of $){let z=new Set;for(let[Q,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 X=await b2(G);if(z.has(X)&&!(Q===9&&X===await b2(J.routingSourcePath)))throw Error("Native setup storage paths overlap");let W=Z.get(X);if(W!==void 0&&W!==J.host)throw Error("Native setup storage paths overlap between selected hosts");Z.set(X,J.host),z.add(X)}}}import{types as E7}from"node:util";var f2=new WeakMap;function g2($){return typeof $==="object"&&$!==null?f2.get($):void 0}function S1($){if(!$||typeof $!=="object"||E7.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 d extends Error{constructor($){super($);this.name="SetupRefusal",f2.set(this,$)}}var u3="OpenCode's separate Anthropic login is not used. Add that account through /claude Accounts if needed, or remove the separate login from OpenCode.";function h2($){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 c3($,Z){let J=[];for(let z of $)if(await v2(z,Z)!=="local")J.push(h2(z));if(J.length)throw new d(J.join(`
|
|
12
|
-
`))}function
|
|
2
|
+
import{x as e1}from"./index-0kxy8k2c.js";import{A as q4,B as l$,C as a$,D as s$,E as n$,F as K4,z as Y4}from"./index-b1dvkp15.js";import{ha as t9,ia as e6,ja as Y3}from"./index-62x1p34p.js";var O2=e6((xH,i9)=>{var P2={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"},$5={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},Z5={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?P2.up():"");if($)Z+=P2.left;return Z}};i9.exports={cursor:P2,scroll:$5,erase:Z5,beep:"\x07"}});import{stdin as x5,stdout as y5}from"node:process";import{createInterface as h5}from"node:readline/promises";import{authorize as v5,createNativeAccountRuntime as m5,exchange as w5,formatNativeAccountState as u5,generateRelayToken as c5,getAccountStoragePath as p5,isValidApiBaseURL as d5,readNativeEnrollmentMode as l5,resolveNativePoolPaths as a5,WORKER_SCRIPT as s5}from"@cortexkit/anthropic-auth-core";import{randomUUID as I8}from"node:crypto";import{constants as h1}from"node:fs";import{lstat as _8,mkdir as A8,open as R8}from"node:fs/promises";import{homedir as S8}from"node:os";import{isAbsolute as W9,join as Q2}from"node:path";import{types as H2}from"node:util";import{createProviderErrorRedactor as q9,createWindowsOwnerOnly as b8,ensureWindowsOwnerOnlyDirectory as k8,formatLogLine as T8,isOwnerOnly as E8,isSecretKey as f8,NativeMigrationError as g8,NativePiAuthSlotError as x8,setupEnrollment as y8}from"@cortexkit/anthropic-auth-core";import{readFile as V8}from"node:fs/promises";import{assertHostsStopped as j8,createNativeAccountRuntime as M8,discoverNativeVaultInventory as F8,inspectNativeHostAuthEntry as Z2,NativePiAuthSlotError as B8,nativePiAuthSlotPaths as D8,openNativePiAuthSlot as z2,readNativeEnrollmentMode as L8,requireNoSupervisedAuthContentSnapshot as N8}from"@cortexkit/anthropic-auth-core";import{dirname as c7}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as p7,CLAUSTRUM_PI_ENROLLMENT_NAME as d7,getHostClaustrumEnrollmentPaths as l7,resolveClaustrumConnectionPath as a7}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as YG}from"@cortexkit/claustrum-client";import{ClaustrumClient as lz}from"@cortexkit/claustrum-client";import{resolve as T2}from"node:path";import{storeIdentity as KZ}from"@cortexkit/claustrum-client";import{SubcClient as jZ}from"@cortexkit/subc-client";import{ClaustrumCredentialError as M4}from"@cortexkit/claustrum-client";import{SocketClosedError as F4,SocketTimeoutError as B4,SubcCallError as D4}from"@cortexkit/subc-client";class I extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var G3=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class P0 extends I{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function j0($){if($ instanceof P0||$ instanceof F4||$ instanceof B4)return"unreachable";let Z=$ instanceof M4||$ instanceof D4?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(G3,Z))return"answered";return G3[Z]}var X3=300000,B1=300000,Q3=1000;class e0{#$;#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;#Z;#G=!1;constructor($,Z){this.#$=$,this.#z=Z}get running(){return this.#Z}request(){if(this.#Z)return this.#G=!0,this.#Z;return this.#Z=(async()=>{do{this.#G=!1;try{await this.#$()}catch($){this.#z($)}}while(this.#G)})().finally(()=>{this.#Z=void 0}),this.#Z}}class L1{#$;#z=new e0;#Z;#G="polling";#H;#X;#J=!1;#U;#q=!1;#W=0;constructor($){this.#$=$,this.#Z=new D1(async()=>{let Z=this.#q;if(this.#q=!1,Z||this.#U!==this.#$.view())await this.#$.discover(this.#U??"")},(Z)=>{if(!this.#J)this.#$.onError?.(Z)})}get mode(){return this.#G}start(){if(this.#J||this.#H||this.#X)return;if(typeof this.#$.client.watchScoped!=="function"){this.#Q("fallback","client-without-watch");return}this.#j(!1)}stop(){if(this.#J)return;if(this.#J=!0,this.#X)(this.#$.clearTimeoutImpl??clearTimeout)(this.#X);this.#X=void 0;let $=this.#H;this.#H=void 0,$?.handle.stop()}#Q($,Z){if(this.#G===$)return;this.#G=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#Y($,Z){this.#X=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#X=void 0,!this.#J)Z()},$),this.#X.unref?.()}async#j($){let Z;try{Z=await this.#$.enrollmentToken()}catch(Q){if(this.#J)return;this.#$.onError?.(Q),this.#F("token-unreadable");return}let J=this.#$.client.watchScoped;if(this.#J||this.#H||!J)return;this.#z.restart(),this.#q=$;let z,G;try{G=J.call(this.#$.client,(Q)=>{if(this.#J||!z||this.#H!==z)return;if(z.notices++,z.notices===1)this.#$.onReachable?.(),z.acceptedAt=(this.#$.now??Date.now)(),this.#Q("watching","accepted");if(!this.#z.continuous(Q))this.#q=!0;this.#U=Q.view,this.#Z.request()},{enrollmentToken:Z})}catch(Q){this.#$.onError?.(Q),this.#F("watch-failed");return}z={handle:G,notices:0},this.#H=z,this.#Q("polling",$?"resubscribing":"opening");let X=z;G.closed.then((Q)=>this.#V(X,Q),(Q)=>this.#V(X,{kind:"transport_lost",error:Q}))}#V($,Z){if(this.#J||this.#H!==$)return;if(this.#H=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#Q("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#F("refused");try{this.#$.onRefused(Z.error)}catch(J){this.#$.onError?.(J)}return}if($.notices>0){let J=(this.#$.now??Date.now)();if($.acceptedAt!==void 0&&J-$.acceptedAt>=300000)this.#W=0;let z=Math.min(1000*2**Math.min(this.#W,16),300000);this.#W++,this.#Q("polling","resubscribing"),this.#Y(z,()=>void this.#j(!0));return}this.#F(Z.kind)}#F($){this.#Q("fallback",$),this.#Y(300000,()=>void this.#j(!1))}}var C1=60000,E2=4*C1,L4=2*C1,W3=new Map,N1=new Map;function $1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function N4($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!$1(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 C4($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class f2{transport;key;#$=[];#z=!1;#Z=new Set;#G=new Map;#H=new D1(async()=>{try{let $=await this.transport.getUsage();if(!$1($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>$1(Z)&&typeof Z.provider==="string"),this.#z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#Z=new Set(this.#z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#Z)this.#G.delete(Z)}catch{this.#$=[],this.#z=!1,this.#Z.clear()}},()=>{});#X=new e0;#J="polling";#U=0;#q=0;#W=new Map;#Q;#Y;#j={};#V=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#H.running)return this.#H.running;if(this.#J==="watching")return Promise.resolve();for(let[J,z]of N1)if($-z>=C1)N1.delete(J);let Z=N1.get(this.key);if(Z!==void 0&&$-Z<C1)return Promise.resolve();return N1.set(this.key,$),this.#H.request()}watchMode(){return this.#J}watch($={}){this.#U++;let Z=$.provider;if(Z===void 0)this.#q++;else this.#W.set(Z,(this.#W.get(Z)??0)+1);if(this.#U===1)this.#j=$,this.#K();let J=!1;return()=>{if(J)return;if(J=!0,Z===void 0)this.#q--;else{let z=(this.#W.get(Z)??1)-1;if(z>0)this.#W.set(Z,z);else this.#W.delete(Z)}if(--this.#U===0)this.#F()}}#F(){if(this.#Y)(this.#j.clearTimeoutImpl??clearTimeout)(this.#Y);this.#Y=void 0;let $=this.#Q;this.#Q=void 0,$?.handle?.stop(),this.#J="polling"}#M($){this.#Y=(this.#j.setTimeoutImpl??setTimeout)(()=>{if(this.#Y=void 0,this.#U>0&&!this.#Q)this.#K()},$),this.#Y.unref?.()}#K(){let $=this.transport.watchUsage;if(!$){this.#J="fallback";return}this.#J="polling",this.#X.restart();let Z={notices:0};this.#Q=Z;let J;try{J=$.call(this.transport,(z)=>this.#B(Z,z))}catch(z){this.#D(Z,z);return}Z.handle=J,J.closed.then(()=>this.#D(Z,void 0),(z)=>this.#D(Z,z))}#B($,Z){if(this.#Q!==$)return;if($.notices++,$.notices===1)this.#J="watching";if($.notices===2)this.#V=0;let J=N4(Z);if(!J)this.#X.restart();if(!(J?this.#X.continuous(J):!1)||J?.provider===void 0||this.#q>0||this.#W.has(J.provider))this.#H.request()}#D($,Z){if(this.#Q!==$)return;this.#Q=void 0;let J=C4(Z);if(J==="unknown_method"||J==="usage_watch_limit"){this.#J="fallback";return}if($.notices>0){let z=Math.min(Q3*2**Math.min(this.#V,16),B1);this.#V++,this.#J="polling",this.#M(z);return}if(this.#J="fallback",this.#H.request(),Z===void 0||j0(Z)==="unreachable")this.#M(B1)}current($,Z,J){for(let z of this.#$){if(z.provider!==$||typeof z.account!=="string"||z.account.trim()!==Z)continue;if(z.stale!==void 0||z.errorClass!==void 0||!$1(z.usage))continue;let G=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(G)||J-G>=E2)continue;return{entry:z,context:{fetchedAt:G,...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),G=(z??this.#$.find((Q)=>Q.provider===$&&Q.account===void 0&&Q.errorClass!==void 0))?.errorClass;if(G==="upstream_failed")return{miss:"upstream-failed"};if(G==="credential_absent"||G==="credential_unusable"||G==="credential_rejected")return{miss:"credential"};if(G!==void 0)return{miss:"unreachable"};if(z){let Q=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!$1(z.usage)||!Number.isFinite(Q))return{miss:"unreachable"};let W={entry:z,context:{fetchedAt:Q,...typeof z.source==="string"&&{source:z.source}}};return J>=Q+E2||z.stale!==void 0?{miss:"stale",reading:W}:{reading:W}}if(this.#Z.has($))return{miss:"absent"};let X=this.#G.get($)??J;return this.#G.set($,X),{miss:J-X>=L4?"unreachable":"cold"}}}function H3($,Z){let J=JSON.stringify([T2($.connectionFile),T2(Z)]),z=W3.get(J);if(!z)z={source:new f2($,J),refs:0},W3.set(J,z);z.refs++;let G=!1;return{source:z.source,release(){if(G)return;if(G=!0,--z.refs===0)W3.delete(J)}}}import{ClaustrumCredentialError as iz}from"@cortexkit/claustrum-client";import{appendFileSync as T4,chmodSync as E4,existsSync as K3,renameSync as u2,statSync as f4}from"node:fs";import{open as g4}from"node:fs/promises";import{dirname as x4,resolve as y4}from"node:path";import{randomUUID as P4}from"node:crypto";import{lstat as h2,readFile as v2,rename as O4,unlink as g2}from"node:fs/promises";import{dirname as M0,resolve as i}from"node:path";var _=process.platform==="win32",x2=new Set;function U3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var y2;function y0(){return y2??=import("@cortexkit/private-files"),y2}class u extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor($,Z,J){let z=J;super(`Private file refused at ${Z}: ${$} (${z?.reason??z?.code??"io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`,{cause:J});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=U3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}async function s($,Z,J){try{return await J()}catch(z){if(z instanceof u)throw z;throw new u($,Z,z)}}var I4;async function Q0($,Z){$=i($),Z??=I4,await s($,"safe-parent",async()=>{let J=await(await y0()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await h2($);throw new u(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function p($,Z,J=!1){if($=i($),Z==="directory")return Q0($);await s($,"verify",async()=>{let z=await y0(),G=await z.verifyOwnerOnly($),X=!1;if(!G.ok){let{reason:Q}=G.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 Q0(M0($)),await z.securePrivatePath($,Z),X=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:Q,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await z.verifyPrivatePath($,Z),X&&!x2.has($))x2.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function J0($,Z=!1,J){$=i($),await s($,"directory",async()=>{let z=await y0();try{return await h2($),await Q0($,J)}catch(X){if(U3(X)!=="ENOENT")throw X}let G=M0($);if(G===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await J0(G,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(X){if(U3(X)!=="EEXIST")throw X}await Q0($,J)})}async function t($,Z=!1){if(!_)return v2($,"utf8");return(await _4($,Z)).toString("utf8")}async function _4($,Z=!1){if(!_)return v2($);if($=i($),Z)await Q0(M0($)),await p($,"file",!0);return s($,"read",async()=>(await y0()).readOwnerOnly($))}async function h0($,Z){await Q0(M0(i($))),await s($,"create",async()=>{await(await y0()).createPrivateFile(i($),Z)})}async function m2($){await Q0(M0(i($))),await s($,"directory-create",async()=>{await(await y0()).createOwnerOnly(i($),{kind:"dir"})})}async function q3($,Z,J={}){$=i($),Z=i(Z);let z=J.now??(()=>performance.now()),G=z(),X=J.deadline??1/0,Q,W=[0,10,20,40,80,100],H,Y=0;for(let K of W){let F=Math.min(Q??1/0,X);if(z()>=F)break;if(K)await(J.sleep??((P)=>new Promise((C)=>setTimeout(C,P))))(Math.min(K,Math.max(0,F-z())));if(z()>=F)break;let B=z();if(await J.beforeRename?.(),Q!==void 0)Q+=z()-B;if(z()>=X)break;Y++;try{return await(J.rename??O4)($,Z),{attempts:Y,elapsedMs:z()-G}}catch(P){H??=P;let C=P;if(!(C.win32Code!==void 0?C.win32Code===32||C.win32Code===33:["EBUSY","EPERM","EACCES"].includes(C.code??"")&&!C.reason))break;Q??=z()+500}}let q=new u(Z,"rename",H??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw q.attempts=Y,q.elapsedMs=z()-G,q}async function v0($,Z,J={}){$=i($),await J0(M0($));try{await p($,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}let z=i(J.stagePath??`${$}.${P4()}.tmp`);if(M0(z)!==M0($))throw new u($,"stage-directory",{code:"EXDEV"});let G=!1,X=!1,Q={attempts:0,elapsedMs:0},W="stage-create",H=(Y)=>{try{J.onOutcome?.({path:$,stage:Y?.stage??"published",published:X,fileDurable:X,durabilityConfirmed:!1,attempts:Y?.attempts??Q.attempts,elapsedMs:Y?.elapsedMs??Q.elapsedMs,...Y&&{code:Y.code,win32Code:Y.win32Code}})}catch{}};try{if(await h0(z,Z),G=!0,W="before-rename",Q=await q3(z,$,J),G=!1,X=!0,W="published-callback",J.onRenamed?.(),W="published-verify",await p($,"file"),J.durable&&J.durability!=="file-only-on-windows")throw new u($,"directory-sync-unsupported",{code:"ENOTSUP"});H()}catch(Y){let q=Y instanceof u?Y:new u($,W,Y);if(q.published=X,q.fileDurable=X,X)Object.assign(q,Q);if(G){try{await g2(z)}catch{q.orphanPath=z}G=!1}throw H(q),q}finally{if(G)await g2(z).catch(()=>{})}}var A4=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,R4=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function S4($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function m0($={}){let Z=[R4,...$.extraValuePatterns??[]].map((X)=>new RegExp(X.source,X.flags.includes("g")?X.flags:`${X.flags}g`));function J(X){let Q=X.toLowerCase().replace(/[-_]/g,"");return A4.test(X)||Q.includes("apikey")||Q.endsWith("secret")||Q.endsWith("password")||Q.endsWith("token")&&!Q.endsWith("tokens")||!!$.extraSecretKeys?.(Q)}function z(X){let Q=X,W=[["name",X.name],["message",X.message],["stack",X.stack]];for(let Y of["code","status","cause"])if(Q[Y]!==void 0)W.push([Y,Q[Y]]);let H=new Set(W.map(([Y])=>Y));for(let Y of Object.entries(X))if(!H.has(Y[0]))W.push(Y);return W}function G(X,Q,W,H=0){if(typeof X==="string")return Z.reduce((Y,q)=>Y.replace(q,"***REDACTED***"),X);if(!X||typeof X!=="object")return X;if(W.has(X))return"[Circular]";W.add(X);try{if(Array.isArray(X))return X.map((K)=>G(K,Q,W,H));let Y=S4(X);if(Y&&H>=8)return"[Truncated]";let q=Y?H+1:H;return Object.fromEntries((Y?z(X):Object.entries(X)).map(([K,F])=>[K,Q&&J(K)?"***REDACTED***":G(F,Q,W,q)]))}finally{W.delete(X)}}return{redact:(X)=>G(X,!0,new WeakSet),redactStrings:(X)=>G(X,!1,new WeakSet)}}var w2=m0(),b4=w2.redact,k4=w2.redactStrings;var P1={error:0,warn:1,info:2,debug:3,trace:4},p2=5242880,d2=3;function V3($){try{E4($,384)}catch{}}function h4($){try{if(!(K3($)&&f4($).size>=p2))return;for(let J=d2-1;J>=1;J--)if(K3(`${$}.${J}`)){let z=`${$}.${J+1}`;u2(`${$}.${J}`,z),V3(z)}let Z=`${$}.1`;u2($,Z),V3(Z)}catch{}}async function W0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await s(Z,"log-close",()=>J.close())}async function c2($,Z){await J0(x4(Z));try{await p(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await h0(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await p(Z,"file",!0)}}return $.handle=await s(Z,"log-open",()=>g4(Z,"a")),$.file=Z,$.handle}async function v4($,Z,J){Z=y4(Z);try{if($.file!==Z)await W0($);let z=$.handle??await c2($,Z);if((await s(Z,"log-stat",()=>z.stat())).size>=p2){await W0($);for(let X=d2-1;X>=0;X--){let Q=X===0?Z:`${Z}.${X}`,W=`${Z}.${X+1}`;try{await p(Q,"file",!0)}catch(H){if(H.code==="ENOENT")continue;throw H}try{await p(W,"file",!0)}catch(H){if(H.code!=="ENOENT")throw H}await q3(Q,W),await p(W,"file")}z=await c2($,Z)}await s(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await W0($).catch(()=>{}),z}}function m4($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function w4($){let Z,J,z,G=m0(),X,Q=[],W,H=Promise.resolve(),Y,q={};function K(U){let V=H.then(U);return H=V.catch((j)=>{Y=j}),V}function F(U){if(_&&U.file!==Z)K(()=>W0(q)).catch(()=>{});Z=U.file,J=U.level,G=m0(U),X=U.captureSink}function B(U){if(U===void 0||U in P1)z=U}function P(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function C(){if(z)return z;let U=typeof J==="function"?J():J;if(U&&U in P1)return U;return"info"}function D(U=!0){if(W)clearTimeout(W),W=void 0;if(!Q.length){if(_)return K(async()=>{if(U)await W0(q);if(Y)throw Y});return}let V;try{V=P()}catch{if(Q=[],_&&U)return K(()=>W0(q));return}let j=Q.join("");if(Q=[],!V){if(_&&U)return K(()=>W0(q));return}if(_)return K(async()=>{try{await v4(q,V,j)}finally{if(U)await W0(q)}});try{if(h4(V),K3(V))V3(V);T4(V,j,{encoding:"utf8",mode:384})}catch{}}function R(){if(!W)W=setTimeout(()=>{W=void 0;let U=D(!1);if(U instanceof Promise)U.catch(()=>{})},500)}function S(U,V,j,b){if(Z===void 0&&X===void 0)return;try{if(P1[V]>P1[C()])return;let g=G.redactStrings(j),k;try{k=G.redact(b)}catch{k="[unserializable]"}let m=`[${new Date().toISOString()}] ${V.toUpperCase()} [${U}] ${g}`+(b===void 0?"":m4(k))+`
|
|
3
|
+
`;try{X?.({channel:U,level:V,message:g,data:k})}catch{}if(Z===void 0)return;if(Q.push(m),Q.length>=50){let n=D(!1);if(n instanceof Promise)n.catch(()=>{})}else R()}catch{}}function y(U){return{error:(V,j)=>S(U,"error",V,j),warn:(V,j)=>S(U,"warn",V,j),info:(V,j)=>S(U,"info",V,j),debug:(V,j)=>S(U,"debug",V,j),trace:(V,j)=>S(U,"trace",V,j)}}function L(){if(_)K(()=>W0(q)).catch(()=>{});if(Y=void 0,Q=[],W)clearTimeout(W),W=void 0;Z=void 0,J=void 0,z=void 0,G=m0(),X=void 0}if($)F($);return{configure:F,createLogger:y,setLogLevel:B,flushLogs:D,reset:L}}var u4=w4();function O0($){return u4.createLogger($)}function j3($){let Z=new AbortController,J=[],z=!1,G=()=>{if(z)return;z=!0;for(let{source:W,listener:H}of J)W.removeEventListener("abort",H);J.length=0},X=(W)=>{if(z||Z.signal.aborted)return;Z.abort(W),G()},Q=$.find((W)=>W.aborted);if(Q)return Z.abort(Q.reason),{signal:Z.signal,dispose:G};for(let W of $){if(Z.signal.aborted)break;let H=()=>X(W.reason);if(J.push({source:W,listener:H}),W.addEventListener("abort",H,{once:!0}),W.aborted)X(W.reason)}return{signal:Z.signal,dispose:G}}import{ClaustrumCredentialError as D$}from"@cortexkit/claustrum-client";import{createHash as i4,randomBytes as r4,randomUUID as o4}from"node:crypto";import{constants as z$}from"node:fs";import{chmod as t4,mkdir as e4,open as Q$,readFile as D3,realpath as $7,rename as Z7,stat as W$,unlink as H$}from"node:fs/promises";import{basename as J7,dirname as R0,extname as KJ,isAbsolute as VJ,join as z7,resolve as jJ}from"node:path";import{ClaustrumCredentialError as G7,ClaustrumClient as FJ,writeEnrollmentTokenFile as X7}from"@cortexkit/claustrum-client";import{randomUUID as l2}from"node:crypto";import{mkdir as c4,open as a2,rename as p4,rm as d4}from"node:fs/promises";import{dirname as s2}from"node:path";class O1 extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function Z1($,Z,J={}){await n2($,Z,J)}async function n2($,Z,J,z){if(_)return v0($,J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
4
|
+
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??l2)()}.tmp`,onRenamed:z,durable:J.durable,durability:J.durability,onOutcome:J.onOutcome});await c4(s2($),{recursive:!0});let G=`${$}.${(J.stageName??l2)()}.tmp`,X,Q=!1;try{if(X=await a2(G,"wx",384),Q=!0,await X.writeFile(J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
5
|
+
`,"utf8"),await X.chmod(384),J.durable)try{await X.sync()}catch(W){throw new O1(W)}if(await X.close(),X=void 0,await J.beforeRename?.(),await p4(G,$),Q=!1,z?.(),J.durable){let W=await a2(s2($),"r");try{await W.sync()}catch(H){throw new O1(H)}finally{await W.close()}}}finally{if(await X?.close().catch(()=>{}),Q)await d4(G,{force:!0}).catch(()=>{})}}var l4=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 I1}from"node:crypto";import{mkdir as i2,open as Z$,readFile as r2,rename as o2,rm as _1,stat as t2}from"node:fs/promises";import{dirname as B3,join as e2}from"node:path";function M3($,Z){return`${$}.${Z}.lock`}class I0 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class _0 extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function F3($,Z,J){let z=performance.now();for(;;){Z.signal?.throwIfAborted();let G=await H0({path:$,name:Z.name,ttlMs:Z.ttlMs,renew:Z.renew??!1,...Z.onStep?{onStep:Z.onStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}});if(G)try{return Z.signal?.throwIfAborted(),await J(G)}finally{await G.release()}let X=Z.timeoutMs-(performance.now()-z);if(X<=0)throw new I0({target:$,name:Z.name,timeoutMs:Z.timeoutMs});await new Promise((Q)=>setTimeout(Q,Math.min(25,Math.ceil(X))))}}async function $$($,Z){let J=await Z$($,"wx",384);try{await J.writeFile(Z,"utf8")}finally{await J.close()}}var a4=globalThis.setTimeout.bind(globalThis),s4=globalThis.clearTimeout.bind(globalThis);function J$($){let Z=$?.code;return Z==="ENOENT"||!_&&(Z==="EINVAL"||Z==="ENOTDIR")}function H0($){return n4({...$,now:Date.now})}async function n4($){let Z=M3($.path,$.name),J=e2(Z,"owner.json"),z=I1(),G=$.now??Date.now,X=null,Q=!1,W=!1,H,Y,q=new Promise((M)=>{Y=M});function K(M){try{let N=$.onRenewalTimer?.(M);if(N&&(typeof N==="object"||typeof N==="function")&&"then"in N&&typeof N.then==="function")Promise.resolve(N).catch(()=>{})}catch{}}function F(){if(!X)return;s4(X),X=null,K("cancelled")}function B(M,N){if(H||Q)return;H=Object.freeze({reason:M,expectedOwnerId:z,...typeof N?.ownerId==="string"?{observedOwnerId:N.ownerId}:{},...typeof N?.expiresAt==="number"?{observedExpiresAt:N.expiresAt}:{}}),F(),Y(H)}let P,C=null,D=`${Z}.evicting`,R=e2(D,"owner.json"),S=I1(),y=5000,L=8;async function U(){if(_)try{return JSON.parse(await t(Z,!0))}catch(M){if(M.code!=="EISDIR"&&M.reason!=="wrong-kind")throw M;return await p(Z,"directory",!0),JSON.parse(await t(J,!0))}try{return JSON.parse(await r2(Z,"utf8"))}catch(M){if(M.code!=="EISDIR")throw M;return JSON.parse(await r2(J,"utf8"))}}async function V(){if(_){let x=await U(),w=Number(x?.expiresAt)-G();await v0(Z,`${JSON.stringify({ownerId:z,expiresAt:G()+$.ttlMs})}
|
|
6
|
+
`,{deadline:performance.now()+Math.max(0,w),beforeRename:async()=>{let F1=await U();if(F1?.ownerId!==z||!(Number(F1?.expiresAt)>G())||!await h())throw new _0({target:$.path,name:$.name})}});return}let M=`${Z}.${I1()}.tmp`,N,O=!1;try{N=await Z$(M,"wx",384),O=!0,await N.writeFile(`${JSON.stringify({ownerId:z,expiresAt:G()+$.ttlMs})}
|
|
7
|
+
`,"utf8"),await N.chmod(384),await N.close(),N=void 0;let x=await U();if(x?.ownerId!==z||!(Number(x?.expiresAt)>G())||!await h())throw new _0({target:$.path,name:$.name});await o2(M,Z),O=!1}finally{if(await N?.close().catch(()=>{}),O)await _1(M,{force:!0}).catch(()=>{})}}async function j(){let M=`${JSON.stringify({ownerId:z,expiresAt:G()+$.ttlMs})}
|
|
8
|
+
`;if(_)await h0(Z,M);else await $$(Z,M)}async function b(M){let N=M.code;if(N==="EEXIST"){if(_)await U();return!0}if(N==="EISDIR"){if(_)await p(Z,"directory",!0),await t(J,!0);return!0}return!1}async function g(){if(_)await J0(B3(Z));try{return await j(),!0}catch(M){let N=M.code;if(await b(M))return!1;if(N==="ENOENT"){if(_)await J0(B3(Z));else await i2(B3(Z),{recursive:!0});try{return await j(),!0}catch(O){if(await b(O))return!1;throw O}}throw M}}async function k(){await new Promise((M)=>setTimeout(M,Math.floor(Math.random()*4)))}async function m(M=!0){if(M&&$.onStep)await $.onStep("lock-read-ready");let N;try{N=await U()}catch(x){if(_&&x.code!=="ENOENT")throw x}let O=Number(N?.expiresAt);if(Number.isFinite(O)&&O>G())return{status:"live"};if(typeof N?.ownerId==="string"&&Number.isFinite(O))return{status:"stale",identity:{kind:"owner",ownerId:N.ownerId,expiresAt:O}};try{let x=await t2(Z),w=Number.isFinite(O)?O:x.mtimeMs+$.ttlMs;if(w>G())return{status:"live"};return{status:"stale",identity:{kind:"stat",dev:x.dev,ino:x.ino,mtimeMs:x.mtimeMs,expiresAt:w}}}catch(x){if(x.code==="ENOENT"){if($.onStep)await $.onStep("lock-missing");return{status:"missing"}}throw x}}function n(M,N){if(N.status!=="stale")return!1;let O=N.identity;if(M.kind==="owner"&&O.kind==="owner")return M.ownerId===O.ownerId&&M.expiresAt===O.expiresAt;return M.kind==="stat"&&O.kind==="stat"&&M.dev===O.dev&&M.ino===O.ino&&M.mtimeMs===O.mtimeMs&&M.expiresAt===O.expiresAt}async function h(){try{return JSON.parse(await t(R,_))?.ownerId===S}catch(M){if(_&&M.code!=="ENOENT")throw M;return!1}}async function c(M){if(_)await s(M,"remove",()=>_1(M,{recursive:!0,force:!0}));else await _1(M,{recursive:!0,force:!0}).catch(()=>{})}async function o(){if(await h())await c(D)}async function j1(){if(_)await m2(D);else await i2(D);try{let M=`${JSON.stringify({ownerId:S,createdAt:G()})}
|
|
9
|
+
`;if(_)await h0(R,M);else await $$(R,M)}catch(M){if(J$(M))return!1;throw await o(),M}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function x0(){let M;try{M=await t2(D)}catch(O){if(O.code==="ENOENT")return"missing";throw O}if(_)await p(D,"directory",!0);if(M.mtimeMs+y>G())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let N=`${D}.${I1()}`;try{await o2(D,N)}catch(O){if(O.code==="ENOENT")return"missing";throw O}if($.onStep)await $.onStep("stale-marker-claimed");return await c(N),"recovered"}async function M1(M){try{if(!await j1())return!1}catch(N){if(N.code==="EEXIST"){if(_){await p(D,"directory",!0);try{await t(R,!0)}catch(O){if(O.code!=="ENOENT")throw O}}return!1}throw N}try{await M()}finally{await o()}return!0}async function T(){for(let M=0;M<L;M++){if($.onStep)await $.onStep("relinquish-read");let N;try{N=await U()}catch(O){if(_)throw O;return}if(N?.ownerId!==z)return;try{await _1(Z,{recursive:!0,force:!0});return}catch(O){if(_)throw O;await k()}}}function X0(){if(!$.renew||Q||H)return;let M=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(X=a4(()=>{X=null;let N=(async()=>{let O=!Q;try{if(!await M1(async()=>{let w=await U(),F1=G();if(Q||H){O=!1;return}if(w?.ownerId!==z){B("taken-over",w),O=!1;return}if(!(Number(w?.expiresAt)>F1)){B("expired",w),O=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(Q||H){O=!1;return}if(!await h())return;if($.onStep)await $.onStep("renewal-write-fenced");if(Q||H){O=!1;return}if(!await h())return;if($.onStep)await $.onStep("renewal-write-ready");if(Q||H){O=!1;return}if(await V(),$.onStep)await $.onStep("renewal-write-finished");if(!await h()){B("marker-lost"),O=!1,await T();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(x){if(_&&x instanceof u)P=x,B("renewal-failed"),O=!1;try{let w=await U();if(w?.ownerId!==z)B("taken-over",w);else if(!(Number(w?.expiresAt)>G()))B("expired",w)}catch{B("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(O&&!Q&&!H)X0()}})();C=N,N.finally(()=>{if(C===N)C=null})},M),"unref"in X)X.unref();K("scheduled")}function k2(){try{let M=$.onContended?.();if(M&&(typeof M==="object"||typeof M==="function")&&"then"in M&&typeof M.then==="function")Promise.resolve(M).catch(()=>{})}catch{}return null}let C0=await g();if(!C0)for(let M=0;M<L;M++){if(C0=await g(),C0)break;let N=await m();if(N.status==="live")return k2();if(N.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await j1()){await k();continue}}catch(O){if(O.code!=="EEXIST")throw O;if(await x0()==="fresh")return null;await k();continue}try{let O=await m();if(O.status==="live")return k2();if(!n(N.identity,O))continue;if(!await h())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await h())return null;let x=await m(!1);if(!n(N.identity,x))continue;if(await c(Z),!await h())return null;if($.onStep)await $.onStep("stale-lock-removed");if(C0=await g(),!C0)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await h())return await T(),C0=!1,null;break}finally{await o()}}if(!C0)return null;return X0(),{ownerId:z,whenLost:()=>q,hasLost:()=>H!==void 0,assertOwned:async()=>{if(P)throw P;let M;try{let N=await U();if(M=N,!Q&&!H&&N?.ownerId===z&&Number(N?.expiresAt)>G())return;B(N?.ownerId!==z?"taken-over":"expired",N)}catch(N){if(B("unreadable"),_&&N instanceof u)throw N}throw new _0({target:$.path,name:$.name,expectedOwnerId:z,...typeof M?.ownerId==="string"?{observedOwnerId:M.ownerId}:{},...typeof M?.expiresAt==="number"?{observedExpiresAt:M.expiresAt}:{}})},release:async()=>{if(_&&W)return;Q=!0,F(),await C;for(let M=0;M<L;M++){try{let N=!1;if(await M1(async()=>{let x;try{x=await U()}catch(w){if(_&&w.code==="ENOENT"){N=!0;return}throw w}if(x?.ownerId!==z){N=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await h())return;await c(Z),N=!0})){if(_&&!N)throw new u(Z,"release-not-confirmed",{code:"EIO"});W=N;return}await x0()}catch(N){if(_)throw N;return}await k()}if(_)throw new u(Z,"release-not-confirmed",{code:"ETIMEDOUT"})}}}var Q7=1,R1=16384,U$=30000,N3=/^[0-9a-f]{64}$/,Y$=new Set(["invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),q$=new Set(["pending_queue_full"]);function L3($){if(!($ instanceof G7))return;if(Y$.has($.code))return{code:$.code,disposition:"terminal"};if(q$.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function K$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function A1($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function V$($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function J1(){return new I("invalid-state","invalid Claustrum enrollment state")}function C3($){if(!K$($)||$.version!==Q7||typeof $.proposedName!=="string"||$.proposedName.length===0)throw J1();if($.phase==="pending"){if(!N3.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!A1($.createdAt)||!A1($.updatedAt))throw J1();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)||!V$($.tokenGeneration)||!A1($.updatedAt))throw J1();return{version:1,phase:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration,updatedAt:$.updatedAt}}if($.phase==="denied"||$.phase==="blocked"){if($.errorCode!==void 0&&typeof $.errorCode!=="string"||!A1($.updatedAt))throw J1();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw J1()}function P3($){if(!K$($)||!N3.test(String($.token??""))||!V$($.token_generation))throw new I("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function W7($){if(!$.isFile())throw new I("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new I("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new I("unsafe-file","Claustrum enrollment file must be owned by the current user")}function G$($){try{return JSON.parse($)}catch{throw new I("invalid-state","Claustrum enrollment file is not valid JSON")}}async function S0($){if(_)try{await J0(R0($));let J=await t($,!0);if(Buffer.byteLength(J)>R1)throw new I("unsafe-file","Claustrum enrollment file is too large");return G$(J)}catch(J){if(J.code==="ENOENT")return;throw J}let Z;try{Z=await Q$($,z$.O_RDONLY|z$.O_NOFOLLOW)}catch(J){if(J.code==="ENOENT")return;throw new I("unsafe-file","Claustrum enrollment file could not be opened safely")}try{W7(await Z.stat());let J=Buffer.alloc(R1+1),{bytesRead:z}=await Z.read(J,0,J.byteLength,0);if(z>R1)throw new I("unsafe-file","Claustrum enrollment file is too large");return G$(J.subarray(0,z).toString("utf8"))}finally{await Z.close()}}function X$($,Z){let J=[];for(let z of $.split(`
|
|
10
|
+
`)){if(z.trim()===""||z.startsWith("#"))continue;let G=z.split(":");if(G.length!==Z||!/^[^\s:,]+$/.test(G[0]??"")||!/^\d+$/.test(G[2]??"")||!Number.isSafeInteger(Number(G[2]))||Z===7&&(!/^\d+$/.test(G[3]??"")||!Number.isSafeInteger(Number(G[3])))||Z===4&&G[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(G[3]??""))return;J.push(G)}return J}async function H7($,Z,J){try{let[z,G]=await Promise.all([D3(J.passwdPath??"/etc/passwd","utf8"),D3(J.groupPath??"/etc/group","utf8")]),X=X$(z,7),Q=X$(G,4);if(!X||!Q)return!1;let W=X.filter((K)=>Number(K[2])===$),H=Q.filter((K)=>Number(K[2])===Z);if(W.length!==1||H.length!==1)return!1;let Y=W[0]?.[0],q=H[0]?.[3]??"";return(q===""||q.split(",").every((K)=>K===Y))&&!X.some((K)=>Number(K[2])!==$&&Number(K[3])===Z)}catch{return!1}}function j$($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>D3(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function M$($,Z={}){if(!_){let J=process.geteuid?.();if(J===void 0)return;let z=process.getegid?.(),G;try{G=await $7($)}catch{return}let X;for(;;){let Q=await W$(G).catch(()=>{return});if(Q&&(Q.mode&18)!==0&&(Q.mode&512)===0){if(X===void 0)X=z!==void 0&&await H7(J,z,Z);if((Q.mode&2)!==0||Q.uid!==J||Q.gid!==z||!X)throw new I("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${G}. Another user could replace it. Run: chmod g-w,o-w ${G}`)}let W=R0(G);if(W===G)return;G=W}}try{await Q0($,j$(Z))}catch(J){if(!(J instanceof u))throw J;throw new I("unsafe-file",`Claustrum enrollment parent refused: ${J.path} (${J.reason??J.code}). Use a folder that other users cannot write or replace.`)}}async function S1($,Z={}){if(_){await J0($,!1,j$(Z));return}await e4($,{recursive:!0,mode:448});let J=await W$($),z=process.geteuid?.();if(z!==void 0&&J.uid!==z)throw new I("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((J.mode&63)!==0)await t4($,448)}async function A0($,Z,J={}){let z=R0($);await S1(z,J),await M$(z,J);let G=`${JSON.stringify(Z)}
|
|
11
|
+
`;if(Buffer.byteLength(G)>R1)throw new I("invalid-state","Claustrum enrollment state is too large");if(_)return v0($,G);let X=z7(z,`.${J7($)}.${process.pid}.${o4()}.tmp`),Q,W=!1;try{Q=await Q$(X,"wx",384),W=!0,await Q.writeFile(G,"utf8"),await Q.chmod(384),await Q.sync(),await Q.close(),Q=void 0,await Z7(X,$),W=!1}finally{if(await Q?.close().catch(()=>{}),W)await H$(X).catch(()=>{})}}async function O3($,Z){let J=await S0($.tokenPath),z=J===void 0?void 0:P3(J),G=await S0($.statePath),X=G===void 0?void 0:C3(G);if(z)return{state:"approved",proposedName:X?.proposedName??Z,...X?.phase==="approved"&&X.approvedName!==void 0&&{approvedName:X.approvedName},tokenGeneration:z.token_generation};if(!X)return{state:"idle"};if(X.phase==="approved")return{state:"blocked",proposedName:X.proposedName,code:"missing_token"};return F0(X)}async function B0($){let Z=await S0($);if(Z===void 0)throw new I("not-enrolled","Claustrum enrollment is not configured");return P3(Z)}function F0($){if($.phase==="pending")return{state:"pending",proposedName:$.proposedName,...$.requestId!==void 0&&{requestId:$.requestId}};if($.phase==="approved")return{state:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration};if($.phase==="denied")return{state:"denied",proposedName:$.proposedName};return{state:"blocked",proposedName:$.proposedName,code:$.errorCode??"unknown"}}function F$(){return new I("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class I3{#$;#z;#Z;#G;#H;#X;#J;constructor($){this.#J=$.ancestorOptions??{},this.#$=$.client,this.#z=$.paths,this.#Z=$.proposedName,this.#G=$.now??Date.now,this.#H=$.mintSecret??(()=>r4(32).toString("hex")),this.#X=$.writeTokenFile??X7}async status(){return O3(this.#z,this.#Z)}async resetTerminal(){return B$(this.#z,this.#Z)}async#U($,Z){let J={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#G()};return await A0(this.#z.statePath,J,this.#J),F0(J)}async reconcile(){await S1(R0(this.#z.statePath),this.#J);let $=await H0({name:"ceremony",path:this.#z.statePath,ttlMs:U$,renew:!0});if(!$)return{state:"busy"};try{let Z=await S0(this.#z.tokenPath),J=Z===void 0?void 0:P3(Z),z=await S0(this.#z.statePath),G=z===void 0?void 0:C3(z);if(G&&G.proposedName!==this.#Z)throw F$();if(J){if(!G||G.phase==="pending"){let Q={version:1,phase:"approved",proposedName:G?.proposedName??this.#Z,tokenGeneration:J.token_generation,updatedAt:this.#G()};await A0(this.#z.statePath,Q,this.#J),G=Q}return{state:"approved",proposedName:G.proposedName,...G.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:J.token_generation}}if(G?.phase==="approved"){let Q={version:1,phase:"blocked",proposedName:G.proposedName,errorCode:"missing_token",updatedAt:this.#G()};return await A0(this.#z.statePath,Q,this.#J),F0(Q)}if(G&&G.phase!=="pending")return F0(G);if(!G){let Q=this.#G();if(G={version:1,phase:"pending",proposedName:this.#Z,requestSecret:this.#H(),createdAt:Q,updatedAt:Q},!N3.test(G.requestSecret))throw new I("invalid-state","invalid minted Claustrum enrollment secret");await A0(this.#z.statePath,G,this.#J)}if(!G.requestId)try{let Q=i4("sha256").update(Buffer.from(G.requestSecret,"hex")).digest("hex"),W=await this.#$.enrollPropose({name:G.proposedName,requestSecretHash:Q});G={...G,requestId:W.requestId,updatedAt:this.#G()},await A0(this.#z.statePath,G,this.#J)}catch(Q){let W=L3(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:G.proposedName,retryCode:W.code};return this.#U(G,W.code)}let X=G.requestId;if(!X)return F0(G);try{let Q=await this.#$.enrollPoll({requestId:X,requestSecret:G.requestSecret});if(Q.status==="pending")return F0(G);if(Q.status==="denied"){let H={version:1,phase:"denied",proposedName:G.proposedName,updatedAt:this.#G()};return await A0(this.#z.statePath,H,this.#J),F0(H)}await S1(R0(this.#z.tokenPath),this.#J),await M$(R0(this.#z.tokenPath),this.#J),await this.#X(this.#z.tokenPath,{token:Q.token,token_generation:Q.tokenGeneration});let W={version:1,phase:"approved",proposedName:G.proposedName,approvedName:Q.name,tokenGeneration:Q.tokenGeneration,updatedAt:this.#G()};return await A0(this.#z.statePath,W,this.#J),F0(W)}catch(Q){let W=L3(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:G.proposedName,requestId:X,retryCode:W.code};return this.#U(G,W.code)}}finally{await $.release()}}}async function B$($,Z){await S1(R0($.statePath));let J=await H0({name:"ceremony",path:$.statePath,ttlMs:U$,renew:!0});if(!J)return"busy";try{if(await S0($.tokenPath)!==void 0)return"refused-approved";let z=await S0($.statePath);if(z===void 0)return"idle";let G=C3(z);if(G.proposedName!==Z)throw F$();if(G.phase==="pending")return"refused-pending";return await J.assertOwned(),await H$($.statePath),"reset"}finally{await J.release()}}var _3="claustrum-tombstone:v1:";function L$($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function U7($,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 R3=O0("claustrum");function b3($,Z,J,z=R3){let G=L$(Z,J);return z.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:J?.recordVersion??null,retry:G,reason:U7(Z,J)}),G}var S3=300000,N$=60000;function A3(){return new I("invalid-material","Claustrum returned invalid credential material")}function Y7($){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,G=z.access_token??z.access;Z=typeof G==="string"?G:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(_3))throw A3();return Z}function q7($,Z){if(!$.operations.includes("read"))return;if(!$.categories.includes(Z.category))return;if($.credentialType==="oauth")return $.refreshAdapter===Z.refreshAdapter?"oauth":void 0;if($.credentialType==="api_key"&&Z.apiKeys)return $.refreshAdapter===void 0?"api_key":void 0;return}function K7($){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:G,operation:X})=>Object.freeze({selectorKind:z,selector:G,operation:X})))})}class b1{#$;#z;#Z;#G;#H;#X;#J;#U=new WeakMap;#q=new WeakMap;#W=new Map;#Q=new WeakMap;#Y;#j;#V=!1;#F=new P0;#M;#K=!1;#B=-1/0;#D=2000;#L=!1;#C;#P=new Set;constructor($){let Z=$.tokenPath;if($.readToken)this.#z=$.readToken;else if(Z)this.#z=()=>B0(Z);else throw new I("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#G=$.family,this.#H=$.parseIdentity,this.#X=$.requireAssertion??!1,this.#Z=$.now??Date.now,this.#J=$.logger??R3,this.#Y=$.setTimeoutImpl??setTimeout,this.#j=$.clearTimeoutImpl??clearTimeout}transportLost($){if(this.#L||this.#V)return;this.#V=!0,this.#F=$ instanceof D$?$:new P0,this.#J.warn("serving kept vault receipt",{reason:"unreachable"}),this.#O()}reachable(){if(this.#L||!this.#V)return;if(this.#V=!1,this.#M)this.#j(this.#M);this.#M=void 0,this.#D=2000;for(let $ of this.#W.values())$.since=null;(this.#J.info??R3.info)("vault receipt serving resumed",{reason:"reachable"})}#O(){if(this.#L||!this.#V||this.#M||this.#K)return;this.#M=this.#Y(()=>{this.#M=void 0,this.#I(!0)},this.#D),this.#M.unref?.()}#I($=!1){if(this.#L||!this.#V||this.#K)return;if(this.#Z()-this.#B<1000){this.#O();return}this.#B=this.#Z(),this.#K=!0,this.#R().catch(()=>{if($&&this.#V)this.#D=Math.min(this.#D*2,30000)}).finally(()=>{this.#K=!1,this.#O()})}#N($){if(this.#L)throw new I("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#_($){this.#N($);let Z=await this.#z();if(this.#N($),!/^[0-9a-f]{64}$/.test(Z.token)||!Number.isSafeInteger(Z.token_generation)||Z.token_generation<1)throw new I("invalid-token","Invalid Claustrum enrollment token");return Z.token}async#A($,Z){this.#N(Z);let J,z;try{let G=$();J=Z?await Promise.race([G,new Promise((X,Q)=>{let W=()=>Q(Z.reason);if(Z.addEventListener("abort",W,{once:!0}),z=()=>Z.removeEventListener("abort",W),Z.aborted)W()})]):await G}catch(G){if(this.#N(Z),j0(G)==="unreachable")this.transportLost(G);else this.reachable();if(G instanceof D$)throw G;if(j0(G)==="unreachable")throw new P0;throw new I("unavailable","Claustrum scoped operation unavailable")}finally{z?.()}return this.#N(Z),this.reachable(),J}async discover($){let Z=await this.#R($);return this.#C=Z.view,Z}async#R($){let Z,J;try{J=await this.#_($)}catch(H){throw this.#W.clear(),H}try{Z=await this.#A(()=>this.#$.listScoped(J),$)}catch(H){throw this.listFailed(H),H}let z=[],G=[],X=new Map;for(let H of Z.rows){let Y=q7(H,this.#G);if(!Y)continue;G.push({row:H,type:Y}),X.set(H.id,(X.get(H.id)??0)+1)}let Q=[];for(let{row:H,type:Y}of G){let q;if(!H.id.trim())q="empty credential id";else if((X.get(H.id)??0)>1)q="duplicate credential id";else if(H.accountId!==void 0&&!H.accountId.trim())q="blank account identity";else if(!H.state.trim())q="empty state";if(q){z.push({...H.id.trim()&&{credentialId:H.id},reason:q});continue}Q.push(Object.freeze({credentialId:H.id,credentialType:Y,...H.accountId!==void 0&&{accountIdentity:H.accountId},state:H.state,...H.email!==void 0&&{email:H.email},...H.orgName!==void 0&&{orgName:H.orgName}}))}for(let H of z)this.#J.warn("skipped malformed vault record",H);let W=K7(Z);return{view:Z.view,credentials:Object.freeze(Q),skipped:Object.freeze(z),...W&&{grantReach:W}}}listFailed($){if(j0($)==="unreachable")this.transportLost($);else this.reachable(),this.#W.clear()}forget($){this.#W.delete($)}retain($){let Z=new Map($.map((J)=>[J.credentialId,J]));for(let[J,z]of this.#W){let G=Z.get(J);if(!G?.enabled||G.state!=="active"||G.credentialType!==z.attempt.credentialType||G.accountIdentity!==z.attempt.expectedAccountIdentity)this.forget(J)}}keptReceiptState(){let $=null;for(let[Z,J]of this.#W){if(!this.#S(J.attempt)){this.forget(Z);continue}if(J.since!==null)$=Math.min($??J.since,J.since)}return Object.freeze({active:$!==null,since:$})}#S($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#Z()>N$}async authorize($,Z,J="vault"){this.#N(Z);let{credentialId:z,credentialType:G,accountIdentity:X}=$,Q=this.#W.get(z);if(Q&&(Q.attempt.credentialType!==G||Q.attempt.expectedAccountIdentity!==X))this.forget(z),Q=void 0;let W;try{W=await this.#_(Z)}catch(H){throw this.#W.clear(),H}if(this.#V&&Q)return this.#I(),this.#b(z,Q,W,J);try{let H=await this.#k({credentialId:z,credentialType:G,accountIdentity:X},W,Z);return this.#W.set(z,{attempt:H,routeId:J,since:null}),H}catch(H){if(this.#N(Z),j0(H)!=="unreachable")throw this.forget(z),H;return this.#b(z,Q,W,J,H)}}#b($,Z,J,z,G=this.#F){if(!Z||this.#W.get($)!==Z||!this.#S(Z.attempt))throw this.forget($),G;if(Z.since===null)Z.since=this.#Z();let X=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#U.set(X,J),this.#Q.set(X,z),X}async#k($,Z,J){if(!$.credentialId)throw new I("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:z,credentialType:G,accountIdentity:X}=$;if(this.#X&&X===void 0)throw new I("identity-unasserted","Claustrum dispatch requires a known account identity");let Q=await this.#A(()=>this.#$.getScoped({credentialId:z,enrollmentToken:Z,...G==="oauth"&&{minTtlMs:S3}}),J);if(Q.credentialId!==void 0&&Q.credentialId!==z)throw new I("identity-changed","Claustrum served credential identity changed");let W=Q.expiresAtMs;if(!Number.isSafeInteger(Q.recordVersion)||Q.recordVersion<0||W===null&&G==="oauth"||W!==null&&(!Number.isFinite(W)||W-this.#Z()<S3))throw new I("insufficient-validity","Claustrum served credential has insufficient validity");let H=Y7(Q.material),Y=Q.accountId?.trim()?Q.accountId:void 0;if(this.#X&&(Q.credentialId===void 0||Y===void 0))throw new I("identity-unasserted","Claustrum served credential did not assert its identity");let q=Y===void 0?this.#H?.(H):void 0,K=Y??q;if(X!==void 0&&K!==void 0&&K!==X)throw new I("identity-changed","Claustrum served credential identity changed");let F=K??X,P=Object.freeze(Object.defineProperty({credentialId:z,credentialType:G,...F!==void 0&&{accountIdentity:F},accountIdentitySource:Y!==void 0?"asserted":q!==void 0?"parsed":X!==void 0?"expected":"none",...X!==void 0&&{expectedAccountIdentity:X},...Q.credentialId!==void 0&&{assertedCredentialId:Q.credentialId},...Y!==void 0&&{assertedAccountIdentity:Y},...Q.projectId!==void 0&&{projectId:Q.projectId},recordVersion:Q.recordVersion,expiresAtMs:W},"accessToken",{value:H,enumerable:!1}));return this.#U.set(P,Z),P}async reportFailure($,Z,J){if(Z!==401)return;this.#N();let z=this.#U.get($);if(!z)throw new I("no-receipt","Claustrum failure report requires an original dispatch receipt");let G=this.#Q.get($);if(G!==void 0){this.forget($.credentialId),this.#J.debug("scoped 401 not reported",{routeId:G,reason:"kept-receipt"});return}let X=this.#W.get($.credentialId);if(X&&X.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let Q=this.#q.get($);if(Q)return Q;let W=this.#A(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:z,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#q.set($,W);try{await W,this.#J.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:J})}catch(H){throw this.#q.delete($),H}}watchRoster($){this.#N();let Z=new L1({client:this.#$,enrollmentToken:()=>this.#_(),view:$.view??(()=>this.#C),discover:async(J)=>{await $.onView(J)},onRefused:(J)=>{this.listFailed(J),$.onRefused?.(J)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#J,now:this.#Z,setTimeoutImpl:this.#Y,clearTimeoutImpl:this.#j});return this.#P.add(Z),Z.start(),{get mode(){return Z.mode},close:()=>{this.#P.delete(Z),Z.stop()}}}close(){if(this.#L)return;if(this.#L=!0,this.#M)this.#j(this.#M);this.#M=void 0;for(let $ of this.#P)$.stop();this.#P.clear(),this.#W.clear(),this.#$.close()}}import{resolve as d3}from"node:path";var b0="all",V7=Object.freeze(["primary"]);function P$($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function u0($,Z){return JSON.stringify([$,Z])}function D0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function d($){return typeof $==="number"&&Number.isFinite($)}function C$($){return typeof $==="string"&&$.length>0}function l($,Z,J){return $[Z]===void 0||J($[Z])}function j7($){return d($)&&$>0}function k3($){return typeof $==="string"}function M7($){if(!D0($)||!C$($.scope)||!C$($.label))return!1;switch($.kind){case"reading":return d($.checkedAt)&&d($.usedPercent)&&l($,"resetsAt",k3)&&l($,"windowMinutes",j7);case"retired":return d($.retiredAt);case"absent":return d($.checkedAt);default:return!1}}function F7($){if(!D0($)||!d($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&l($,"remainingPercent",d)&&l($,"usedPercent",d)&&l($,"resetsAt",k3)&&l($,"limit",d)&&l($,"used",d)&&l($,"remaining",d)&&l($,"unit",k3)}function O$($){return D0($)&&d($.value)&&Number.isInteger($.value)&&$.value>=0&&d($.checkedAt)}function T3($){return D0($)&&Object.values($).every(O$)}function B7($){return typeof $==="boolean"}function c0($){return D0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&l($,"balance",d)&&l($,"overageLimitReached",B7)&&d($.checkedAt)}function I$($){if(!D0($))return;let Z=Object.entries($).filter(([,J])=>O$(J));return Z.length===0?void 0:Object.fromEntries(Z)}function k0($){if(w0($))return $;if(!D0($))return;let{counters:Z,credits:J,...z}=$;if(!w0(z))return;let G=I$(Z),X=c0(J)?J:void 0;return{...z,...G===void 0?{}:{counters:G},...X===void 0?{}:{credits:X}}}function w0($){if(!D0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!M7(J))return!1;let z=u0(J.scope,J.label);if(Z.has(z))return!1;Z.add(z)}return l($,"budget",F7)&&l($,"counters",T3)&&l($,"credits",c0)}class k1 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function E1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function T1($){return typeof $==="number"&&Number.isFinite($)}function _$($){return $===void 0||typeof $==="string"&&$!==""}function A$($){return typeof $==="string"&&$!==""}function z1($,Z){return $[Z]===void 0||T1($[Z])}function E3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function D7($){return E1($)&&_$($.scope)&&A$($.label)&&T1($.usedPercent)&&E3($,"resetsAt")&&($.windowMinutes===void 0||T1($.windowMinutes)&&$.windowMinutes>0)}function L7($){return E1($)&&_$($.scope)&&A$($.label)}function N7($){if(!E1($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&z1($,"remainingPercent")&&z1($,"usedPercent")&&E3($,"resetsAt")&&z1($,"limit")&&z1($,"used")&&z1($,"remaining")&&E3($,"unit")}function p0($){if(!E1($)||!T1($.checkedAt))return!1;let Z=$.readings??[],J=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(J))return!1;let z=new Set;for(let G of Z){if(!D7(G))return!1;let X=u0(G.scope??b0,G.label);if(z.has(X))return!1;z.add(X)}if(!J.every(L7))return!1;return($.budget===void 0||N7($.budget))&&($.counters===void 0||T3($.counters))&&($.credits===void 0||c0($.credits))}function C7($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function P7($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function O7($,Z){let J=new Map(Object.entries($??{}));for(let[z,G]of Object.entries(Z??{})){let X=J.get(z);if(X===void 0||G.checkedAt>=X.checkedAt)J.set(z,G)}return J.size===0?void 0:Object.fromEntries(J)}function I7($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function G1($,Z){let J=$===void 0?void 0:k0($);if($!==void 0&&J===void 0)throw new k1("stored quota map is malformed");if(!p0(Z))throw new k1("quota observation is malformed");let z=J??{limits:[]},G=Z.checkedAt,X=new Map;for(let D of z.limits)X.set(u0(D.scope,D.label),D);let Q=(D)=>{let R=X.get(D);return R===void 0||G>=P$(R)},W=new Set;for(let D of Z.readings??[]){let R=D.scope??b0,S=u0(R,D.label);if(W.add(S),!Q(S))continue;X.set(S,{scope:R,label:D.label,kind:"reading",checkedAt:G,usedPercent:D.usedPercent,...D.resetsAt===void 0?{}:{resetsAt:D.resetsAt},...D.windowMinutes===void 0?{}:{windowMinutes:D.windowMinutes}})}for(let D of Z.coverage??[]){let R=D.scope??b0,S=u0(R,D.label);if(W.has(S)||!Q(S))continue;let y=X.get(S);X.set(S,y===void 0||y.kind==="absent"?{scope:R,label:D.label,kind:"absent",checkedAt:G}:{scope:R,label:D.label,kind:"retired",retiredAt:G})}let{limits:H,budget:Y,counters:q,credits:K,...F}=z,B=P7(z.budget,Z.budget,G),P=O7(z.counters,Z.counters),C=I7(z.credits,Z.credits);return{...F,limits:[...X.values()].sort(C7),...B===void 0?{}:{budget:B},...P===void 0?{}:{counters:P},...C===void 0?{}:{credits:C}}}var _7=Object.freeze({validate:w0,decode:k0,merge:G1});import{createHash as b7}from"node:crypto";import{resolve as b$}from"node:path";function R$($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function f3($,Z,J){return $.some((z)=>R$(z,Z,J))}function g3($,Z,J){let z={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((G)=>G.credentialId!==Z||G.accountIdentity!==J),z]}function x3($,Z,J){return $.filter((z)=>!Z.some((G)=>R$(z,G,J)))}var k$="vault:";function k7($){return b7("sha256").update($).digest("hex")}function T7($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function E7($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function L0($){return[$.credentialId,...$.aliases??[]]}function T$($,Z,J={}){let z=J.now??Date.now(),G=J.routePrefix??k$,X=J.reservedRouteIds??new Set,Q=$?.rows??[],W=[...$?.declined??[]],H=Z.skipped.length===0,Y=new Set(Z.credentials.map((L)=>L.credentialId)),q=new Set(Z.skipped.flatMap((L)=>L.credentialId===void 0?[]:[L.credentialId])),K=Z.skipped.some((L)=>L.credentialId===void 0),F=(L)=>!Y.has(L)&&(q.has(L)||K),B=new Map;for(let L of Q){if(L.accountIdentity===void 0)continue;for(let U of L0(L))if(!B.has(U))B.set(U,L.accountIdentity)}let P=new Map;for(let L of Z.credentials){let U=L.accountIdentity!==void 0?{credential:L,identity:L.accountIdentity,claimed:!0}:{credential:L,identity:B.get(L.credentialId),claimed:!1},V=E7(U),j=P.get(V)??[];j.push(U),P.set(V,j)}let C=new Set,D=new Set(X),R=[],S=(L,U)=>L.credential.credentialId.localeCompare(U.credential.credentialId),y=[...P.values()].map((L)=>L.toSorted(S)).sort((L,U)=>L[0]&&U[0]?S(L[0],U[0]):0);for(let L of y){let U=L[0]?.identity,V=L.filter((T)=>T.credential.state==="active"),j=V.length?V:L,b=j.filter((T)=>T.claimed),g=b.length?b:j,k=new Set(L.map((T)=>T.credential.credentialId)),m=Q.find((T)=>!C.has(T)&&L0(T).some((X0)=>k.has(X0))&&(T.accountIdentity===void 0||T.accountIdentity===U)),n=g.find((T)=>T.credential.credentialId===m?.credentialId)??g[0];if(!n)continue;let h=n.credential,c=m??(U===void 0?void 0:Q.find((T)=>!C.has(T)&&T.accountIdentity===U));if(c)C.add(c);let o=c?.routeId;if(!o||X.has(o)){let T=`${G}${h.credentialId}${U===void 0?"":`~${k7(U).slice(0,10)}`}`;o=T;for(let X0=2;D.has(o);X0++)o=`${T}~${X0}`}D.add(o);let j1=c?L0(c).filter(F):[],x0=[...new Set([...L.map((T)=>T.credential.credentialId),...j1])].filter((T)=>T!==h.credentialId).sort((T,X0)=>T.localeCompare(X0)),M1=J.mapAccount?.(h)??{};R.push({previousIndex:c?Q.indexOf(c):1/0,row:{routeId:o,credentialId:h.credentialId,credentialType:h.credentialType,...U!==void 0&&{accountIdentity:U},...x0.length&&{aliases:x0},state:h.state,label:M1.label?.trim()||T7(h),...h.email!==void 0&&{email:h.email},...h.orgName!==void 0&&{orgName:h.orgName},enabled:![h.credentialId,...x0].some((T)=>f3(W,T,U)),addedAt:c?.addedAt??z,...c?.quota!==void 0&&{quota:c.quota},...!n.claimed&&U!==void 0&&{unclaimed:!0}}})}return Q.forEach((L,U)=>{if(C.has(L)||!L0(L).some(F))return;if(D.has(L.routeId))return;let[V,...j]=L0(L).filter((k)=>!Y.has(k));if(V===void 0)return;D.add(L.routeId);let{aliases:b,...g}=L;R.push({previousIndex:U,row:{...g,credentialId:V,...j.length&&{aliases:j},stale:!0}})}),R.sort((L,U)=>L.previousIndex===U.previousIndex?L.row.credentialId.localeCompare(U.row.credentialId):L.previousIndex-U.previousIndex),{version:1,view:Z.view,complete:H,...!H&&{rejected:Z.skipped.map((L)=>({...L.credentialId!==void 0&&{credentialId:L.credentialId},reason:L.reason}))},rows:R.map((L)=>L.row),declined:W}}function y3($){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 X1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function d0($){return $===void 0||typeof $==="string"}function f7($){let Z=X1($)?k0($.quota):void 0;if(!X1($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!d0($.accountIdentity)||!d0($.email)||!d0($.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 g7=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function S$($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!X1(J)||!d0(J.credentialId)||typeof J.reason!=="string"||!g7.has(J.reason))return;Z.push(J)}return Z}function x7($){if(!X1($)||$.version!==1||!d0($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!S$($.rejected))throw new I("invalid-state","Claustrum roster file is not valid");let Z=[];for(let G of $.rows){let X=f7(G);if(!X)throw new I("invalid-state","Claustrum roster file is not valid");Z.push(X)}let J=[];for(let G of $.declined){if(!X1(G)||typeof G.credentialId!=="string"||!d0(G.accountIdentity))throw new I("invalid-state","Claustrum roster file is not valid");J.push(G)}let z=S$($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...z&&{rejected:z},rows:Z,declined:J}}async function e($){let Z;try{Z=await t($,_)}catch(z){if(z.code==="ENOENT")return;throw z}let J;try{J=JSON.parse(Z)}catch{throw new I("invalid-state","Claustrum roster file is not valid")}return x7(J)}var y7={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},h7={name:"claustrum-roster",ttlMs:30000};async function l0($,Z,J={}){return F3($,{...y7,signal:J.signal},async(z)=>{let G=await e($),{next:X,result:Q}=await Z(G,{assertOwned:()=>z.assertOwned()});if(X)await z.assertOwned(),await Z1($,X,{beforeRename:async()=>{await J.beforePublish?.(),J.signal?.throwIfAborted(),await z.assertOwned()}});return Q})}function h3($,Z){return l0($,(J)=>{let z=J?.rows.find((X)=>X.routeId===Z);if(!J||!z)throw new I("route-unavailable","Claustrum route is not in the roster");let G=g3(J.declined,z.credentialId,z.accountIdentity);return{next:{...J,declined:G,rows:J.rows.map((X)=>X===z?{...X,enabled:!1}:X)},result:void 0}})}function v3($,Z){return l0($,(J)=>{let z=J?.rows.find((G)=>G.routeId===Z);if(!J||!z)throw new I("route-unavailable","Claustrum route is not in the roster");return{next:{...J,declined:x3(J.declined,L0(z),z.accountIdentity),rows:J.rows.map((G)=>G===z?{...G,enabled:!0}:G)},result:void 0}})}function v7($,Z){if(!L0($).includes(Z.credentialId))return"refuse";if($.unclaimed&&(Z.accountIdentitySource==="expected"||Z.accountIdentitySource==="none"))return"refuse";if($.accountIdentity===Z.accountIdentity)return"hold";if($.accountIdentity===void 0&&Z.expectedAccountIdentity===void 0&&Z.accountIdentity!==void 0&&(Z.accountIdentitySource==="asserted"||Z.accountIdentitySource==="parsed")&&L0($).length===1)return"bind";return"refuse"}async function m3($,Z){let{routeId:J,observation:z,...G}=Z;return E$($,{routeId:J,observation:z,accountIdentity:G.accountIdentity,receipt:G})}async function E$($,Z){if(!p0(Z.observation))return!1;let J=U0($,await e($));if(!N0(J,Z).kept)return!1;return f$($,Z)}function w3($,Z){return E$($,Z)}function N0($,Z){let J=$?.rows.find((Q)=>Q.routeId===Z.routeId),z=!J?"refuse":Z.receipt?v7(J,Z.receipt):J.accountIdentity!==void 0&&J.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!J||z==="refuse")return{roster:$,kept:!1};let G=G1(J.quota,Z.observation),X=z==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{roster:{...$,rows:$.rows.map((Q)=>Q===J?{...Q,...X,quota:G}:Q)},kept:!0}}var f1=new Map;function u3($){f1.delete(b$($))}async function c3($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){u3($.path);return}let J=await H0({...h7,path:$.path,renew:!0});if(!J){let X=await e($.path);if($.signal?.throwIfAborted(),!X?.view)throw new I("roster-busy","Claustrum account discovery is already in progress");return X}let z=b$($.path),G;try{let X=await e($.path),Q=f1.get(z);G=Q&&(Q.previousView===X?.view||Q.inventory.view===X?.view)?Q:{inventory:await $.custody.discover($.signal),previousView:X?.view},f1.delete(z);let{inventory:W}=G;return $.onInventory?.(W),$.signal?.throwIfAborted(),await l0($.path,async(H)=>{if(!await Z())return{result:void 0};$.signal?.throwIfAborted(),await J.assertOwned();let Y=typeof $.projection==="function"?$.projection():$.projection,q=T$(H,W,Y);return{...JSON.stringify(H)!==JSON.stringify(q)&&{next:q},result:q}},{beforePublish:async()=>{$.signal?.throwIfAborted(),await J.assertOwned()}})}catch(X){if(X instanceof I0&&G&&!$.signal?.aborted&&await Z())f1.set(z,G);throw X}finally{await J.release()}}var a0=new Map,m7=O0("claustrum"),g$=100;function x$($){let Z=d3($),J=a0.get(Z);if(!J)J={path:Z,pending:new Map,listeners:new Set,wake:new Set,abort:new AbortController,failures:0,draining:!1,order:0},a0.set(Z,J);return J}function y$($,Z){let J=x$($);J.listeners.add(Z);let z;return()=>z??=(()=>{return J.listeners.delete(Z),J.listeners.size?Promise.resolve():p3($)})()}function w7($){let Z=new Map,{observation:J}=$,z=JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]),G=(W,H,Y)=>Z.set(`${z}:${W}`,{at:H,order:0,publication:{...$,observation:Y}}),X=(W,H)=>JSON.stringify([W??"all",H]),Q=new Set;for(let W of J.readings??[]){let H=X(W.scope,W.label);Q.add(H),G(H,J.checkedAt,{checkedAt:J.checkedAt,readings:[{...W}]})}for(let W of J.coverage??[]){let H=X(W.scope,W.label);if(!Q.has(H))G(H,J.checkedAt,{checkedAt:J.checkedAt,coverage:[{...W}]})}if(J.budget)G("budget",J.checkedAt,{checkedAt:J.checkedAt,budget:{...J.budget}});for(let[W,H]of Object.entries(J.counters??{}))G(`counter:${W}`,H.checkedAt,{checkedAt:J.checkedAt,counters:{[W]:{...H}}});if(J.credits)G("credits",J.credits.checkedAt,{checkedAt:J.checkedAt,credits:{...J.credits}});if(!Z.size)G("empty",J.checkedAt,{checkedAt:J.checkedAt});return Z}function f$($,Z){if(!p0(Z.observation))return Promise.resolve(!1);let J=x$($),z=JSON.stringify([Z.accountIdentity??null,Z.accountIdentity===void 0?Z.routeId:null]),G=J.pending.get(z)??new Map;for(let[X,Q]of w7(Z)){let W=G.get(X);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;G.set(X,Q)}}if(G.size)J.pending.set(z,G);for(let X of J.listeners)X(Z);return v$(J,g$),Promise.resolve(!0)}function h$($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,J)=>Z.order-J.order)}function U0($,Z){let J=a0.get(d3($));if(J)for(let z of h$(J.pending)){if(z.priorReading)Z=N0(Z,z.priorReading).roster;Z=N0(Z,z.publication).roster}return Z}function v$($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;if($.timer=setTimeout(()=>{$.timer=void 0,m$($)},Z),!$.draining)$.timer.unref?.()}function m$($){if($.running||$.abort.signal.aborted)return;let Z=new Map([...$.pending].map(([J,z])=>[J,new Map(z)]));$.running=(async()=>{try{await l0($.path,(J)=>{let z=J;for(let G of h$(Z)){if(G.priorReading)z=N0(z,G.priorReading).roster;z=N0(z,G.publication).roster}return{...z!==J&&{next:z},result:void 0}},{signal:$.abort.signal});for(let[J,z]of Z){let G=$.pending.get(J);for(let[X,Q]of z)if(G?.get(X)===Q)G.delete(X);if(!G?.size)$.pending.delete(J)}$.failures=0}catch(J){if(!$.abort.signal.aborted&&$.failures++===0)m7.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()):g$;v$($,J)}})()}async function p3($,Z=1000){let J=d3($),z=a0.get(J);if(!z)return;z.draining=!0,clearTimeout(z.timer),z.timer=void 0;let G,X,Q=new Promise((W)=>{X=()=>{if(!z.pending.size||z.abort.signal.aborted)W()},z.wake.add(X),X()});try{if(z.pending.size)m$(z);await Promise.race([Q,new Promise((W)=>{G=setTimeout(W,Math.max(0,Z))})])}finally{if(clearTimeout(G),X)z.wake.delete(X);if(z.draining=!1,!z.listeners.size){if(z.abort.abort(),clearTimeout(z.timer),z.pending.clear(),a0.get(J)===z)a0.delete(J)}}}class w${#$;#z=new AbortController;#Z;#G;#H;#X;#J;#U;#q;#W=!1;#Q;#Y;#j;#V=new Map;#F;#M;constructor($){this.#$=$,this.#Z=$.logger??O0("claustrum"),this.#M=y$($.rosterPath,(Z)=>{this.#J=N0(this.#J,Z).roster})}#K($){this.#z.signal.throwIfAborted(),$?.throwIfAborted()}async#B(){return await this.#$.isCustodyActive?.()??!0}#D($,Z){let J=j3([this.#z.signal,...Z?[Z]:[]]);return new Promise((z,G)=>{let X=()=>{J.signal.removeEventListener("abort",Q),J.dispose()},Q=()=>{X(),G(J.signal.reason)};if(J.signal.addEventListener("abort",Q,{once:!0}),$.then((W)=>{if(X(),J.signal.aborted)G(J.signal.reason);else z(W)},(W)=>{X(),G(W)}),J.signal.aborted)Q()})}async#L(){if(this.#K(),this.#G)return this.#G;if(!this.#H)this.#H=this.#$.connect().then(($)=>{if(this.#z.signal.aborted)$.close(),this.#K();if(this.#G=new b1({client:$,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Z,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&$.insula)this.#Q=H3($.insula,this.#$.tokenPath);return this.#G}).finally(()=>{this.#H=void 0});return this.#D(this.#H)}snapshot(){return this.#J}grantReach(){let $=this.#U;return $&&this.#J?.view===$.view?$.reach:void 0}watchState(){return Object.freeze({vault:this.#Y?.mode??"polling",...this.#$.insula&&{insula:this.#Q?.source.watchMode()??"polling"}})}#C(){this.#Y?.close(),this.#Y=void 0,this.#j?.(),this.#j=void 0}keptReceiptState(){return this.#G?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return y3(this.#J)}refresh(){if(this.#K(),this.#X)return this.#X;return this.#X=(async()=>{if(!await this.#B()){this.#J=void 0,this.#U=void 0,this.#C(),this.#G?.close(),this.#G=void 0,this.#Q?.release(),this.#Q=void 0;return}let $=await this.#L(),Z,J=await c3({path:this.#$.rosterPath,custody:$,onInventory:(G)=>{Z=G},isActive:()=>this.#B(),signal:this.#z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#K();let z=J?.view!==this.#J?.view;if(this.#J=U0(this.#$.rosterPath,J),$.retain(J?.rows??[]),Z&&J?.view!==void 0)this.#U=Z.grantReach?{view:J.view,reach:Z.grantReach}:void 0;if(J&&z)this.#$.onRoster?.(J);return this.#F=(this.#$.now??Date.now)(),J})().finally(()=>{this.#X=void 0}),this.#X}start(){if(this.#W)return;this.#K(),this.#W=!0;let $=async()=>{try{if(await this.#P())await this.refresh();await this.refreshInsulaQuota(),this.#O()}catch(J){if(!this.#z.signal.aborted)this.#$.onError?.(J)}if(this.#z.signal.aborted)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#q=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#q=void 0,$()},Z),this.#q.unref?.()};$()}async#P(){if(this.#Y?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#F===void 0||$-this.#F>=X3)return!0;return!await this.#B()}#O(){let $=this.#G;if(this.#z.signal.aborted||!$)return;if(this.#Y??=$.watchRoster({view:()=>this.#J?.view,onView:async()=>{while(this.#X)await this.#X.catch(()=>{});await this.refresh()},onRefused:(Z)=>this.#$.onError?.(Z),onError:(Z)=>{if(!this.#z.signal.aborted)this.#$.onError?.(Z)}}),this.#$.insula&&this.#Q&&!this.#j)this.#j=this.#Q.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#z.signal.aborted||!await this.#B())return;try{await B0(this.#$.tokenPath),await this.#L(),await this.#Q?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#z.signal.aborted||!await this.#B())return;try{return await B0(this.#$.tokenPath),this.#I($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#z.signal.aborted||!await this.#B())return;try{await B0(this.#$.tokenPath);let J=U0(this.#$.rosterPath,await e(this.#$.rosterPath))?.rows.find((z)=>z.routeId===$);return this.#I(J?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute($){let Z=this.#$.insula;if(!Z||this.#z.signal.aborted||!await this.#B())return{miss:"unreachable"};try{await B0(this.#$.tokenPath);let z=U0(this.#$.rosterPath,await e(this.#$.rosterPath))?.rows.find((Q)=>Q.routeId===$)?.accountIdentity;if(!z||!this.#Q)return{miss:"unreachable"};let G=this.#Q.source.lookup(Z.provider,z,(this.#$.now??Date.now)()),X=G.reading&&Z.normalize(G.reading.entry,G.reading.context);if(G.miss)return{miss:G.miss,...X!==void 0&&{reading:X}};return X===void 0?{miss:"unreachable"}:{reading:X}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute($,Z){let J=await this.lookupInsulaQuotaForRoute($);if(J.miss==="cold"||J.miss==="upstream-failed"){if(this.#V.get($)!==J.miss)this.#V.set($,J.miss),this.#Z.warn("skipped insula provider poll",{reason:J.miss});return}return this.#V.delete($),J.miss?Z():J.reading}#I($){if(!this.#$.insula||!$)return;let Z=this.#Q?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){this.#K(Z);let J=this.#J??await this.#D(this.refresh(),Z);if(!J||!await this.#B())throw this.#G?.close(),this.#G=void 0,this.#C(),this.#Q?.release(),this.#Q=void 0,new I("not-active","Claustrum scoped custody is not active");let z=U0(this.#$.rosterPath,await e(this.#$.rosterPath));this.#K(Z);let G=J.rows.find((H)=>H.routeId===$),X=z?.rows.find((H)=>H.routeId===$);if(X&&!X.enabled){if(G)this.#G?.forget(G.credentialId);throw new I("route-declined","Claustrum route is disabled")}if(!G||!X||X.state!=="active"||X.credentialId!==G.credentialId||X.accountIdentity!==G.accountIdentity||X.credentialType!==G.credentialType){if(G)this.#G?.forget(G.credentialId);throw new I("route-unavailable","Claustrum route is disabled, removed or changed")}let Q=await this.#D(this.#L(),Z),W=j3([this.#z.signal,...Z?[Z]:[]]);try{return await Q.authorize({credentialId:X.credentialId,credentialType:X.credentialType,...X.accountIdentity!==void 0&&{accountIdentity:X.accountIdentity}},W.signal,$)}finally{W.dispose()}}async reportFailure($,Z,J){if(this.#K(),!this.#G)throw new I("no-receipt","Claustrum dispatch receipt has no active owner");await this.#G.reportFailure($,Z,J)}async send($,Z,J){let z=J.signal,G=await this.authorize($,z),X=await Z(G,z);if(X.status===401&&G.fromKeptReceipt)return await this.reportFailure(G,401,J.reporterSource??"direct"),X;if(X.status===401&&!z?.aborted){let Q;try{Q=await this.authorize($,z)}catch{}if(b3(J.site,G,Q,this.#Z))await X.body?.cancel().catch(()=>{}),G=Q,X=await Z(Q,z)}if(X.status===401)await this.reportFailure(G,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 X}async decline($){this.#K(),await h3(this.#$.rosterPath,$),this.#J=U0(this.#$.rosterPath,await e(this.#$.rosterPath)),this.#G?.retain(this.#J?.rows??[])}async accept($){this.#K(),await v3(this.#$.rosterPath,$),this.#J=U0(this.#$.rosterPath,await e(this.#$.rosterPath))}async recordQuota($,Z,J){return this.#K(),m3(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.#K(),w3(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:J})}close(){if(this.#z.signal.aborted)return;if(this.#z.abort(new I("closed","Claustrum consumer is closed")),this.#q)(this.#$.clearTimeoutImpl??clearTimeout)(this.#q);this.#q=void 0,this.#C(),this.#G?.close(),this.#Q?.release(),this.#Q=void 0,this.#J=void 0,this.#U=void 0,this.#M(),u3(this.#$.rosterPath)}async dispose(){this.close(),await this.#M()}}var g1={opencode:p7,pi:d7};function l3($,Z){let{tokenPath:J}=l7($,Z);return{stateDir:c7(J),host:$,override:J}}function a3($,Z){return a7($==="pi"?Z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0,$==="pi"?{...Z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:Z)}class Q1 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 s3($){return["auth","grant","--principal",`enrolled:${g1[$]}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"]}async function u$($,Z){try{if(await Z.processFence(),(await Z.runner.run(Z.ckBinary??"ck",s3($),{env:Z.env})).exitCode!==0)throw new Q1("permission-refused")}catch{throw new Q1("permission-refused")}}import{createHash as e7}from"node:crypto";import{lstat as $8,mkdir as Z8,readFile as t$}from"node:fs/promises";import{dirname as J8}from"node:path";import{assertHostsStopped as z8,canonicalPath as i3,createNativeAccountRuntime as G8,custodyTombstoneOAuth as X8,inspectNativeHostAuthEntry as e$,NativeMigrationError as T0,nativePoolHoldsAccountData as Q8,prepareNativeMigration as W8,readNativeEnrollmentMode as $9,readNativeMigrationJournal as H8,releaseNativeMigrationPreflight as U8,requireNoSupervisedAuthContentSnapshot as Y8,runNativeMigration as q8,writeNativeHostAuth as K8}from"@cortexkit/anthropic-auth-core";import{dirname as s7,join as c$,resolve as n3}from"node:path";import{ACCOUNT_FILE_NAME as p$,ACCOUNT_STATE_FILE_NAME as n7,canonicalPath as d$,getStickyRoutingStatePath as i7,resolveLocalRoutingDestination as r7,resolveNativePoolPaths as o7}from"@cortexkit/anthropic-auth-core";async function Y0($,Z){let J=$==="pi"?s$(Z):l$(Z),z=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),G=n3(z||c$(J,p$)),X=n3(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(G.endsWith(p$)?c$(s7(G),n7):`${G}.state.json`)),Q=await o7(G,X),W=$==="pi"?Z.PI_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim();return{host:$,paths:Q,legacyConfigPath:G,legacyStatePath:X,hostAuthPath:$==="pi"?n$(Z):a$(Z),routingSourcePath:n3(W||i7(G)),routingDestinationPath:r7($,Q,Z)}}async function i$($){let Z=new Map;for(let J of $){let z=new Set;for(let[G,X]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 d$(X);if(z.has(Q)&&!(G===9&&Q===await d$(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 t7}from"node:util";var r$=new WeakMap;function o$($){return typeof $==="object"&&$!==null?r$.get($):void 0}function x1($){if(!$||typeof $!=="object"||t7.isProxy($))return;if(Object.getOwnPropertyDescriptor($,"name")?.value==="ProcessInspectionError"&&Object.getOwnPropertyDescriptor($,"code")?.value==="process-inspection-failed")return"Process inspection failed; setup cannot prove hosts are stopped.";return}class a extends Error{constructor($){super($);this.name="SetupRefusal",r$.set(this,$)}}var r3="OpenCode's separate Anthropic login is not used. Add that account through /claude Accounts if needed, or remove the separate login from OpenCode.";function Z9($){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 o3($,Z){let J=[];for(let z of $)if(await $9(z,Z)!=="local")J.push(Z9(z));if(J.length)throw new a(J.join(`
|
|
12
|
+
`))}function E0($,Z){return async()=>{Y8(Z.env);try{await z8(Z.fence,Z.env)}catch(J){let z=x1(J);if(z)throw new a(z);throw J}await o3([$],Z.env)}}async function t3($){try{return e7("sha256").update(await t$($)).digest("hex")}catch(Z){if(Z.code==="ENOENT")return"absent";throw new T0("unsafe-source")}}async function W1($,Z){let J;try{J=JSON.parse(await t$(Z,"utf8"))}catch(X){if(X.code!=="ENOENT")throw new T0("unsafe-source")}let z=e$($,J),G=J?.anthropic;return{...z,realLogin:z.kind==="oauth"&&Boolean(G?.access&&G.refresh)}}async function y1($,Z){let{paths:J}=$,z=$.generation2?void 0:await W1(J.host,J.hostAuthPath),G=await Promise.all([J.paths.config,J.paths.state,J.paths.runtime,J.paths.roster,J.paths.journal,J.routingDestinationPath].map(t3));return JSON.stringify([await $9(J.host,Z),z?.digest,...G])}async function e3($,Z,J){let z=Z.paths??await Y0($,Z.env),G=E0($,Z);await G();let X=await H8(z.paths);if(X&&X.host!==$)throw new T0("invalid-source");let Q=X?.phase==="committed"||X?.phase==="retired";if(X&&X.kind!=="empty-init"&&(X.hostAuthPath!==await i3(z.hostAuthPath)||X.routingPaths.source!==await i3(z.routingSourcePath)||X.routingPaths.destination!==await i3(z.routingDestinationPath)))throw new T0("invalid-source");let W={paths:z,generation2:J,action:"migration",notice:!1,fingerprint:"",authorityPhase:X?.phase??"absent",poolPopulation:"not-evaluated"};if(J){if(X&&!Q)throw new T0("invalid-source");if(W.action=X?"reuse":"empty-init",!X){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 Y of H){try{await $8(Y)}catch(q){if(q.code==="ENOENT")continue;throw new T0("unsafe-source")}throw new T0("invalid-source")}}}else{W.slot=await W1($,z.hostAuthPath),W.poolPopulation=X?.kind==="empty-init"?await Q8({paths:z.paths}):"not-evaluated";let H=W.poolPopulation===!0;if($==="opencode"&&(H||Q&&X?.kind!=="empty-init"&&W.slot.kind==="oauth"))W.action="skip",W.notice=W.slot.realLogin;else W.preflight=await W8({...z,env:Z.env,processFence:G,removePiAnthropicAuth:Z.removePiAnthropicAuth})}return W.fingerprint=await y1(W,Z.env),W}async function s0($,Z){await E0($.paths.host,Z)();let J=await e3($.paths.host,{...Z,paths:$.paths},$.generation2);try{if(J.fingerprint!==$.fingerprint||J.action!==$.action)throw new a("Setup inputs changed. Rerun setup with all hosts stopped.")}finally{if(J.preflight)U8(J.preflight)}}async function $2($,Z){if($.paths.host!=="opencode"||$.slot?.kind!=="absent")return;let J=E0("opencode",Z);await J(),await Z8(J8($.paths.hostAuthPath),{recursive:!0,mode:448}),await K8({host:"opencode",authPath:$.paths.hostAuthPath,sourceDigest:"absent",expectedDigest:e$("opencode",{anthropic:X8("anthropic")}).digest,env:Z.env,removePiAnthropicAuth:!1,processFence:J})}async function J9($,Z){let J={...Z.env},z=E0($,{...Z,env:J});await z();let G=Z.paths??await Y0($,J),X=await Z.login?.($);if(X&&!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(X.accountIdentity))throw Error("Claude sign-in did not establish an account UUID");if(await z(),await Z.beforeCommit?.(),!Z.skipMigration)await q8({paths:G.paths,legacyConfigPath:G.legacyConfigPath,legacyStatePath:G.legacyStatePath,host:$,hostAuthPath:G.hostAuthPath,routingSourcePath:G.routingSourcePath,routingDestinationPath:G.routingDestinationPath,env:J,processFence:z,removePiAnthropicAuth:Z.removePiAnthropicAuth,preflight:Z.preflight});if(X){let Q=G8({paths:G.paths,host:$,vault:{env:J},beforePoolWrite:z});try{if((await Q.read()).mode!=="local")throw new a(Z9($));await z(),await Q.loginOAuth({routeId:"main",replace:!0,...X})}finally{Q.close()}}if(Z.skipMigration){let Q=await W1($,G.hostAuthPath);await $2({paths:G,slot:Q},Z)}}var z9={opencode:"OpenCode",pi:"Pi"};function C8($,Z){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`${z9[Z]} has no read grant in the vault, so setup cannot see any Claude login. Run ${["ck",...s3(Z)].join(" ")}, then rerun setup.`;case"grant-reaches-nothing":return`${z9[Z]}'s vault read grant reaches no Claude login: no vault login carries the anthropic-native category, which logins saved before vault categories existed lack. Run ck auth reclassify --from-registry, check the logins with ck auth status, then rerun setup.`}}class z0 extends Error{code;constructor($,Z="opencode"){super(C8($,Z));this.name="NativeVaultActivationError",this.code=$}}function P8($){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 J2($){try{return JSON.parse(await V8($,"utf8"))}catch(Z){if(Z.code==="ENOENT")return;throw new z0("host-auth-invalid")}}async function H1($,Z){if($==="opencode")return"opencode";let J=Z.paths??await Y0($,Z.env),z=Z2($,await J2(J.hostAuthPath)),G=z2({env:Z.env,authPath:J.hostAuthPath}),{stashPath:X}=D8({env:Z.env,authPath:J.hostAuthPath});return JSON.stringify([z.digest,await G.inspect(),await t3(X)])}async function G9($){try{N8($.env)}catch{throw new z0("auth-content-refused")}try{await j8($.fence,$.env)}catch(Z){let J=x1(Z);if(J)throw new a(J);throw Z}}async function X9($,Z){let J={...Z.env};await(()=>G9({...Z,env:J}))();let G=Z.paths??await Y0($,J),X=$==="opencode"&&Z.inspectOpenCodeAuth!==!1&&Z2("opencode",await J2(G.hostAuthPath)).kind==="oauth";if($==="pi"){let Q=Z2("pi",await J2(G.hostAuthPath)),W=await z2({env:J,authPath:G.hostAuthPath}).inspect();if(W.slot==="placeholder"&&W.stash==="missing")throw new B8("missing-stash");if(Q.kind!=="absent"&&W.slot!=="placeholder"&&!Z.removePiAnthropicAuth)throw new z0("consent-required")}return{priorMode:await L8($,J),fingerprint:await H1($,{...Z,env:J}),separateOpenCodeLogin:X}}async function Q9($,Z,J){let z={...Z.env},G=()=>G9({...Z,env:z});await G();let X=Z.paths??await Y0($,z);if(await H1($,Z)!==J.fingerprint)throw new z0("host-auth-invalid");await u$($,{env:z,runner:Z.runner,processFence:G,ckBinary:Z.enrollment?.ckBinary});let Q=Z.discover??(()=>F8({paths:X.paths,host:$,env:$==="pi"?{...z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE}:z})),W,H=async()=>{return W=await Q(),W},Y=M8({paths:X.paths,host:$,vault:{env:z,discover:H}});try{await G(),await Y.vault.refresh();let q=await Y.read(),K=q.accounts.find((F)=>F.id==="main");if(q.mode!=="claustrum"||!K?.accountIdentity||K.source!=="vault"){let F=P8(W);throw F==="primary-unverified"?new z0(F):new z0(F,$)}if(await G(),$==="pi")await z2({env:z,authPath:X.hostAuthPath}).enterVault();return J.priorMode==="claustrum"?"already-vault":"committed"}finally{Y.close()}}var O8=/(?:^|[/\\])(opencode|litecode|opencode2|pi)(?:\.exe)?(?=$|\s|")/i;class G2 extends Error{activeHosts;constructor($){let Z=$.map((z)=>({pid:z.pid,command:O8.exec(z.command)?.[1]??"host"})),J=Z.map((z)=>` - PID ${z.pid}: ${z.command}`).join(`
|
|
13
13
|
`);super(`OpenCode or Pi processes are currently running:
|
|
14
14
|
${J}
|
|
15
15
|
|
|
16
|
-
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=Z,this.name="ProcessFenceViolationError"}}var
|
|
17
|
-
`,$.length-
|
|
18
|
-
`,
|
|
16
|
+
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=Z,this.name="ProcessFenceViolationError"}}var h8={"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 U1(){return($)=>$}var W2=["opencode","pi"],v8=new Set(["enrolled","not-enrolled","unknown"]),K9=U1()(["auth-content-refused","host-auth-invalid","primary-conflict","consent-required","primary-unverified","no-read-grant","grant-reaches-nothing"]),V9=U1()(["enrollment-refused","enrollment-reset","approval-refused","permission-refused"]),j9=U1()(["invalid-source","unsafe-source","consent-required","primary-unverified","migration-busy","ownership-lost","retirement-refused","pool-populated","host-login-present","settings-changed"]),M9=U1()(["invalid-options","invalid-auth","invalid-stash","unsafe-path","missing-stash","conflict","lock-timeout","lock-compromised","io"]),F9=U1()(["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"]),m8={name:new Set(["Error","TypeError","SyntaxError","RangeError","AggregateError","AbortError","PrivateFileError","PrivateFilesUnavailableError","DiagnosticFileError","NativeRuntimeError","NativeAuthorityError","NativeMigrationError","NativeMigrationSourceError","NativeHostAuthError","NativeHostAuthWriteError","NativePiAuthSlotError","NativeCustodyError","NativeVaultActivationError","NativeVaultEnrollmentError","SetupCommandError","ProcessFenceViolationError","ProcessInspectionError","LockOwnershipError","LockContentionError","ClaustrumConsumerError","ClaustrumCredentialError"]),code:new Set([...K9,...V9,...j9,...M9,...F9,"EACCES","EPERM","ENOENT","EEXIST","ENOTDIR","EISDIR","ENOTEMPTY","EBUSY","ETIMEDOUT","ECONNREFUSED","ECONNRESET","ECANCELED","EIO","EINVAL","ENOTSUP","ENOSYS","ENOMEM","EMFILE","ENFILE","ELOOP","EROFS","EXDEV","ENAMETOOLONG","EBADF","EPIPE","ENOSPC","EINTR","ERR_INVALID_ARG_TYPE","ERR_INVALID_ARG_VALUE","ERR_OUT_OF_RANGE","ERR_FEATURE_UNAVAILABLE_ON_PLATFORM","ERR_PRIVATE_FILES_SECURITY","ERR_PRIVATE_FILES_UNAVAILABLE","ERR_PRIVATE_FILE","ERR_DIAGNOSTICS_DIRECTORY_UNAVAILABLE","ERR_DIAGNOSTICS_NOT_DIRECTORY","ERR_DIAGNOSTICS_NOT_OWNER_ONLY","unsafe-runtime","invalid-runtime","runtime-io","runtime-conflict","publication-refused","invalid-journal","source-io","source-changed","source-too-large","write-io"]),stage:new Set(["safe-parent","verify","directory","read","create","directory-create","rename","stage-directory","stage-create","before-rename","published-callback","published-verify","directory-sync-unsupported"]),reason:new Set(["wrong-owner","extra-ace","not-protected","null-dacl","empty-dacl","reparse-point","unsupported-filesystem","unsafe-ancestor","wrong-kind","io-error","mode","writable-by-others"])},w8=new Set([...K9.flatMap(($)=>$==="no-read-grant"||$==="grant-reaches-nothing"?W2.map((Z)=>new z0($,Z).message):[new z0($).message]),...V9.map(($)=>new Q1($).message),...j9.map(($)=>new g8($).message),...M9.map(($)=>new x8($).message),...F9.map(($)=>`Native custody refused: ${$}`),"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 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@2.0.0 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","OAuth metadata read failed"]),u8=new Set(["opencode","litecode","opencode2","pi","host"]),c8=64,p8=256,d8=4096,X2=65536,l8=4096,a8=3,H9="[output beyond the diagnostic limit omitted]",s8="[output withheld: no line break within the inspected window]",n8="[detail withheld: the known credentials could not be read safely]",U2=new TextEncoder,B9=new TextDecoder;function v($,Z){let J=Object.getOwnPropertyDescriptor($,Z);return J!==void 0&&"value"in J?J.value:void 0}function q0($){return $!==null&&(typeof $==="object"||typeof $==="function")&&!H2.isProxy($)}function Y2($,Z){if(!q0($)||!Array.isArray($))return;let J=v($,"length");if(typeof J!=="number"||J>Z)return;let z=[];for(let G=0;G<J;G+=1){let X=Object.getOwnPropertyDescriptor($,String(G));if(X===void 0||!("value"in X))return;z.push(X.value)}return z}function i8($){let Z=Y2($,c8);if(Z===void 0||Z.length===0)return;let J=[];for(let z of Z){if(!q0(z))return;let G=v(z,"pid"),X=v(z,"command");if(typeof G!=="number"||!Number.isSafeInteger(G)||G<0)return;if(typeof X!=="string"||!u8.has(X.toLowerCase()))return;J.push({pid:G,command:X})}return J}function q2($){try{if(!q0($))return;if(v($,"name")==="ProcessInspectionError")return"";let Z=v($,"message");if(typeof Z!=="string")return;if(w8.has(Z))return Z;if(Z.startsWith("Unknown setup argument: "))return Z;let J=v($,"status");if(typeof J==="number"&&Number.isInteger(J)&&J>=100&&J<=599&&Z===`OAuth metadata read failed: ${J}`)return Z;let z=i8(v($,"activeHosts"));if(z){let G=new G2(z).message;if(Z===G)return G}}catch{}return}function D9($){try{if(!q0($))return;let Z=Y2(y8($),W2.length);if(Z===void 0)return;let J=[];for(let z of Z){if(!q0(z))return;let G=W2.find((Q)=>Q===v(z,"host")),X=v(z,"outcome");if(G===void 0||!v8.has(X))return;J.push({host:G,outcome:X})}return J}catch{return}}function r8($,Z=[]){try{let J=new Set,z=Y2(Z,p8);if(z===void 0)return;for(let X of z){if(typeof X!=="string")return;if(X!=="")J.add(X)}if(!q0($))return;let G=Reflect.ownKeys($);if(G.length>d8)return;for(let X of G){if(typeof X!=="string"||!f8(X))continue;let Q=Object.getOwnPropertyDescriptor($,X);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 o8($,Z){let J=U2.encode($);if(J.length<=Z)return $;let z=Math.max(0,Z);while(z>0&&((J[z]??0)&192)===128)z-=1;return B9.decode(J.subarray(0,z))}function t8($,Z){let J=U2.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 B9.decode(J.subarray(z))}function e8($,Z,J){let z=$,G=!1;if($.length>X2){if(G=!0,J==="tail"){let H=$.indexOf(`
|
|
17
|
+
`,$.length-X2);z=H===-1?"":$.slice(H+1)}else{let H=$.lastIndexOf(`
|
|
18
|
+
`,X2);z=H===-1?"":$.slice(0,H)}if(z==="")return[s8]}let X=Z.redactText(z).split(/\r?\n/);if(X.length>1&&X[X.length-1]==="")X.pop();if(J==="tail")X.reverse();let Q=[],W=l8;for(let H of X){let Y=U2.encode(H).length+1;if(Y<=W){Q.push(H),W-=Y;continue}if(Q.length===0)Q.push(J==="tail"?t8(H,W-1):o8(H,W-1));G=!0;break}if(J==="tail")Q.reverse();if(G)if(J==="tail")Q.unshift(H9);else Q.push(H9);return Q}function L9($){let Z=$;for(let J=0;Z!==null&&J<8;J+=1){if(H2.isProxy(Z))break;let z=v(Z,"name");if(typeof z==="string")return z;Z=Object.getPrototypeOf(Z)}return"object"}function U9($,Z){let J={};if(Z===void 0)return J;try{if(!q0($))return J;let z=q9(Z);try{for(let G of["name","code","stage","reason"]){let X=G==="name"?L9($):v($,G);if(typeof X==="string"&&m8[G].has(X)&&z.redactText(X)===X)J[G]=X}}finally{z.dispose()}}catch{return{}}return J}function $6($){if(!q0($))return;let Z=v($,"step"),J=v($,"exitCode"),z=v($,"signal"),G=v($,"stderrTail");if(typeof Z!=="string"||Z.length===0||!(J===null||typeof J==="number"&&Number.isInteger(J))||!(z===null||typeof z==="string")||typeof G!=="string")return;return{step:Z,exitCode:J,signal:z,stderrTail:G}}function N9($,Z){if($===null||typeof $!=="object"&&typeof $!=="function")return[`thrown ${typeof $}: ${String($)}`];if(H2.isProxy($))return["thrown proxy (not inspected)"];let J=[],z=L9($),G=v($,"message");J.push(typeof G==="string"?`${z}: ${G}`:`${z} (no message)`);let X=v($,"code");if(typeof X==="string"||typeof X==="number")J.push(`code: ${X}`);let Q=v($,"stack");if(typeof Q==="string")J.push(Q);let W=v($,"cause");if(W!==void 0)if(Z>=a8)J.push("caused by: [not described]");else J.push("caused by:",...N9(W,Z+1));return J}function Y9($,Z){let J=v($,Z);return typeof J==="string"&&J!==""?J:void 0}function Z6($){if(!q0($))return;let Z=Y9($,"XDG_STATE_HOME"),J=Y9($,"HOME"),z=Z&&W9(Z)?Z:Q2(J&&W9(J)?J:S8(),".local","state");return Q2(z,"cortexkit","anthropic-auth","diagnostics")}async function J6($,Z,J,z={}){let G=(X)=>({error:{name:"DiagnosticFileError",code:X}});try{let X=Z6($);if(X===void 0)return G("ERR_DIAGNOSTICS_DIRECTORY_UNAVAILABLE");if(!await k8(X,z)){await A8(X,{recursive:!0,mode:448});let H=await _8(X);if(!H.isDirectory())return G("ERR_DIAGNOSTICS_NOT_DIRECTORY");if(!await E8(X,()=>(H.mode&63)===0&&H.uid===process.getuid?.(),z))return G("ERR_DIAGNOSTICS_NOT_OWNER_ONLY")}let Q=Q2(X,`${Z}-${Date.now()}-${process.pid}-${I8()}.log`);if(await b8(Q,J,z))return{path:Q};let W=await R8(Q,h1.O_WRONLY|h1.O_CREAT|h1.O_EXCL|(h1.O_NOFOLLOW??0),384);try{await W.writeFile(J,"utf8")}finally{await W.close()}return{path:Q}}catch(X){return{error:X}}}async function z6($,Z,J,z,G,X,Q,W={}){let H,Y=r8(J,z);if(Y===void 0)H=[n8];else try{let P=q9(Y);try{let{text:C,keep:D}=X();H=e8(C,P,D)}finally{P.dispose()}}catch{H=["[failure detail could not be recorded]"]}let q=h8[$],K=T8("error","cli",`${q} failed`,{stage:$,code:Z,...G}),F=await J6(J,$,`${[K,...H].join(`
|
|
19
19
|
`)}
|
|
20
|
-
`,W.ownership),
|
|
21
|
-
`)}catch{}}return
|
|
22
|
-
${
|
|
23
|
-
`),keep:"head"}),Z,
|
|
24
|
-
`)J.push("enter");else if(
|
|
25
|
-
`),
|
|
26
|
-
`),q=!1;for(let
|
|
27
|
-
`){if(
|
|
28
|
-
`){if(
|
|
29
|
-
`)}var
|
|
30
|
-
`),
|
|
20
|
+
`,W.ownership),B=F.path;if(B===void 0){let P={error:U9(Q,Y),saveError:U9(F.error,Y)};try{(W.stderr??((D)=>process.stderr.write(D)))(`CLI failure metadata: ${JSON.stringify(P)}
|
|
21
|
+
`)}catch{}}return B===void 0?`${q} failed (${Z}). Details could not be saved to a private diagnostics file.`:`${q} failed (${Z}). Details were written to ${B}`}async function Y1($,Z,J,z=[],G={}){let X=q2(Z);if(X!==void 0)return X;let Q=$6(Z);return z6($,`${$}/unexpected-error`,J,z,{},()=>({text:[...Q?[`step: ${Q.step}`,`exitCode: ${Q.exitCode}`,`signal: ${Q.signal}`]:[],...N9(Z,0),...Q?[`stderrTail:
|
|
22
|
+
${Q.stderrTail}`]:[]].join(`
|
|
23
|
+
`),keep:"head"}),Z,G)}import{createProcessFence as R5,NativePiAuthSlotError as S5,openNativePiAuthSlot as b5,publishNativeEmptyInit as k5,readNativeEnrollmentMode as T5,releaseNativeMigrationPreflight as E5,requireNoSupervisedAuthContentSnapshot as f5,runSetup as g5}from"@cortexkit/anthropic-auth-core";import{AsyncLocalStorage as X6}from"node:async_hooks";var rG=new X6;var C9=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});var n0="commonAuthPool";var R6=Object.freeze(["version","accounts",n0]);var A={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 D2($){let Z=$.toString(),J=[];for(let z=0;z<Z.length;){let G=Z[z];if(G==="\x1B"){let X=Z.slice(z,z+3),Q=X[1]==="["||X[1]==="O"?X[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(G==="\r"||G===`
|
|
24
|
+
`)J.push("enter");else if(G==="\x03")J.push("escape");else if(G&&G>=" ")J.push("char");z+=1}return J}var E9=`${String.fromCharCode(27)}\\[[0-9;]*m`,S6=new RegExp(E9,"g"),b6=new RegExp(`^${E9}`);function f9($){return $.replace(S6,"")}function f0($,Z){if(Z<=0)return"";if(f9($).length<=Z)return $;let J=Z>=3?"...":".".repeat(Z),z=Math.max(0,Z-J.length),G="",X=0,Q=0;while(X<$.length&&Q<z){if($[X]==="\x1B"){let W=$.slice(X).match(b6);if(W){G+=W[0],X+=W[0].length;continue}}G+=$[X],X+=1,Q+=1}return G.includes("\x1B[")?`${G}${A.reset}${J}`:G+J}function r0($){return $.input.isTTY===!0}var k6=50;function T6($){if($==="red")return A.red;if($==="cyan")return A.cyan;return""}async function p1($,Z,J){if(!r0($))throw Error("Interactive select requires a TTY terminal");if(Z.length===0)throw Error("No menu items provided");let{input:z,output:G,signals:X}=$,Q=0,W=null,H=!1,Y=0,q=()=>{let K=G.columns??80,F=G.rows??24,B=Y;if(J.clearScreen)G.write(A.clearScreen+A.moveTo(1,1));else if(B>0)G.write(A.up(B));let P=0,C=(V)=>{G.write(`${A.clearLine}${V}
|
|
25
|
+
`),P+=1},D=J.lines??[],R=1+(J.subtitle?3:0)+D.length+(D.length?1:0),S=Math.max(1,Math.min(Z.length,F-R-2-1)),y=Math.max(0,Math.min(Q-Math.floor(S/2),Math.max(0,Z.length-S))),L=Z.slice(y,y+S);if(C(`${A.dim}┌ ${A.reset}${f0(J.message,Math.max(1,K-4))}`),J.subtitle)C(`${A.dim}│${A.reset}`),C(`${A.cyan}◆${A.reset} ${f0(J.subtitle,Math.max(1,K-4))}`),C("");for(let V of D)C(`${A.cyan}│${A.reset} ${f0(V,Math.max(1,K-4))}`);if(D.length)C(`${A.cyan}│${A.reset}`);for(let V=0;V<L.length;V++){let j=L[V];if(!j)continue;let b=y+V===Q,g=T6(j.color),k=g?`${b?"":A.dim}${g}${j.label}${A.reset}`:b?j.label:`${A.dim}${j.label}${A.reset}`;if(j.hint)k+=` ${A.dim}${j.hint}${A.reset}`;k=f0(k,Math.max(1,K-8)),C(b?`${A.cyan}│${A.reset} ${A.green}●${A.reset} ${k}`:`${A.cyan}│${A.reset} ${A.dim}○${A.reset} ${k}`)}let U=L.length<Z.length?` (${y+1}-${y+L.length}/${Z.length})`:"";C(`${A.cyan}│${A.reset} ${A.dim}${f0(`Up/Down to select | Enter: confirm | Esc: back${U}`,Math.max(1,K-6))}${A.reset}`),C(`${A.cyan}└${A.reset}`);for(let V=P;V<B;V++)C("");Y=P};return new Promise((K)=>{let F=z.isRaw??!1,B=()=>{if(H)return;if(H=!0,W)clearTimeout(W);z.removeListener("data",D);try{z.setRawMode(F),z.pause(),G.write(A.show)}catch{}X?.removeListener("SIGINT",C),X?.removeListener("SIGTERM",C)},P=(R)=>{B(),K(R)},C=()=>P(null),D=(R)=>{for(let S of D2(R)){if(H)break;if(W)clearTimeout(W),W=null;switch(S){case"up":Q=(Q-1+Z.length)%Z.length,q();break;case"down":Q=(Q+1)%Z.length,q();break;case"enter":P(Z[Q]?.value??null);break;case"escape":P(null);break;case"escape-start":W=setTimeout(()=>P(null),k6);break;default:break}}};X?.once("SIGINT",C),X?.once("SIGTERM",C);try{z.setRawMode(!0)}catch{B(),K(null);return}z.resume(),G.write(A.hide),q(),z.on("data",D)})}async function d1($,Z,J=!1){if(!r0($))return!1;return await p1($,J?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:Z})??!1}import{execFile as h6}from"node:child_process";import{promisify as v6}from"node:util";var m6=v6(h6),g9={async run($,Z,J={}){try{let z=J.env?{...process.env,...J.env}:process.env,{stdout:G,stderr:X}=await m6($,Z,{env:z,timeout:J.timeoutMs??15000,maxBuffer:10485760});return{exitCode:0,stdout:typeof G==="string"?G:String(G),stderr:typeof X==="string"?X:String(X)}}catch(z){let G=z;return{exitCode:typeof G?.code==="number"?G.code:1,signal:typeof G?.signal==="string"?G.signal:null,...typeof G?.syscall==="string"&&(G.syscall==="spawn"||G.syscall.startsWith("spawn "))?{spawnError:!0}:{},stdout:typeof G?.stdout==="string"?G.stdout:G?.stdout!=null?String(G.stdout):"",stderr:typeof G?.stderr==="string"?G.stderr:G?.stderr!=null?String(G.stderr):String(G?.message??z)}}}};import{styleText as r1}from"node:util";import{stdout as J5,stdin as z5}from"node:process";import G5 from"node:readline";var x9=(()=>{let $=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(Z)=>{let J=0;$.lastIndex=0;while($.test(Z))J+=1;return Z.length-J}})(),y9=($)=>{return $===12288||$>=65281&&$<=65376||$>=65504&&$<=65510},h9=($)=>{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 w6=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,u6=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,v9=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,c6=/\t{1,1000}/y,m9=/[\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,p6=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,d6=/\p{M}+/gu,l6={limit:1/0,ellipsis:""},w9=($,Z={},J={})=>{let z=Z.limit??1/0,G=Z.ellipsis??"",X=Z?.ellipsisWidth??(G?w9(G,l6,J).width:0),Q=0,W=J.controlWidth??0,H=J.tabWidth??8,Y=J.emojiWidth??2,q=2,K=J.regularWidth??1,F=J.wideWidth??2,B=[[p6,K],[w6,0],[u6,W],[c6,H],[m9,Y],[v9,F]],P=0,C=0,D=$.length,R=0,S=!1,y=D,L=Math.max(0,z-X),U=0,V=0,j=0,b=0;$:while(!0){if(V>U||C>=D&&C>P){let g=$.slice(U,V)||$.slice(P,C);R=0;for(let k of g.replaceAll(d6,"")){let m=k.codePointAt(0)||0;if(y9(m))b=2;else if(h9(m))b=F;else b=K;if(j+b>L)y=Math.min(y,Math.max(U,P)+R);if(j+b>z){S=!0;break $}R+=k.length,j+=b}U=V=0}if(C>=D)break $;for(let g=0,k=B.length;g<k;g++){let[m,n]=B[g];if(m.lastIndex=C,m.test($)){if(R=m===v9?x9($.slice(C,m.lastIndex)):m===m9?1:m.lastIndex-C,b=R*n,j+b>L)y=Math.min(y,C+Math.floor((L-j)/n));if(j+b>z){S=!0;break $}j+=b,U=P,V=C,C=P=m.lastIndex;continue $}}C+=1}return{width:S?L:j,index:S?y:D,truncated:S,ellipsed:S&&z>=X}},u9=w9;var a6={limit:1/0,ellipsis:"",ellipsisWidth:0},s6=($,Z={})=>{return u9($,a6,Z).width},G0=s6;var l1="\x1B",a9="",n6=39,N2="\x07",s9="[",i6="]",n9="m",C2=`${i6}8;;`,c9=new RegExp(`(?:\\${s9}(?<code>\\d+)m|\\${C2}(?<uri>.*)${N2})`,"y"),p9=($)=>{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},d9=($)=>`${l1}${s9}${$}${n9}`,l9=($)=>`${l1}${C2}${$}${N2}`,L2=($,Z,J)=>{let z=Z[Symbol.iterator](),G=!1,X=!1,Q=$.at(-1),W=Q===void 0?0:G0(Q),H=z.next(),Y=z.next(),q=0;while(!H.done){let K=H.value,F=G0(K);if(W+F<=J)$[$.length-1]+=K;else $.push(K),W=0;if(K===l1||K===a9)G=!0,X=Z.startsWith(C2,q+1);if(G){if(X){if(K===N2)G=!1,X=!1}else if(K===n9)G=!1}else if(W+=F,W===J&&!Y.done)$.push(""),W=0;H=Y,Y=z.next(),q+=K.length}if(Q=$.at(-1),!W&&Q!==void 0&&Q.length&&$.length>1)$[$.length-2]+=$.pop()},r6=($)=>{let Z=$.split(" "),J=Z.length;while(J){if(G0(Z[J-1]))break;J--}if(J===Z.length)return $;return Z.slice(0,J).join(" ")+Z.slice(J).join("")},o6=($,Z,J={})=>{if(J.trim!==!1&&$.trim()==="")return"";let z="",G,X,Q=$.split(" "),W=[""],H=0;for(let K=0;K<Q.length;K++){let F=Q[K];if(J.trim!==!1){let P=W.at(-1)??"",C=P.trimStart();if(P.length!==C.length)W[W.length-1]=C,H=G0(C)}if(K!==0){if(H>=Z&&(J.wordWrap===!1||J.trim===!1))W.push(""),H=0;if(H||J.trim===!1)W[W.length-1]+=" ",H++}let B=G0(F);if(J.hard&&B>Z){let P=Z-H,C=1+Math.floor((B-P-1)/Z);if(Math.floor((B-1)/Z)<C)W.push("");L2(W,F,Z),H=G0(W.at(-1)??"");continue}if(H+B>Z&&H&&B){if(J.wordWrap===!1&&H<Z){L2(W,F,Z),H=G0(W.at(-1)??"");continue}W.push(""),H=0}if(H+B>Z&&J.wordWrap===!1){L2(W,F,Z),H=G0(W.at(-1)??"");continue}W[W.length-1]+=F,H+=B}if(J.trim!==!1)W=W.map((K)=>r6(K));let Y=W.join(`
|
|
26
|
+
`),q=!1;for(let K=0;K<Y.length;K++){let F=Y[K];if(z+=F,!q){if(q=F>="\uD800"&&F<="\uDBFF",q)continue}else q=!1;if(F===l1||F===a9){c9.lastIndex=K+1;let P=c9.exec(Y)?.groups;if(P?.code!==void 0){let C=Number.parseFloat(P.code);G=C===n6?void 0:C}else if(P?.uri!==void 0)X=P.uri.length===0?void 0:P.uri}if(Y[K+1]===`
|
|
27
|
+
`){if(X)z+=l9("");let B=G?p9(G):void 0;if(G&&B)z+=d9(B)}else if(F===`
|
|
28
|
+
`){if(G&&p9(G))z+=d9(G);if(X)z+=l9(X)}}return z},t6=/\r?\n/;function a1($,Z,J){return String($).normalize().split(t6).map((z)=>o6(z,Z,J)).join(`
|
|
29
|
+
`)}var r=t9(O2(),1);function _2($,Z,J){if(!J.some((Q)=>!Q.disabled))return $;let z=$+Z,G=Math.max(J.length-1,0),X=z<0?G:z>G?0:z;return J[X]?.disabled?_2(X,Z<0?-1:1,J):X}function s1($,Z,J,z){let G=z.split(`
|
|
30
|
+
`),X=0,Q=$;for(let H of G){if(Q<=H.length)break;Q-=H.length+1,X++}for(X=Math.max(0,Math.min(G.length-1,X+J)),Q=Math.min(Q,G[X].length)+Z;Q<0&&X>0;)X--,Q+=G[X].length+1;for(;Q>G[X].length&&X<G.length-1;)Q-=G[X].length+1,X++;Q=Math.max(0,Math.min(G[X].length,Q));let W=0;for(let H=0;H<X;H++)W+=G[H].length+1;return W+Q}var X5=["up","down","left","right","space","enter","cancel"],Q5=["January","February","March","April","May","June","July","August","September","October","November","December"],$0={actions:new Set(X5),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:[...Q5],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 W5($){if($!==void 0)return $;if($0.accessible!==void 0)return $0.accessible;let Z=process.env.ACCESSIBLE;return Z!==void 0&&Z!==""&&Z!=="0"&&Z!=="false"}function e9($,Z){if(typeof $=="string")return $0.aliases.get($)===Z;for(let J of $)if(J!==void 0&&e9(J,Z))return!0;return!1}function H5($,Z){if($===Z)return;let J=$.split(`
|
|
31
31
|
`),z=Z.split(`
|
|
32
|
-
`),
|
|
33
|
-
`),
|
|
34
|
-
`).length-1;this.output.write(
|
|
35
|
-
`);this.output.write(X
|
|
36
|
-
`).slice(
|
|
37
|
-
`)),this._prevFrame=$;return}}this.output.write(i.erase.down())}this.output.write($),this.state==="initial"&&(this.state="active"),this._prevFrame=$}}}function c8($,Z){if($===void 0||Z.length===0)return 0;let J=Z.findIndex((z)=>z.value===$);return J!==-1?J:0}function p8($,Z){return(Z.label??String(Z.value)).toLowerCase().includes($.toLowerCase())}function d8($,Z){if(Z)return $?Z:Z[0]}var l8=class extends l0{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#z="";#Z;#Q;#H;#G;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return d1(["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}${d1("inverse",J)}${z}`}get options(){return typeof this.#Q=="function"?this.#Q():this.#Q}constructor(Z){super(Z),this.#Q=Z.options,this.#H=Z.placeholder,this.#G=Z.completeOnTab===!0;let J=this.options;this.filteredOptions=[...J],this.multiple=Z.multiple===!0,this.#Z=typeof Z.options=="function"?Z.filter:Z.filter??p8;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 Q of z){let G=J.findIndex((X)=>X.value===Q);G!==-1&&(this.toggleSelected(Q),this.#$=G)}this.focusedValue=this.options[this.#$]?.value,this.on("key",(Q,G)=>this.#J(Q,G)),this.on("userInput",(Q)=>this.#U(Q))}_isActionKey(Z,J){return Z==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&Z!==void 0&&Z!==""}#J(Z,J){let z=J.name==="up",Q=J.name==="down",G=J.name==="return",X=this.userInput===""||this.userInput==="\t",W=this.#H,H=this.options,Y=W!==void 0&&W!==""&&H.some((q)=>!q.disabled&&(this.#Z?this.#Z(W,q):!0));if(J.name==="tab"&&X&&Y){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(W,!0),this.isNavigating=!1;return}if(J.name==="tab"&&this.#G&&!this.multiple&&this.focusedValue!==void 0){let q=String(this.focusedValue);this._clearUserInput(),this._setUserInput(q,!0),this.isNavigating=!1;return}z||Q?(this.#$=F$(this.#$,z?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):G?this.value=d8(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])}#U(Z){if(Z!==this.#z){this.#z=Z;let J=this.options;Z&&this.#Z?this.filteredOptions=J.filter((G)=>this.#Z?.(Z,G)):this.filteredOptions=[...J];let z=c8(this.focusedValue,this.filteredOptions);this.#$=F$(z,0,this.filteredOptions);let Q=this.filteredOptions[this.#$];Q&&!Q.disabled?this.focusedValue=Q.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};var a8={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function f9($){return[...$].map((Z)=>a8[Z])}function s8($){let Z=new Intl.DateTimeFormat($,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),J=[],z="/";for(let Q of Z)Q.type==="literal"?z=Q.value.trim()||Q.value:(Q.type==="year"||Q.type==="month"||Q.type==="day")&&J.push({type:Q.type,len:Q.type==="year"?4:2});return{segments:J,separator:z}}function M$($){return Number.parseInt(($||"0").replace(/_/g,"0"),10)||0}function p1($){return{year:M$($.year),month:M$($.month),day:M$($.day)}}function B$($,Z){return new Date($||2001,Z||1,0).getDate()}function m9($){let{year:Z,month:J,day:z}=p1($);if(!Z||Z<0||Z>9999||!J||J<1||J>12||!z||z<1)return;let Q=new Date(Date.UTC(Z,J-1,z));if(!(Q.getUTCFullYear()!==Z||Q.getUTCMonth()!==J-1||Q.getUTCDate()!==z))return{year:Z,month:J,day:z}}function g9($){let Z=m9($);return Z?new Date(Date.UTC(Z.year,Z.month-1,Z.day)):void 0}function n8($,Z,J,z){let Q=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:Q?.year??1,max:G?.year??9999}:$==="month"?{min:Q&&Z.year===Q.year?Q.month:1,max:G&&Z.year===G.year?G.month:12}:{min:Q&&Z.year===Q.year&&Z.month===Q.month?Q.day:1,max:G&&Z.year===G.year&&Z.month===G.month?G.day:B$(Z.year,Z.month)}}class w9 extends l0{#$;#z;#Z;#Q;#H;#G={segmentIndex:0,positionInSegment:0};#J=!0;#U=null;inlineError="";get segmentCursor(){return{...this.#G}}get segmentValues(){return{...this.#Z}}get segments(){return this.#$}get separator(){return this.#z}get formattedValue(){return this.#V(this.#Z)}#V($){return this.#$.map((Z)=>$[Z.type]).join(this.#z)}#W(){this._setUserInput(this.#V(this.#Z)),this._setValue(g9(this.#Z)??void 0)}constructor($){let Z=$.format?{segments:f9($.format),separator:$.separator??"/"}:s8($.locale),J=$.separator??Z.separator,z=$.format?f9($.format):Z.segments,Q=$.initialValue??$.defaultValue,G=Q?{year:String(Q.getUTCFullYear()).padStart(4,"0"),month:String(Q.getUTCMonth()+1).padStart(2,"0"),day:String(Q.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},X=z.map((W)=>G[W.type]).join(J);super({...$,initialUserInput:X},!1),this.#$=z,this.#z=J,this.#Z=G,this.#Q=$.minDate,this.#H=$.maxDate,this.#W(),this.on("cursor",(W)=>this.#K(W)),this.on("key",(W,H)=>this.#F(W,H)),this.on("finalize",()=>this.#M($))}#X(){let $=Math.max(0,Math.min(this.#G.segmentIndex,this.#$.length-1)),Z=this.#$[$];if(Z)return this.#G.positionInSegment=Math.max(0,Math.min(this.#G.positionInSegment,Z.len-1)),{segment:Z,index:$}}#q($){this.inlineError="",this.#U=null;let Z=this.#X();Z&&(this.#G.segmentIndex=Math.max(0,Math.min(this.#$.length-1,Z.index+$)),this.#G.positionInSegment=0,this.#J=!0)}#j($){let Z=this.#X();if(!Z)return;let{segment:J}=Z,z=this.#Z[J.type],Q=!z||z.replace(/_/g,"")==="",G=Number.parseInt((z||"0").replace(/_/g,"0"),10)||0,X=n8(J.type,p1(this.#Z),this.#Q,this.#H),W;Q?W=$===1?X.min:X.max:W=Math.max(Math.min(X.max,G+$),X.min),this.#Z={...this.#Z,[J.type]:W.toString().padStart(J.len,"0")},this.#J=!0,this.#U=null,this.#W()}#K($){if($)switch($){case"right":return this.#q(1);case"left":return this.#q(-1);case"up":return this.#j(1);case"down":return this.#j(-1)}}#F($,Z){if(Z?.name==="backspace"||Z?.sequence===""||Z?.sequence==="\b"||$===""||$==="\b"){this.inlineError="";let J=this.#X();if(!J)return;if(!this.#Z[J.segment.type].replace(/_/g,"")){this.#q(-1);return}this.#Z[J.segment.type]="_".repeat(J.segment.len),this.#J=!0,this.#G.positionInSegment=0,this.#W();return}if(Z?.name==="tab"){this.inlineError="";let J=this.#X();if(!J)return;let z=Z.shift?-1:1,Q=J.index+z;Q>=0&&Q<this.#$.length&&(this.#G.segmentIndex=Q,this.#G.positionInSegment=0,this.#J=!0);return}if($&&/^[0-9]$/.test($)){let J=this.#X();if(!J)return;let{segment:z}=J,Q=!this.#Z[z.type].replace(/_/g,"");if(this.#J&&this.#U!==null&&!Q){let B=this.#U+$,L={...this.#Z,[z.type]:B},F=this.#Y(L,z);if(F){this.inlineError=F,this.#U=null,this.#J=!1;return}this.inlineError="",this.#Z[z.type]=B,this.#U=null,this.#J=!1,this.#W(),J.index<this.#$.length-1&&(this.#G.segmentIndex=J.index+1,this.#G.positionInSegment=0,this.#J=!0);return}this.#J&&!Q&&(this.#Z[z.type]="_".repeat(z.len),this.#G.positionInSegment=0),this.#J=!1,this.#U=null;let G=this.#Z[z.type],X=G.indexOf("_"),W=X>=0?X:Math.min(this.#G.positionInSegment,z.len-1);if(W<0||W>=z.len)return;let H=G.slice(0,W)+$+G.slice(W+1),Y=!1;if(W===0&&G==="__"&&(z.type==="month"||z.type==="day")){let B=Number.parseInt($,10);H=`0${$}`,Y=B<=(z.type==="month"?1:2)}if(z.type==="year"&&(H=(G.replace(/_/g,"")+$).padStart(z.len,"_")),!H.includes("_")){let B={...this.#Z,[z.type]:H},L=this.#Y(B,z);if(L){this.inlineError=L;return}}this.inlineError="",this.#Z[z.type]=H;let q=H.includes("_")?void 0:m9(this.#Z);if(q){let{year:B,month:L}=q,F=B$(B,L);this.#Z={year:String(Math.max(0,Math.min(9999,B))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,L))).padStart(2,"0"),day:String(Math.max(1,Math.min(F,q.day))).padStart(2,"0")}}this.#W();let V=H.indexOf("_");Y?(this.#J=!0,this.#U=$):V>=0?this.#G.positionInSegment=V:X>=0&&J.index<this.#$.length-1?(this.#G.segmentIndex=J.index+1,this.#G.positionInSegment=0,this.#J=!0):this.#G.positionInSegment=Math.min(W+1,z.len-1)}}#Y($,Z){let{month:J,day:z}=p1($);if(Z.type==="month"&&(J<0||J>12))return $0.date.messages.invalidMonth;if(Z.type==="day"&&(z<0||z>31))return $0.date.messages.invalidDay(31,"any month")}#M($){let{year:Z,month:J,day:z}=p1(this.#Z);if(Z&&J&&z){let Q=B$(Z,J);this.#Z={...this.#Z,day:String(Math.min(z,Q)).padStart(2,"0")}}this.value=g9(this.#Z)??$.defaultValue??void 0}}var i8=class extends l0{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((Q)=>z.includes(Q.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((Q)=>z.findIndex((G)=>G.value===Q)===-1):this.value=[...this.value,...z.map((Q)=>Q.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,Q])=>[{value:z,group:!0,label:z},...Q.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 Q=this.options[this.cursor]?.group===!0;!this.#$&&Q&&(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 Q=this.options[this.cursor]?.group===!0;!this.#$&&Q&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},r8=new Set(["up","down","left","right"]);class u9 extends l0{#$=!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===`
|
|
32
|
+
`),G=Math.max(J.length,z.length),X=[];for(let Q=0;Q<G;Q++)J[Q]!==z[Q]&&X.push(Q);return{lines:X,numLinesBefore:J.length,numLinesAfter:z.length,numLines:G}}var wH=globalThis.process.platform.startsWith("win"),o1=Symbol("clack:cancel");function t1($){return $===o1}function n1($,Z){let J=$;J.isTTY&&J.setRawMode(Z)}var $4=($)=>("rows"in $)&&typeof $.rows=="number"?$.rows:20;function Z4($,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 o0{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return W5(this.opts.accessible)}constructor($,Z=!0){let{input:J=z5,output:z=J5,render:G,signal:X,...Q}=$;this.opts=Q,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=G.bind(this),this._track=Z,this._abortSignal=X,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 G of J)G.cb(...Z),G.once&&z.push(()=>J.splice(J.indexOf(G),1));for(let G of z)G()}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(o1);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=G5.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),n1(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(r.cursor.show),this.output.off("resize",this.render),n1(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(r.cursor.show),this.output.off("resize",this.render),n1(this.input,!1),$(o1)})})}_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&&$0.aliases.has(Z.name)&&this.emit("cursor",$0.aliases.get(Z.name)),$0.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=Z4(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")}e9([$,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(`
|
|
33
|
+
`),n1(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let $=a1(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
34
|
+
`).length-1;this.output.write(r.cursor.move(-999,$*-1))}render(){let $=a1(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if($!==this._prevFrame){if(this.state==="initial")this.output.write(r.cursor.hide);else{let Z=H5(this._prevFrame,$),J=$4(this.output);if(this.restoreCursor(),Z){let z=Math.max(0,Z.numLinesAfter-J),G=Math.max(0,Z.numLinesBefore-J),X=Z.lines.find((Q)=>Q>=z);if(X===void 0){this._prevFrame=$;return}if(Z.lines.length===1){this.output.write(r.cursor.move(0,X-G)),this.output.write(r.erase.lines(1));let Q=$.split(`
|
|
35
|
+
`);this.output.write(Q[X]),this._prevFrame=$,this.output.write(r.cursor.move(0,Q.length-X-1));return}else if(Z.lines.length>1){if(z<G)X=z;else{let W=X-G;W>0&&this.output.write(r.cursor.move(0,W))}this.output.write(r.erase.down());let Q=$.split(`
|
|
36
|
+
`).slice(X);this.output.write(Q.join(`
|
|
37
|
+
`)),this._prevFrame=$;return}}this.output.write(r.erase.down())}this.output.write($),this.state==="initial"&&(this.state="active"),this._prevFrame=$}}}function U5($,Z){if($===void 0||Z.length===0)return 0;let J=Z.findIndex((z)=>z.value===$);return J!==-1?J:0}function Y5($,Z){return(Z.label??String(Z.value)).toLowerCase().includes($.toLowerCase())}function q5($,Z){if(Z)return $?Z:Z[0]}var K5=class extends o0{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#z="";#Z;#G;#H;#X;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return r1(["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}${r1("inverse",J)}${z}`}get options(){return typeof this.#G=="function"?this.#G():this.#G}constructor(Z){super(Z),this.#G=Z.options,this.#H=Z.placeholder,this.#X=Z.completeOnTab===!0;let J=this.options;this.filteredOptions=[...J],this.multiple=Z.multiple===!0,this.#Z=typeof Z.options=="function"?Z.filter:Z.filter??Y5;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 G of z){let X=J.findIndex((Q)=>Q.value===G);X!==-1&&(this.toggleSelected(G),this.#$=X)}this.focusedValue=this.options[this.#$]?.value,this.on("key",(G,X)=>this.#J(G,X)),this.on("userInput",(G)=>this.#U(G))}_isActionKey(Z,J){return Z==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&Z!==void 0&&Z!==""}#J(Z,J){let z=J.name==="up",G=J.name==="down",X=J.name==="return",Q=this.userInput===""||this.userInput==="\t",W=this.#H,H=this.options,Y=W!==void 0&&W!==""&&H.some((q)=>!q.disabled&&(this.#Z?this.#Z(W,q):!0));if(J.name==="tab"&&Q&&Y){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(W,!0),this.isNavigating=!1;return}if(J.name==="tab"&&this.#X&&!this.multiple&&this.focusedValue!==void 0){let q=String(this.focusedValue);this._clearUserInput(),this._setUserInput(q,!0),this.isNavigating=!1;return}z||G?(this.#$=_2(this.#$,z?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):X?this.value=q5(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])}#U(Z){if(Z!==this.#z){this.#z=Z;let J=this.options;Z&&this.#Z?this.filteredOptions=J.filter((X)=>this.#Z?.(Z,X)):this.filteredOptions=[...J];let z=U5(this.focusedValue,this.filteredOptions);this.#$=_2(z,0,this.filteredOptions);let G=this.filteredOptions[this.#$];G&&!G.disabled?this.focusedValue=G.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};var V5={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function r9($){return[...$].map((Z)=>V5[Z])}function j5($){let Z=new Intl.DateTimeFormat($,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),J=[],z="/";for(let G of Z)G.type==="literal"?z=G.value.trim()||G.value:(G.type==="year"||G.type==="month"||G.type==="day")&&J.push({type:G.type,len:G.type==="year"?4:2});return{segments:J,separator:z}}function I2($){return Number.parseInt(($||"0").replace(/_/g,"0"),10)||0}function i1($){return{year:I2($.year),month:I2($.month),day:I2($.day)}}function A2($,Z){return new Date($||2001,Z||1,0).getDate()}function J4($){let{year:Z,month:J,day:z}=i1($);if(!Z||Z<0||Z>9999||!J||J<1||J>12||!z||z<1)return;let G=new Date(Date.UTC(Z,J-1,z));if(!(G.getUTCFullYear()!==Z||G.getUTCMonth()!==J-1||G.getUTCDate()!==z))return{year:Z,month:J,day:z}}function o9($){let Z=J4($);return Z?new Date(Date.UTC(Z.year,Z.month-1,Z.day)):void 0}function M5($,Z,J,z){let G=J?{year:J.getUTCFullYear(),month:J.getUTCMonth()+1,day:J.getUTCDate()}:null,X=z?{year:z.getUTCFullYear(),month:z.getUTCMonth()+1,day:z.getUTCDate()}:null;return $==="year"?{min:G?.year??1,max:X?.year??9999}:$==="month"?{min:G&&Z.year===G.year?G.month:1,max:X&&Z.year===X.year?X.month:12}:{min:G&&Z.year===G.year&&Z.month===G.month?G.day:1,max:X&&Z.year===X.year&&Z.month===X.month?X.day:A2(Z.year,Z.month)}}class z4 extends o0{#$;#z;#Z;#G;#H;#X={segmentIndex:0,positionInSegment:0};#J=!0;#U=null;inlineError="";get segmentCursor(){return{...this.#X}}get segmentValues(){return{...this.#Z}}get segments(){return this.#$}get separator(){return this.#z}get formattedValue(){return this.#q(this.#Z)}#q($){return this.#$.map((Z)=>$[Z.type]).join(this.#z)}#W(){this._setUserInput(this.#q(this.#Z)),this._setValue(o9(this.#Z)??void 0)}constructor($){let Z=$.format?{segments:r9($.format),separator:$.separator??"/"}:j5($.locale),J=$.separator??Z.separator,z=$.format?r9($.format):Z.segments,G=$.initialValue??$.defaultValue,X=G?{year:String(G.getUTCFullYear()).padStart(4,"0"),month:String(G.getUTCMonth()+1).padStart(2,"0"),day:String(G.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},Q=z.map((W)=>X[W.type]).join(J);super({...$,initialUserInput:Q},!1),this.#$=z,this.#z=J,this.#Z=X,this.#G=$.minDate,this.#H=$.maxDate,this.#W(),this.on("cursor",(W)=>this.#V(W)),this.on("key",(W,H)=>this.#F(W,H)),this.on("finalize",()=>this.#K($))}#Q(){let $=Math.max(0,Math.min(this.#X.segmentIndex,this.#$.length-1)),Z=this.#$[$];if(Z)return this.#X.positionInSegment=Math.max(0,Math.min(this.#X.positionInSegment,Z.len-1)),{segment:Z,index:$}}#Y($){this.inlineError="",this.#U=null;let Z=this.#Q();Z&&(this.#X.segmentIndex=Math.max(0,Math.min(this.#$.length-1,Z.index+$)),this.#X.positionInSegment=0,this.#J=!0)}#j($){let Z=this.#Q();if(!Z)return;let{segment:J}=Z,z=this.#Z[J.type],G=!z||z.replace(/_/g,"")==="",X=Number.parseInt((z||"0").replace(/_/g,"0"),10)||0,Q=M5(J.type,i1(this.#Z),this.#G,this.#H),W;G?W=$===1?Q.min:Q.max:W=Math.max(Math.min(Q.max,X+$),Q.min),this.#Z={...this.#Z,[J.type]:W.toString().padStart(J.len,"0")},this.#J=!0,this.#U=null,this.#W()}#V($){if($)switch($){case"right":return this.#Y(1);case"left":return this.#Y(-1);case"up":return this.#j(1);case"down":return this.#j(-1)}}#F($,Z){if(Z?.name==="backspace"||Z?.sequence===""||Z?.sequence==="\b"||$===""||$==="\b"){this.inlineError="";let J=this.#Q();if(!J)return;if(!this.#Z[J.segment.type].replace(/_/g,"")){this.#Y(-1);return}this.#Z[J.segment.type]="_".repeat(J.segment.len),this.#J=!0,this.#X.positionInSegment=0,this.#W();return}if(Z?.name==="tab"){this.inlineError="";let J=this.#Q();if(!J)return;let z=Z.shift?-1:1,G=J.index+z;G>=0&&G<this.#$.length&&(this.#X.segmentIndex=G,this.#X.positionInSegment=0,this.#J=!0);return}if($&&/^[0-9]$/.test($)){let J=this.#Q();if(!J)return;let{segment:z}=J,G=!this.#Z[z.type].replace(/_/g,"");if(this.#J&&this.#U!==null&&!G){let F=this.#U+$,B={...this.#Z,[z.type]:F},P=this.#M(B,z);if(P){this.inlineError=P,this.#U=null,this.#J=!1;return}this.inlineError="",this.#Z[z.type]=F,this.#U=null,this.#J=!1,this.#W(),J.index<this.#$.length-1&&(this.#X.segmentIndex=J.index+1,this.#X.positionInSegment=0,this.#J=!0);return}this.#J&&!G&&(this.#Z[z.type]="_".repeat(z.len),this.#X.positionInSegment=0),this.#J=!1,this.#U=null;let X=this.#Z[z.type],Q=X.indexOf("_"),W=Q>=0?Q:Math.min(this.#X.positionInSegment,z.len-1);if(W<0||W>=z.len)return;let H=X.slice(0,W)+$+X.slice(W+1),Y=!1;if(W===0&&X==="__"&&(z.type==="month"||z.type==="day")){let F=Number.parseInt($,10);H=`0${$}`,Y=F<=(z.type==="month"?1:2)}if(z.type==="year"&&(H=(X.replace(/_/g,"")+$).padStart(z.len,"_")),!H.includes("_")){let F={...this.#Z,[z.type]:H},B=this.#M(F,z);if(B){this.inlineError=B;return}}this.inlineError="",this.#Z[z.type]=H;let q=H.includes("_")?void 0:J4(this.#Z);if(q){let{year:F,month:B}=q,P=A2(F,B);this.#Z={year:String(Math.max(0,Math.min(9999,F))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,B))).padStart(2,"0"),day:String(Math.max(1,Math.min(P,q.day))).padStart(2,"0")}}this.#W();let K=H.indexOf("_");Y?(this.#J=!0,this.#U=$):K>=0?this.#X.positionInSegment=K:Q>=0&&J.index<this.#$.length-1?(this.#X.segmentIndex=J.index+1,this.#X.positionInSegment=0,this.#J=!0):this.#X.positionInSegment=Math.min(W+1,z.len-1)}}#M($,Z){let{month:J,day:z}=i1($);if(Z.type==="month"&&(J<0||J>12))return $0.date.messages.invalidMonth;if(Z.type==="day"&&(z<0||z>31))return $0.date.messages.invalidDay(31,"any month")}#K($){let{year:Z,month:J,day:z}=i1(this.#Z);if(Z&&J&&z){let G=A2(Z,J);this.#Z={...this.#Z,day:String(Math.min(z,G)).padStart(2,"0")}}this.value=o9(this.#Z)??$.defaultValue??void 0}}var F5=class extends o0{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((G)=>z.includes(G.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((G)=>z.findIndex((X)=>X.value===G)===-1):this.value=[...this.value,...z.map((G)=>G.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,G])=>[{value:z,group:!0,label:z},...G.map((X)=>({...X,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 G=this.options[this.cursor]?.group===!0;!this.#$&&G&&(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 G=this.options[this.cursor]?.group===!0;!this.#$&&G&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},B5=new Set(["up","down","left","right"]);class G4 extends o0{#$=!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
38
|
`?`${Z}█
|
|
39
|
-
${z}`:`${Z}${
|
|
39
|
+
${z}`:`${Z}${r1("inverse",J)}${z}`}get cursor(){return this._cursor}#Z($){if(this.userInput.length===0){this._setUserInput($);return}this._setUserInput(this.userInput.slice(0,this.cursor)+$+this.userInput.slice(this.cursor))}#G($){let Z=this.value??"";switch($){case"up":this._cursor=s1(this._cursor,0,-1,Z);return;case"down":this._cursor=s1(this._cursor,0,1,Z);return;case"left":this._cursor=s1(this._cursor,-1,0,Z);return;case"right":this._cursor=s1(this._cursor,1,0,Z);return}}_shouldSubmit($,Z){if(this.#z)return this.focused==="submit"?!0:(this.#Z(`
|
|
40
40
|
`),this._cursor++,!1);let J=this.#$;return this.#$=!0,J&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
|
|
41
41
|
`&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#Z(`
|
|
42
|
-
`),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&&
|
|
43
|
-
`:""}${
|
|
44
|
-
`,z=$.placeholder&&$.placeholder.length>0?E("inverse",$.placeholder[0])+E("dim",$.placeholder.slice(1)):E(["inverse","hidden"],"_"),
|
|
42
|
+
`),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&&B5.has(z.name)){this.#$=!1,this.#G(z.name);return}if(J==="\t"&&this.#z){this.focused=this.focused==="editor"?"submit":"editor";return}if(z?.name!=="return"){if(this.#$=!1,z?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(z?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}J&&(this.#z&&this.focused==="submit"&&(this.focused="editor"),this.#Z(J??""),this._cursor++)}}),this.on("userInput",(J)=>{this._setValue(J)}),this.on("finalize",()=>{this.value||(this.value=$.defaultValue),this.value===void 0&&(this.value="")})}}class R2 extends o0{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}${r1("inverse",J)}${z}`}get cursor(){return this._cursor}constructor($){super({...$,initialUserInput:$.initialUserInput??$.initialValue}),this.on("userInput",(Z)=>{this._setValue(Z)}),this.on("finalize",()=>{this.value||(this.value=$.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as E,stripVTControlCharacters as eH}from"node:util";import Z0 from"node:process";var Q4=t9(O2(),1);function D5(){if(Z0.platform!=="win32")return Z0.env.TERM!=="linux";return Boolean(Z0.env.CI)||Boolean(Z0.env.WT_SESSION)||Boolean(Z0.env.TERMINUS_SUBLIME)||Z0.env.ConEmuTask==="{cmd::Cmder}"||Z0.env.TERM_PROGRAM==="Terminus-Sublime"||Z0.env.TERM_PROGRAM==="vscode"||Z0.env.TERM==="xterm-256color"||Z0.env.TERM==="alacritty"||Z0.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var L5=D5();var f=($,Z)=>L5?$:Z,X4=f("◆","*"),N5=f("■","x"),C5=f("▲","x"),P5=f("◇","o"),zU=f("┌","T"),g0=f("│","|"),S2=f("└","—"),GU=f("┐","T"),XU=f("┘","—"),QU=f("●",">"),WU=f("○"," "),HU=f("◻","[•]"),UU=f("◼","[+]"),YU=f("◻","[ ]"),qU=f("▪","•"),KU=f("─","-"),VU=f("╮","+"),jU=f("├","+"),MU=f("╯","+"),FU=f("╰","+"),BU=f("╭","+"),DU=f("●","•"),LU=f("◆","*"),NU=f("▲","!"),CU=f("■","x"),O5=($)=>{switch($){case"initial":case"active":return E("cyan",X4);case"cancel":return E("red",N5);case"error":return E("yellow",C5);case"submit":return E("green",P5);case"validating":return E("dim",X4)}};var PU=[`${E("dim","↑/↓")} to navigate`,`${E("dim","Space:")} select`,`${E("dim","Enter:")} confirm`];var OU={light:f("─","-"),heavy:f("━","="),block:f("█","#")};var IU=[`${E("dim","↑/↓")} to navigate`,`${E("dim","Enter:")} confirm`];var _U=`${E("gray",g0)} `;var W4=($)=>new R2({validate:$.validate,placeholder:$.placeholder,defaultValue:$.defaultValue,initialValue:$.initialValue,output:$.output,signal:$.signal,input:$.input,render(){let Z=$?.withGuide??$0.withGuide,J=`${`${Z?`${E("gray",g0)}
|
|
43
|
+
`:""}${O5(this.state)} `}${$.message}
|
|
44
|
+
`,z=$.placeholder&&$.placeholder.length>0?E("inverse",$.placeholder[0])+E("dim",$.placeholder.slice(1)):E(["inverse","hidden"],"_"),G=this.userInput?this.userInputWithCursor:z,X=this.value??"";switch(this.state){case"validating":{let Q=Z?`${E("cyan",g0)} `:"",W=Z?E("cyan",S2):"",H=E("dim",G),Y=E("dim","Validating...");return`${J}${Q}${H}
|
|
45
45
|
${W} ${Y}
|
|
46
|
-
`}case"error":{let
|
|
47
|
-
${W}${
|
|
48
|
-
${H}${
|
|
49
|
-
`}case"submit":{let X
|
|
50
|
-
${W}`:""}`}default:{let
|
|
46
|
+
`}case"error":{let Q=this.error?` ${E("yellow",this.error)}`:"",W=Z?`${E("yellow",g0)} `:"",H=Z?E("yellow",S2):"";return`${J.trim()}
|
|
47
|
+
${W}${G}
|
|
48
|
+
${H}${Q}
|
|
49
|
+
`}case"submit":{let Q=X?`${Z?" ":""}${E("dim",X)}`:"",W=Z?E("gray",g0):"";return`${J}${W}${Q}`}case"cancel":{let Q=X?` ${E(["strikethrough","dim"],X)}`:"",W=Z?E("gray",g0):"";return`${J}${W}${Q}${X.trim()?`
|
|
50
|
+
${W}`:""}`}default:{let Q=Z?`${E("cyan",g0)} `:"",W=Z?E("cyan",S2):"";return`${J}${Q}${G}
|
|
51
51
|
${W}
|
|
52
|
-
`}}}}).prompt();import{authorize as
|
|
53
|
-
`),
|
|
52
|
+
`}}}}).prompt();import{authorize as I5,exchange as _5,resolveClaudeCodeIdentity as A5}from"@cortexkit/anthropic-auth-core";async function H4($,Z={authorize:I5,exchange:_5,resolveClaudeCodeIdentity:A5,text:W4,isCancel:t1,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 G=await Z.exchange(z,J.verifier,J.redirectUri,J.state);if(G.type!=="success")throw Error("Claude sign-in failed");let X=await Z.resolveClaudeCodeIdentity(G.access,void 0,void 0);if(!X.accountUuid)throw Error("Claude sign-in did not establish an account UUID");return{accountIdentity:X.accountUuid,credential:{type:"oauth",access:G.access,refresh:G.refresh,expires:G.expires}}}var U4='Warning: OpenCode holds a separate Anthropic OAuth login. Remove the separate OpenCode Anthropic login, then choose "Claude via credential vault". Setup has left that login unchanged.';function V0($,Z){let J=$.get(Z);if(!J)throw Error("Missing setup plan");return J}async function V4($=[],Z={}){let J={...Z.env??process.env},z=Z.terminal??{input:process.stdin,output:process.stdout,signals:process},G=(U)=>z.output.write(`${U}
|
|
53
|
+
`),X=$.filter((U)=>U!=="--remove-pi-auth").map((U)=>U==="-y"?"--yes":U),Q=X.includes("--login");if(Q&&X.includes("--claustrum"))return G("Local sign-in and vault setup are two separate choices. Use --login or --claustrum, not both."),1;if(Q&&X.includes("--opencode=2"))return G(e1),1;let W=Z.runner??g9,H=Z.fence??R5(W,{platform:Z.platform}),Y=Z.migrateLocal??J9,q=new Map,K=new Map,F=new Map,B=new Map,P=!1,C="setup-process-check",D=(U)=>({env:J,fence:H,paths:F.get(U),removePiAnthropicAuth:B.get(U)??!1}),R=(U)=>({...D(U),runner:W});async function S(U){if(!U.hosts.includes("pi"))return;let V=V0(F,"pi");if((await W1("pi",V.hostAuthPath)).kind==="absent")return;{let k=await b5({env:J,authPath:V.hostAuthPath}).inspect();if(k.slot==="placeholder"&&k.stash==="missing")throw new S5("missing-stash");if(U.mode==="claustrum"){if(k.slot==="placeholder")return}}if($.includes("--remove-pi-auth")){B.set("pi",!0);return}let b=U.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(X.includes("--yes")||!z.input.isTTY)throw new a(b);if(!await d1(z,U.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 a("Native account-pool setup cannot finish while the stored Pi OAuth token takes precedence.");B.set("pi",!0)}async function y(U,V){let j=V0(K,U);if(await T5(U,J)!==(V?"claustrum":j.priorMode)||await H1(U,R(U))!==j.fingerprint)throw new a("Setup inputs changed. Rerun setup with all hosts stopped.")}let L={packages:{opencode:Y4,pi:q4},version:await K4(),displayName:"CortexKit Anthropic Auth",slashCommand:"/claude",vault:{connectionFile:a3(J.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE&&!J.OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE?"pi":"opencode",J),hosts:{opencode:{name:g1.opencode,paths:l3("opencode",J)},pi:{name:g1.pi,paths:l3("pi",J)}}},async beforeSignIn(U,V){if(C=V.mode==="claustrum"?"setup-activation":"cli-setup",!P){f5(J);for(let j of V.hosts)F.set(j,await Y0(j,J));if(await i$([...F.values()]),V.mode==="claustrum"){let j=V.hosts.map((g)=>a3(g,J)),b=j[0];if(new Set(j).size!==1||!b)throw new a("Selected hosts use different vault connection files.");L.vault.connectionFile=b}if(V.mode==="local"&&Q&&V.hosts.includes("opencode")&&V.opencodeGeneration==="2")throw new a(e1);if(V.mode==="local"){await o3(V.hosts,J);for(let j of V.hosts)await E0(j,D(j))()}await S(V);for(let j of V.hosts)if(V.mode==="claustrum"){if(K.set(j,await(Z.vaultPreflight??X9)(j,{...R(j),inspectOpenCodeAuth:V.opencodeGeneration!=="2"})),V0(K,j).separateOpenCodeLogin)G(U4)}else q.set(j,await e3(j,D(j),j==="opencode"&&V.opencodeGeneration==="2"));P=!0}else if(V.mode==="claustrum")await y(U,!1);else await s0(V0(q,U),D(U))},async signInLocal(U){let V=V0(q,U);if(!Q){if(V.generation2)G(e1);return}if(await s0(V,D(U)),await Y(U,{...D(U),login:Z.localLogin??H4,preflight:V.preflight,skipMigration:V.action==="skip",beforeCommit:()=>s0(V,D(U))}),V.fingerprint=await y1(V,J),V.notice)G(r3)},async beforeRegister(U,V){if(V==="local")await s0(V0(q,U),D(U));else await y(U,!0),await(Z.vaultActivate??Q9)(U,R(U),V0(K,U)),V0(K,U).fingerprint=await H1(U,R(U))},async migrate(U,V){if(V.mode==="claustrum"){if(await y(U,!0),U===V.hosts.at(-1)&&K.get("opencode")?.separateOpenCodeLogin)G(U4);return}let j=V0(q,U);if(await s0(j,D(U)),Q)return;if(j.action==="migration")await Y(U,{...D(U),preflight:j.preflight});else if(j.action==="empty-init")await k5({paths:j.paths.paths,routingDestinationPath:j.paths.routingDestinationPath,env:J,processFence:E0(U,D(U))});else if(j.action==="skip"){if(await $2(j,D(U)),j.notice)G(r3)}j.fingerprint=await y1(j,J)}};try{return await g5(L,X,{...Z,env:J,terminal:z,runner:W,fence:H}),0}catch(U){let j=o$(U)??q2(U)??await Y1(C,U,J);if(j)G(j);for(let{host:b,outcome:g}of D9(U)??[]){if(g!=="enrolled")continue;let k=b==="opencode"?"OpenCode":"Pi";G(`${k} stays connected to the vault. In ${k}, run /claude → Accounts → Disconnect from the vault to undo it. Or run setup again to finish connecting.`)}return 1}finally{for(let U of q.values())if(U.preflight)E5(U.preflight)}}async function t0($){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Native account changes require offline setup without OPENCODE_AUTH_CONTENT");let Z=await a5(),J=m5({paths:Z,host:"opencode"});try{return await J.read(),await $(J)}finally{J.close()}}async function $3(){if(await l5("opencode",process.env)!=="local")throw Error("Disconnect from the vault first.")}function j4(){console.log(`Usage:
|
|
54
54
|
opencode-anthropic-auth setup [--yes] [--dry-run]
|
|
55
55
|
opencode-anthropic-auth login [label]
|
|
56
56
|
opencode-anthropic-auth api add [label]
|
|
@@ -60,9 +60,9 @@ ${W}
|
|
|
60
60
|
Setup --yes selects every found host, including Pi. Run setup without --yes to choose hosts.
|
|
61
61
|
Native credentials are managed by the offline setup migration.
|
|
62
62
|
Legacy import source:
|
|
63
|
-
${
|
|
63
|
+
${p5()}`)}function b2($,Z){let J=$?.trim();if(!J)throw Error(`${Z} is required`);return J}async function z3($){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(),G;try{G=JSON.parse(z)}catch{throw Error(`Cloudflare API returned ${J.status}: ${z}`)}if(!J.ok||G.success===!1){let X=G.errors?.map((Q)=>Q.message).filter(Boolean).join("; ");throw Error(X||`Cloudflare API returned ${J.status}`)}return G.result}async function n5($,Z,J,z){return z3({token:$,method:"POST",path:`/accounts/${Z}/storage/kv/namespaces`,body:JSON.stringify({title:J}),fetchImpl:z})}async function i5($){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([s5],{type:"application/javascript+module"}),"worker.js"),z3({token:$.token,method:"PUT",path:`/accounts/${$.accountId}/workers/scripts/${$.scriptName}`,body:J,fetchImpl:$.fetchImpl})}async function r5($,Z,J,z){await z3({token:$,method:"POST",path:`/accounts/${Z}/workers/scripts/${J}/subdomain`,body:JSON.stringify({enabled:!0,previews_enabled:!1}),fetchImpl:z})}async function o5($,Z,J){return z3({token:$,method:"GET",path:`/accounts/${Z}/workers/subdomain`,fetchImpl:J}).catch(()=>null)}async function t5($={}){await t0((B)=>B.read());let Z=$.fetchImpl??fetch,J=$.prompt??J3,z=$.warn??((B)=>console.warn(B)),G=b2(process.env.CLOUDFLARE_API_TOKEN?.trim()||await J("Cloudflare API token: "),"Cloudflare API token");$.secrets?.push(G);let X=b2(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=c5();$.secrets?.push(H),console.log("Creating Cloudflare KV namespace...");let Y=await n5(G,X,W,Z);console.log("Uploading relay Worker..."),await i5({token:G,accountId:X,scriptName:Q,kvNamespaceId:Y.id,relayToken:H,fetchImpl:Z}),await r5(G,X,Q,Z).catch(async(B)=>{z(await Y1("cli-relay-workers-dev",B,process.env,[G,H]))});let q=await o5(G,X,Z),F=(q?.subdomain?`https://${Q}.${q.subdomain}.workers.dev`:"")||b2(await J3("Relay Worker URL: "),"Relay Worker URL");await t0((B)=>B.updateRelay({enabled:!0,url:F,token:H,fallbackToDirect:!0,transport:"http"})),console.log(`Relay enabled at ${F}`),console.log("Relay settings saved to the native account store.")}var Z3=null;async function J3($){return Z3??=h5({input:x5,output:y5}),(await Z3.question($)).trim()}function e5(){Z3?.close(),Z3=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??J3,z=Z.authorize??v5,G=Z.exchange??w5;await $3(),await t0(async(X)=>{let Q=await X.read(),W=$?.trim()||await J("Fallback account label (optional): "),H=await z("max");console.log(`
|
|
64
64
|
Open this URL in your browser and complete Claude sign-in:
|
|
65
65
|
`),console.log(`${H.url}
|
|
66
|
-
`);let Y=await J("Paste the full callback URL or authorization code here: ");Z.secrets?.push(Y);let q=await
|
|
67
|
-
Saved native fallback account${W?` "${W}"`:""}.`)})}async function
|
|
68
|
-
Saved API fallback route${z?` "${z}"`:""} (${
|
|
66
|
+
`);let Y=await J("Paste the full callback URL or authorization code here: ");Z.secrets?.push(Y);let q=await G(Y,H.verifier,H.redirectUri,H.state);if(q.type==="failed")throw Error("Authentication failed");if(Z.secrets?.push(q.access,q.refresh),process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Local login cannot be verified while OPENCODE_AUTH_CONTENT is set");await $3();let K=W&&W!=="main"?W:crypto.randomUUID(),F=Q.accounts.some((B)=>B.id===K&&B.source==="local");await X.loginOAuth({routeId:K,replace:F,label:W||void 0,credential:{access:q.access,refresh:q.refresh,expires:q.expires}}),console.log(`
|
|
67
|
+
Saved native fallback account${W?` "${W}"`:""}.`)})}async function ZZ($,Z={}){await $3(),await t0((H)=>H.read());let J=Z.prompt??J3,z=$?.trim()||await J("API fallback label (optional): "),G=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(!d5(G))throw Error("API fallback base URL must be an http(s) URL without embedded credentials");let X=process.env.OPENCODE_ANTHROPIC_AUTH_API_KEY?.trim()||await J("API key: ");if(!X.trim())throw Error("API key is required");Z.secrets?.push(X.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 t0(async(H)=>{await $3();let Y=await H.read(),q=z&&z!=="main"?z:crypto.randomUUID(),K=Y.accounts.find((F)=>F.id===q);if(K?.source==="vault")throw Error("Vault routes cannot be replaced with a local API key");await H.addApi({routeId:q,replace:Boolean(K),label:z||void 0,apiKey:X.trim(),baseURL:G,authHeader:W})}),console.log(`
|
|
68
|
+
Saved API fallback route${z?` "${z}"`:""} (${G}).`)}async function JZ(){await t0(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 G=z.label||z.id,X=z.enabled?"enabled":"disabled";if(z.type==="api"){console.log(`${J+1}. ${G} (${X}) — 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}. ${G} (${X}) — ${H}${z.state?` — ${u5(z)}`:""}`)}})}async function zZ($){let[Z,J,z]=process.argv.slice(2);if(!Z||Z==="help"||Z==="--help"||Z==="-h"){j4();return}if(Z==="setup"){$.stage="cli-setup";let G=await V4(process.argv.slice(3));if(G!==0)process.exitCode=G;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 t5({secrets:$.secrets});return}j4(),process.exitCode=1}if(Y3.main==Y3.module){let $={stage:"cli-command",secrets:[]};try{await zZ($)}catch(Z){console.error(await Y1($.stage,Z,process.env,$.secrets)),process.exitCode=1}finally{e5()}}export{V4 as runSetupCommand,t5 as relaySetup,$Z as login,ZZ as addApiRoute};
|