@cortexkit/opencode-anthropic-auth 2.2.7 → 2.2.8
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 +1 -1
- package/dist/index-0jd4jg49.js +43 -0
- package/dist/{index-62x1p34p.js → index-71temqvq.js} +1 -1
- package/dist/{index-ppdrzs41.js → index-bcp23wwb.js} +1 -1
- package/dist/{index-hazrk5c3.js → index-c8ehrd0p.js} +1 -1
- package/dist/{index-20d6rmjj.js → index-j6x60aqq.js} +1 -1
- package/dist/{index-0kxy8k2c.js → index-m4dazzyf.js} +1 -1
- package/dist/{index-b1dvkp15.js → index-naff9h33.js} +1 -1
- package/dist/{index-jvhs8sxv.js → index-nm4pjrt8.js} +2 -2
- package/dist/{index-6chd6jnr.js → index-sg0knfec.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/oauth-destination.d.ts +35 -0
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/adapter.d.ts +5 -4
- package/dist/v2/server.js +9 -9
- package/dist/v2/tui.js +1 -1
- package/package.json +2 -2
- package/dist/index-cjjjgewq.js +0 -43
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{x as $3}from"./index-0kxy8k2c.js";import{A as D4,B as o$,C as t$,D as e$,E as $9,F as L4,z as B4}from"./index-b1dvkp15.js";import{ha as G4,ia as M5,ja as q3}from"./index-62x1p34p.js";var I2=M5((oH,J4)=>{var _2={to($,Z){if(!Z)return`\x1B[${$+1}G`;return`\x1B[${Z+1};${$+1}H`},move($,Z){let J="";if($<0)J+=`\x1B[${-$}D`;else if($>0)J+=`\x1B[${$}C`;if(Z<0)J+=`\x1B[${-Z}A`;else if(Z>0)J+=`\x1B[${Z}B`;return J},up:($=1)=>`\x1B[${$}A`,down:($=1)=>`\x1B[${$}B`,forward:($=1)=>`\x1B[${$}C`,backward:($=1)=>`\x1B[${$}D`,nextLine:($=1)=>"\x1B[E".repeat($),prevLine:($=1)=>"\x1B[F".repeat($),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},V5={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},F5={screen:"\x1B[2J",up:($=1)=>"\x1B[1J".repeat($),down:($=1)=>"\x1B[J".repeat($),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines($){let Z="";for(let J=0;J<$;J++)Z+=this.line+(J<$-1?_2.up():"");if($)Z+=_2.left;return Z}};J4.exports={cursor:_2,scroll:V5,erase:F5,beep:"\x07"}});import{stdin as r5,stdout as o5}from"node:process";import{createInterface as t5}from"node:readline/promises";import{authorize as e5,createNativeAccountRuntime as $Z,exchange as ZZ,formatNativeAccountState as JZ,generateRelayToken as zZ,getAccountStoragePath as XZ,isValidApiBaseURL as GZ,readNativeEnrollmentMode as QZ,resolveNativePoolPaths as WZ,WORKER_SCRIPT as HZ}from"@cortexkit/anthropic-auth-core";import{randomUUID as y8}from"node:crypto";import{constants as v1}from"node:fs";import{lstat as h8,mkdir as v8,open as m8}from"node:fs/promises";import{homedir as w8}from"node:os";import{isAbsolute as j9,join as H2}from"node:path";import{types as U2}from"node:util";import{createProviderErrorRedactor as B9,createWindowsOwnerOnly as u8,ensureWindowsOwnerOnlyDirectory as c8,formatLogLine as p8,isOwnerOnly as d8,isSecretKey as l8,NativeMigrationError as a8,NativePiAuthSlotError as s8,PRIVATE_FILES_UNAVAILABLE_MESSAGE as D9,setupEnrollment as n8}from"@cortexkit/anthropic-auth-core";import{readFile as I8}from"node:fs/promises";import{assertHostsStopped as A8,createNativeAccountRuntime as R8,discoverNativeVaultInventory as S8,inspectNativeHostAuthEntry as z2,NativePiAuthSlotError as b8,nativePiAuthSlotPaths as k8,openNativePiAuthSlot as G2,readNativeEnrollmentMode as T8,requireNoSupervisedAuthContentSnapshot as E8}from"@cortexkit/anthropic-auth-core";import{dirname as $8}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as Z8,CLAUSTRUM_PI_ENROLLMENT_NAME as J8,getHostClaustrumEnrollmentPaths as a$,resolveClaustrumConnectionPath as z8}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as AX}from"@cortexkit/claustrum-client";import{ClaustrumClient as WX}from"@cortexkit/claustrum-client";import{resolve as f2}from"node:path";import{storeIdentity as RZ}from"@cortexkit/claustrum-client";import{SubcClient as bZ}from"@cortexkit/subc-client";import{ClaustrumCredentialError as P4}from"@cortexkit/claustrum-client";import{SocketClosedError as O4,SocketTimeoutError as _4,SubcCallError as I4}from"@cortexkit/subc-client";class _ extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var G3=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class P0 extends _{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function M0($){if($ instanceof P0||$ instanceof O4||$ instanceof _4)return"unreachable";let Z=$ instanceof P4||$ instanceof I4?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(G3,Z))return"answered";return G3[Z]}var Q3=300000,D1=300000,W3=1000;class Z1{#$;#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;#J;#X=!1;constructor($,Z){this.#$=$,this.#z=Z}get running(){return this.#J}request(){if(this.#J)return this.#X=!0,this.#J;return this.#J=(async()=>{do{this.#X=!1;try{await this.#$()}catch($){this.#z($)}}while(this.#X)})().finally(()=>{this.#J=void 0}),this.#J}}class N1{#$;#z=new Z1;#J;#X="polling";#H;#G;#Z=!1;#Y;#K=!1;#W=0;constructor($){this.#$=$,this.#J=new L1(async()=>{let Z=this.#K;if(this.#K=!1,Z||this.#Y!==this.#$.view())await this.#$.discover(this.#Y??"")},(Z)=>{if(!this.#Z)this.#$.onError?.(Z)})}get mode(){return this.#X}start(){if(this.#Z||this.#H||this.#G)return;if(typeof this.#$.client.watchScoped!=="function"){this.#Q("fallback","client-without-watch");return}this.#M(!1)}stop(){if(this.#Z)return;if(this.#Z=!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.#Z)Z()},$),this.#G.unref?.()}async#M($){let Z;try{Z=await this.#$.enrollmentToken()}catch(Q){if(this.#Z)return;this.#$.onError?.(Q),this.#F("token-unreadable");return}let J=this.#$.client.watchScoped;if(this.#Z||this.#H||!J)return;this.#z.restart(),this.#K=$;let z,X;try{X=J.call(this.#$.client,(Q)=>{if(this.#Z||!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.#K=!0;this.#Y=Q.view,this.#J.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.#Z||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.#M(!0));return}this.#F(Z.kind)}#F($){this.#Q("fallback",$),this.#U(300000,()=>void this.#M(!1))}}var P1=60000,g2=4*P1,A4=2*P1,H3=new Map,C1=new Map;function J1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function R4($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!J1(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 S4($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class x2{transport;key;#$=[];#z=!1;#J=new Set;#X=new Map;#H=new L1(async()=>{try{let $=await this.transport.getUsage();if(!J1($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>J1(Z)&&typeof Z.provider==="string"),this.#z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#J=new Set(this.#z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#J)this.#X.delete(Z)}catch{this.#$=[],this.#z=!1,this.#J.clear()}},()=>{});#G=new Z1;#Z="polling";#Y=0;#K=0;#W=new Map;#Q;#U;#M={};#j=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#H.running)return this.#H.running;if(this.#Z==="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.#Z}watch($={}){this.#Y++;let Z=$.provider;if(Z===void 0)this.#K++;else this.#W.set(Z,(this.#W.get(Z)??0)+1);if(this.#Y===1)this.#M=$,this.#q();let J=!1;return()=>{if(J)return;if(J=!0,Z===void 0)this.#K--;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.#M.clearTimeoutImpl??clearTimeout)(this.#U);this.#U=void 0;let $=this.#Q;this.#Q=void 0,$?.handle?.stop(),this.#Z="polling"}#V($){this.#U=(this.#M.setTimeoutImpl??setTimeout)(()=>{if(this.#U=void 0,this.#Y>0&&!this.#Q)this.#q()},$),this.#U.unref?.()}#q(){let $=this.transport.watchUsage;if(!$){this.#Z="fallback";return}this.#Z="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.#Z="watching";if($.notices===2)this.#j=0;let J=R4(Z);if(!J)this.#G.restart();if(!(J?this.#G.continuous(J):!1)||J?.provider===void 0||this.#K>0||this.#W.has(J.provider))this.#H.request()}#D($,Z){if(this.#Q!==$)return;this.#Q=void 0;let J=S4(Z);if(J==="unknown_method"||J==="usage_watch_limit"){this.#Z="fallback";return}if($.notices>0){let z=Math.min(W3*2**Math.min(this.#j,16),D1);this.#j++,this.#Z="polling",this.#V(z);return}if(this.#Z="fallback",this.#H.request(),Z===void 0||M0(Z)==="unreachable")this.#V(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||!J1(z.usage))continue;let X=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(X)||J-X>=g2)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(!J1(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+g2||z.stale!==void 0?{miss:"stale",reading:W}:{reading:W}}if(this.#J.has($))return{miss:"absent"};let G=this.#X.get($)??J;return this.#X.set($,G),{miss:J-G>=A4?"unreachable":"cold"}}}function Y3($,Z){let J=JSON.stringify([f2($.connectionFile),f2(Z)]),z=H3.get(J);if(!z)z={source:new x2($,J),refs:0},H3.set(J,z);z.refs++;let X=!1;return{source:z.source,release(){if(X)return;if(X=!0,--z.refs===0)H3.delete(J)}}}import{ClaustrumCredentialError as qX}from"@cortexkit/claustrum-client";import{appendFileSync as u4,chmodSync as c4,existsSync as j3,renameSync as a2,statSync as p4}from"node:fs";import{open as d4}from"node:fs/promises";import{dirname as l4,resolve as a4}from"node:path";import{randomUUID as m2}from"node:crypto";import{lstat as w2,readFile as u2,rename as b4,unlink as y2}from"node:fs/promises";import{tmpdir as k4}from"node:os";import{dirname as V0,join as T4,resolve as i}from"node:path";var I=process.platform==="win32",h2=new Set;function U3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var v2;var c2="native-addon-unavailable";function p2($){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:$}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:c2})}function E4($,Z){return Z instanceof $.PrivateFilesUnavailableError||Z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function f4($){try{await $.verifyPrivatePath(T4(k4(),`.common-auth-private-files-probe-${m2()}`),"file")}catch(Z){if(E4($,Z))throw p2(Z)}}function m0(){return v2??=import("@cortexkit/private-files").then(async($)=>{if(I)await f4($);return $},($)=>{throw I?p2($):$}),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}: ${$} (${c2}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`:`Private file refused at ${Z}: ${$} (${z?.reason??z?.code??"io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`,{cause:J});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=U3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}async function s($,Z,J){try{return await J()}catch(z){if(z instanceof u)throw z;throw new u($,Z,z)}}var g4;async function W0($,Z){$=i($),Z??=g4,await s($,"safe-parent",async()=>{let J=await(await m0()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await w2($);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 W0($);await s($,"verify",async()=>{let z=await m0(),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 W0(V0($)),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&&!h2.has($))h2.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function z0($,Z=!1,J){$=i($),await s($,"directory",async()=>{let z=await m0();try{return await w2($),await W0($,J)}catch(G){if(U3(G)!=="ENOENT")throw G}let X=V0($);if(X===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await z0(X,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(U3(G)!=="EEXIST")throw G}await W0($,J)})}async function e($,Z=!1){if(!I)return u2($,"utf8");return(await x4($,Z)).toString("utf8")}async function x4($,Z=!1){if(!I)return u2($);if($=i($),Z)await W0(V0($)),await p($,"file",!0);return s($,"read",async()=>(await m0()).readOwnerOnly($))}async function w0($,Z){await W0(V0(i($))),await s($,"create",async()=>{await(await m0()).createPrivateFile(i($),Z)})}async function d2($){await W0(V0(i($))),await s($,"directory-create",async()=>{await(await m0()).createOwnerOnly(i($),{kind:"dir"})})}async function K3($,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 B=Math.min(Q??1/0,G);if(z()>=B)break;if(K)await(J.sleep??((P)=>new Promise((C)=>setTimeout(C,P))))(Math.min(K,Math.max(0,B-z())));if(z()>=B)break;let F=z();if(await J.beforeRename?.(),Q!==void 0)Q+=z()-F;if(z()>=G)break;U++;try{return await(J.rename??b4)($,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 u0($,Z,J={}){$=i($),await z0(V0($));try{await p($,"file",!0)}catch(U){if(U.code!=="ENOENT")throw U}let z=i(J.stagePath??`${$}.${m2()}.tmp`);if(V0(z)!==V0($))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 w0(z,Z),X=!0,W="before-rename",Q=await K3(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 y2(z)}catch{q.orphanPath=z}X=!1}throw H(q),q}finally{if(X)await y2(z).catch(()=>{})}}var y4=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,h4=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function v4($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function c0($={}){let Z=[h4,...$.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 y4.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=v4(G);if(U&&H>=8)return"[Truncated]";let q=U?H+1:H;return Object.fromEntries((U?z(G):Object.entries(G)).map(([K,B])=>[K,Q&&J(K)?"***REDACTED***":X(B,Q,W,q)]))}finally{W.delete(G)}}return{redact:(G)=>X(G,!0,new WeakSet),redactStrings:(G)=>X(G,!1,new WeakSet)}}var l2=c0(),m4=l2.redact,w4=l2.redactStrings;var O1={error:0,warn:1,info:2,debug:3,trace:4},n2=5242880,i2=3;function M3($){try{c4($,384)}catch{}}function s4($){try{if(!(j3($)&&p4($).size>=n2))return;for(let J=i2-1;J>=1;J--)if(j3(`${$}.${J}`)){let z=`${$}.${J+1}`;a2(`${$}.${J}`,z),M3(z)}let Z=`${$}.1`;a2($,Z),M3(Z)}catch{}}async function H0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await s(Z,"log-close",()=>J.close())}async function s2($,Z){await z0(l4(Z));try{await p(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await w0(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await p(Z,"file",!0)}}return $.handle=await s(Z,"log-open",()=>d4(Z,"a")),$.file=Z,$.handle}async function n4($,Z,J){Z=a4(Z);try{if($.file!==Z)await H0($);let z=$.handle??await s2($,Z);if((await s(Z,"log-stat",()=>z.stat())).size>=n2){await H0($);for(let G=i2-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 K3(Q,W),await p(W,"file")}z=await s2($,Z)}await s(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await H0($).catch(()=>{}),z}}function i4($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function r4($){let Z,J,z,X=c0(),G,Q=[],W,H=Promise.resolve(),U,q={};function K(Y){let j=H.then(Y);return H=j.catch((M)=>{U=M}),j}function B(Y){if(I&&Y.file!==Z)K(()=>H0(q)).catch(()=>{});Z=Y.file,J=Y.level,X=c0(Y),G=Y.captureSink}function F(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(I)return K(async()=>{if(Y)await H0(q);if(U)throw U});return}let j;try{j=P()}catch{if(Q=[],I&&Y)return K(()=>H0(q));return}let M=Q.join("");if(Q=[],!j){if(I&&Y)return K(()=>H0(q));return}if(I)return K(async()=>{try{await n4(q,j,M)}finally{if(Y)await H0(q)}});try{if(s4(j),j3(j))M3(j);u4(j,M,{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,M,b){if(Z===void 0&&G===void 0)return;try{if(O1[j]>O1[C()])return;let x=X.redactStrings(M),k;try{k=X.redact(b)}catch{k="[unserializable]"}let m=`[${new Date().toISOString()}] ${j.toUpperCase()} [${Y}] ${x}`+(b===void 0?"":i4(k))+`
|
|
2
|
+
import{y as $3}from"./index-m4dazzyf.js";import{A as B4,B as D4,C as o$,D as t$,E as e$,F as $9,G as L4}from"./index-naff9h33.js";import{ia as G4,ja as M5,ka as q3}from"./index-71temqvq.js";var I2=M5((oH,J4)=>{var _2={to($,Z){if(!Z)return`\x1B[${$+1}G`;return`\x1B[${Z+1};${$+1}H`},move($,Z){let J="";if($<0)J+=`\x1B[${-$}D`;else if($>0)J+=`\x1B[${$}C`;if(Z<0)J+=`\x1B[${-Z}A`;else if(Z>0)J+=`\x1B[${Z}B`;return J},up:($=1)=>`\x1B[${$}A`,down:($=1)=>`\x1B[${$}B`,forward:($=1)=>`\x1B[${$}C`,backward:($=1)=>`\x1B[${$}D`,nextLine:($=1)=>"\x1B[E".repeat($),prevLine:($=1)=>"\x1B[F".repeat($),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},V5={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},F5={screen:"\x1B[2J",up:($=1)=>"\x1B[1J".repeat($),down:($=1)=>"\x1B[J".repeat($),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines($){let Z="";for(let J=0;J<$;J++)Z+=this.line+(J<$-1?_2.up():"");if($)Z+=_2.left;return Z}};J4.exports={cursor:_2,scroll:V5,erase:F5,beep:"\x07"}});import{stdin as r5,stdout as o5}from"node:process";import{createInterface as t5}from"node:readline/promises";import{authorize as e5,createNativeAccountRuntime as $Z,exchange as ZZ,formatNativeAccountState as JZ,generateRelayToken as zZ,getAccountStoragePath as XZ,isValidApiBaseURL as GZ,readNativeEnrollmentMode as QZ,resolveNativePoolPaths as WZ,WORKER_SCRIPT as HZ}from"@cortexkit/anthropic-auth-core";import{randomUUID as y8}from"node:crypto";import{constants as v1}from"node:fs";import{lstat as h8,mkdir as v8,open as m8}from"node:fs/promises";import{homedir as w8}from"node:os";import{isAbsolute as j9,join as H2}from"node:path";import{types as U2}from"node:util";import{createProviderErrorRedactor as B9,createWindowsOwnerOnly as u8,ensureWindowsOwnerOnlyDirectory as c8,formatLogLine as p8,isOwnerOnly as d8,isSecretKey as l8,NativeMigrationError as a8,NativePiAuthSlotError as s8,PRIVATE_FILES_UNAVAILABLE_MESSAGE as D9,setupEnrollment as n8}from"@cortexkit/anthropic-auth-core";import{readFile as I8}from"node:fs/promises";import{assertHostsStopped as A8,createNativeAccountRuntime as R8,discoverNativeVaultInventory as S8,inspectNativeHostAuthEntry as z2,NativePiAuthSlotError as b8,nativePiAuthSlotPaths as k8,openNativePiAuthSlot as G2,readNativeEnrollmentMode as T8,requireNoSupervisedAuthContentSnapshot as E8}from"@cortexkit/anthropic-auth-core";import{dirname as $8}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as Z8,CLAUSTRUM_PI_ENROLLMENT_NAME as J8,getHostClaustrumEnrollmentPaths as a$,resolveClaustrumConnectionPath as z8}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as AX}from"@cortexkit/claustrum-client";import{ClaustrumClient as WX}from"@cortexkit/claustrum-client";import{resolve as f2}from"node:path";import{storeIdentity as RZ}from"@cortexkit/claustrum-client";import{SubcClient as bZ}from"@cortexkit/subc-client";import{ClaustrumCredentialError as P4}from"@cortexkit/claustrum-client";import{SocketClosedError as O4,SocketTimeoutError as _4,SubcCallError as I4}from"@cortexkit/subc-client";class _ extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var G3=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class P0 extends _{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function M0($){if($ instanceof P0||$ instanceof O4||$ instanceof _4)return"unreachable";let Z=$ instanceof P4||$ instanceof I4?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(G3,Z))return"answered";return G3[Z]}var Q3=300000,D1=300000,W3=1000;class Z1{#$;#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;#J;#X=!1;constructor($,Z){this.#$=$,this.#z=Z}get running(){return this.#J}request(){if(this.#J)return this.#X=!0,this.#J;return this.#J=(async()=>{do{this.#X=!1;try{await this.#$()}catch($){this.#z($)}}while(this.#X)})().finally(()=>{this.#J=void 0}),this.#J}}class N1{#$;#z=new Z1;#J;#X="polling";#H;#G;#Z=!1;#Y;#K=!1;#W=0;constructor($){this.#$=$,this.#J=new L1(async()=>{let Z=this.#K;if(this.#K=!1,Z||this.#Y!==this.#$.view())await this.#$.discover(this.#Y??"")},(Z)=>{if(!this.#Z)this.#$.onError?.(Z)})}get mode(){return this.#X}start(){if(this.#Z||this.#H||this.#G)return;if(typeof this.#$.client.watchScoped!=="function"){this.#Q("fallback","client-without-watch");return}this.#M(!1)}stop(){if(this.#Z)return;if(this.#Z=!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.#Z)Z()},$),this.#G.unref?.()}async#M($){let Z;try{Z=await this.#$.enrollmentToken()}catch(Q){if(this.#Z)return;this.#$.onError?.(Q),this.#F("token-unreadable");return}let J=this.#$.client.watchScoped;if(this.#Z||this.#H||!J)return;this.#z.restart(),this.#K=$;let z,X;try{X=J.call(this.#$.client,(Q)=>{if(this.#Z||!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.#K=!0;this.#Y=Q.view,this.#J.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.#Z||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.#M(!0));return}this.#F(Z.kind)}#F($){this.#Q("fallback",$),this.#U(300000,()=>void this.#M(!1))}}var P1=60000,g2=4*P1,A4=2*P1,H3=new Map,C1=new Map;function J1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function R4($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!J1(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 S4($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class x2{transport;key;#$=[];#z=!1;#J=new Set;#X=new Map;#H=new L1(async()=>{try{let $=await this.transport.getUsage();if(!J1($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>J1(Z)&&typeof Z.provider==="string"),this.#z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#J=new Set(this.#z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#J)this.#X.delete(Z)}catch{this.#$=[],this.#z=!1,this.#J.clear()}},()=>{});#G=new Z1;#Z="polling";#Y=0;#K=0;#W=new Map;#Q;#U;#M={};#j=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#H.running)return this.#H.running;if(this.#Z==="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.#Z}watch($={}){this.#Y++;let Z=$.provider;if(Z===void 0)this.#K++;else this.#W.set(Z,(this.#W.get(Z)??0)+1);if(this.#Y===1)this.#M=$,this.#q();let J=!1;return()=>{if(J)return;if(J=!0,Z===void 0)this.#K--;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.#M.clearTimeoutImpl??clearTimeout)(this.#U);this.#U=void 0;let $=this.#Q;this.#Q=void 0,$?.handle?.stop(),this.#Z="polling"}#V($){this.#U=(this.#M.setTimeoutImpl??setTimeout)(()=>{if(this.#U=void 0,this.#Y>0&&!this.#Q)this.#q()},$),this.#U.unref?.()}#q(){let $=this.transport.watchUsage;if(!$){this.#Z="fallback";return}this.#Z="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.#Z="watching";if($.notices===2)this.#j=0;let J=R4(Z);if(!J)this.#G.restart();if(!(J?this.#G.continuous(J):!1)||J?.provider===void 0||this.#K>0||this.#W.has(J.provider))this.#H.request()}#D($,Z){if(this.#Q!==$)return;this.#Q=void 0;let J=S4(Z);if(J==="unknown_method"||J==="usage_watch_limit"){this.#Z="fallback";return}if($.notices>0){let z=Math.min(W3*2**Math.min(this.#j,16),D1);this.#j++,this.#Z="polling",this.#V(z);return}if(this.#Z="fallback",this.#H.request(),Z===void 0||M0(Z)==="unreachable")this.#V(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||!J1(z.usage))continue;let X=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(X)||J-X>=g2)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(!J1(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+g2||z.stale!==void 0?{miss:"stale",reading:W}:{reading:W}}if(this.#J.has($))return{miss:"absent"};let G=this.#X.get($)??J;return this.#X.set($,G),{miss:J-G>=A4?"unreachable":"cold"}}}function Y3($,Z){let J=JSON.stringify([f2($.connectionFile),f2(Z)]),z=H3.get(J);if(!z)z={source:new x2($,J),refs:0},H3.set(J,z);z.refs++;let X=!1;return{source:z.source,release(){if(X)return;if(X=!0,--z.refs===0)H3.delete(J)}}}import{ClaustrumCredentialError as qX}from"@cortexkit/claustrum-client";import{appendFileSync as u4,chmodSync as c4,existsSync as j3,renameSync as a2,statSync as p4}from"node:fs";import{open as d4}from"node:fs/promises";import{dirname as l4,resolve as a4}from"node:path";import{randomUUID as m2}from"node:crypto";import{lstat as w2,readFile as u2,rename as b4,unlink as y2}from"node:fs/promises";import{tmpdir as k4}from"node:os";import{dirname as V0,join as T4,resolve as i}from"node:path";var I=process.platform==="win32",h2=new Set;function U3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var v2;var c2="native-addon-unavailable";function p2($){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:$}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:c2})}function E4($,Z){return Z instanceof $.PrivateFilesUnavailableError||Z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function f4($){try{await $.verifyPrivatePath(T4(k4(),`.common-auth-private-files-probe-${m2()}`),"file")}catch(Z){if(E4($,Z))throw p2(Z)}}function m0(){return v2??=import("@cortexkit/private-files").then(async($)=>{if(I)await f4($);return $},($)=>{throw I?p2($):$}),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}: ${$} (${c2}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`:`Private file refused at ${Z}: ${$} (${z?.reason??z?.code??"io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`,{cause:J});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=U3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}async function s($,Z,J){try{return await J()}catch(z){if(z instanceof u)throw z;throw new u($,Z,z)}}var g4;async function W0($,Z){$=i($),Z??=g4,await s($,"safe-parent",async()=>{let J=await(await m0()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await w2($);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 W0($);await s($,"verify",async()=>{let z=await m0(),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 W0(V0($)),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&&!h2.has($))h2.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function z0($,Z=!1,J){$=i($),await s($,"directory",async()=>{let z=await m0();try{return await w2($),await W0($,J)}catch(G){if(U3(G)!=="ENOENT")throw G}let X=V0($);if(X===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await z0(X,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(U3(G)!=="EEXIST")throw G}await W0($,J)})}async function e($,Z=!1){if(!I)return u2($,"utf8");return(await x4($,Z)).toString("utf8")}async function x4($,Z=!1){if(!I)return u2($);if($=i($),Z)await W0(V0($)),await p($,"file",!0);return s($,"read",async()=>(await m0()).readOwnerOnly($))}async function w0($,Z){await W0(V0(i($))),await s($,"create",async()=>{await(await m0()).createPrivateFile(i($),Z)})}async function d2($){await W0(V0(i($))),await s($,"directory-create",async()=>{await(await m0()).createOwnerOnly(i($),{kind:"dir"})})}async function K3($,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 B=Math.min(Q??1/0,G);if(z()>=B)break;if(K)await(J.sleep??((P)=>new Promise((C)=>setTimeout(C,P))))(Math.min(K,Math.max(0,B-z())));if(z()>=B)break;let F=z();if(await J.beforeRename?.(),Q!==void 0)Q+=z()-F;if(z()>=G)break;U++;try{return await(J.rename??b4)($,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 u0($,Z,J={}){$=i($),await z0(V0($));try{await p($,"file",!0)}catch(U){if(U.code!=="ENOENT")throw U}let z=i(J.stagePath??`${$}.${m2()}.tmp`);if(V0(z)!==V0($))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 w0(z,Z),X=!0,W="before-rename",Q=await K3(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 y2(z)}catch{q.orphanPath=z}X=!1}throw H(q),q}finally{if(X)await y2(z).catch(()=>{})}}var y4=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,h4=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function v4($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function c0($={}){let Z=[h4,...$.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 y4.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=v4(G);if(U&&H>=8)return"[Truncated]";let q=U?H+1:H;return Object.fromEntries((U?z(G):Object.entries(G)).map(([K,B])=>[K,Q&&J(K)?"***REDACTED***":X(B,Q,W,q)]))}finally{W.delete(G)}}return{redact:(G)=>X(G,!0,new WeakSet),redactStrings:(G)=>X(G,!1,new WeakSet)}}var l2=c0(),m4=l2.redact,w4=l2.redactStrings;var O1={error:0,warn:1,info:2,debug:3,trace:4},n2=5242880,i2=3;function M3($){try{c4($,384)}catch{}}function s4($){try{if(!(j3($)&&p4($).size>=n2))return;for(let J=i2-1;J>=1;J--)if(j3(`${$}.${J}`)){let z=`${$}.${J+1}`;a2(`${$}.${J}`,z),M3(z)}let Z=`${$}.1`;a2($,Z),M3(Z)}catch{}}async function H0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await s(Z,"log-close",()=>J.close())}async function s2($,Z){await z0(l4(Z));try{await p(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await w0(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await p(Z,"file",!0)}}return $.handle=await s(Z,"log-open",()=>d4(Z,"a")),$.file=Z,$.handle}async function n4($,Z,J){Z=a4(Z);try{if($.file!==Z)await H0($);let z=$.handle??await s2($,Z);if((await s(Z,"log-stat",()=>z.stat())).size>=n2){await H0($);for(let G=i2-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 K3(Q,W),await p(W,"file")}z=await s2($,Z)}await s(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await H0($).catch(()=>{}),z}}function i4($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function r4($){let Z,J,z,X=c0(),G,Q=[],W,H=Promise.resolve(),U,q={};function K(Y){let j=H.then(Y);return H=j.catch((M)=>{U=M}),j}function B(Y){if(I&&Y.file!==Z)K(()=>H0(q)).catch(()=>{});Z=Y.file,J=Y.level,X=c0(Y),G=Y.captureSink}function F(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(I)return K(async()=>{if(Y)await H0(q);if(U)throw U});return}let j;try{j=P()}catch{if(Q=[],I&&Y)return K(()=>H0(q));return}let M=Q.join("");if(Q=[],!j){if(I&&Y)return K(()=>H0(q));return}if(I)return K(async()=>{try{await n4(q,j,M)}finally{if(Y)await H0(q)}});try{if(s4(j),j3(j))M3(j);u4(j,M,{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,M,b){if(Z===void 0&&G===void 0)return;try{if(O1[j]>O1[C()])return;let x=X.redactStrings(M),k;try{k=X.redact(b)}catch{k="[unserializable]"}let m=`[${new Date().toISOString()}] ${j.toUpperCase()} [${Y}] ${x}`+(b===void 0?"":i4(k))+`
|
|
3
3
|
`;try{G?.({channel:Y,level:j,message:x,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 h(Y){return{error:(j,M)=>S(Y,"error",j,M),warn:(j,M)=>S(Y,"warn",j,M),info:(j,M)=>S(Y,"info",j,M),debug:(j,M)=>S(Y,"debug",j,M),trace:(j,M)=>S(Y,"trace",j,M)}}function L(){if(I)K(()=>H0(q)).catch(()=>{});if(U=void 0,Q=[],W)clearTimeout(W),W=void 0;Z=void 0,J=void 0,z=void 0,X=c0(),G=void 0}if($)B($);return{configure:B,createLogger:h,setLogLevel:F,flushLogs:D,reset:L}}var o4=r4();function O0($){return o4.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 O$}from"@cortexkit/claustrum-client";import{createHash as G7,randomBytes as Q7,randomUUID as W7}from"node:crypto";import{constants as H$}from"node:fs";import{chmod as H7,mkdir as Y7,open as q$,readFile as L3,realpath as U7,rename as q7,stat as K$,unlink as C3}from"node:fs/promises";import{basename as K7,dirname as R0,extname as SJ,isAbsolute as bJ,join as j7,resolve as kJ}from"node:path";import{ClaustrumCredentialError as M7,ClaustrumClient as EJ,writeEnrollmentTokenFile as V7}from"@cortexkit/claustrum-client";import{randomUUID as r2}from"node:crypto";import{mkdir as t4,open as o2,rename as e4,rm as $7}from"node:fs/promises";import{dirname as t2}from"node:path";class _1 extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function z1($,Z,J={}){await e2($,Z,J)}async function e2($,Z,J,z){if(I)return u0($,J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
4
4
|
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??r2)()}.tmp`,onRenamed:z,durable:J.durable,durability:J.durability,onOutcome:J.onOutcome});await t4(t2($),{recursive:!0});let X=`${$}.${(J.stageName??r2)()}.tmp`,G,Q=!1;try{if(G=await o2(X,"wx",384),Q=!0,await G.writeFile(J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
5
5
|
`,"utf8"),await G.chmod(384),J.durable)try{await G.sync()}catch(W){throw new _1(W)}if(await G.close(),G=void 0,await J.beforeRename?.(),await e4(X,$),Q=!1,z?.(),J.durable){let W=await o2(t2($),"r");try{await W.sync()}catch(H){throw new _1(H)}finally{await W.close()}}}finally{if(await G?.close().catch(()=>{}),Q)await $7(X,{force:!0}).catch(()=>{})}}var Z7=Object.freeze({sidebar:Object.freeze({name:"sidebar-write",ttlMs:1e4,timeoutMs:15000,renew:!0}),preferences:Object.freeze({name:"preferences",ttlMs:1e4,timeoutMs:2000,renew:!0})});import{randomUUID as I1}from"node:crypto";import{mkdir as $$,open as Q$,readFile as Z$,rename as J$,rm as A1,stat as z$}from"node:fs/promises";import{dirname as D3,join as X$}from"node:path";function F3($,Z){return`${$}.${Z}.lock`}class _0 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class I0 extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function B3($,Z,J){let z=performance.now();for(;;){Z.signal?.throwIfAborted();let X=await Y0({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 _0({target:$,name:Z.name,timeoutMs:Z.timeoutMs});await new Promise((Q)=>setTimeout(Q,Math.min(25,Math.ceil(G))))}}async function G$($,Z){let J=await Q$($,"wx",384);try{await J.writeFile(Z,"utf8")}finally{await J.close()}}var J7=globalThis.setTimeout.bind(globalThis),z7=globalThis.clearTimeout.bind(globalThis);function W$($){let Z=$?.code;return Z==="ENOENT"||!I&&(Z==="EINVAL"||Z==="ENOTDIR")}function Y0($){return X7({...$,now:Date.now})}async function X7($){let Z=F3($.path,$.name),J=X$(Z,"owner.json"),z=I1(),X=$.now??Date.now,G=null,Q=!1,W=!1,H,U,q=new Promise((V)=>{U=V});function K(V){try{let N=$.onRenewalTimer?.(V);if(N&&(typeof N==="object"||typeof N==="function")&&"then"in N&&typeof N.then==="function")Promise.resolve(N).catch(()=>{})}catch{}}function B(){if(!G)return;z7(G),G=null,K("cancelled")}function F(V,N){if(H||Q)return;H=Object.freeze({reason:V,expectedOwnerId:z,...typeof N?.ownerId==="string"?{observedOwnerId:N.ownerId}:{},...typeof N?.expiresAt==="number"?{observedExpiresAt:N.expiresAt}:{}}),B(),U(H)}let P,C=null,D=`${Z}.evicting`,R=X$(D,"owner.json"),S=I1(),h=5000,L=8;async function Y(){if(I)try{return JSON.parse(await e(Z,!0))}catch(V){if(V.code!=="EISDIR"&&V.reason!=="wrong-kind")throw V;return await p(Z,"directory",!0),JSON.parse(await e(J,!0))}try{return JSON.parse(await Z$(Z,"utf8"))}catch(V){if(V.code!=="EISDIR")throw V;return JSON.parse(await Z$(J,"utf8"))}}async function j(){if(I){let y=await Y(),w=Number(y?.expiresAt)-X();await u0(Z,`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|