@cortexkit/opencode-anthropic-auth 2.12.0 → 2.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +4 -4
- package/dist/index-e91y2kqv.js +47 -0
- package/dist/index.js +1 -1
- package/dist/oauth-destination.d.ts +35 -12
- package/dist/transform.d.ts +2 -1
- package/dist/v2/adapter.d.ts +12 -2
- package/dist/v2/server.js +11 -11
- package/package.json +2 -2
- package/dist/index-z31s2mjs.js +0 -47
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{C as m3}from"./index-gqxrgdvk.js";import{E as i4,F as o4,G as I7,H as R7,I as S7,J as T7,K as r4}from"./index-427t44z7.js";import{ma as x4,na as lJ,oa as r3}from"./index-dpxaxyck.js";var P$=lJ((jF,E4)=>{var L$={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"},aJ={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},sJ={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?L$.up():"");if($)Z+=L$.left;return Z}};E4.exports={cursor:L$,scroll:aJ,erase:sJ,beep:"\x07"}});import{stdin as gz,stdout as wz}from"node:process";import{createInterface as mz}from"node:readline/promises";import{authorize as hz,createNativeAccountRuntime as uz,decideOpenCodeStateLayoutOnce as cz,exchange as pz,formatNativeAccountState as dz,generateRelayToken as lz,getAccountStoragePath as az,isValidApiBaseURL as sz,readNativeEnrollmentMode as nz,resolveNativePoolPaths as iz,WORKER_SCRIPT as oz}from"@cortexkit/anthropic-auth-core";import{randomUUID as WZ}from"node:crypto";import{constants as A3}from"node:fs";import{lstat as YZ,mkdir as HZ,open as UZ}from"node:fs/promises";import{homedir as KZ}from"node:os";import{isAbsolute as qZ,join as a7}from"node:path";import{types as G$}from"node:util";import{anthropicAuthStateRoot as FZ,createProviderErrorRedactor as s7,createWindowsOwnerOnly as BZ,ensureWindowsOwnerOnlyDirectory as VZ,formatLogLine as MZ,HOLDER_REGISTRATION_ERROR_MESSAGES as jZ,isOwnerOnly as DZ,isSecretKey as NZ,isStateLayoutRefusalCode as LZ,NativeMigrationError as PZ,NativePiAuthSlotError as CZ,PRIVATE_FILES_UNAVAILABLE_MESSAGE as n7,RELOCATED_MESSAGE as OZ,STATE_LAYOUT_REFUSAL_CODES as AZ,STATE_LAYOUT_REFUSAL_PUBLIC_MESSAGES as _Z,setupEnrollment as IZ,stateLayoutRefusalPublicMessage as RZ}from"@cortexkit/anthropic-auth-core";import{readFile as o5}from"node:fs/promises";import{assertHostsStopped as r5,createNativeAccountRuntime as t5,discoverNativeVaultInventory as e5,inspectNativeHostAuthEntry as e9,NativePiAuthSlotError as $Z,nativePiAuthSlotPaths as ZZ,openNativePiAuthSlot as Z$,readNativeEnrollmentMode as JZ,requireNoSupervisedAuthContentSnapshot as zZ}from"@cortexkit/anthropic-auth-core";import{dirname as L5}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as P5,CLAUSTRUM_PI_ENROLLMENT_NAME as C5,getHostClaustrumEnrollmentPaths as P7,resolveClaustrumConnectionPath as O5}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as jY}from"@cortexkit/claustrum-client";import{ClaustrumClient as iW}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as z8}from"@cortexkit/claustrum-client";import{SocketClosedError as X8,SocketTimeoutError as G8,SubcCallError as Q8}from"@cortexkit/subc-client";class A extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var a3=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",route_busy:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class u extends A{reason;constructor($){super("unavailable","Claustrum scoped operation unavailable");if(this.name="ClaustrumUnreachableError",$==="host-accessor-missing"||$==="host-accessor-failed")this.reason=$}}function J0($){if($ instanceof u||$ instanceof X8||$ instanceof G8)return"unreachable";let Z=$ instanceof z8||$ instanceof Q8?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(a3,Z))return"answered";return a3[Z]}import{resolve as x$}from"node:path";import{storeIdentity as VX}from"@cortexkit/claustrum-client";import{SubcClient as jX}from"@cortexkit/subc-client";var J1=300000,Z3=300000,s3=1000;class f1{#$;#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 J3{#$;#Z;#z;#Y=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#z}request(){if(this.#z)return this.#Y=!0,this.#z;return this.#z=(async()=>{do{this.#Y=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#Y)})().finally(()=>{this.#z=void 0}),this.#z}}class z3{#$;#Z=new f1;#z;#Y="polling";#G;#Q;#X=!1;#J;#H=!1;#W=0;constructor($){this.#$=$,this.#z=new J3(async()=>{let Z=this.#H;if(this.#H=!1,Z||this.#J!==this.#$.view())await this.#$.discover(this.#J??"")},(Z)=>{if(!this.#X)this.#$.onError?.(Z)})}get mode(){return this.#Y}start(){if(this.#X||this.#G||this.#Q)return;if(typeof this.#$.client.watchScoped!=="function"){this.#q("fallback","client-without-watch");return}this.#V(!1)}stop(){if(this.#X)return;if(this.#X=!0,this.#Q)(this.#$.clearTimeoutImpl??clearTimeout)(this.#Q);this.#Q=void 0;let $=this.#G;this.#G=void 0,$?.handle.stop()}#q($,Z){if(this.#Y===$)return;this.#Y=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#F($,Z){this.#Q=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#Q=void 0,!this.#X)Z()},$),this.#Q.unref?.()}async#V($){let Z;try{Z=await this.#$.enrollmentToken()}catch(Q){if(this.#X)return;this.#$.onError?.(Q),this.#j("token-unreadable");return}let J=this.#$.client.watchScoped;if(this.#X||this.#G||!J)return;this.#Z.restart(),this.#H=$;let z,X;try{X=J.call(this.#$.client,(Q)=>{if(this.#X||!z||this.#G!==z)return;if(z.notices++,z.notices===1)this.#$.onReachable?.(),z.acceptedAt=(this.#$.now??Date.now)(),this.#q("watching","accepted");if(!this.#Z.continuous(Q))this.#H=!0;this.#J=Q.view,this.#z.request()},{enrollmentToken:Z})}catch(Q){this.#$.onError?.(Q),this.#j("watch-failed");return}z={handle:X,notices:0},this.#G=z,this.#q("polling",$?"resubscribing":"opening");let G=z;X.closed.then((Q)=>this.#K(G,Q),(Q)=>this.#K(G,{kind:"transport_lost",error:Q}))}#K($,Z){if(this.#X||this.#G!==$)return;if(this.#G=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#q("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#j("refused");try{this.#$.onRefused(Z.error)}catch(J){this.#$.onError?.(J)}return}if($.notices>0){let J=(this.#$.now??Date.now)();if($.acceptedAt!==void 0&&J-$.acceptedAt>=300000)this.#W=0;let z=Math.min(1000*2**Math.min(this.#W,16),300000);this.#W++,this.#q("polling","resubscribing"),this.#F(z,()=>void this.#V(!0));return}this.#j(Z.kind)}#j($){this.#q("fallback",$),this.#F(300000,()=>void this.#V(!1))}}var G3=60000,y$=4*G3,W8=2*G3,n3=new Map,X3=new Map;function z1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Y8($){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 H8($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class v${transport;key;#$=[];#Z=!1;#z=new Set;#Y=new Map;#G=new J3(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.#Y.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#z.clear()}},()=>{});#Q=new f1;#X="polling";#J=0;#H=0;#W=new Map;#q;#F;#V={};#K=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#G.running)return this.#G.running;if(this.#X==="watching")return Promise.resolve();for(let[J,z]of X3)if($-z>=G3)X3.delete(J);let Z=X3.get(this.key);if(Z!==void 0&&$-Z<G3)return Promise.resolve();return X3.set(this.key,$),this.#G.request()}watchMode(){return this.#X}watch($={}){this.#J++;let Z=$.provider;if(Z===void 0)this.#H++;else this.#W.set(Z,(this.#W.get(Z)??0)+1);if(this.#J===1)this.#V=$,this.#O();let J=!1;return()=>{if(J)return;if(J=!0,Z===void 0)this.#H--;else{let z=(this.#W.get(Z)??1)-1;if(z>0)this.#W.set(Z,z);else this.#W.delete(Z)}if(--this.#J===0)this.#j()}}#j(){if(this.#F)(this.#V.clearTimeoutImpl??clearTimeout)(this.#F);this.#F=void 0;let $=this.#q;this.#q=void 0,$?.handle?.stop(),this.#X="polling"}#B($){this.#F=(this.#V.setTimeoutImpl??setTimeout)(()=>{if(this.#F=void 0,this.#J>0&&!this.#q)this.#O()},$),this.#F.unref?.()}#O(){let $=this.transport.watchUsage;if(!$){this.#X="fallback";return}this.#X="polling",this.#Q.restart();let Z={notices:0};this.#q=Z;let J;try{J=$.call(this.transport,(z)=>this.#A(Z,z))}catch(z){this.#I(Z,z);return}Z.handle=J,J.closed.then(()=>this.#I(Z,void 0),(z)=>this.#I(Z,z))}#A($,Z){if(this.#q!==$)return;if($.notices++,$.notices===1)this.#X="watching";if($.notices===2)this.#K=0;let J=Y8(Z);if(!J)this.#Q.restart();if(!(J?this.#Q.continuous(J):!1)||J?.provider===void 0||this.#H>0||this.#W.has(J.provider))this.#G.request()}#I($,Z){if(this.#q!==$)return;this.#q=void 0;let J=H8(Z);if(J==="unknown_method"||J==="usage_watch_limit"){this.#X="fallback";return}if($.notices>0){let z=Math.min(s3*2**Math.min(this.#K,16),Z3);this.#K++,this.#X="polling",this.#B(z);return}if(this.#X="fallback",this.#G.request(),Z===void 0||J0(Z)==="unreachable")this.#B(Z3)}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>=y$)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}}};if(z.stale!==void 0&&(!z1(z.stale)||z.stale.class!=="local_source_unavailable"))return{miss:"upstream-failed",reading:W};return J>=Q+y$||z.stale!==void 0?{miss:"stale",reading:W}:{reading:W}}if(this.#z.has($))return{miss:"absent"};let G=this.#Y.get($)??J;return this.#Y.set($,G),{miss:J-G>=W8?"unreachable":"cold"}}}function i3($,Z){let J=JSON.stringify([x$($.connectionFile),x$(Z)]),z=n3.get(J);if(!z)z={source:new v$($,J),refs:0},n3.set(J,z);z.refs++;let X=!1;return{source:z.source,release(){if(X)return;if(X=!0,--z.refs===0)n3.delete(J)}}}import{ClaustrumCredentialError as $Y}from"@cortexkit/claustrum-client";import{appendFileSync as C8,chmodSync as O8,existsSync as e3,renameSync as s$,statSync as A8}from"node:fs";import{open as _8}from"node:fs/promises";import{dirname as I8,resolve as R8}from"node:path";import{randomUUID as h$}from"node:crypto";import{lstat as u$,readFile as c$,rename as U8,unlink as g$}from"node:fs/promises";import{tmpdir as K8}from"node:os";import{dirname as _0,join as q8,resolve as z0}from"node:path";var _=process.platform==="win32",w$=new Set;function o3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var m$;var p$="native-addon-unavailable";function d$($){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:$}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:p$})}function F8($,Z){return Z instanceof $.PrivateFilesUnavailableError||Z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function B8($){try{await $.verifyPrivatePath(q8(K8(),`.common-auth-private-files-probe-${h$()}`),"file")}catch(Z){if(F8($,Z))throw d$(Z)}}function X1(){return m$??=import("@cortexkit/private-files").then(async($)=>{if(_)await B8($);return $},($)=>{throw _?d$($):$}),m$}class h 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}: ${$} (${p$}). 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=o3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}function Q3($){return _&&$ instanceof h&&$.reason==="io-error"&&($.win32Code===32||$.win32Code===303)}async function t($,Z,J){try{return await J()}catch(z){if(z instanceof h)throw z;throw new h($,Z,z)}}var V8;async function j0($,Z){$=z0($),Z??=V8,await t($,"safe-parent",async()=>{let J=await(await X1()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await u$($);throw new h(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function s($,Z,J=!1){if($=z0($),Z==="directory")return j0($);await t($,"verify",async()=>{let z=await X1(),X=await z.verifyOwnerOnly($),G=!1;if(!X.ok){let{reason:Q}=X.refusal;if(Q==="io-error")await z.verifyPrivatePath($,Z);if(J&&[z.EXTRA_ACE,z.NOT_PROTECTED,z.NULL_DACL,z.EMPTY_DACL].includes(Q))await j0(_0($)),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&&!w$.has($))w$.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function U0($,Z=!1,J){$=z0($),await t($,"directory",async()=>{let z=await X1();try{return await u$($),await j0($,J)}catch(G){if(o3(G)!=="ENOENT")throw G}let X=_0($);if(X===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await U0(X,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(o3(G)!=="EEXIST")throw G}await j0($,J)})}async function Q0($,Z=!1){if(!_)return c$($,"utf8");return(await M8($,Z)).toString("utf8")}async function M8($,Z=!1){if(!_)return c$($);if($=z0($),Z)await j0(_0($)),await s($,"file",!0);return t($,"read",async()=>(await X1()).readOwnerOnly($))}async function G1($,Z){await j0(_0(z0($))),await t($,"create",async()=>{await(await X1()).createPrivateFile(z0($),Z)})}async function l$($){await j0(_0(z0($))),await t($,"directory-create",async()=>{await(await X1()).createOwnerOnly(z0($),{kind:"dir"})})}async function t3($,Z,J={}){$=z0($),Z=z0(Z);let z=J.now??(()=>performance.now()),X=z(),G=J.deadline??1/0,Q,W=[0,10,20,40,80,100],Y,H=0;for(let K of W){let F=Math.min(Q??1/0,G);if(z()>=F)break;if(K)await(J.sleep??((N)=>new Promise((P)=>setTimeout(P,N))))(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;H++;try{return await(J.rename??U8)($,Z),{attempts:H,elapsedMs:z()-X}}catch(N){Y??=N;let P=N;if(!(P.win32Code!==void 0?P.win32Code===32||P.win32Code===33:["EBUSY","EPERM","EACCES"].includes(P.code??"")&&!P.reason))break;Q??=z()+500}}let U=new h(Z,"rename",Y??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw U.attempts=H,U.elapsedMs=z()-X,U}async function Q1($,Z,J={}){$=z0($),await U0(_0($));try{await s($,"file",!0)}catch(H){if(H.code!=="ENOENT")throw H}let z=z0(J.stagePath??`${$}.${h$()}.tmp`);if(_0(z)!==_0($))throw new h($,"stage-directory",{code:"EXDEV"});let X=!1,G=!1,Q={attempts:0,elapsedMs:0},W="stage-create",Y=(H)=>{try{J.onOutcome?.({path:$,stage:H?.stage??"published",published:G,fileDurable:G,durabilityConfirmed:!1,attempts:H?.attempts??Q.attempts,elapsedMs:H?.elapsedMs??Q.elapsedMs,...H&&{code:H.code,win32Code:H.win32Code}})}catch{}};try{if(await G1(z,Z),X=!0,W="before-rename",Q=await t3(z,$,J),X=!1,G=!0,W="published-callback",J.onRenamed?.(),W="published-verify",await s($,"file"),J.durable&&J.durability!=="file-only-on-windows")throw new h($,"directory-sync-unsupported",{code:"ENOTSUP"});Y()}catch(H){let U=H instanceof h?H:new h($,W,H);if(U.published=G,U.fileDurable=G,G)Object.assign(U,Q);if(X){try{await g$(z)}catch{U.orphanPath=z}X=!1}throw Y(U),U}finally{if(X)await g$(z).catch(()=>{})}}var j8=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,D8=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function N8($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function W1($={}){let Z=[D8,...$.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 j8.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 H of["code","status","cause"])if(Q[H]!==void 0)W.push([H,Q[H]]);let Y=new Set(W.map(([H])=>H));for(let H of Object.entries(G))if(!Y.has(H[0]))W.push(H);return W}function X(G,Q,W,Y=0){if(typeof G==="string")return Z.reduce((H,U)=>H.replace(U,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if(W.has(G))return"[Circular]";W.add(G);try{if(Array.isArray(G))return G.map((K)=>X(K,Q,W,Y));let H=N8(G);if(H&&Y>=8)return"[Truncated]";let U=H?Y+1:Y;return Object.fromEntries((H?z(G):Object.entries(G)).map(([K,F])=>[K,Q&&J(K)?"***REDACTED***":X(F,Q,W,U)]))}finally{W.delete(G)}}return{redact:(G)=>X(G,!0,new WeakSet),redactStrings:(G)=>X(G,!1,new WeakSet)}}var a$=W1(),L8=a$.redact,P8=a$.redactStrings;var W3={error:0,warn:1,info:2,debug:3,trace:4},i$=5242880,o$=3;function $9($){try{O8($,384)}catch{}}function S8($){try{if(!(e3($)&&A8($).size>=i$))return;for(let J=o$-1;J>=1;J--)if(e3(`${$}.${J}`)){let z=`${$}.${J+1}`;s$(`${$}.${J}`,z),$9(z)}let Z=`${$}.1`;s$($,Z),$9(Z)}catch{}}async function D0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await t(Z,"log-close",()=>J.close())}async function n$($,Z){await U0(I8(Z));try{await s(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await G1(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await s(Z,"file",!0)}}return $.handle=await t(Z,"log-open",()=>_8(Z,"a")),$.file=Z,$.handle}async function T8($,Z,J){Z=R8(Z);try{if($.file!==Z)await D0($);let z=$.handle??await n$($,Z);if((await t(Z,"log-stat",()=>z.stat())).size>=i$){await D0($);for(let G=o$-1;G>=0;G--){let Q=G===0?Z:`${Z}.${G}`,W=`${Z}.${G+1}`;try{await s(Q,"file",!0)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}try{await s(W,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}await t3(Q,W),await s(W,"file")}z=await n$($,Z)}await t(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await D0($).catch(()=>{}),z}}function k8($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function E8($){let Z,J,z,X=W1(),G,Q=[],W,Y=Promise.resolve(),H,U={};function K(M){let q=Y.then(M);return Y=q.catch((D)=>{H=D}),q}function F(M){if(_&&M.file!==Z)K(()=>D0(U)).catch(()=>{});Z=M.file,J=M.level,X=W1(M),G=M.captureSink}function B(M){if(M===void 0||M in W3)z=M}function N(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function P(){if(z)return z;let M=typeof J==="function"?J():J;if(M&&M in W3)return M;return"info"}function C(M=!0){if(W)clearTimeout(W),W=void 0;if(!Q.length){if(_)return K(async()=>{if(M)await D0(U);if(H)throw H});return}let q;try{q=N()}catch{if(Q=[],_&&M)return K(()=>D0(U));return}let D=Q.join("");if(Q=[],!q){if(_&&M)return K(()=>D0(U));return}if(_)return K(async()=>{try{await T8(U,q,D)}finally{if(M)await D0(U)}});try{if(S8(q),e3(q))$9(q);C8(q,D,{encoding:"utf8",mode:384})}catch{}}function I(){if(!W)W=setTimeout(()=>{W=void 0;let M=C(!1);if(M instanceof Promise)M.catch(()=>{})},500)}function T(M,q,D,O){if(Z===void 0&&G===void 0)return;try{if(W3[q]>W3[P()])return;let g=X.redactStrings(D),E;try{E=X.redact(O)}catch{E="[unserializable]"}let x=`[${new Date().toISOString()}] ${q.toUpperCase()} [${M}] ${g}`+(O===void 0?"":k8(E))+`
|
|
2
|
+
import{C as m3}from"./index-gqxrgdvk.js";import{E as i4,F as o4,G as I7,H as R7,I as S7,J as T7,K as r4}from"./index-427t44z7.js";import{ma as x4,na as lJ,oa as r3}from"./index-dpxaxyck.js";var P$=lJ((DF,E4)=>{var L$={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"},aJ={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},sJ={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?L$.up():"");if($)Z+=L$.left;return Z}};E4.exports={cursor:L$,scroll:aJ,erase:sJ,beep:"\x07"}});import{stdin as gz,stdout as wz}from"node:process";import{createInterface as mz}from"node:readline/promises";import{authorize as hz,createNativeAccountRuntime as uz,decideOpenCodeStateLayoutOnce as cz,exchange as pz,formatNativeAccountState as dz,generateRelayToken as lz,getAccountStoragePath as az,isValidApiBaseURL as sz,readNativeEnrollmentMode as nz,resolveNativePoolPaths as iz,WORKER_SCRIPT as oz}from"@cortexkit/anthropic-auth-core";import{randomUUID as WZ}from"node:crypto";import{constants as A3}from"node:fs";import{lstat as YZ,mkdir as HZ,open as UZ}from"node:fs/promises";import{homedir as KZ}from"node:os";import{isAbsolute as qZ,join as a7}from"node:path";import{types as G$}from"node:util";import{anthropicAuthStateRoot as FZ,createProviderErrorRedactor as s7,createWindowsOwnerOnly as BZ,ensureWindowsOwnerOnlyDirectory as VZ,formatLogLine as MZ,HOLDER_REGISTRATION_ERROR_MESSAGES as jZ,isOwnerOnly as DZ,isSecretKey as NZ,isStateLayoutRefusalCode as LZ,NativeMigrationError as PZ,NativePiAuthSlotError as CZ,PRIVATE_FILES_UNAVAILABLE_MESSAGE as n7,RELOCATED_MESSAGE as OZ,STATE_LAYOUT_REFUSAL_CODES as AZ,STATE_LAYOUT_REFUSAL_PUBLIC_MESSAGES as _Z,setupEnrollment as IZ,stateLayoutRefusalPublicMessage as RZ}from"@cortexkit/anthropic-auth-core";import{readFile as o5}from"node:fs/promises";import{assertHostsStopped as r5,createNativeAccountRuntime as t5,discoverNativeVaultInventory as e5,inspectNativeHostAuthEntry as e9,NativePiAuthSlotError as $Z,nativePiAuthSlotPaths as ZZ,openNativePiAuthSlot as Z$,readNativeEnrollmentMode as JZ,requireNoSupervisedAuthContentSnapshot as zZ}from"@cortexkit/anthropic-auth-core";import{dirname as L5}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as P5,CLAUSTRUM_PI_ENROLLMENT_NAME as C5,getHostClaustrumEnrollmentPaths as P7,resolveClaustrumConnectionPath as O5}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as jY}from"@cortexkit/claustrum-client";import{ClaustrumClient as iW}from"@cortexkit/claustrum-client";import{ClaustrumCredentialError as z8}from"@cortexkit/claustrum-client";import{SocketClosedError as X8,SocketTimeoutError as G8,SubcCallError as Q8}from"@cortexkit/subc-client";class A extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var a3=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",route_busy:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class u extends A{reason;constructor($){super("unavailable","Claustrum scoped operation unavailable");if(this.name="ClaustrumUnreachableError",$==="host-accessor-missing"||$==="host-accessor-failed")this.reason=$}}function J0($){if($ instanceof u||$ instanceof X8||$ instanceof G8)return"unreachable";let Z=$ instanceof z8||$ instanceof Q8?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(a3,Z))return"answered";return a3[Z]}import{resolve as x$}from"node:path";import{storeIdentity as VX}from"@cortexkit/claustrum-client";import{SubcClient as jX}from"@cortexkit/subc-client";var J1=300000,Z3=300000,s3=1000;class f1{#$;#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 J3{#$;#Z;#z;#Y=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#z}request(){if(this.#z)return this.#Y=!0,this.#z;return this.#z=(async()=>{do{this.#Y=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#Y)})().finally(()=>{this.#z=void 0}),this.#z}}class z3{#$;#Z=new f1;#z;#Y="polling";#G;#Q;#X=!1;#J;#H=!1;#W=0;constructor($){this.#$=$,this.#z=new J3(async()=>{let Z=this.#H;if(this.#H=!1,Z||this.#J!==this.#$.view())await this.#$.discover(this.#J??"")},(Z)=>{if(!this.#X)this.#$.onError?.(Z)})}get mode(){return this.#Y}start(){if(this.#X||this.#G||this.#Q)return;if(typeof this.#$.client.watchScoped!=="function"){this.#q("fallback","client-without-watch");return}this.#V(!1)}stop(){if(this.#X)return;if(this.#X=!0,this.#Q)(this.#$.clearTimeoutImpl??clearTimeout)(this.#Q);this.#Q=void 0;let $=this.#G;this.#G=void 0,$?.handle.stop()}#q($,Z){if(this.#Y===$)return;this.#Y=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#F($,Z){this.#Q=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#Q=void 0,!this.#X)Z()},$),this.#Q.unref?.()}async#V($){let Z;try{Z=await this.#$.enrollmentToken()}catch(Q){if(this.#X)return;this.#$.onError?.(Q),this.#j("token-unreadable");return}let J=this.#$.client.watchScoped;if(this.#X||this.#G||!J)return;this.#Z.restart(),this.#H=$;let z,X;try{X=J.call(this.#$.client,(Q)=>{if(this.#X||!z||this.#G!==z)return;if(z.notices++,z.notices===1)this.#$.onReachable?.(),z.acceptedAt=(this.#$.now??Date.now)(),this.#q("watching","accepted");if(!this.#Z.continuous(Q))this.#H=!0;this.#J=Q.view,this.#z.request()},{enrollmentToken:Z})}catch(Q){this.#$.onError?.(Q),this.#j("watch-failed");return}z={handle:X,notices:0},this.#G=z,this.#q("polling",$?"resubscribing":"opening");let G=z;X.closed.then((Q)=>this.#K(G,Q),(Q)=>this.#K(G,{kind:"transport_lost",error:Q}))}#K($,Z){if(this.#X||this.#G!==$)return;if(this.#G=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#q("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#j("refused");try{this.#$.onRefused(Z.error)}catch(J){this.#$.onError?.(J)}return}if($.notices>0){let J=(this.#$.now??Date.now)();if($.acceptedAt!==void 0&&J-$.acceptedAt>=300000)this.#W=0;let z=Math.min(1000*2**Math.min(this.#W,16),300000);this.#W++,this.#q("polling","resubscribing"),this.#F(z,()=>void this.#V(!0));return}this.#j(Z.kind)}#j($){this.#q("fallback",$),this.#F(300000,()=>void this.#V(!1))}}var G3=60000,y$=4*G3,W8=2*G3,n3=new Map,X3=new Map;function z1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Y8($){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 H8($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class v${transport;key;#$=[];#Z=!1;#z=new Set;#Y=new Map;#G=new J3(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.#Y.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#z.clear()}},()=>{});#Q=new f1;#X="polling";#J=0;#H=0;#W=new Map;#q;#F;#V={};#K=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#G.running)return this.#G.running;if(this.#X==="watching")return Promise.resolve();for(let[J,z]of X3)if($-z>=G3)X3.delete(J);let Z=X3.get(this.key);if(Z!==void 0&&$-Z<G3)return Promise.resolve();return X3.set(this.key,$),this.#G.request()}watchMode(){return this.#X}watch($={}){this.#J++;let Z=$.provider;if(Z===void 0)this.#H++;else this.#W.set(Z,(this.#W.get(Z)??0)+1);if(this.#J===1)this.#V=$,this.#O();let J=!1;return()=>{if(J)return;if(J=!0,Z===void 0)this.#H--;else{let z=(this.#W.get(Z)??1)-1;if(z>0)this.#W.set(Z,z);else this.#W.delete(Z)}if(--this.#J===0)this.#j()}}#j(){if(this.#F)(this.#V.clearTimeoutImpl??clearTimeout)(this.#F);this.#F=void 0;let $=this.#q;this.#q=void 0,$?.handle?.stop(),this.#X="polling"}#B($){this.#F=(this.#V.setTimeoutImpl??setTimeout)(()=>{if(this.#F=void 0,this.#J>0&&!this.#q)this.#O()},$),this.#F.unref?.()}#O(){let $=this.transport.watchUsage;if(!$){this.#X="fallback";return}this.#X="polling",this.#Q.restart();let Z={notices:0};this.#q=Z;let J;try{J=$.call(this.transport,(z)=>this.#A(Z,z))}catch(z){this.#I(Z,z);return}Z.handle=J,J.closed.then(()=>this.#I(Z,void 0),(z)=>this.#I(Z,z))}#A($,Z){if(this.#q!==$)return;if($.notices++,$.notices===1)this.#X="watching";if($.notices===2)this.#K=0;let J=Y8(Z);if(!J)this.#Q.restart();if(!(J?this.#Q.continuous(J):!1)||J?.provider===void 0||this.#H>0||this.#W.has(J.provider))this.#G.request()}#I($,Z){if(this.#q!==$)return;this.#q=void 0;let J=H8(Z);if(J==="unknown_method"||J==="usage_watch_limit"){this.#X="fallback";return}if($.notices>0){let z=Math.min(s3*2**Math.min(this.#K,16),Z3);this.#K++,this.#X="polling",this.#B(z);return}if(this.#X="fallback",this.#G.request(),Z===void 0||J0(Z)==="unreachable")this.#B(Z3)}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>=y$)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}}};if(z.stale!==void 0&&(!z1(z.stale)||z.stale.class!=="local_source_unavailable"))return{miss:"upstream-failed",reading:W};return J>=Q+y$||z.stale!==void 0?{miss:"stale",reading:W}:{reading:W}}if(this.#z.has($))return{miss:"absent"};let G=this.#Y.get($)??J;return this.#Y.set($,G),{miss:J-G>=W8?"unreachable":"cold"}}}function i3($,Z){let J=JSON.stringify([x$($.connectionFile),x$(Z)]),z=n3.get(J);if(!z)z={source:new v$($,J),refs:0},n3.set(J,z);z.refs++;let X=!1;return{source:z.source,release(){if(X)return;if(X=!0,--z.refs===0)n3.delete(J)}}}import{ClaustrumCredentialError as $Y}from"@cortexkit/claustrum-client";import{appendFileSync as C8,chmodSync as O8,existsSync as e3,renameSync as s$,statSync as A8}from"node:fs";import{open as _8}from"node:fs/promises";import{dirname as I8,resolve as R8}from"node:path";import{randomUUID as h$}from"node:crypto";import{lstat as u$,readFile as c$,rename as U8,unlink as g$}from"node:fs/promises";import{tmpdir as K8}from"node:os";import{dirname as _0,join as q8,resolve as z0}from"node:path";var _=process.platform==="win32",w$=new Set;function o3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var m$;var p$="native-addon-unavailable";function d$($){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:$}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:p$})}function F8($,Z){return Z instanceof $.PrivateFilesUnavailableError||Z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function B8($){try{await $.verifyPrivatePath(q8(K8(),`.common-auth-private-files-probe-${h$()}`),"file")}catch(Z){if(F8($,Z))throw d$(Z)}}function X1(){return m$??=import("@cortexkit/private-files").then(async($)=>{if(_)await B8($);return $},($)=>{throw _?d$($):$}),m$}class h 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}: ${$} (${p$}). 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=o3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}function Q3($){return _&&$ instanceof h&&$.reason==="io-error"&&($.win32Code===32||$.win32Code===303)}async function t($,Z,J){try{return await J()}catch(z){if(z instanceof h)throw z;throw new h($,Z,z)}}var V8;async function j0($,Z){$=z0($),Z??=V8,await t($,"safe-parent",async()=>{let J=await(await X1()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await u$($);throw new h(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function s($,Z,J=!1){if($=z0($),Z==="directory")return j0($);await t($,"verify",async()=>{let z=await X1(),X=await z.verifyOwnerOnly($),G=!1;if(!X.ok){let{reason:Q}=X.refusal;if(Q==="io-error")await z.verifyPrivatePath($,Z);if(J&&[z.EXTRA_ACE,z.NOT_PROTECTED,z.NULL_DACL,z.EMPTY_DACL].includes(Q))await j0(_0($)),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&&!w$.has($))w$.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function U0($,Z=!1,J){$=z0($),await t($,"directory",async()=>{let z=await X1();try{return await u$($),await j0($,J)}catch(G){if(o3(G)!=="ENOENT")throw G}let X=_0($);if(X===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await U0(X,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(o3(G)!=="EEXIST")throw G}await j0($,J)})}async function Q0($,Z=!1){if(!_)return c$($,"utf8");return(await M8($,Z)).toString("utf8")}async function M8($,Z=!1){if(!_)return c$($);if($=z0($),Z)await j0(_0($)),await s($,"file",!0);return t($,"read",async()=>(await X1()).readOwnerOnly($))}async function G1($,Z){await j0(_0(z0($))),await t($,"create",async()=>{await(await X1()).createPrivateFile(z0($),Z)})}async function l$($){await j0(_0(z0($))),await t($,"directory-create",async()=>{await(await X1()).createOwnerOnly(z0($),{kind:"dir"})})}async function t3($,Z,J={}){$=z0($),Z=z0(Z);let z=J.now??(()=>performance.now()),X=z(),G=J.deadline??1/0,Q,W=[0,10,20,40,80,100],Y,H=0;for(let K of W){let F=Math.min(Q??1/0,G);if(z()>=F)break;if(K)await(J.sleep??((N)=>new Promise((P)=>setTimeout(P,N))))(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;H++;try{return await(J.rename??U8)($,Z),{attempts:H,elapsedMs:z()-X}}catch(N){Y??=N;let P=N;if(!(P.win32Code!==void 0?P.win32Code===32||P.win32Code===33:["EBUSY","EPERM","EACCES"].includes(P.code??"")&&!P.reason))break;Q??=z()+500}}let U=new h(Z,"rename",Y??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw U.attempts=H,U.elapsedMs=z()-X,U}async function Q1($,Z,J={}){$=z0($),await U0(_0($));try{await s($,"file",!0)}catch(H){if(H.code!=="ENOENT")throw H}let z=z0(J.stagePath??`${$}.${h$()}.tmp`);if(_0(z)!==_0($))throw new h($,"stage-directory",{code:"EXDEV"});let X=!1,G=!1,Q={attempts:0,elapsedMs:0},W="stage-create",Y=(H)=>{try{J.onOutcome?.({path:$,stage:H?.stage??"published",published:G,fileDurable:G,durabilityConfirmed:!1,attempts:H?.attempts??Q.attempts,elapsedMs:H?.elapsedMs??Q.elapsedMs,...H&&{code:H.code,win32Code:H.win32Code}})}catch{}};try{if(await G1(z,Z),X=!0,W="before-rename",Q=await t3(z,$,J),X=!1,G=!0,W="published-callback",J.onRenamed?.(),W="published-verify",await s($,"file"),J.durable&&J.durability!=="file-only-on-windows")throw new h($,"directory-sync-unsupported",{code:"ENOTSUP"});Y()}catch(H){let U=H instanceof h?H:new h($,W,H);if(U.published=G,U.fileDurable=G,G)Object.assign(U,Q);if(X){try{await g$(z)}catch{U.orphanPath=z}X=!1}throw Y(U),U}finally{if(X)await g$(z).catch(()=>{})}}var j8=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,D8=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function N8($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function W1($={}){let Z=[D8,...$.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 j8.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 H of["code","status","cause"])if(Q[H]!==void 0)W.push([H,Q[H]]);let Y=new Set(W.map(([H])=>H));for(let H of Object.entries(G))if(!Y.has(H[0]))W.push(H);return W}function X(G,Q,W,Y=0){if(typeof G==="string")return Z.reduce((H,U)=>H.replace(U,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if(W.has(G))return"[Circular]";W.add(G);try{if(Array.isArray(G))return G.map((K)=>X(K,Q,W,Y));let H=N8(G);if(H&&Y>=8)return"[Truncated]";let U=H?Y+1:Y;return Object.fromEntries((H?z(G):Object.entries(G)).map(([K,F])=>[K,Q&&J(K)?"***REDACTED***":X(F,Q,W,U)]))}finally{W.delete(G)}}return{redact:(G)=>X(G,!0,new WeakSet),redactStrings:(G)=>X(G,!1,new WeakSet)}}var a$=W1(),L8=a$.redact,P8=a$.redactStrings;var W3={error:0,warn:1,info:2,debug:3,trace:4},i$=5242880,o$=3;function $9($){try{O8($,384)}catch{}}function S8($){try{if(!(e3($)&&A8($).size>=i$))return;for(let J=o$-1;J>=1;J--)if(e3(`${$}.${J}`)){let z=`${$}.${J+1}`;s$(`${$}.${J}`,z),$9(z)}let Z=`${$}.1`;s$($,Z),$9(Z)}catch{}}async function D0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await t(Z,"log-close",()=>J.close())}async function n$($,Z){await U0(I8(Z));try{await s(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await G1(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await s(Z,"file",!0)}}return $.handle=await t(Z,"log-open",()=>_8(Z,"a")),$.file=Z,$.handle}async function T8($,Z,J){Z=R8(Z);try{if($.file!==Z)await D0($);let z=$.handle??await n$($,Z);if((await t(Z,"log-stat",()=>z.stat())).size>=i$){await D0($);for(let G=o$-1;G>=0;G--){let Q=G===0?Z:`${Z}.${G}`,W=`${Z}.${G+1}`;try{await s(Q,"file",!0)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}try{await s(W,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}await t3(Q,W),await s(W,"file")}z=await n$($,Z)}await t(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await D0($).catch(()=>{}),z}}function k8($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function E8($){let Z,J,z,X=W1(),G,Q=[],W,Y=Promise.resolve(),H,U={};function K(M){let q=Y.then(M);return Y=q.catch((D)=>{H=D}),q}function F(M){if(_&&M.file!==Z)K(()=>D0(U)).catch(()=>{});Z=M.file,J=M.level,X=W1(M),G=M.captureSink}function B(M){if(M===void 0||M in W3)z=M}function N(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function P(){if(z)return z;let M=typeof J==="function"?J():J;if(M&&M in W3)return M;return"info"}function C(M=!0){if(W)clearTimeout(W),W=void 0;if(!Q.length){if(_)return K(async()=>{if(M)await D0(U);if(H)throw H});return}let q;try{q=N()}catch{if(Q=[],_&&M)return K(()=>D0(U));return}let D=Q.join("");if(Q=[],!q){if(_&&M)return K(()=>D0(U));return}if(_)return K(async()=>{try{await T8(U,q,D)}finally{if(M)await D0(U)}});try{if(S8(q),e3(q))$9(q);C8(q,D,{encoding:"utf8",mode:384})}catch{}}function I(){if(!W)W=setTimeout(()=>{W=void 0;let M=C(!1);if(M instanceof Promise)M.catch(()=>{})},500)}function T(M,q,D,O){if(Z===void 0&&G===void 0)return;try{if(W3[q]>W3[P()])return;let g=X.redactStrings(D),E;try{E=X.redact(O)}catch{E="[unserializable]"}let x=`[${new Date().toISOString()}] ${q.toUpperCase()} [${M}] ${g}`+(O===void 0?"":k8(E))+`
|
|
3
3
|
`;try{G?.({channel:M,level:q,message:g,data:E})}catch{}if(Z===void 0)return;if(Q.push(x),Q.length>=50){let $0=C(!1);if($0 instanceof Promise)$0.catch(()=>{})}else I()}catch{}}function w(M){return{error:(q,D)=>T(M,"error",q,D),warn:(q,D)=>T(M,"warn",q,D),info:(q,D)=>T(M,"info",q,D),debug:(q,D)=>T(M,"debug",q,D),trace:(q,D)=>T(M,"trace",q,D)}}function c(){if(_)K(()=>D0(U)).catch(()=>{});if(H=void 0,Q=[],W)clearTimeout(W),W=void 0;Z=void 0,J=void 0,z=void 0,X=W1(),G=void 0}if($)F($);return{configure:F,createLogger:w,setLogLevel:B,flushLogs:C,reset:c}}var b8=E8();function X0($){return b8.createLogger($)}function v0($){let Z=new AbortController,J=[],z=!1,X=()=>{if(z)return;z=!0;for(let{source:W,listener:Y}of J)W.removeEventListener("abort",Y);J.length=0},G=(W)=>{if(z||Z.signal.aborted)return;Z.abort(W),X()},Q=$.find((W)=>W.aborted);if(Q)return Z.abort(Q.reason),{signal:Z.signal,dispose:X};for(let W of $){if(Z.signal.aborted)break;let Y=()=>G(W.reason);if(J.push({source:W,listener:Y}),W.addEventListener("abort",Y,{once:!0}),W.aborted)G(W.reason)}return{signal:Z.signal,dispose:X}}import{channel as A6}from"node:diagnostics_channel";import{ClaustrumCredentialError as x2}from"@cortexkit/claustrum-client";import{createHash as U6,randomBytes as K6,randomUUID as q6}from"node:crypto";import{constants as B2}from"node:fs";import{chmod as F6,mkdir as B6,open as N2,readFile as Q9,realpath as V6,rename as M6,stat as L2,unlink as Y9}from"node:fs/promises";import{basename as j6,dirname as c0,extname as xG,isAbsolute as yG,join as D6,resolve as vG}from"node:path";import{ClaustrumCredentialError as P2,ClaustrumClient as wG,writeEnrollmentTokenFile as N6}from"@cortexkit/claustrum-client";import{lstat as f8,stat as x8}from"node:fs/promises";import{resolve as y8}from"node:path";async function v8($,Z){try{let J=await Z($);return J.isFile()?J:void 0}catch(J){return J.code==="ENOENT"?"absent":void 0}}function g8($,Z){if($==="absent"||Z==="absent")return $===Z;return $.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs&&$.ctimeMs===Z.ctimeMs}class g0{#$;#Z=new Map;constructor($={}){this.#$=$.followSymlinks?(Z)=>($.stat??x8)(Z):(Z)=>($.lstat??f8)(Z)}async read($,Z,J){let z=$.map((H)=>y8(H)),X=JSON.stringify(z),G=await Promise.all(z.map((H)=>v8(H,this.#$))),Q=G.every((H)=>H!==void 0)?G:void 0,W=this.#Z.get(X);if(Q&&W&&Q.every((H,U)=>{let K=W.identities[U];return K!==void 0&&g8(H,K)}))return J?.(Q),W.value;this.#Z.delete(X);let Y=await Z(z);if(Q){if(this.#Z.size>=64){let H=this.#Z.keys().next().value;if(H!==void 0)this.#Z.delete(H)}this.#Z.set(X,{identities:Q,value:Y})}return Y}}import{randomUUID as r$}from"node:crypto";import{mkdir as w8,open as t$,rename as m8,rm as h8}from"node:fs/promises";import{dirname as e$}from"node:path";class Y3 extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function Y1($,Z,J={}){await $2($,Z,J)}async function $2($,Z,J,z){if(_)return Q1($,J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
4
4
|
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??r$)()}.tmp`,onRenamed:z,durable:J.durable,durability:J.durability,onOutcome:J.onOutcome});await w8(e$($),{recursive:!0});let X=`${$}.${(J.stageName??r$)()}.tmp`,G,Q=!1;try{if(G=await t$(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 Y3(W)}if(await G.close(),G=void 0,await J.beforeRename?.(),await m8(X,$),Q=!1,z?.(),J.durable){let W=await t$(e$($),"r");try{await W.sync()}catch(Y){throw new Y3(Y)}finally{await W.close()}}}finally{if(await G?.close().catch(()=>{}),Q)await h8(X,{force:!0}).catch(()=>{})}}var u8=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 v1}from"node:crypto";import{link as l8,lstat as R0,mkdir as J2,open as U3,readdir as a8,readFile as z2,rename as X2,rm as K1,stat as y1,unlink as s8}from"node:fs/promises";import{basename as n8,dirname as H3,join as z9}from"node:path";import{resolve as Z2}from"node:path";class x1 extends Error{path;code="ENOENT";constructor($,Z){super(`Lock record disappeared: ${$}`,{cause:Z});this.path=$}}function w0($,Z){return $ instanceof h&&$.reason==="io-error"&&$.win32Code===5&&($.stage==="read"||$.stage==="verify")&&Z.some((J)=>Z2(J)===$.path)}function H1($,Z,J){return $ instanceof h&&$.reason==="io-error"&&$.win32Code===5&&$.stage===J&&Z.some((z)=>Z2(z)===$.path)}async function K0($,Z){try{return await Z()}catch(J){if(!w0(J,[$]))throw J;try{return await Z()}catch(z){if(z.code==="ENOENT")throw new x1($,J);throw J}}}import{join as c8,resolve as p8}from"node:path";function U1($,Z){return`${$}.${Z}.lock`}class I0 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class N0 extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}function d8($,Z,J){let z=p8(U1(Z,J)),X=[z,c8(z,"owner.json")];return(Q3($)||w0($,X))&&($.stage==="read"||$.stage==="verify")&&X.includes($.path)||_&&(H1($,[z],"create")||H1($,[`${z}.evicting`],"directory-create"))}async function Z9($,Z,J){let z=performance.now(),X;for(;;){Z.signal?.throwIfAborted();let G;try{G=await L0({path:$,name:Z.name,ttlMs:Z.ttlMs,renew:Z.renew??!1,...Z.onStep?{onStep:Z.onStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}}),X=void 0}catch(W){if(!d8(W,$,Z.name))throw W;G=null,X??=W}if(G)try{return Z.signal?.throwIfAborted(),await J(G)}finally{await G.release(Z.signal)}let Q=Z.timeoutMs-(performance.now()-z);if(Q<=0){if(X)throw X;throw new I0({target:$,name:Z.name,timeoutMs:Z.timeoutMs})}await new Promise((W)=>setTimeout(W,Math.min(25,Math.ceil(Q))))}}var q1;async function i8($,Z){let J=`${$}.${v1()}.tmp`,z;try{z=await U3(J,"wx",384);try{if(q1?.beforeWrite)await q1.beforeWrite(J);await z.writeFile(Z,"utf8")}finally{await z.close()}try{if(q1?.beforeLink)await q1.beforeLink(J,$);await l8(J,$)}catch(X){let G=X.code;if(G!=="EPERM"&&G!=="ENOTSUP"&&G!=="EOPNOTSUPP"&&G!=="EXDEV")throw X;await H2($,Z)}}finally{if(z)await K1(J,{force:!0}).catch(()=>{})}}async function H2($,Z){let J=await U3($,"wx",384),z;try{z=await J.stat()}catch{z=void 0}try{if(q1?.beforeWrite)await q1.beforeWrite($);await J.writeFile(Z,"utf8")}catch(X){try{let G=await R0($).catch(()=>{return});if(z&&G&&G.dev===z.dev&&G.ino===z.ino)await K1($,{force:!0}).catch(()=>{})}catch{}throw X}finally{await J.close()}}var U2=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,o8=600000,r8=256,t8=4096,G2=new Set,Q2=new Set,e8;function $6($,Z){let J=`${Z}.`,z=".tmp";if(!$.startsWith(J)||!$.endsWith(".tmp"))return!1;return U2.test($.slice(J.length,-4))}function K2($,Z){return $.dev===Z.dev&&$.ino===Z.ino&&$.size===Z.size&&$.mtimeMs===Z.mtimeMs&&$.birthtimeMs===Z.birthtimeMs}async function W2($){let Z=await R0($);if(!Z.isFile()||Z.isSymbolicLink())return;if(Z.size>t8)return;let J=await U3($,"r"),z;try{if(!K2(Z,await J.stat()))return;z=await J.readFile("utf8")}finally{await J.close()}let X;try{X=JSON.parse(z)}catch{return}if(!X||typeof X!=="object"||Array.isArray(X))return;let G=Object.keys(X).sort();if(G.length!==2||G[0]!=="expiresAt"||G[1]!=="ownerId")return;let{ownerId:Q,expiresAt:W}=X;if(typeof Q!=="string"||!U2.test(Q))return;if(typeof W!=="number"||!Number.isFinite(W))return;return{identity:Z,expiresAt:W}}async function Z6($,Z,J){let z=H3($),X=n8($),G=e8,W=(await(G?.readdir??a8)(z)).filter((H)=>$6(H,X)).slice(0,r8),Y=Math.max(Number.isFinite(Z)?Z:0,o8);for(let H of W){let U=z9(z,H);try{if(J()-(await R0(U)).mtimeMs<Y)continue;let K=await W2(U);if(!K||!(K.expiresAt<J()-Y))continue;if(G?.beforeUnlink)await G.beforeUnlink(U);let F=await W2(U);if(!F||!K2(K.identity,F.identity)||!(F.expiresAt<J()-Y))continue;await(G?.unlink??s8)(U)}catch{}}}function J6($,Z,J){if(G2.has($))return;G2.add($);let z=Promise.resolve().then(()=>Z6($,Z,J)).catch(()=>{});Q2.add(z),z.finally(()=>Q2.delete(z))}var z6=globalThis.setTimeout.bind(globalThis),X6=globalThis.clearTimeout.bind(globalThis);function q2($){let Z=$?.code;return Z==="ENOENT"||!_&&(Z==="EINVAL"||Z==="ENOTDIR")}var Y2;function J9($,Z){if($.dev!==Z.dev||$.ino!==Z.ino)return!1;if($.ino===0&&$.birthtimeMs!==Z.birthtimeMs)return!1;return!0}var G6=1000;function L0($){return Q6({...$,now:Date.now})}async function Q6($){let Z=U1($.path,$.name),J=z9(Z,"owner.json"),z=v1(),X=$.now??Date.now,G=null,Q=!1,W=!1,Y,H,U=new Promise((V)=>{H=V});function K(V){try{let j=$.onRenewalTimer?.(V);if(j&&(typeof j==="object"||typeof j==="function")&&"then"in j&&typeof j.then==="function")Promise.resolve(j).catch(()=>{})}catch{}}function F(){if(!G)return;X6(G),G=null,K("cancelled")}function B(V,j){if(Y||Q)return;Y=Object.freeze({reason:V,expectedOwnerId:z,...typeof j?.ownerId==="string"?{observedOwnerId:j.ownerId}:{},...typeof j?.expiresAt==="number"?{observedExpiresAt:j.expiresAt}:{}}),F(),H(Y)}let N,P=null,C=`${Z}.evicting`,I=z9(C,"owner.json"),T=v1(),w=5000,c=8;function M(V){return _&&(H1(V,[Z],"create")||H1(V,[C],"directory-create"))}async function q(){if(_)try{return JSON.parse(await K0(Z,()=>Q0(Z,!0)))}catch(V){if(V.code!=="EISDIR"&&V.reason!=="wrong-kind")throw V;return await K0(Z,()=>s(Z,"directory",!0)),JSON.parse(await K0(J,()=>Q0(J,!0)))}try{return JSON.parse(await z2(Z,"utf8"))}catch(V){if(V.code!=="EISDIR")throw V;return JSON.parse(await z2(J,"utf8"))}}async function D(){if(_){let R=await q(),S=Number(R?.expiresAt)-X();await Q1(Z,`${JSON.stringify({ownerId:z,expiresAt:X()+$.ttlMs})}
|
|
@@ -30,7 +30,7 @@ ${Q.stderrTail}`]:[]].join(`
|
|
|
30
30
|
`)}var G0=x4(P$(),1);function O$($,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?O$(G,Z<0?-1:1,J):G}function f3($,Z,J,z){let X=z.split(`
|
|
31
31
|
`),G=0,Q=$;for(let Y of X){if(Q<=Y.length)break;Q-=Y.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 Y=0;Y<G;Y++)W+=X[Y].length+1;return W+Q}var rJ=["up","down","left","right","space","enter","cancel"],tJ=["January","February","March","April","May","June","July","August","September","October","November","December"],Y0={actions:new Set(rJ),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:[...tJ],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 eJ($){if($!==void 0)return $;if(Y0.accessible!==void 0)return Y0.accessible;let Z=process.env.ACCESSIBLE;return Z!==void 0&&Z!==""&&Z!=="0"&&Z!=="false"}function y4($,Z){if(typeof $=="string")return Y0.aliases.get($)===Z;for(let J of $)if(J!==void 0&&y4(J,Z))return!0;return!1}function $z($,Z){if($===Z)return;let J=$.split(`
|
|
32
32
|
`),z=Z.split(`
|
|
33
|
-
`),X=Math.max(J.length,z.length),G=[];for(let Q=0;Q<X;Q++)J[Q]!==z[Q]&&G.push(Q);return{lines:G,numLinesBefore:J.length,numLinesAfter:z.length,numLines:X}}var
|
|
33
|
+
`),X=Math.max(J.length,z.length),G=[];for(let Q=0;Q<X;Q++)J[Q]!==z[Q]&&G.push(Q);return{lines:G,numLinesBefore:J.length,numLinesAfter:z.length,numLines:X}}var OF=globalThis.process.platform.startsWith("win"),g3=Symbol("clack:cancel");function w3($){return $===g3}function x3($,Z){let J=$;J.isTTY&&J.setRawMode(Z)}var v4=($)=>("rows"in $)&&typeof $.rows=="number"?$.rows:20;function g4($,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 T1{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return eJ(this.opts.accessible)}constructor($,Z=!0){let{input:J=iJ,output:z=nJ,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(),$(g3);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=oJ.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),x3(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(G0.cursor.show),this.output.off("resize",this.render),x3(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(G0.cursor.show),this.output.off("resize",this.render),x3(this.input,!1),$(g3)})})}_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&&Y0.aliases.has(Z.name)&&this.emit("cursor",Y0.aliases.get(Z.name)),Y0.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=g4(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")}y4([$,Z?.name,Z?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
34
34
|
`),x3(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let $=b3(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
35
35
|
`).length-1;this.output.write(G0.cursor.move(-999,$*-1))}render(){let $=b3(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if($!==this._prevFrame){if(this.state==="initial")this.output.write(G0.cursor.hide);else{let Z=$z(this._prevFrame,$),J=v4(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(G0.cursor.move(0,G-X)),this.output.write(G0.erase.lines(1));let Q=$.split(`
|
|
36
36
|
`);this.output.write(Q[G]),this._prevFrame=$,this.output.write(G0.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(G0.cursor.move(0,W))}this.output.write(G0.erase.down());let Q=$.split(`
|
|
@@ -40,7 +40,7 @@ ${Q.stderrTail}`]:[]].join(`
|
|
|
40
40
|
${z}`:`${Z}${v3("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))}#Y($){let Z=this.value??"";switch($){case"up":this._cursor=f3(this._cursor,0,-1,Z);return;case"down":this._cursor=f3(this._cursor,0,1,Z);return;case"left":this._cursor=f3(this._cursor,-1,0,Z);return;case"right":this._cursor=f3(this._cursor,1,0,Z);return}}_shouldSubmit($,Z){if(this.#Z)return this.focused==="submit"?!0:(this.#z(`
|
|
41
41
|
`),this._cursor++,!1);let J=this.#$;return this.#$=!0,J&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
|
|
42
42
|
`&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#z(`
|
|
43
|
-
`),this._cursor++,!1)}constructor($){let Z=$.initialUserInput??$.initialValue;super({...$,initialUserInput:Z},!1),Z!==void 0&&(this._cursor=Z.length),this.#Z=$.showSubmit??!1,this.on("key",(J,z)=>{if(z?.name&&Hz.has(z.name)){this.#$=!1,this.#Y(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 _$ extends T1{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}${v3("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 y,stripVTControlCharacters as
|
|
43
|
+
`),this._cursor++,!1)}constructor($){let Z=$.initialUserInput??$.initialValue;super({...$,initialUserInput:Z},!1),Z!==void 0&&(this._cursor=Z.length),this.#Z=$.showSubmit??!1,this.on("key",(J,z)=>{if(z?.name&&Hz.has(z.name)){this.#$=!1,this.#Y(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 _$ extends T1{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}${v3("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 y,stripVTControlCharacters as vF}from"node:util";import H0 from"node:process";var c4=x4(P$(),1);function Uz(){if(H0.platform!=="win32")return H0.env.TERM!=="linux";return Boolean(H0.env.CI)||Boolean(H0.env.WT_SESSION)||Boolean(H0.env.TERMINUS_SUBLIME)||H0.env.ConEmuTask==="{cmd::Cmder}"||H0.env.TERM_PROGRAM==="Terminus-Sublime"||H0.env.TERM_PROGRAM==="vscode"||H0.env.TERM==="xterm-256color"||H0.env.TERM==="alacritty"||H0.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Kz=Uz();var v=($,Z)=>Kz?$:Z,u4=v("◆","*"),qz=v("■","x"),Fz=v("▲","x"),Bz=v("◇","o"),hF=v("┌","T"),e0=v("│","|"),I$=v("└","—"),uF=v("┐","T"),cF=v("┘","—"),pF=v("●",">"),dF=v("○"," "),lF=v("◻","[•]"),aF=v("◼","[+]"),sF=v("◻","[ ]"),nF=v("▪","•"),iF=v("─","-"),oF=v("╮","+"),rF=v("├","+"),tF=v("╯","+"),eF=v("╰","+"),$B=v("╭","+"),ZB=v("●","•"),JB=v("◆","*"),zB=v("▲","!"),XB=v("■","x"),Vz=($)=>{switch($){case"initial":case"active":return y("cyan",u4);case"cancel":return y("red",qz);case"error":return y("yellow",Fz);case"submit":return y("green",Bz);case"validating":return y("dim",u4)}};var GB=[`${y("dim","↑/↓")} to navigate`,`${y("dim","Space:")} select`,`${y("dim","Enter:")} confirm`];var QB={light:v("─","-"),heavy:v("━","="),block:v("█","#")};var WB=[`${y("dim","↑/↓")} to navigate`,`${y("dim","Enter:")} confirm`];var YB=`${y("gray",e0)} `;var p4=($)=>new _$({validate:$.validate,placeholder:$.placeholder,defaultValue:$.defaultValue,initialValue:$.initialValue,output:$.output,signal:$.signal,input:$.input,render(){let Z=$?.withGuide??Y0.withGuide,J=`${`${Z?`${y("gray",e0)}
|
|
44
44
|
`:""}${Vz(this.state)} `}${$.message}
|
|
45
45
|
`,z=$.placeholder&&$.placeholder.length>0?y("inverse",$.placeholder[0])+y("dim",$.placeholder.slice(1)):y(["inverse","hidden"],"_"),X=this.userInput?this.userInputWithCursor:z,G=this.value??"";switch(this.state){case"validating":{let Q=Z?`${y("cyan",e0)} `:"",W=Z?y("cyan",I$):"",Y=y("dim",X),H=y("dim","Validating...");return`${J}${Q}${Y}
|
|
46
46
|
${W} ${H}
|
|
@@ -63,7 +63,7 @@ Setup --yes selects every found host, including Pi. Run setup without --yes to c
|
|
|
63
63
|
Run setup --help to list every setup option.
|
|
64
64
|
Native credentials are managed by the offline setup migration.
|
|
65
65
|
Legacy import source:
|
|
66
|
-
${az()}`)}function S$($,Z){let J=$?.trim();if(!J)throw Error(`${Z} is required`);return J}async function d3($){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 rz($,Z,J,z){return d3({token:$,method:"POST",path:`/accounts/${Z}/storage/kv/namespaces`,body:JSON.stringify({title:J}),fetchImpl:z})}async function tz($){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([oz],{type:"application/javascript+module"}),"worker.js"),d3({token:$.token,method:"PUT",path:`/accounts/${$.accountId}/workers/scripts/${$.scriptName}`,body:J,fetchImpl:$.fetchImpl})}async function ez($,Z,J,z){await d3({token:$,method:"POST",path:`/accounts/${Z}/workers/scripts/${J}/subdomain`,body:JSON.stringify({enabled:!0,previews_enabled:!1}),fetchImpl:z})}async function $X($,Z,J){return d3({token:$,method:"GET",path:`/accounts/${Z}/workers/subdomain`,fetchImpl:J}).catch(()=>null)}async function ZX($={}){await k1((B)=>B.
|
|
66
|
+
${az()}`)}function S$($,Z){let J=$?.trim();if(!J)throw Error(`${Z} is required`);return J}async function d3($){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 rz($,Z,J,z){return d3({token:$,method:"POST",path:`/accounts/${Z}/storage/kv/namespaces`,body:JSON.stringify({title:J}),fetchImpl:z})}async function tz($){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([oz],{type:"application/javascript+module"}),"worker.js"),d3({token:$.token,method:"PUT",path:`/accounts/${$.accountId}/workers/scripts/${$.scriptName}`,body:J,fetchImpl:$.fetchImpl})}async function ez($,Z,J,z){await d3({token:$,method:"POST",path:`/accounts/${Z}/workers/scripts/${J}/subdomain`,body:JSON.stringify({enabled:!0,previews_enabled:!1}),fetchImpl:z})}async function $X($,Z,J){return d3({token:$,method:"GET",path:`/accounts/${Z}/workers/subdomain`,fetchImpl:J}).catch(()=>null)}async function ZX($={}){await k1((B)=>B.assertRelayLocation());let Z=$.fetchImpl??fetch,J=$.prompt??p3,z=$.warn??((B)=>console.warn(B)),X=S$(process.env.CLOUDFLARE_API_TOKEN?.trim()||await J("Cloudflare API token: "),"Cloudflare API token");$.secrets?.push(X);let G=S$(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`,Y=lz();$.secrets?.push(Y),console.log("Creating Cloudflare KV namespace...");let H=await rz(X,G,W,Z);console.log("Uploading relay Worker..."),await tz({token:X,accountId:G,scriptName:Q,kvNamespaceId:H.id,relayToken:Y,fetchImpl:Z}),await ez(X,G,Q,Z).catch(async(B)=>{z(await r0("cli-relay-workers-dev",B,process.env,[X,Y]))});let U=await $X(X,G,Z),F=(U?.subdomain?`https://${Q}.${U.subdomain}.workers.dev`:"")||S$(await p3("Relay Worker URL: "),"Relay Worker URL");await k1((B)=>B.updateRelay({enabled:!0,url:F,token:Y,fallbackToDirect:!0,transport:"http"})),console.log(`Relay enabled at ${F}`),console.log("Relay settings saved to the native account store.")}var c3=null;async function p3($){return c3??=mz({input:gz,output:wz}),(await c3.question($)).trim()}function JX(){c3?.close(),c3=null}async function zX($,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??p3,z=Z.authorize??hz,X=Z.exchange??pz;await u3(),await k1(async(G)=>{let Q=await G.read(),W=$?.trim()||await J("Fallback account label (optional): "),Y=await z("max");console.log(`
|
|
67
67
|
Open this URL in your browser and complete Claude sign-in:
|
|
68
68
|
`),console.log(`${Y.url}
|
|
69
69
|
`);let H=await J("Paste the full callback URL or authorization code here: ");Z.secrets?.push(H);let U=await X(H,Y.verifier,Y.redirectUri,Y.state);if(U.type==="failed")throw Error("Authentication failed");if(Z.secrets?.push(U.access,U.refresh),process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Local login cannot be verified while OPENCODE_AUTH_CONTENT is set");await u3();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:U.access,refresh:U.refresh,expires:U.expires}}),console.log(`
|