@cortexkit/opencode-anthropic-auth 2.2.0 → 2.2.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 +1 -1
- package/dist/{index-f2ne65w4.js → index-62x1p34p.js} +1 -1
- package/dist/{index-pden7a7y.js → index-88zg9ztr.js} +1 -1
- package/dist/{index-ccrq4mra.js → index-8ysjtqek.js} +1 -1
- package/dist/{index-ah5s0bew.js → index-ppdrzs41.js} +1 -1
- package/dist/index-xbwa4x53.js +2 -0
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.d.ts +53 -0
- package/dist/sidebar-state.js +1 -1
- package/dist/tui/claude-sidebar.d.ts +5 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.js +1 -1
- package/dist/v2/tui.js +1 -1
- package/package.json +2 -2
- package/src/sidebar-state.ts +125 -0
- package/src/tui/claude-sidebar.tsx +164 -93
- package/src/tui-compiled/sidebar-state.ts +125 -0
- package/src/tui-compiled/tui/claude-sidebar.tsx +288 -231
- package/dist/index-czyrqpxc.js +0 -2
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{x as s1}from"./index-0kxy8k2c.js";import{A as n9,B as R2,C as S2,D as k2,E as E2,F as i9,z as s9}from"./index-b1dvkp15.js";import{ca as x9,da as T8,ea as Q3}from"./index-f2ne65w4.js";var j$=T8((zH,T9)=>{var K$={to($,Z){if(!Z)return`\x1B[${$+1}G`;return`\x1B[${Z+1};${$+1}H`},move($,Z){let J="";if($<0)J+=`\x1B[${-$}D`;else if($>0)J+=`\x1B[${$}C`;if(Z<0)J+=`\x1B[${-Z}A`;else if(Z>0)J+=`\x1B[${Z}B`;return J},up:($=1)=>`\x1B[${$}A`,down:($=1)=>`\x1B[${$}B`,forward:($=1)=>`\x1B[${$}C`,backward:($=1)=>`\x1B[${$}D`,nextLine:($=1)=>"\x1B[E".repeat($),prevLine:($=1)=>"\x1B[F".repeat($),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},f8={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},g8={screen:"\x1B[2J",up:($=1)=>"\x1B[1J".repeat($),down:($=1)=>"\x1B[J".repeat($),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines($){let Z="";for(let J=0;J<$;J++)Z+=this.line+(J<$-1?K$.up():"");if($)Z+=K$.left;return Z}};T9.exports={cursor:K$,scroll:f8,erase:g8,beep:"\x07"}});import{stdin as j5,stdout as M5}from"node:process";import{createInterface as F5}from"node:readline/promises";import{authorize as B5,createNativeAccountRuntime as D5,exchange as L5,formatNativeAccountState as N5,generateRelayToken as C5,getAccountStoragePath as P5,isValidApiBaseURL as O5,readNativeEnrollmentMode as _5,resolveNativePoolPaths as I5,WORKER_SCRIPT as A5}from"@cortexkit/anthropic-auth-core";import{randomUUID as z6}from"node:crypto";import{constants as E1}from"node:fs";import{lstat as Q6,mkdir as G6,open as X6}from"node:fs/promises";import{homedir as W6}from"node:os";import{isAbsolute as d2,join as o3}from"node:path";import{types as e3}from"node:util";import{createProviderErrorRedactor as n2,createWindowsOwnerOnly as H6,ensureWindowsOwnerOnlyDirectory as U6,formatLogLine as Y6,isOwnerOnly as q6,isSecretKey as V6,NativeMigrationError as K6,NativePiAuthSlotError as j6,setupEnrollment as M6}from"@cortexkit/anthropic-auth-core";import{readFile as a7}from"node:fs/promises";import{assertHostsStopped as s7,createNativeAccountRuntime as n7,discoverNativeVaultInventory as i7,inspectNativeHostAuthEntry as a3,NativePiAuthSlotError as r7,nativePiAuthSlotPaths as o7,openNativePiAuthSlot as n3,readNativeEnrollmentMode as t7,requireNoSupervisedAuthContentSnapshot as e7}from"@cortexkit/anthropic-auth-core";import{dirname as C7}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as P7,CLAUSTRUM_PI_ENROLLMENT_NAME as O7,getHostClaustrumEnrollmentPaths as _7,resolveClaustrumConnectionPath as I7}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as Tz}from"@cortexkit/claustrum-client";import{ClaustrumClient as jz}from"@cortexkit/claustrum-client";import{resolve as P$}from"node:path";import{storeIdentity as l5}from"@cortexkit/claustrum-client";import{SubcClient as s5}from"@cortexkit/subc-client";import{ClaustrumCredentialError as t9}from"@cortexkit/claustrum-client";import{SocketClosedError as e9,SocketTimeoutError as $4,SubcCallError as Z4}from"@cortexkit/subc-client";class _ extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var t1=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class L0 extends _{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function K0($){if($ instanceof L0||$ instanceof e9||$ instanceof $4)return"unreachable";let Z=$ instanceof t9||$ instanceof Z4?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(t1,Z))return"answered";return t1[Z]}var e1=300000,V1=300000,$3=1000;class s0{#$;#z=0;restart(){this.#z=0}continuous($){let Z=$.kind==="changed"&&$.seq===this.#z+1&&(this.#$===void 0||$.epoch===this.#$);return this.#$=$.epoch,this.#z=$.seq,Z}}class K1{#$;#z;#Z;#Q=!1;constructor($,Z){this.#$=$,this.#z=Z}get running(){return this.#Z}request(){if(this.#Z)return this.#Q=!0,this.#Z;return this.#Z=(async()=>{do{this.#Q=!1;try{await this.#$()}catch($){this.#z($)}}while(this.#Q)})().finally(()=>{this.#Z=void 0}),this.#Z}}class j1{#$;#z=new s0;#Z;#Q="polling";#H;#G;#J=!1;#U;#V=!1;#W=0;constructor($){this.#$=$,this.#Z=new K1(async()=>{let Z=this.#V;if(this.#V=!1,Z||this.#U!==this.#$.view())await this.#$.discover(this.#U??"")},(Z)=>{if(!this.#J)this.#$.onError?.(Z)})}get mode(){return this.#Q}start(){if(this.#J||this.#H||this.#G)return;if(typeof this.#$.client.watchScoped!=="function"){this.#X("fallback","client-without-watch");return}this.#j(!1)}stop(){if(this.#J)return;if(this.#J=!0,this.#G)(this.#$.clearTimeoutImpl??clearTimeout)(this.#G);this.#G=void 0;let $=this.#H;this.#H=void 0,$?.handle.stop()}#X($,Z){if(this.#Q===$)return;this.#Q=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#q($,Z){this.#G=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#G=void 0,!this.#J)Z()},$),this.#G.unref?.()}async#j($){let Z;try{Z=await this.#$.enrollmentToken()}catch(X){if(this.#J)return;this.#$.onError?.(X),this.#F("token-unreadable");return}let J=this.#$.client.watchScoped;if(this.#J||this.#H||!J)return;this.#z.restart(),this.#V=$;let z,Q;try{Q=J.call(this.#$.client,(X)=>{if(this.#J||!z||this.#H!==z)return;if(z.notices++,z.notices===1)this.#$.onReachable?.(),z.acceptedAt=(this.#$.now??Date.now)(),this.#X("watching","accepted");if(!this.#z.continuous(X))this.#V=!0;this.#U=X.view,this.#Z.request()},{enrollmentToken:Z})}catch(X){this.#$.onError?.(X),this.#F("watch-failed");return}z={handle:Q,notices:0},this.#H=z,this.#X("polling",$?"resubscribing":"opening");let G=z;Q.closed.then((X)=>this.#K(G,X),(X)=>this.#K(G,{kind:"transport_lost",error:X}))}#K($,Z){if(this.#J||this.#H!==$)return;if(this.#H=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#X("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#F("refused");try{this.#$.onRefused(Z.error)}catch(J){this.#$.onError?.(J)}return}if($.notices>0){let J=(this.#$.now??Date.now)();if($.acceptedAt!==void 0&&J-$.acceptedAt>=300000)this.#W=0;let z=Math.min(1000*2**Math.min(this.#W,16),300000);this.#W++,this.#X("polling","resubscribing"),this.#q(z,()=>void this.#j(!0));return}this.#F(Z.kind)}#F($){this.#X("fallback",$),this.#q(300000,()=>void this.#j(!1))}}var F1=60000,O$=4*F1,J4=2*F1,Z3=new Map,M1=new Map;function n0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function z4($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!n0(Z)||typeof Z.kind!=="string"||typeof Z.epoch!=="string"||Z.epoch.length===0||typeof Z.seq!=="number"||!Number.isSafeInteger(Z.seq)||Z.seq<1||Z.provider!==void 0&&typeof Z.provider!=="string")return;return{kind:Z.kind,epoch:Z.epoch,seq:Z.seq,...typeof Z.provider==="string"&&{provider:Z.provider}}}function Q4($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class _${transport;key;#$=[];#z=!1;#Z=new Set;#Q=new Map;#H=new K1(async()=>{try{let $=await this.transport.getUsage();if(!n0($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>n0(Z)&&typeof Z.provider==="string"),this.#z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#Z=new Set(this.#z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#Z)this.#Q.delete(Z)}catch{this.#$=[],this.#z=!1,this.#Z.clear()}},()=>{});#G=new s0;#J="polling";#U=0;#V=0;#W=new Map;#X;#q;#j={};#K=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#H.running)return this.#H.running;if(this.#J==="watching")return Promise.resolve();for(let[J,z]of M1)if($-z>=F1)M1.delete(J);let Z=M1.get(this.key);if(Z!==void 0&&$-Z<F1)return Promise.resolve();return M1.set(this.key,$),this.#H.request()}watchMode(){return this.#J}watch($={}){this.#U++;let Z=$.provider;if(Z===void 0)this.#V++;else this.#W.set(Z,(this.#W.get(Z)??0)+1);if(this.#U===1)this.#j=$,this.#M();let J=!1;return()=>{if(J)return;if(J=!0,Z===void 0)this.#V--;else{let z=(this.#W.get(Z)??1)-1;if(z>0)this.#W.set(Z,z);else this.#W.delete(Z)}if(--this.#U===0)this.#F()}}#F(){if(this.#q)(this.#j.clearTimeoutImpl??clearTimeout)(this.#q);this.#q=void 0;let $=this.#X;this.#X=void 0,$?.handle?.stop(),this.#J="polling"}#Y($){this.#q=(this.#j.setTimeoutImpl??setTimeout)(()=>{if(this.#q=void 0,this.#U>0&&!this.#X)this.#M()},$),this.#q.unref?.()}#M(){let $=this.transport.watchUsage;if(!$){this.#J="fallback";return}this.#J="polling",this.#G.restart();let Z={notices:0};this.#X=Z;let J;try{J=$.call(this.transport,(z)=>this.#N(Z,z))}catch(z){this.#B(Z,z);return}Z.handle=J,J.closed.then(()=>this.#B(Z,void 0),(z)=>this.#B(Z,z))}#N($,Z){if(this.#X!==$)return;if($.notices++,$.notices===1)this.#J="watching";if($.notices===2)this.#K=0;let J=z4(Z);if(!J)this.#G.restart();if(!(J?this.#G.continuous(J):!1)||J?.provider===void 0||this.#V>0||this.#W.has(J.provider))this.#H.request()}#B($,Z){if(this.#X!==$)return;this.#X=void 0;let J=Q4(Z);if(J==="unknown_method"||J==="usage_watch_limit"){this.#J="fallback";return}if($.notices>0){let z=Math.min($3*2**Math.min(this.#K,16),V1);this.#K++,this.#J="polling",this.#Y(z);return}if(this.#J="fallback",this.#H.request(),Z===void 0||K0(Z)==="unreachable")this.#Y(V1)}current($,Z,J){for(let z of this.#$){if(z.provider!==$||typeof z.account!=="string"||z.account.trim()!==Z)continue;if(z.stale!==void 0||z.errorClass!==void 0||!n0(z.usage))continue;let Q=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(Q)||J-Q>=O$)continue;return{entry:z,context:{fetchedAt:Q,...typeof z.source==="string"&&{source:z.source}}}}return}lookup($,Z,J){if(!this.#z)return{miss:"unreachable"};let z=this.#$.find((X)=>X.provider===$&&typeof X.account==="string"&&X.account.trim()===Z),Q=(z??this.#$.find((X)=>X.provider===$&&X.account===void 0&&X.errorClass!==void 0))?.errorClass;if(Q==="upstream_failed")return{miss:"upstream-failed"};if(Q==="credential_absent"||Q==="credential_unusable"||Q==="credential_rejected")return{miss:"credential"};if(Q!==void 0)return{miss:"unreachable"};if(z){let X=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!n0(z.usage)||!Number.isFinite(X))return{miss:"unreachable"};let W={entry:z,context:{fetchedAt:X,...typeof z.source==="string"&&{source:z.source}}};return J>=X+O$||z.stale!==void 0?{miss:"stale",reading:W}:{reading:W}}if(this.#Z.has($))return{miss:"absent"};let G=this.#Q.get($)??J;return this.#Q.set($,G),{miss:J-G>=J4?"unreachable":"cold"}}}function J3($,Z){let J=JSON.stringify([P$($.connectionFile),P$(Z)]),z=Z3.get(J);if(!z)z={source:new _$($,J),refs:0},Z3.set(J,z);z.refs++;let Q=!1;return{source:z.source,release(){if(Q)return;if(Q=!0,--z.refs===0)Z3.delete(J)}}}import{ClaustrumCredentialError as Dz}from"@cortexkit/claustrum-client";import{appendFileSync as j4,chmodSync as M4,existsSync as X3,renameSync as T$,statSync as F4}from"node:fs";import{open as B4}from"node:fs/promises";import{dirname as D4,resolve as L4}from"node:path";import{randomUUID as G4}from"node:crypto";import{lstat as R$,readFile as S$,rename as X4,unlink as I$}from"node:fs/promises";import{dirname as j0,resolve as n}from"node:path";var I=process.platform==="win32",A$=new Set;function z3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var b$;function T0(){return b$??=import("@cortexkit/private-files"),b$}class u extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor($,Z,J){let z=J;super(`Private file refused at ${Z}: ${$} (${z?.reason??z?.code??"io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`,{cause:J});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=z3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}async function l($,Z,J){try{return await J()}catch(z){if(z instanceof u)throw z;throw new u($,Z,z)}}var W4;async function X0($,Z){$=n($),Z??=W4,await l($,"safe-parent",async()=>{let J=await(await T0()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await R$($);throw new u(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function p($,Z,J=!1){if($=n($),Z==="directory")return X0($);await l($,"verify",async()=>{let z=await T0(),Q=await z.verifyOwnerOnly($),G=!1;if(!Q.ok){let{reason:X}=Q.refusal;if(X==="io-error")await z.verifyPrivatePath($,Z);if(J&&[z.EXTRA_ACE,z.NOT_PROTECTED,z.NULL_DACL,z.EMPTY_DACL].includes(X))await X0(j0($)),await z.securePrivatePath($,Z),G=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:X,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await z.verifyPrivatePath($,Z),G&&!A$.has($))A$.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function J0($,Z=!1,J){$=n($),await l($,"directory",async()=>{let z=await T0();try{return await R$($),await X0($,J)}catch(G){if(z3(G)!=="ENOENT")throw G}let Q=j0($);if(Q===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await J0(Q,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(z3(G)!=="EEXIST")throw G}await X0($,J)})}async function o($,Z=!1){if(!I)return S$($,"utf8");return(await H4($,Z)).toString("utf8")}async function H4($,Z=!1){if(!I)return S$($);if($=n($),Z)await X0(j0($)),await p($,"file",!0);return l($,"read",async()=>(await T0()).readOwnerOnly($))}async function f0($,Z){await X0(j0(n($))),await l($,"create",async()=>{await(await T0()).createPrivateFile(n($),Z)})}async function k$($){await X0(j0(n($))),await l($,"directory-create",async()=>{await(await T0()).createOwnerOnly(n($),{kind:"dir"})})}async function G3($,Z,J={}){$=n($),Z=n(Z);let z=J.now??(()=>performance.now()),Q=z(),G=J.deadline??1/0,X,W=[0,10,20,40,80,100],H,Y=0;for(let V of W){let B=Math.min(X??1/0,G);if(z()>=B)break;if(V)await(J.sleep??((F)=>new Promise((D)=>setTimeout(D,F))))(Math.min(V,Math.max(0,B-z())));if(z()>=B)break;let L=z();if(await J.beforeRename?.(),X!==void 0)X+=z()-L;if(z()>=G)break;Y++;try{return await(J.rename??X4)($,Z),{attempts:Y,elapsedMs:z()-Q}}catch(F){H??=F;let D=F;if(!(D.win32Code!==void 0?D.win32Code===32||D.win32Code===33:["EBUSY","EPERM","EACCES"].includes(D.code??"")&&!D.reason))break;X??=z()+500}}let q=new u(Z,"rename",H??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw q.attempts=Y,q.elapsedMs=z()-Q,q}async function g0($,Z,J={}){$=n($),await J0(j0($));try{await p($,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}let z=n(J.stagePath??`${$}.${G4()}.tmp`);if(j0(z)!==j0($))throw new u($,"stage-directory",{code:"EXDEV"});let Q=!1,G=!1,X={attempts:0,elapsedMs:0},W="stage-create",H=(Y)=>{try{J.onOutcome?.({path:$,stage:Y?.stage??"published",published:G,fileDurable:G,durabilityConfirmed:!1,attempts:Y?.attempts??X.attempts,elapsedMs:Y?.elapsedMs??X.elapsedMs,...Y&&{code:Y.code,win32Code:Y.win32Code}})}catch{}};try{if(await f0(z,Z),Q=!0,W="before-rename",X=await G3(z,$,J),Q=!1,G=!0,W="published-callback",J.onRenamed?.(),W="published-verify",await p($,"file"),J.durable&&J.durability!=="file-only-on-windows")throw new u($,"directory-sync-unsupported",{code:"ENOTSUP"});H()}catch(Y){let q=Y instanceof u?Y:new u($,W,Y);if(q.published=G,q.fileDurable=G,G)Object.assign(q,X);if(Q){try{await I$(z)}catch{q.orphanPath=z}Q=!1}throw H(q),q}finally{if(Q)await I$(z).catch(()=>{})}}var U4=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,Y4=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function q4($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function x0($={}){let Z=[Y4,...$.extraValuePatterns??[]].map((G)=>new RegExp(G.source,G.flags.includes("g")?G.flags:`${G.flags}g`));function J(G){let X=G.toLowerCase().replace(/[-_]/g,"");return U4.test(G)||X.includes("apikey")||X.endsWith("secret")||X.endsWith("password")||X.endsWith("token")&&!X.endsWith("tokens")||!!$.extraSecretKeys?.(X)}function z(G){let X=G,W=[["name",G.name],["message",G.message],["stack",G.stack]];for(let Y of["code","status","cause"])if(X[Y]!==void 0)W.push([Y,X[Y]]);let H=new Set(W.map(([Y])=>Y));for(let Y of Object.entries(G))if(!H.has(Y[0]))W.push(Y);return W}function Q(G,X,W,H=0){if(typeof G==="string")return Z.reduce((Y,q)=>Y.replace(q,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if(W.has(G))return"[Circular]";W.add(G);try{if(Array.isArray(G))return G.map((V)=>Q(V,X,W,H));let Y=q4(G);if(Y&&H>=8)return"[Truncated]";let q=Y?H+1:H;return Object.fromEntries((Y?z(G):Object.entries(G)).map(([V,B])=>[V,X&&J(V)?"***REDACTED***":Q(B,X,W,q)]))}finally{W.delete(G)}}return{redact:(G)=>Q(G,!0,new WeakSet),redactStrings:(G)=>Q(G,!1,new WeakSet)}}var E$=x0(),V4=E$.redact,K4=E$.redactStrings;var B1={error:0,warn:1,info:2,debug:3,trace:4},g$=5242880,x$=3;function W3($){try{M4($,384)}catch{}}function N4($){try{if(!(X3($)&&F4($).size>=g$))return;for(let J=x$-1;J>=1;J--)if(X3(`${$}.${J}`)){let z=`${$}.${J+1}`;T$(`${$}.${J}`,z),W3(z)}let Z=`${$}.1`;T$($,Z),W3(Z)}catch{}}async function W0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await l(Z,"log-close",()=>J.close())}async function f$($,Z){await J0(D4(Z));try{await p(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await f0(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await p(Z,"file",!0)}}return $.handle=await l(Z,"log-open",()=>B4(Z,"a")),$.file=Z,$.handle}async function C4($,Z,J){Z=L4(Z);try{if($.file!==Z)await W0($);let z=$.handle??await f$($,Z);if((await l(Z,"log-stat",()=>z.stat())).size>=g$){await W0($);for(let G=x$-1;G>=0;G--){let X=G===0?Z:`${Z}.${G}`,W=`${Z}.${G+1}`;try{await p(X,"file",!0)}catch(H){if(H.code==="ENOENT")continue;throw H}try{await p(W,"file",!0)}catch(H){if(H.code!=="ENOENT")throw H}await G3(X,W),await p(W,"file")}z=await f$($,Z)}await l(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await W0($).catch(()=>{}),z}}function P4($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function O4($){let Z,J,z,Q=x0(),G,X=[],W,H=Promise.resolve(),Y,q={};function V(U){let K=H.then(U);return H=K.catch((j)=>{Y=j}),K}function B(U){if(I&&U.file!==Z)V(()=>W0(q)).catch(()=>{});Z=U.file,J=U.level,Q=x0(U),G=U.captureSink}function L(U){if(U===void 0||U in B1)z=U}function F(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function D(){if(z)return z;let U=typeof J==="function"?J():J;if(U&&U in B1)return U;return"info"}function P(U=!0){if(W)clearTimeout(W),W=void 0;if(!X.length){if(I)return V(async()=>{if(U)await W0(q);if(Y)throw Y});return}let K;try{K=F()}catch{if(X=[],I&&U)return V(()=>W0(q));return}let j=X.join("");if(X=[],!K){if(I&&U)return V(()=>W0(q));return}if(I)return V(async()=>{try{await C4(q,K,j)}finally{if(U)await W0(q)}});try{if(N4(K),X3(K))W3(K);j4(K,j,{encoding:"utf8",mode:384})}catch{}}function R(){if(!W)W=setTimeout(()=>{W=void 0;let U=P(!1);if(U instanceof Promise)U.catch(()=>{})},500)}function f(U,K,j,b){if(Z===void 0&&G===void 0)return;try{if(B1[K]>B1[D()])return;let g=Q.redactStrings(j),S;try{S=Q.redact(b)}catch{S="[unserializable]"}let m=`[${new Date().toISOString()}] ${K.toUpperCase()} [${U}] ${g}`+(b===void 0?"":P4(S))+`
|
|
2
|
+
import{x as s1}from"./index-0kxy8k2c.js";import{A as n9,B as R2,C as S2,D as k2,E as E2,F as i9,z as s9}from"./index-b1dvkp15.js";import{ha as x9,ia as T8,ja as Q3}from"./index-62x1p34p.js";var j$=T8((zH,T9)=>{var K$={to($,Z){if(!Z)return`\x1B[${$+1}G`;return`\x1B[${Z+1};${$+1}H`},move($,Z){let J="";if($<0)J+=`\x1B[${-$}D`;else if($>0)J+=`\x1B[${$}C`;if(Z<0)J+=`\x1B[${-Z}A`;else if(Z>0)J+=`\x1B[${Z}B`;return J},up:($=1)=>`\x1B[${$}A`,down:($=1)=>`\x1B[${$}B`,forward:($=1)=>`\x1B[${$}C`,backward:($=1)=>`\x1B[${$}D`,nextLine:($=1)=>"\x1B[E".repeat($),prevLine:($=1)=>"\x1B[F".repeat($),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},f8={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},g8={screen:"\x1B[2J",up:($=1)=>"\x1B[1J".repeat($),down:($=1)=>"\x1B[J".repeat($),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines($){let Z="";for(let J=0;J<$;J++)Z+=this.line+(J<$-1?K$.up():"");if($)Z+=K$.left;return Z}};T9.exports={cursor:K$,scroll:f8,erase:g8,beep:"\x07"}});import{stdin as j5,stdout as M5}from"node:process";import{createInterface as F5}from"node:readline/promises";import{authorize as B5,createNativeAccountRuntime as D5,exchange as L5,formatNativeAccountState as N5,generateRelayToken as C5,getAccountStoragePath as P5,isValidApiBaseURL as O5,readNativeEnrollmentMode as _5,resolveNativePoolPaths as I5,WORKER_SCRIPT as A5}from"@cortexkit/anthropic-auth-core";import{randomUUID as z6}from"node:crypto";import{constants as E1}from"node:fs";import{lstat as Q6,mkdir as G6,open as X6}from"node:fs/promises";import{homedir as W6}from"node:os";import{isAbsolute as d2,join as o3}from"node:path";import{types as e3}from"node:util";import{createProviderErrorRedactor as n2,createWindowsOwnerOnly as H6,ensureWindowsOwnerOnlyDirectory as U6,formatLogLine as Y6,isOwnerOnly as q6,isSecretKey as V6,NativeMigrationError as K6,NativePiAuthSlotError as j6,setupEnrollment as M6}from"@cortexkit/anthropic-auth-core";import{readFile as a7}from"node:fs/promises";import{assertHostsStopped as s7,createNativeAccountRuntime as n7,discoverNativeVaultInventory as i7,inspectNativeHostAuthEntry as a3,NativePiAuthSlotError as r7,nativePiAuthSlotPaths as o7,openNativePiAuthSlot as n3,readNativeEnrollmentMode as t7,requireNoSupervisedAuthContentSnapshot as e7}from"@cortexkit/anthropic-auth-core";import{dirname as C7}from"node:path";import{CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as P7,CLAUSTRUM_PI_ENROLLMENT_NAME as O7,getHostClaustrumEnrollmentPaths as _7,resolveClaustrumConnectionPath as I7}from"@cortexkit/anthropic-auth-core";import{writeEnrollmentTokenFile as Tz}from"@cortexkit/claustrum-client";import{ClaustrumClient as jz}from"@cortexkit/claustrum-client";import{resolve as P$}from"node:path";import{storeIdentity as l5}from"@cortexkit/claustrum-client";import{SubcClient as s5}from"@cortexkit/subc-client";import{ClaustrumCredentialError as t9}from"@cortexkit/claustrum-client";import{SocketClosedError as e9,SocketTimeoutError as $4,SubcCallError as Z4}from"@cortexkit/subc-client";class _ extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var t1=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class L0 extends _{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function K0($){if($ instanceof L0||$ instanceof e9||$ instanceof $4)return"unreachable";let Z=$ instanceof t9||$ instanceof Z4?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(t1,Z))return"answered";return t1[Z]}var e1=300000,V1=300000,$3=1000;class s0{#$;#z=0;restart(){this.#z=0}continuous($){let Z=$.kind==="changed"&&$.seq===this.#z+1&&(this.#$===void 0||$.epoch===this.#$);return this.#$=$.epoch,this.#z=$.seq,Z}}class K1{#$;#z;#Z;#Q=!1;constructor($,Z){this.#$=$,this.#z=Z}get running(){return this.#Z}request(){if(this.#Z)return this.#Q=!0,this.#Z;return this.#Z=(async()=>{do{this.#Q=!1;try{await this.#$()}catch($){this.#z($)}}while(this.#Q)})().finally(()=>{this.#Z=void 0}),this.#Z}}class j1{#$;#z=new s0;#Z;#Q="polling";#H;#G;#J=!1;#U;#V=!1;#W=0;constructor($){this.#$=$,this.#Z=new K1(async()=>{let Z=this.#V;if(this.#V=!1,Z||this.#U!==this.#$.view())await this.#$.discover(this.#U??"")},(Z)=>{if(!this.#J)this.#$.onError?.(Z)})}get mode(){return this.#Q}start(){if(this.#J||this.#H||this.#G)return;if(typeof this.#$.client.watchScoped!=="function"){this.#X("fallback","client-without-watch");return}this.#j(!1)}stop(){if(this.#J)return;if(this.#J=!0,this.#G)(this.#$.clearTimeoutImpl??clearTimeout)(this.#G);this.#G=void 0;let $=this.#H;this.#H=void 0,$?.handle.stop()}#X($,Z){if(this.#Q===$)return;this.#Q=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#q($,Z){this.#G=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#G=void 0,!this.#J)Z()},$),this.#G.unref?.()}async#j($){let Z;try{Z=await this.#$.enrollmentToken()}catch(X){if(this.#J)return;this.#$.onError?.(X),this.#F("token-unreadable");return}let J=this.#$.client.watchScoped;if(this.#J||this.#H||!J)return;this.#z.restart(),this.#V=$;let z,Q;try{Q=J.call(this.#$.client,(X)=>{if(this.#J||!z||this.#H!==z)return;if(z.notices++,z.notices===1)this.#$.onReachable?.(),z.acceptedAt=(this.#$.now??Date.now)(),this.#X("watching","accepted");if(!this.#z.continuous(X))this.#V=!0;this.#U=X.view,this.#Z.request()},{enrollmentToken:Z})}catch(X){this.#$.onError?.(X),this.#F("watch-failed");return}z={handle:Q,notices:0},this.#H=z,this.#X("polling",$?"resubscribing":"opening");let G=z;Q.closed.then((X)=>this.#K(G,X),(X)=>this.#K(G,{kind:"transport_lost",error:X}))}#K($,Z){if(this.#J||this.#H!==$)return;if(this.#H=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#X("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#F("refused");try{this.#$.onRefused(Z.error)}catch(J){this.#$.onError?.(J)}return}if($.notices>0){let J=(this.#$.now??Date.now)();if($.acceptedAt!==void 0&&J-$.acceptedAt>=300000)this.#W=0;let z=Math.min(1000*2**Math.min(this.#W,16),300000);this.#W++,this.#X("polling","resubscribing"),this.#q(z,()=>void this.#j(!0));return}this.#F(Z.kind)}#F($){this.#X("fallback",$),this.#q(300000,()=>void this.#j(!1))}}var F1=60000,O$=4*F1,J4=2*F1,Z3=new Map,M1=new Map;function n0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function z4($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!n0(Z)||typeof Z.kind!=="string"||typeof Z.epoch!=="string"||Z.epoch.length===0||typeof Z.seq!=="number"||!Number.isSafeInteger(Z.seq)||Z.seq<1||Z.provider!==void 0&&typeof Z.provider!=="string")return;return{kind:Z.kind,epoch:Z.epoch,seq:Z.seq,...typeof Z.provider==="string"&&{provider:Z.provider}}}function Q4($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class _${transport;key;#$=[];#z=!1;#Z=new Set;#Q=new Map;#H=new K1(async()=>{try{let $=await this.transport.getUsage();if(!n0($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>n0(Z)&&typeof Z.provider==="string"),this.#z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#Z=new Set(this.#z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#Z)this.#Q.delete(Z)}catch{this.#$=[],this.#z=!1,this.#Z.clear()}},()=>{});#G=new s0;#J="polling";#U=0;#V=0;#W=new Map;#X;#q;#j={};#K=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#H.running)return this.#H.running;if(this.#J==="watching")return Promise.resolve();for(let[J,z]of M1)if($-z>=F1)M1.delete(J);let Z=M1.get(this.key);if(Z!==void 0&&$-Z<F1)return Promise.resolve();return M1.set(this.key,$),this.#H.request()}watchMode(){return this.#J}watch($={}){this.#U++;let Z=$.provider;if(Z===void 0)this.#V++;else this.#W.set(Z,(this.#W.get(Z)??0)+1);if(this.#U===1)this.#j=$,this.#M();let J=!1;return()=>{if(J)return;if(J=!0,Z===void 0)this.#V--;else{let z=(this.#W.get(Z)??1)-1;if(z>0)this.#W.set(Z,z);else this.#W.delete(Z)}if(--this.#U===0)this.#F()}}#F(){if(this.#q)(this.#j.clearTimeoutImpl??clearTimeout)(this.#q);this.#q=void 0;let $=this.#X;this.#X=void 0,$?.handle?.stop(),this.#J="polling"}#Y($){this.#q=(this.#j.setTimeoutImpl??setTimeout)(()=>{if(this.#q=void 0,this.#U>0&&!this.#X)this.#M()},$),this.#q.unref?.()}#M(){let $=this.transport.watchUsage;if(!$){this.#J="fallback";return}this.#J="polling",this.#G.restart();let Z={notices:0};this.#X=Z;let J;try{J=$.call(this.transport,(z)=>this.#N(Z,z))}catch(z){this.#B(Z,z);return}Z.handle=J,J.closed.then(()=>this.#B(Z,void 0),(z)=>this.#B(Z,z))}#N($,Z){if(this.#X!==$)return;if($.notices++,$.notices===1)this.#J="watching";if($.notices===2)this.#K=0;let J=z4(Z);if(!J)this.#G.restart();if(!(J?this.#G.continuous(J):!1)||J?.provider===void 0||this.#V>0||this.#W.has(J.provider))this.#H.request()}#B($,Z){if(this.#X!==$)return;this.#X=void 0;let J=Q4(Z);if(J==="unknown_method"||J==="usage_watch_limit"){this.#J="fallback";return}if($.notices>0){let z=Math.min($3*2**Math.min(this.#K,16),V1);this.#K++,this.#J="polling",this.#Y(z);return}if(this.#J="fallback",this.#H.request(),Z===void 0||K0(Z)==="unreachable")this.#Y(V1)}current($,Z,J){for(let z of this.#$){if(z.provider!==$||typeof z.account!=="string"||z.account.trim()!==Z)continue;if(z.stale!==void 0||z.errorClass!==void 0||!n0(z.usage))continue;let Q=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!Number.isFinite(Q)||J-Q>=O$)continue;return{entry:z,context:{fetchedAt:Q,...typeof z.source==="string"&&{source:z.source}}}}return}lookup($,Z,J){if(!this.#z)return{miss:"unreachable"};let z=this.#$.find((X)=>X.provider===$&&typeof X.account==="string"&&X.account.trim()===Z),Q=(z??this.#$.find((X)=>X.provider===$&&X.account===void 0&&X.errorClass!==void 0))?.errorClass;if(Q==="upstream_failed")return{miss:"upstream-failed"};if(Q==="credential_absent"||Q==="credential_unusable"||Q==="credential_rejected")return{miss:"credential"};if(Q!==void 0)return{miss:"unreachable"};if(z){let X=typeof z.fetchedAt==="string"?Date.parse(z.fetchedAt):Number.NaN;if(!n0(z.usage)||!Number.isFinite(X))return{miss:"unreachable"};let W={entry:z,context:{fetchedAt:X,...typeof z.source==="string"&&{source:z.source}}};return J>=X+O$||z.stale!==void 0?{miss:"stale",reading:W}:{reading:W}}if(this.#Z.has($))return{miss:"absent"};let G=this.#Q.get($)??J;return this.#Q.set($,G),{miss:J-G>=J4?"unreachable":"cold"}}}function J3($,Z){let J=JSON.stringify([P$($.connectionFile),P$(Z)]),z=Z3.get(J);if(!z)z={source:new _$($,J),refs:0},Z3.set(J,z);z.refs++;let Q=!1;return{source:z.source,release(){if(Q)return;if(Q=!0,--z.refs===0)Z3.delete(J)}}}import{ClaustrumCredentialError as Dz}from"@cortexkit/claustrum-client";import{appendFileSync as j4,chmodSync as M4,existsSync as X3,renameSync as T$,statSync as F4}from"node:fs";import{open as B4}from"node:fs/promises";import{dirname as D4,resolve as L4}from"node:path";import{randomUUID as G4}from"node:crypto";import{lstat as R$,readFile as S$,rename as X4,unlink as I$}from"node:fs/promises";import{dirname as j0,resolve as n}from"node:path";var I=process.platform==="win32",A$=new Set;function z3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var b$;function T0(){return b$??=import("@cortexkit/private-files"),b$}class u extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor($,Z,J){let z=J;super(`Private file refused at ${Z}: ${$} (${z?.reason??z?.code??"io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`,{cause:J});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=z3(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}async function l($,Z,J){try{return await J()}catch(z){if(z instanceof u)throw z;throw new u($,Z,z)}}var W4;async function X0($,Z){$=n($),Z??=W4,await l($,"safe-parent",async()=>{let J=await(await T0()).verifySafeParent($,Z);if(J.ok===!1){if(J.reason==="io-error"||J.reason==="wrong-kind")await R$($);throw new u(J.level??J.path,"safe-parent",{...J,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function p($,Z,J=!1){if($=n($),Z==="directory")return X0($);await l($,"verify",async()=>{let z=await T0(),Q=await z.verifyOwnerOnly($),G=!1;if(!Q.ok){let{reason:X}=Q.refusal;if(X==="io-error")await z.verifyPrivatePath($,Z);if(J&&[z.EXTRA_ACE,z.NOT_PROTECTED,z.NULL_DACL,z.EMPTY_DACL].includes(X))await X0(j0($)),await z.securePrivatePath($,Z),G=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:X,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await z.verifyPrivatePath($,Z),G&&!A$.has($))A$.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function J0($,Z=!1,J){$=n($),await l($,"directory",async()=>{let z=await T0();try{return await R$($),await X0($,J)}catch(G){if(z3(G)!=="ENOENT")throw G}let Q=j0($);if(Q===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await J0(Q,!1,J);try{await z.createOwnerOnly($,{kind:"dir"})}catch(G){if(z3(G)!=="EEXIST")throw G}await X0($,J)})}async function o($,Z=!1){if(!I)return S$($,"utf8");return(await H4($,Z)).toString("utf8")}async function H4($,Z=!1){if(!I)return S$($);if($=n($),Z)await X0(j0($)),await p($,"file",!0);return l($,"read",async()=>(await T0()).readOwnerOnly($))}async function f0($,Z){await X0(j0(n($))),await l($,"create",async()=>{await(await T0()).createPrivateFile(n($),Z)})}async function k$($){await X0(j0(n($))),await l($,"directory-create",async()=>{await(await T0()).createOwnerOnly(n($),{kind:"dir"})})}async function G3($,Z,J={}){$=n($),Z=n(Z);let z=J.now??(()=>performance.now()),Q=z(),G=J.deadline??1/0,X,W=[0,10,20,40,80,100],H,Y=0;for(let V of W){let B=Math.min(X??1/0,G);if(z()>=B)break;if(V)await(J.sleep??((F)=>new Promise((D)=>setTimeout(D,F))))(Math.min(V,Math.max(0,B-z())));if(z()>=B)break;let L=z();if(await J.beforeRename?.(),X!==void 0)X+=z()-L;if(z()>=G)break;Y++;try{return await(J.rename??X4)($,Z),{attempts:Y,elapsedMs:z()-Q}}catch(F){H??=F;let D=F;if(!(D.win32Code!==void 0?D.win32Code===32||D.win32Code===33:["EBUSY","EPERM","EACCES"].includes(D.code??"")&&!D.reason))break;X??=z()+500}}let q=new u(Z,"rename",H??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw q.attempts=Y,q.elapsedMs=z()-Q,q}async function g0($,Z,J={}){$=n($),await J0(j0($));try{await p($,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}let z=n(J.stagePath??`${$}.${G4()}.tmp`);if(j0(z)!==j0($))throw new u($,"stage-directory",{code:"EXDEV"});let Q=!1,G=!1,X={attempts:0,elapsedMs:0},W="stage-create",H=(Y)=>{try{J.onOutcome?.({path:$,stage:Y?.stage??"published",published:G,fileDurable:G,durabilityConfirmed:!1,attempts:Y?.attempts??X.attempts,elapsedMs:Y?.elapsedMs??X.elapsedMs,...Y&&{code:Y.code,win32Code:Y.win32Code}})}catch{}};try{if(await f0(z,Z),Q=!0,W="before-rename",X=await G3(z,$,J),Q=!1,G=!0,W="published-callback",J.onRenamed?.(),W="published-verify",await p($,"file"),J.durable&&J.durability!=="file-only-on-windows")throw new u($,"directory-sync-unsupported",{code:"ENOTSUP"});H()}catch(Y){let q=Y instanceof u?Y:new u($,W,Y);if(q.published=G,q.fileDurable=G,G)Object.assign(q,X);if(Q){try{await I$(z)}catch{q.orphanPath=z}Q=!1}throw H(q),q}finally{if(Q)await I$(z).catch(()=>{})}}var U4=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,Y4=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function q4($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function x0($={}){let Z=[Y4,...$.extraValuePatterns??[]].map((G)=>new RegExp(G.source,G.flags.includes("g")?G.flags:`${G.flags}g`));function J(G){let X=G.toLowerCase().replace(/[-_]/g,"");return U4.test(G)||X.includes("apikey")||X.endsWith("secret")||X.endsWith("password")||X.endsWith("token")&&!X.endsWith("tokens")||!!$.extraSecretKeys?.(X)}function z(G){let X=G,W=[["name",G.name],["message",G.message],["stack",G.stack]];for(let Y of["code","status","cause"])if(X[Y]!==void 0)W.push([Y,X[Y]]);let H=new Set(W.map(([Y])=>Y));for(let Y of Object.entries(G))if(!H.has(Y[0]))W.push(Y);return W}function Q(G,X,W,H=0){if(typeof G==="string")return Z.reduce((Y,q)=>Y.replace(q,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if(W.has(G))return"[Circular]";W.add(G);try{if(Array.isArray(G))return G.map((V)=>Q(V,X,W,H));let Y=q4(G);if(Y&&H>=8)return"[Truncated]";let q=Y?H+1:H;return Object.fromEntries((Y?z(G):Object.entries(G)).map(([V,B])=>[V,X&&J(V)?"***REDACTED***":Q(B,X,W,q)]))}finally{W.delete(G)}}return{redact:(G)=>Q(G,!0,new WeakSet),redactStrings:(G)=>Q(G,!1,new WeakSet)}}var E$=x0(),V4=E$.redact,K4=E$.redactStrings;var B1={error:0,warn:1,info:2,debug:3,trace:4},g$=5242880,x$=3;function W3($){try{M4($,384)}catch{}}function N4($){try{if(!(X3($)&&F4($).size>=g$))return;for(let J=x$-1;J>=1;J--)if(X3(`${$}.${J}`)){let z=`${$}.${J+1}`;T$(`${$}.${J}`,z),W3(z)}let Z=`${$}.1`;T$($,Z),W3(Z)}catch{}}async function W0($){let{file:Z,handle:J}=$;if($.file=void 0,$.handle=void 0,Z&&J)await l(Z,"log-close",()=>J.close())}async function f$($,Z){await J0(D4(Z));try{await p(Z,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J;try{await f0(Z,"")}catch(z){if(z.code!=="EEXIST")throw z;await p(Z,"file",!0)}}return $.handle=await l(Z,"log-open",()=>B4(Z,"a")),$.file=Z,$.handle}async function C4($,Z,J){Z=L4(Z);try{if($.file!==Z)await W0($);let z=$.handle??await f$($,Z);if((await l(Z,"log-stat",()=>z.stat())).size>=g$){await W0($);for(let G=x$-1;G>=0;G--){let X=G===0?Z:`${Z}.${G}`,W=`${Z}.${G+1}`;try{await p(X,"file",!0)}catch(H){if(H.code==="ENOENT")continue;throw H}try{await p(W,"file",!0)}catch(H){if(H.code!=="ENOENT")throw H}await G3(X,W),await p(W,"file")}z=await f$($,Z)}await l(Z,"log-append",()=>z.appendFile(J,"utf8"))}catch(z){throw await W0($).catch(()=>{}),z}}function P4($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function O4($){let Z,J,z,Q=x0(),G,X=[],W,H=Promise.resolve(),Y,q={};function V(U){let K=H.then(U);return H=K.catch((j)=>{Y=j}),K}function B(U){if(I&&U.file!==Z)V(()=>W0(q)).catch(()=>{});Z=U.file,J=U.level,Q=x0(U),G=U.captureSink}function L(U){if(U===void 0||U in B1)z=U}function F(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function D(){if(z)return z;let U=typeof J==="function"?J():J;if(U&&U in B1)return U;return"info"}function P(U=!0){if(W)clearTimeout(W),W=void 0;if(!X.length){if(I)return V(async()=>{if(U)await W0(q);if(Y)throw Y});return}let K;try{K=F()}catch{if(X=[],I&&U)return V(()=>W0(q));return}let j=X.join("");if(X=[],!K){if(I&&U)return V(()=>W0(q));return}if(I)return V(async()=>{try{await C4(q,K,j)}finally{if(U)await W0(q)}});try{if(N4(K),X3(K))W3(K);j4(K,j,{encoding:"utf8",mode:384})}catch{}}function R(){if(!W)W=setTimeout(()=>{W=void 0;let U=P(!1);if(U instanceof Promise)U.catch(()=>{})},500)}function f(U,K,j,b){if(Z===void 0&&G===void 0)return;try{if(B1[K]>B1[D()])return;let g=Q.redactStrings(j),S;try{S=Q.redact(b)}catch{S="[unserializable]"}let m=`[${new Date().toISOString()}] ${K.toUpperCase()} [${U}] ${g}`+(b===void 0?"":P4(S))+`
|
|
3
3
|
`;try{G?.({channel:U,level:K,message:g,data:S})}catch{}if(Z===void 0)return;if(X.push(m),X.length>=50){let s=P(!1);if(s instanceof Promise)s.catch(()=>{})}else R()}catch{}}function v(U){return{error:(K,j)=>f(U,"error",K,j),warn:(K,j)=>f(U,"warn",K,j),info:(K,j)=>f(U,"info",K,j),debug:(K,j)=>f(U,"debug",K,j),trace:(K,j)=>f(U,"trace",K,j)}}function N(){if(I)V(()=>W0(q)).catch(()=>{});if(Y=void 0,X=[],W)clearTimeout(W),W=void 0;Z=void 0,J=void 0,z=void 0,Q=x0(),G=void 0}if($)B($);return{configure:B,createLogger:v,setLogLevel:L,flushLogs:P,reset:N}}var _4=O4();function i0($){return _4.createLogger($)}function H3($){let Z=new AbortController,J=[],z=!1,Q=()=>{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),Q()},X=$.find((W)=>W.aborted);if(X)return Z.abort(X.reason),{signal:Z.signal,dispose:Q};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:Q}}import{ClaustrumCredentialError as U2}from"@cortexkit/claustrum-client";import{createHash as T4,randomBytes as f4,randomUUID as g4}from"node:crypto";import{constants as n$}from"node:fs";import{chmod as x4,mkdir as y4,open as o$,readFile as V3,realpath as v4,rename as h4,stat as t$,unlink as e$}from"node:fs/promises";import{basename as m4,dirname as P0,extname as lZ,isAbsolute as aZ,join as w4,resolve as sZ}from"node:path";import{ClaustrumCredentialError as u4,ClaustrumClient as iZ,writeEnrollmentTokenFile as c4}from"@cortexkit/claustrum-client";import{randomUUID as y$}from"node:crypto";import{mkdir as I4,open as v$,rename as A4,rm as b4}from"node:fs/promises";import{dirname as h$}from"node:path";class D1 extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function r0($,Z,J={}){await m$($,Z,J)}async function m$($,Z,J,z){if(I)return g0($,J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
4
4
|
`,{beforeRename:J.beforeRename,stagePath:`${$}.${(J.stageName??y$)()}.tmp`,onRenamed:z,durable:J.durable,durability:J.durability,onOutcome:J.onOutcome});await I4(h$($),{recursive:!0});let Q=`${$}.${(J.stageName??y$)()}.tmp`,G,X=!1;try{if(G=await v$(Q,"wx",384),X=!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 D1(W)}if(await G.close(),G=void 0,await J.beforeRename?.(),await A4(Q,$),X=!1,z?.(),J.durable){let W=await v$(h$($),"r");try{await W.sync()}catch(H){throw new D1(H)}finally{await W.close()}}}finally{if(await G?.close().catch(()=>{}),X)await b4(Q,{force:!0}).catch(()=>{})}}var R4=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 L1}from"node:crypto";import{mkdir as w$,open as a$,readFile as u$,rename as c$,rm as N1,stat as p$}from"node:fs/promises";import{dirname as q3,join as d$}from"node:path";function U3($,Z){return`${$}.${Z}.lock`}class o0 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=$}}async function Y3($,Z,J){let z=performance.now();for(;;){let Q=await H0({path:$,name:Z.name,ttlMs:Z.ttlMs,renew:Z.renew??!1,...Z.onStep?{onStep:Z.onStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}});if(Q)try{return await J(Q)}finally{await Q.release()}let G=Z.timeoutMs-(performance.now()-z);if(G<=0)throw new o0({target:$,name:Z.name,timeoutMs:Z.timeoutMs});await new Promise((X)=>setTimeout(X,Math.min(25,Math.ceil(G))))}}async function l$($,Z){let J=await a$($,"wx",384);try{await J.writeFile(Z,"utf8")}finally{await J.close()}}var S4=globalThis.setTimeout.bind(globalThis),k4=globalThis.clearTimeout.bind(globalThis);function s$($){let Z=$?.code;return Z==="ENOENT"||!I&&(Z==="EINVAL"||Z==="ENOTDIR")}function H0($){return E4({...$,now:Date.now})}async function E4($){let Z=U3($.path,$.name),J=d$(Z,"owner.json"),z=L1(),Q=$.now??Date.now,G=null,X=!1,W=!1,H,Y,q=new Promise((M)=>{Y=M});function V(M){try{let C=$.onRenewalTimer?.(M);if(C&&(typeof C==="object"||typeof C==="function")&&"then"in C&&typeof C.then==="function")Promise.resolve(C).catch(()=>{})}catch{}}function B(){if(!G)return;k4(G),G=null,V("cancelled")}function L(M,C){if(H||X)return;H=Object.freeze({reason:M,expectedOwnerId:z,...typeof C?.ownerId==="string"?{observedOwnerId:C.ownerId}:{},...typeof C?.expiresAt==="number"?{observedExpiresAt:C.expiresAt}:{}}),B(),Y(H)}let F,D=null,P=`${Z}.evicting`,R=d$(P,"owner.json"),f=L1(),v=5000,N=8;async function U(){if(I)try{return JSON.parse(await o(Z,!0))}catch(M){if(M.code!=="EISDIR"&&M.reason!=="wrong-kind")throw M;return await p(Z,"directory",!0),JSON.parse(await o(J,!0))}try{return JSON.parse(await u$(Z,"utf8"))}catch(M){if(M.code!=="EISDIR")throw M;return JSON.parse(await u$(J,"utf8"))}}async function K(){if(I){let x=await U(),w=Number(x?.expiresAt)-Q();await g0(Z,`${JSON.stringify({ownerId:z,expiresAt:Q()+$.ttlMs})}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createRequire as q}from"node:module";var j=Object.create;var{getPrototypeOf:k,defineProperty:i,getOwnPropertyNames:l}=Object;var m=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,r=(a,b,d)=>{var f=a!=null&&typeof a==="object";if(f){var g=b?o??=new WeakMap:p??=new WeakMap,h=g.get(a);if(h)return h}d=a!=null?j(k(a)):{};let c=b||!a||!a.__esModule?i(d,"default",{value:a,enumerable:!0}):d;for(let e of l(a))if(!m.call(c,e))i(c,e,{get:n.bind(a,e),enumerable:!0});if(f)g.set(a,c);return c};var s=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var u=q(import.meta.url);
|
|
2
|
-
export{r as
|
|
2
|
+
export{r as ha,s as ia,u as ja};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{I as $}from"./index-
|
|
1
|
+
import{I as $}from"./index-xbwa4x53.js";var D=(f)=>f!==null&&typeof f==="object"&&!Array.isArray(f),F=(f)=>D(f)&&typeof f.sessionId==="string"&&f.sessionId.length>0,A=(f)=>{if(!F(f)||!D(f)||f.command!=="claude"||typeof f.sectionId!=="string"||typeof f.actionId!=="string")return!1;if(f.itemId!==void 0&&typeof f.itemId!=="string")return!1;if(f.confirmed!==void 0&&typeof f.confirmed!=="boolean")return!1;if(f.values!==void 0&&(!D(f.values)||!Object.values(f.values).every((q)=>q===null||typeof q==="string"||typeof q==="boolean"||typeof q==="number"&&Number.isFinite(q))))return!1;return!0};function B(f){return{"~standard":{version:1,vendor:"cortexkit-native",validate:(q)=>f(q)?{value:q}:{issues:[{message:"Invalid native menu payload"}]}}}}var Z=(f)=>D(f)&&f.command==="claude"&&D(f.menu)&&f.menu.command==="claude"&&typeof f.menu.title==="string"&&Array.isArray(f.menu.sections),L=(f)=>D(f)&&f.command==="claude"&&typeof f.ok==="boolean"&&typeof f.text==="string"&&D(f.menu)&&Array.isArray(f.menu.sections),M={"~standard":{version:1,vendor:"cortexkit-native",validate:(f)=>({value:$(f)})}},P={id:"cortexkit-anthropic-native",methods:{open:{input:B(F),output:B(Z)},apply:{input:B(A),output:B(L)},sidebar:{input:B(F),output:M}},events:{opened:{schema:B((f)=>F(f)&&Z(f.payload))},notification:{schema:B((f)=>F(f)&&typeof f.message==="string"&&["info","warning","error"].includes(String(f.kind)))}}};async function U(f,q,Q){let W=new AbortController,J=(j)=>({sessionId:j,notify(H,K="info"){G.events.emit("notification",{sessionId:j,message:H,kind:K}).catch(()=>{})}}),G=await f.rpc.register(P,{open:(j)=>q.open(J(j.sessionId)),apply:(j)=>q.apply(j,J(j.sessionId)),sidebar:(j)=>Q.readSidebar(j.sessionId)}),X;try{X=await f.command.transform((j)=>j.add({name:"claude",description:"Native Claude accounts and settings",async execute(H){let K=await q.open(J(H.sessionID));await G.events.emit("opened",{sessionId:H.sessionID,payload:K})}}))}catch(j){throw await G.dispose(),j}let z=(async()=>{try{for await(let j of f.event.subscribe({signal:W.signal}))if(j.type==="session.deleted")Q.forgetSession(j.data.sessionID)}catch{}})(),Y=!1;return{async dispose(){if(Y)return;Y=!0,W.abort(),await Promise.all([G.dispose(),X.dispose(),z])}}}
|
|
2
2
|
export{P as t,U as u};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{q as J8}from"./index-6chd6jnr.js";import{s as Z8}from"./index-hazrk5c3.js";import{C as W8}from"./index-b1dvkp15.js";import{G as X8,L as M9,N as Y8,O as G8}from"./index-czyrqpxc.js";import{aa as y3}from"./index-ah5s0bew.js";import{randomUUID as iJ}from"node:crypto";import{existsSync as rY}from"node:fs";import{acquireNativeAccountRuntime as sY,applyCustomHeaders as U7,assertNotCustodyTombstone as aY,authorize as Q7,buildAccountList as g$,buildClaudeQuotaSummary as tY,buildFallbackQuotaSummaries as eY,buildPrimeRequestBody as $5,CACHE_KEEP_EXTENDED_TTL_BETA as J5,CacheKeepManager as Z5,CacheKeepSessionRegistry as W5,CLAUDE_FABLE_MYTHOS_5_1_PRICING as X5,CLAUDE_FABLE_MYTHOS_5_CONTEXT_WINDOW as Y5,CLAUDE_FABLE_MYTHOS_5_MAX_OUTPUT_TOKENS as G5,CLAUDE_FABLE_MYTHOS_5_MODEL_SPECS as V5,CLAUDE_FABLE_MYTHOS_5_PRICING as K5,CLAUDE_HAIKU_4_5_MODEL_ID as B7,CLAUDE_HAIKU_5_5_CONTEXT_WINDOW as z5,CLAUDE_HAIKU_5_5_LONG_CONTEXT_PRICING as L9,CLAUDE_HAIKU_5_5_LONG_CONTEXT_THRESHOLD as O5,CLAUDE_HAIKU_5_5_MAX_OUTPUT_TOKENS as j5,CLAUDE_HAIKU_5_5_MODEL_ID as N9,CLAUDE_HAIKU_5_5_PRICING as H9,CLAUDE_HAIKU_5_5_RELEASE_DATE as _5,CLAUDE_OPUS_5_5_CONTEXT_WINDOW as L5,CLAUDE_OPUS_5_5_MAX_OUTPUT_TOKENS as N5,CLAUDE_OPUS_5_5_MODEL_ID as D9,CLAUDE_OPUS_5_5_PRICING as U9,CLAUDE_OPUS_5_5_RELEASE_DATE as H5,CLAUDE_SONNET_5_5_CONTEXT_WINDOW as D5,CLAUDE_SONNET_5_5_MAX_OUTPUT_TOKENS as U5,CLAUDE_SONNET_5_5_MODEL_ID as Q9,CLAUDE_SONNET_5_5_PRICING as B9,CLAUDE_SONNET_5_5_RELEASE_DATE as Q5,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as nJ,computeXxhash64Hex as B5,configuredAnthropicOAuthAccountCount as F5,createEmptyStorage as o$,createNativeUsagePublisher as w5,createProviderErrorResponseScope as F9,createSseFramer as T5,createStickyNoRouteResponse as S5,custodyTombstoneOAuth as oJ,decideStickyQuotaFailure as rJ,decodeSseFrame as E5,detectClaustrumConnection as F7,dumpDirectRequest as w9,dumpResponseArtifact as sJ,effectiveRelayStatus as C5,exchange as aJ,executeAccountCommand as P5,executeCache1hCommand as tJ,executeCacheKeepCommand as A5,executeDumpCommand as w7,executeFastModeCommand as T7,executeKillswitchCommand as S7,executeLaneStartCommand as E7,executeLoggingCommand as C7,executePrimeCommand as R5,executeRoutingCommand as P7,FALLBACK_BACKGROUND_TICK_MS as q5,fallbackAccountUuidForLineage as M5,formatEnrollmentStatus as A7,formatNativeAccountState as eJ,formatOAuthAccountTier as B4,formatQuotaBackoffMessage as R7,formatRefreshBackoffMessage as I5,getAccountStoragePath as x5,getCache1hMode as F4,getCache1hPersistentMode as w4,getCacheKeepWindow as q7,getClaudeCodeIdentityForVerifiedAccount as f5,getClaudeFableMythos5ReleaseDate as k5,getClaustrumMode as T4,getDefaultCacheKeepRegistryDirectory as v5,getFallbackReauthLabels as h5,getHostClaustrumEnrollmentPaths as T9,getKillswitchConfig as $Z,getPersistedLogLevel as JZ,getQuotaCheckIntervalMs as M7,getQuotaNextRefreshAt as F1,getRequestGzipLatch as b5,getRequestGzipLatchPath as g5,getRoutingMode as e$,getScopedQuotaWindowForModel as y5,getThinkingPrefixMismatchBehavior as m5,inspectNativeHostAuthEntry as c5,isApiKeyAccount as c1,isCache1hEnabled as S4,isCache1hPersistentlyEnabled as S9,isCacheKeepAlways as I7,isCacheKeepHybridActive as x7,isCacheKeepPersistentlyEnabled as p5,isCacheKeepSubagentsEnabled as l5,isClaudeFable51Model as u5,isClaudeFableOrMythos51Model as V8,isClaudeHaiku55Model as d5,isClaudeOpus5FamilyModel as i5,isClaudeOpus5Model as n5,isClaudeOpus55Model as o5,isClaudeSonnet55Model as r5,isCostZeroingEnabled as s5,isCustodyTombstoneOAuth as ZZ,isDumpPersistentlyEnabled as WZ,isFastModeEnabled as XZ,isFastModePersistentlyEnabled as YZ,isFastModeSupportedModel as f7,isKillswitchEnabled as r$,isNativeTransientAccountError as w1,isOAuthAccount as B0,isPermanentRefreshError as s$,isPrimePersistentlyEnabled as E9,isQuotaBearingHeaderFrame as a5,isValidApiBaseURL as GZ,killswitchPassesPolicy as a$,killswitchRetryAfterSeconds as k7,log as y$,logger as h,mergeAnthropicBetas as v7,mergeHeaderQuotaForPersistence as h7,NativeCustodyError as t5,NativeRuntimeError as e5,NativeVaultNoAccountError as VZ,nativeAccountCanServe as y0,nativeLocalQuotaLineage as $G,nativeMigrationAuthorityPhase as b7,normalizeQuotaHeaders as JG,oauthProfileIsFresh as C9,oauthProfileMatchesIdentity as ZG,PARALLEL_TOOL_CALLS_SYSTEM_PROMPT as WG,PrimeManager as XG,parseAccountCommandAction as YG,parseCache1hCommandAction as GG,parseCacheKeepCommandAction as VG,parseDumpCommandAction as KG,parseFastModeCommandAction as zG,parseLaneStartCommandAction as OG,parseLoggingCommandAction as jG,parsePrimeCommandAction as _G,parseRoutingCommandAction as LG,parseSseFrame as NG,QUOTA_HEADER_FEED_SCHEMA_VERSION as P9,QuotaHeaderFeedRegistry as HG,QuotaManager as DG,quotaSnapshotCheckedAt as T1,quotaSnapshotHasStandardWindows as KZ,quotaSnapshotModelScopeIsExhausted as A9,quotaSnapshotPassesModelScope as R9,quotaSnapshotPassesPolicy as p1,readClaustrumEnrollmentStatus as g7,readNativeAccountsForRequest as UG,readNativeEnrollmentMode as S1,readNativeHostAuthKind as QG,readNativeMigrationJournal as y7,refreshBackoffActive as E1,remapRequestBodyModel as BG,resetClaustrumEnrollmentState as FG,resolveNativePoolPaths as wG,STICKY_ROUTING_MAIN_ACCOUNT_ID as W$,StickySessionRouter as TG,sendViaRelay as SG,sendWithRequestGzip as EG,setCache1hState as q9,setDumpEnabled as zZ,setFastModeEnabled as OZ,setLogLevel as CG,shouldFallbackStatus as PG,snapshotHasServableLocalOAuth as m7,stickyQuotaSnapshotIsFresh as C1,stickyRouteFamilyForModel as AG,TrailingAssistantHistoryError as c7,tokenFingerprint as t$}from"@cortexkit/anthropic-auth-core";import{randomUUID as rZ}from"node:crypto";import{isValidAnthropicRequestId as sZ,isValidBillingPromptId as a8}from"@cortexkit/anthropic-auth-core";var Y4="x-cortexkit-billing-lineage",t8=4096,e8=4096,$W=1024,aZ=new Set(["title","summary","compaction"]),JW="[lane start] — automated cache warm; no response needed.";function ZW($){let J=$.info?.sessionID??$.info?.sessionId;return typeof J==="string"&&J.length>0?J:void 0}function WW($){if($.info?.synthetic===!0||$.info?.ignored===!0||typeof $.info?.agent==="string"&&aZ.has($.info.agent))return!0;for(let J of $.parts??[]){if(J.type==="compaction"||J.synthetic===!0||J.ignored===!0)return!0;if(J.metadata?.compaction_continue===!0)return!0;if(J.type==="text"&&J.text===JW)return!0}return!1}function Q1($,J){while($.size>J){let W=$.keys().next().value;if(W===void 0)return;$.delete(W)}}function _J($){let J=$.get("request-id")??$.get("x-request-id");return J&&sZ(J)?J:void 0}class LJ{#$;#j;#z;#_;#X;#J=new Map;#W=new Map;#Z=new Map;#Y=new Map;#G=new Map;#V=new Map;#K=new Map;constructor($={}){this.#$=$.createPromptId??rZ,this.#j=$.createRequestToken??rZ,this.#z=$.maxPrompts??t8,this.#_=$.maxRequests??e8,this.#X=$.maxSessions??$W}observeMessages($){let J;for(let H=$.length-1;H>=0;H-=1)if($[H]?.info?.role==="user"){J=$[H];break}if(!J)return;let W=ZW(J),X=J.info?.id;if(!W||typeof X!=="string"||X.length===0)return;let V=this.#O(W,X);if(WW(J)){this.#W.delete(V),this.#W.set(V,!0),Q1(this.#W,this.#z),this.#J.delete(V);return}this.#W.delete(V);let O=this.#J.get(V);if(O){this.#J.delete(V),this.#J.set(V,O);return}let z=this.#$();if(!a8(z))return;this.#J.set(V,z),Q1(this.#J,this.#z)}markHeaders($){let J=this.#O($.sessionId,$.messageId);if(aZ.has($.agent??"")||this.#W.has(J))return!1;let W=this.#J.get(J);if(!W)return!1;let X=this.#j();if(!X||/[\r\n]/.test(X))return!1;let V={sessionId:$.sessionId,messageId:$.messageId,promptId:W,requestToken:X,generation:this.#G.get($.sessionId)??0,sequence:0};return this.#Z.set(X,V),Q1(this.#Z,this.#_),$.headers[Y4]=X,!0}resolveHeader($){if(!$)return;let J=this.#Z.get($);if(!J)return;this.#Z.delete($),this.#Z.set($,J);let W=(this.#V.get(J.sessionId)??0)+1;this.#V.delete(J.sessionId),this.#V.set(J.sessionId,W),Q1(this.#V,this.#X);let X={...J,previousRequestId:this.#Y.get(J.sessionId),sequence:W};if(X.previousRequestId===void 0)delete X.previousRequestId;return X}commit($,J){if(!$||!J||!sZ(J))return!1;if((this.#G.get($.sessionId)??0)!==$.generation)return!1;let W=this.#Z.get($.requestToken);if(!W||W.sessionId!==$.sessionId||W.messageId!==$.messageId||W.promptId!==$.promptId||W.generation!==$.generation)return!1;if(this.#J.get(this.#O($.sessionId,$.messageId))!==$.promptId)return!1;if($.sequence<(this.#K.get($.sessionId)??0))return!1;return this.#K.delete($.sessionId),this.#K.set($.sessionId,$.sequence),Q1(this.#K,this.#X),this.#Y.delete($.sessionId),this.#Y.set($.sessionId,J),Q1(this.#Y,this.#X),!0}clearSession($){this.#G.set($,(this.#G.get($)??0)+1),this.#Y.delete($),this.#V.delete($),this.#K.delete($);let J=`${$}\x00`;for(let W of this.#J.keys())if(W.startsWith(J))this.#J.delete(W);for(let W of this.#W.keys())if(W.startsWith(J))this.#W.delete(W);for(let[W,X]of this.#Z)if(X.sessionId===$)this.#Z.delete(W);Q1(this.#G,this.#X)}#O($,J){return`${$}\x00${J}`}}import{setBounded as eZ,stickyRetryAfterWithJitter as XW}from"@cortexkit/anthropic-auth-core";var V4="cache-diagnosis-2026-04-07",YW="MC-CACHE-DIAG ",GW=1000,VW=300000,KW={turn:!1,start:!0,prewarm_cachekeep:!0},zW=1000;class NJ{entries=new Map;previousFor($){return this.entries.get($)??null}capture($,J,W){eZ(this.entries,$,{messageId:J,receivedAt:W},GW)}}class HJ{hashes=new Map;capture($,J){if(this.hashes.has($))return null;return eZ(this.hashes,$,!0,zW),`MC-CACHE-DIAG-BETAS ${JSON.stringify({hash:$,betas:[...J].sort()})}`}}function n4($,J,W){let X=$.get(J);if(X)$.set(W,X)}async function DJ($,J,W,X,V){let O=new Headers($.headers);if(O.set("retry-after",String(XW(J,W))),X)return await $.body?.cancel().catch(()=>{}),O.set("content-type","application/json"),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:"Sticky OAuth account five-hour quota resets shortly; retaining session affinity."}}),{status:429,headers:O});let z=new Response($.body,{status:$.status,statusText:$.statusText,headers:O});return n4(V,$,z),z}function o4($,J){$.diagnostics={previous_message_id:J}}function d$($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function OW($){return d$($)&&$.type==="ephemeral"}function $3($,J){if(!OW($))return;J.push($.ttl==="1h"?"1h":"5m")}function tZ($,J){if(!Array.isArray($))return;for(let W of $)if(d$(W))$3(W.cache_control,J)}function r4($){if(!d$($))return null;let J=[];if($3($.cache_control,J),tZ($.system,J),Array.isArray($.messages)){for(let W of $.messages)if(d$(W))tZ(W.content,J)}return J.at(-1)??null}function jW($){if(!Object.hasOwn($,"diagnostics"))return{state:"absent"};let J=$.diagnostics;if(J===null)return{state:"server_null"};if(!d$(J))return null;if(!Object.hasOwn(J,"cache_miss_reason"))return null;let W=J.cache_miss_reason;if(W===null)return{state:"pending"};if(!d$(W)||typeof W.type!=="string"||!W.type)return null;let X=W.cache_missed_input_tokens;if(X!==void 0&&typeof X!=="number")return null;return{state:"populated",missReason:W.type,cacheMissedInputTokens:X}}function G4($,J){let W=$[J];return typeof W==="number"&&Number.isFinite(W)&&W>=0?W:null}function J3($){if(typeof $.source!=="string"||$.source.length===0||typeof $.accountId!=="string"||$.accountId.length===0||typeof $.synthetic!=="boolean"||typeof $.betasHash!=="string"||$.betasHash.length===0)return{};let J=KW[$.source];if(J!==void 0&&J!==$.synthetic)$.onWarning?.(`cache diagnostics source/synthetic mismatch: source=${$.source} expected=${J} actual=${$.synthetic}`);let W=Math.trunc($.receivedAt);if(!Number.isFinite($.receivedAt)||W!==$.receivedAt)return{};if(!d$($.message))return{};let X=$.message.id,V=$.message.model,O=$.message.usage;if(typeof X!=="string"||X.length===0)return{};if(typeof V!=="string"||V.length===0||!d$(O))return{};let z=G4(O,"input_tokens"),H=G4(O,"cache_read_input_tokens"),w=G4(O,"cache_creation_input_tokens"),R=O.cache_creation;if(z===null||H===null||w===null||!d$(R))return{};let A=G4(R,"ephemeral_5m_input_tokens"),c=G4(R,"ephemeral_1h_input_tokens");if(A===null||c===null)return{};let a=jW($.message);if(!a)return{};let u={v:2,source:$.source,account_id:$.accountId,synthetic:$.synthetic,betas_hash:$.betasHash,session_id:$.request.sessionId,ts_ms_received:W,model:V,is_subagent:$.request.isSubagent,ttl_sent:$.request.ttlSent,cache_read:H,cache_creation:w,input_tokens:z,ephemeral_5m_tokens:A,ephemeral_1h_tokens:c,message_id:X,previous_message_id:$.request.previousMessageId,diag_state:a.state};if(a.missReason!==void 0)u.miss_reason=a.missReason;if(a.cacheMissedInputTokens!==void 0)u.cache_missed_input_tokens=a.cacheMissedInputTokens;if($.requestedModel!==void 0&&$.requestedModel!==V)u.requested_model=$.requestedModel;let s=a.missReason==="previous_message_not_found"&&$.request.previousMessageId!==null&&$.request.previousMessageReceivedAt!==void 0&&$.receivedAt-$.request.previousMessageReceivedAt<VW&&$.receivedAt>=$.request.previousMessageReceivedAt?{messageId:X,previousMessageId:$.request.previousMessageId}:void 0;return{record:u,messageId:X,...s?{canary:s}:{}}}function Z3($){return`${YW}${JSON.stringify($)}`}import{getClaustrumMode as s4,hasNoLocalCredential as UJ,isCustodyTombstoneOAuth as _W,isOAuthAccount as QJ,nativeAccountCanServe as BJ}from"@cortexkit/anthropic-auth-core";function K4($,J){if(s4(J)!=="claustrum"||!J?.claustrum?.scopedRoster)return!1;let W=J.accounts.find((X)=>X.id===$);return Boolean(W&&QJ(W)&&BJ(W)&&W.claustrumScopedCredentialId&&W.anthropicAccountUuid&&UJ(W))}function W3($){if(s4($)!=="claustrum")return{fallbacks:"R",evidence:"V"};if(!$?.claustrum?.scopedRoster)return{fallbacks:"M",evidence:"N"};return{fallbacks:$.accounts.filter((W)=>BJ(W)&&QJ(W)).every((W)=>Boolean(W.claustrumScopedCredentialId&&W.anthropicAccountUuid&&UJ(W)))?"T":"R",evidence:"V"}}function FJ($){if(_W($,"anthropic"))return"T";if($.type==="oauth"&&$.access&&$.refresh)return"R";return"X"}function wJ($,J){if($.role==="main"){if(s4(J)!=="claustrum")return"na";let X=J?.claustrum?.scopedRoster?J.claustrum.primaryAccount:void 0;if(!X)return"unknown-identity";if(X.state==="needs_reauth")return"on-vault-reauth";return BJ(X)?"on-vault-served":"on-cold"}if(s4(J)!=="claustrum")return"off";let W=J?.accounts.find((X)=>X.id===$.id);if(!W||!QJ(W)||!W.claustrumScopedCredentialId||!W.anthropicAccountUuid||!UJ(W))return"off";if(W.claustrumScopedState==="needs_reauth")return"on-vault-reauth";return K4($.id,J)?"on-vault-served":"on-cold"}class z4 extends Error{verdict;dimensions;code="custody_state_mismatch";constructor($,J){super(`custody state mismatch: ${$}`);this.verdict=$;this.dimensions=J}toJSON(){return{code:this.code,verdict:this.verdict,dimensions:this.dimensions}}}function X3($){if($.authority!=="committed"&&$.authority!=="retired")throw new z4("MIGRATION_REQUIRED",$);if($.mode==="L"&&$.main==="R"&&$.evidence==="V"&&$.localOAuthServable===!0)return{verdict:"LOCAL_SERVE"};if($.mode==="L"&&$.main==="T"&&$.fallbacks==="R"&&$.evidence==="V")return{verdict:"LOCAL_SERVE"};if($.mode==="C"&&$.main==="T"&&$.fallbacks==="T"&&$.evidence==="V")return{verdict:"CLAUSTRUM_SERVE"};throw new z4("FAIL_CLOSED",$)}import{createHash as LW}from"node:crypto";import{defaultAdaptiveEffort as NW,isClaudeFable51Model as SJ,isClaudeOpus55Model as HW,isClaudeSonnet55Model as DW,normalizeAdaptiveEffort as UW,supportsPerMessageEffort as QW}from"@cortexkit/anthropic-auth-core";var z3=512,BW=1024,FW=4096,O4=32,j4=32,t4="[A-Za-z0-9_-]{1,128}",wW="<cortexkit-internal-effort ",TW="<cortexkit-internal-effort-plan ",O3=/^\s*(?:§[0-9]+§\s*)+$/,_4={low:"l",medium:"m",high:"h",xhigh:"x",max:"z"},CJ=Object.fromEntries(Object.entries(_4).map(([$,J])=>[J,$])),PJ="<cortexkit-internal-effort-v2 ",AJ="<cortexkit-internal-effort-anchor-v1 ",v1="x-cortexkit-effort-plan";class S0 extends Error{check;details;constructor($,J="unspecified",W={}){super($);this.check=J;this.details=W;this.name="EffortMarkerCorrelationError"}}function o0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function SW($){if(SJ($))return"fable-5-1";if(HW($))return"opus-5-5";if(DW($))return"sonnet-5-5";return}function TJ($){if($?.info?.role!=="user")return;if($.info.model?.providerID!=="anthropic")return;return SW($.info.model.modelID)}function Y3($){return UW($.info?.model?.variant)??NW($.info?.model?.modelID)}function G3($){return $.parts?.some((J)=>{if(J.type==="text")return J.ignored!==!0&&J.text!=="";if(J.type==="file")return J.mime!=="text/plain"&&J.mime!=="application/x-directory";return J.type==="compaction"||J.type==="subtask"})??!1}function O1($){return LW("sha256").update($).digest("hex")}function EW($){return O1(`scope:${$}`).slice(0,j4)}function e4($){return O1(`cortexkit-effort-v2:${$}`).slice(0,O4)}function CW($,J,W){let X=_4[W],V=`transition:${$}:${J}:${X}`;return`${PJ}scope="${$}" boundary="${J}" effort="${X}" check="${e4(V)}"/>`}function j3($){let J=$.match(new RegExp(`^${PJ}scope="([0-9a-f]{${j4}})" boundary="(${t4})" effort="([lmhxz])" check="([0-9a-f]{${O4}})"/>$`));if(!J)return null;let[,W,X,V,O]=J,z=CJ[V??""];if(!W||!X||!V||!O||!z)return null;let H=`transition:${W}:${X}:${V}`;if(e4(H)!==O)return null;return{scope:W,boundary:X,effort:z,token:$}}function PW($,J,W,X){let V=_4[W],O=`anchor:${$}:${J}:${V}:${X}`;return`${AJ}scope="${$}" boundary="${J}" effort="${V}" digest="${X}" check="${e4(O)}"/>`}function _3($){let J=$.match(new RegExp(`^${AJ}scope="([0-9a-f]{${j4}})" boundary="(${t4})" effort="([lmhxz])" digest="([0-9a-f]{64})" check="([0-9a-f]{${O4}})"/>$`));if(!J)return null;let[,W,X,V,O,z]=J,H=CJ[V??""];if(!W||!X||!V||!O||!z||!H)return null;let w=`anchor:${W}:${X}:${V}:${O}`;if(e4(w)!==z)return null;return{scope:W,boundary:X,effort:H,digest:O,token:$}}function EJ($){return $.trim()===""||O3.test($)}function V3(){return new RegExp(`(?:${TW}nonce="[^"]+" baseline="[^"]+" count="[^"]+" sig="[0-9a-f]+"/>|${wW}nonce="[^"]+" effort="[^"]+" sig="[0-9a-f]+"/>)`,"g")}function AW(){return new RegExp(`${PJ}scope="[0-9a-f]{${j4}}" boundary="${t4}" effort="[lmhxz]" check="[0-9a-f]{${O4}}"/>`,"g")}function RW(){return new RegExp(`${AJ}scope="[0-9a-f]{${j4}}" boundary="${t4}" effort="[lmhxz]" digest="[0-9a-f]{64}" check="[0-9a-f]{${O4}}"/>`,"g")}function L3($,J,W){let X=0,V=$,O=$.replace(V3(),"");if(O!==$&&O3.test(O))X+=[...$.matchAll(V3())].length,V=O;return V=V.replace(AW(),(z)=>{let H=j3(z);if(!H)return z;return J?.(H),X++,""}),V=V.replace(RW(),(z)=>{let H=_3(z);if(!H)return z;return W?.(H),X++,""}),{text:V,removed:X}}function qW($){for(let J of $){if(!Array.isArray(J.parts))continue;J.parts=J.parts.flatMap((W)=>{if(W.type!=="text"||typeof W.text!=="string"||!W.text.includes("<cortexkit-internal-effort"))return[W];let X=L3(W.text);if(X.removed===0)return[W];if(EJ(X.text))return[];return W.text=X.text,[W]})}}function a4($,J,W,X,V){let O=V?`:${V}`:"",z=`plan:${$}:${_4[J]}:${W.toString(36)}${O}`;return O1([z,...X].join(`
|
|
1
|
+
import{q as J8}from"./index-6chd6jnr.js";import{s as Z8}from"./index-hazrk5c3.js";import{C as W8}from"./index-b1dvkp15.js";import{G as X8,L as M9,N as Y8,O as G8}from"./index-xbwa4x53.js";import{fa as y3}from"./index-ppdrzs41.js";import{randomUUID as iJ}from"node:crypto";import{existsSync as rY}from"node:fs";import{acquireNativeAccountRuntime as sY,applyCustomHeaders as U7,assertNotCustodyTombstone as aY,authorize as Q7,buildAccountList as g$,buildClaudeQuotaSummary as tY,buildFallbackQuotaSummaries as eY,buildPrimeRequestBody as $5,CACHE_KEEP_EXTENDED_TTL_BETA as J5,CacheKeepManager as Z5,CacheKeepSessionRegistry as W5,CLAUDE_FABLE_MYTHOS_5_1_PRICING as X5,CLAUDE_FABLE_MYTHOS_5_CONTEXT_WINDOW as Y5,CLAUDE_FABLE_MYTHOS_5_MAX_OUTPUT_TOKENS as G5,CLAUDE_FABLE_MYTHOS_5_MODEL_SPECS as V5,CLAUDE_FABLE_MYTHOS_5_PRICING as K5,CLAUDE_HAIKU_4_5_MODEL_ID as B7,CLAUDE_HAIKU_5_5_CONTEXT_WINDOW as z5,CLAUDE_HAIKU_5_5_LONG_CONTEXT_PRICING as L9,CLAUDE_HAIKU_5_5_LONG_CONTEXT_THRESHOLD as O5,CLAUDE_HAIKU_5_5_MAX_OUTPUT_TOKENS as j5,CLAUDE_HAIKU_5_5_MODEL_ID as N9,CLAUDE_HAIKU_5_5_PRICING as H9,CLAUDE_HAIKU_5_5_RELEASE_DATE as _5,CLAUDE_OPUS_5_5_CONTEXT_WINDOW as L5,CLAUDE_OPUS_5_5_MAX_OUTPUT_TOKENS as N5,CLAUDE_OPUS_5_5_MODEL_ID as D9,CLAUDE_OPUS_5_5_PRICING as U9,CLAUDE_OPUS_5_5_RELEASE_DATE as H5,CLAUDE_SONNET_5_5_CONTEXT_WINDOW as D5,CLAUDE_SONNET_5_5_MAX_OUTPUT_TOKENS as U5,CLAUDE_SONNET_5_5_MODEL_ID as Q9,CLAUDE_SONNET_5_5_PRICING as B9,CLAUDE_SONNET_5_5_RELEASE_DATE as Q5,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as nJ,computeXxhash64Hex as B5,configuredAnthropicOAuthAccountCount as F5,createEmptyStorage as o$,createNativeUsagePublisher as w5,createProviderErrorResponseScope as F9,createSseFramer as T5,createStickyNoRouteResponse as S5,custodyTombstoneOAuth as oJ,decideStickyQuotaFailure as rJ,decodeSseFrame as E5,detectClaustrumConnection as F7,dumpDirectRequest as w9,dumpResponseArtifact as sJ,effectiveRelayStatus as C5,exchange as aJ,executeAccountCommand as P5,executeCache1hCommand as tJ,executeCacheKeepCommand as A5,executeDumpCommand as w7,executeFastModeCommand as T7,executeKillswitchCommand as S7,executeLaneStartCommand as E7,executeLoggingCommand as C7,executePrimeCommand as R5,executeRoutingCommand as P7,FALLBACK_BACKGROUND_TICK_MS as q5,fallbackAccountUuidForLineage as M5,formatEnrollmentStatus as A7,formatNativeAccountState as eJ,formatOAuthAccountTier as B4,formatQuotaBackoffMessage as R7,formatRefreshBackoffMessage as I5,getAccountStoragePath as x5,getCache1hMode as F4,getCache1hPersistentMode as w4,getCacheKeepWindow as q7,getClaudeCodeIdentityForVerifiedAccount as f5,getClaudeFableMythos5ReleaseDate as k5,getClaustrumMode as T4,getDefaultCacheKeepRegistryDirectory as v5,getFallbackReauthLabels as h5,getHostClaustrumEnrollmentPaths as T9,getKillswitchConfig as $Z,getPersistedLogLevel as JZ,getQuotaCheckIntervalMs as M7,getQuotaNextRefreshAt as F1,getRequestGzipLatch as b5,getRequestGzipLatchPath as g5,getRoutingMode as e$,getScopedQuotaWindowForModel as y5,getThinkingPrefixMismatchBehavior as m5,inspectNativeHostAuthEntry as c5,isApiKeyAccount as c1,isCache1hEnabled as S4,isCache1hPersistentlyEnabled as S9,isCacheKeepAlways as I7,isCacheKeepHybridActive as x7,isCacheKeepPersistentlyEnabled as p5,isCacheKeepSubagentsEnabled as l5,isClaudeFable51Model as u5,isClaudeFableOrMythos51Model as V8,isClaudeHaiku55Model as d5,isClaudeOpus5FamilyModel as i5,isClaudeOpus5Model as n5,isClaudeOpus55Model as o5,isClaudeSonnet55Model as r5,isCostZeroingEnabled as s5,isCustodyTombstoneOAuth as ZZ,isDumpPersistentlyEnabled as WZ,isFastModeEnabled as XZ,isFastModePersistentlyEnabled as YZ,isFastModeSupportedModel as f7,isKillswitchEnabled as r$,isNativeTransientAccountError as w1,isOAuthAccount as B0,isPermanentRefreshError as s$,isPrimePersistentlyEnabled as E9,isQuotaBearingHeaderFrame as a5,isValidApiBaseURL as GZ,killswitchPassesPolicy as a$,killswitchRetryAfterSeconds as k7,log as y$,logger as h,mergeAnthropicBetas as v7,mergeHeaderQuotaForPersistence as h7,NativeCustodyError as t5,NativeRuntimeError as e5,NativeVaultNoAccountError as VZ,nativeAccountCanServe as y0,nativeLocalQuotaLineage as $G,nativeMigrationAuthorityPhase as b7,normalizeQuotaHeaders as JG,oauthProfileIsFresh as C9,oauthProfileMatchesIdentity as ZG,PARALLEL_TOOL_CALLS_SYSTEM_PROMPT as WG,PrimeManager as XG,parseAccountCommandAction as YG,parseCache1hCommandAction as GG,parseCacheKeepCommandAction as VG,parseDumpCommandAction as KG,parseFastModeCommandAction as zG,parseLaneStartCommandAction as OG,parseLoggingCommandAction as jG,parsePrimeCommandAction as _G,parseRoutingCommandAction as LG,parseSseFrame as NG,QUOTA_HEADER_FEED_SCHEMA_VERSION as P9,QuotaHeaderFeedRegistry as HG,QuotaManager as DG,quotaSnapshotCheckedAt as T1,quotaSnapshotHasStandardWindows as KZ,quotaSnapshotModelScopeIsExhausted as A9,quotaSnapshotPassesModelScope as R9,quotaSnapshotPassesPolicy as p1,readClaustrumEnrollmentStatus as g7,readNativeAccountsForRequest as UG,readNativeEnrollmentMode as S1,readNativeHostAuthKind as QG,readNativeMigrationJournal as y7,refreshBackoffActive as E1,remapRequestBodyModel as BG,resetClaustrumEnrollmentState as FG,resolveNativePoolPaths as wG,STICKY_ROUTING_MAIN_ACCOUNT_ID as W$,StickySessionRouter as TG,sendViaRelay as SG,sendWithRequestGzip as EG,setCache1hState as q9,setDumpEnabled as zZ,setFastModeEnabled as OZ,setLogLevel as CG,shouldFallbackStatus as PG,snapshotHasServableLocalOAuth as m7,stickyQuotaSnapshotIsFresh as C1,stickyRouteFamilyForModel as AG,TrailingAssistantHistoryError as c7,tokenFingerprint as t$}from"@cortexkit/anthropic-auth-core";import{randomUUID as rZ}from"node:crypto";import{isValidAnthropicRequestId as sZ,isValidBillingPromptId as a8}from"@cortexkit/anthropic-auth-core";var Y4="x-cortexkit-billing-lineage",t8=4096,e8=4096,$W=1024,aZ=new Set(["title","summary","compaction"]),JW="[lane start] — automated cache warm; no response needed.";function ZW($){let J=$.info?.sessionID??$.info?.sessionId;return typeof J==="string"&&J.length>0?J:void 0}function WW($){if($.info?.synthetic===!0||$.info?.ignored===!0||typeof $.info?.agent==="string"&&aZ.has($.info.agent))return!0;for(let J of $.parts??[]){if(J.type==="compaction"||J.synthetic===!0||J.ignored===!0)return!0;if(J.metadata?.compaction_continue===!0)return!0;if(J.type==="text"&&J.text===JW)return!0}return!1}function Q1($,J){while($.size>J){let W=$.keys().next().value;if(W===void 0)return;$.delete(W)}}function _J($){let J=$.get("request-id")??$.get("x-request-id");return J&&sZ(J)?J:void 0}class LJ{#$;#j;#z;#_;#X;#J=new Map;#W=new Map;#Z=new Map;#Y=new Map;#G=new Map;#V=new Map;#K=new Map;constructor($={}){this.#$=$.createPromptId??rZ,this.#j=$.createRequestToken??rZ,this.#z=$.maxPrompts??t8,this.#_=$.maxRequests??e8,this.#X=$.maxSessions??$W}observeMessages($){let J;for(let H=$.length-1;H>=0;H-=1)if($[H]?.info?.role==="user"){J=$[H];break}if(!J)return;let W=ZW(J),X=J.info?.id;if(!W||typeof X!=="string"||X.length===0)return;let V=this.#O(W,X);if(WW(J)){this.#W.delete(V),this.#W.set(V,!0),Q1(this.#W,this.#z),this.#J.delete(V);return}this.#W.delete(V);let O=this.#J.get(V);if(O){this.#J.delete(V),this.#J.set(V,O);return}let z=this.#$();if(!a8(z))return;this.#J.set(V,z),Q1(this.#J,this.#z)}markHeaders($){let J=this.#O($.sessionId,$.messageId);if(aZ.has($.agent??"")||this.#W.has(J))return!1;let W=this.#J.get(J);if(!W)return!1;let X=this.#j();if(!X||/[\r\n]/.test(X))return!1;let V={sessionId:$.sessionId,messageId:$.messageId,promptId:W,requestToken:X,generation:this.#G.get($.sessionId)??0,sequence:0};return this.#Z.set(X,V),Q1(this.#Z,this.#_),$.headers[Y4]=X,!0}resolveHeader($){if(!$)return;let J=this.#Z.get($);if(!J)return;this.#Z.delete($),this.#Z.set($,J);let W=(this.#V.get(J.sessionId)??0)+1;this.#V.delete(J.sessionId),this.#V.set(J.sessionId,W),Q1(this.#V,this.#X);let X={...J,previousRequestId:this.#Y.get(J.sessionId),sequence:W};if(X.previousRequestId===void 0)delete X.previousRequestId;return X}commit($,J){if(!$||!J||!sZ(J))return!1;if((this.#G.get($.sessionId)??0)!==$.generation)return!1;let W=this.#Z.get($.requestToken);if(!W||W.sessionId!==$.sessionId||W.messageId!==$.messageId||W.promptId!==$.promptId||W.generation!==$.generation)return!1;if(this.#J.get(this.#O($.sessionId,$.messageId))!==$.promptId)return!1;if($.sequence<(this.#K.get($.sessionId)??0))return!1;return this.#K.delete($.sessionId),this.#K.set($.sessionId,$.sequence),Q1(this.#K,this.#X),this.#Y.delete($.sessionId),this.#Y.set($.sessionId,J),Q1(this.#Y,this.#X),!0}clearSession($){this.#G.set($,(this.#G.get($)??0)+1),this.#Y.delete($),this.#V.delete($),this.#K.delete($);let J=`${$}\x00`;for(let W of this.#J.keys())if(W.startsWith(J))this.#J.delete(W);for(let W of this.#W.keys())if(W.startsWith(J))this.#W.delete(W);for(let[W,X]of this.#Z)if(X.sessionId===$)this.#Z.delete(W);Q1(this.#G,this.#X)}#O($,J){return`${$}\x00${J}`}}import{setBounded as eZ,stickyRetryAfterWithJitter as XW}from"@cortexkit/anthropic-auth-core";var V4="cache-diagnosis-2026-04-07",YW="MC-CACHE-DIAG ",GW=1000,VW=300000,KW={turn:!1,start:!0,prewarm_cachekeep:!0},zW=1000;class NJ{entries=new Map;previousFor($){return this.entries.get($)??null}capture($,J,W){eZ(this.entries,$,{messageId:J,receivedAt:W},GW)}}class HJ{hashes=new Map;capture($,J){if(this.hashes.has($))return null;return eZ(this.hashes,$,!0,zW),`MC-CACHE-DIAG-BETAS ${JSON.stringify({hash:$,betas:[...J].sort()})}`}}function n4($,J,W){let X=$.get(J);if(X)$.set(W,X)}async function DJ($,J,W,X,V){let O=new Headers($.headers);if(O.set("retry-after",String(XW(J,W))),X)return await $.body?.cancel().catch(()=>{}),O.set("content-type","application/json"),new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:"Sticky OAuth account five-hour quota resets shortly; retaining session affinity."}}),{status:429,headers:O});let z=new Response($.body,{status:$.status,statusText:$.statusText,headers:O});return n4(V,$,z),z}function o4($,J){$.diagnostics={previous_message_id:J}}function d$($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function OW($){return d$($)&&$.type==="ephemeral"}function $3($,J){if(!OW($))return;J.push($.ttl==="1h"?"1h":"5m")}function tZ($,J){if(!Array.isArray($))return;for(let W of $)if(d$(W))$3(W.cache_control,J)}function r4($){if(!d$($))return null;let J=[];if($3($.cache_control,J),tZ($.system,J),Array.isArray($.messages)){for(let W of $.messages)if(d$(W))tZ(W.content,J)}return J.at(-1)??null}function jW($){if(!Object.hasOwn($,"diagnostics"))return{state:"absent"};let J=$.diagnostics;if(J===null)return{state:"server_null"};if(!d$(J))return null;if(!Object.hasOwn(J,"cache_miss_reason"))return null;let W=J.cache_miss_reason;if(W===null)return{state:"pending"};if(!d$(W)||typeof W.type!=="string"||!W.type)return null;let X=W.cache_missed_input_tokens;if(X!==void 0&&typeof X!=="number")return null;return{state:"populated",missReason:W.type,cacheMissedInputTokens:X}}function G4($,J){let W=$[J];return typeof W==="number"&&Number.isFinite(W)&&W>=0?W:null}function J3($){if(typeof $.source!=="string"||$.source.length===0||typeof $.accountId!=="string"||$.accountId.length===0||typeof $.synthetic!=="boolean"||typeof $.betasHash!=="string"||$.betasHash.length===0)return{};let J=KW[$.source];if(J!==void 0&&J!==$.synthetic)$.onWarning?.(`cache diagnostics source/synthetic mismatch: source=${$.source} expected=${J} actual=${$.synthetic}`);let W=Math.trunc($.receivedAt);if(!Number.isFinite($.receivedAt)||W!==$.receivedAt)return{};if(!d$($.message))return{};let X=$.message.id,V=$.message.model,O=$.message.usage;if(typeof X!=="string"||X.length===0)return{};if(typeof V!=="string"||V.length===0||!d$(O))return{};let z=G4(O,"input_tokens"),H=G4(O,"cache_read_input_tokens"),w=G4(O,"cache_creation_input_tokens"),R=O.cache_creation;if(z===null||H===null||w===null||!d$(R))return{};let A=G4(R,"ephemeral_5m_input_tokens"),c=G4(R,"ephemeral_1h_input_tokens");if(A===null||c===null)return{};let a=jW($.message);if(!a)return{};let u={v:2,source:$.source,account_id:$.accountId,synthetic:$.synthetic,betas_hash:$.betasHash,session_id:$.request.sessionId,ts_ms_received:W,model:V,is_subagent:$.request.isSubagent,ttl_sent:$.request.ttlSent,cache_read:H,cache_creation:w,input_tokens:z,ephemeral_5m_tokens:A,ephemeral_1h_tokens:c,message_id:X,previous_message_id:$.request.previousMessageId,diag_state:a.state};if(a.missReason!==void 0)u.miss_reason=a.missReason;if(a.cacheMissedInputTokens!==void 0)u.cache_missed_input_tokens=a.cacheMissedInputTokens;if($.requestedModel!==void 0&&$.requestedModel!==V)u.requested_model=$.requestedModel;let s=a.missReason==="previous_message_not_found"&&$.request.previousMessageId!==null&&$.request.previousMessageReceivedAt!==void 0&&$.receivedAt-$.request.previousMessageReceivedAt<VW&&$.receivedAt>=$.request.previousMessageReceivedAt?{messageId:X,previousMessageId:$.request.previousMessageId}:void 0;return{record:u,messageId:X,...s?{canary:s}:{}}}function Z3($){return`${YW}${JSON.stringify($)}`}import{getClaustrumMode as s4,hasNoLocalCredential as UJ,isCustodyTombstoneOAuth as _W,isOAuthAccount as QJ,nativeAccountCanServe as BJ}from"@cortexkit/anthropic-auth-core";function K4($,J){if(s4(J)!=="claustrum"||!J?.claustrum?.scopedRoster)return!1;let W=J.accounts.find((X)=>X.id===$);return Boolean(W&&QJ(W)&&BJ(W)&&W.claustrumScopedCredentialId&&W.anthropicAccountUuid&&UJ(W))}function W3($){if(s4($)!=="claustrum")return{fallbacks:"R",evidence:"V"};if(!$?.claustrum?.scopedRoster)return{fallbacks:"M",evidence:"N"};return{fallbacks:$.accounts.filter((W)=>BJ(W)&&QJ(W)).every((W)=>Boolean(W.claustrumScopedCredentialId&&W.anthropicAccountUuid&&UJ(W)))?"T":"R",evidence:"V"}}function FJ($){if(_W($,"anthropic"))return"T";if($.type==="oauth"&&$.access&&$.refresh)return"R";return"X"}function wJ($,J){if($.role==="main"){if(s4(J)!=="claustrum")return"na";let X=J?.claustrum?.scopedRoster?J.claustrum.primaryAccount:void 0;if(!X)return"unknown-identity";if(X.state==="needs_reauth")return"on-vault-reauth";return BJ(X)?"on-vault-served":"on-cold"}if(s4(J)!=="claustrum")return"off";let W=J?.accounts.find((X)=>X.id===$.id);if(!W||!QJ(W)||!W.claustrumScopedCredentialId||!W.anthropicAccountUuid||!UJ(W))return"off";if(W.claustrumScopedState==="needs_reauth")return"on-vault-reauth";return K4($.id,J)?"on-vault-served":"on-cold"}class z4 extends Error{verdict;dimensions;code="custody_state_mismatch";constructor($,J){super(`custody state mismatch: ${$}`);this.verdict=$;this.dimensions=J}toJSON(){return{code:this.code,verdict:this.verdict,dimensions:this.dimensions}}}function X3($){if($.authority!=="committed"&&$.authority!=="retired")throw new z4("MIGRATION_REQUIRED",$);if($.mode==="L"&&$.main==="R"&&$.evidence==="V"&&$.localOAuthServable===!0)return{verdict:"LOCAL_SERVE"};if($.mode==="L"&&$.main==="T"&&$.fallbacks==="R"&&$.evidence==="V")return{verdict:"LOCAL_SERVE"};if($.mode==="C"&&$.main==="T"&&$.fallbacks==="T"&&$.evidence==="V")return{verdict:"CLAUSTRUM_SERVE"};throw new z4("FAIL_CLOSED",$)}import{createHash as LW}from"node:crypto";import{defaultAdaptiveEffort as NW,isClaudeFable51Model as SJ,isClaudeOpus55Model as HW,isClaudeSonnet55Model as DW,normalizeAdaptiveEffort as UW,supportsPerMessageEffort as QW}from"@cortexkit/anthropic-auth-core";var z3=512,BW=1024,FW=4096,O4=32,j4=32,t4="[A-Za-z0-9_-]{1,128}",wW="<cortexkit-internal-effort ",TW="<cortexkit-internal-effort-plan ",O3=/^\s*(?:§[0-9]+§\s*)+$/,_4={low:"l",medium:"m",high:"h",xhigh:"x",max:"z"},CJ=Object.fromEntries(Object.entries(_4).map(([$,J])=>[J,$])),PJ="<cortexkit-internal-effort-v2 ",AJ="<cortexkit-internal-effort-anchor-v1 ",v1="x-cortexkit-effort-plan";class S0 extends Error{check;details;constructor($,J="unspecified",W={}){super($);this.check=J;this.details=W;this.name="EffortMarkerCorrelationError"}}function o0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function SW($){if(SJ($))return"fable-5-1";if(HW($))return"opus-5-5";if(DW($))return"sonnet-5-5";return}function TJ($){if($?.info?.role!=="user")return;if($.info.model?.providerID!=="anthropic")return;return SW($.info.model.modelID)}function Y3($){return UW($.info?.model?.variant)??NW($.info?.model?.modelID)}function G3($){return $.parts?.some((J)=>{if(J.type==="text")return J.ignored!==!0&&J.text!=="";if(J.type==="file")return J.mime!=="text/plain"&&J.mime!=="application/x-directory";return J.type==="compaction"||J.type==="subtask"})??!1}function O1($){return LW("sha256").update($).digest("hex")}function EW($){return O1(`scope:${$}`).slice(0,j4)}function e4($){return O1(`cortexkit-effort-v2:${$}`).slice(0,O4)}function CW($,J,W){let X=_4[W],V=`transition:${$}:${J}:${X}`;return`${PJ}scope="${$}" boundary="${J}" effort="${X}" check="${e4(V)}"/>`}function j3($){let J=$.match(new RegExp(`^${PJ}scope="([0-9a-f]{${j4}})" boundary="(${t4})" effort="([lmhxz])" check="([0-9a-f]{${O4}})"/>$`));if(!J)return null;let[,W,X,V,O]=J,z=CJ[V??""];if(!W||!X||!V||!O||!z)return null;let H=`transition:${W}:${X}:${V}`;if(e4(H)!==O)return null;return{scope:W,boundary:X,effort:z,token:$}}function PW($,J,W,X){let V=_4[W],O=`anchor:${$}:${J}:${V}:${X}`;return`${AJ}scope="${$}" boundary="${J}" effort="${V}" digest="${X}" check="${e4(O)}"/>`}function _3($){let J=$.match(new RegExp(`^${AJ}scope="([0-9a-f]{${j4}})" boundary="(${t4})" effort="([lmhxz])" digest="([0-9a-f]{64})" check="([0-9a-f]{${O4}})"/>$`));if(!J)return null;let[,W,X,V,O,z]=J,H=CJ[V??""];if(!W||!X||!V||!O||!z||!H)return null;let w=`anchor:${W}:${X}:${V}:${O}`;if(e4(w)!==z)return null;return{scope:W,boundary:X,effort:H,digest:O,token:$}}function EJ($){return $.trim()===""||O3.test($)}function V3(){return new RegExp(`(?:${TW}nonce="[^"]+" baseline="[^"]+" count="[^"]+" sig="[0-9a-f]+"/>|${wW}nonce="[^"]+" effort="[^"]+" sig="[0-9a-f]+"/>)`,"g")}function AW(){return new RegExp(`${PJ}scope="[0-9a-f]{${j4}}" boundary="${t4}" effort="[lmhxz]" check="[0-9a-f]{${O4}}"/>`,"g")}function RW(){return new RegExp(`${AJ}scope="[0-9a-f]{${j4}}" boundary="${t4}" effort="[lmhxz]" digest="[0-9a-f]{64}" check="[0-9a-f]{${O4}}"/>`,"g")}function L3($,J,W){let X=0,V=$,O=$.replace(V3(),"");if(O!==$&&O3.test(O))X+=[...$.matchAll(V3())].length,V=O;return V=V.replace(AW(),(z)=>{let H=j3(z);if(!H)return z;return J?.(H),X++,""}),V=V.replace(RW(),(z)=>{let H=_3(z);if(!H)return z;return W?.(H),X++,""}),{text:V,removed:X}}function qW($){for(let J of $){if(!Array.isArray(J.parts))continue;J.parts=J.parts.flatMap((W)=>{if(W.type!=="text"||typeof W.text!=="string"||!W.text.includes("<cortexkit-internal-effort"))return[W];let X=L3(W.text);if(X.removed===0)return[W];if(EJ(X.text))return[];return W.text=X.text,[W]})}}function a4($,J,W,X,V){let O=V?`:${V}`:"",z=`plan:${$}:${_4[J]}:${W.toString(36)}${O}`;return O1([z,...X].join(`
|
|
2
2
|
`))}function MW($){return["v2",$.scope,_4[$.baseline],$.markerCount.toString(36),$.digest].join(".")}function IW($){if(!$)return null;let J=$.match(/^v2\.([0-9a-f]{32})\.([lmhxz])\.([0-9a-z]+)\.([0-9a-f]{64})$/);if(!J)return null;let[,W,X,V,O]=J,z=CJ[X??""],H=Number.parseInt(V??"",36);if(!W||!z||!O||!Number.isSafeInteger(H)||H<0||H>z3)return null;return{scope:W,baseline:z,markerCount:H,digest:O}}function N3($){let J=$.findLast((u)=>u.info?.role==="user"),W=TJ(J);if(!J||!W)return null;if(qW($),!Array.isArray(J.parts)||!G3(J))return null;let X=J.info?.sessionID,V=J.info?.id;if(typeof X!=="string"||typeof V!=="string")throw new S0("Cannot correlate Fable 5.1 effort markers without session and message IDs");let O=EW(X),z=$.findLast((u)=>u.info?.role==="user"&&u.parts?.some((s)=>s.type==="compaction")),H=typeof z?.info?.id==="string"?z.info.id:void 0,w,R;if(z&&TJ(z)===W)w=Y3(z),R=w;let A=[];for(let u of $){let s=u.info;if(s?.role!=="user")continue;if(H&&typeof s.id==="string"&&s.id<=H)continue;if(TJ(u)!==W||!G3(u))continue;let T=Y3(u);if(!w){w=T,R=T;continue}if(T===R)continue;if(A.length>=z3)throw new S0("Too many Fable 5.1 effort changes in the active context");if(!Array.isArray(u.parts)||typeof s.id!=="string")throw new S0("Cannot mark a Fable 5.1 effort change without message identity");let o=CW(O,s.id,T);u.parts.push({type:"text",text:o}),A.push(o),R=T}if(!w)return null;let c=a4(O,w,A.length,A,A.length>0?V:void 0),a=A.length>0?PW(O,V,R??w,c):void 0;if(a)J.parts.push({type:"text",text:a});return{scope:O,baseline:w,markerCount:A.length,digest:c,transitionTokens:A,anchorToken:a,sessionId:X,messageId:V}}function xW($){let J=Array.isArray($.messages)?$.messages:[],W=[];for(let X of J){let V=[],O=[];if(!o0(X)||X.role!=="user"){W.push({value:X,transitions:V,anchors:O});continue}let z=(H)=>L3(H,(w)=>V.push(w),(w)=>O.push(w));if(typeof X.content==="string"){let H=z(X.content);X.content=H.removed>0&&EJ(H.text)?"":H.text}else if(Array.isArray(X.content))X.content=X.content.flatMap((H)=>{if(!o0(H)||H.type!=="text"||typeof H.text!=="string")return[H];let w=z(H.text);if(w.removed>0&&EJ(w.text))return[];return[{...H,text:w.text}]});W.push({value:X,transitions:V,anchors:O})}return $.messages=W.map((X)=>X.value),{messages:W}}function fW($,J){let W=$[J]?.value,X=$[J-1]?.value;if(!o0(W)||W.role!=="user"||!Array.isArray(W.content)||W.content.length===0||!o0(X)||X.role!=="assistant"||!Array.isArray(X.content))return!1;let V=new Set(X.content.flatMap((O)=>o0(O)&&O.type==="tool_use"&&typeof O.id==="string"?[O.id]:[]));return W.content.every((O)=>o0(O)&&O.type==="tool_result"&&typeof O.tool_use_id==="string"&&V.has(O.tool_use_id))}function kW($,J){if(J<0)return!1;let W=$.flatMap((X,V)=>V>J&&o0(X.value)&&X.value.role==="user"?[V]:[]);return W.length>0&&W.every((X)=>fW($,X))}function K3($){if(!o0($))return null;if(typeof $.id==="string")return $.id;return typeof $.message_id==="string"?$.message_id:null}function vW($,J){if(!J)return null;if(J.scope!==$.scope||J.baseline!==$.baseline||J.markerCount!==$.markerCount||J.digest!==$.digest||J.transitionTokens.length!==$.markerCount)throw new S0("Fable 5.1 effort marker request plan mismatch");let W=J.transitionTokens.map((O)=>j3(O)),X=J.anchorToken?_3(J.anchorToken):null,V=W.at(-1)?.effort??$.baseline;if(W.some((O)=>O===null)||W.some((O)=>O?.scope!==$.scope)||$.markerCount>0&&(!X||X.scope!==$.scope||X.boundary!==J.messageId||X.effort!==V||X.digest!==$.digest)||$.markerCount===0&&X!==null||$.digest!==a4($.scope,$.baseline,$.markerCount,J.transitionTokens,J.markerCount>0?J.messageId:void 0))throw new S0("Fable 5.1 effort marker request plan mismatch");return{transitions:W,anchor:X}}function H3($,J,W,X){if(!Array.isArray($.messages))return{found:0,inserted:0};let V=IW(W);if(W&&!V)throw new S0("Missing or invalid internal Fable 5.1 effort request plan");let O=V?vW(V,X):null,z=O?.transitions??null;if(!$.messages.some((b)=>{if(!o0(b)||b.role!=="user")return!1;if(typeof b.content==="string"&&b.content.includes("<cortexkit-internal-effort"))return!0;return Array.isArray(b.content)&&b.content.some((O0)=>o0(O0)&&O0.type==="text"&&typeof O0.text==="string"&&O0.text.includes("<cortexkit-internal-effort"))})){if(!V)return{found:0,inserted:0};if(V.markerCount!==0){let b=$.messages.findLastIndex((q)=>o0(q)&&q.role==="user"),O0=$.messages[b],m0=o0(O0)&&Array.isArray(O0.content)?O0.content:[];throw new S0(`Fable 5.1 effort marker correlation failed: expected ${V.markerCount}, found 0`,"missing_all_markers",{markerCount:V.markerCount,resolvedPlan:O!==null,plannedBoundaryId:O?.anchor?.boundary??null,expectedAnchorHash:O?.anchor?O1(O.anchor.token):null,retainedMessageCount:$.messages.length,retainedUserMessageCount:$.messages.filter((q)=>o0(q)&&q.role==="user").length,lastUserMessageIndex:b,lastUserTextBlockCount:m0.filter((q)=>o0(q)&&q.type==="text").length,lastUserToolResultBlockCount:m0.filter((q)=>o0(q)&&q.type==="tool_result").length})}if(!z&&V.digest!==a4(V.scope,V.baseline,0,[]))throw new S0("Fable 5.1 effort marker request plan mismatch");if(J&&SJ($.model)){let b=o0($.output_config)?{...$.output_config}:{};b.effort=z?.at(-1)?.effort??V.baseline,$.output_config=b}return{found:0,inserted:0}}let w=xW($),R=w.messages.flatMap((b)=>b.transitions),A=w.messages.flatMap((b)=>b.anchors),c=R.length;if(!V){if(c===0)return{found:0,inserted:0};throw new S0("Missing or invalid internal Fable 5.1 effort request plan")}for(let b of w.messages){for(let O0 of b.transitions)if(O0.scope!==V.scope)throw new S0("Fable 5.1 effort marker scope mismatch");if(b.anchors.length>1)throw new S0("Multiple internal Fable 5.1 effort anchors on one user boundary")}let a=w.messages.findIndex((b)=>b.anchors.length===1),u=w.messages.findLastIndex((b)=>o0(b.value)&&b.value.role==="user"),s=A[0],T=w.messages[u]?.value,o=kW(w.messages,a);if(V.markerCount>0&&(A.length!==1||a!==u&&!o||!s||s.scope!==V.scope))throw new S0("Missing or invalid internal Fable 5.1 effort anchor placement","anchor_placement",{anchorBoundaryId:s?.boundary??null,plannedBoundaryId:O?.anchor?.boundary??null,lastUserMessageId:K3(T),anchorMessageIndex:a,lastUserMessageIndex:u,validToolContinuationSuffix:o,anchorsFound:A.length,markerCount:V.markerCount,scope:V.scope,foundScope:s?.scope??null,expectedAnchorHash:O?.anchor?O1(O.anchor.token):null,foundAnchorHash:s?O1(s.token):null,anchorMatchesExpected:O?.anchor!=null&&s?.token===O.anchor.token});if(V.markerCount===0&&A.length!==0)throw new S0("Unexpected internal Fable 5.1 effort anchor");if(O?.anchor&&s?.token!==O.anchor.token)throw new S0("Mismatched internal Fable 5.1 effort anchor token","anchor_token",{anchorBoundaryId:s?.boundary??null,plannedBoundaryId:O.anchor.boundary,lastUserMessageId:K3(T),anchorMessageIndex:a,lastUserMessageIndex:u,anchorsFound:A.length,markerCount:V.markerCount,scope:V.scope,foundScope:s?.scope??null,expectedAnchorHash:O1(O.anchor.token),foundAnchorHash:s?O1(s.token):null,anchorMatchesExpected:!1});let q0=V.baseline;if(z){let b=z.length-c;if(b<0)throw new S0(`Fable 5.1 effort marker correlation failed: expected ${V.markerCount}, found ${c}`);let O0=z.slice(b);if(R.some((q,s0)=>q.token!==O0[s0]?.token))throw new S0("Fable 5.1 effort marker non-prefix loss");let m0=z.slice(0,b);if(s&&m0.some((q)=>q.boundary===s.boundary))throw new S0("Fable 5.1 effort marker non-prefix loss");q0=m0.at(-1)?.effort??V.baseline}else{if(c!==V.markerCount)throw new S0(`Fable 5.1 effort marker correlation failed: expected ${V.markerCount}, found ${c}`);let b=a4(V.scope,V.baseline,V.markerCount,R.map((m0)=>m0.token),s?.boundary);if(V.digest!==b)throw new S0("Fable 5.1 effort marker request plan mismatch");let O0=R.at(-1)?.effort??V.baseline;if(s&&(s.effort!==O0||s.digest!==V.digest))throw new S0("Missing or invalid internal Fable 5.1 effort anchor")}let G0=J&&QW($),I0=0,L0=[];for(let b of w.messages){let O0=b.transitions.at(-1);if(O0&&G0)L0.push({role:"system",content:[],output_config:{effort:O0.effort}}),I0++;L0.push(b.value)}if($.messages=L0,G0&&(I0>0||SJ($.model))){let b=o0($.output_config)?{...$.output_config}:{};b.effort=q0,$.output_config=b}return{found:c,inserted:I0}}class RJ{plans=new Map;history=new Map;historyByMessage=new Map;record($){let J=this.key($.sessionId,$.messageId),W={...$,transitionTokens:[...$.transitionTokens]};this.remember(J,W),this.plans.delete(J),this.plans.set(J,W);while(this.plans.size>BW){let X=this.plans.keys().next().value;if(typeof X!=="string")break;this.plans.delete(X)}}clear($,J){let W=this.key($,J);this.plans.delete(W);for(let X of this.historyByMessage.get(W)??[])this.history.delete(X);this.historyByMessage.delete(W)}markHeaders($){let J=this.key($.sessionId,$.messageId),W=this.plans.get(J);if(!W)return!1;return $.headers[v1]=this.remember(J,W),this.plans.delete(J),this.plans.set(J,W),!0}resolveHeader($){return $?this.history.get($):void 0}remember($,J){let W=MW(J),X=this.history.get(W);if(X&&this.key(X.sessionId,X.messageId)!==$){if(X.markerCount!==0||J.markerCount!==0||X.sessionId!==J.sessionId)throw new S0("Fable 5.1 effort plan header collision");let O=this.key(X.sessionId,X.messageId),z=this.historyByMessage.get(O);if(z?.delete(W),z?.size===0)this.historyByMessage.delete(O)}this.history.delete(W),this.history.set(W,J);let V=this.historyByMessage.get($)??new Set;V.add(W),this.historyByMessage.set($,V);while(this.history.size>FW){let O=this.history.entries().next().value;if(!O)break;let[z,H]=O;this.history.delete(z);let w=this.key(H.sessionId,H.messageId),R=this.historyByMessage.get(w);if(R?.delete(z),R?.size===0)this.historyByMessage.delete(w)}return W}key($,J){return`${$}\x00${J}`}}import{CLAUDE_FABLE_5_1_MODEL_ID as D3,CLAUDE_FABLE_5_MODEL_ID as U3,isClaudeOpus5Model as hW,isClaudeOpus55Model as bW,normalizeAnthropicModelId as gW}from"@cortexkit/anthropic-auth-core";var Q3="claude-opus-4-8",qJ=10,B3=128,yW=86400000;function h$($){if(typeof $!=="string")return null;let J=gW($);if(bW(J))return"opus-5-5";if(hW(J))return"opus-5";if(J===D3||J.startsWith(`${D3}-`))return"fable-5-1";if(J===U3||J.startsWith(`${U3}-`))return"fable-5";return null}function h1($){return h$($)!==null}function mW($,J){let W=h$(J);return W?`${$}\x00${W}`:null}function cW($){try{let J=JSON.parse($);return typeof J.model==="string"?{body:J,model:J.model}:null}catch{return null}}class MJ{now;recoveries=new Map;selectedModels=new Map;nextCycle=1;constructor($=Date.now){this.now=$}prune(){let $=this.now();for(let[J,W]of this.recoveries)if($-W.updatedAt>=yW)this.recoveries.delete(J);while(this.recoveries.size>B3){let J=this.recoveries.keys().next().value;if(typeof J!=="string")break;this.recoveries.delete(J)}}clearSession($){this.selectedModels.delete($);for(let J of this.recoveries.keys())if(J.startsWith(`${$}\x00`))this.recoveries.delete(J)}resetForModelChange($,J){let W=this.selectedModels.get($),X=W!==void 0&&W!==J;if(X)this.clearSession($);this.selectedModels.delete($),this.selectedModels.set($,J);while(this.selectedModels.size>B3){let V=this.selectedModels.keys().next().value;if(V===void 0)break;this.selectedModels.delete(V)}return X}plan($,J){if(!$||typeof J!=="string")return null;this.prune();for(let[O,z]of[...this.recoveries]){if(!O.startsWith(`${$}\x00`))continue;z.updatedAt=this.now(),this.recoveries.delete(O),this.recoveries.set(O,z)}let W=cW(J);if(!W||!h1(W.model))return null;let X=mW($,W.model);if(!X)return null;let V=this.recoveries.get(X);if(V)V.nextRequestSequence++;if(!V||V.remaining<=0)return{sessionId:$,recoveryKey:X,requestedModel:W.model,effectiveModel:W.model,bodyText:J,downgraded:!1,cycle:V?.cycle,standbyCacheAnchor:V?.standbyCacheAnchor};return V.updatedAt=this.now(),this.recoveries.delete(X),this.recoveries.set(X,V),W.body.model=Q3,{sessionId:$,recoveryKey:X,requestedModel:V.model,effectiveModel:Q3,bodyText:JSON.stringify(W.body),downgraded:!0,cycle:V.cycle,cacheAccountId:V.cacheAccountId,standbyCacheAnchor:V.standbyCacheAnchor,requestSequence:V.nextRequestSequence}}recoveryAccount($){if($.cycle===void 0)return $.cacheAccountId;let J=this.recoveries.get($.recoveryKey);return J?.cycle===$.cycle?J.cacheAccountId:$.cacheAccountId}bindRecoveryAccount($,J){if(!$.downgraded||$.cycle===void 0)return!1;let W=this.recoveries.get($.recoveryKey);if(!W||W.cycle!==$.cycle)return!1;if(W.cacheAccountId===J)return!1;return W.cacheAccountId=J,W.standbyCacheAnchor=void 0,W.standbyAnchorSequence=0,W.updatedAt=this.now(),$.cacheAccountId=J,$.standbyCacheAnchor=void 0,!0}activate($,J){if($.downgraded||!h1($.requestedModel))return this.remaining($);let W=this.recoveries.get($.recoveryKey),X=W&&W.sourceSuccesses<qJ?W.reRefusals+1:0,V={model:$.requestedModel,remaining:qJ*2**Math.min(X,2),reRefusals:X,sourceSuccesses:0,cycle:this.nextCycle++,cacheAccountId:J,standbyCacheAnchor:$.standbyCacheAnchor,nextRequestSequence:0,standbyAnchorSequence:0,updatedAt:this.now()};return this.recoveries.delete($.recoveryKey),this.recoveries.set($.recoveryKey,V),this.prune(),V.remaining}completeSource($,J=!0){if($.downgraded||$.cycle==null||$.completed)return!1;$.completed=!0;let W=this.recoveries.get($.recoveryKey);if(!W||W.cycle!==$.cycle||W.remaining>0)return!1;if(!J)return W.sourceSuccesses=0,!1;return W.sourceSuccesses=Math.min(W.sourceSuccesses+1,qJ),W.updatedAt=this.now(),!0}complete($,J){if(!$.downgraded||$.cycle==null||$.completed)return{counted:!1,remaining:this.remaining($)};$.completed=!0;let W=this.recoveries.get($.recoveryKey);if(!W||W.cycle!==$.cycle||W.remaining<=0)return{counted:!1,remaining:W?.remaining??0};if(W.remaining--,J&&(!W.cacheAccountId||J.oauthAccountId===W.cacheAccountId)&&$.requestSequence!=null&&$.requestSequence>=W.standbyAnchorSequence)W.standbyCacheAnchor=J,W.standbyAnchorSequence=$.requestSequence;return W.updatedAt=this.now(),this.recoveries.delete($.recoveryKey),this.recoveries.set($.recoveryKey,W),{counted:!0,remaining:W.remaining}}remaining($){return this.prune(),this.recoveries.get($.recoveryKey)?.remaining??0}}function i$($){return typeof $==="object"&&$!==null}function pW($){if(Array.isArray($))return $;if(i$($)&&Array.isArray($.data))return $.data;return[]}function T3($){if(!i$($)||!i$($.info))return;return $.info}function F3($){let J=T3($);return typeof J?.role==="string"?J.role:void 0}function lW($){let J=T3($);return typeof J?.id==="string"?J.id:void 0}function IJ($){if(!i$($)||!i$($.info))return null;let J=$.info,W=i$(J.model)?J.model:void 0,X=typeof J.agent==="string"?J.agent:void 0,V=typeof W?.providerID==="string"?W.providerID:typeof J.providerID==="string"?J.providerID:void 0,O=typeof W?.modelID==="string"?W.modelID:typeof W?.id==="string"?W.id:typeof J.modelID==="string"?J.modelID:void 0,z=typeof W?.variant==="string"?W.variant:typeof J.variant==="string"?J.variant:void 0;if(!X&&(!V||!O)&&!z)return null;let H={};if(X)H.agent=X;if(V&&O)H.model={providerID:V,modelID:O};if(z)H.variant=z;return H}function xJ($,J){return{agent:$.agent??J.agent,model:$.model??J.model,variant:$.variant??J.variant,latestAssistantMessageId:$.latestAssistantMessageId??J.latestAssistantMessageId,latestUserMessageId:$.latestUserMessageId??J.latestUserMessageId}}function w3($){return Boolean($.agent&&$.model&&$.variant)}async function $9($,J){if(!$||!J)return null;let W=$,X=[];if(typeof W.session?.messages==="function")try{X=pW(await Promise.resolve(W.session.messages({path:{id:J},query:{limit:100}})))}catch{X=[]}let V,O;for(let H of X){let w=lW(H);if(!w)continue;let R=F3(H);if(R==="assistant"&&(!V||w>V))V=w;if(R==="user"&&(!O||w>O))O=w}let z={latestAssistantMessageId:V,latestUserMessageId:O};for(let H=X.length-1;H>=0;H--){if(F3(X[H])!=="assistant")continue;let w=IJ(X[H]);if(!w)continue;if(z=xJ(z,w),w3(z))return z}for(let H=X.length-1;H>=0;H--){let w=IJ(X[H]);if(!w)continue;if(z=xJ(z,w),w3(z))return z}if(typeof W.session?.get==="function")try{let H=await Promise.resolve(W.session.get({path:{id:J}})),w=i$(H)&&i$(H.data)?H.data:i$(H)?H:void 0,R=w?IJ({info:w}):null;if(R)z=xJ(z,R)}catch{}if(!z.agent&&!z.model&&!z.variant&&!z.latestAssistantMessageId&&!z.latestUserMessageId)return null;return z}var S3="[lane start] — automated cache warm; no response needed.",J9="x-cortexkit-lane-start",uW=1000;function dW($){if(!$||typeof $!=="object")return!1;let J=$;return J.type==="text"&&J.text===S3&&J.synthetic===!0}async function E3($,J){let W=$?.session;if(typeof W?.promptAsync!=="function")throw Error("OpenCode plugin client does not support session.promptAsync");let X=await $9($,J),V={noReply:!1,parts:[{type:"text",text:S3,synthetic:!0}]};if(X?.agent)V.agent=X.agent;if(X?.model)V.model=X.model;if(X?.variant)V.variant=X.variant;await Promise.resolve(W.promptAsync({path:{id:J},body:V}))}class fJ{#$=new Map;observeSyntheticMessage($){if(!$.parts.some(dW))return!1;let J=`${$.sessionId}\x00${$.messageId}`;if(!this.#$.has(J)&&this.#$.size>=uW){let W=this.#$.keys().next().value;if(W!==void 0)this.#$.delete(W)}return this.#$.set(J,$.sessionId),!0}markHeaders($){let J=`${$.sessionId}\x00${$.messageId}`;if(!this.#$.has(J))return!1;return this.#$.delete(J),$.headers[J9]="1",!0}clearSession($){for(let[J,W]of this.#$)if(W===$)this.#$.delete(J)}}import{createNativeUi as iW,disconnectNativeVaultForHost as nW,readNativeEnrollmentMode as oW}from"@cortexkit/anthropic-auth-core";function C3($){if(!$?.trim())throw TypeError("sessionId is required");return $}function P3($){if($.host!=="opencode")throw TypeError("OpenCode host is required");let J=iW({...$,readMode:$.readMode??(()=>oW("opencode",process.env)),disconnectVault:$.disconnectVault??(()=>nW({host:"opencode",env:process.env}))});return{menu:J,open(W){return J.open({sessionId:C3(W),notify(){}})},apply(W){return J.apply(W,{sessionId:C3(W.sessionId),notify(){}})}}}import{primeStorageFingerprint as rW}from"@cortexkit/anthropic-auth-core";var Z9=new Map,W9=new Map;function A3($,J){let W=W9.get($);if(W?.fingerprint!==J.fingerprint||W.marker!==J.marker)return;let X=Z9.get(J.fingerprint);if(X?.slots.delete($),X?.slots.size===0)X.manager.stop(),Z9.delete(J.fingerprint);W9.delete($)}function R3($,J,W){let X=rW($),V=Z9.get(X),O=V?.manager??J();if(V)W.rebind(O);let z=W9.get(W.slot);if(z&&z.fingerprint!==X)A3(W.slot,z);let H=V??{manager:O,slots:new Set};if(!V)Z9.set(X,H);let w={fingerprint:X,marker:Symbol(W.slot)};return H.slots.add(W.slot),W9.set(W.slot,w),{manager:O,release:()=>A3(W.slot,w)}}import{classifySafeErrorForLog as sW,logger as aW}from"@cortexkit/anthropic-auth-core";function q3($,J,W){aW.warn("quota","fallback quota preflight could not obtain a reading",{accountId:$,requiredByPolicy:J,...sW(W)})}var kJ="x-cortexkit-request-class",tW=new Set(["title","summary","prime"]);function M3($){return typeof $==="string"&&tW.has($)}function I3($){let J=$.get("x-cortexkit-request-class");return $.delete("x-cortexkit-request-class"),J==="auxiliary"?"auxiliary":"main"}import{getKillswitchThresholdsForAccount as eW,getScopedQuotaWindowForModel as $X,killswitchPassesPolicy as JX}from"@cortexkit/anthropic-auth-core";function x3($){let J=Math.floor($.retryAfterSeconds/60),W=$.retryAfterSeconds%60,X=`Retry in ${J}m ${W}s.`;return $.modelName?`${$.modelName} weekly limit reached, no routable accounts. ${X}`:`Killswitch: no routable accounts. ${X}`}function f3($){if(!$.requestModelId)return{isScopedDriven:!1};if(!JX($.mainQuota,$.storage))return{isScopedDriven:!1};let J=$X($.mainQuota,$.requestModelId);if(!J)return{isScopedDriven:!1};if(!Number.isFinite(J.remainingPercent))return{isScopedDriven:!1};let W=eW($.storage);if(J.remainingPercent<=W.scoped)return{isScopedDriven:!0,modelName:J.modelName,modelId:$.requestModelId};return{isScopedDriven:!1}}var n$=[],k3=1,v3=new Map;function h3($){if(typeof $!=="string"||$.length===0)throw TypeError("sessionId is required")}function b3($,J){if(h3(J),"menu"in $){if($.command!=="claude"||$.menu.command!=="claude")throw TypeError("Only the claude menu is supported");n$.push({id:k3++,type:"open-menu",payload:$,sessionId:J})}else n$.push({id:k3++,type:"open-dialog",payload:$,sessionId:J});if(n$.length>100)n$=n$.slice(n$.length-100)}function g3($,J){if(h3(J),v3.set(J,Date.now()),$>0)n$=n$.filter((W)=>W.id>$||W.sessionId!==J);return n$.filter((W)=>W.id>$&&W.sessionId===J)}function X9($){let J=Date.now(),W=v3.get($)??0;return W>0&&J-W<3000}import{randomBytes as ZX,timingSafeEqual as WX}from"node:crypto";import{readFile as XX,unlink as YX}from"node:fs/promises";import{createServer as GX}from"node:http";import{join as VX}from"node:path";import{parseApplyRequest as KX}from"@cortexkit/anthropic-auth-core";function zX($){return new Promise((J,W)=>{let X=[],V=0;$.on("data",(O)=>{if(V+=O.length,V>1e6){$.destroy(),W(Error("body too large"));return}X.push(O)}),$.on("end",()=>J(Buffer.concat(X).toString("utf8"))),$.on("error",W)})}function OX($,J){if(!$?.startsWith("Bearer "))return!1;let W=Buffer.from($.slice(7)),X=Buffer.from(J);return W.length===X.length&&WX(W,X)}async function m3($){let J=ZX(32).toString("hex"),W=GX((O,z)=>{X(O,z)});async function X(O,z){let H=(w,R)=>{z.writeHead(w,{"content-type":"application/json"}),z.end(JSON.stringify(R))};try{let w=O.url??"";if(O.method==="GET"&&w==="/health")return H(200,{ok:!0});if(O.method!=="POST"||!w.startsWith("/rpc/"))return H(404,{error:"not found"});if(!OX(O.headers.authorization,J))return H(401,{error:"unauthorized"});let R=w.slice(5),A=JSON.parse(await zX(O)||"{}");if(R==="pending-notifications"){if(typeof A.sessionId!=="string"||A.sessionId.length===0)return H(400,{error:"sessionId is required"});let c=$.drain(Number(A.lastReceivedId??0),A.sessionId);return H(200,{messages:c})}if(R==="apply"){if(!$.apply)return H(501,{error:"text apply unavailable"});let c=await $.apply(A);return H(200,c)}if(R==="apply-menu"){let c=KX(A);if(c?.command!=="claude"||!c.sessionId?.trim())return H(400,{error:"invalid menu request"});if(!$.applyMenu)return H(501,{error:"menu unavailable"});return H(200,await $.applyMenu(c))}return H(404,{error:"unknown method"})}catch{if(!z.headersSent&&!z.writableEnded&&!z.destroyed)H(500,{error:"RPC request failed"})}}let V=await new Promise((O,z)=>{W.on("error",z),W.listen(0,"127.0.0.1",()=>{let H=W.address();if(H&&typeof H==="object")O(H.port);else z(Error("no port"))})});W.unref();try{await y3($.dir,{port:V,token:J,pid:process.pid})}catch(O){throw await new Promise((z)=>W.close(()=>z())),O}return{port:V,token:J,async stop(){await new Promise((O)=>W.close(()=>O()));try{let O=VX($.dir,`port-${process.pid}.json`),z=JSON.parse(await XX(O,"utf8"));if(z.port===V&&z.pid===process.pid)await YX(O)}catch{}}}}async function c3($,J){let W=globalThis,X=W.__anthropicAuthRpcServers??new Map,V=W.__anthropicAuthRpcServersPending??new Map;W.__anthropicAuthRpcServers=X,W.__anthropicAuthRpcServersPending=V;let O=V.get($)??Promise.resolve(),z,H=O.catch(()=>{}).then(async()=>{let R=X.get($);if(R){if(await R.stop(),X.get($)===R)X.delete($)}z=await J(),X.set($,z)});V.set($,H);try{await H}finally{if(V.get($)===H)V.delete($)}let w=z;if(!w)throw Error("RPC server failed to start");return{server:w,release:async()=>{if(X.get($)!==w)return;if(await w.stop(),X.get($)===w)X.delete($)}}}import{isClaudeFable51Model as jX}from"@cortexkit/anthropic-auth-core";var u3="server-side-fallback-2026-07-01",d3="",Y9="cortexkit-server-fallback-v1:";function M$($){return $!==null&&typeof $==="object"&&!Array.isArray($)?$:void 0}function b1($,J){let W=$?.[J];return typeof W==="string"?W:void 0}function g1($){return typeof $==="string"&&$.length>0&&$.length<=128&&/^claude-[a-z0-9-]+$/i.test($)}function _X($){return`${Y9}${$.fromModel}|${$.toModel}`}function LX($){if(typeof $!=="string"||!$.startsWith(Y9))return null;let J=$.slice(Y9.length),W=J.indexOf("|");if(W<=0||W!==J.lastIndexOf("|"))return null;let X=J.slice(0,W),V=J.slice(W+1);if(!g1(X)||!g1(V))return null;return{fromModel:X,toModel:V}}function NX($){if($.type!=="fallback")return null;let J=b1(M$($.from),"model"),W=b1(M$($.to),"model");if(!g1(J)||!g1(W))return null;return{fromModel:J,toModel:W}}function HX($){return{type:"fallback",from:{model:$.fromModel},to:{model:$.toModel}}}function DX($,J){let W=0,X=0;if(!Array.isArray($.messages))return{restoredMarkers:W,droppedMarkers:X};for(let V of $.messages){let O=M$(V);if(O?.role!=="assistant"||!Array.isArray(O.content))continue;let z=[];for(let H of O.content){let w=M$(H);if(!(w?.type==="thinking"&&(w.thinking===d3||w.thinking==="")&&typeof w.signature==="string"&&w.signature.startsWith(Y9))){z.push(H);continue}let A=LX(w.signature);if(J&&A)z.push(HX(A)),W++;else X++}O.content=z}return{restoredMarkers:W,droppedMarkers:X}}function i3($){return $?.trim().toLowerCase()==="legacy"?"legacy":"server"}function n3($,J){let W=J&&(h1($.model)||jX($.model)),X=DX($,W);if(W)$.fallbacks="default";else if($.fallbacks==="default")delete $.fallbacks;return{enabled:W,...X}}function UX($){let J,W=[];for(let V of $.split(/\r?\n/))if(V.startsWith("event:"))J=V.slice(6).trim();else if(V.startsWith("data:")){let O=V.slice(5);W.push(O.startsWith(" ")?O.slice(1):O)}let X=W.join(`
|
|
3
3
|
`);if(!X||X==="[DONE]")return{event:J};try{return{event:J,data:M$(JSON.parse(X))}}catch{return{event:J}}}function p3($){let J=$.indexOf(`
|
|
4
4
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{mkdir as l,readdir as u,readFile as c,rename as p,unlink as m,writeFile as d}from"node:fs/promises";import{join as a}from"node:path";function f(t){try{return process.kill(t,0),!0}catch(r){return r.code==="EPERM"}}async function b(t,r){await l(t,{recursive:!0});let s={...r,startedAt:Date.now()},e=a(t,`port-${r.pid}.json`),i=`${e}.${process.pid}.tmp`;return await d(i,JSON.stringify(s),{encoding:"utf8",mode:384}),await p(i,e),e}async function h(t,r){let s;try{s=await u(t)}catch{return null}let e=[];for(let n of s){if(!n.startsWith("port-")||!n.endsWith(".json"))continue;try{let o=JSON.parse(await c(a(t,n),"utf8"));if(Number.isFinite(o.port))if(f(o.pid))e.push(o);else m(a(t,n)).catch(()=>{})}catch{}}if(e.length===0)return null;let i=r&&r>=1?e.filter((n)=>n.pid===r):[];return(i.length>0?i:e).sort((n,o)=>o.startedAt-n.startedAt)[0]??null}
|
|
2
|
-
export{b as
|
|
2
|
+
export{b as fa,h as ga};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{randomUUID as P}from"node:crypto";import{mkdir as h,readFile as y,rename as S,rm as C,rmdir as w,stat as R,unlink as m,writeFile as b}from"node:fs/promises";import{tmpdir as d}from"node:os";import{dirname as v,join as M}from"node:path";import{formatQuota as c,isQuotaStale as s,logger as z,quotaDisplayProjection as I,quotaTextParts as u}from"@cortexkit/anthropic-auth-core";var n="OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE",i=M(d(),"opencode-anthropic-auth"),l=M(i,"sidebar-state.json");function f(){return process.env[n]||l}var W={main:{quota:null},fallbacks:[],activeId:void 0,route:"main",relay:null,fastMode:!1,lastUpdated:0};function Q(J){return J!==null&&typeof J==="object"&&!Array.isArray(J)}function N(J){return typeof J==="number"&&Number.isFinite(J)}function o(J){if(!Q(J))return;let Z=Number(J.count),V=Number(J.inputTokens),X=Number(J.outputTokens),G=Number(J.since);if(![Z,V,X,G].every(Number.isFinite)||Z<0||V<0||X<0||G<0)return;return{count:Math.floor(Z),inputTokens:Math.floor(V),outputTokens:Math.floor(X),since:Math.floor(G)}}function r(J){if(!Q(J))return;if(typeof J.id!=="string"||!J.id.trim())return;if(typeof J.label!=="string"||!J.label.trim())return;let Z={id:J.id.trim(),label:J.label.trim()};if(J.nextDueAt===null)Z.nextDueAt=null;else if(N(J.nextDueAt))Z.nextDueAt=J.nextDueAt;if(J.lastPrimedAt===null)Z.lastPrimedAt=null;else if(N(J.lastPrimedAt))Z.lastPrimedAt=J.lastPrimedAt;if(J.lastResult==="ok"||J.lastResult==="error"||J.lastResult==="skipped")Z.lastResult=J.lastResult;let V=o(J.usage);if(V)Z.usage=V;if(N(J.estimatedCostUsd))Z.estimatedCostUsd=J.estimatedCostUsd;return Z}function a(J){if(!Q(J))return;if(typeof J.enabled!=="boolean")return;let Z=Array.isArray(J.accounts)?J.accounts.map(r).filter((V)=>V!=null):[];return{enabled:J.enabled,accounts:Z}}function q(J){if(!Q(J))return;let Z=Number(J.usedPercent),V=Number(J.remainingPercent);if(!Number.isFinite(Z)||!Number.isFinite(V))return;return{usedPercent:Z,remainingPercent:V,resetsAt:typeof J.resetsAt==="string"?J.resetsAt:void 0,...N(J.checkedAt)&&{checkedAt:J.checkedAt}}}function D(J){if(!Q(J))return null;let Z={};if(N(J.checkedAt))Z.checkedAt=J.checkedAt;let V=q(J.five_hour),X=q(J.seven_day);if(V)Z.five_hour=V;if(X)Z.seven_day=X;if(Array.isArray(J.scoped)){let G=J.scoped.map((Y)=>{if(!Q(Y))return;let $=q(Y);if(!$)return;if(typeof Y.id!=="string"||!Y.id.trim())return;if(typeof Y.title!=="string"||!Y.title.trim())return;if(typeof Y.modelName!=="string"||!Y.modelName.trim())return;let j=typeof Y.modelId==="string"&&Y.modelId.trim()?Y.modelId.trim():void 0;return{...$,id:Y.id.trim(),title:Y.title.trim(),...j&&{modelId:j},modelName:Y.modelName.trim()}}).filter((Y)=>Y!=null);Z.scoped=G}if(Q(J.extraUsage)){let G=A(J.extraUsage.used),Y=A(J.extraUsage.limit);if(G&&Y&&typeof J.extraUsage.exhausted==="boolean")Z.extraUsage={used:G,limit:Y,...typeof J.extraUsage.utilizationPercent==="number"&&Number.isFinite(J.extraUsage.utilizationPercent)&&{utilizationPercent:J.extraUsage.utilizationPercent},...typeof J.extraUsage.severity==="string"&&{severity:J.extraUsage.severity},exhausted:J.extraUsage.exhausted}}if(typeof J.bindingWindow==="string"&&J.bindingWindow.trim())Z.bindingWindow=J.bindingWindow.trim();if(typeof J.fallbackAdvised==="boolean")Z.fallbackAdvised=J.fallbackAdvised;return Object.keys(Z).length?Z:null}function A(J){if(!Q(J))return;if(!Number.isInteger(J.amountMinor)||typeof J.currency!=="string"||!/^[A-Za-z]{3}$/.test(J.currency.trim())||!Number.isInteger(J.exponent)||J.exponent<0||J.exponent>20)return;return{amountMinor:J.amountMinor,currency:J.currency.trim(),exponent:J.exponent}}function p(J){if(!Q(J))return{...W};let Z={quota:null};if(Q(J.main)){let $=J.main;if(Z.quota=D($.quota),typeof $.enabled==="boolean")Z.enabled=$.enabled;if(typeof $.stateLine==="string")Z.stateLine=$.stateLine;if($.quotaDated===!0)Z.quotaDated=!0;if(typeof $.tierLabel==="string"&&$.tierLabel.trim())Z.tierLabel=$.tierLabel.trim();if(typeof $.quotaBackedOff==="boolean")Z.quotaBackedOff=$.quotaBackedOff;if(typeof $.quotaBackoffUntil==="number")Z.quotaBackoffUntil=$.quotaBackoffUntil;if(typeof $.refreshBackedOff==="boolean")Z.refreshBackedOff=$.refreshBackedOff;if(typeof $.refreshBackoffUntil==="number")Z.refreshBackoffUntil=$.refreshBackoffUntil}let V=Array.isArray(J.fallbacks)?J.fallbacks.filter(Q).filter(($)=>typeof $.id==="string").map(($)=>({id:$.id,label:typeof $.label==="string"?$.label:void 0,quota:D($.quota),enabled:typeof $.enabled==="boolean"?$.enabled:!1,...typeof $.stateLine==="string"&&{stateLine:$.stateLine},...$.quotaDated===!0&&{quotaDated:!0},needsReauth:typeof $.needsReauth==="boolean"?$.needsReauth:!1,...$.vaultReauth===!0&&{vaultReauth:!0},...$.vaultServed===!0&&{vaultServed:!0},...typeof $.custodyState==="string"&&{custodyState:$.custodyState},tierLabel:typeof $.tierLabel==="string"&&$.tierLabel.trim()?$.tierLabel.trim():void 0})):[],X=null;if(Q(J.relay)){let $=J.relay;if(typeof $.enabled==="boolean"&&typeof $.transport==="string")X={enabled:$.enabled,transport:$.transport}}let G;if(Q(J.cacheKeep)){let $=J.cacheKeep;if(typeof $.enabled==="boolean")G={enabled:$.enabled,window:typeof $.window==="string"?$.window:void 0,trackedSessions:typeof $.trackedSessions==="number"?$.trackedSessions:void 0}}let Y=Array.isArray(J.fableRecoveries)?J.fableRecoveries.filter(Q).flatMap(($)=>{if(typeof $.sessionId!=="string"||$.mode!=="opus"&&$.mode!=="fable"&&$.mode!=="server"||typeof $.remaining!=="number"||!Number.isFinite($.remaining)||typeof $.changedAt!=="number"||!Number.isFinite($.changedAt))return[];return[{sessionId:$.sessionId,mode:$.mode,remaining:Math.max(0,Math.floor($.remaining)),changedAt:$.changedAt,requestedModelId:typeof $.requestedModelId==="string"?$.requestedModelId:void 0,targetModelId:typeof $.targetModelId==="string"?$.targetModelId:void 0}]}):[];return{main:Z,fallbacks:V,activeId:typeof J.activeId==="string"?J.activeId:void 0,route:typeof J.route==="string"?J.route:W.route,relay:X,fastMode:typeof J.fastMode==="boolean"?J.fastMode:W.fastMode,cacheKeep:G,prime:a(J.prime),fableRecoveries:Y.length>0?Y:void 0,lastUpdated:typeof J.lastUpdated==="number"?J.lastUpdated:0}}var H=Promise.resolve(),t=1000,e=2000,JJ=5,ZJ=15,E=new Map;function WJ(J,Z=f()){if(J)E.set(Z,J);else E.delete(Z)}function U(J){return E.get(J)}var k=null;function HJ(J){k=J}function UJ(){return k}function $J(J){return new Promise((Z)=>setTimeout(Z,J))}async function F(J){let Z=`${J}.lock`,V=U(J),X=V?.lockBudgetMs??t,G=V?.lockRetryMinMs??JJ,Y=V?.lockRetryMaxMs??ZJ,$=Date.now()+X;while(!0){try{await h(Z);let K=P(),x=M(Z,K);return await b(x,"",{encoding:"utf8",mode:384,flag:"wx"}),await V?.onLockAcquired?.(Z),{ownsLock:async()=>{try{return await R(x),!0}catch{return!1}},release:async()=>{try{await m(x)}catch{return}await V?.beforeReleaseDirectoryRemoval?.(Z),await w(Z).catch(()=>{})}}}catch(K){if(K.code!=="EEXIST")return z.trace("sidebar","state lock unavailable; write skipped",{stateFile:J,error:K instanceof Error?K.message:String(K)}),null}try{let K=await R(Z);if(Date.now()-K.mtimeMs>e){await V?.afterStaleLockStat?.(Z);let x=`${Z}.evict-${process.pid}-${P()}`;try{await S(Z,x)}catch(O){if(O.code==="ENOENT")continue;throw O}await V?.onStaleLockClaimed?.(Z),await C(x,{recursive:!0,force:!0}).catch(()=>{});continue}}catch(K){if(K.code==="ENOENT")continue;return z.trace("sidebar","state lock inspection failed; write skipped",{stateFile:J,error:K instanceof Error?K.message:String(K)}),null}let j=$-Date.now();if(j<=0)return z.warn("sidebar","lock budget exhausted, write skipped",{stateFile:J,budgetMs:X}),null;let B=G+Math.floor(Math.random()*(Y-G+1));await $J(Math.min(B,j))}}async function qJ(J){return(await F(J))?.release??null}async function VJ(J,Z,V){let X=U(J),G=`${J}.${process.pid}.${P()}.tmp`;await b(G,JSON.stringify(Z),{encoding:"utf8",mode:384});try{if(!await V())return z.trace("sidebar","state lock lost before rename; write aborted",{stateFile:J}),await C(G,{force:!0}).catch(()=>{}),"lock-lost-before-rename";if(await X?.beforeRename?.(J,G),!await V())return z.trace("sidebar","state lock lost before rename; write aborted",{stateFile:J}),await C(G,{force:!0}).catch(()=>{}),"lock-lost-before-rename";if(await S(G,J),await U(J)?.afterRename?.(J),!await V())return"lock-lost-after-rename";return"written"}catch(Y){throw await C(G,{force:!0}).catch(()=>{}),Y}}async function T(J=f()){try{let Z=await y(J,"utf8");return p(JSON.parse(Z))}catch{return W}}async function LJ(J,Z=f(),V={}){return H=H.then(async()=>{await h(v(Z),{recursive:!0});for(let X=0;X<2;X++){let G=X===1,Y=await F(Z);if(!Y){if(G)z.warn("sidebar","post-rename repair lock unavailable; write skipped",{stateFile:Z});return}let $=J,j;try{if(V.routingAuthoritative===!1){let B=await T(Z),K=await V.resolvePreservedRouting?.(B);if(K){let x=K.state??J;$={...x,activeId:K.activeId,route:K.route,lastUpdated:Math.max(x.lastUpdated,B.lastUpdated)}}await U(Z)?.afterMergeRead?.(Z)}else if(G){let B=await T(Z);$={...B,activeId:J.activeId,route:J.route,relay:J.relay,fastMode:J.fastMode,cacheKeep:J.cacheKeep,lastUpdated:Math.max(B.lastUpdated,J.lastUpdated)}}$=p($),j=await VJ(Z,$,Y.ownsLock)}finally{await Y.release()}if(j==="lock-lost-after-rename"){if(G){z.warn("sidebar","post-rename repair lost lock; write skipped",{stateFile:Z});return}z.warn("sidebar","state lock lost after rename; repairing write",{stateFile:Z});continue}if(j==="lock-lost-before-rename")return;V.onRoutingResolved?.({activeId:$.activeId,route:$.route});return}}).catch(()=>{}),H}async function PJ(){return H}function XJ(J){let Z=J.activeId;if(Z&&Z!=="main"){let V=J.fallbacks?.find((X)=>X.enabled&&X.id===Z);if(V)return{id:V.id,name:V.label??V.id,quota:V.quota,...V.stateLine&&{stateLine:V.stateLine,quotaDated:V.quotaDated}}}return{id:"main",name:"main",quota:J.main?.quota??null,...J.main?.stateLine&&{stateLine:J.main.stateLine,quotaDated:J.main.quotaDated}}}function L(J){if(J==="claude-mythos-5-1"||J?.startsWith("claude-mythos-5-1-"))return"Mythos 5.1";if(J==="claude-fable-5-1"||J?.startsWith("claude-fable-5-1-"))return"Fable 5.1";if(J==="claude-fable-5"||J?.startsWith("claude-fable-5-"))return"Fable 5";if(J==="claude-opus-5-5"||J?.startsWith("claude-opus-5-5-"))return"Opus 5.5";if(J==="claude-opus-5"||J?.startsWith("claude-opus-5-"))return"Opus 5";if(J==="claude-opus-4-8"||J?.startsWith("claude-opus-4-8-"))return"Opus 4.8";return J??"Fable 5"}function g(J){return new Date(J).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function YJ(J){if(J===0)return"0";if(J<0.0001)return J.toExponential(2);return J.toFixed(Math.min(6,Math.max(0,4)))}function EJ(J,Z=Date.now()){if(J.lastResult==="error")return{text:"err",hasError:!0};if(J.lastResult==="skipped")return{text:"skip",hasError:!1};if(J.nextDueAt&&J.nextDueAt>Z)return{text:g(J.nextDueAt),hasError:!1};if(J.lastPrimedAt)return{text:`primed ${g(J.lastPrimedAt)} ✓`,hasError:!1};if(J.usage?.count)return{text:`✓ ${J.usage.count} ≈ $${YJ(J.estimatedCostUsd??0)}`,hasError:!1};return{text:"—",hasError:!1}}function MJ(J,Z){let V=J.fableRecoveries?.find((X)=>X.sessionId===Z);if(!V)return;if(V.mode==="fable")return`${L(V.requestedModelId)} · restored`;if(V.mode==="server")return`${L(V.requestedModelId)}→${L(V.targetModelId)} · safety`;return`Opus 4.8 · ${V.remaining} left`}function fJ(J,Z=10){if(Z<=0)return"";let V=J;if(Bun.stringWidth(V)>Z){V="";for(let X of J){if(Bun.stringWidth(V+X)>Z-1)break;V+=X}V+="…"}return V+" ".repeat(Math.max(0,Z-Bun.stringWidth(V)))}function GJ(J,Z=Date.now()){let V=J?.scoped??[];return V.map((X,G)=>{let Y=I({scoped:V.map((B,K)=>({...B,usedPercent:K===G?100:0,remainingPercent:K===G?0:100,checkedAt:Z}))},Z),$=u(Y,{now:Z,form:"narrow"})[0],j=$?.replace(/ 0% left$/,"");return j&&j!==$?j:X.title})}function _J(J,Z=Date.now()){return Math.max(2,...J.flatMap((V)=>GJ(V,Z).map((X)=>Bun.stringWidth(X))))}var KJ=3;function RJ(J){let{width:Z,labelWidth:V,barWidth:X,figure:G,reset:Y}=J,$={barCells:X,reset:Y||void 0};if(Z===void 0)return $;let j=(x)=>V+1+(x.barCells>0?x.barCells+1:0)+Bun.stringWidth(G)+(x.reset?1+Bun.stringWidth(x.reset):0),B=Math.min(KJ,X),K=[$];for(let x=X;x>=B;x--)K.push({barCells:x});return K.find((x)=>j(x)<=Z)??{barCells:B}}function DJ(J,Z,V){if(!J||J.state==="on-pace")return null;let X=`${J.state} ${Math.round(Math.abs(J.deltaPercent))}%`,G=V?`${X} · out in ${V}`:`${X} · lasts to reset`;if(Z===void 0||Bun.stringWidth(G)<=Z)return G;if(Z<=0)return"";let Y="";for(let $ of G){if(Bun.stringWidth(Y+$)>Z-1)break;Y+=$}return`${Y.trimEnd()}…`}function AJ(J,Z=Date.now()){let V=J?.five_hour?.usedPercent??null,X=J?.seven_day?.usedPercent??null,G=J?.scoped??[],Y=G.map((j)=>j.usedPercent);if(!J||V==null&&X==null&&G.length===0&&!J.extraUsage)return{fiveHourUsedPercent:V,sevenDayUsedPercent:X,scopedUsedPercents:Y,text:null,stale:!1};let $=I(J,Z);return{fiveHourUsedPercent:V,sevenDayUsedPercent:X,scopedUsedPercents:Y,text:c($,{now:Z,form:"narrow"}),stale:s($,{now:Z})}}function TJ(J,Z=!0){let V=J.activeId===void 0?void 0:XJ(J).id;return[{id:"main",name:"main",quota:J.main?.quota??null,quotaDated:J.main?.quotaDated,active:V==="main"},...Z?(J.fallbacks??[]).filter((X)=>X.enabled||X.custodyState&&X.custodyState!=="off").map((X)=>({id:X.id,name:X.label??X.id,quota:X.quota,quotaDated:X.quotaDated,active:V===X.id})):[]]}var gJ=18000000,hJ=604800000,xJ=300000,jJ=0.01,BJ=1;function SJ(J,Z,V){if(!J.resetsAt)return null;let X=new Date(J.resetsAt).getTime();if(!Number.isFinite(X))return null;let G=X-Z,Y=V-G;if(Y<xJ)return null;if(Y<Z*jJ)return null;if(Y>=Z)return null;let $=J.usedPercent,j=Math.min(Math.max(Y/Z*100,0),100),B=$-j,K=Math.abs(B)<BJ?"on-pace":B>0?"deficit":"reserve",x=null;if($>0){let O=Y*100/$,_=G+O;if(_<X)x=new Date(_).toISOString()}return{pacePercent:j,deltaPercent:B,state:K,runsOutAt:x}}
|
|
2
|
+
export{f as G,W as H,p as I,WJ as J,HJ as K,UJ as L,qJ as M,T as N,LJ as O,PJ as P,XJ as Q,L as R,g as S,YJ as T,EJ as U,MJ as V,fJ as W,GJ as X,_J as Y,KJ as Z,RJ as _,DJ as $,AJ as aa,TJ as ba,gJ as ca,hJ as da,SJ as ea};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{p as a}from"./index-
|
|
1
|
+
import{p as a}from"./index-8ysjtqek.js";import"./index-6chd6jnr.js";import"./index-hazrk5c3.js";import"./index-b1dvkp15.js";import"./index-xbwa4x53.js";import"./index-ppdrzs41.js";import"./index-62x1p34p.js";export{a as AnthropicAuthPlugin};
|
package/dist/rpc/port-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{fa as a,ga as b}from"../index-ppdrzs41.js";import"../index-62x1p34p.js";export{a as writePortFile,b as discoverPortFile};
|
package/dist/rpc/protocol.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{q as a}from"../index-6chd6jnr.js";import"../index-
|
|
1
|
+
import{q as a}from"../index-6chd6jnr.js";import"../index-62x1p34p.js";export{a as COMMAND_MODAL_NAMES};
|
package/dist/rpc/rpc-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ga as s}from"../index-ppdrzs41.js";import"../index-62x1p34p.js";async function i(e,o,t,n){let r=await s(e,n);if(!r)return null;let a=new AbortController,l=setTimeout(()=>a.abort(),2000);try{let p=await fetch(`http://127.0.0.1:${r.port}/rpc/${o}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r.token}`},body:JSON.stringify(t),signal:a.signal});if(!p.ok)return null;return await p.json()}catch{return null}finally{clearTimeout(l)}}function c(e,o){return{async pending(t,n){return(await i(e,"pending-notifications",{lastReceivedId:t,sessionId:n},o))?.messages??[]},async apply(t){return await i(e,"apply",{...t},o)??{text:"apply failed",knobs:{}}},async applyMenu(t){if(t.command!=="claude"||!t.sessionId?.trim())throw TypeError("A claude menu sessionId is required");let n=await i(e,"apply-menu",{...t},o);if(!n)throw Error("Menu apply unavailable; outcome unknown");return n}}}export{c as createRpcClient};
|
package/dist/rpc/rpc-dir.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as a,s as b}from"../index-hazrk5c3.js";import"../index-
|
|
1
|
+
import{r as a,s as b}from"../index-hazrk5c3.js";import"../index-62x1p34p.js";export{a as tmpdir,b as getRpcDir};
|
package/dist/sidebar-state.d.ts
CHANGED
|
@@ -165,6 +165,59 @@ export declare function formatPrimeAccountValue(account: PrimeSidebarAccountStat
|
|
|
165
165
|
export declare function getFableRecoverySummary(state: SidebarState, sessionId: string): string | undefined;
|
|
166
166
|
/** Keep full shared names when they fit; truncate only to preserve row columns. */
|
|
167
167
|
export declare function formatQuotaRowLabel(name: string, width?: number): string;
|
|
168
|
+
/**
|
|
169
|
+
* The short names model-scoped rows read under, in the order of `quota.scoped`:
|
|
170
|
+
* the names common-auth's narrow one-line form gives them (`Fa` for Fable;
|
|
171
|
+
* models whose short names would collide are extended until they differ, as
|
|
172
|
+
* `Fabl` and `Fabr`), so the expanded rows and the collapsed line agree.
|
|
173
|
+
*
|
|
174
|
+
* common-auth exposes that short name only inside the narrow text, and the
|
|
175
|
+
* narrow line shows just one model window (the tightest). So each window's
|
|
176
|
+
* name is read from a narrow line of a copy of the reading in which that
|
|
177
|
+
* window alone is spent: every model window stays in, so collisions resolve
|
|
178
|
+
* exactly as they do in the real line, and the one piece the line shows is
|
|
179
|
+
* `<short name> 0% left`. The figures in the copy are never displayed.
|
|
180
|
+
*/
|
|
181
|
+
export declare function scopedQuotaShortNames(quota: Pick<AccountQuota, 'scoped'> | null | undefined, now?: number): string[];
|
|
182
|
+
/**
|
|
183
|
+
* The width of the quota rows' label column: the longest label any of these
|
|
184
|
+
* accounts shows. `5h` and `7d` always show, so it is at least 2.
|
|
185
|
+
*/
|
|
186
|
+
export declare function quotaLabelColumnWidth(quotas: readonly (AccountQuota | null | undefined)[], now?: number): number;
|
|
187
|
+
/** The narrowest a quota row's bar shrinks to. */
|
|
188
|
+
export declare const QUOTA_BAR_MIN_CELLS = 3;
|
|
189
|
+
export interface QuotaRowFit {
|
|
190
|
+
/** Bar cells to draw. */
|
|
191
|
+
barCells: number;
|
|
192
|
+
/** The reset text to draw at the right edge, or undefined for none. */
|
|
193
|
+
reset?: string;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Fits one quota row into `width` cells. The row reads `label bar figure` on
|
|
197
|
+
* the left and the reset at the right edge, with a one-cell gap before the
|
|
198
|
+
* reset that the caller always draws. When the full row is too wide, the
|
|
199
|
+
* reset is dropped first, so the figure (the percent left) is never cut to
|
|
200
|
+
* keep it; then the bar shrinks, down to `QUOTA_BAR_MIN_CELLS`. A row still
|
|
201
|
+
* too wide at that point keeps the minimum bar and is cut at the right edge
|
|
202
|
+
* by the caller's no-wrap text, which cuts the figure's end. Without a
|
|
203
|
+
* measured width the full row is used.
|
|
204
|
+
*/
|
|
205
|
+
export declare function fitQuotaRow(input: {
|
|
206
|
+
width: number | undefined;
|
|
207
|
+
labelWidth: number;
|
|
208
|
+
barWidth: number;
|
|
209
|
+
/** The figure with any binding marker, such as `97% left •`. */
|
|
210
|
+
figure: string;
|
|
211
|
+
reset?: string;
|
|
212
|
+
}): QuotaRowFit;
|
|
213
|
+
/**
|
|
214
|
+
* The pacing subline for a window that is off pace: `deficit 12% · out in
|
|
215
|
+
* 1d23h` for a deficit that runs out before the reset, otherwise the delta
|
|
216
|
+
* and `lasts to reset` (`reserve 4% · lasts to reset`). When it is wider than
|
|
217
|
+
* `width` cells it is cut to fit and ends in `…` rather than wrapping. Null
|
|
218
|
+
* when there is no pacing or the window is on pace.
|
|
219
|
+
*/
|
|
220
|
+
export declare function fitPaceLine(pacing: QuotaPacing | null, width: number | undefined, runsOutIn: string | undefined): string | null;
|
|
168
221
|
export declare function getCollapsedQuotaSummary(quota: AccountQuota | null, now?: number): {
|
|
169
222
|
fiveHourUsedPercent: number | null;
|
|
170
223
|
sevenDayUsedPercent: number | null;
|
package/dist/sidebar-state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as v,G as a,H as b,I as c,J as d,K as e,L as f,M as g,N as h,O as i,P as j,Q as k,R as l,S as m,T as n,U as o,V as p,W as q,X as r,Y as s,Z as t,_ as u}from"./index-
|
|
1
|
+
import{$ as v,G as a,H as b,I as c,J as d,K as e,L as f,M as g,N as h,O as i,P as j,Q as k,R as l,S as m,T as n,U as o,V as p,W as q,X as r,Y as s,Z as t,_ as u,aa as w,ba as x,ca as y,da as z,ea as A}from"./index-xbwa4x53.js";import"./index-62x1p34p.js";export{i as setSidebarState,r as scopedQuotaShortNames,k as resolveActiveAccount,s as quotaLabelColumnWidth,c as normalizeSidebarState,a as getSidebarStateFile,h as getSidebarState,f as getInitialSidebarRoutingTestHooks,p as getFableRecoverySummary,w as getCollapsedQuotaSummary,x as getCollapsedAccounts,q as formatQuotaRowLabel,m as formatPrimeTime,n as formatPrimeCost,o as formatPrimeAccountValue,l as formatFallbackModelLabel,u as fitQuotaRow,v as fitPaceLine,j as drainSidebarWrites,A as computeQuotaPacing,d as __setSidebarStateWriteTestHooks,e as __setInitialSidebarRoutingTestHooks,g as __acquireSidebarStateLockForTest,z as SEVEN_DAY_MS,t as QUOTA_BAR_MIN_CELLS,y as FIVE_HOUR_MS,b as DEFAULT_SIDEBAR_STATE};
|
|
@@ -27,6 +27,11 @@ export declare function AccountBlock(props: {
|
|
|
27
27
|
stateLine?: string;
|
|
28
28
|
quotaDated?: boolean;
|
|
29
29
|
tierLabel?: string;
|
|
30
|
+
/**
|
|
31
|
+
* The quota rows' label column width, shared across the sidebar's accounts
|
|
32
|
+
* so their bars line up; defaults to this account's own longest label.
|
|
33
|
+
*/
|
|
34
|
+
labelWidth?: number;
|
|
30
35
|
marginTop?: number;
|
|
31
36
|
now: number;
|
|
32
37
|
}): any;
|
package/dist/tui-preferences.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./index-
|
|
1
|
+
import"./index-62x1p34p.js";import{readFileSync as k,watch as C}from"node:fs";import{mkdir as _,readFile as I,rename as E,writeFile as b}from"node:fs/promises";import{homedir as g}from"node:os";import{basename as F,dirname as P,join as N}from"node:path";import{clearTimeout as D,setTimeout as L}from"node:timers";import{applyEdits as T,modify as y,parse as f}from"jsonc-parser";var v="OPENCODE_TUI_PREFERENCES_FILE",h="tui-preferences.jsonc";function A(){let J=process.env[v];if(J)return J;let z=process.env.OPENCODE_CONFIG_DIR||N(process.env.XDG_CONFIG_HOME||N(g(),".config"),"opencode");return N(z,h)}function H(J){return typeof J==="object"&&J!==null&&!Array.isArray(J)}async function qq(){try{let J=await I(A(),"utf8"),z=[],q=f(J,z,{allowTrailingComma:!0});if(z.length>0)return{};return H(q)?q:{}}catch{return{}}}var m="anthropic-auth",p=160,R={forceToTop:!1,order:p,startCollapsed:!1,rememberCollapsed:!0,collapsed:null,pollMs:1500,refreshDebounceMs:200,header:{label:"CLAUDE",showVersion:!0},sections:{quota:!0,fallbackAccounts:!0,routing:!0,cache:!0,health:!0,pacing:!0},appearance:{barWidth:10,barFilledChar:"█",barEmptyChar:"░",warnThreshold:50,errorThreshold:80}};function $(J,z){return typeof J==="boolean"?J:z}function Y(J,z,q,X){if(typeof J!=="number"||!Number.isFinite(J))return z;return Math.min(Math.max(Math.round(J),q),X)}function c(J,z,q){if(typeof J!=="string"||J.length===0)return z;return J.slice(0,q)}function w(J,z){if(typeof J!=="string")return z;return[...J][0]??z}function zq(J){let z=J[m];if(!H(z))return structuredClone(R);let q=R,X=H(z.header)?z.header:{},Q=H(z.sections)?z.sections:{},Z=H(z.appearance)?z.appearance:{},G=Y(Z.warnThreshold,q.appearance.warnThreshold,0,99),V=Math.max(Y(Z.errorThreshold,q.appearance.errorThreshold,0,100),Math.min(G+1,100));return{forceToTop:$(z.forceToTop,q.forceToTop),order:Y(z.order,q.order,-1e4,1e4),startCollapsed:$(z.startCollapsed,q.startCollapsed),rememberCollapsed:$(z.rememberCollapsed,q.rememberCollapsed),collapsed:typeof z.collapsed==="boolean"?z.collapsed:null,pollMs:Y(z.pollMs,q.pollMs,500,30000),refreshDebounceMs:Y(z.refreshDebounceMs,q.refreshDebounceMs,50,5000),header:{label:c(X.label,q.header.label,20),showVersion:$(X.showVersion,q.header.showVersion)},sections:{quota:$(Q.quota,q.sections.quota),fallbackAccounts:$(Q.fallbackAccounts,q.sections.fallbackAccounts),routing:$(Q.routing,q.sections.routing),cache:$(Q.cache,q.sections.cache),health:$(Q.health,q.sections.health),pacing:$(Q.pacing,q.sections.pacing)},appearance:{barWidth:Y(Z.barWidth,q.appearance.barWidth,4,40),barFilledChar:w(Z.barFilledChar,q.appearance.barFilledChar),barEmptyChar:w(Z.barEmptyChar,q.appearance.barEmptyChar),warnThreshold:G,errorThreshold:V}}}var u=-1e5;function Jq(J,z,q){let X=J[z];if(!H(X))return q;if(X.forceToTop===!0)return u+Object.keys(J).indexOf(z);return Y(X.order,q,-1e4,1e4)}var s=`// Shared preferences for opencode TUI plugins.
|
|
2
2
|
// One top-level key per plugin (short name). See each plugin's README for
|
|
3
3
|
// its supported settings. This file is safe to hand-edit; plugins update
|
|
4
4
|
// individual keys in place and preserve comments.
|