@cortexkit/opencode-anthropic-auth 2.2.3 → 2.2.4
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 +28 -28
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,46 +1,46 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{x as e1}from"./index-0kxy8k2c.js";import{A as F4,B as i$,C as r$,D as o$,E as t$,F as B4,z as M4}from"./index-b1dvkp15.js";import{ha as z4,ia as U5,ja as U3}from"./index-62x1p34p.js";var I2=U5((sH,$4)=>{var O2={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"},q5={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},K5={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?O2.up():"");if($)Z+=O2.left;return Z}};$4.exports={cursor:O2,scroll:q5,erase:K5,beep:"\x07"}});import{stdin as a5,stdout as s5}from"node:process";import{createInterface as n5}from"node:readline/promises";import{authorize as i5,createNativeAccountRuntime as r5,exchange as o5,formatNativeAccountState as t5,generateRelayToken as e5,getAccountStoragePath as $Z,isValidApiBaseURL as ZZ,readNativeEnrollmentMode as JZ,resolveNativePoolPaths as zZ,WORKER_SCRIPT as XZ}from"@cortexkit/anthropic-auth-core";import{randomUUID as E8}from"node:crypto";import{constants as v1}from"node:fs";import{lstat as f8,mkdir as g8,open as x8}from"node:fs/promises";import{homedir as y8}from"node:os";import{isAbsolute as q9,join as W2}from"node:path";import{types as Y2}from"node:util";import{createProviderErrorRedactor as M9,createWindowsOwnerOnly as v8,ensureWindowsOwnerOnlyDirectory as h8,formatLogLine as m8,isOwnerOnly as w8,isSecretKey as u8,NativeMigrationError as c8,NativePiAuthSlotError as p8,PRIVATE_FILES_UNAVAILABLE_MESSAGE as F9,setupEnrollment as d8}from"@cortexkit/anthropic-auth-core";import{readFile as C8}from"node:fs/promises";import{assertHostsStopped as P8,createNativeAccountRuntime as O8,discoverNativeVaultInventory as I8,inspectNativeHostAuthEntry as J2,NativePiAuthSlotError as _8,nativePiAuthSlotPaths as A8,openNativePiAuthSlot as X2,readNativeEnrollmentMode as R8,requireNoSupervisedAuthContentSnapshot as S8}from"@cortexkit/anthropic-auth-core";import{dirname as r7}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as o7,CLAUSTRUM_PI_ENROLLMENT_NAME as t7,getHostClaustrumEnrollmentPaths as e7,resolveClaustrumConnectionPath as $8}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as PX}from"@cortexkit/claustrum-client";import{ClaustrumClient as zX}from"@cortexkit/claustrum-client";import{resolve as E2}from"node:path";import{storeIdentity as OZ}from"@cortexkit/claustrum-client";import{SubcClient as _Z}from"@cortexkit/subc-client";import{ClaustrumCredentialError as N4}from"@cortexkit/claustrum-client";import{SocketClosedError as C4,SocketTimeoutError as P4,SubcCallError as O4}from"@cortexkit/subc-client";class I extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var X3=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 V0($){if($ instanceof P0||$ instanceof C4||$ instanceof P4)return"unreachable";let Z=$ instanceof N4||$ instanceof O4?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(X3,Z))return"answered";return X3[Z]}var G3=300000,D1=300000,Q3=1000;class $1{#$;#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 L1{#$;#z;#Z;#X=!1;constructor($,Z){this.#$=$,this.#z=Z}get running(){return this.#Z}request(){if(this.#Z)return this.#X=!0,this.#Z;return this.#Z=(async()=>{do{this.#X=!1;try{await this.#$()}catch($){this.#z($)}}while(this.#X)})().finally(()=>{this.#Z=void 0}),this.#Z}}class N1{#$;#z=new $1;#Z;#X="polling";#H;#G;#J=!1;#Y;#q=!1;#W=0;constructor($){this.#$=$,this.#Z=new L1(async()=>{let Z=this.#q;if(this.#q=!1,Z||this.#Y!==this.#$.view())await this.#$.discover(this.#Y??"")},(Z)=>{if(!this.#J)this.#$.onError?.(Z)})}get mode(){return this.#X}start(){if(this.#J||this.#H||this.#G)return;if(typeof this.#$.client.watchScoped!=="function"){this.#Q("fallback","client-without-watch");return}this.#V(!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()}#Q($,Z){if(this.#X===$)return;this.#X=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#U($,Z){this.#G=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#G=void 0,!this.#J)Z()},$),this.#G.unref?.()}async#V($){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,X;try{X=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.#Y=Q.view,this.#Z.request()},{enrollmentToken:Z})}catch(Q){this.#$.onError?.(Q),this.#F("watch-failed");return}z={handle:X,notices:0},this.#H=z,this.#Q("polling",$?"resubscribing":"opening");let G=z;X.closed.then((Q)=>this.#j(G,Q),(Q)=>this.#j(G,{kind:"transport_lost",error:Q}))}#j($,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.#U(z,()=>void this.#V(!0));return}this.#F(Z.kind)}#F($){this.#Q("fallback",$),this.#U(300000,()=>void this.#V(!1))}}var P1=60000,f2=4*P1,I4=2*P1,W3=new Map,C1=new Map;function Z1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function _4($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!Z1(Z)||typeof Z.kind!=="string"||typeof Z.epoch!=="string"||Z.epoch.length===0||typeof Z.seq!=="number"||!Number.isSafeInteger(Z.seq)||Z.seq<1||Z.provider!==void 0&&typeof Z.provider!=="string")return;return{kind:Z.kind,epoch:Z.epoch,seq:Z.seq,...typeof Z.provider==="string"&&{provider:Z.provider}}}function A4($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class g2{transport;key;#$=[];#z=!1;#Z=new Set;#X=new Map;#H=new L1(async()=>{try{let $=await this.transport.getUsage();if(!Z1($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>Z1(Z)&&typeof Z.provider==="string"),this.#z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#Z=new Set(this.#z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#Z)this.#X.delete(Z)}catch{this.#$=[],this.#z=!1,this.#Z.clear()}},()=>{});#G=new $1;#J="polling";#Y=0;#q=0;#W=new Map;#Q;#U;#V={};#j=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 C1)if($-z>=P1)C1.delete(J);let Z=C1.get(this.key);if(Z!==void 0&&$-Z<P1)return Promise.resolve();return C1.set(this.key,$),this.#H.request()}watchMode(){return this.#J}watch($={}){this.#Y++;let Z=$.provider;if(Z===void 0)this.#q++;else this.#W.set(Z,(this.#W.get(Z)??0)+1);if(this.#Y===1)this.#V=$,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.#Y===0)this.#F()}}#F(){if(this.#U)(this.#V.clearTimeoutImpl??clearTimeout)(this.#U);this.#U=void 0;let $=this.#Q;this.#Q=void 0,$?.handle?.stop(),this.#J="polling"}#M($){this.#U=(this.#V.setTimeoutImpl??setTimeout)(()=>{if(this.#U=void 0,this.#Y>0&&!this.#Q)this.#K()},$),this.#U.unref?.()}#K(){let $=this.transport.watchUsage;if(!$){this.#J="fallback";return}this.#J="polling",this.#G.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.#j=0;let J=_4(Z);if(!J)this.#G.restart();if(!(J?this.#G.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=A4(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.#j,16),D1);this.#j++,this.#J="polling",this.#M(z);return}if(this.#J="fallback",this.#H.request(),Z===void 0||V0(Z)==="unreachable")this.#M(D1)}current($,Z,J){for(let z of this.#$){if(z.provider!==$||typeof z.account!=="string"||z.account.trim()!==Z)continue;if(z.stale!==void 0||z.errorClass!==void 0||!Z1(z.usage))continue;let X=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(X)||J-X>=f2)continue;return{entry:z,context:{fetchedAt:X,...typeof z.source==="string"&&{source:z.source}}}}return}lookup($,Z,J){if(!this.#z)return{miss:"unreachable"};let z=this.#$.find((Q)=>Q.provider===$&&typeof Q.account==="string"&&Q.account.trim()===Z),X=(z??this.#$.find((Q)=>Q.provider===$&&Q.account===void 0&&Q.errorClass!==void 0))?.errorClass;if(X==="upstream_failed")return{miss:"upstream-failed"};if(X==="credential_absent"||X==="credential_unusable"||X==="credential_rejected")return{miss:"credential"};if(X!==void 0)return{miss:"unreachable"};if(z){let Q=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Z1(z.usage)||!Number.isFinite(Q))return{miss:"unreachable"};let W={entry:z,context:{fetchedAt:Q,...typeof z.source==="string"&&{source:z.source}}};return J>=Q+f2||z.stale!==void 0?{miss:"stale",reading:W}:{reading:W}}if(this.#Z.has($))return{miss:"absent"};let G=this.#X.get($)??J;return this.#X.set($,G),{miss:J-G>=I4?"unreachable":"cold"}}}function H3($,Z){let J=JSON.stringify([E2($.connectionFile),E2(Z)]),z=W3.get(J);if(!z)z={source:new g2($,J),refs:0},W3.set(J,z);z.refs++;let X=!1;return{source:z.source,release(){if(X)return;if(X=!0,--z.refs===0)W3.delete(J)}}}import{ClaustrumCredentialError as WX}from"@cortexkit/claustrum-client";import{appendFileSync as m4,chmodSync as w4,existsSync as K3,renameSync as l2,statSync as u4}from"node:fs";import{open as c4}from"node:fs/promises";import{dirname as p4,resolve as d4}from"node:path";import{randomUUID as h2}from"node:crypto";import{lstat as m2,readFile as w2,rename as R4,unlink as x2}from"node:fs/promises";import{tmpdir as S4}from"node:os";import{dirname as M0,join as b4,resolve as i}from"node:path";var _=process.platform==="win32",y2=new Set;function Y3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var v2;var u2="native-addon-unavailable";function c2($){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:$}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:u2})}function k4($,Z){return Z instanceof $.PrivateFilesUnavailableError||Z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function T4($){try{await $.verifyPrivatePath(b4(S4(),`.common-auth-private-files-probe-${h2()}`),"file")}catch(Z){if(k4($,Z))throw c2(Z)}}function y0(){return v2??=import("@cortexkit/private-files").then(async($)=>{if(_)await T4($);return $},($)=>{throw _?c2($):$}),v2}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(z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"?`Private file refused at ${Z}: ${$} (${u2}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`:`Private file refused at ${Z}: ${$} (${z?.reason??z?.code??"io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`,{cause:J});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=Y3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}async function s($,Z,J){try{return await J()}catch(z){if(z instanceof u)throw z;throw new u($,Z,z)}}var E4;async function Q0($,Z){$=i($),Z??=E4,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 m2($);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(),X=await z.verifyOwnerOnly($),G=!1;if(!X.ok){let{reason:Q}=X.refusal;if(Q==="io-error")await z.verifyPrivatePath($,Z);if(J&&[z.EXTRA_ACE,z.NOT_PROTECTED,z.NULL_DACL,z.EMPTY_DACL].includes(Q))await Q0(M0($)),await z.securePrivatePath($,Z),G=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:Q,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await z.verifyPrivatePath($,Z),G&&!y2.has($))y2.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 m2($),await Q0($,J)}catch(G){if(Y3(G)!=="ENOENT")throw G}let X=M0($);if(X===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await J0(X,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(Y3(G)!=="EEXIST")throw G}await Q0($,J)})}async function t($,Z=!1){if(!_)return w2($,"utf8");return(await f4($,Z)).toString("utf8")}async function f4($,Z=!1){if(!_)return w2($);if($=i($),Z)await Q0(M0($)),await p($,"file",!0);return s($,"read",async()=>(await y0()).readOwnerOnly($))}async function v0($,Z){await Q0(M0(i($))),await s($,"create",async()=>{await(await y0()).createPrivateFile(i($),Z)})}async function p2($){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()),X=z(),G=J.deadline??1/0,Q,W=[0,10,20,40,80,100],H,U=0;for(let K of W){let F=Math.min(Q??1/0,G);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()>=G)break;U++;try{return await(J.rename??R4)($,Z),{attempts:U,elapsedMs:z()-X}}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=U,q.elapsedMs=z()-X,q}async function h0($,Z,J={}){$=i($),await J0(M0($));try{await p($,"file",!0)}catch(U){if(U.code!=="ENOENT")throw U}let z=i(J.stagePath??`${$}.${h2()}.tmp`);if(M0(z)!==M0($))throw new u($,"stage-directory",{code:"EXDEV"});let X=!1,G=!1,Q={attempts:0,elapsedMs:0},W="stage-create",H=(U)=>{try{J.onOutcome?.({path:$,stage:U?.stage??"published",published:G,fileDurable:G,durabilityConfirmed:!1,attempts:U?.attempts??Q.attempts,elapsedMs:U?.elapsedMs??Q.elapsedMs,...U&&{code:U.code,win32Code:U.win32Code}})}catch{}};try{if(await v0(z,Z),X=!0,W="before-rename",Q=await q3(z,$,J),X=!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(U){let q=U instanceof u?U:new u($,W,U);if(q.published=G,q.fileDurable=G,G)Object.assign(q,Q);if(X){try{await x2(z)}catch{q.orphanPath=z}X=!1}throw H(q),q}finally{if(X)await x2(z).catch(()=>{})}}var g4=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,x4=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function y4($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function m0($={}){let Z=[x4,...$.extraValuePatterns??[]].map((G)=>new RegExp(G.source,G.flags.includes("g")?G.flags:`${G.flags}g`));function J(G){let Q=G.toLowerCase().replace(/[-_]/g,"");return g4.test(G)||Q.includes("apikey")||Q.endsWith("secret")||Q.endsWith("password")||Q.endsWith("token")&&!Q.endsWith("tokens")||!!$.extraSecretKeys?.(Q)}function z(G){let Q=G,W=[["name",G.name],["message",G.message],["stack",G.stack]];for(let U of["code","status","cause"])if(Q[U]!==void 0)W.push([U,Q[U]]);let H=new Set(W.map(([U])=>U));for(let U of Object.entries(G))if(!H.has(U[0]))W.push(U);return W}function X(G,Q,W,H=0){if(typeof G==="string")return Z.reduce((U,q)=>U.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((K)=>X(K,Q,W,H));let U=y4(G);if(U&&H>=8)return"[Truncated]";let q=U?H+1:H;return Object.fromEntries((U?z(G):Object.entries(G)).map(([K,F])=>[K,Q&&J(K)?"***REDACTED***":X(F,Q,W,q)]))}finally{W.delete(G)}}return{redact:(G)=>X(G,!0,new WeakSet),redactStrings:(G)=>X(G,!1,new WeakSet)}}var d2=m0(),v4=d2.redact,h4=d2.redactStrings;var O1={error:0,warn:1,info:2,debug:3,trace:4},s2=5242880,n2=3;function j3($){try{w4($,384)}catch{}}function l4($){try{if(!(K3($)&&u4($).size>=s2))return;for(let J=n2-1;J>=1;J--)if(K3(`${$}.${J}`)){let z=`${$}.${J+1}`;l2(`${$}.${J}`,z),j3(z)}let Z=`${$}.1`;l2($,Z),j3(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 a2($,Z){await J0(p4(Z));try{await p(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await v0(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await p(Z,"file",!0)}}return $.handle=await s(Z,"log-open",()=>c4(Z,"a")),$.file=Z,$.handle}async function a4($,Z,J){Z=d4(Z);try{if($.file!==Z)await W0($);let z=$.handle??await a2($,Z);if((await s(Z,"log-stat",()=>z.stat())).size>=s2){await W0($);for(let G=n2-1;G>=0;G--){let Q=G===0?Z:`${Z}.${G}`,W=`${Z}.${G+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 a2($,Z)}await s(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await W0($).catch(()=>{}),z}}function s4($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function n4($){let Z,J,z,X=m0(),G,Q=[],W,H=Promise.resolve(),U,q={};function K(Y){let j=H.then(Y);return H=j.catch((V)=>{U=V}),j}function F(Y){if(_&&Y.file!==Z)K(()=>W0(q)).catch(()=>{});Z=Y.file,J=Y.level,X=m0(Y),G=Y.captureSink}function B(Y){if(Y===void 0||Y in O1)z=Y}function P(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function C(){if(z)return z;let Y=typeof J==="function"?J():J;if(Y&&Y in O1)return Y;return"info"}function D(Y=!0){if(W)clearTimeout(W),W=void 0;if(!Q.length){if(_)return K(async()=>{if(Y)await W0(q);if(U)throw U});return}let j;try{j=P()}catch{if(Q=[],_&&Y)return K(()=>W0(q));return}let V=Q.join("");if(Q=[],!j){if(_&&Y)return K(()=>W0(q));return}if(_)return K(async()=>{try{await a4(q,j,V)}finally{if(Y)await W0(q)}});try{if(l4(j),K3(j))j3(j);m4(j,V,{encoding:"utf8",mode:384})}catch{}}function R(){if(!W)W=setTimeout(()=>{W=void 0;let Y=D(!1);if(Y instanceof Promise)Y.catch(()=>{})},500)}function S(Y,j,V,b){if(Z===void 0&&G===void 0)return;try{if(O1[j]>O1[C()])return;let g=X.redactStrings(V),k;try{k=X.redact(b)}catch{k="[unserializable]"}let m=`[${new Date().toISOString()}] ${j.toUpperCase()} [${Y}] ${g}`+(b===void 0?"":s4(k))+`
|
|
3
|
-
`;try{G?.({channel:Y,level:j,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(Y){return{error:(j,V)=>S(Y,"error",j,V),warn:(j,V)=>S(Y,"warn",j,V),info:(j,V)=>S(Y,"info",j,V),debug:(j,V)=>S(Y,"debug",j,V),trace:(j,V)=>S(Y,"trace",j,V)}}function
|
|
2
|
+
import{x as e1}from"./index-0kxy8k2c.js";import{A as F4,B as i$,C as r$,D as o$,E as t$,F as B4,z as M4}from"./index-b1dvkp15.js";import{ha as z4,ia as q5,ja as U3}from"./index-62x1p34p.js";var I2=q5((nH,$4)=>{var O2={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"},K5={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},j5={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?O2.up():"");if($)Z+=O2.left;return Z}};$4.exports={cursor:O2,scroll:K5,erase:j5,beep:"\x07"}});import{stdin as s5,stdout as n5}from"node:process";import{createInterface as i5}from"node:readline/promises";import{authorize as r5,createNativeAccountRuntime as o5,exchange as t5,formatNativeAccountState as e5,generateRelayToken as $Z,getAccountStoragePath as ZZ,isValidApiBaseURL as JZ,readNativeEnrollmentMode as zZ,resolveNativePoolPaths as XZ,WORKER_SCRIPT as GZ}from"@cortexkit/anthropic-auth-core";import{randomUUID as f8}from"node:crypto";import{constants as v1}from"node:fs";import{lstat as g8,mkdir as x8,open as y8}from"node:fs/promises";import{homedir as v8}from"node:os";import{isAbsolute as q9,join as W2}from"node:path";import{types as Y2}from"node:util";import{createProviderErrorRedactor as M9,createWindowsOwnerOnly as h8,ensureWindowsOwnerOnlyDirectory as m8,formatLogLine as w8,isOwnerOnly as u8,isSecretKey as c8,NativeMigrationError as p8,NativePiAuthSlotError as d8,PRIVATE_FILES_UNAVAILABLE_MESSAGE as F9,setupEnrollment as l8}from"@cortexkit/anthropic-auth-core";import{readFile as P8}from"node:fs/promises";import{assertHostsStopped as O8,createNativeAccountRuntime as I8,discoverNativeVaultInventory as _8,inspectNativeHostAuthEntry as J2,NativePiAuthSlotError as A8,nativePiAuthSlotPaths as R8,openNativePiAuthSlot as X2,readNativeEnrollmentMode as S8,requireNoSupervisedAuthContentSnapshot as b8}from"@cortexkit/anthropic-auth-core";import{dirname as r7}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as o7,CLAUSTRUM_PI_ENROLLMENT_NAME as t7,getHostClaustrumEnrollmentPaths as e7,resolveClaustrumConnectionPath as $8}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as OX}from"@cortexkit/claustrum-client";import{ClaustrumClient as XX}from"@cortexkit/claustrum-client";import{resolve as E2}from"node:path";import{storeIdentity as IZ}from"@cortexkit/claustrum-client";import{SubcClient as AZ}from"@cortexkit/subc-client";import{ClaustrumCredentialError as L4}from"@cortexkit/claustrum-client";import{SocketClosedError as C4,SocketTimeoutError as P4,SubcCallError as O4}from"@cortexkit/subc-client";class I extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var X3=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 V0($){if($ instanceof P0||$ instanceof C4||$ instanceof P4)return"unreachable";let Z=$ instanceof L4||$ instanceof O4?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(X3,Z))return"answered";return X3[Z]}var G3=300000,D1=300000,Q3=1000;class $1{#$;#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 N1{#$;#z;#Z;#X=!1;constructor($,Z){this.#$=$,this.#z=Z}get running(){return this.#Z}request(){if(this.#Z)return this.#X=!0,this.#Z;return this.#Z=(async()=>{do{this.#X=!1;try{await this.#$()}catch($){this.#z($)}}while(this.#X)})().finally(()=>{this.#Z=void 0}),this.#Z}}class L1{#$;#z=new $1;#Z;#X="polling";#H;#G;#J=!1;#Y;#q=!1;#W=0;constructor($){this.#$=$,this.#Z=new N1(async()=>{let Z=this.#q;if(this.#q=!1,Z||this.#Y!==this.#$.view())await this.#$.discover(this.#Y??"")},(Z)=>{if(!this.#J)this.#$.onError?.(Z)})}get mode(){return this.#X}start(){if(this.#J||this.#H||this.#G)return;if(typeof this.#$.client.watchScoped!=="function"){this.#Q("fallback","client-without-watch");return}this.#V(!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()}#Q($,Z){if(this.#X===$)return;this.#X=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#U($,Z){this.#G=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#G=void 0,!this.#J)Z()},$),this.#G.unref?.()}async#V($){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,X;try{X=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.#Y=Q.view,this.#Z.request()},{enrollmentToken:Z})}catch(Q){this.#$.onError?.(Q),this.#F("watch-failed");return}z={handle:X,notices:0},this.#H=z,this.#Q("polling",$?"resubscribing":"opening");let G=z;X.closed.then((Q)=>this.#j(G,Q),(Q)=>this.#j(G,{kind:"transport_lost",error:Q}))}#j($,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.#U(z,()=>void this.#V(!0));return}this.#F(Z.kind)}#F($){this.#Q("fallback",$),this.#U(300000,()=>void this.#V(!1))}}var P1=60000,f2=4*P1,I4=2*P1,W3=new Map,C1=new Map;function Z1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function _4($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!Z1(Z)||typeof Z.kind!=="string"||typeof Z.epoch!=="string"||Z.epoch.length===0||typeof Z.seq!=="number"||!Number.isSafeInteger(Z.seq)||Z.seq<1||Z.provider!==void 0&&typeof Z.provider!=="string")return;return{kind:Z.kind,epoch:Z.epoch,seq:Z.seq,...typeof Z.provider==="string"&&{provider:Z.provider}}}function A4($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class g2{transport;key;#$=[];#z=!1;#Z=new Set;#X=new Map;#H=new N1(async()=>{try{let $=await this.transport.getUsage();if(!Z1($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>Z1(Z)&&typeof Z.provider==="string"),this.#z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#Z=new Set(this.#z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#Z)this.#X.delete(Z)}catch{this.#$=[],this.#z=!1,this.#Z.clear()}},()=>{});#G=new $1;#J="polling";#Y=0;#q=0;#W=new Map;#Q;#U;#V={};#j=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 C1)if($-z>=P1)C1.delete(J);let Z=C1.get(this.key);if(Z!==void 0&&$-Z<P1)return Promise.resolve();return C1.set(this.key,$),this.#H.request()}watchMode(){return this.#J}watch($={}){this.#Y++;let Z=$.provider;if(Z===void 0)this.#q++;else this.#W.set(Z,(this.#W.get(Z)??0)+1);if(this.#Y===1)this.#V=$,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.#Y===0)this.#F()}}#F(){if(this.#U)(this.#V.clearTimeoutImpl??clearTimeout)(this.#U);this.#U=void 0;let $=this.#Q;this.#Q=void 0,$?.handle?.stop(),this.#J="polling"}#M($){this.#U=(this.#V.setTimeoutImpl??setTimeout)(()=>{if(this.#U=void 0,this.#Y>0&&!this.#Q)this.#K()},$),this.#U.unref?.()}#K(){let $=this.transport.watchUsage;if(!$){this.#J="fallback";return}this.#J="polling",this.#G.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.#j=0;let J=_4(Z);if(!J)this.#G.restart();if(!(J?this.#G.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=A4(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.#j,16),D1);this.#j++,this.#J="polling",this.#M(z);return}if(this.#J="fallback",this.#H.request(),Z===void 0||V0(Z)==="unreachable")this.#M(D1)}current($,Z,J){for(let z of this.#$){if(z.provider!==$||typeof z.account!=="string"||z.account.trim()!==Z)continue;if(z.stale!==void 0||z.errorClass!==void 0||!Z1(z.usage))continue;let X=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(X)||J-X>=f2)continue;return{entry:z,context:{fetchedAt:X,...typeof z.source==="string"&&{source:z.source}}}}return}lookup($,Z,J){if(!this.#z)return{miss:"unreachable"};let z=this.#$.find((Q)=>Q.provider===$&&typeof Q.account==="string"&&Q.account.trim()===Z),X=(z??this.#$.find((Q)=>Q.provider===$&&Q.account===void 0&&Q.errorClass!==void 0))?.errorClass;if(X==="upstream_failed")return{miss:"upstream-failed"};if(X==="credential_absent"||X==="credential_unusable"||X==="credential_rejected")return{miss:"credential"};if(X!==void 0)return{miss:"unreachable"};if(z){let Q=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Z1(z.usage)||!Number.isFinite(Q))return{miss:"unreachable"};let W={entry:z,context:{fetchedAt:Q,...typeof z.source==="string"&&{source:z.source}}};return J>=Q+f2||z.stale!==void 0?{miss:"stale",reading:W}:{reading:W}}if(this.#Z.has($))return{miss:"absent"};let G=this.#X.get($)??J;return this.#X.set($,G),{miss:J-G>=I4?"unreachable":"cold"}}}function H3($,Z){let J=JSON.stringify([E2($.connectionFile),E2(Z)]),z=W3.get(J);if(!z)z={source:new g2($,J),refs:0},W3.set(J,z);z.refs++;let X=!1;return{source:z.source,release(){if(X)return;if(X=!0,--z.refs===0)W3.delete(J)}}}import{ClaustrumCredentialError as HX}from"@cortexkit/claustrum-client";import{appendFileSync as m4,chmodSync as w4,existsSync as K3,renameSync as l2,statSync as u4}from"node:fs";import{open as c4}from"node:fs/promises";import{dirname as p4,resolve as d4}from"node:path";import{randomUUID as h2}from"node:crypto";import{lstat as m2,readFile as w2,rename as R4,unlink as x2}from"node:fs/promises";import{tmpdir as S4}from"node:os";import{dirname as M0,join as b4,resolve as i}from"node:path";var _=process.platform==="win32",y2=new Set;function Y3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var v2;var u2="native-addon-unavailable";function c2($){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:$}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:u2})}function k4($,Z){return Z instanceof $.PrivateFilesUnavailableError||Z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function T4($){try{await $.verifyPrivatePath(b4(S4(),`.common-auth-private-files-probe-${h2()}`),"file")}catch(Z){if(k4($,Z))throw c2(Z)}}function y0(){return v2??=import("@cortexkit/private-files").then(async($)=>{if(_)await T4($);return $},($)=>{throw _?c2($):$}),v2}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(z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"?`Private file refused at ${Z}: ${$} (${u2}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`:`Private file refused at ${Z}: ${$} (${z?.reason??z?.code??"io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`,{cause:J});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=Y3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}async function s($,Z,J){try{return await J()}catch(z){if(z instanceof u)throw z;throw new u($,Z,z)}}var E4;async function Q0($,Z){$=i($),Z??=E4,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 m2($);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(),X=await z.verifyOwnerOnly($),G=!1;if(!X.ok){let{reason:Q}=X.refusal;if(Q==="io-error")await z.verifyPrivatePath($,Z);if(J&&[z.EXTRA_ACE,z.NOT_PROTECTED,z.NULL_DACL,z.EMPTY_DACL].includes(Q))await Q0(M0($)),await z.securePrivatePath($,Z),G=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:Q,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await z.verifyPrivatePath($,Z),G&&!y2.has($))y2.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 m2($),await Q0($,J)}catch(G){if(Y3(G)!=="ENOENT")throw G}let X=M0($);if(X===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await J0(X,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(Y3(G)!=="EEXIST")throw G}await Q0($,J)})}async function t($,Z=!1){if(!_)return w2($,"utf8");return(await f4($,Z)).toString("utf8")}async function f4($,Z=!1){if(!_)return w2($);if($=i($),Z)await Q0(M0($)),await p($,"file",!0);return s($,"read",async()=>(await y0()).readOwnerOnly($))}async function v0($,Z){await Q0(M0(i($))),await s($,"create",async()=>{await(await y0()).createPrivateFile(i($),Z)})}async function p2($){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()),X=z(),G=J.deadline??1/0,Q,W=[0,10,20,40,80,100],H,U=0;for(let K of W){let F=Math.min(Q??1/0,G);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()>=G)break;U++;try{return await(J.rename??R4)($,Z),{attempts:U,elapsedMs:z()-X}}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=U,q.elapsedMs=z()-X,q}async function h0($,Z,J={}){$=i($),await J0(M0($));try{await p($,"file",!0)}catch(U){if(U.code!=="ENOENT")throw U}let z=i(J.stagePath??`${$}.${h2()}.tmp`);if(M0(z)!==M0($))throw new u($,"stage-directory",{code:"EXDEV"});let X=!1,G=!1,Q={attempts:0,elapsedMs:0},W="stage-create",H=(U)=>{try{J.onOutcome?.({path:$,stage:U?.stage??"published",published:G,fileDurable:G,durabilityConfirmed:!1,attempts:U?.attempts??Q.attempts,elapsedMs:U?.elapsedMs??Q.elapsedMs,...U&&{code:U.code,win32Code:U.win32Code}})}catch{}};try{if(await v0(z,Z),X=!0,W="before-rename",Q=await q3(z,$,J),X=!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(U){let q=U instanceof u?U:new u($,W,U);if(q.published=G,q.fileDurable=G,G)Object.assign(q,Q);if(X){try{await x2(z)}catch{q.orphanPath=z}X=!1}throw H(q),q}finally{if(X)await x2(z).catch(()=>{})}}var g4=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,x4=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function y4($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function m0($={}){let Z=[x4,...$.extraValuePatterns??[]].map((G)=>new RegExp(G.source,G.flags.includes("g")?G.flags:`${G.flags}g`));function J(G){let Q=G.toLowerCase().replace(/[-_]/g,"");return g4.test(G)||Q.includes("apikey")||Q.endsWith("secret")||Q.endsWith("password")||Q.endsWith("token")&&!Q.endsWith("tokens")||!!$.extraSecretKeys?.(Q)}function z(G){let Q=G,W=[["name",G.name],["message",G.message],["stack",G.stack]];for(let U of["code","status","cause"])if(Q[U]!==void 0)W.push([U,Q[U]]);let H=new Set(W.map(([U])=>U));for(let U of Object.entries(G))if(!H.has(U[0]))W.push(U);return W}function X(G,Q,W,H=0){if(typeof G==="string")return Z.reduce((U,q)=>U.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((K)=>X(K,Q,W,H));let U=y4(G);if(U&&H>=8)return"[Truncated]";let q=U?H+1:H;return Object.fromEntries((U?z(G):Object.entries(G)).map(([K,F])=>[K,Q&&J(K)?"***REDACTED***":X(F,Q,W,q)]))}finally{W.delete(G)}}return{redact:(G)=>X(G,!0,new WeakSet),redactStrings:(G)=>X(G,!1,new WeakSet)}}var d2=m0(),v4=d2.redact,h4=d2.redactStrings;var O1={error:0,warn:1,info:2,debug:3,trace:4},s2=5242880,n2=3;function j3($){try{w4($,384)}catch{}}function l4($){try{if(!(K3($)&&u4($).size>=s2))return;for(let J=n2-1;J>=1;J--)if(K3(`${$}.${J}`)){let z=`${$}.${J+1}`;l2(`${$}.${J}`,z),j3(z)}let Z=`${$}.1`;l2($,Z),j3(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 a2($,Z){await J0(p4(Z));try{await p(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await v0(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await p(Z,"file",!0)}}return $.handle=await s(Z,"log-open",()=>c4(Z,"a")),$.file=Z,$.handle}async function a4($,Z,J){Z=d4(Z);try{if($.file!==Z)await W0($);let z=$.handle??await a2($,Z);if((await s(Z,"log-stat",()=>z.stat())).size>=s2){await W0($);for(let G=n2-1;G>=0;G--){let Q=G===0?Z:`${Z}.${G}`,W=`${Z}.${G+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 a2($,Z)}await s(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await W0($).catch(()=>{}),z}}function s4($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function n4($){let Z,J,z,X=m0(),G,Q=[],W,H=Promise.resolve(),U,q={};function K(Y){let j=H.then(Y);return H=j.catch((V)=>{U=V}),j}function F(Y){if(_&&Y.file!==Z)K(()=>W0(q)).catch(()=>{});Z=Y.file,J=Y.level,X=m0(Y),G=Y.captureSink}function B(Y){if(Y===void 0||Y in O1)z=Y}function P(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function C(){if(z)return z;let Y=typeof J==="function"?J():J;if(Y&&Y in O1)return Y;return"info"}function D(Y=!0){if(W)clearTimeout(W),W=void 0;if(!Q.length){if(_)return K(async()=>{if(Y)await W0(q);if(U)throw U});return}let j;try{j=P()}catch{if(Q=[],_&&Y)return K(()=>W0(q));return}let V=Q.join("");if(Q=[],!j){if(_&&Y)return K(()=>W0(q));return}if(_)return K(async()=>{try{await a4(q,j,V)}finally{if(Y)await W0(q)}});try{if(l4(j),K3(j))j3(j);m4(j,V,{encoding:"utf8",mode:384})}catch{}}function R(){if(!W)W=setTimeout(()=>{W=void 0;let Y=D(!1);if(Y instanceof Promise)Y.catch(()=>{})},500)}function S(Y,j,V,b){if(Z===void 0&&G===void 0)return;try{if(O1[j]>O1[C()])return;let g=X.redactStrings(V),k;try{k=X.redact(b)}catch{k="[unserializable]"}let m=`[${new Date().toISOString()}] ${j.toUpperCase()} [${Y}] ${g}`+(b===void 0?"":s4(k))+`
|
|
3
|
+
`;try{G?.({channel:Y,level:j,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(Y){return{error:(j,V)=>S(Y,"error",j,V),warn:(j,V)=>S(Y,"warn",j,V),info:(j,V)=>S(Y,"info",j,V),debug:(j,V)=>S(Y,"debug",j,V),trace:(j,V)=>S(Y,"trace",j,V)}}function N(){if(_)K(()=>W0(q)).catch(()=>{});if(U=void 0,Q=[],W)clearTimeout(W),W=void 0;Z=void 0,J=void 0,z=void 0,X=m0(),G=void 0}if($)F($);return{configure:F,createLogger:y,setLogLevel:B,flushLogs:D,reset:N}}var i4=n4();function O0($){return i4.createLogger($)}function V3($){let Z=new AbortController,J=[],z=!1,X=()=>{if(z)return;z=!0;for(let{source:W,listener:H}of J)W.removeEventListener("abort",H);J.length=0},G=(W)=>{if(z||Z.signal.aborted)return;Z.abort(W),X()},Q=$.find((W)=>W.aborted);if(Q)return Z.abort(Q.reason),{signal:Z.signal,dispose:X};for(let W of $){if(Z.signal.aborted)break;let H=()=>G(W.reason);if(J.push({source:W,listener:H}),W.addEventListener("abort",H,{once:!0}),W.aborted)G(W.reason)}return{signal:Z.signal,dispose:X}}import{ClaustrumCredentialError as P$}from"@cortexkit/claustrum-client";import{createHash as z7,randomBytes as X7,randomUUID as G7}from"node:crypto";import{constants as W$}from"node:fs";import{chmod as Q7,mkdir as W7,open as U$,readFile as D3,realpath as H7,rename as Y7,stat as q$,unlink as L3}from"node:fs/promises";import{basename as U7,dirname as R0,extname as _J,isAbsolute as AJ,join as q7,resolve as RJ}from"node:path";import{ClaustrumCredentialError as K7,ClaustrumClient as bJ,writeEnrollmentTokenFile as j7}from"@cortexkit/claustrum-client";import{randomUUID as i2}from"node:crypto";import{mkdir as r4,open as r2,rename as o4,rm as t4}from"node:fs/promises";import{dirname as o2}from"node:path";class I1 extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function J1($,Z,J={}){await t2($,Z,J)}async function t2($,Z,J,z){if(_)return h0($,J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
4
4
|
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??i2)()}.tmp`,onRenamed:z,durable:J.durable,durability:J.durability,onOutcome:J.onOutcome});await r4(o2($),{recursive:!0});let X=`${$}.${(J.stageName??i2)()}.tmp`,G,Q=!1;try{if(G=await r2(X,"wx",384),Q=!0,await G.writeFile(J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
5
|
-
`,"utf8"),await G.chmod(384),J.durable)try{await G.sync()}catch(W){throw new I1(W)}if(await G.close(),G=void 0,await J.beforeRename?.(),await o4(X,$),Q=!1,z?.(),J.durable){let W=await r2(o2($),"r");try{await W.sync()}catch(H){throw new I1(H)}finally{await W.close()}}}finally{if(await G?.close().catch(()=>{}),Q)await t4(X,{force:!0}).catch(()=>{})}}var e4=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 _1}from"node:crypto";import{mkdir as e2,open as G$,readFile as $$,rename as Z$,rm as A1,stat as J$}from"node:fs/promises";import{dirname as B3,join as z$}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 X=await H0({path:$,name:Z.name,ttlMs:Z.ttlMs,renew:Z.renew??!1,...Z.onStep?{onStep:Z.onStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}});if(X)try{return Z.signal?.throwIfAborted(),await J(X)}finally{await X.release()}let G=Z.timeoutMs-(performance.now()-z);if(G<=0)throw new I0({target:$,name:Z.name,timeoutMs:Z.timeoutMs});await new Promise((Q)=>setTimeout(Q,Math.min(25,Math.ceil(G))))}}async function X$($,Z){let J=await G$($,"wx",384);try{await J.writeFile(Z,"utf8")}finally{await J.close()}}var $7=globalThis.setTimeout.bind(globalThis),Z7=globalThis.clearTimeout.bind(globalThis);function Q$($){let Z=$?.code;return Z==="ENOENT"||!_&&(Z==="EINVAL"||Z==="ENOTDIR")}function H0($){return J7({...$,now:Date.now})}async function J7($){let Z=M3($.path,$.name),J=z$(Z,"owner.json"),z=_1(),X=$.now??Date.now,G=null,Q=!1,W=!1,H,U,q=new Promise((M)=>{U=M});function K(M){try{let
|
|
6
|
-
`,{deadline:performance.now()+Math.max(0,w),beforeRename:async()=>{let B1=await Y();if(B1?.ownerId!==z||!(Number(B1?.expiresAt)>X())||!await v())throw new _0({target:$.path,name:$.name})}});return}let M=`${Z}.${_1()}.tmp`,
|
|
7
|
-
`,"utf8"),await
|
|
8
|
-
`;if(_)await v0(Z,M);else await X$(Z,M)}async function b(M){let
|
|
9
|
-
`;if(_)await v0(R,M);else await X$(R,M)}catch(M){if(Q$(M))return!1;throw await o(),M}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function x0(){let M;try{M=await J$(D)}catch(O){if(O.code==="ENOENT")return"missing";throw O}if(_)await p(D,"directory",!0);if(M.mtimeMs+y>X())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let
|
|
10
|
-
`)){if(z.trim()===""||z.startsWith("#"))continue;let X=z.split(":");if(X.length!==Z||!/^[^\s:,]+$/.test(X[0]??"")||!/^\d+$/.test(X[2]??"")||!Number.isSafeInteger(Number(X[2]))||Z===7&&(!/^\d+$/.test(X[3]??"")||!Number.isSafeInteger(Number(X[3])))||Z===4&&X[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(X[3]??""))return;J.push(X)}return J}async function F7($,Z,J){try{let[z,X]=await Promise.all([D3(J.passwdPath??"/etc/passwd","utf8"),D3(J.groupPath??"/etc/group","utf8")]),G=Y$(z,7),Q=Y$(X,4);if(!G||!Q)return!1;let W=G.filter((K)=>Number(K[2])===$),H=Q.filter((K)=>Number(K[2])===Z);if(W.length!==1||H.length!==1)return!1;let U=W[0]?.[0],q=H[0]?.[3]??"";return(q===""||q.split(",").every((K)=>K===U))&&!G.some((K)=>Number(K[2])!==$&&Number(K[3])===Z)}catch{return!1}}function D$($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>D3(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function
|
|
11
|
-
`;if(Buffer.byteLength(X)>S1)throw new I("invalid-state","Claustrum enrollment state is too large");if(_)return h0($,X);let G=q7(z,`.${U7($)}.${process.pid}.${G7()}.tmp`),Q,W=!1;try{Q=await U$(G,"wx",384),W=!0,await Q.writeFile(X,"utf8"),await Q.chmod(384),await Q.sync(),await Q.close(),Q=void 0,await Y7(G,$),W=!1}finally{if(await Q?.close().catch(()=>{}),W)await N3(G).catch(()=>{})}}async function I3($,Z){let J=await S0($.tokenPath),z=J===void 0?void 0:O3(J),X=await S0($.statePath),G=X===void 0?void 0:P3(X);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 F0(G)}async function B0($){let Z=await S0($);if(Z===void 0)throw new I("not-enrolled","Claustrum enrollment is not configured");return O3(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 N$(){return new I("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class _3{#$;#z;#Z;#X;#H;#G;#J;constructor($){this.#J=$.ancestorOptions??{},this.#$=$.client,this.#z=$.paths,this.#Z=$.proposedName,this.#X=$.now??Date.now,this.#H=$.mintSecret??(()=>X7(32).toString("hex")),this.#G=$.writeTokenFile??j7}async status(){return I3(this.#z,this.#Z)}async resetTerminal(){return C$(this.#z,this.#Z)}async#Y($,Z){let J={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#X()};return await A0(this.#z.statePath,J,this.#J),F0(J)}async reconcile(){await b1(R0(this.#z.statePath),this.#J);let $=await H0({name:"ceremony",path:this.#z.statePath,ttlMs:K$,renew:!0});if(!$)return{state:"busy"};try{let Z=await S0(this.#z.tokenPath),J=Z===void 0?void 0:O3(Z),z=await S0(this.#z.statePath),X=z===void 0?void 0:P3(z);if(X&&X.proposedName!==this.#Z)throw N$();if(J){if(!X||X.phase==="pending"){let Q={version:1,phase:"approved",proposedName:X?.proposedName??this.#Z,tokenGeneration:J.token_generation,updatedAt:this.#X()};await A0(this.#z.statePath,Q,this.#J),X=Q}return{state:"approved",proposedName:X.proposedName,...X.phase==="approved"&&X.approvedName!==void 0&&{approvedName:X.approvedName},tokenGeneration:J.token_generation}}if(X?.phase==="approved"){let Q={version:1,phase:"blocked",proposedName:X.proposedName,errorCode:"missing_token",updatedAt:this.#X()};return await A0(this.#z.statePath,Q,this.#J),F0(Q)}if(X&&X.phase!=="pending")return F0(X);if(!X){let Q=this.#X();if(X={version:1,phase:"pending",proposedName:this.#Z,requestSecret:this.#H(),createdAt:Q,updatedAt:Q},!C3.test(X.requestSecret))throw new I("invalid-state","invalid minted Claustrum enrollment secret");await A0(this.#z.statePath,X,this.#J)}if(!X.requestId)try{let Q=z7("sha256").update(Buffer.from(X.requestSecret,"hex")).digest("hex"),W=await this.#$.enrollPropose({name:X.proposedName,requestSecretHash:Q});X={...X,requestId:W.requestId,updatedAt:this.#X()},await A0(this.#z.statePath,X,this.#J)}catch(Q){let W=L3(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,retryCode:W.code};if(W.code===j$)return await $.assertOwned(),await N3(this.#z.statePath).catch((H)=>{if(H.code!=="ENOENT")throw H}),{state:"unavailable",proposedName:X.proposedName,code:W.code};return this.#Y(X,W.code)}let G=X.requestId;if(!G)return F0(X);try{let Q=await this.#$.enrollPoll({requestId:G,requestSecret:X.requestSecret});if(Q.status==="pending")return F0(X);if(Q.status==="denied"){let H={version:1,phase:"denied",proposedName:X.proposedName,updatedAt:this.#X()};return await A0(this.#z.statePath,H,this.#J),F0(H)}await b1(R0(this.#z.tokenPath),this.#J),await L$(R0(this.#z.tokenPath),this.#J),await this.#G(this.#z.tokenPath,{token:Q.token,token_generation:Q.tokenGeneration});let W={version:1,phase:"approved",proposedName:X.proposedName,approvedName:Q.name,tokenGeneration:Q.tokenGeneration,updatedAt:this.#X()};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:X.proposedName,requestId:G,retryCode:W.code};return this.#Y(X,W.code)}}finally{await $.release()}}}async function C$($,Z){await b1(R0($.statePath));let J=await H0({name:"ceremony",path:$.statePath,ttlMs:K$,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 X=P3(z);if(X.proposedName!==Z)throw N$();if(X.phase==="pending")return"refused-pending";return await J.assertOwned(),await N3($.statePath),"reset"}finally{await J.release()}}var A3="claustrum-tombstone:v1:";function O$($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function B7($,Z){if(Z===void 0)return"reauthorize-failed";if(Z.credentialId!==$.credentialId)return"credential-changed";if(Z.accountIdentity!==$.accountIdentity)return"account-changed";if(Z.recordVersion===$.recordVersion)return"version-unchanged";return"rotated"}var S3=O0("claustrum");function k3($,Z,J,z=S3){let X=O$(Z,J);return z.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:J?.recordVersion??null,retry:X,reason:B7(Z,J)}),X}var b3=300000,I$=60000;function R3(){return new I("invalid-material","Claustrum returned invalid credential material")}function D7($){let Z=$.trim();if(Z.startsWith("{")){let J;try{J=JSON.parse(Z)}catch{throw R3()}if(!J||typeof J!=="object")throw R3();let z=J,X=z.access_token??z.access;Z=typeof X==="string"?X:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(A3))throw R3();return Z}function L7($,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 N7($){let{grants:Z,grantTuples:J}=$;if(Z===void 0||J===void 0)return;return Object.freeze({grants:Z,tuples:Object.freeze(J.map(({selectorKind:z,selector:X,operation:G})=>Object.freeze({selectorKind:z,selector:X,operation:G})))})}class k1{#$;#z;#Z;#X;#H;#G;#J;#Y=new WeakMap;#q=new WeakMap;#W=new Map;#Q=new WeakMap;#U;#V;#j=!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.#X=$.family,this.#H=$.parseIdentity,this.#G=$.requireAssertion??!1,this.#Z=$.now??Date.now,this.#J=$.logger??S3,this.#U=$.setTimeoutImpl??setTimeout,this.#V=$.clearTimeoutImpl??clearTimeout}transportLost($){if(this.#L||this.#j)return;this.#j=!0,this.#F=$ instanceof P$?$:new P0,this.#J.warn("serving kept vault receipt",{reason:"unreachable"}),this.#O()}reachable(){if(this.#L||!this.#j)return;if(this.#j=!1,this.#M)this.#V(this.#M);this.#M=void 0,this.#D=2000;for(let $ of this.#W.values())$.since=null;(this.#J.info??S3.info)("vault receipt serving resumed",{reason:"reachable"})}#O(){if(this.#L||!this.#j||this.#M||this.#K)return;this.#M=this.#U(()=>{this.#M=void 0,this.#I(!0)},this.#D),this.#M.unref?.()}#I($=!1){if(this.#L||!this.#j||this.#K)return;if(this.#Z()-this.#B<1000){this.#O();return}this.#B=this.#Z(),this.#K=!0,this.#R().catch(()=>{if($&&this.#j)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 X=$();J=Z?await Promise.race([X,new Promise((G,Q)=>{let W=()=>Q(Z.reason);if(Z.addEventListener("abort",W,{once:!0}),z=()=>Z.removeEventListener("abort",W),Z.aborted)W()})]):await X}catch(X){if(this.#N(Z),V0(X)==="unreachable")this.transportLost(X);else this.reachable();if(X instanceof P$)throw X;if(V0(X)==="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=[],X=[],G=new Map;for(let H of Z.rows){let U=L7(H,this.#X);if(!U)continue;X.push({row:H,type:U}),G.set(H.id,(G.get(H.id)??0)+1)}let Q=[];for(let{row:H,type:U}of X){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}Q.push(Object.freeze({credentialId:H.id,credentialType:U,...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=N7(Z);return{view:Z.view,credentials:Object.freeze(Q),skipped:Object.freeze(z),...W&&{grantReach:W}}}listFailed($){if(V0($)==="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 X=Z.get(J);if(!X?.enabled||X.state!=="active"||X.credentialType!==z.attempt.credentialType||X.accountIdentity!==z.attempt.expectedAccountIdentity)this.forget(J)}}keptReceiptState(){let $=null;for(let[Z,J]of this.#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()>I$}async authorize($,Z,J="vault"){this.#N(Z);let{credentialId:z,credentialType:X,accountIdentity:G}=$,Q=this.#W.get(z);if(Q&&(Q.attempt.credentialType!==X||Q.attempt.expectedAccountIdentity!==G))this.forget(z),Q=void 0;let W;try{W=await this.#_(Z)}catch(H){throw this.#W.clear(),H}if(this.#j&&Q)return this.#I(),this.#b(z,Q,W,J);try{let H=await this.#k({credentialId:z,credentialType:X,accountIdentity:G},W,Z);return this.#W.set(z,{attempt:H,routeId:J,since:null}),H}catch(H){if(this.#N(Z),V0(H)!=="unreachable")throw this.forget(z),H;return this.#b(z,Q,W,J,H)}}#b($,Z,J,z,X=this.#F){if(!Z||this.#W.get($)!==Z||!this.#S(Z.attempt))throw this.forget($),X;if(Z.since===null)Z.since=this.#Z();let G=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#Y.set(G,J),this.#Q.set(G,z),G}async#k($,Z,J){if(!$.credentialId)throw new I("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:z,credentialType:X,accountIdentity:G}=$;if(this.#G&&G===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,...X==="oauth"&&{minTtlMs:b3}}),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&&X==="oauth"||W!==null&&(!Number.isFinite(W)||W-this.#Z()<b3))throw new I("insufficient-validity","Claustrum served credential has insufficient validity");let H=D7(Q.material),U=Q.accountId?.trim()?Q.accountId:void 0;if(this.#G&&(Q.credentialId===void 0||U===void 0))throw new I("identity-unasserted","Claustrum served credential did not assert its identity");let q=U===void 0?this.#H?.(H):void 0,K=U??q;if(G!==void 0&&K!==void 0&&K!==G)throw new I("identity-changed","Claustrum served credential identity changed");let F=K??G,P=Object.freeze(Object.defineProperty({credentialId:z,credentialType:X,...F!==void 0&&{accountIdentity:F},accountIdentitySource:U!==void 0?"asserted":q!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...Q.credentialId!==void 0&&{assertedCredentialId:Q.credentialId},...U!==void 0&&{assertedAccountIdentity:U},...Q.projectId!==void 0&&{projectId:Q.projectId},recordVersion:Q.recordVersion,expiresAtMs:W},"accessToken",{value:H,enumerable:!1}));return this.#Y.set(P,Z),P}async reportFailure($,Z,J){if(Z!==401)return;this.#N();let z=this.#Y.get($);if(!z)throw new I("no-receipt","Claustrum failure report requires an original dispatch receipt");let X=this.#Q.get($);if(X!==void 0){this.forget($.credentialId),this.#J.debug("scoped 401 not reported",{routeId:X,reason:"kept-receipt"});return}let G=this.#W.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let Q=this.#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 N1({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.#U,clearTimeoutImpl:this.#V});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.#V(this.#M);this.#M=void 0;for(let $ of this.#P)$.stop();this.#P.clear(),this.#W.clear(),this.#$.close()}}import{resolve as l3}from"node:path";var b0="all",C7=Object.freeze(["primary"]);function A$($){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 _$($){return typeof $==="string"&&$.length>0}function l($,Z,J){return $[Z]===void 0||J($[Z])}function P7($){return d($)&&$>0}function T3($){return typeof $==="string"}function O7($){if(!D0($)||!_$($.scope)||!_$($.label))return!1;switch($.kind){case"reading":return d($.checkedAt)&&d($.usedPercent)&&l($,"resetsAt",T3)&&l($,"windowMinutes",P7);case"retired":return d($.retiredAt);case"absent":return d($.checkedAt);default:return!1}}function I7($){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",T3)&&l($,"limit",d)&&l($,"used",d)&&l($,"remaining",d)&&l($,"unit",T3)}function R$($){return D0($)&&d($.value)&&Number.isInteger($.value)&&$.value>=0&&d($.checkedAt)}function E3($){return D0($)&&Object.values($).every(R$)}function _7($){return typeof $==="boolean"}function c0($){return D0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&l($,"balance",d)&&l($,"overageLimitReached",_7)&&d($.checkedAt)}function S$($){if(!D0($))return;let Z=Object.entries($).filter(([,J])=>R$(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 X=S$(Z),G=c0(J)?J:void 0;return{...z,...X===void 0?{}:{counters:X},...G===void 0?{}:{credits:G}}}function w0($){if(!D0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!O7(J))return!1;let z=u0(J.scope,J.label);if(Z.has(z))return!1;Z.add(z)}return l($,"budget",I7)&&l($,"counters",E3)&&l($,"credits",c0)}class T1 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function f1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function E1($){return typeof $==="number"&&Number.isFinite($)}function b$($){return $===void 0||typeof $==="string"&&$!==""}function k$($){return typeof $==="string"&&$!==""}function X1($,Z){return $[Z]===void 0||E1($[Z])}function f3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function A7($){return f1($)&&b$($.scope)&&k$($.label)&&E1($.usedPercent)&&f3($,"resetsAt")&&($.windowMinutes===void 0||E1($.windowMinutes)&&$.windowMinutes>0)}function R7($){return f1($)&&b$($.scope)&&k$($.label)}function S7($){if(!f1($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&X1($,"remainingPercent")&&X1($,"usedPercent")&&f3($,"resetsAt")&&X1($,"limit")&&X1($,"used")&&X1($,"remaining")&&f3($,"unit")}function p0($){if(!f1($)||!E1($.checkedAt))return!1;let Z=$.readings??[],J=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(J))return!1;let z=new Set;for(let X of Z){if(!A7(X))return!1;let G=u0(X.scope??b0,X.label);if(z.has(G))return!1;z.add(G)}if(!J.every(R7))return!1;return($.budget===void 0||S7($.budget))&&($.counters===void 0||E3($.counters))&&($.credits===void 0||c0($.credits))}function b7($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function k7($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function T7($,Z){let J=new Map(Object.entries($??{}));for(let[z,X]of Object.entries(Z??{})){let G=J.get(z);if(G===void 0||X.checkedAt>=G.checkedAt)J.set(z,X)}return J.size===0?void 0:Object.fromEntries(J)}function E7($,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 T1("stored quota map is malformed");if(!p0(Z))throw new T1("quota observation is malformed");let z=J??{limits:[]},X=Z.checkedAt,G=new Map;for(let D of z.limits)G.set(u0(D.scope,D.label),D);let Q=(D)=>{let R=G.get(D);return R===void 0||X>=A$(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;G.set(S,{scope:R,label:D.label,kind:"reading",checkedAt:X,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=G.get(S);G.set(S,y===void 0||y.kind==="absent"?{scope:R,label:D.label,kind:"absent",checkedAt:X}:{scope:R,label:D.label,kind:"retired",retiredAt:X})}let{limits:H,budget:U,counters:q,credits:K,...F}=z,B=k7(z.budget,Z.budget,X),P=T7(z.counters,Z.counters),C=E7(z.credits,Z.credits);return{...F,limits:[...G.values()].sort(b7),...B===void 0?{}:{budget:B},...P===void 0?{}:{counters:P},...C===void 0?{}:{credits:C}}}var f7=Object.freeze({validate:w0,decode:k0,merge:G1});import{createHash as v7}from"node:crypto";import{resolve as f$}from"node:path";function T$($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function g3($,Z,J){return $.some((z)=>T$(z,Z,J))}function x3($,Z,J){let z={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((X)=>X.credentialId!==Z||X.accountIdentity!==J),z]}function y3($,Z,J){return $.filter((z)=>!Z.some((X)=>T$(z,X,J)))}var g$="vault:";function h7($){return v7("sha256").update($).digest("hex")}function m7($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function w7($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function L0($){return[$.credentialId,...$.aliases??[]]}function x$($,Z,J={}){let z=J.now??Date.now(),X=J.routePrefix??g$,G=J.reservedRouteIds??new Set,Q=$?.rows??[],W=[...$?.declined??[]],H=Z.skipped.length===0,U=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)=>!U.has(L)&&(q.has(L)||K),B=new Map;for(let L of Q){if(L.accountIdentity===void 0)continue;for(let Y of L0(L))if(!B.has(Y))B.set(Y,L.accountIdentity)}let P=new Map;for(let L of Z.credentials){let Y=L.accountIdentity!==void 0?{credential:L,identity:L.accountIdentity,claimed:!0}:{credential:L,identity:B.get(L.credentialId),claimed:!1},j=w7(Y),V=P.get(j)??[];V.push(Y),P.set(j,V)}let C=new Set,D=new Set(G),R=[],S=(L,Y)=>L.credential.credentialId.localeCompare(Y.credential.credentialId),y=[...P.values()].map((L)=>L.toSorted(S)).sort((L,Y)=>L[0]&&Y[0]?S(L[0],Y[0]):0);for(let L of y){let Y=L[0]?.identity,j=L.filter((T)=>T.credential.state==="active"),V=j.length?j:L,b=V.filter((T)=>T.claimed),g=b.length?b:V,k=new Set(L.map((T)=>T.credential.credentialId)),m=Q.find((T)=>!C.has(T)&&L0(T).some((G0)=>k.has(G0))&&(T.accountIdentity===void 0||T.accountIdentity===Y)),n=g.find((T)=>T.credential.credentialId===m?.credentialId)??g[0];if(!n)continue;let v=n.credential,c=m??(Y===void 0?void 0:Q.find((T)=>!C.has(T)&&T.accountIdentity===Y));if(c)C.add(c);let o=c?.routeId;if(!o||G.has(o)){let T=`${X}${v.credentialId}${Y===void 0?"":`~${h7(Y).slice(0,10)}`}`;o=T;for(let G0=2;D.has(o);G0++)o=`${T}~${G0}`}D.add(o);let M1=c?L0(c).filter(F):[],x0=[...new Set([...L.map((T)=>T.credential.credentialId),...M1])].filter((T)=>T!==v.credentialId).sort((T,G0)=>T.localeCompare(G0)),F1=J.mapAccount?.(v)??{};R.push({previousIndex:c?Q.indexOf(c):1/0,row:{routeId:o,credentialId:v.credentialId,credentialType:v.credentialType,...Y!==void 0&&{accountIdentity:Y},...x0.length&&{aliases:x0},state:v.state,label:F1.label?.trim()||m7(v),...v.email!==void 0&&{email:v.email},...v.orgName!==void 0&&{orgName:v.orgName},enabled:![v.credentialId,...x0].some((T)=>g3(W,T,Y)),addedAt:c?.addedAt??z,...c?.quota!==void 0&&{quota:c.quota},...!n.claimed&&Y!==void 0&&{unclaimed:!0}}})}return Q.forEach((L,Y)=>{if(C.has(L)||!L0(L).some(F))return;if(D.has(L.routeId))return;let[j,...V]=L0(L).filter((k)=>!U.has(k));if(j===void 0)return;D.add(L.routeId);let{aliases:b,...g}=L;R.push({previousIndex:Y,row:{...g,credentialId:j,...V.length&&{aliases:V},stale:!0}})}),R.sort((L,Y)=>L.previousIndex===Y.previousIndex?L.row.credentialId.localeCompare(Y.row.credentialId):L.previousIndex-Y.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 v3($){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 Q1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function d0($){return $===void 0||typeof $==="string"}function u7($){let Z=Q1($)?k0($.quota):void 0;if(!Q1($)||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 c7=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function E$($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!Q1(J)||!d0(J.credentialId)||typeof J.reason!=="string"||!c7.has(J.reason))return;Z.push(J)}return Z}function p7($){if(!Q1($)||$.version!==1||!d0($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!E$($.rejected))throw new I("invalid-state","Claustrum roster file is not valid");let Z=[];for(let X of $.rows){let G=u7(X);if(!G)throw new I("invalid-state","Claustrum roster file is not valid");Z.push(G)}let J=[];for(let X of $.declined){if(!Q1(X)||typeof X.credentialId!=="string"||!d0(X.accountIdentity))throw new I("invalid-state","Claustrum roster file is not valid");J.push(X)}let z=E$($.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 p7(J)}var d7={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},l7={name:"claustrum-roster",ttlMs:30000};async function l0($,Z,J={}){return F3($,{...d7,signal:J.signal},async(z)=>{let X=await e($),{next:G,result:Q}=await Z(X,{assertOwned:()=>z.assertOwned()});if(G)await z.assertOwned(),await J1($,G,{beforeRename:async()=>{await J.beforePublish?.(),J.signal?.throwIfAborted(),await z.assertOwned()}});return Q})}function h3($,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");let X=x3(J.declined,z.credentialId,z.accountIdentity);return{next:{...J,declined:X,rows:J.rows.map((G)=>G===z?{...G,enabled:!1}:G)},result:void 0}})}function m3($,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");return{next:{...J,declined:y3(J.declined,L0(z),z.accountIdentity),rows:J.rows.map((X)=>X===z?{...X,enabled:!0}:X)},result:void 0}})}function a7($,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 w3($,Z){let{routeId:J,observation:z,...X}=Z;return y$($,{routeId:J,observation:z,accountIdentity:X.accountIdentity,receipt:X})}async function y$($,Z){if(!p0(Z.observation))return!1;let J=Y0($,await e($));if(!N0(J,Z).kept)return!1;return v$($,Z)}function u3($,Z){return y$($,Z)}function N0($,Z){let J=$?.rows.find((Q)=>Q.routeId===Z.routeId),z=!J?"refuse":Z.receipt?a7(J,Z.receipt):J.accountIdentity!==void 0&&J.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!J||z==="refuse")return{roster:$,kept:!1};let X=G1(J.quota,Z.observation),G=z==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{roster:{...$,rows:$.rows.map((Q)=>Q===J?{...Q,...G,quota:X}:Q)},kept:!0}}var g1=new Map;function c3($){g1.delete(f$($))}async function p3($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){c3($.path);return}let J=await H0({...l7,path:$.path,renew:!0});if(!J){let G=await e($.path);if($.signal?.throwIfAborted(),!G?.view)throw new I("roster-busy","Claustrum account discovery is already in progress");return G}let z=f$($.path),X;try{let G=await e($.path),Q=g1.get(z);X=Q&&(Q.previousView===G?.view||Q.inventory.view===G?.view)?Q:{inventory:await $.custody.discover($.signal),previousView:G?.view},g1.delete(z);let{inventory:W}=X;return $.onInventory?.(W),$.signal?.throwIfAborted(),await l0($.path,async(H)=>{if(!await Z())return{result:void 0};$.signal?.throwIfAborted(),await J.assertOwned();let U=typeof $.projection==="function"?$.projection():$.projection,q=x$(H,W,U);return{...JSON.stringify(H)!==JSON.stringify(q)&&{next:q},result:q}},{beforePublish:async()=>{$.signal?.throwIfAborted(),await J.assertOwned()}})}catch(G){if(G instanceof I0&&X&&!$.signal?.aborted&&await Z())g1.set(z,X);throw G}finally{await J.release()}}var a0=new Map,s7=O0("claustrum"),h$=100;function m$($){let Z=l3($),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 w$($,Z){let J=m$($);J.listeners.add(Z);let z;return()=>z??=(()=>{return J.listeners.delete(Z),J.listeners.size?Promise.resolve():d3($)})()}function n7($){let Z=new Map,{observation:J}=$,z=JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]),X=(W,H,U)=>Z.set(`${z}:${W}`,{at:H,order:0,publication:{...$,observation:U}}),G=(W,H)=>JSON.stringify([W??"all",H]),Q=new Set;for(let W of J.readings??[]){let H=G(W.scope,W.label);Q.add(H),X(H,J.checkedAt,{checkedAt:J.checkedAt,readings:[{...W}]})}for(let W of J.coverage??[]){let H=G(W.scope,W.label);if(!Q.has(H))X(H,J.checkedAt,{checkedAt:J.checkedAt,coverage:[{...W}]})}if(J.budget)X("budget",J.checkedAt,{checkedAt:J.checkedAt,budget:{...J.budget}});for(let[W,H]of Object.entries(J.counters??{}))X(`counter:${W}`,H.checkedAt,{checkedAt:J.checkedAt,counters:{[W]:{...H}}});if(J.credits)X("credits",J.credits.checkedAt,{checkedAt:J.checkedAt,credits:{...J.credits}});if(!Z.size)X("empty",J.checkedAt,{checkedAt:J.checkedAt});return Z}function v$($,Z){if(!p0(Z.observation))return Promise.resolve(!1);let J=m$($),z=JSON.stringify([Z.accountIdentity??null,Z.accountIdentity===void 0?Z.routeId:null]),X=J.pending.get(z)??new Map;for(let[G,Q]of n7(Z)){let W=X.get(G);if(!W||Q.at>=W.at){if(Q.order=++J.order,Q.publication.observation.coverage)Q.priorReading=W?.publication.observation.readings?W.publication:W?.priorReading;X.set(G,Q)}}if(X.size)J.pending.set(z,X);for(let G of J.listeners)G(Z);return c$(J,h$),Promise.resolve(!0)}function u$($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,J)=>Z.order-J.order)}function Y0($,Z){let J=a0.get(l3($));if(J)for(let z of u$(J.pending)){if(z.priorReading)Z=N0(Z,z.priorReading).roster;Z=N0(Z,z.publication).roster}return Z}function c$($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;if($.timer=setTimeout(()=>{$.timer=void 0,p$($)},Z),!$.draining)$.timer.unref?.()}function p$($){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 X of u$(Z)){if(X.priorReading)z=N0(z,X.priorReading).roster;z=N0(z,X.publication).roster}return{...z!==J&&{next:z},result:void 0}},{signal:$.abort.signal});for(let[J,z]of Z){let X=$.pending.get(J);for(let[G,Q]of z)if(X?.get(G)===Q)X.delete(G);if(!X?.size)$.pending.delete(J)}$.failures=0}catch(J){if(!$.abort.signal.aborted&&$.failures++===0)s7.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()):h$;c$($,J)}})()}async function d3($,Z=1000){let J=l3($),z=a0.get(J);if(!z)return;z.draining=!0,clearTimeout(z.timer),z.timer=void 0;let X,G,Q=new Promise((W)=>{G=()=>{if(!z.pending.size||z.abort.signal.aborted)W()},z.wake.add(G),G()});try{if(z.pending.size)p$(z);await Promise.race([Q,new Promise((W)=>{X=setTimeout(W,Math.max(0,Z))})])}finally{if(clearTimeout(X),G)z.wake.delete(G);if(z.draining=!1,!z.listeners.size){if(z.abort.abort(),clearTimeout(z.timer),z.pending.clear(),a0.get(J)===z)a0.delete(J)}}}class d${#$;#z=new AbortController;#Z;#X;#H;#G;#J;#Y;#q;#W=!1;#Q;#U;#V;#j=new Map;#F;#M;constructor($){this.#$=$,this.#Z=$.logger??O0("claustrum"),this.#M=w$($.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=V3([this.#z.signal,...Z?[Z]:[]]);return new Promise((z,X)=>{let G=()=>{J.signal.removeEventListener("abort",Q),J.dispose()},Q=()=>{G(),X(J.signal.reason)};if(J.signal.addEventListener("abort",Q,{once:!0}),$.then((W)=>{if(G(),J.signal.aborted)X(J.signal.reason);else z(W)},(W)=>{G(),X(W)}),J.signal.aborted)Q()})}async#L(){if(this.#K(),this.#X)return this.#X;if(!this.#H)this.#H=this.#$.connect().then(($)=>{if(this.#z.signal.aborted)$.close(),this.#K();if(this.#X=new k1({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.#X}).finally(()=>{this.#H=void 0});return this.#D(this.#H)}snapshot(){return this.#J}grantReach(){let $=this.#Y;return $&&this.#J?.view===$.view?$.reach:void 0}watchState(){return Object.freeze({vault:this.#U?.mode??"polling",...this.#$.insula&&{insula:this.#Q?.source.watchMode()??"polling"}})}#C(){this.#U?.close(),this.#U=void 0,this.#V?.(),this.#V=void 0}keptReceiptState(){return this.#X?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return v3(this.#J)}refresh(){if(this.#K(),this.#G)return this.#G;return this.#G=(async()=>{if(!await this.#B()){this.#J=void 0,this.#Y=void 0,this.#C(),this.#X?.close(),this.#X=void 0,this.#Q?.release(),this.#Q=void 0;return}let $=await this.#L(),Z,J=await p3({path:this.#$.rosterPath,custody:$,onInventory:(X)=>{Z=X},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=Y0(this.#$.rosterPath,J),$.retain(J?.rows??[]),Z&&J?.view!==void 0)this.#Y=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.#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.#U?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#F===void 0||$-this.#F>=G3)return!0;return!await this.#B()}#O(){let $=this.#X;if(this.#z.signal.aborted||!$)return;if(this.#U??=$.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.#Q&&!this.#V)this.#V=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=Y0(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=Y0(this.#$.rosterPath,await e(this.#$.rosterPath))?.rows.find((Q)=>Q.routeId===$)?.accountIdentity;if(!z||!this.#Q)return{miss:"unreachable"};let X=this.#Q.source.lookup(Z.provider,z,(this.#$.now??Date.now)()),G=X.reading&&Z.normalize(X.reading.entry,X.reading.context);if(X.miss)return{miss:X.miss,...G!==void 0&&{reading:G}};return G===void 0?{miss:"unreachable"}:{reading:G}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute($,Z){let J=await this.lookupInsulaQuotaForRoute($);if(J.miss==="cold"||J.miss==="upstream-failed"){if(this.#j.get($)!==J.miss)this.#j.set($,J.miss),this.#Z.warn("skipped insula provider poll",{reason:J.miss});return}return this.#j.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.#X?.close(),this.#X=void 0,this.#C(),this.#Q?.release(),this.#Q=void 0,new I("not-active","Claustrum scoped custody is not active");let z=Y0(this.#$.rosterPath,await e(this.#$.rosterPath));this.#K(Z);let X=J.rows.find((H)=>H.routeId===$),G=z?.rows.find((H)=>H.routeId===$);if(G&&!G.enabled){if(X)this.#X?.forget(X.credentialId);throw new I("route-declined","Claustrum route is disabled")}if(!X||!G||G.state!=="active"||G.credentialId!==X.credentialId||G.accountIdentity!==X.accountIdentity||G.credentialType!==X.credentialType){if(X)this.#X?.forget(X.credentialId);throw new I("route-unavailable","Claustrum route is disabled, removed or changed")}let Q=await this.#D(this.#L(),Z),W=V3([this.#z.signal,...Z?[Z]:[]]);try{return await Q.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},W.signal,$)}finally{W.dispose()}}async reportFailure($,Z,J){if(this.#K(),!this.#X)throw new I("no-receipt","Claustrum dispatch receipt has no active owner");await this.#X.reportFailure($,Z,J)}async send($,Z,J){let z=J.signal,X=await this.authorize($,z),G=await Z(X,z);if(G.status===401&&X.fromKeptReceipt)return await this.reportFailure(X,401,J.reporterSource??"direct"),G;if(G.status===401&&!z?.aborted){let Q;try{Q=await this.authorize($,z)}catch{}if(k3(J.site,X,Q,this.#Z))await G.body?.cancel().catch(()=>{}),X=Q,G=await Z(Q,z)}if(G.status===401)await this.reportFailure(X,401,J.reporterSource??"direct").catch((Q)=>this.#$.onError?.(Q)),Promise.resolve().then(()=>this.refresh()).catch((Q)=>{if(!this.#z.signal.aborted)this.#$.onError?.(Q)});return G}async decline($){this.#K(),await h3(this.#$.rosterPath,$),this.#J=Y0(this.#$.rosterPath,await e(this.#$.rosterPath)),this.#X?.retain(this.#J?.rows??[])}async accept($){this.#K(),await m3(this.#$.rosterPath,$),this.#J=Y0(this.#$.rosterPath,await e(this.#$.rosterPath))}async recordQuota($,Z,J){return this.#K(),w3(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(),u3(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.#X?.close(),this.#Q?.release(),this.#Q=void 0,this.#J=void 0,this.#Y=void 0,this.#M(),c3(this.#$.rosterPath)}async dispose(){this.close(),await this.#M()}}var s0={opencode:o7,pi:t7};function a3($,Z){let{tokenPath:J}=e7($,Z);return{stateDir:r7(J),host:$,override:J}}function s3($,Z){return $8($==="pi"?Z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0,$==="pi"?{...Z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:Z)}class W1 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 n3($){return["auth","grant","--principal",`enrolled:${s0[$]}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"]}async function l$($,Z){try{if(await Z.processFence(),(await Z.runner.run(Z.ckBinary??"ck",n3($),{env:Z.env})).exitCode!==0)throw new W1("permission-refused")}catch{throw new W1("permission-refused")}}import{createHash as W8}from"node:crypto";import{lstat as H8,mkdir as Y8,readFile as J9}from"node:fs/promises";import{dirname as U8}from"node:path";import{assertHostsStopped as q8,canonicalPath as r3,createNativeAccountRuntime as K8,custodyTombstoneOAuth as j8,inspectNativeHostAuthEntry as z9,NativeMigrationError as T0,nativePoolHoldsAccountData as V8,prepareNativeMigration as M8,readNativeEnrollmentMode as X9,readNativeMigrationJournal as F8,releaseNativeMigrationPreflight as B8,requireNoSupervisedAuthContentSnapshot as D8,runNativeMigration as L8,writeNativeHostAuth as N8}from"@cortexkit/anthropic-auth-core";import{dirname as Z8,join as a$,resolve as i3}from"node:path";import{ACCOUNT_FILE_NAME as s$,ACCOUNT_STATE_FILE_NAME as J8,canonicalPath as n$,getStickyRoutingStatePath as z8,resolveLocalRoutingDestination as X8,resolveNativePoolPaths as G8}from"@cortexkit/anthropic-auth-core";async function U0($,Z){let J=$==="pi"?o$(Z):i$(Z),z=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),X=i3(z||a$(J,s$)),G=i3(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(X.endsWith(s$)?a$(Z8(X),J8):`${X}.state.json`)),Q=await G8(X,G),W=$==="pi"?Z.PI_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim();return{host:$,paths:Q,legacyConfigPath:X,legacyStatePath:G,hostAuthPath:$==="pi"?t$(Z):r$(Z),routingSourcePath:i3(W||z8(X)),routingDestinationPath:X8($,Q,Z)}}async function e$($){let Z=new Map;for(let J of $){let z=new Set;for(let[X,G]of[J.paths.legacyConfig,J.paths.legacyState,J.paths.config,J.paths.state,J.paths.runtime,J.paths.roster,J.paths.journal,J.hostAuthPath,J.routingSourcePath,J.routingDestinationPath].entries()){let Q=await n$(G);if(z.has(Q)&&!(X===9&&Q===await n$(J.routingSourcePath)))throw Error("Native setup storage paths overlap");let W=Z.get(Q);if(W!==void 0&&W!==J.host)throw Error("Native setup storage paths overlap between selected hosts");Z.set(Q,J.host),z.add(Q)}}}import{types as Q8}from"node:util";var $9=new WeakMap;function Z9($){return typeof $==="object"&&$!==null?$9.get($):void 0}function x1($){if(!$||typeof $!=="object"||Q8.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",$9.set(this,$)}}var o3="OpenCode's separate Anthropic login is not used. Add that account through /claude Accounts if needed, or remove the separate login from OpenCode.";function G9($){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 t3($,Z){let J=[];for(let z of $)if(await X9(z,Z)!=="local")J.push(G9(z));if(J.length)throw new a(J.join(`
|
|
12
|
-
`))}function E0($,Z){return async()=>{
|
|
5
|
+
`,"utf8"),await G.chmod(384),J.durable)try{await G.sync()}catch(W){throw new I1(W)}if(await G.close(),G=void 0,await J.beforeRename?.(),await o4(X,$),Q=!1,z?.(),J.durable){let W=await r2(o2($),"r");try{await W.sync()}catch(H){throw new I1(H)}finally{await W.close()}}}finally{if(await G?.close().catch(()=>{}),Q)await t4(X,{force:!0}).catch(()=>{})}}var e4=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 _1}from"node:crypto";import{mkdir as e2,open as G$,readFile as $$,rename as Z$,rm as A1,stat as J$}from"node:fs/promises";import{dirname as B3,join as z$}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 X=await H0({path:$,name:Z.name,ttlMs:Z.ttlMs,renew:Z.renew??!1,...Z.onStep?{onStep:Z.onStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}});if(X)try{return Z.signal?.throwIfAborted(),await J(X)}finally{await X.release()}let G=Z.timeoutMs-(performance.now()-z);if(G<=0)throw new I0({target:$,name:Z.name,timeoutMs:Z.timeoutMs});await new Promise((Q)=>setTimeout(Q,Math.min(25,Math.ceil(G))))}}async function X$($,Z){let J=await G$($,"wx",384);try{await J.writeFile(Z,"utf8")}finally{await J.close()}}var $7=globalThis.setTimeout.bind(globalThis),Z7=globalThis.clearTimeout.bind(globalThis);function Q$($){let Z=$?.code;return Z==="ENOENT"||!_&&(Z==="EINVAL"||Z==="ENOTDIR")}function H0($){return J7({...$,now:Date.now})}async function J7($){let Z=M3($.path,$.name),J=z$(Z,"owner.json"),z=_1(),X=$.now??Date.now,G=null,Q=!1,W=!1,H,U,q=new Promise((M)=>{U=M});function K(M){try{let L=$.onRenewalTimer?.(M);if(L&&(typeof L==="object"||typeof L==="function")&&"then"in L&&typeof L.then==="function")Promise.resolve(L).catch(()=>{})}catch{}}function F(){if(!G)return;Z7(G),G=null,K("cancelled")}function B(M,L){if(H||Q)return;H=Object.freeze({reason:M,expectedOwnerId:z,...typeof L?.ownerId==="string"?{observedOwnerId:L.ownerId}:{},...typeof L?.expiresAt==="number"?{observedExpiresAt:L.expiresAt}:{}}),F(),U(H)}let P,C=null,D=`${Z}.evicting`,R=z$(D,"owner.json"),S=_1(),y=5000,N=8;async function Y(){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 $$(Z,"utf8"))}catch(M){if(M.code!=="EISDIR")throw M;return JSON.parse(await $$(J,"utf8"))}}async function j(){if(_){let x=await Y(),w=Number(x?.expiresAt)-X();await h0(Z,`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
6
|
+
`,{deadline:performance.now()+Math.max(0,w),beforeRename:async()=>{let B1=await Y();if(B1?.ownerId!==z||!(Number(B1?.expiresAt)>X())||!await v())throw new _0({target:$.path,name:$.name})}});return}let M=`${Z}.${_1()}.tmp`,L,O=!1;try{L=await G$(M,"wx",384),O=!0,await L.writeFile(`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
7
|
+
`,"utf8"),await L.chmod(384),await L.close(),L=void 0;let x=await Y();if(x?.ownerId!==z||!(Number(x?.expiresAt)>X())||!await v())throw new _0({target:$.path,name:$.name});await Z$(M,Z),O=!1}finally{if(await L?.close().catch(()=>{}),O)await A1(M,{force:!0}).catch(()=>{})}}async function V(){let M=`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
8
|
+
`;if(_)await v0(Z,M);else await X$(Z,M)}async function b(M){let L=M.code;if(L==="EEXIST"){if(_)await Y();return!0}if(L==="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 V(),!0}catch(M){let L=M.code;if(await b(M))return!1;if(L==="ENOENT"){if(_)await J0(B3(Z));else await e2(B3(Z),{recursive:!0});try{return await V(),!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 L;try{L=await Y()}catch(x){if(_&&x.code!=="ENOENT")throw x}let O=Number(L?.expiresAt);if(Number.isFinite(O)&&O>X())return{status:"live"};if(typeof L?.ownerId==="string"&&Number.isFinite(O))return{status:"stale",identity:{kind:"owner",ownerId:L.ownerId,expiresAt:O}};try{let x=await J$(Z),w=Number.isFinite(O)?O:x.mtimeMs+$.ttlMs;if(w>X())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,L){if(L.status!=="stale")return!1;let O=L.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 v(){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",()=>A1(M,{recursive:!0,force:!0}));else await A1(M,{recursive:!0,force:!0}).catch(()=>{})}async function o(){if(await v())await c(D)}async function M1(){if(_)await p2(D);else await e2(D);try{let M=`${JSON.stringify({ownerId:S,createdAt:X()})}
|
|
9
|
+
`;if(_)await v0(R,M);else await X$(R,M)}catch(M){if(Q$(M))return!1;throw await o(),M}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function x0(){let M;try{M=await J$(D)}catch(O){if(O.code==="ENOENT")return"missing";throw O}if(_)await p(D,"directory",!0);if(M.mtimeMs+y>X())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let L=`${D}.${_1()}`;try{await Z$(D,L)}catch(O){if(O.code==="ENOENT")return"missing";throw O}if($.onStep)await $.onStep("stale-marker-claimed");return await c(L),"recovered"}async function F1(M){try{if(!await M1())return!1}catch(L){if(L.code==="EEXIST"){if(_){await p(D,"directory",!0);try{await t(R,!0)}catch(O){if(O.code!=="ENOENT")throw O}}return!1}throw L}try{await M()}finally{await o()}return!0}async function T(){for(let M=0;M<N;M++){if($.onStep)await $.onStep("relinquish-read");let L;try{L=await Y()}catch(O){if(_)throw O;return}if(L?.ownerId!==z)return;try{await A1(Z,{recursive:!0,force:!0});return}catch(O){if(_)throw O;await k()}}}function G0(){if(!$.renew||Q||H)return;let M=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=$7(()=>{G=null;let L=(async()=>{let O=!Q;try{if(!await F1(async()=>{let w=await Y(),B1=X();if(Q||H){O=!1;return}if(w?.ownerId!==z){B("taken-over",w),O=!1;return}if(!(Number(w?.expiresAt)>B1)){B("expired",w),O=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(Q||H){O=!1;return}if(!await v())return;if($.onStep)await $.onStep("renewal-write-fenced");if(Q||H){O=!1;return}if(!await v())return;if($.onStep)await $.onStep("renewal-write-ready");if(Q||H){O=!1;return}if(await j(),$.onStep)await $.onStep("renewal-write-finished");if(!await v()){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 Y();if(w?.ownerId!==z)B("taken-over",w);else if(!(Number(w?.expiresAt)>X()))B("expired",w)}catch{B("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(O&&!Q&&!H)G0()}})();C=L,L.finally(()=>{if(C===L)C=null})},M),"unref"in G)G.unref();K("scheduled")}function T2(){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<N;M++){if(C0=await g(),C0)break;let L=await m();if(L.status==="live")return T2();if(L.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await M1()){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 T2();if(!n(L.identity,O))continue;if(!await v())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await v())return null;let x=await m(!1);if(!n(L.identity,x))continue;if(await c(Z),!await v())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 v())return await T(),C0=!1,null;break}finally{await o()}}if(!C0)return null;return G0(),{ownerId:z,whenLost:()=>q,hasLost:()=>H!==void 0,assertOwned:async()=>{if(P)throw P;let M;try{let L=await Y();if(M=L,!Q&&!H&&L?.ownerId===z&&Number(L?.expiresAt)>X())return;B(L?.ownerId!==z?"taken-over":"expired",L)}catch(L){if(B("unreadable"),_&&L instanceof u)throw L}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<N;M++){try{let L=!1;if(await F1(async()=>{let x;try{x=await Y()}catch(w){if(_&&w.code==="ENOENT"){L=!0;return}throw w}if(x?.ownerId!==z){L=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await v())return;await c(Z),L=!0})){if(_&&!L)throw new u(Z,"release-not-confirmed",{code:"EIO"});W=L;return}await x0()}catch(L){if(_)throw L;return}await k()}if(_)throw new u(Z,"release-not-confirmed",{code:"ETIMEDOUT"})}}}var V7=1,S1=16384,K$=30000,C3=/^[0-9a-f]{64}$/,j$="unknown_method",V$=new Set([j$,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),M$=new Set(["pending_queue_full"]);function N3($){if(!($ instanceof K7))return;if(V$.has($.code))return{code:$.code,disposition:"terminal"};if(M$.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function F$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function R1($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function B$($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function z1(){return new I("invalid-state","invalid Claustrum enrollment state")}function P3($){if(!F$($)||$.version!==V7||typeof $.proposedName!=="string"||$.proposedName.length===0)throw z1();if($.phase==="pending"){if(!C3.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!R1($.createdAt)||!R1($.updatedAt))throw z1();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)||!B$($.tokenGeneration)||!R1($.updatedAt))throw z1();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"||!R1($.updatedAt))throw z1();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw z1()}function O3($){if(!F$($)||!C3.test(String($.token??""))||!B$($.token_generation))throw new I("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function M7($){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 H$($){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)>S1)throw new I("unsafe-file","Claustrum enrollment file is too large");return H$(J)}catch(J){if(J.code==="ENOENT")return;throw J}let Z;try{Z=await U$($,W$.O_RDONLY|W$.O_NOFOLLOW)}catch(J){if(J.code==="ENOENT")return;throw new I("unsafe-file","Claustrum enrollment file could not be opened safely")}try{M7(await Z.stat());let J=Buffer.alloc(S1+1),{bytesRead:z}=await Z.read(J,0,J.byteLength,0);if(z>S1)throw new I("unsafe-file","Claustrum enrollment file is too large");return H$(J.subarray(0,z).toString("utf8"))}finally{await Z.close()}}function Y$($,Z){let J=[];for(let z of $.split(`
|
|
10
|
+
`)){if(z.trim()===""||z.startsWith("#"))continue;let X=z.split(":");if(X.length!==Z||!/^[^\s:,]+$/.test(X[0]??"")||!/^\d+$/.test(X[2]??"")||!Number.isSafeInteger(Number(X[2]))||Z===7&&(!/^\d+$/.test(X[3]??"")||!Number.isSafeInteger(Number(X[3])))||Z===4&&X[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(X[3]??""))return;J.push(X)}return J}async function F7($,Z,J){try{let[z,X]=await Promise.all([D3(J.passwdPath??"/etc/passwd","utf8"),D3(J.groupPath??"/etc/group","utf8")]),G=Y$(z,7),Q=Y$(X,4);if(!G||!Q)return!1;let W=G.filter((K)=>Number(K[2])===$),H=Q.filter((K)=>Number(K[2])===Z);if(W.length!==1||H.length!==1)return!1;let U=W[0]?.[0],q=H[0]?.[3]??"";return(q===""||q.split(",").every((K)=>K===U))&&!G.some((K)=>Number(K[2])!==$&&Number(K[3])===Z)}catch{return!1}}function D$($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>D3(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function N$($,Z={}){if(!_){let J=process.geteuid?.();if(J===void 0)return;let z=process.getegid?.(),X;try{X=await H7($)}catch{return}let G;for(;;){let Q=await q$(X).catch(()=>{return});if(Q&&(Q.mode&18)!==0&&(Q.mode&512)===0){if(G===void 0)G=z!==void 0&&await F7(J,z,Z);if((Q.mode&2)!==0||Q.uid!==J||Q.gid!==z||!G)throw new I("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${X}. Another user could replace it. Run: chmod g-w,o-w ${X}`)}let W=R0(X);if(W===X)return;X=W}}try{await Q0($,D$(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 b1($,Z={}){if(_){await J0($,!1,D$(Z));return}await W7($,{recursive:!0,mode:448});let J=await q$($),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 Q7($,448)}async function A0($,Z,J={}){let z=R0($);await b1(z,J),await N$(z,J);let X=`${JSON.stringify(Z)}
|
|
11
|
+
`;if(Buffer.byteLength(X)>S1)throw new I("invalid-state","Claustrum enrollment state is too large");if(_)return h0($,X);let G=q7(z,`.${U7($)}.${process.pid}.${G7()}.tmp`),Q,W=!1;try{Q=await U$(G,"wx",384),W=!0,await Q.writeFile(X,"utf8"),await Q.chmod(384),await Q.sync(),await Q.close(),Q=void 0,await Y7(G,$),W=!1}finally{if(await Q?.close().catch(()=>{}),W)await L3(G).catch(()=>{})}}async function I3($,Z){let J=await S0($.tokenPath),z=J===void 0?void 0:O3(J),X=await S0($.statePath),G=X===void 0?void 0:P3(X);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 F0(G)}async function B0($){let Z=await S0($);if(Z===void 0)throw new I("not-enrolled","Claustrum enrollment is not configured");return O3(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 L$(){return new I("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class _3{#$;#z;#Z;#X;#H;#G;#J;constructor($){this.#J=$.ancestorOptions??{},this.#$=$.client,this.#z=$.paths,this.#Z=$.proposedName,this.#X=$.now??Date.now,this.#H=$.mintSecret??(()=>X7(32).toString("hex")),this.#G=$.writeTokenFile??j7}async status(){return I3(this.#z,this.#Z)}async resetTerminal(){return C$(this.#z,this.#Z)}async#Y($,Z){let J={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#X()};return await A0(this.#z.statePath,J,this.#J),F0(J)}async reconcile(){await b1(R0(this.#z.statePath),this.#J);let $=await H0({name:"ceremony",path:this.#z.statePath,ttlMs:K$,renew:!0});if(!$)return{state:"busy"};try{let Z=await S0(this.#z.tokenPath),J=Z===void 0?void 0:O3(Z),z=await S0(this.#z.statePath),X=z===void 0?void 0:P3(z);if(X&&X.proposedName!==this.#Z)throw L$();if(J){if(!X||X.phase==="pending"){let Q={version:1,phase:"approved",proposedName:X?.proposedName??this.#Z,tokenGeneration:J.token_generation,updatedAt:this.#X()};await A0(this.#z.statePath,Q,this.#J),X=Q}return{state:"approved",proposedName:X.proposedName,...X.phase==="approved"&&X.approvedName!==void 0&&{approvedName:X.approvedName},tokenGeneration:J.token_generation}}if(X?.phase==="approved"){let Q={version:1,phase:"blocked",proposedName:X.proposedName,errorCode:"missing_token",updatedAt:this.#X()};return await A0(this.#z.statePath,Q,this.#J),F0(Q)}if(X&&X.phase!=="pending")return F0(X);if(!X){let Q=this.#X();if(X={version:1,phase:"pending",proposedName:this.#Z,requestSecret:this.#H(),createdAt:Q,updatedAt:Q},!C3.test(X.requestSecret))throw new I("invalid-state","invalid minted Claustrum enrollment secret");await A0(this.#z.statePath,X,this.#J)}if(!X.requestId)try{let Q=z7("sha256").update(Buffer.from(X.requestSecret,"hex")).digest("hex"),W=await this.#$.enrollPropose({name:X.proposedName,requestSecretHash:Q});X={...X,requestId:W.requestId,updatedAt:this.#X()},await A0(this.#z.statePath,X,this.#J)}catch(Q){let W=N3(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,retryCode:W.code};if(W.code===j$)return await $.assertOwned(),await L3(this.#z.statePath).catch((H)=>{if(H.code!=="ENOENT")throw H}),{state:"unavailable",proposedName:X.proposedName,code:W.code};return this.#Y(X,W.code)}let G=X.requestId;if(!G)return F0(X);try{let Q=await this.#$.enrollPoll({requestId:G,requestSecret:X.requestSecret});if(Q.status==="pending")return F0(X);if(Q.status==="denied"){let H={version:1,phase:"denied",proposedName:X.proposedName,updatedAt:this.#X()};return await A0(this.#z.statePath,H,this.#J),F0(H)}await b1(R0(this.#z.tokenPath),this.#J),await N$(R0(this.#z.tokenPath),this.#J),await this.#G(this.#z.tokenPath,{token:Q.token,token_generation:Q.tokenGeneration});let W={version:1,phase:"approved",proposedName:X.proposedName,approvedName:Q.name,tokenGeneration:Q.tokenGeneration,updatedAt:this.#X()};return await A0(this.#z.statePath,W,this.#J),F0(W)}catch(Q){let W=N3(Q);if(!W)throw Q;if(W.disposition==="retry")return{state:"pending",proposedName:X.proposedName,requestId:G,retryCode:W.code};return this.#Y(X,W.code)}}finally{await $.release()}}}async function C$($,Z){await b1(R0($.statePath));let J=await H0({name:"ceremony",path:$.statePath,ttlMs:K$,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 X=P3(z);if(X.proposedName!==Z)throw L$();if(X.phase==="pending")return"refused-pending";return await J.assertOwned(),await L3($.statePath),"reset"}finally{await J.release()}}var A3="claustrum-tombstone:v1:";function O$($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function B7($,Z){if(Z===void 0)return"reauthorize-failed";if(Z.credentialId!==$.credentialId)return"credential-changed";if(Z.accountIdentity!==$.accountIdentity)return"account-changed";if(Z.recordVersion===$.recordVersion)return"version-unchanged";return"rotated"}var S3=O0("claustrum");function k3($,Z,J,z=S3){let X=O$(Z,J);return z.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:J?.recordVersion??null,retry:X,reason:B7(Z,J)}),X}var b3=300000,I$=60000;function R3(){return new I("invalid-material","Claustrum returned invalid credential material")}function D7($){let Z=$.trim();if(Z.startsWith("{")){let J;try{J=JSON.parse(Z)}catch{throw R3()}if(!J||typeof J!=="object")throw R3();let z=J,X=z.access_token??z.access;Z=typeof X==="string"?X:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(A3))throw R3();return Z}function N7($,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 L7($){let{grants:Z,grantTuples:J}=$;if(Z===void 0||J===void 0)return;return Object.freeze({grants:Z,tuples:Object.freeze(J.map(({selectorKind:z,selector:X,operation:G})=>Object.freeze({selectorKind:z,selector:X,operation:G})))})}class k1{#$;#z;#Z;#X;#H;#G;#J;#Y=new WeakMap;#q=new WeakMap;#W=new Map;#Q=new WeakMap;#U;#V;#j=!1;#F=new P0;#M;#K=!1;#B=-1/0;#D=2000;#N=!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.#X=$.family,this.#H=$.parseIdentity,this.#G=$.requireAssertion??!1,this.#Z=$.now??Date.now,this.#J=$.logger??S3,this.#U=$.setTimeoutImpl??setTimeout,this.#V=$.clearTimeoutImpl??clearTimeout}transportLost($){if(this.#N||this.#j)return;this.#j=!0,this.#F=$ instanceof P$?$:new P0,this.#J.warn("serving kept vault receipt",{reason:"unreachable"}),this.#O()}reachable(){if(this.#N||!this.#j)return;if(this.#j=!1,this.#M)this.#V(this.#M);this.#M=void 0,this.#D=2000;for(let $ of this.#W.values())$.since=null;(this.#J.info??S3.info)("vault receipt serving resumed",{reason:"reachable"})}#O(){if(this.#N||!this.#j||this.#M||this.#K)return;this.#M=this.#U(()=>{this.#M=void 0,this.#I(!0)},this.#D),this.#M.unref?.()}#I($=!1){if(this.#N||!this.#j||this.#K)return;if(this.#Z()-this.#B<1000){this.#O();return}this.#B=this.#Z(),this.#K=!0,this.#R().catch(()=>{if($&&this.#j)this.#D=Math.min(this.#D*2,30000)}).finally(()=>{this.#K=!1,this.#O()})}#L($){if(this.#N)throw new I("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 I("invalid-token","Invalid Claustrum enrollment token");return Z.token}async#A($,Z){this.#L(Z);let J,z;try{let X=$();J=Z?await Promise.race([X,new Promise((G,Q)=>{let W=()=>Q(Z.reason);if(Z.addEventListener("abort",W,{once:!0}),z=()=>Z.removeEventListener("abort",W),Z.aborted)W()})]):await X}catch(X){if(this.#L(Z),V0(X)==="unreachable")this.transportLost(X);else this.reachable();if(X instanceof P$)throw X;if(V0(X)==="unreachable")throw new P0;throw new I("unavailable","Claustrum scoped operation unavailable")}finally{z?.()}return this.#L(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=[],X=[],G=new Map;for(let H of Z.rows){let U=N7(H,this.#X);if(!U)continue;X.push({row:H,type:U}),G.set(H.id,(G.get(H.id)??0)+1)}let Q=[];for(let{row:H,type:U}of X){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}Q.push(Object.freeze({credentialId:H.id,credentialType:U,...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=L7(Z);return{view:Z.view,credentials:Object.freeze(Q),skipped:Object.freeze(z),...W&&{grantReach:W}}}listFailed($){if(V0($)==="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 X=Z.get(J);if(!X?.enabled||X.state!=="active"||X.credentialType!==z.attempt.credentialType||X.accountIdentity!==z.attempt.expectedAccountIdentity)this.forget(J)}}keptReceiptState(){let $=null;for(let[Z,J]of this.#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()>I$}async authorize($,Z,J="vault"){this.#L(Z);let{credentialId:z,credentialType:X,accountIdentity:G}=$,Q=this.#W.get(z);if(Q&&(Q.attempt.credentialType!==X||Q.attempt.expectedAccountIdentity!==G))this.forget(z),Q=void 0;let W;try{W=await this.#_(Z)}catch(H){throw this.#W.clear(),H}if(this.#j&&Q)return this.#I(),this.#b(z,Q,W,J);try{let H=await this.#k({credentialId:z,credentialType:X,accountIdentity:G},W,Z);return this.#W.set(z,{attempt:H,routeId:J,since:null}),H}catch(H){if(this.#L(Z),V0(H)!=="unreachable")throw this.forget(z),H;return this.#b(z,Q,W,J,H)}}#b($,Z,J,z,X=this.#F){if(!Z||this.#W.get($)!==Z||!this.#S(Z.attempt))throw this.forget($),X;if(Z.since===null)Z.since=this.#Z();let G=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#Y.set(G,J),this.#Q.set(G,z),G}async#k($,Z,J){if(!$.credentialId)throw new I("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:z,credentialType:X,accountIdentity:G}=$;if(this.#G&&G===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,...X==="oauth"&&{minTtlMs:b3}}),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&&X==="oauth"||W!==null&&(!Number.isFinite(W)||W-this.#Z()<b3))throw new I("insufficient-validity","Claustrum served credential has insufficient validity");let H=D7(Q.material),U=Q.accountId?.trim()?Q.accountId:void 0;if(this.#G&&(Q.credentialId===void 0||U===void 0))throw new I("identity-unasserted","Claustrum served credential did not assert its identity");let q=U===void 0?this.#H?.(H):void 0,K=U??q;if(G!==void 0&&K!==void 0&&K!==G)throw new I("identity-changed","Claustrum served credential identity changed");let F=K??G,P=Object.freeze(Object.defineProperty({credentialId:z,credentialType:X,...F!==void 0&&{accountIdentity:F},accountIdentitySource:U!==void 0?"asserted":q!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...Q.credentialId!==void 0&&{assertedCredentialId:Q.credentialId},...U!==void 0&&{assertedAccountIdentity:U},...Q.projectId!==void 0&&{projectId:Q.projectId},recordVersion:Q.recordVersion,expiresAtMs:W},"accessToken",{value:H,enumerable:!1}));return this.#Y.set(P,Z),P}async reportFailure($,Z,J){if(Z!==401)return;this.#L();let z=this.#Y.get($);if(!z)throw new I("no-receipt","Claustrum failure report requires an original dispatch receipt");let X=this.#Q.get($);if(X!==void 0){this.forget($.credentialId),this.#J.debug("scoped 401 not reported",{routeId:X,reason:"kept-receipt"});return}let G=this.#W.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let Q=this.#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.#L();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.#U,clearTimeoutImpl:this.#V});return this.#P.add(Z),Z.start(),{get mode(){return Z.mode},close:()=>{this.#P.delete(Z),Z.stop()}}}close(){if(this.#N)return;if(this.#N=!0,this.#M)this.#V(this.#M);this.#M=void 0;for(let $ of this.#P)$.stop();this.#P.clear(),this.#W.clear(),this.#$.close()}}import{resolve as l3}from"node:path";var b0="all",C7=Object.freeze(["primary"]);function A$($){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 _$($){return typeof $==="string"&&$.length>0}function l($,Z,J){return $[Z]===void 0||J($[Z])}function P7($){return d($)&&$>0}function T3($){return typeof $==="string"}function O7($){if(!D0($)||!_$($.scope)||!_$($.label))return!1;switch($.kind){case"reading":return d($.checkedAt)&&d($.usedPercent)&&l($,"resetsAt",T3)&&l($,"windowMinutes",P7);case"retired":return d($.retiredAt);case"absent":return d($.checkedAt);default:return!1}}function I7($){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",T3)&&l($,"limit",d)&&l($,"used",d)&&l($,"remaining",d)&&l($,"unit",T3)}function R$($){return D0($)&&d($.value)&&Number.isInteger($.value)&&$.value>=0&&d($.checkedAt)}function E3($){return D0($)&&Object.values($).every(R$)}function _7($){return typeof $==="boolean"}function c0($){return D0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&l($,"balance",d)&&l($,"overageLimitReached",_7)&&d($.checkedAt)}function S$($){if(!D0($))return;let Z=Object.entries($).filter(([,J])=>R$(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 X=S$(Z),G=c0(J)?J:void 0;return{...z,...X===void 0?{}:{counters:X},...G===void 0?{}:{credits:G}}}function w0($){if(!D0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!O7(J))return!1;let z=u0(J.scope,J.label);if(Z.has(z))return!1;Z.add(z)}return l($,"budget",I7)&&l($,"counters",E3)&&l($,"credits",c0)}class T1 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function f1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function E1($){return typeof $==="number"&&Number.isFinite($)}function b$($){return $===void 0||typeof $==="string"&&$!==""}function k$($){return typeof $==="string"&&$!==""}function X1($,Z){return $[Z]===void 0||E1($[Z])}function f3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function A7($){return f1($)&&b$($.scope)&&k$($.label)&&E1($.usedPercent)&&f3($,"resetsAt")&&($.windowMinutes===void 0||E1($.windowMinutes)&&$.windowMinutes>0)}function R7($){return f1($)&&b$($.scope)&&k$($.label)}function S7($){if(!f1($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&X1($,"remainingPercent")&&X1($,"usedPercent")&&f3($,"resetsAt")&&X1($,"limit")&&X1($,"used")&&X1($,"remaining")&&f3($,"unit")}function p0($){if(!f1($)||!E1($.checkedAt))return!1;let Z=$.readings??[],J=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(J))return!1;let z=new Set;for(let X of Z){if(!A7(X))return!1;let G=u0(X.scope??b0,X.label);if(z.has(G))return!1;z.add(G)}if(!J.every(R7))return!1;return($.budget===void 0||S7($.budget))&&($.counters===void 0||E3($.counters))&&($.credits===void 0||c0($.credits))}function b7($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function k7($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function T7($,Z){let J=new Map(Object.entries($??{}));for(let[z,X]of Object.entries(Z??{})){let G=J.get(z);if(G===void 0||X.checkedAt>=G.checkedAt)J.set(z,X)}return J.size===0?void 0:Object.fromEntries(J)}function E7($,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 T1("stored quota map is malformed");if(!p0(Z))throw new T1("quota observation is malformed");let z=J??{limits:[]},X=Z.checkedAt,G=new Map;for(let D of z.limits)G.set(u0(D.scope,D.label),D);let Q=(D)=>{let R=G.get(D);return R===void 0||X>=A$(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;G.set(S,{scope:R,label:D.label,kind:"reading",checkedAt:X,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=G.get(S);G.set(S,y===void 0||y.kind==="absent"?{scope:R,label:D.label,kind:"absent",checkedAt:X}:{scope:R,label:D.label,kind:"retired",retiredAt:X})}let{limits:H,budget:U,counters:q,credits:K,...F}=z,B=k7(z.budget,Z.budget,X),P=T7(z.counters,Z.counters),C=E7(z.credits,Z.credits);return{...F,limits:[...G.values()].sort(b7),...B===void 0?{}:{budget:B},...P===void 0?{}:{counters:P},...C===void 0?{}:{credits:C}}}var f7=Object.freeze({validate:w0,decode:k0,merge:G1});import{createHash as v7}from"node:crypto";import{resolve as f$}from"node:path";function T$($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function g3($,Z,J){return $.some((z)=>T$(z,Z,J))}function x3($,Z,J){let z={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((X)=>X.credentialId!==Z||X.accountIdentity!==J),z]}function y3($,Z,J){return $.filter((z)=>!Z.some((X)=>T$(z,X,J)))}var g$="vault:";function h7($){return v7("sha256").update($).digest("hex")}function m7($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function w7($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function N0($){return[$.credentialId,...$.aliases??[]]}function x$($,Z,J={}){let z=J.now??Date.now(),X=J.routePrefix??g$,G=J.reservedRouteIds??new Set,Q=$?.rows??[],W=[...$?.declined??[]],H=Z.skipped.length===0,U=new Set(Z.credentials.map((N)=>N.credentialId)),q=new Set(Z.skipped.flatMap((N)=>N.credentialId===void 0?[]:[N.credentialId])),K=Z.skipped.some((N)=>N.credentialId===void 0),F=(N)=>!U.has(N)&&(q.has(N)||K),B=new Map;for(let N of Q){if(N.accountIdentity===void 0)continue;for(let Y of N0(N))if(!B.has(Y))B.set(Y,N.accountIdentity)}let P=new Map;for(let N of Z.credentials){let Y=N.accountIdentity!==void 0?{credential:N,identity:N.accountIdentity,claimed:!0}:{credential:N,identity:B.get(N.credentialId),claimed:!1},j=w7(Y),V=P.get(j)??[];V.push(Y),P.set(j,V)}let C=new Set,D=new Set(G),R=[],S=(N,Y)=>N.credential.credentialId.localeCompare(Y.credential.credentialId),y=[...P.values()].map((N)=>N.toSorted(S)).sort((N,Y)=>N[0]&&Y[0]?S(N[0],Y[0]):0);for(let N of y){let Y=N[0]?.identity,j=N.filter((T)=>T.credential.state==="active"),V=j.length?j:N,b=V.filter((T)=>T.claimed),g=b.length?b:V,k=new Set(N.map((T)=>T.credential.credentialId)),m=Q.find((T)=>!C.has(T)&&N0(T).some((G0)=>k.has(G0))&&(T.accountIdentity===void 0||T.accountIdentity===Y)),n=g.find((T)=>T.credential.credentialId===m?.credentialId)??g[0];if(!n)continue;let v=n.credential,c=m??(Y===void 0?void 0:Q.find((T)=>!C.has(T)&&T.accountIdentity===Y));if(c)C.add(c);let o=c?.routeId;if(!o||G.has(o)){let T=`${X}${v.credentialId}${Y===void 0?"":`~${h7(Y).slice(0,10)}`}`;o=T;for(let G0=2;D.has(o);G0++)o=`${T}~${G0}`}D.add(o);let M1=c?N0(c).filter(F):[],x0=[...new Set([...N.map((T)=>T.credential.credentialId),...M1])].filter((T)=>T!==v.credentialId).sort((T,G0)=>T.localeCompare(G0)),F1=J.mapAccount?.(v)??{};R.push({previousIndex:c?Q.indexOf(c):1/0,row:{routeId:o,credentialId:v.credentialId,credentialType:v.credentialType,...Y!==void 0&&{accountIdentity:Y},...x0.length&&{aliases:x0},state:v.state,label:F1.label?.trim()||m7(v),...v.email!==void 0&&{email:v.email},...v.orgName!==void 0&&{orgName:v.orgName},enabled:![v.credentialId,...x0].some((T)=>g3(W,T,Y)),addedAt:c?.addedAt??z,...c?.quota!==void 0&&{quota:c.quota},...!n.claimed&&Y!==void 0&&{unclaimed:!0}}})}return Q.forEach((N,Y)=>{if(C.has(N)||!N0(N).some(F))return;if(D.has(N.routeId))return;let[j,...V]=N0(N).filter((k)=>!U.has(k));if(j===void 0)return;D.add(N.routeId);let{aliases:b,...g}=N;R.push({previousIndex:Y,row:{...g,credentialId:j,...V.length&&{aliases:V},stale:!0}})}),R.sort((N,Y)=>N.previousIndex===Y.previousIndex?N.row.credentialId.localeCompare(Y.row.credentialId):N.previousIndex-Y.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 v3($){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 Q1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function d0($){return $===void 0||typeof $==="string"}function u7($){let Z=Q1($)?k0($.quota):void 0;if(!Q1($)||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 c7=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function E$($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!Q1(J)||!d0(J.credentialId)||typeof J.reason!=="string"||!c7.has(J.reason))return;Z.push(J)}return Z}function p7($){if(!Q1($)||$.version!==1||!d0($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!E$($.rejected))throw new I("invalid-state","Claustrum roster file is not valid");let Z=[];for(let X of $.rows){let G=u7(X);if(!G)throw new I("invalid-state","Claustrum roster file is not valid");Z.push(G)}let J=[];for(let X of $.declined){if(!Q1(X)||typeof X.credentialId!=="string"||!d0(X.accountIdentity))throw new I("invalid-state","Claustrum roster file is not valid");J.push(X)}let z=E$($.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 p7(J)}var d7={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},l7={name:"claustrum-roster",ttlMs:30000};async function l0($,Z,J={}){return F3($,{...d7,signal:J.signal},async(z)=>{let X=await e($),{next:G,result:Q}=await Z(X,{assertOwned:()=>z.assertOwned()});if(G)await z.assertOwned(),await J1($,G,{beforeRename:async()=>{await J.beforePublish?.(),J.signal?.throwIfAborted(),await z.assertOwned()}});return Q})}function h3($,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");let X=x3(J.declined,z.credentialId,z.accountIdentity);return{next:{...J,declined:X,rows:J.rows.map((G)=>G===z?{...G,enabled:!1}:G)},result:void 0}})}function m3($,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");return{next:{...J,declined:y3(J.declined,N0(z),z.accountIdentity),rows:J.rows.map((X)=>X===z?{...X,enabled:!0}:X)},result:void 0}})}function a7($,Z){if(!N0($).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")&&N0($).length===1)return"bind";return"refuse"}async function w3($,Z){let{routeId:J,observation:z,...X}=Z;return y$($,{routeId:J,observation:z,accountIdentity:X.accountIdentity,receipt:X})}async function y$($,Z){if(!p0(Z.observation))return!1;let J=Y0($,await e($));if(!L0(J,Z).kept)return!1;return v$($,Z)}function u3($,Z){return y$($,Z)}function L0($,Z){let J=$?.rows.find((Q)=>Q.routeId===Z.routeId),z=!J?"refuse":Z.receipt?a7(J,Z.receipt):J.accountIdentity!==void 0&&J.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!J||z==="refuse")return{roster:$,kept:!1};let X=G1(J.quota,Z.observation),G=z==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{roster:{...$,rows:$.rows.map((Q)=>Q===J?{...Q,...G,quota:X}:Q)},kept:!0}}var g1=new Map;function c3($){g1.delete(f$($))}async function p3($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){c3($.path);return}let J=await H0({...l7,path:$.path,renew:!0});if(!J){let G=await e($.path);if($.signal?.throwIfAborted(),!G?.view)throw new I("roster-busy","Claustrum account discovery is already in progress");return G}let z=f$($.path),X;try{let G=await e($.path),Q=g1.get(z);X=Q&&(Q.previousView===G?.view||Q.inventory.view===G?.view)?Q:{inventory:await $.custody.discover($.signal),previousView:G?.view},g1.delete(z);let{inventory:W}=X;return $.onInventory?.(W),$.signal?.throwIfAborted(),await l0($.path,async(H)=>{if(!await Z())return{result:void 0};$.signal?.throwIfAborted(),await J.assertOwned();let U=typeof $.projection==="function"?$.projection():$.projection,q=x$(H,W,U);return{...JSON.stringify(H)!==JSON.stringify(q)&&{next:q},result:q}},{beforePublish:async()=>{$.signal?.throwIfAborted(),await J.assertOwned()}})}catch(G){if(G instanceof I0&&X&&!$.signal?.aborted&&await Z())g1.set(z,X);throw G}finally{await J.release()}}var a0=new Map,s7=O0("claustrum"),h$=100;function m$($){let Z=l3($),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 w$($,Z){let J=m$($);J.listeners.add(Z);let z;return()=>z??=(()=>{return J.listeners.delete(Z),J.listeners.size?Promise.resolve():d3($)})()}function n7($){let Z=new Map,{observation:J}=$,z=JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]),X=(W,H,U)=>Z.set(`${z}:${W}`,{at:H,order:0,publication:{...$,observation:U}}),G=(W,H)=>JSON.stringify([W??"all",H]),Q=new Set;for(let W of J.readings??[]){let H=G(W.scope,W.label);Q.add(H),X(H,J.checkedAt,{checkedAt:J.checkedAt,readings:[{...W}]})}for(let W of J.coverage??[]){let H=G(W.scope,W.label);if(!Q.has(H))X(H,J.checkedAt,{checkedAt:J.checkedAt,coverage:[{...W}]})}if(J.budget)X("budget",J.checkedAt,{checkedAt:J.checkedAt,budget:{...J.budget}});for(let[W,H]of Object.entries(J.counters??{}))X(`counter:${W}`,H.checkedAt,{checkedAt:J.checkedAt,counters:{[W]:{...H}}});if(J.credits)X("credits",J.credits.checkedAt,{checkedAt:J.checkedAt,credits:{...J.credits}});if(!Z.size)X("empty",J.checkedAt,{checkedAt:J.checkedAt});return Z}function v$($,Z){if(!p0(Z.observation))return Promise.resolve(!1);let J=m$($),z=JSON.stringify([Z.accountIdentity??null,Z.accountIdentity===void 0?Z.routeId:null]),X=J.pending.get(z)??new Map;for(let[G,Q]of n7(Z)){let W=X.get(G);if(!W||Q.at>=W.at){if(Q.order=++J.order,Q.publication.observation.coverage)Q.priorReading=W?.publication.observation.readings?W.publication:W?.priorReading;X.set(G,Q)}}if(X.size)J.pending.set(z,X);for(let G of J.listeners)G(Z);return c$(J,h$),Promise.resolve(!0)}function u$($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,J)=>Z.order-J.order)}function Y0($,Z){let J=a0.get(l3($));if(J)for(let z of u$(J.pending)){if(z.priorReading)Z=L0(Z,z.priorReading).roster;Z=L0(Z,z.publication).roster}return Z}function c$($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;if($.timer=setTimeout(()=>{$.timer=void 0,p$($)},Z),!$.draining)$.timer.unref?.()}function p$($){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 X of u$(Z)){if(X.priorReading)z=L0(z,X.priorReading).roster;z=L0(z,X.publication).roster}return{...z!==J&&{next:z},result:void 0}},{signal:$.abort.signal});for(let[J,z]of Z){let X=$.pending.get(J);for(let[G,Q]of z)if(X?.get(G)===Q)X.delete(G);if(!X?.size)$.pending.delete(J)}$.failures=0}catch(J){if(!$.abort.signal.aborted&&$.failures++===0)s7.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()):h$;c$($,J)}})()}async function d3($,Z=1000){let J=l3($),z=a0.get(J);if(!z)return;z.draining=!0,clearTimeout(z.timer),z.timer=void 0;let X,G,Q=new Promise((W)=>{G=()=>{if(!z.pending.size||z.abort.signal.aborted)W()},z.wake.add(G),G()});try{if(z.pending.size)p$(z);await Promise.race([Q,new Promise((W)=>{X=setTimeout(W,Math.max(0,Z))})])}finally{if(clearTimeout(X),G)z.wake.delete(G);if(z.draining=!1,!z.listeners.size){if(z.abort.abort(),clearTimeout(z.timer),z.pending.clear(),a0.get(J)===z)a0.delete(J)}}}class d${#$;#z=new AbortController;#Z;#X;#H;#G;#J;#Y;#q;#W=!1;#Q;#U;#V;#j=new Map;#F;#M;constructor($){this.#$=$,this.#Z=$.logger??O0("claustrum"),this.#M=w$($.rosterPath,(Z)=>{this.#J=L0(this.#J,Z).roster})}#K($){this.#z.signal.throwIfAborted(),$?.throwIfAborted()}async#B(){return await this.#$.isCustodyActive?.()??!0}#D($,Z){let J=V3([this.#z.signal,...Z?[Z]:[]]);return new Promise((z,X)=>{let G=()=>{J.signal.removeEventListener("abort",Q),J.dispose()},Q=()=>{G(),X(J.signal.reason)};if(J.signal.addEventListener("abort",Q,{once:!0}),$.then((W)=>{if(G(),J.signal.aborted)X(J.signal.reason);else z(W)},(W)=>{G(),X(W)}),J.signal.aborted)Q()})}async#N(){if(this.#K(),this.#X)return this.#X;if(!this.#H)this.#H=this.#$.connect().then(($)=>{if(this.#z.signal.aborted)$.close(),this.#K();if(this.#X=new k1({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.#X}).finally(()=>{this.#H=void 0});return this.#D(this.#H)}snapshot(){return this.#J}grantReach(){let $=this.#Y;return $&&this.#J?.view===$.view?$.reach:void 0}watchState(){return Object.freeze({vault:this.#U?.mode??"polling",...this.#$.insula&&{insula:this.#Q?.source.watchMode()??"polling"}})}#C(){this.#U?.close(),this.#U=void 0,this.#V?.(),this.#V=void 0}keptReceiptState(){return this.#X?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return v3(this.#J)}refresh(){if(this.#K(),this.#G)return this.#G;return this.#G=(async()=>{if(!await this.#B()){this.#J=void 0,this.#Y=void 0,this.#C(),this.#X?.close(),this.#X=void 0,this.#Q?.release(),this.#Q=void 0;return}let $=await this.#N(),Z,J=await p3({path:this.#$.rosterPath,custody:$,onInventory:(X)=>{Z=X},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=Y0(this.#$.rosterPath,J),$.retain(J?.rows??[]),Z&&J?.view!==void 0)this.#Y=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.#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.#U?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#F===void 0||$-this.#F>=G3)return!0;return!await this.#B()}#O(){let $=this.#X;if(this.#z.signal.aborted||!$)return;if(this.#U??=$.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.#Q&&!this.#V)this.#V=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.#N(),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=Y0(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=Y0(this.#$.rosterPath,await e(this.#$.rosterPath))?.rows.find((Q)=>Q.routeId===$)?.accountIdentity;if(!z||!this.#Q)return{miss:"unreachable"};let X=this.#Q.source.lookup(Z.provider,z,(this.#$.now??Date.now)()),G=X.reading&&Z.normalize(X.reading.entry,X.reading.context);if(X.miss)return{miss:X.miss,...G!==void 0&&{reading:G}};return G===void 0?{miss:"unreachable"}:{reading:G}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute($,Z){let J=await this.lookupInsulaQuotaForRoute($);if(J.miss==="cold"||J.miss==="upstream-failed"){if(this.#j.get($)!==J.miss)this.#j.set($,J.miss),this.#Z.warn("skipped insula provider poll",{reason:J.miss});return}return this.#j.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.#X?.close(),this.#X=void 0,this.#C(),this.#Q?.release(),this.#Q=void 0,new I("not-active","Claustrum scoped custody is not active");let z=Y0(this.#$.rosterPath,await e(this.#$.rosterPath));this.#K(Z);let X=J.rows.find((H)=>H.routeId===$),G=z?.rows.find((H)=>H.routeId===$);if(G&&!G.enabled){if(X)this.#X?.forget(X.credentialId);throw new I("route-declined","Claustrum route is disabled")}if(!X||!G||G.state!=="active"||G.credentialId!==X.credentialId||G.accountIdentity!==X.accountIdentity||G.credentialType!==X.credentialType){if(X)this.#X?.forget(X.credentialId);throw new I("route-unavailable","Claustrum route is disabled, removed or changed")}let Q=await this.#D(this.#N(),Z),W=V3([this.#z.signal,...Z?[Z]:[]]);try{return await Q.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},W.signal,$)}finally{W.dispose()}}async reportFailure($,Z,J){if(this.#K(),!this.#X)throw new I("no-receipt","Claustrum dispatch receipt has no active owner");await this.#X.reportFailure($,Z,J)}async send($,Z,J){let z=J.signal,X=await this.authorize($,z),G=await Z(X,z);if(G.status===401&&X.fromKeptReceipt)return await this.reportFailure(X,401,J.reporterSource??"direct"),G;if(G.status===401&&!z?.aborted){let Q;try{Q=await this.authorize($,z)}catch{}if(k3(J.site,X,Q,this.#Z))await G.body?.cancel().catch(()=>{}),X=Q,G=await Z(Q,z)}if(G.status===401)await this.reportFailure(X,401,J.reporterSource??"direct").catch((Q)=>this.#$.onError?.(Q)),Promise.resolve().then(()=>this.refresh()).catch((Q)=>{if(!this.#z.signal.aborted)this.#$.onError?.(Q)});return G}async decline($){this.#K(),await h3(this.#$.rosterPath,$),this.#J=Y0(this.#$.rosterPath,await e(this.#$.rosterPath)),this.#X?.retain(this.#J?.rows??[])}async accept($){this.#K(),await m3(this.#$.rosterPath,$),this.#J=Y0(this.#$.rosterPath,await e(this.#$.rosterPath))}async recordQuota($,Z,J){return this.#K(),w3(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(),u3(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.#X?.close(),this.#Q?.release(),this.#Q=void 0,this.#J=void 0,this.#Y=void 0,this.#M(),c3(this.#$.rosterPath)}async dispose(){this.close(),await this.#M()}}var s0={opencode:o7,pi:t7};function a3($,Z){let{tokenPath:J}=e7($,Z);return{stateDir:r7(J),host:$,override:J}}function s3($,Z){return $8($==="pi"?Z.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0,$==="pi"?{...Z,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:Z)}class W1 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 n3($){return["auth","grant","--principal",`enrolled:${s0[$]}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"]}async function l$($,Z){try{if(await Z.processFence(),(await Z.runner.run(Z.ckBinary??"ck",n3($),{env:Z.env})).exitCode!==0)throw new W1("permission-refused")}catch{throw new W1("permission-refused")}}import{createHash as W8}from"node:crypto";import{lstat as H8,mkdir as Y8,readFile as J9}from"node:fs/promises";import{dirname as U8}from"node:path";import{assertHostsStopped as q8,canonicalPath as r3,createNativeAccountRuntime as K8,custodyTombstoneOAuth as j8,inspectNativeHostAuthEntry as z9,NativeMigrationError as T0,nativeJournalMayAdoptLaterHostLogin as V8,nativePoolHoldsAccountData as M8,prepareNativeMigration as F8,readNativeEnrollmentMode as X9,readNativeMigrationJournal as B8,releaseNativeMigrationPreflight as D8,requireNoSupervisedAuthContentSnapshot as N8,runNativeMigration as L8,writeNativeHostAuth as C8}from"@cortexkit/anthropic-auth-core";import{dirname as Z8,join as a$,resolve as i3}from"node:path";import{ACCOUNT_FILE_NAME as s$,ACCOUNT_STATE_FILE_NAME as J8,canonicalPath as n$,getStickyRoutingStatePath as z8,resolveLocalRoutingDestination as X8,resolveNativePoolPaths as G8}from"@cortexkit/anthropic-auth-core";async function U0($,Z){let J=$==="pi"?o$(Z):i$(Z),z=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),X=i3(z||a$(J,s$)),G=i3(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(X.endsWith(s$)?a$(Z8(X),J8):`${X}.state.json`)),Q=await G8(X,G),W=$==="pi"?Z.PI_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim();return{host:$,paths:Q,legacyConfigPath:X,legacyStatePath:G,hostAuthPath:$==="pi"?t$(Z):r$(Z),routingSourcePath:i3(W||z8(X)),routingDestinationPath:X8($,Q,Z)}}async function e$($){let Z=new Map;for(let J of $){let z=new Set;for(let[X,G]of[J.paths.legacyConfig,J.paths.legacyState,J.paths.config,J.paths.state,J.paths.runtime,J.paths.roster,J.paths.journal,J.hostAuthPath,J.routingSourcePath,J.routingDestinationPath].entries()){let Q=await n$(G);if(z.has(Q)&&!(X===9&&Q===await n$(J.routingSourcePath)))throw Error("Native setup storage paths overlap");let W=Z.get(Q);if(W!==void 0&&W!==J.host)throw Error("Native setup storage paths overlap between selected hosts");Z.set(Q,J.host),z.add(Q)}}}import{types as Q8}from"node:util";var $9=new WeakMap;function Z9($){return typeof $==="object"&&$!==null?$9.get($):void 0}function x1($){if(!$||typeof $!=="object"||Q8.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",$9.set(this,$)}}var o3="OpenCode's separate Anthropic login is not used. Add that account through /claude Accounts if needed, or remove the separate login from OpenCode.";function G9($){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 t3($,Z){let J=[];for(let z of $)if(await X9(z,Z)!=="local")J.push(G9(z));if(J.length)throw new a(J.join(`
|
|
12
|
+
`))}function E0($,Z){return async()=>{N8(Z.env);try{await q8(Z.fence,Z.env)}catch(J){let z=x1(J);if(z)throw new a(z);throw J}await t3([$],Z.env)}}async function e3($){try{return W8("sha256").update(await J9($)).digest("hex")}catch(Z){if(Z.code==="ENOENT")return"absent";throw new T0("unsafe-source")}}async function H1($,Z){let J;try{J=JSON.parse(await J9(Z,"utf8"))}catch(G){if(G.code!=="ENOENT")throw new T0("unsafe-source")}let z=z9($,J),X=J?.anthropic;return{...z,realLogin:z.kind==="oauth"&&Boolean(X?.access&&X.refresh)}}async function y1($,Z){let{paths:J}=$,z=$.generation2?void 0:await H1(J.host,J.hostAuthPath),X=await Promise.all([J.paths.config,J.paths.state,J.paths.runtime,J.paths.roster,J.paths.journal,J.routingDestinationPath].map(e3));return JSON.stringify([await X9(J.host,Z),z?.digest,...X])}async function $2($,Z,J){let z=Z.paths??await U0($,Z.env),X=E0($,Z);await X();let G=await B8(z.paths);if(G&&G.host!==$)throw new T0("invalid-source");let Q=G?.phase==="committed"||G?.phase==="retired";if(G&&G.kind!=="empty-init"&&(G.hostAuthPath!==await r3(z.hostAuthPath)||G.routingPaths.source!==await r3(z.routingSourcePath)||G.routingPaths.destination!==await r3(z.routingDestinationPath)))throw new T0("invalid-source");let W={paths:z,generation2:J,action:"migration",notice:!1,fingerprint:"",authorityPhase:G?.phase??"absent",poolPopulation:"not-evaluated"};if(J){if(G&&!Q)throw new T0("invalid-source");if(W.action=G?"reuse":"empty-init",!G){let H=[z.paths.config,z.paths.state,z.paths.runtime,z.paths.roster];if(!Z.env.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE)H.push(z.routingDestinationPath);for(let U of H){try{await H8(U)}catch(q){if(q.code==="ENOENT")continue;throw new T0("unsafe-source")}throw new T0("invalid-source")}}}else{W.slot=await H1($,z.hostAuthPath);let H=V8(G,$)&&W.slot.kind==="oauth";W.poolPopulation=G?.kind==="empty-init"||H?await M8({paths:z.paths}):"not-evaluated";let U=W.poolPopulation===!0;if($==="opencode"&&(U||Q&&G?.kind!=="empty-init"&&!H&&W.slot.kind==="oauth"))W.action="skip",W.notice=W.slot.realLogin;else W.preflight=await F8({...z,env:Z.env,processFence:X,removePiAnthropicAuth:Z.removePiAnthropicAuth})}return W.fingerprint=await y1(W,Z.env),W}async function n0($,Z){await E0($.paths.host,Z)();let J=await $2($.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)D8(J.preflight)}}async function Z2($,Z){if($.paths.host!=="opencode"||$.slot?.kind!=="absent")return;let J=E0("opencode",Z);await J(),await Y8(U8($.paths.hostAuthPath),{recursive:!0,mode:448}),await C8({host:"opencode",authPath:$.paths.hostAuthPath,sourceDigest:"absent",expectedDigest:z9("opencode",{anthropic:j8("anthropic")}).digest,env:Z.env,removePiAnthropicAuth:!1,processFence:J})}async function Q9($,Z){let J={...Z.env},z=E0($,{...Z,env:J});await z();let X=Z.paths??await U0($,J),G=await Z.login?.($);if(G&&!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(G.accountIdentity))throw Error("Claude sign-in did not establish an account UUID");if(await z(),await Z.beforeCommit?.(),!Z.skipMigration)await L8({paths:X.paths,legacyConfigPath:X.legacyConfigPath,legacyStatePath:X.legacyStatePath,host:$,hostAuthPath:X.hostAuthPath,routingSourcePath:X.routingSourcePath,routingDestinationPath:X.routingDestinationPath,env:J,processFence:z,removePiAnthropicAuth:Z.removePiAnthropicAuth,preflight:Z.preflight});if(G){let Q=K8({paths:X.paths,host:$,vault:{env:J},beforePoolWrite:z});try{if((await Q.read()).mode!=="local")throw new a(G9($));await z(),await Q.loginOAuth({routeId:"main",replace:!0,...G})}finally{Q.close()}}if(Z.skipMigration){let Q=await H1($,X.hostAuthPath);await Z2({paths:X,slot:Q},Z)}}var W9={opencode:"OpenCode",pi:"Pi"};function k8($,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`${W9[Z]} has no read grant in the vault, so setup cannot see any Claude login. Run ${["ck",...n3(Z)].join(" ")}, then rerun setup.`;case"grant-reaches-nothing":return`${W9[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(k8($,Z));this.name="NativeVaultActivationError",this.code=$}}function T8($){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 z2($){try{return JSON.parse(await P8($,"utf8"))}catch(Z){if(Z.code==="ENOENT")return;throw new z0("host-auth-invalid")}}async function Y1($,Z){if($==="opencode")return"opencode";let J=Z.paths??await U0($,Z.env),z=J2($,await z2(J.hostAuthPath)),X=X2({env:Z.env,authPath:J.hostAuthPath}),{stashPath:G}=R8({env:Z.env,authPath:J.hostAuthPath});return JSON.stringify([z.digest,await X.inspect(),await e3(G)])}async function H9($){try{b8($.env)}catch{throw new z0("auth-content-refused")}try{await O8($.fence,$.env)}catch(Z){let J=x1(Z);if(J)throw new a(J);throw Z}}async function Y9($,Z){let J={...Z.env};await(()=>H9({...Z,env:J}))();let X=Z.paths??await U0($,J),G=$==="opencode"&&Z.inspectOpenCodeAuth!==!1&&J2("opencode",await z2(X.hostAuthPath)).kind==="oauth";if($==="pi"){let Q=J2("pi",await z2(X.hostAuthPath)),W=await X2({env:J,authPath:X.hostAuthPath}).inspect();if(W.slot==="placeholder"&&W.stash==="missing")throw new A8("missing-stash");if(Q.kind!=="absent"&&W.slot!=="placeholder"&&!Z.removePiAnthropicAuth)throw new z0("consent-required")}return{priorMode:await S8($,J),fingerprint:await Y1($,{...Z,env:J}),separateOpenCodeLogin:G}}async function U9($,Z,J){let z={...Z.env},X=()=>H9({...Z,env:z});await X();let G=Z.paths??await U0($,z);if(await Y1($,Z)!==J.fingerprint)throw new z0("host-auth-invalid");await l$($,{env:z,runner:Z.runner,processFence:X,ckBinary:Z.enrollment?.ckBinary});let Q=Z.discover??(()=>_8({paths:G.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},U=I8({paths:G.paths,host:$,vault:{env:z,discover:H}});try{await X(),await U.vault.refresh();let q=await U.read(),K=q.accounts.find((F)=>F.id==="main");if(q.mode!=="claustrum"||!K?.accountIdentity||K.source!=="vault"){let F=T8(W);throw F==="primary-unverified"?new z0(F):new z0(F,$)}if(await X(),$==="pi")await X2({env:z,authPath:G.hostAuthPath}).enterVault();return J.priorMode==="claustrum"?"already-vault":"committed"}finally{U.close()}}var E8=/(?:^|[/\\])(opencode|litecode|opencode2|pi)(?:\.exe)?(?=$|\s|")/i;class G2 extends Error{activeHosts;constructor($){let Z=$.map((z)=>({pid:z.pid,command:E8.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
|
|
16
|
+
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=Z,this.name="ProcessFenceViolationError"}}var a8={"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 H2=["opencode","pi"],s8=new Set(["enrolled","not-enrolled","unknown"]),B9=U1()(["auth-content-refused","host-auth-invalid","primary-conflict","consent-required","primary-unverified","no-read-grant","grant-reaches-nothing"]),D9=U1()(["enrollment-refused","enrollment-reset","approval-refused","permission-refused"]),N9=U1()(["invalid-source","unsafe-source","consent-required","primary-unverified","migration-busy","ownership-lost","retirement-refused","pool-populated","host-login-present","settings-changed"]),L9=U1()(["invalid-options","invalid-auth","invalid-stash","unsafe-path","missing-stash","conflict","lock-timeout","lock-compromised","io"]),C9=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"]),n8={name:new Set(["Error","TypeError","SyntaxError","RangeError","AggregateError","AbortError","PrivateFileError","PrivateFilesUnavailableError","DiagnosticFileError","NativeRuntimeError","NativeAuthorityError","NativeMigrationError","NativeMigrationSourceError","NativeHostAuthError","NativeHostAuthWriteError","NativePiAuthSlotError","NativeCustodyError","NativeVaultActivationError","NativeVaultEnrollmentError","SetupCommandError","HostNotEnrolledError","ProcessFenceViolationError","ProcessInspectionError","LockOwnershipError","LockContentionError","ClaustrumConsumerError","ClaustrumCredentialError"]),code:new Set([...B9,...D9,...N9,...L9,...C9,"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","native-addon-unavailable","unsafe-ancestor","wrong-kind","io-error","mode","writable-by-others"])},i8=new Set([...B9.flatMap(($)=>$==="no-read-grant"||$==="grant-reaches-nothing"?H2.map((Z)=>new z0($,Z).message):[new z0($).message]),...D9.map(($)=>new W1($).message),...N9.map(($)=>new p8($).message),...L9.map(($)=>new d8($).message),...C9.map(($)=>`Native custody refused: ${$}`),F9,"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 setup","Anthropic account migration is incomplete; resume setup","Anthropic account migration journal is invalid","Anthropic account migration journal changed","Anthropic runtime state is invalid","Anthropic runtime file is not owner-only regular storage","Anthropic runtime storage is unavailable","Anthropic runtime observation is older than persisted state","Anthropic runtime publication was refused","Claustrum connection failed; start ck and rerun setup.","Claustrum enrollment refused; inspect its status with ck before rerunning setup.","Invalid enrollment request id.","This Claustrum vault does not support connecting plugins yet, so setup cannot connect to it. Run setup without --claustrum to use local accounts.",'This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or run setup without --claustrum to use local accounts.',"OAuth metadata read failed"]),r8=Object.values(s0).join("|"),o8="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",t8=[new RegExp(`^Claustrum approval is still pending\\. In another terminal, run: ck auth enroll approve --request-id [A-Za-z0-9_-]{1,128} --name (?:${r8}) and then rerun setup\\.$`),/^The vault never created the enrollment request \(last error: [a-z][a-z0-9_]{0,63}\)\. Check that ck is running, then rerun setup\.$/],e8=new Set(["opencode","litecode","opencode2","pi","host"]),$6=64,Z6=256,J6=4096,Q2=65536,z6=4096,X6=3,K9="[output beyond the diagnostic limit omitted]",G6="[output withheld: no line break within the inspected window]",Q6="[detail withheld: the known credentials could not be read safely]",U2=new TextEncoder,P9=new TextDecoder;function h($,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")&&!Y2.isProxy($)}function q2($,Z){if(!q0($)||!Array.isArray($))return;let J=h($,"length");if(typeof J!=="number"||J>Z)return;let z=[];for(let X=0;X<J;X+=1){let G=Object.getOwnPropertyDescriptor($,String(X));if(G===void 0||!("value"in G))return;z.push(G.value)}return z}function W6($){let Z=q2($,$6);if(Z===void 0||Z.length===0)return;let J=[];for(let z of Z){if(!q0(z))return;let X=h(z,"pid"),G=h(z,"command");if(typeof X!=="number"||!Number.isSafeInteger(X)||X<0)return;if(typeof G!=="string"||!e8.has(G.toLowerCase()))return;J.push({pid:X,command:G})}return J}function K2($){try{if(!q0($))return;if(h($,"name")==="ProcessInspectionError")return"";let Z=h($,"message");if(typeof Z!=="string")return;if(h($,"name")==="HostNotEnrolledError"&&Z===o8)return Z;if(i8.has(Z))return Z;if(Z.startsWith("Unknown setup argument: "))return Z;if(h($,"name")==="HostNotEnrolledError"&&t8.some((X)=>X.test(Z)))return Z;if(h($,"code")==="ERR_PRIVATE_FILES_UNAVAILABLE")return F9;let J=h($,"status");if(typeof J==="number"&&Number.isInteger(J)&&J>=100&&J<=599&&Z===`OAuth metadata read failed: ${J}`)return Z;let z=W6(h($,"activeHosts"));if(z){let X=new G2(z).message;if(Z===X)return X}}catch{}return}function O9($){try{if(!q0($))return;let Z=q2(l8($),H2.length);if(Z===void 0)return;let J=[];for(let z of Z){if(!q0(z))return;let X=H2.find((Q)=>Q===h(z,"host")),G=h(z,"outcome");if(X===void 0||!s8.has(G))return;J.push({host:X,outcome:G})}return J}catch{return}}function H6($,Z=[]){try{let J=new Set,z=q2(Z,Z6);if(z===void 0)return;for(let G of z){if(typeof G!=="string")return;if(G!=="")J.add(G)}if(!q0($))return;let X=Reflect.ownKeys($);if(X.length>J6)return;for(let G of X){if(typeof G!=="string"||!c8(G))continue;let Q=Object.getOwnPropertyDescriptor($,G);if(Q===void 0)continue;if(!("value"in Q))return;if(Q.value===void 0||Q.value==="")continue;if(typeof Q.value!=="string")return;J.add(Q.value)}return[...J]}catch{return}}function Y6($,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 P9.decode(J.subarray(0,z))}function U6($,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 P9.decode(J.subarray(z))}function q6($,Z,J){let z=$,X=!1;if($.length>Q2){if(X=!0,J==="tail"){let H=$.indexOf(`
|
|
17
17
|
`,$.length-Q2);z=H===-1?"":$.slice(H+1)}else{let H=$.lastIndexOf(`
|
|
18
|
-
`,Q2);z=H===-1?"":$.slice(0,H)}if(z==="")return[
|
|
18
|
+
`,Q2);z=H===-1?"":$.slice(0,H)}if(z==="")return[G6]}let G=Z.redactText(z).split(/\r?\n/);if(G.length>1&&G[G.length-1]==="")G.pop();if(J==="tail")G.reverse();let Q=[],W=z6;for(let H of G){let U=U2.encode(H).length+1;if(U<=W){Q.push(H),W-=U;continue}if(Q.length===0)Q.push(J==="tail"?U6(H,W-1):Y6(H,W-1));X=!0;break}if(J==="tail")Q.reverse();if(X)if(J==="tail")Q.unshift(K9);else Q.push(K9);return Q}function I9($){let Z=$;for(let J=0;Z!==null&&J<8;J+=1){if(Y2.isProxy(Z))break;let z=h(Z,"name");if(typeof z==="string")return z;Z=Object.getPrototypeOf(Z)}return"object"}function j9($,Z){let J={};if(Z===void 0)return J;try{if(!q0($))return J;let z=M9(Z);try{for(let X of["name","code","stage","reason"]){let G=X==="name"?I9($):h($,X);if(typeof G==="string"&&n8[X].has(G)&&z.redactText(G)===G)J[X]=G}}finally{z.dispose()}}catch{return{}}return J}function K6($){if(!q0($))return;let Z=h($,"step"),J=h($,"exitCode"),z=h($,"signal"),X=h($,"stderrTail");if(typeof Z!=="string"||Z.length===0||!(J===null||typeof J==="number"&&Number.isInteger(J))||!(z===null||typeof z==="string")||typeof X!=="string")return;return{step:Z,exitCode:J,signal:z,stderrTail:X}}function _9($,Z){if($===null||typeof $!=="object"&&typeof $!=="function")return[`thrown ${typeof $}: ${String($)}`];if(Y2.isProxy($))return["thrown proxy (not inspected)"];let J=[],z=I9($),X=h($,"message");J.push(typeof X==="string"?`${z}: ${X}`:`${z} (no message)`);let G=h($,"code");if(typeof G==="string"||typeof G==="number")J.push(`code: ${G}`);let Q=h($,"stack");if(typeof Q==="string")J.push(Q);let W=h($,"cause");if(W!==void 0)if(Z>=X6)J.push("caused by: [not described]");else J.push("caused by:",..._9(W,Z+1));return J}function V9($,Z){let J=h($,Z);return typeof J==="string"&&J!==""?J:void 0}function j6($){if(!q0($))return;let Z=V9($,"XDG_STATE_HOME"),J=V9($,"HOME"),z=Z&&q9(Z)?Z:W2(J&&q9(J)?J:v8(),".local","state");return W2(z,"cortexkit","anthropic-auth","diagnostics")}async function V6($,Z,J,z={}){let X=(G)=>({error:{name:"DiagnosticFileError",code:G}});try{let G=j6($);if(G===void 0)return X("ERR_DIAGNOSTICS_DIRECTORY_UNAVAILABLE");if(!await m8(G,z)){await x8(G,{recursive:!0,mode:448});let H=await g8(G);if(!H.isDirectory())return X("ERR_DIAGNOSTICS_NOT_DIRECTORY");if(!await u8(G,()=>(H.mode&63)===0&&H.uid===process.getuid?.(),z))return X("ERR_DIAGNOSTICS_NOT_OWNER_ONLY")}let Q=W2(G,`${Z}-${Date.now()}-${process.pid}-${f8()}.log`);if(await h8(Q,J,z))return{path:Q};let W=await y8(Q,v1.O_WRONLY|v1.O_CREAT|v1.O_EXCL|(v1.O_NOFOLLOW??0),384);try{await W.writeFile(J,"utf8")}finally{await W.close()}return{path:Q}}catch(G){return{error:G}}}async function M6($,Z,J,z,X,G,Q,W={}){let H,U=H6(J,z);if(U===void 0)H=[Q6];else try{let P=M9(U);try{let{text:C,keep:D}=G();H=q6(C,P,D)}finally{P.dispose()}}catch{H=["[failure detail could not be recorded]"]}let q=a8[$],K=w8("error","cli",`${q} failed`,{stage:$,code:Z,...X}),F=await V6(J,$,`${[K,...H].join(`
|
|
19
19
|
`)}
|
|
20
20
|
`,W.ownership),B=F.path;if(B===void 0){let P={error:j9(Q,U),saveError:j9(F.error,U)};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 q1($,Z,J,z=[],X={}){let G=K2(Z);if(G!==void 0)return G;let Q=
|
|
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 q1($,Z,J,z=[],X={}){let G=K2(Z);if(G!==void 0)return G;let Q=K6(Z);return M6($,`${$}/unexpected-error`,J,z,{},()=>({text:[...Q?[`step: ${Q.step}`,`exitCode: ${Q.exitCode}`,`signal: ${Q.signal}`]:[],..._9(Z,0),...Q?[`stderrTail:
|
|
22
22
|
${Q.stderrTail}`]:[]].join(`
|
|
23
|
-
`),keep:"head"}),Z,X)}import{createProcessFence as
|
|
24
|
-
`)J.push("enter");else if(X==="\x03")J.push("escape");else if(X&&X>=" ")J.push("char");z+=1}return J}var v9=`${String.fromCharCode(27)}\\[[0-9;]*m`,
|
|
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))),
|
|
26
|
-
`),q=!1;for(let K=0;K<U.length;K++){let F=U[K];if(z+=F,!q){if(q=F>="\uD800"&&F<="\uDBFF",q)continue}else q=!1;if(F===l1||F===o9){s9.lastIndex=K+1;let P=s9.exec(U)?.groups;if(P?.code!==void 0){let C=Number.parseFloat(P.code);X=C===
|
|
23
|
+
`),keep:"head"}),Z,X)}import{createProcessFence as m5,NativePiAuthSlotError as w5,openNativePiAuthSlot as u5,publishNativeEmptyInit as c5,readNativeEnrollmentMode as p5,releaseNativeMigrationPreflight as d5,requireNoSupervisedAuthContentSnapshot as l5,runSetup as a5}from"@cortexkit/anthropic-auth-core";import{AsyncLocalStorage as B6}from"node:async_hooks";var YG=new B6;var A9=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});var i0="commonAuthPool";var m6=Object.freeze(["version","accounts",i0]);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 N2($){let Z=$.toString(),J=[];for(let z=0;z<Z.length;){let X=Z[z];if(X==="\x1B"){let G=Z.slice(z,z+3),Q=G[1]==="["||G[1]==="O"?G[2]:void 0;if(Q&&"ABCD".includes(Q)){let H={A:"up",B:"down",C:"right",D:"left"}[Q];if(H)J.push(H);z+=3}else if(z+1===Z.length){if(z===0)J.push("escape-start");z+=1}else if((Z[z+1]==="["||Z[z+1]==="O")&&z+2>=Z.length)break;else z+=1;continue}if(X==="\r"||X===`
|
|
24
|
+
`)J.push("enter");else if(X==="\x03")J.push("escape");else if(X&&X>=" ")J.push("char");z+=1}return J}var v9=`${String.fromCharCode(27)}\\[[0-9;]*m`,w6=new RegExp(v9,"g"),u6=new RegExp(`^${v9}`);function h9($){return $.replace(w6,"")}function f0($,Z){if(Z<=0)return"";if(h9($).length<=Z)return $;let J=Z>=3?"...":".".repeat(Z),z=Math.max(0,Z-J.length),X="",G=0,Q=0;while(G<$.length&&Q<z){if($[G]==="\x1B"){let W=$.slice(G).match(u6);if(W){X+=W[0],G+=W[0].length;continue}}X+=$[G],G+=1,Q+=1}return X.includes("\x1B[")?`${X}${A.reset}${J}`:X+J}function o0($){return $.input.isTTY===!0}var c6=50;function p6($){if($==="red")return A.red;if($==="cyan")return A.cyan;return""}async function p1($,Z,J){if(!o0($))throw Error("Interactive select requires a TTY terminal");if(Z.length===0)throw Error("No menu items provided");let{input:z,output:X,signals:G}=$,Q=0,W=null,H=!1,U=0,q=()=>{let K=X.columns??80,F=X.rows??24,B=U;if(J.clearScreen)X.write(A.clearScreen+A.moveTo(1,1));else if(B>0)X.write(A.up(B));let P=0,C=(j)=>{X.write(`${A.clearLine}${j}
|
|
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))),N=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 j of D)C(`${A.cyan}│${A.reset} ${f0(j,Math.max(1,K-4))}`);if(D.length)C(`${A.cyan}│${A.reset}`);for(let j=0;j<N.length;j++){let V=N[j];if(!V)continue;let b=y+j===Q,g=p6(V.color),k=g?`${b?"":A.dim}${g}${V.label}${A.reset}`:b?V.label:`${A.dim}${V.label}${A.reset}`;if(V.hint)k+=` ${A.dim}${V.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 Y=N.length<Z.length?` (${y+1}-${y+N.length}/${Z.length})`:"";C(`${A.cyan}│${A.reset} ${A.dim}${f0(`Up/Down to select | Enter: confirm | Esc: back${Y}`,Math.max(1,K-6))}${A.reset}`),C(`${A.cyan}└${A.reset}`);for(let j=P;j<B;j++)C("");U=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(),X.write(A.show)}catch{}G?.removeListener("SIGINT",C),G?.removeListener("SIGTERM",C)},P=(R)=>{B(),K(R)},C=()=>P(null),D=(R)=>{for(let S of N2(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),c6);break;default:break}}};G?.once("SIGINT",C),G?.once("SIGTERM",C);try{z.setRawMode(!0)}catch{B(),K(null);return}z.resume(),X.write(A.hide),q(),z.on("data",D)})}async function d1($,Z,J=!1){if(!o0($))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 i6}from"node:child_process";import{promisify as r6}from"node:util";var o6=r6(i6),m9={async run($,Z,J={}){try{let z=J.env?{...process.env,...J.env}:process.env,{stdout:X,stderr:G}=await o6($,Z,{env:z,timeout:J.timeoutMs??15000,maxBuffer:10485760});return{exitCode:0,stdout:typeof X==="string"?X:String(X),stderr:typeof G==="string"?G:String(G)}}catch(z){let X=z;return{exitCode:typeof X?.code==="number"?X.code:1,signal:typeof X?.signal==="string"?X.signal:null,...typeof X?.syscall==="string"&&(X.syscall==="spawn"||X.syscall.startsWith("spawn "))?{spawnError:!0}:{},stdout:typeof X?.stdout==="string"?X.stdout:X?.stdout!=null?String(X.stdout):"",stderr:typeof X?.stderr==="string"?X.stderr:X?.stderr!=null?String(X.stderr):String(X?.message??z)}}}};import{styleText as r1}from"node:util";import{stdout as V5,stdin as M5}from"node:process";import F5 from"node:readline";var w9=(()=>{let $=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(Z)=>{let J=0;$.lastIndex=0;while($.test(Z))J+=1;return Z.length-J}})(),u9=($)=>{return $===12288||$>=65281&&$<=65376||$>=65504&&$<=65510},c9=($)=>{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 t6=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,e6=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,p9=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,$5=/\t{1,1000}/y,d9=/[\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,Z5=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,J5=/\p{M}+/gu,z5={limit:1/0,ellipsis:""},l9=($,Z={},J={})=>{let z=Z.limit??1/0,X=Z.ellipsis??"",G=Z?.ellipsisWidth??(X?l9(X,z5,J).width:0),Q=0,W=J.controlWidth??0,H=J.tabWidth??8,U=J.emojiWidth??2,q=2,K=J.regularWidth??1,F=J.wideWidth??2,B=[[Z5,K],[t6,0],[e6,W],[$5,H],[d9,U],[p9,F]],P=0,C=0,D=$.length,R=0,S=!1,y=D,N=Math.max(0,z-G),Y=0,j=0,V=0,b=0;$:while(!0){if(j>Y||C>=D&&C>P){let g=$.slice(Y,j)||$.slice(P,C);R=0;for(let k of g.replaceAll(J5,"")){let m=k.codePointAt(0)||0;if(u9(m))b=2;else if(c9(m))b=F;else b=K;if(V+b>N)y=Math.min(y,Math.max(Y,P)+R);if(V+b>z){S=!0;break $}R+=k.length,V+=b}Y=j=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===p9?w9($.slice(C,m.lastIndex)):m===d9?1:m.lastIndex-C,b=R*n,V+b>N)y=Math.min(y,C+Math.floor((N-V)/n));if(V+b>z){S=!0;break $}V+=b,Y=P,j=C,C=P=m.lastIndex;continue $}}C+=1}return{width:S?N:V,index:S?y:D,truncated:S,ellipsed:S&&z>=G}},a9=l9;var X5={limit:1/0,ellipsis:"",ellipsisWidth:0},G5=($,Z={})=>{return a9($,X5,Z).width},X0=G5;var l1="\x1B",o9="",Q5=39,C2="\x07",t9="[",W5="]",e9="m",P2=`${W5}8;;`,s9=new RegExp(`(?:\\${t9}(?<code>\\d+)m|\\${P2}(?<uri>.*)${C2})`,"y"),n9=($)=>{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},i9=($)=>`${l1}${t9}${$}${e9}`,r9=($)=>`${l1}${P2}${$}${C2}`,L2=($,Z,J)=>{let z=Z[Symbol.iterator](),X=!1,G=!1,Q=$.at(-1),W=Q===void 0?0:X0(Q),H=z.next(),U=z.next(),q=0;while(!H.done){let K=H.value,F=X0(K);if(W+F<=J)$[$.length-1]+=K;else $.push(K),W=0;if(K===l1||K===o9)X=!0,G=Z.startsWith(P2,q+1);if(X){if(G){if(K===C2)X=!1,G=!1}else if(K===e9)X=!1}else if(W+=F,W===J&&!U.done)$.push(""),W=0;H=U,U=z.next(),q+=K.length}if(Q=$.at(-1),!W&&Q!==void 0&&Q.length&&$.length>1)$[$.length-2]+=$.pop()},H5=($)=>{let Z=$.split(" "),J=Z.length;while(J){if(X0(Z[J-1]))break;J--}if(J===Z.length)return $;return Z.slice(0,J).join(" ")+Z.slice(J).join("")},Y5=($,Z,J={})=>{if(J.trim!==!1&&$.trim()==="")return"";let z="",X,G,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=X0(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=X0(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=X0(W.at(-1)??"");continue}if(H+B>Z&&H&&B){if(J.wordWrap===!1&&H<Z){L2(W,F,Z),H=X0(W.at(-1)??"");continue}W.push(""),H=0}if(H+B>Z&&J.wordWrap===!1){L2(W,F,Z),H=X0(W.at(-1)??"");continue}W[W.length-1]+=F,H+=B}if(J.trim!==!1)W=W.map((K)=>H5(K));let U=W.join(`
|
|
26
|
+
`),q=!1;for(let K=0;K<U.length;K++){let F=U[K];if(z+=F,!q){if(q=F>="\uD800"&&F<="\uDBFF",q)continue}else q=!1;if(F===l1||F===o9){s9.lastIndex=K+1;let P=s9.exec(U)?.groups;if(P?.code!==void 0){let C=Number.parseFloat(P.code);X=C===Q5?void 0:C}else if(P?.uri!==void 0)G=P.uri.length===0?void 0:P.uri}if(U[K+1]===`
|
|
27
27
|
`){if(G)z+=r9("");let B=X?n9(X):void 0;if(X&&B)z+=i9(B)}else if(F===`
|
|
28
|
-
`){if(X&&n9(X))z+=i9(X);if(G)z+=r9(G)}}return z},
|
|
28
|
+
`){if(X&&n9(X))z+=i9(X);if(G)z+=r9(G)}}return z},U5=/\r?\n/;function a1($,Z,J){return String($).normalize().split(U5).map((z)=>Y5(z,Z,J)).join(`
|
|
29
29
|
`)}var r=z4(I2(),1);function A2($,Z,J){if(!J.some((Q)=>!Q.disabled))return $;let z=$+Z,X=Math.max(J.length-1,0),G=z<0?X:z>X?0:z;return J[G]?.disabled?A2(G,Z<0?-1:1,J):G}function s1($,Z,J,z){let X=z.split(`
|
|
30
|
-
`),G=0,Q=$;for(let H of X){if(Q<=H.length)break;Q-=H.length+1,G++}for(G=Math.max(0,Math.min(X.length-1,G+J)),Q=Math.min(Q,X[G].length)+Z;Q<0&&G>0;)G--,Q+=X[G].length+1;for(;Q>X[G].length&&G<X.length-1;)Q-=X[G].length+1,G++;Q=Math.max(0,Math.min(X[G].length,Q));let W=0;for(let H=0;H<G;H++)W+=X[H].length+1;return W+Q}var
|
|
30
|
+
`),G=0,Q=$;for(let H of X){if(Q<=H.length)break;Q-=H.length+1,G++}for(G=Math.max(0,Math.min(X.length-1,G+J)),Q=Math.min(Q,X[G].length)+Z;Q<0&&G>0;)G--,Q+=X[G].length+1;for(;Q>X[G].length&&G<X.length-1;)Q-=X[G].length+1,G++;Q=Math.max(0,Math.min(X[G].length,Q));let W=0;for(let H=0;H<G;H++)W+=X[H].length+1;return W+Q}var B5=["up","down","left","right","space","enter","cancel"],D5=["January","February","March","April","May","June","July","August","September","October","November","December"],$0={actions:new Set(B5),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:[...D5],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 N5($){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 X4($,Z){if(typeof $=="string")return $0.aliases.get($)===Z;for(let J of $)if(J!==void 0&&X4(J,Z))return!0;return!1}function L5($,Z){if($===Z)return;let J=$.split(`
|
|
31
31
|
`),z=Z.split(`
|
|
32
|
-
`),X=Math.max(J.length,z.length),G=[];for(let Q=0;Q<X;Q++)J[Q]!==z[Q]&&G.push(Q);return{lines:G,numLinesBefore:J.length,numLinesAfter:z.length,numLines:X}}var
|
|
32
|
+
`),X=Math.max(J.length,z.length),G=[];for(let Q=0;Q<X;Q++)J[Q]!==z[Q]&&G.push(Q);return{lines:G,numLinesBefore:J.length,numLinesAfter:z.length,numLines:X}}var eH=globalThis.process.platform.startsWith("win"),o1=Symbol("clack:cancel");function t1($){return $===o1}function n1($,Z){let J=$;J.isTTY&&J.setRawMode(Z)}var G4=($)=>("rows"in $)&&typeof $.rows=="number"?$.rows:20;function Q4($,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 t0{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return N5(this.opts.accessible)}constructor($,Z=!0){let{input:J=M5,output:z=V5,render:X,signal:G,...Q}=$;this.opts=Q,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=X.bind(this),this._track=Z,this._abortSignal=G,this.input=J,this.output=z}unsubscribe(){this._subscribers.clear()}setSubscriber($,Z){let J=this._subscribers.get($)??[];J.push(Z),this._subscribers.set($,J)}on($,Z){this.setSubscriber($,{cb:Z})}once($,Z){this.setSubscriber($,{cb:Z,once:!0})}emit($,...Z){let J=this._subscribers.get($)??[],z=[];for(let X of J)X.cb(...Z),X.once&&z.push(()=>J.splice(J.indexOf(X),1));for(let X of z)X()}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(o1);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=F5.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=Q4(this.opts.validate,this.value),z;J instanceof Promise?(this.state="validating",this.render(),z=await J):z=J,z&&(this.error=z instanceof Error?z.message:z,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}X4([$,Z?.name,Z?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
33
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
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=L5(this._prevFrame,$),J=G4(this.output);if(this.restoreCursor(),Z){let z=Math.max(0,Z.numLinesAfter-J),X=Math.max(0,Z.numLinesBefore-J),G=Z.lines.find((Q)=>Q>=z);if(G===void 0){this._prevFrame=$;return}if(Z.lines.length===1){this.output.write(r.cursor.move(0,G-X)),this.output.write(r.erase.lines(1));let Q=$.split(`
|
|
35
35
|
`);this.output.write(Q[G]),this._prevFrame=$,this.output.write(r.cursor.move(0,Q.length-G-1));return}else if(Z.lines.length>1){if(z<X)G=z;else{let W=G-X;W>0&&this.output.write(r.cursor.move(0,W))}this.output.write(r.erase.down());let Q=$.split(`
|
|
36
36
|
`).slice(G);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 N5($,Z){if($===void 0||Z.length===0)return 0;let J=Z.findIndex((z)=>z.value===$);return J!==-1?J:0}function C5($,Z){return(Z.label??String(Z.value)).toLowerCase().includes($.toLowerCase())}function P5($,Z){if(Z)return $?Z:Z[0]}var O5=class extends t0{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#z="";#Z;#X;#H;#G;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.#X=="function"?this.#X():this.#X}constructor(Z){super(Z),this.#X=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??C5;let z;if(Z.initialValue&&Array.isArray(Z.initialValue)?this.multiple?z=Z.initialValue:z=Z.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(z=[this.options[0]?.value]),z)for(let X of z){let G=J.findIndex((Q)=>Q.value===X);G!==-1&&(this.toggleSelected(X),this.#$=G)}this.focusedValue=this.options[this.#$]?.value,this.on("key",(X,G)=>this.#J(X,G)),this.on("userInput",(X)=>this.#Y(X))}_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",X=J.name==="down",G=J.name==="return",Q=this.userInput===""||this.userInput==="\t",W=this.#H,H=this.options,U=W!==void 0&&W!==""&&H.some((q)=>!q.disabled&&(this.#Z?this.#Z(W,q):!0));if(J.name==="tab"&&Q&&U){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(W,!0),this.isNavigating=!1;return}if(J.name==="tab"&&this.#G&&!this.multiple&&this.focusedValue!==void 0){let q=String(this.focusedValue);this._clearUserInput(),this._setUserInput(q,!0),this.isNavigating=!1;return}z||X?(this.#$=A2(this.#$,z?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):G?this.value=P5(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])}#Y(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=N5(this.focusedValue,this.filteredOptions);this.#$=A2(z,0,this.filteredOptions);let X=this.filteredOptions[this.#$];X&&!X.disabled?this.focusedValue=X.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};var I5={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function Z4($){return[...$].map((Z)=>I5[Z])}function _5($){let Z=new Intl.DateTimeFormat($,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),J=[],z="/";for(let X of Z)X.type==="literal"?z=X.value.trim()||X.value:(X.type==="year"||X.type==="month"||X.type==="day")&&J.push({type:X.type,len:X.type==="year"?4:2});return{segments:J,separator:z}}function _2($){return Number.parseInt(($||"0").replace(/_/g,"0"),10)||0}function i1($){return{year:_2($.year),month:_2($.month),day:_2($.day)}}function R2($,Z){return new Date($||2001,Z||1,0).getDate()}function W4($){let{year:Z,month:J,day:z}=i1($);if(!Z||Z<0||Z>9999||!J||J<1||J>12||!z||z<1)return;let X=new Date(Date.UTC(Z,J-1,z));if(!(X.getUTCFullYear()!==Z||X.getUTCMonth()!==J-1||X.getUTCDate()!==z))return{year:Z,month:J,day:z}}function J4($){let Z=W4($);return Z?new Date(Date.UTC(Z.year,Z.month-1,Z.day)):void 0}function A5($,Z,J,z){let X=J?{year:J.getUTCFullYear(),month:J.getUTCMonth()+1,day:J.getUTCDate()}:null,G=z?{year:z.getUTCFullYear(),month:z.getUTCMonth()+1,day:z.getUTCDate()}:null;return $==="year"?{min:X?.year??1,max:G?.year??9999}:$==="month"?{min:X&&Z.year===X.year?X.month:1,max:G&&Z.year===G.year?G.month:12}:{min:X&&Z.year===X.year&&Z.month===X.month?X.day:1,max:G&&Z.year===G.year&&Z.month===G.month?G.day:R2(Z.year,Z.month)}}class H4 extends t0{#$;#z;#Z;#X;#H;#G={segmentIndex:0,positionInSegment:0};#J=!0;#Y=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.#q(this.#Z)}#q($){return this.#$.map((Z)=>$[Z.type]).join(this.#z)}#W(){this._setUserInput(this.#q(this.#Z)),this._setValue(J4(this.#Z)??void 0)}constructor($){let Z=$.format?{segments:Z4($.format),separator:$.separator??"/"}:_5($.locale),J=$.separator??Z.separator,z=$.format?Z4($.format):Z.segments,X=$.initialValue??$.defaultValue,G=X?{year:String(X.getUTCFullYear()).padStart(4,"0"),month:String(X.getUTCMonth()+1).padStart(2,"0"),day:String(X.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},Q=z.map((W)=>G[W.type]).join(J);super({...$,initialUserInput:Q},!1),this.#$=z,this.#z=J,this.#Z=G,this.#X=$.minDate,this.#H=$.maxDate,this.#W(),this.on("cursor",(W)=>this.#j(W)),this.on("key",(W,H)=>this.#F(W,H)),this.on("finalize",()=>this.#K($))}#Q(){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:$}}#U($){this.inlineError="",this.#Y=null;let Z=this.#Q();Z&&(this.#G.segmentIndex=Math.max(0,Math.min(this.#$.length-1,Z.index+$)),this.#G.positionInSegment=0,this.#J=!0)}#V($){let Z=this.#Q();if(!Z)return;let{segment:J}=Z,z=this.#Z[J.type],X=!z||z.replace(/_/g,"")==="",G=Number.parseInt((z||"0").replace(/_/g,"0"),10)||0,Q=A5(J.type,i1(this.#Z),this.#X,this.#H),W;X?W=$===1?Q.min:Q.max:W=Math.max(Math.min(Q.max,G+$),Q.min),this.#Z={...this.#Z,[J.type]:W.toString().padStart(J.len,"0")},this.#J=!0,this.#Y=null,this.#W()}#j($){if($)switch($){case"right":return this.#U(1);case"left":return this.#U(-1);case"up":return this.#V(1);case"down":return this.#V(-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.#U(-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.#Q();if(!J)return;let z=Z.shift?-1:1,X=J.index+z;X>=0&&X<this.#$.length&&(this.#G.segmentIndex=X,this.#G.positionInSegment=0,this.#J=!0);return}if($&&/^[0-9]$/.test($)){let J=this.#Q();if(!J)return;let{segment:z}=J,X=!this.#Z[z.type].replace(/_/g,"");if(this.#J&&this.#Y!==null&&!X){let F=this.#Y+$,B={...this.#Z,[z.type]:F},P=this.#M(B,z);if(P){this.inlineError=P,this.#Y=null,this.#J=!1;return}this.inlineError="",this.#Z[z.type]=F,this.#Y=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&&!X&&(this.#Z[z.type]="_".repeat(z.len),this.#G.positionInSegment=0),this.#J=!1,this.#Y=null;let G=this.#Z[z.type],Q=G.indexOf("_"),W=Q>=0?Q: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),U=!1;if(W===0&&G==="__"&&(z.type==="month"||z.type==="day")){let F=Number.parseInt($,10);H=`0${$}`,U=F<=(z.type==="month"?1:2)}if(z.type==="year"&&(H=(G.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:W4(this.#Z);if(q){let{year:F,month:B}=q,P=R2(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("_");U?(this.#J=!0,this.#Y=$):K>=0?this.#G.positionInSegment=K:Q>=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)}}#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 X=R2(Z,J);this.#Z={...this.#Z,day:String(Math.min(z,X)).padStart(2,"0")}}this.value=J4(this.#Z)??$.defaultValue??void 0}}var R5=class extends t0{options;cursor=0;#$;getGroupItems(Z){return this.options.filter((J)=>J.group===Z)}isGroupSelected(Z){let J=this.getGroupItems(Z),z=this.value;return z===void 0?!1:J.every((X)=>z.includes(X.value))}toggleValue(){let Z=this.options[this.cursor];if(Z!==void 0)if(this.value===void 0&&(this.value=[]),Z.group===!0){let J=Z.value,z=this.getGroupItems(J);this.isGroupSelected(J)?this.value=this.value.filter((X)=>z.findIndex((G)=>G.value===X)===-1):this.value=[...this.value,...z.map((X)=>X.value)],this.value=Array.from(new Set(this.value))}else{let J=this.value.includes(Z.value);this.value=J?this.value.filter((z)=>z!==Z.value):[...this.value,Z.value]}}constructor(Z){super(Z,!1);let{options:J}=Z;this.#$=Z.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([z,X])=>[{value:z,group:!0,label:z},...X.map((G)=>({...G,group:z}))]),this.value=[...Z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:z})=>z===Z.cursorAt),this.#$?0:1),this.on("cursor",(z)=>{switch(z){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let X=this.options[this.cursor]?.group===!0;!this.#$&&X&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let X=this.options[this.cursor]?.group===!0;!this.#$&&X&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},S5=new Set(["up","down","left","right"]);class Y4 extends t0{#$=!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===`
|
|
37
|
+
`)),this._prevFrame=$;return}}this.output.write(r.erase.down())}this.output.write($),this.state==="initial"&&(this.state="active"),this._prevFrame=$}}}function C5($,Z){if($===void 0||Z.length===0)return 0;let J=Z.findIndex((z)=>z.value===$);return J!==-1?J:0}function P5($,Z){return(Z.label??String(Z.value)).toLowerCase().includes($.toLowerCase())}function O5($,Z){if(Z)return $?Z:Z[0]}var I5=class extends t0{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#z="";#Z;#X;#H;#G;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.#X=="function"?this.#X():this.#X}constructor(Z){super(Z),this.#X=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??P5;let z;if(Z.initialValue&&Array.isArray(Z.initialValue)?this.multiple?z=Z.initialValue:z=Z.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(z=[this.options[0]?.value]),z)for(let X of z){let G=J.findIndex((Q)=>Q.value===X);G!==-1&&(this.toggleSelected(X),this.#$=G)}this.focusedValue=this.options[this.#$]?.value,this.on("key",(X,G)=>this.#J(X,G)),this.on("userInput",(X)=>this.#Y(X))}_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",X=J.name==="down",G=J.name==="return",Q=this.userInput===""||this.userInput==="\t",W=this.#H,H=this.options,U=W!==void 0&&W!==""&&H.some((q)=>!q.disabled&&(this.#Z?this.#Z(W,q):!0));if(J.name==="tab"&&Q&&U){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(W,!0),this.isNavigating=!1;return}if(J.name==="tab"&&this.#G&&!this.multiple&&this.focusedValue!==void 0){let q=String(this.focusedValue);this._clearUserInput(),this._setUserInput(q,!0),this.isNavigating=!1;return}z||X?(this.#$=A2(this.#$,z?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):G?this.value=O5(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])}#Y(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=C5(this.focusedValue,this.filteredOptions);this.#$=A2(z,0,this.filteredOptions);let X=this.filteredOptions[this.#$];X&&!X.disabled?this.focusedValue=X.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};var _5={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function Z4($){return[...$].map((Z)=>_5[Z])}function A5($){let Z=new Intl.DateTimeFormat($,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),J=[],z="/";for(let X of Z)X.type==="literal"?z=X.value.trim()||X.value:(X.type==="year"||X.type==="month"||X.type==="day")&&J.push({type:X.type,len:X.type==="year"?4:2});return{segments:J,separator:z}}function _2($){return Number.parseInt(($||"0").replace(/_/g,"0"),10)||0}function i1($){return{year:_2($.year),month:_2($.month),day:_2($.day)}}function R2($,Z){return new Date($||2001,Z||1,0).getDate()}function W4($){let{year:Z,month:J,day:z}=i1($);if(!Z||Z<0||Z>9999||!J||J<1||J>12||!z||z<1)return;let X=new Date(Date.UTC(Z,J-1,z));if(!(X.getUTCFullYear()!==Z||X.getUTCMonth()!==J-1||X.getUTCDate()!==z))return{year:Z,month:J,day:z}}function J4($){let Z=W4($);return Z?new Date(Date.UTC(Z.year,Z.month-1,Z.day)):void 0}function R5($,Z,J,z){let X=J?{year:J.getUTCFullYear(),month:J.getUTCMonth()+1,day:J.getUTCDate()}:null,G=z?{year:z.getUTCFullYear(),month:z.getUTCMonth()+1,day:z.getUTCDate()}:null;return $==="year"?{min:X?.year??1,max:G?.year??9999}:$==="month"?{min:X&&Z.year===X.year?X.month:1,max:G&&Z.year===G.year?G.month:12}:{min:X&&Z.year===X.year&&Z.month===X.month?X.day:1,max:G&&Z.year===G.year&&Z.month===G.month?G.day:R2(Z.year,Z.month)}}class H4 extends t0{#$;#z;#Z;#X;#H;#G={segmentIndex:0,positionInSegment:0};#J=!0;#Y=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.#q(this.#Z)}#q($){return this.#$.map((Z)=>$[Z.type]).join(this.#z)}#W(){this._setUserInput(this.#q(this.#Z)),this._setValue(J4(this.#Z)??void 0)}constructor($){let Z=$.format?{segments:Z4($.format),separator:$.separator??"/"}:A5($.locale),J=$.separator??Z.separator,z=$.format?Z4($.format):Z.segments,X=$.initialValue??$.defaultValue,G=X?{year:String(X.getUTCFullYear()).padStart(4,"0"),month:String(X.getUTCMonth()+1).padStart(2,"0"),day:String(X.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},Q=z.map((W)=>G[W.type]).join(J);super({...$,initialUserInput:Q},!1),this.#$=z,this.#z=J,this.#Z=G,this.#X=$.minDate,this.#H=$.maxDate,this.#W(),this.on("cursor",(W)=>this.#j(W)),this.on("key",(W,H)=>this.#F(W,H)),this.on("finalize",()=>this.#K($))}#Q(){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:$}}#U($){this.inlineError="",this.#Y=null;let Z=this.#Q();Z&&(this.#G.segmentIndex=Math.max(0,Math.min(this.#$.length-1,Z.index+$)),this.#G.positionInSegment=0,this.#J=!0)}#V($){let Z=this.#Q();if(!Z)return;let{segment:J}=Z,z=this.#Z[J.type],X=!z||z.replace(/_/g,"")==="",G=Number.parseInt((z||"0").replace(/_/g,"0"),10)||0,Q=R5(J.type,i1(this.#Z),this.#X,this.#H),W;X?W=$===1?Q.min:Q.max:W=Math.max(Math.min(Q.max,G+$),Q.min),this.#Z={...this.#Z,[J.type]:W.toString().padStart(J.len,"0")},this.#J=!0,this.#Y=null,this.#W()}#j($){if($)switch($){case"right":return this.#U(1);case"left":return this.#U(-1);case"up":return this.#V(1);case"down":return this.#V(-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.#U(-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.#Q();if(!J)return;let z=Z.shift?-1:1,X=J.index+z;X>=0&&X<this.#$.length&&(this.#G.segmentIndex=X,this.#G.positionInSegment=0,this.#J=!0);return}if($&&/^[0-9]$/.test($)){let J=this.#Q();if(!J)return;let{segment:z}=J,X=!this.#Z[z.type].replace(/_/g,"");if(this.#J&&this.#Y!==null&&!X){let F=this.#Y+$,B={...this.#Z,[z.type]:F},P=this.#M(B,z);if(P){this.inlineError=P,this.#Y=null,this.#J=!1;return}this.inlineError="",this.#Z[z.type]=F,this.#Y=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&&!X&&(this.#Z[z.type]="_".repeat(z.len),this.#G.positionInSegment=0),this.#J=!1,this.#Y=null;let G=this.#Z[z.type],Q=G.indexOf("_"),W=Q>=0?Q: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),U=!1;if(W===0&&G==="__"&&(z.type==="month"||z.type==="day")){let F=Number.parseInt($,10);H=`0${$}`,U=F<=(z.type==="month"?1:2)}if(z.type==="year"&&(H=(G.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:W4(this.#Z);if(q){let{year:F,month:B}=q,P=R2(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("_");U?(this.#J=!0,this.#Y=$):K>=0?this.#G.positionInSegment=K:Q>=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)}}#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 X=R2(Z,J);this.#Z={...this.#Z,day:String(Math.min(z,X)).padStart(2,"0")}}this.value=J4(this.#Z)??$.defaultValue??void 0}}var S5=class extends t0{options;cursor=0;#$;getGroupItems(Z){return this.options.filter((J)=>J.group===Z)}isGroupSelected(Z){let J=this.getGroupItems(Z),z=this.value;return z===void 0?!1:J.every((X)=>z.includes(X.value))}toggleValue(){let Z=this.options[this.cursor];if(Z!==void 0)if(this.value===void 0&&(this.value=[]),Z.group===!0){let J=Z.value,z=this.getGroupItems(J);this.isGroupSelected(J)?this.value=this.value.filter((X)=>z.findIndex((G)=>G.value===X)===-1):this.value=[...this.value,...z.map((X)=>X.value)],this.value=Array.from(new Set(this.value))}else{let J=this.value.includes(Z.value);this.value=J?this.value.filter((z)=>z!==Z.value):[...this.value,Z.value]}}constructor(Z){super(Z,!1);let{options:J}=Z;this.#$=Z.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([z,X])=>[{value:z,group:!0,label:z},...X.map((G)=>({...G,group:z}))]),this.value=[...Z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:z})=>z===Z.cursorAt),this.#$?0:1),this.on("cursor",(z)=>{switch(z){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let X=this.options[this.cursor]?.group===!0;!this.#$&&X&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let X=this.options[this.cursor]?.group===!0;!this.#$&&X&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},b5=new Set(["up","down","left","right"]);class Y4 extends t0{#$=!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
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))}#X($){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
|
-
`:""}${
|
|
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.#X(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 S2 extends t0{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 KY}from"node:util";import Z0 from"node:process";var q4=z4(I2(),1);function k5(){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 T5=k5();var f=($,Z)=>T5?$:Z,U4=f("◆","*"),E5=f("■","x"),f5=f("▲","x"),g5=f("◇","o"),FY=f("┌","T"),g0=f("│","|"),b2=f("└","—"),BY=f("┐","T"),DY=f("┘","—"),NY=f("●",">"),LY=f("○"," "),CY=f("◻","[•]"),PY=f("◼","[+]"),OY=f("◻","[ ]"),IY=f("▪","•"),_Y=f("─","-"),AY=f("╮","+"),RY=f("├","+"),SY=f("╯","+"),bY=f("╰","+"),kY=f("╭","+"),TY=f("●","•"),EY=f("◆","*"),fY=f("▲","!"),gY=f("■","x"),x5=($)=>{switch($){case"initial":case"active":return E("cyan",U4);case"cancel":return E("red",E5);case"error":return E("yellow",f5);case"submit":return E("green",g5);case"validating":return E("dim",U4)}};var xY=[`${E("dim","↑/↓")} to navigate`,`${E("dim","Space:")} select`,`${E("dim","Enter:")} confirm`];var yY={light:f("─","-"),heavy:f("━","="),block:f("█","#")};var vY=[`${E("dim","↑/↓")} to navigate`,`${E("dim","Enter:")} confirm`];var hY=`${E("gray",g0)} `;var K4=($)=>new S2({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
|
+
`:""}${x5(this.state)} `}${$.message}
|
|
44
44
|
`,z=$.placeholder&&$.placeholder.length>0?E("inverse",$.placeholder[0])+E("dim",$.placeholder.slice(1)):E(["inverse","hidden"],"_"),X=this.userInput?this.userInputWithCursor:z,G=this.value??"";switch(this.state){case"validating":{let Q=Z?`${E("cyan",g0)} `:"",W=Z?E("cyan",b2):"",H=E("dim",X),U=E("dim","Validating...");return`${J}${Q}${H}
|
|
45
45
|
${W} ${U}
|
|
46
46
|
`}case"error":{let Q=this.error?` ${E("yellow",this.error)}`:"",W=Z?`${E("yellow",g0)} `:"",H=Z?E("yellow",b2):"";return`${J.trim()}
|
|
@@ -49,8 +49,8 @@ ${H}${Q}
|
|
|
49
49
|
`}case"submit":{let Q=G?`${Z?" ":""}${E("dim",G)}`:"",W=Z?E("gray",g0):"";return`${J}${W}${Q}`}case"cancel":{let Q=G?` ${E(["strikethrough","dim"],G)}`:"",W=Z?E("gray",g0):"";return`${J}${W}${Q}${G.trim()?`
|
|
50
50
|
${W}`:""}`}default:{let Q=Z?`${E("cyan",g0)} `:"",W=Z?E("cyan",b2):"";return`${J}${Q}${X}
|
|
51
51
|
${W}
|
|
52
|
-
`}}}}).prompt();import{authorize as
|
|
53
|
-
`),G=$.filter((Y)=>Y!=="--remove-pi-auth").map((Y)=>Y==="-y"?"--yes":Y),Q=G.includes("--login");if(Q&&G.includes("--claustrum"))return X("Local sign-in and vault setup are two separate choices. Use --login or --claustrum, not both."),1;if(Q&&G.includes("--opencode=2"))return X(e1),1;let W=Z.runner??m9,H=Z.fence??
|
|
52
|
+
`}}}}).prompt();import{authorize as y5,exchange as v5,resolveClaudeCodeIdentity as h5}from"@cortexkit/anthropic-auth-core";async function j4($,Z={authorize:y5,exchange:v5,resolveClaudeCodeIdentity:h5,text:K4,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 X=await Z.exchange(z,J.verifier,J.redirectUri,J.state);if(X.type!=="success")throw Error("Claude sign-in failed");let G=await Z.resolveClaudeCodeIdentity(X.access,void 0,void 0);if(!G.accountUuid)throw Error("Claude sign-in did not establish an account UUID");return{accountIdentity:G.accountUuid,credential:{type:"oauth",access:X.access,refresh:X.refresh,expires:X.expires}}}var V4='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 j0($,Z){let J=$.get(Z);if(!J)throw Error("Missing setup plan");return J}async function D4($=[],Z={}){let J={...Z.env??process.env},z=Z.terminal??{input:process.stdin,output:process.stdout,signals:process},X=(Y)=>z.output.write(`${Y}
|
|
53
|
+
`),G=$.filter((Y)=>Y!=="--remove-pi-auth").map((Y)=>Y==="-y"?"--yes":Y),Q=G.includes("--login");if(Q&&G.includes("--claustrum"))return X("Local sign-in and vault setup are two separate choices. Use --login or --claustrum, not both."),1;if(Q&&G.includes("--opencode=2"))return X(e1),1;let W=Z.runner??m9,H=Z.fence??m5(W,{platform:Z.platform}),U=Z.migrateLocal??Q9,q=new Map,K=new Map,F=new Map,B=new Map,P=!1,C="setup-process-check",D=(Y)=>({env:J,fence:H,paths:F.get(Y),removePiAnthropicAuth:B.get(Y)??!1}),R=(Y)=>({...D(Y),runner:W});async function S(Y){if(!Y.hosts.includes("pi"))return;let j=j0(F,"pi");if((await H1("pi",j.hostAuthPath)).kind==="absent")return;{let k=await u5({env:J,authPath:j.hostAuthPath}).inspect();if(k.slot==="placeholder"&&k.stash==="missing")throw new w5("missing-stash");if(Y.mode==="claustrum"){if(k.slot==="placeholder")return}}if($.includes("--remove-pi-auth")){B.set("pi",!0);return}let b=Y.mode==="claustrum"?"Pi has stored Anthropic authentication. Rerun with --remove-pi-auth to preserve it privately during vault use and restore it on disconnect.":"Pi has a stored Anthropic login. Rerun with --remove-pi-auth to move it into the native account pool.";if(G.includes("--yes")||!z.input.isTTY)throw new a(b);if(!await d1(z,Y.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(Y,j){let V=j0(K,Y);if(await p5(Y,J)!==(j?"claustrum":V.priorMode)||await Y1(Y,R(Y))!==V.fingerprint)throw new a("Setup inputs changed. Rerun setup with all hosts stopped.")}let N={packages:{opencode:M4,pi:F4},version:await B4(),displayName:"CortexKit Anthropic Auth",slashCommand:"/claude",vault:{connectionFile:s3(J.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE&&!J.OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE?"pi":"opencode",J),hosts:{opencode:{name:s0.opencode,paths:a3("opencode",J)},pi:{name:s0.pi,paths:a3("pi",J)}}},async beforeSignIn(Y,j){if(C=j.mode==="claustrum"?"setup-activation":"cli-setup",!P){l5(J);for(let V of j.hosts)F.set(V,await U0(V,J));if(await e$([...F.values()]),j.mode==="claustrum"){let V=j.hosts.map((g)=>s3(g,J)),b=V[0];if(new Set(V).size!==1||!b)throw new a("Selected hosts use different vault connection files.");N.vault.connectionFile=b}if(j.mode==="local"&&Q&&j.hosts.includes("opencode")&&j.opencodeGeneration==="2")throw new a(e1);if(j.mode==="local"){await t3(j.hosts,J);for(let V of j.hosts)await E0(V,D(V))()}await S(j);for(let V of j.hosts)if(j.mode==="claustrum"){if(K.set(V,await(Z.vaultPreflight??Y9)(V,{...R(V),inspectOpenCodeAuth:j.opencodeGeneration!=="2"})),j0(K,V).separateOpenCodeLogin)X(V4)}else q.set(V,await $2(V,D(V),V==="opencode"&&j.opencodeGeneration==="2"));P=!0}else if(j.mode==="claustrum")await y(Y,!1);else await n0(j0(q,Y),D(Y))},async signInLocal(Y){let j=j0(q,Y);if(!Q){if(j.generation2)X(e1);return}if(await n0(j,D(Y)),await U(Y,{...D(Y),login:Z.localLogin??j4,preflight:j.preflight,skipMigration:j.action==="skip",beforeCommit:()=>n0(j,D(Y))}),j.fingerprint=await y1(j,J),j.notice)X(o3)},async beforeRegister(Y,j){if(j==="local")await n0(j0(q,Y),D(Y));else await y(Y,!0),await(Z.vaultActivate??U9)(Y,R(Y),j0(K,Y)),j0(K,Y).fingerprint=await Y1(Y,R(Y))},async migrate(Y,j){if(j.mode==="claustrum"){if(await y(Y,!0),Y===j.hosts.at(-1)&&K.get("opencode")?.separateOpenCodeLogin)X(V4);return}let V=j0(q,Y);if(await n0(V,D(Y)),Q)return;if(V.action==="migration")await U(Y,{...D(Y),preflight:V.preflight});else if(V.action==="empty-init")await c5({paths:V.paths.paths,routingDestinationPath:V.paths.routingDestinationPath,env:J,processFence:E0(Y,D(Y))});else if(V.action==="skip"){if(await Z2(V,D(Y)),V.notice)X(o3)}V.fingerprint=await y1(V,J)}};try{return await a5(N,G,{...Z,env:J,terminal:z,runner:W,fence:H}),0}catch(Y){let V=Z9(Y)??K2(Y)??await q1(C,Y,J);if(V)X(V);for(let{host:b,outcome:g}of O9(Y)??[]){if(g!=="enrolled")continue;let k=b==="opencode"?"OpenCode":"Pi";X(`${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 Y of q.values())if(Y.preflight)d5(Y.preflight)}}async function e0($){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Native account changes require offline setup without OPENCODE_AUTH_CONTENT");let Z=await XZ(),J=o5({paths:Z,host:"opencode"});try{return await J.read(),await $(J)}finally{J.close()}}async function $3(){if(await zZ("opencode",process.env)!=="local")throw Error("Disconnect from the vault first.")}function N4(){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
|
+
${ZZ()}`)}function k2($,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(),X;try{X=JSON.parse(z)}catch{throw Error(`Cloudflare API returned ${J.status}: ${z}`)}if(!J.ok||X.success===!1){let G=X.errors?.map((Q)=>Q.message).filter(Boolean).join("; ");throw Error(G||`Cloudflare API returned ${J.status}`)}return X.result}async function QZ($,Z,J,z){return z3({token:$,method:"POST",path:`/accounts/${Z}/storage/kv/namespaces`,body:JSON.stringify({title:J}),fetchImpl:z})}async function WZ($){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([GZ],{type:"application/javascript+module"}),"worker.js"),z3({token:$.token,method:"PUT",path:`/accounts/${$.accountId}/workers/scripts/${$.scriptName}`,body:J,fetchImpl:$.fetchImpl})}async function HZ($,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 YZ($,Z,J){return z3({token:$,method:"GET",path:`/accounts/${Z}/workers/subdomain`,fetchImpl:J}).catch(()=>null)}async function UZ($={}){await e0((B)=>B.read());let Z=$.fetchImpl??fetch,J=$.prompt??J3,z=$.warn??((B)=>console.warn(B)),X=k2(process.env.CLOUDFLARE_API_TOKEN?.trim()||await J("Cloudflare API token: "),"Cloudflare API token");$.secrets?.push(X);let G=k2(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=$Z();$.secrets?.push(H),console.log("Creating Cloudflare KV namespace...");let U=await QZ(X,G,W,Z);console.log("Uploading relay Worker..."),await WZ({token:X,accountId:G,scriptName:Q,kvNamespaceId:U.id,relayToken:H,fetchImpl:Z}),await HZ(X,G,Q,Z).catch(async(B)=>{z(await q1("cli-relay-workers-dev",B,process.env,[X,H]))});let q=await YZ(X,G,Z),F=(q?.subdomain?`https://${Q}.${q.subdomain}.workers.dev`:"")||k2(await J3("Relay Worker URL: "),"Relay Worker URL");await e0((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??=i5({input:s5,output:n5}),(await Z3.question($)).trim()}function qZ(){Z3?.close(),Z3=null}async function KZ($,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??r5,X=Z.exchange??t5;await $3(),await e0(async(G)=>{let Q=await G.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
66
|
`);let U=await J("Paste the full callback URL or authorization code here: ");Z.secrets?.push(U);let q=await X(U,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 G.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
|
|
68
|
-
Saved API fallback route${z?` "${z}"`:""} (${X}).`)}async function
|
|
67
|
+
Saved native fallback account${W?` "${W}"`:""}.`)})}async function jZ($,Z={}){await $3(),await e0((H)=>H.read());let J=Z.prompt??J3,z=$?.trim()||await J("API fallback label (optional): "),X=process.env.OPENCODE_ANTHROPIC_AUTH_API_BASE_URL?.trim()||(await J("Anthropic-compatible base URL [https://api.kie.ai/claude]: ")).trim()||"https://api.kie.ai/claude";if(!JZ(X))throw Error("API fallback base URL must be an http(s) URL without embedded credentials");let G=process.env.OPENCODE_ANTHROPIC_AUTH_API_KEY?.trim()||await J("API key: ");if(!G.trim())throw Error("API key is required");Z.secrets?.push(G.trim());let W=(process.env.OPENCODE_ANTHROPIC_AUTH_API_AUTH_HEADER?.trim()||await J("Auth header [authorization-bearer|x-api-key] (default authorization-bearer): ")).trim().toLowerCase()==="x-api-key"?"x-api-key":"authorization-bearer";await e0(async(H)=>{await $3();let U=await H.read(),q=z&&z!=="main"?z:crypto.randomUUID(),K=U.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:G.trim(),baseURL:X,authHeader:W})}),console.log(`
|
|
68
|
+
Saved API fallback route${z?` "${z}"`:""} (${X}).`)}async function VZ(){await e0(async($)=>{let Z=(await $.read()).accounts.filter((J)=>J.id!=="main");if(!Z.length){console.log("No native fallback accounts found.");return}for(let[J,z]of Z.entries()){let X=z.label||z.id,G=z.enabled?"enabled":"disabled";if(z.type==="api"){console.log(`${J+1}. ${X} (${G}) — API route ${z.baseURL}`);continue}let Q=z.quota?.five_hour?.remainingPercent,W=z.quota?.seven_day?.remainingPercent,H=Q===void 0&&W===void 0?"quota unknown":`5h ${Q??"?"}%, 1w ${W??"?"}% remaining`;console.log(`${J+1}. ${X} (${G}) — ${H}${z.state?` — ${e5(z)}`:""}`)}})}async function MZ($){let[Z,J,z]=process.argv.slice(2);if(!Z||Z==="help"||Z==="--help"||Z==="-h"){N4();return}if(Z==="setup"){$.stage="cli-setup";let X=await D4(process.argv.slice(3));if(X!==0)process.exitCode=X;return}if(Z==="login"){$.stage="cli-login",await KZ(J,{secrets:$.secrets});return}if(Z==="api"&&J==="add"){$.stage="cli-api-add",await jZ(z,{secrets:$.secrets});return}if(Z==="list"){$.stage="cli-list",await VZ();return}if(Z==="relay"&&J==="setup"){$.stage="cli-relay-setup",await UZ({secrets:$.secrets});return}N4(),process.exitCode=1}if(U3.main==U3.module){let $={stage:"cli-command",secrets:[]};try{await MZ($)}catch(Z){console.error(await q1($.stage,Z,process.env,$.secrets)),process.exitCode=1}finally{qZ()}}export{D4 as runSetupCommand,UZ as relaySetup,KZ as login,jZ as addApiRoute};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/opencode-anthropic-auth",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.4",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -77,7 +77,7 @@
|
|
|
77
77
|
},
|
|
78
78
|
"dependencies": {
|
|
79
79
|
"@clack/prompts": "^1.6.0",
|
|
80
|
-
"@cortexkit/anthropic-auth-core": "2.2.
|
|
80
|
+
"@cortexkit/anthropic-auth-core": "2.2.4",
|
|
81
81
|
"@cortexkit/claustrum-client": "0.12.0",
|
|
82
82
|
"@cortexkit/private-files": "0.2.1",
|
|
83
83
|
"@cortexkit/subc-client": "^0.22.0",
|