@cortexkit/opencode-anthropic-auth 1.23.0 → 2.0.0

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.
Files changed (82) hide show
  1. package/README.md +239 -195
  2. package/dist/cli-failure.d.ts +69 -0
  3. package/dist/cli.d.ts +14 -9
  4. package/dist/cli.js +98 -76
  5. package/dist/custody-dimensions.d.ts +7 -24
  6. package/dist/custody-mode.d.ts +29 -169
  7. package/dist/effort-history.d.ts +6 -1
  8. package/dist/index-1jkyhgyr.js +2 -0
  9. package/dist/{index-8y2t4mwz.js → index-2arfb1y3.js} +1 -1
  10. package/dist/{index-0jfsxyn9.js → index-4ya27n12.js} +1 -1
  11. package/dist/index-aaajxwzd.js +2 -0
  12. package/dist/index-ae3fq4n6.js +42 -0
  13. package/dist/{index-xzbhzz0a.js → index-fds0s2j4.js} +2 -2
  14. package/dist/index-nngmvczq.js +450 -0
  15. package/dist/index-pn597b6f.js +2 -0
  16. package/dist/{index-1gr8v4fn.js → index-rqync0pc.js} +1 -1
  17. package/dist/index.js +1 -38
  18. package/dist/native-command.d.ts +19 -0
  19. package/dist/rpc/notifications.d.ts +2 -1
  20. package/dist/rpc/port-file.js +1 -1
  21. package/dist/rpc/protocol.d.ts +8 -4
  22. package/dist/rpc/protocol.js +1 -1
  23. package/dist/rpc/rpc-client.d.ts +2 -0
  24. package/dist/rpc/rpc-client.js +1 -1
  25. package/dist/rpc/rpc-dir.js +1 -1
  26. package/dist/rpc/rpc-server.d.ts +5 -1
  27. package/dist/setup/command.d.ts +12 -0
  28. package/dist/setup/command.test.d.ts +1 -0
  29. package/dist/setup/native-activation.d.ts +29 -0
  30. package/dist/setup/native-enrollment.d.ts +26 -0
  31. package/dist/setup/native-enrollment.test.d.ts +1 -0
  32. package/dist/setup/native-local.d.ts +20 -0
  33. package/dist/setup/native-login.d.ts +3 -0
  34. package/dist/setup/native-paths.d.ts +15 -0
  35. package/dist/setup/native-paths.test.d.ts +1 -0
  36. package/dist/setup/pi.d.ts +13 -3
  37. package/dist/setup/process-fence.d.ts +7 -1
  38. package/dist/setup/process-fence.test.d.ts +1 -0
  39. package/dist/sidebar-state.js +1 -1
  40. package/dist/tui/command-dialogs.d.ts +5 -0
  41. package/dist/tui-preferences.js +2 -2
  42. package/dist/v2/activation.d.ts +7 -0
  43. package/dist/v2/adapter.d.ts +276 -0
  44. package/dist/v2/install.d.ts +13 -0
  45. package/dist/v2/lifecycle.d.ts +8 -0
  46. package/dist/v2/menu-contract.d.ts +8 -0
  47. package/dist/v2/menu.d.ts +10 -0
  48. package/dist/v2/models.d.ts +6 -0
  49. package/dist/v2/ownership.d.ts +11 -0
  50. package/dist/v2/prime.d.ts +12 -0
  51. package/dist/v2/rpc.d.ts +50 -0
  52. package/dist/v2/server.d.ts +8 -0
  53. package/dist/v2/server.js +4 -0
  54. package/dist/v2/setup.d.ts +58 -0
  55. package/dist/v2/source.d.ts +41 -0
  56. package/dist/v2/tui.d.ts +13 -0
  57. package/dist/v2/tui.js +2 -0
  58. package/dist/v2/wire.d.ts +36 -0
  59. package/package.json +20 -5
  60. package/src/rpc/notifications.ts +9 -2
  61. package/src/rpc/protocol.ts +8 -7
  62. package/src/rpc/rpc-client.ts +17 -0
  63. package/src/rpc/rpc-server.ts +20 -3
  64. package/src/tui/command-dialogs.tsx +264 -0
  65. package/src/tui/entry.mjs +44 -18
  66. package/src/tui-compiled/rpc/protocol.ts +8 -7
  67. package/src/tui-compiled/rpc/rpc-client.ts +17 -0
  68. package/src/tui-compiled/tui/command-dialogs.tsx +315 -76
  69. package/src/tui-compiled/tui.tsx +24 -7
  70. package/src/tui.tsx +37 -9
  71. package/dist/claustrum-enrollment-registry.d.ts +0 -4
  72. package/dist/custody-enrollment.d.ts +0 -14
  73. package/dist/custody-live.d.ts +0 -111
  74. package/dist/custody-manifest-watcher.d.ts +0 -16
  75. package/dist/index-1fq7h6yd.js +0 -430
  76. package/dist/index-797pmamn.js +0 -2
  77. package/dist/index-a5d6v3ba.js +0 -5
  78. package/dist/index-n96q8pks.js +0 -2
  79. package/dist/index-xxhyhp98.js +0 -2
  80. package/dist/index-z7gfdyv3.js +0 -1
  81. package/dist/local-login.d.ts +0 -64
  82. package/dist/logger-kk9vyem9.js +0 -1
@@ -1,430 +0,0 @@
1
- import{Bg as Q6,Cg as $5,Dg as b2,Eg as E2,Fg as i3,Gg as v2,Hg as Z5,Ig as J5,Lg as J8,Rg as n5,Sg as a5,Tg as D1,Ug as J4,Vg as X8,Wg as G8,Xg as Y8,Yg as N5,Zg as R$,gh as V8,kh as P,lh as w0,mh as l}from"./index-a5d6v3ba.js";import{vh as VJ,wh as U5,xh as L5}from"./index-n96q8pks.js";import{createHash as x5,randomUUID as J1}from"node:crypto";import{mkdir as s2,readFile as B6,rename as O5,rm as m1,stat as G5,writeFile as q6}from"node:fs/promises";import{homedir as QJ}from"node:os";import{dirname as n2,join as p1,resolve as jJ}from"node:path";import{randomUUID as m3}from"node:crypto";import{constants as W0,readdirSync as FZ,statSync as AZ}from"node:fs";import*as T from"node:fs/promises";import{homedir as wZ,tmpdir as TZ,userInfo as v1}from"node:os";import{basename as SZ,dirname as K6,isAbsolute as IZ,join as M0}from"node:path";import{debuglog as r7}from"node:util";import{createHmac as i7,randomBytes as c7,timingSafeEqual as s7}from"node:crypto";import d7 from"node:net";var D0=2,i$=21,c$=5,j2=67108864,C;(function($){$[$.Request=0]="Request",$[$.Response=1]="Response",$[$.Push=2]="Push",$[$.StreamData=3]="StreamData",$[$.StreamEnd=4]="StreamEnd",$[$.Error=5]="Error",$[$.Cancel=6]="Cancel",$[$.Ping=7]="Ping",$[$.Pong=8]="Pong",$[$.Hello=9]="Hello",$[$.HelloAck=10]="HelloAck",$[$.Goodbye=11]="Goodbye"})(C||(C={}));var j3=C.Goodbye;function H3($){return $===C.Cancel||$===C.Ping||$===C.Pong||$===C.Goodbye}var r;(function($){$[$.Passive=0]="Passive",$[$.Interactive=1]="Interactive",$[$.Background=2]="Background"})(r||(r={}));var G0;(function($){$[$.Normal=0]="Normal",$[$.Expedite=1]="Expedite",$[$.Sheddable=2]="Sheddable"})(G0||(G0={}));var B3=1,q3=6,H2=1,u7=8,U3=48,B2=4;var L3=128;function B0($,Z,J,X=G0.Normal){let G=0;if($)G|=B3;if(G|=Z<<H2,J)G|=u7;return G|=X<<B2,G}function q2($){return($&B3)!==0}function N3($){let Z=new Uint8Array(21),J=new DataView(Z.buffer);return J.setUint32(0,$.len,!0),Z[4]=$.ver,Z[5]=$.ty,Z[6]=$.flags,J.setUint16(7,$.channel,!0),J.setUint32(9,$.epoch,!0),J.setBigUint64(13,$.corr,!0),Z}class h extends Error{code;constructor($,Z){super($);this.code=Z,this.name="DecodeError"}}function l7($){let Z=$.len>>>0,J=$.ver>>>0&255,X=$.ty>>>0&255,G=$.flags>>>0&255,Y=$.channel>>>0&65535,z=$.epoch>>>0;if(BigInt.asUintN(64,$.corr),J!==2)throw new h(`unsupported envelope version ${J}`,"unsupported_version");if(X>j3)throw new h(`unknown frame type byte ${X}`,"unknown_frame_type");let K=X;if((G&L3)!==0)throw new h(`reserved flag bits set in flags 0b${G.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((G&q3)>>H2===3)throw new h(`reserved priority bits set in flags 0b${G.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let W=(G&U3)>>B2;if(W===3)throw new h(`reserved admission class set in flags 0b${G.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(W===G0.Sheddable&&K!==C.Push&&K!==C.StreamData)throw new h(`SHEDDABLE admission class is illegal on ${C[K]} in flags 0b${G.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");if(Y===0&&z!==0)throw new h(`control channel carried nonzero epoch ${z}`,"nonzero_epoch_on_control_channel");if(H3(K)&&Z!==0)throw new h(`pure-header frame ${C[K]} declared non-zero body length ${Z}`,"pure_header_frame_with_body")}function U2($){if($.length<5)throw new h(`header shorter than frozen prefix: have ${$.length} bytes`,"too_short_for_prefix");let Z=$[4];if(Z!==2)throw new h(`unsupported envelope version ${Z}`,"unsupported_version");if($.length<21)throw new h(`header too short for version: have ${$.length} bytes, need 21`,"too_short_for_header");let J=new DataView($.buffer,$.byteOffset,$.byteLength),X=J.getUint32(0,!0),G=$[5];if(G>j3)throw new h(`unknown frame type byte ${G}`,"unknown_frame_type");let Y=G,z=$[6];if((z&L3)!==0)throw new h(`reserved flag bits set in flags 0b${z.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((z&q3)>>H2===3)throw new h(`reserved priority bits set in flags 0b${z.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let K=(z&U3)>>B2;if(K===3)throw new h(`reserved admission class set in flags 0b${z.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(K===G0.Sheddable&&Y!==C.Push&&Y!==C.StreamData)throw new h(`SHEDDABLE admission class is illegal on ${C[Y]} in flags 0b${z.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");let W=J.getUint16(7,!0),Q=J.getUint32(9,!0);if(W===0&&Q!==0)throw new h(`control channel carried nonzero epoch ${Q}`,"nonzero_epoch_on_control_channel");if(H3(Y)&&X!==0)throw new h(`pure-header frame ${C[Y]} declared non-zero body length ${X}`,"pure_header_frame_with_body");return{len:X,ver:Z,ty:Y,flags:z,channel:W,epoch:Q,corr:J.getBigUint64(13,!0)}}function z0($,Z,J,X,G,Y){return b0(2,$,Z,J,X,G,Y)}function b0($,Z,J,X,G,Y,z){if(z.length>67108864)throw new h(`frame body ${z.length} exceeds max 67108864`,"frame_body_too_large");let K={len:z.length,ver:$,ty:Z,flags:J,channel:X,epoch:G,corr:Y};return l7(K),{header:K,body:z}}function k0($){if($.header.len!==$.body.length)throw new h(`frame header length ${$.header.len} does not match body length ${$.body.length}`,"frame_length_mismatch");let Z=N3($.header),J=new Uint8Array(Z.length+$.body.length);return J.set(Z,0),J.set($.body,Z.length),J}class c0 extends Error{}class P0 extends Error{}class E0 extends Error{cause;constructor($,Z){super($);this.cause=Z}}class e0 extends Error{cause;constructor($,Z){super($);this.cause=Z}}function x3($){return Buffer.from($.buffer,$.byteOffset,$.byteLength)}var O3=Symbol("subc.socket.writeBorrowed"),D3=Symbol("subc.socket.writeTrackedBorrowed");function v0($,Z,J){let X=$[O3];return X?X.call($,Z,J):$.write(Z,J)}function L2($,Z,J){let X=$[D3];return X?X.call($,Z,J):$.writeTracked(Z,J)}class H1{sock;chunks=[];buffered=0;waiter=null;closedErr=null;bufferedBytes(){return this.buffered}constructor($){this.sock=$,$.on("data",(J)=>{this.chunks.push(J),this.buffered+=J.length,this.tryServe()});let Z=(J)=>{if(!this.closedErr)this.closedErr=J;this.tryServe()};$.on("error",(J)=>Z(J instanceof Error?J:Error(String(J)))),$.on("end",()=>Z(new c0("subc closed the connection"))),$.on("close",()=>Z(new c0("subc connection closed")))}localPort(){return this.sock.localPort??null}static connect($,Z,J){return new Promise((X,G)=>{let Y=d7.connect({host:$,port:Z});Y.setNoDelay(!0);let z=setTimeout(()=>{Y.destroy(),G(new P0(`timed out connecting to ${$}:${Z}`))},Math.max(0,J-Date.now()));Y.once("connect",()=>{clearTimeout(z),X(new H1(Y))}),Y.once("error",(K)=>{clearTimeout(z),G(K)})})}async readFrame($,Z,J){let X=await this.readExact(c$,$),G=X[4];if(G!==D0)throw new h(`unsupported envelope version ${G}`,"unsupported_version");let Y=await this.readExact(i$-c$,$),z=new Uint8Array(i$);z.set(X),z.set(Y,c$);let K=U2(z);if(K.len>j2)throw new h(`frame body ${K.len} exceeds max ${j2}`,"frame_body_too_large");J?.();let W=typeof Z==="number"?Z:Date.now()+Z.afterHeaderMs,Q=K.len===0?new Uint8Array(0):await this.readExact(K.len,W);return{header:K,body:Q}}readExact($,Z){if(this.waiter)return Promise.reject(Error("concurrent readExact is not supported"));if($===0)return Promise.resolve(new Uint8Array(0));return new Promise((J,X)=>{let G=null;if(Number.isFinite(Z)){let Y=Z-Date.now();if(Y<=0){X(new P0(`timed out waiting for ${$} bytes`));return}G=setTimeout(()=>{this.waiter=null,X(new P0(`timed out waiting for ${$} bytes`))},Y)}this.waiter={need:$,resolve:J,reject:X,timer:G},this.tryServe()})}async write($,Z){await this.writeBuffer(Buffer.from($),Z)}writeTracked($,Z){return this.writeTrackedBuffer(Buffer.from($),Z)}async[O3]($,Z){await this.writeBuffer(x3($),Z)}[D3]($,Z){return this.writeTrackedBuffer(x3($),Z)}async writeBuffer($,Z){try{await this.writeTrackedBuffer($,Z).completed}catch(J){if(J instanceof E0||J instanceof e0)throw J.cause??J;throw J}}writeTrackedBuffer($,Z){if(this.closedErr)return{queued:!1,completed:Promise.reject(new E0("subc socket was closed before bytes could be queued",this.closedErr))};let J=!1,X=!1,G=null,Y=new Promise((z,K)=>{let W=(V)=>{if(X)return;if(X=!0,G)clearTimeout(G);V()},Q=Z-Date.now();if(Q<=0){W(()=>K(new E0("timed out before bytes could be queued to subc",new P0("timed out writing to subc"))));return}G=setTimeout(()=>{let V=new P0("timed out writing to subc");W(()=>K(J?new e0("timed out after bytes were handed to the subc socket",V):new E0("timed out before bytes could be queued to subc",V)))},Q);try{this.sock.write($,(V)=>{W(()=>{if(V)K(new e0("subc socket reported a write error after bytes were handed to the socket",V instanceof Error?V:Error(String(V))));else z()})}),J=!0}catch(V){W(()=>K(new E0("subc socket write threw before bytes could be queued",V instanceof Error?V:Error(String(V)))))}});return{queued:J,completed:Y}}close(){this.sock.destroy()}tryServe(){let $=this.waiter;if(!$)return;if(this.buffered>=$.need){let Z=this.take($.need);if(this.waiter=null,$.timer)clearTimeout($.timer);$.resolve(Z);return}if(this.closedErr){if(this.waiter=null,$.timer)clearTimeout($.timer);$.reject(this.closedErr)}}take($){let Z=Buffer.allocUnsafe($),J=0;while(J<$){let X=this.chunks[0],G=$-J;if(X.length<=G)X.copy(Z,J),J+=X.length,this.chunks.shift();else X.copy(Z,J,0,G),this.chunks[0]=X.subarray(G),J+=G}return this.buffered-=$,Z}}var C3=32;var s$=4096,R3="subc-server-v1",P3="subc-client-v1",n7="client";class K0 extends Error{}function x2($,Z,J,X,G){let Y=i7("sha256",Buffer.from($));return Y.update(Buffer.from(Z,"utf8")),Y.update(Buffer.from(J)),Y.update(Buffer.from(X)),Y.update(Buffer.from(G)),new Uint8Array(Y.digest())}function M3($,Z){if($.length!==Z.length)return!1;return s7(Buffer.from($),Buffer.from(Z))}async function _3($,Z,J){let X=Buffer.from(JSON.stringify(Z),"utf8");if(X.length>s$)throw new K0(`auth message too large: ${X.length} > ${s$}`);let G=new Uint8Array(4);new DataView(G.buffer).setUint32(0,X.length,!0),await v0($,G,J),await v0($,X,J)}async function a7($,Z){let J=await $.readExact(4,Z),X=new DataView(J.buffer,J.byteOffset,4).getUint32(0,!0);if(X>s$)throw new K0(`auth message too large: ${X} > ${s$}`);let G=X===0?new Uint8Array(0):await $.readExact(X,Z);try{return JSON.parse(Buffer.from(G).toString("utf8"))}catch(Y){throw new K0(`auth message JSON decode failed: ${String(Y)}`)}}function N2($,Z){if(!Array.isArray($))throw new K0(`auth field '${Z}' must be a byte array`);for(let J of $)if(typeof J!=="number"||!Number.isInteger(J)||J<0||J>255)throw new K0(`auth field '${Z}' has invalid byte ${String(J)}`);return Uint8Array.from($)}async function W$($,Z,J){let X=new Uint8Array(c7(C3));await _3($,{client_nonce:Array.from(X),role:n7},J);let G=await a7($,J),Y=N2(G.server_nonce,"server_nonce"),z=N2(G.daemon_id,"daemon_id"),K=N2(G.server_proof,"server_proof"),W=x2(Z.key,R3,X,Y,z);if(!M3(W,K))throw new K0("server proof mismatch — wrong key or impostor daemon");if(!M3(z,Z.daemonId))throw new K0("daemon id mismatch — connection file points at a different daemon");let Q=x2(Z.key,P3,X,Y,z);await _3($,{client_auth:Array.from(Q)},J)}import{promises as O2}from"node:fs";var F3=1,A3=32,w3=16;class e extends Error{}function T3($,Z){if(!Array.isArray($))throw new e(`connection file field '${Z}' must be a JSON array of bytes`);for(let J of $)if(typeof J!=="number"||!Number.isInteger(J)||J<0||J>255)throw new e(`connection file field '${Z}' has invalid byte ${String(J)}`);return Uint8Array.from($)}function t7($){if($.schema!==F3)throw new e(`unsupported connection file schema ${$.schema}; expected ${F3}`);if($.endpoints.length===0)throw new e("connection file must include at least one endpoint");if($.key.length<A3)throw new e(`connection file key is too short: ${$.key.length} bytes, need at least ${A3}`);if($.daemonId.length!==w3)throw new e(`connection file daemon_id must be ${w3} bytes, got ${$.daemonId.length}`)}async function o7($){if(process.platform==="win32")return;let J=(await O2.stat($)).mode&511;if((J&63)!==0)throw new e(`connection file ${$} has insecure permissions 0o${J.toString(8)}; expected owner-only 0600`)}async function V$($){await o7($);let Z=await O2.readFile($,"utf8"),J;try{J=JSON.parse(Z)}catch(K){throw new e(`connection file JSON read failed for ${$}: ${String(K)}`)}let X=J.wire_version;if(X!==void 0&&X!==D0)throw new e(`connection file wire_version ${String(X)} but this client speaks ${D0}; the client library must be upgraded`);let G=J.endpoints;if(!Array.isArray(G))throw new e("connection file 'endpoints' must be an array");let Y=G.map((K)=>{let W=K;if(typeof W.host!=="string"||typeof W.port!=="number")throw new e("connection file endpoint must be { host: string, port: number }");return{host:W.host,port:W.port}}),z={schema:J.schema,endpoints:Y,key:T3(J.key,"key"),daemonId:T3(J.daemon_id,"daemon_id"),pid:J.pid,daemonVer:J.daemon_ver??""};return t7(z),z}var S3=new WeakMap;class n${channel;epoch;constructor($,Z,J){if(!Number.isInteger($)||$<=0||$>65535)throw RangeError(`route channel must be an integer in 1..65535, got ${$}`);if(!Number.isInteger(Z)||Z<=0||Z>4294967295)throw RangeError(`route epoch must be an integer in 1..4294967295, got ${Z}`);this.channel=$,this.epoch=Z,S3.set(this,J),Object.freeze(this)}static create($,Z,J){return new n$($,Z,J)}}function a$($,Z,J){return n$.create($,Z,J)}class s0 extends Error{handle;code="stale_route_handle";constructor($){super(`route handle (${$.channel}, ${$.epoch}) is not live on the current connection`);this.handle=$,this.name="StaleRouteHandleError"}}function b1(){return Object.freeze({})}function Q$($,Z){return S3.get($)===Z}function t$($,Z){return $===Z}var e7=r7("subc-client"),$Z=1e4,j$=30000,ZZ=50,JZ=2000,I3="request_deadline",D2="deadline_exceeded_no_drop_observed",XZ=30000,GZ=30000,f3=new Uint8Array(0),YZ="management_surface",k3="SUBC_MODULE_ID",E3="SUBC_LAUNCH_NONCE",Z6={baseMs:100,capMs:2000,maxAttempts:6};class $0 extends Error{kind;code;cause;constructor($,Z,J,X){super(Z);this.kind=$,this.code=J,this.cause=X,this.name="SubcCallError"}get detail(){return this.cause instanceof S?this.cause.detail:void 0}}class S extends Error{code;detail;constructor($,Z,J){super($);this.code=Z,this.detail=J}}function M2($){if($ instanceof Uint8Array)return $;let Z=$===null?"null":Array.isArray($)?"array":typeof $;throw new S(`binary request body must be a Uint8Array; got ${Z}`,"binary_body_required")}class B1{sock;currentConn;opts;nextCorr=1n;pending=new Map;lateResponses=new Map;routes=new Map;liveRoutes=new Map;connectionToken=b1();ingressEpochDropCount=0;closedErr=null;closeStarted=!1;reconnecting=null;generation=1;readerActive=!1;constructor($,Z,J){this.sock=$,this.currentConn=Z,this.opts=J,this.readLoop($,this.generation)}get conn(){return this.currentConn}static async connect($){let Z=WZ($),J=await B1.openConnection(Z);return new B1(J.sock,J.conn,Z)}async catalogList($){let Z=this.encode($===void 0?{op:"catalog.list"}:{op:"catalog.list",module_id:$}),J=await this.controlRpc(Z);return this.parseJson(J).modules??[]}async resolveProvider($){let Z=await this.resolveProviders($);if(Z.length===0)throw new S(`no catalog claimant for capability ${$}`,"capability_unprovided");if(Z.length>1)throw new S(`multiple catalog claimants for capability ${$}: ${Z.join(", ")}`,"capability_ambiguous");return Z[0]}async resolveProviders($){if(!v3($))throw new S(`malformed capability identifier ${JSON.stringify($)}`,"invalid_capability_identifier");return(await this.catalogList()).filter((J)=>J.capabilities?.provides.includes($)??!1).map((J)=>J.module_id).sort()}async routeOpen($,Z,J={}){let X=_2(J),G=J.consumerCapabilities,Y=this.encode({op:"route.open",target:$,identity:Z,...X?{consumer_identity:X}:{},...G!==void 0?{consumer_capabilities:G}:{}}),z=null,K=(Q)=>{if(Q.header.ty!==C.Response)return!0;let V=this.parseJson(Q);if(typeof V.route_channel!=="number"||typeof V.route_epoch!=="number")throw new S(`route.open returned no route handle: ${JSON.stringify(V)}`);return z=this.installRoute(V.route_channel,V.route_epoch),!0},W=(Q)=>{if(Q.header.ty!==C.Response)return;try{let V=this.parseJson(Q);if(typeof V.route_channel!=="number"||typeof V.route_epoch!=="number")return;let j=this.installRoute(V.route_channel,V.route_epoch);this.failHandle(j,new S("late route.open was closed","route_closed")),this.liveRoutes.delete(j.channel),this.sendRouteGoodbye(j,!0)}catch{this.closeConnectionAfterCleanupFailure()}};if(await this.controlRpc(Y,K,W),!z)throw new S("route.open response was not installed");return z}async request($,Z,J={}){this.assertLiveHandle($);let X=J.binary??!1,G=X?M2(Z):Z instanceof Uint8Array?Z:this.encode(Z),Y=J.priority??r.Interactive,z=J.admissionClass??G0.Normal,K=await this.send($,G,Y,z,J.timeoutMs,J.onProgress,void 0,void 0,X);return this.decodeReply(K)}async call($,Z,J,X={}){if(X.binary)throw new S("call() builds a JSON body and cannot send a binary request; use callBinary(moduleId, body, opts) with a Uint8Array","binary_call_requires_call_binary");let G=J===void 0?{method:Z}:{method:Z,params:J};return await this.managedCall($,G,X)}async callBinary($,Z,J={}){let X=M2(Z);return this.managedCall($,X,{...J,binary:!0})}async managedCall($,Z,J){let X=!1;for(;;){let G=await this.cachedRouteHandle($,J);try{return await this.managedRequest(G,Z,J)}catch(Y){if(!(Y instanceof $0))throw this.terminalCallError("managed call failed",Y);let z=Y.code==="unknown_channel"||Y.code==="stale_route_epoch";if(z&&!X&&!this.closeStarted){X=!0,this.evictRouteHandle(G);continue}if(z&&X)this.evictRouteHandle(G);if(Y.kind==="not_sent"){try{await this.reconnectAfterDrop(Y)}catch(K){throw this.notSentRecoveryError("managed call was not sent",K)}continue}if(Y.kind==="outcome_unknown"&&Y.code!==D2)this.scheduleReconnectAfterDrop(Y);else if(Y.kind==="outcome_unknown"&&Y.code===D2)this.probeLivenessAfterDeadline();throw Y}}}subscribe($,Z,J,X={}){this.assertLiveHandle($);let G=Z instanceof Uint8Array?Z:this.encode(Z),Y=X.priority??r.Interactive,z=X.admissionClass??G0.Normal,K=this.allocateCorr(),W=r$($,K),Q=null,V=null,j=new Promise((H,U)=>{if(this.closedErr){U(this.closedErr);return}V=H,Q={handle:$,resolve:()=>H(),reject:U,onProgress:J,timer:null,subscription:!0},this.pending.set(W,Q);let x=z0(C.Request,B0(!1,Y,!1,z),$.channel,$.epoch,K,G);v0(this.sock,k0(x),Date.now()+j$).catch((O)=>{let L=this.pending.get(W);if(L)this.rejectPending(W,L,O instanceof Error?O:new S(String(O)))})}),B=!1;return{unsubscribe:()=>{if(B)return;if(B=!0,Q&&V)this.settle(W,Q,V);if(this.isLiveHandle($))this.cancel($,K,Y)},closed:j}}cancel($,Z,J=r.Interactive){this.assertLiveHandle($);let X=z0(C.Cancel,B0(!1,J,!1),$.channel,$.epoch,Z,f3);v0(this.sock,k0(X),Date.now()+j$).catch(()=>{return})}async routePoll($,Z){this.assertLiveHandle($);let J=this.encode({op:"route.poll",route_channel:$.channel,route_epoch:$.epoch,kind:Z}),X=await this.controlRpc(J,(G)=>{if(G.header.ty!==C.Response)return!0;let Y=this.parseJson(G);return Y.route_channel===$.channel&&Y.route_epoch===$.epoch});return this.parseJson(X)}async closeRoute($,Z={}){this.assertLiveHandle($);for(let[J,X]of this.routes)if(X.handle&&t$(X.handle,$))X.closed=!0,X.handle=null,this.routes.delete(J);if(Z.drain)await this.drainUnaryOnHandle($);if(this.failHandle($,new S("route closed by closeRoute","route_closed")),this.liveRoutes.get($.channel)===$)this.liveRoutes.delete($.channel);this.sendRouteGoodbye($)}async closeManagedRoute($,Z,J={}){let X=b3($,Z,_2(J)),G=this.routes.get(X);if(!G)return;G.closed=!0,this.routes.delete(X);let Y=G.handle;if(G.handle=null,Y)await this.closeRoute(Y,J)}async closeRouteChannel($,Z={}){await this.closeRoute($,Z)}close(){this.closeStarted=!0,this.fail(new S("client closed")),this.sock.close()}drainUnaryOnHandle($){let Z=[];for(let J of this.pending.values())if(J.handle===$&&!J.subscription)Z.push(new Promise((X)=>{let G=J.onSettle;J.onSettle=()=>{G?.(),X()}}));return Promise.all(Z).then(()=>{return})}sendRouteGoodbye($,Z=!1){if(this.assertLiveConnection($),this.closedErr){if(Z)this.closeConnectionAfterCleanupFailure();return}let J=z0(C.Goodbye,B0(!1,r.Interactive,!1),$.channel,$.epoch,0n,f3),X=L2(this.sock,k0(J),Date.now()+j$);if(!X.queued&&Z)this.closeConnectionAfterCleanupFailure();X.completed.catch(()=>{if(Z&&!X.queued)this.closeConnectionAfterCleanupFailure()})}static async openConnection($){let Z=await V$($.connectionFile),J=Date.now()+($.handshakeTimeoutMs??$Z),X=Z.endpoints[0],G=await H1.connect(X.host,X.port,J);try{await W$(G,Z,J)}catch(Y){throw G.close(),Y}return{sock:G,conn:Z}}async controlRpc($,Z,J){return this.send(null,$,r.Interactive,G0.Normal,void 0,void 0,Z,J)}send($,Z,J,X,G,Y,z,K,W=!1){if($)this.assertLiveHandle($);if(this.closedErr)return Promise.reject(this.closedErr);let Q;try{Q=this.allocateCorr()}catch(H){return Promise.reject(H)}let V=r$($,Q),j=$?.channel??0,B=$?.epoch??0,q=z0(C.Request,B0(W,J,!1,X),j,B,Q,Z);return new Promise((H,U)=>{let x=G??j$,O={handle:$,resolve:H,reject:U,onProgress:Y,timer:null,acceptFrame:z,onLateResponse:K};O.timer=setTimeout(()=>this.arbitrateTimeout(V,O,j,Q,x),x),this.pending.set(V,O),v0(this.sock,k0(q),Date.now()+x).catch((L)=>{let M=this.pending.get(V);if(M)this.rejectPending(V,M,L instanceof Error?L:new S(String(L)))})})}arbitrateTimeout($,Z,J,X,G){let Y=()=>{if(Z.onLateResponse)this.lateResponses.set($,Z.onLateResponse);this.rejectPending($,Z,new S(this.timeoutMessage(J,X,G),I3))},z=Date.now()+this.opts.timeoutArbitrationGraceMs,K=()=>{if(this.pending.get($)!==Z)return;if((this.readerActive||this.sock.bufferedBytes()>0)&&Date.now()<z){setImmediate(K);return}Y()};setImmediate(K)}async managedRequest($,Z,J){let X=J.binary??!1,G=X?M2(Z):Z instanceof Uint8Array?Z:this.encode(Z),Y=J.priority??r.Interactive,z=J.admissionClass??G0.Normal;try{let K=await this.sendManaged($,G,Y,z,J.timeoutMs,J.onProgress,X);return this.decodeReply(K)}catch(K){if(K instanceof $0)throw K;throw this.terminalCallError("managed call failed",K)}}sendManaged($,Z,J,X,G,Y,z=!1){try{this.assertLiveHandle($)}catch(B){return Promise.reject(this.notSentCallError("request used a stale route handle",B))}if(this.closedErr)return Promise.reject(this.notSentCallError("request was not sent because the subc connection was already closed",this.closedErr));let K;try{K=this.allocateCorr()}catch(B){return Promise.reject(this.notSentCallError("request correlation allocator was exhausted",B))}let W=r$($,K),Q=z0(C.Request,B0(z,J,!1,X),$.channel,$.epoch,K,Z),V=!1,j=(B)=>{if(!V)return this.notSentCallError("request bytes were not queued to the subc socket",B);if(B instanceof S&&B.code===I3)return new $0("outcome_unknown",`managed call deadline exceeded after request bytes were queued to the local socket; no terminal response was observed; outcome unknown${o$(B)}`,D2,B);return this.outcomeUnknownCallError("connection dropped before the managed call returned a response",B)};return new Promise((B,q)=>{let H=G??j$,U={handle:$,resolve:B,reject:q,onProgress:Y,timer:null,classifyFailure:j};U.timer=setTimeout(()=>this.arbitrateTimeout(W,U,$.channel,K,H),H),this.pending.set(W,U);let x=L2(this.sock,k0(Q),Date.now()+H);V=x.queued,x.completed.catch((O)=>{let L=this.pending.get(W);if(L)this.rejectPending(W,L,O instanceof Error?O:new S(String(O)))})})}async cachedRouteHandle($,Z){let J=Z.identity??this.opts.identity;if(!J)throw new $0("terminal","managed call requires a BindIdentity in SubcClient.connect({ identity }) or call(..., { identity })","missing_identity");let X={kind:Z.targetKind??this.opts.targetKind,module_id:$},G=_2(Z),Y=b3(X,J,G),z=this.routes.get(Y);if(!z)z={key:Y,moduleId:$,target:X,identity:J,consumerIdentity:G,handle:null,opening:null},this.routes.set(Y,z);if(z.handle&&this.isLiveHandle(z.handle))return z.handle;if(!z.opening)z.opening=this.openCachedRoute(z).finally(()=>{z.opening=null});return z.opening}async openCachedRoute($){let Z=Date.now()+this.opts.routeOpenRetryDeadlineMs,J=this.opts.reconnectBackoff.baseMs,X=0;for(;;){if($.closed)throw this.routeClosedDuringOpen();try{await this.ensureConnectedForManaged()}catch(G){throw this.notSentRecoveryError("route.open could not run because reconnect failed",G)}if($.handle&&this.isLiveHandle($.handle))return $.handle;try{let G=await this.routeOpen($.target,$.identity,{consumerIdentity:$.consumerIdentity??null});if($.closed)throw this.liveRoutes.delete(G.channel),this.sendRouteGoodbye(G),this.routeClosedDuringOpen();return $.handle=G,G}catch(G){if(G instanceof $0&&G.code==="route_closed")throw G;if(!this.closeStarted&&e$(G)){try{await this.reconnectAfterDrop(G)}catch(Y){throw this.notSentRecoveryError("route.open was not sent and reconnect failed",Y)}continue}if(!this.closeStarted&&G instanceof S&&KZ(G.code)){if(X+=1,Date.now()<Z){await this.opts.sleep(J),J=Math.min(J*2,this.opts.reconnectBackoff.capMs);continue}throw this.notSentCallError(`route.open failed for module ${$.moduleId}: ${G.code} (retry deadline exhausted after ${X} attempts)`,G)}throw this.terminalCallError(`route.open failed for module ${$.moduleId}`,G)}}}lastInboundAtMs=0;livenessProbe=null;hasControlPending(){for(let $ of this.pending.values())if($.handle===null)return!0;return!1}probeLivenessAfterDeadline(){if(this.livenessProbe||this.closeStarted||this.closedErr)return;if(this.hasControlPending())return;let $=this.sock,Z=this.generation,J;try{J=this.allocateCorr()}catch{return}let X=Date.now(),G=z0(C.Ping,B0(!1,r.Interactive,!1,G0.Normal),0,0,J,new Uint8Array),Y=(async()=>{if(await v0($,k0(G),X+this.opts.livenessProbeWindowMs).catch(()=>{}),await this.opts.sleep(this.opts.livenessProbeWindowMs),this.sock!==$||this.generation!==Z||this.closeStarted)return;if(this.lastInboundAtMs>=X)return;if(this.hasControlPending())return;this.fail(new c0(`liveness probe convicted a half-open socket: no inbound frame for ${this.opts.livenessProbeWindowMs}ms after a channel-0 Ping (deadline-no-drop settles preceded this); closing so the next call reconnects`)),$.close()})().finally(()=>{this.livenessProbe=null});this.livenessProbe=Y}async ensureConnectedForManaged(){if(this.closeStarted)throw new S("client closed");if(this.reconnecting)await this.reconnecting;if(this.closedErr)await this.reconnectAfterDrop(this.closedErr)}scheduleReconnectAfterDrop($){if(this.closeStarted||this.reconnecting)return;this.reconnectAfterDrop($).catch(()=>{})}reconnectAfterDrop($){if(this.closeStarted)return Promise.reject(new S("client closed"));if(this.reconnecting)return this.reconnecting;let Z=this.reconnectWithRetry($).finally(()=>{if(this.reconnecting===Z)this.reconnecting=null});return this.reconnecting=Z,Z}async reconnectWithRetry($){let Z=0,J=this.opts.reconnectBackoff.baseMs;for(;;){if(this.closeStarted)throw new S("client closed");Z+=1;try{let X=await B1.openConnection(this.opts);if(this.closeStarted)throw X.sock.close(),new S("client closed");this.replaceConnection(X),await this.reopenCachedRoutes();return}catch(X){if(!e$(X)||Z>=this.opts.reconnectBackoff.maxAttempts){if(X instanceof K0&&Z>1)throw new K0(`reconnect gave up after ${Z} attempts: ${X.message} — the connection file and the daemon's key disagree persistently `+"(daemon restarting in a loop, split connection-file paths, or a genuinely foreign daemon on this port); check the daemon, then restart this host app");throw X}await this.opts.sleep(J),J=Math.min(J*2,this.opts.reconnectBackoff.capMs)}}}replaceConnection($){this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.closedErr=null,this.generation+=1,this.connectionToken=b1(),this.liveRoutes.clear(),this.lateResponses.clear(),this.nextCorr=1n,this.readLoop($.sock,this.generation)}async reopenCachedRoutes(){let $=[...this.routes.keys()];for(let Z of $){let J=this.routes.get(Z);if(J)J.handle=null}for(let Z of $){let J=this.routes.get(Z);if(!J||J.closed)continue;try{let X=await this.routeOpen(J.target,J.identity,{consumerIdentity:J.consumerIdentity??null});if(J.closed){this.liveRoutes.delete(X.channel),this.sendRouteGoodbye(X);continue}J.handle=X}catch(X){if(zZ(X)){this.routes.delete(Z);continue}throw X}}}timeoutMessage($,Z,J){let X=this.sock.localPort();return`request on ${X===null?"channel":`local_port=${X} channel`} ${$} corr ${Z} timed out after ${J}ms`}routeClosedDuringOpen(){return new $0("not_sent","route was closed before route.open completed","route_closed")}async readLoop($,Z){try{for(;;){this.readerActive=!1;let J=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:GZ},()=>{this.readerActive=!0});try{if(this.sock===$&&this.generation===Z)this.dispatch(J)}finally{this.readerActive=!1}}}catch(J){if(this.sock===$&&this.generation===Z)this.fail(J instanceof Error?J:new S(String(J)))}}dispatch($){if(this.lastInboundAtMs=Date.now(),$.header.channel===0&&$.header.ty===C.Push){let Y=this.opts.onControlPush;if(Y){let z=null;try{let K=this.parseJson($);if(K&&typeof K.op==="string")z={op:K.op,body:K}}catch{}if(z)try{Y(z)}catch{}}return}let Z=null;if($.header.channel!==0){if(Z=this.liveRoutes.get($.header.channel)??null,!Z||Z.epoch!==$.header.epoch){this.ingressEpochDropCount+=1;return}}let J=r$(Z,$.header.corr),X=this.pending.get(J);if(X){if(X.acceptFrame&&!X.acceptFrame($))return;switch($.header.ty){case C.Push:case C.StreamData:try{X.onProgress?.($.body)}catch{}return;case C.Response:case C.StreamEnd:this.settle(J,X,()=>X.resolve($));return;case C.Error:this.settle(J,X,()=>X.reject(this.errorFromFrame($)));return;default:return}}let G=this.lateResponses.get(J);if(G&&($.header.ty===C.Response||$.header.ty===C.Error)){this.lateResponses.delete(J),G($);return}if($.header.ty===C.Goodbye&&Z){if(this.failHandle(Z,new S("route closed by subc (GOODBYE)","route_closed")),this.liveRoutes.get(Z.channel)===Z)this.liveRoutes.delete(Z.channel);this.evictRouteHandle(Z);return}if($.header.ty===C.Response||$.header.ty===C.Error||$.header.ty===C.StreamEnd)e7("dropped terminal frame with no waiter: type=%d channel=%d epoch=%d corr=%s port=%s",$.header.ty,$.header.channel,$.header.epoch,$.header.corr,this.sock.localPort()??"?")}settle($,Z,J){if(this.pending.get($)!==Z)return!1;if(this.pending.delete($),Z.timer)clearTimeout(Z.timer);return J(),Z.onSettle?.(),!0}rejectPending($,Z,J){this.settle($,Z,()=>Z.reject(Z.classifyFailure?.(J)??J))}errorFromFrame($){try{let Z=JSON.parse(Buffer.from($.body).toString("utf8"));return new S(Z.message??"subc error",Z.code,Z.detail)}catch{return new S(Buffer.from($.body).toString("utf8")||"subc error")}}evictRouteHandle($){for(let Z of this.routes.values())if(Z.handle&&t$(Z.handle,$))Z.handle=null}failHandle($,Z){for(let[J,X]of this.pending)if(X.handle&&t$(X.handle,$))this.rejectPending(J,X,Z)}fail($){if(!this.closedErr)this.closedErr=$;for(let[Z,J]of this.pending)this.rejectPending(Z,J,$)}notSentCallError($,Z){return new $0("not_sent",`${$}${o$(Z)}`,$6(Z),Z)}outcomeUnknownCallError($,Z){return new $0("outcome_unknown",`${$}${o$(Z)}`,$6(Z),Z)}terminalCallError($,Z){if(Z instanceof $0)return Z;return new $0("terminal",`${$}${o$(Z)}`,$6(Z),Z)}notSentRecoveryError($,Z){if(Z instanceof $0)return Z;if(e$(Z))return this.notSentCallError($,Z);return this.terminalCallError($,Z)}get droppedIngressFrames(){return this.ingressEpochDropCount}installRoute($,Z){let J=a$($,Z,this.connectionToken);return this.liveRoutes.set($,J),J}isLiveHandle($){return Q$($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveConnection($){if(!Q$($,this.connectionToken))throw new s0($)}assertLiveHandle($){if(!this.isLiveHandle($))throw new s0($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let J=new S("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.fail(J),this.sock.close(),this.scheduleReconnectAfterDrop(J),J}let Z=this.nextCorr;return this.nextCorr+=1n,Z}closeConnectionAfterCleanupFailure(){let $=new S("late route cleanup could not be queued","late_route_cleanup_failed");this.fail($),this.sock.close(),this.scheduleReconnectAfterDrop($)}encode($){return Buffer.from(JSON.stringify($),"utf8")}decodeReply($){return q2($.header.flags)?$.body:this.parseJson($)}parseJson($){let Z=$.body;return JSON.parse(Buffer.from(Z.buffer,Z.byteOffset,Z.byteLength).toString("utf8"))}}function e$($){if($ instanceof c0||$ instanceof P0)return!0;if($ instanceof E0||$ instanceof e0)return!0;if($ instanceof $0)return $.kind==="not_sent"||$.kind==="outcome_unknown";if($ instanceof K0)return!0;if($ instanceof S||$ instanceof e)return!1;let Z=$6($);return Z==="ECONNREFUSED"||Z==="ECONNRESET"||Z==="EPIPE"||Z==="ETIMEDOUT"||Z==="ENOENT"}function zZ($){return $ instanceof S&&typeof $.code==="string"}function KZ($){if($==="capability_forbidden")return!1;return $==="unknown_module"||$==="module_reloading"||$==="module_warming"||$==="target_unavailable"||$==="module_timeout"}function WZ($){return{connectionFile:$.connectionFile,handshakeTimeoutMs:$.handshakeTimeoutMs,identity:$.identity,targetKind:$.targetKind??YZ,reconnectBackoff:$.reconnectBackoff??Z6,sleep:$.sleep??((Z)=>new Promise((J)=>setTimeout(J,Z))),routeOpenRetryDeadlineMs:$.routeOpenRetryDeadlineMs??XZ,timeoutArbitrationGraceMs:$.timeoutArbitrationGraceMs??ZZ,livenessProbeWindowMs:$.livenessProbeWindowMs??JZ,onControlPush:$.onControlPush}}function v3($){if(/\s/u.test($))return!1;let Z=$.indexOf("/v");if(Z<=0||$.indexOf("/v",Z+1)!==-1)return!1;let J=$.slice(0,Z),X=$.slice(Z+2);if(new TextEncoder().encode(J).byteLength>64||X.length===0)return!1;if(!/^[a-z][a-z0-9-]*[a-z0-9]$/u.test(J)&&!/^[a-z]$/u.test(J))return!1;if(J.includes("--"))return!1;if(!/^\d+$/u.test(X)||X.length>1&&X.startsWith("0"))return!1;let G=Number(X);return Number.isSafeInteger(G)&&G>=1&&G<=4294967295}function b3($,Z,J){let X=J?`${J.module_id}\x00${J.launch_nonce}`:"";return`${$.kind}\x00${$.module_id}\x00${Z.project_root}\x00${Z.harness}\x00${Z.session}\x00${X}`}function _2($={}){if($.consumerIdentity!==void 0)return $.consumerIdentity??void 0;let Z=process.env[k3],J=process.env[E3];if(!Z||!J)return;return{module_id:Z,launch_nonce:J}}function $6($){if(typeof $==="object"&&$!==null&&"code"in $){let Z=$.code;if(typeof Z==="string")return Z}return}function o$($){if($===void 0)return"";return`: ${$ instanceof Error?$.message:String($)}`}function r$($,Z){return $?`${$.channel}:${$.epoch}:${Z}`:`0:0:${Z}`}import{Buffer as F2}from"node:buffer";var VZ=1e4,QZ=30000,y3=30000,jZ=250,C2=64,P2="health.check",g3=1n;class X6{available;waiters=[];constructor($){if(!Number.isInteger($)||$<=0)throw new g("provider handler capacity must be a positive integer","invalid_handler_capacity");this.available=$}async acquire(){if(this.available>0)return this.available-=1,this.releaseOnce();return await new Promise(($)=>{this.waiters.push($)}),this.releaseOnce()}releaseOnce(){let $=!1;return()=>{if($)return;$=!0;let Z=this.waiters.shift();if(Z)Z();else this.available+=1}}}class g extends Error{code;kind;detail;constructor($,Z,J="terminal",X){super($);this.code=Z,this.kind=J,this.detail=X}}class H${sock;currentConn;opts;closed;resolveClosed=()=>{return};closeStarted=!1;closedErr=null;inflight=new Map;pending=new Map;liveRoutes=new Map;connectionToken=b1();nextCorr=1n;ingressEpochDropCount=0;requestGate=new X6(C2);reconnecting=null;generation=1;connectionEpoch=1;stateQueue=[];drainingStateQueue=!1;restoredDebounceToken=0;storage;constructor($,Z,J,X){this.sock=$,this.currentConn=Z,this.opts=J,this.storage=X,this.closed=new Promise((G)=>{this.resolveClosed=G}),this.readLoop($,this.generation),this.enqueueConnectionState({state:"connected",epoch:this.connectionEpoch})}get droppedIngressFrames(){return this.ingressEpochDropCount}get conn(){return this.currentConn}currentEpoch(){return this.connectionEpoch}async request($,Z,J={}){this.assertLiveHandle($);let X=this.allocateCorr(),G=J6($,X),Y=J.timeoutMs??y3,z=z0(C.Request,B0(!1,J.priority??r.Interactive,!1,J.admissionClass??G0.Normal),$.channel,$.epoch,X,Z);return await new Promise((K,W)=>{let Q=setTimeout(()=>{if(this.pending.delete(G))W(new g("reverse request timed out","request_timeout"))},Y);this.pending.set(G,{resolve:(V)=>K(V.body),reject:W,timer:Q}),this.sendOn(this.sock,this.generation,z).catch((V)=>{let j=this.pending.get(G);if(!j)return;this.pending.delete(G),clearTimeout(j.timer),W(V instanceof Error?V:new g(String(V)))})})}async push($,Z,J={}){this.assertLiveHandle($),await this.sendOn(this.sock,this.generation,z0(C.Push,B0(!1,J.priority??r.Interactive,!1,J.admissionClass??G0.Normal),$.channel,$.epoch,0n,Z))}cancel($,Z){this.assertLiveHandle($),this.sendOn(this.sock,this.generation,z0(C.Cancel,h0(),$.channel,$.epoch,Z,new Uint8Array(0))).catch(()=>{return})}closeRoute($){this.assertLiveHandle($),this.liveRoutes.delete($.channel),this.abortHandle($),this.sendOn(this.sock,this.generation,z0(C.Goodbye,h0(),$.channel,$.epoch,0n,new Uint8Array(0))).catch(()=>{return})}static async connect($){if($.manifest.protocol_ver!==D0)throw new g(`manifest protocol_ver ${$.manifest.protocol_ver} does not match client protocol ${D0}`,"invalid_manifest");let Z=UZ($),J=await H$.openConnection(Z);return new H$(J.sock,J.conn,Z,J.ack.storage)}async close(){if(!this.closeStarted){this.closeStarted=!0,this.cancelRestoredDebounce();let $=this.sock;try{await R2($,z0(C.Goodbye,h0(),0,0,0n,new Uint8Array(0)))}catch{}finally{$.close(),this.finishClosed()}}await this.closed}static async openConnection($,Z){let J=await V$($.connectionFile),X=Date.now()+($.handshakeTimeoutMs??VZ),G=J.endpoints[0],Y=await H1.connect(G.host,G.port,X);try{Z?.(Y),await W$(Y,J,X),await R2(Y,NZ($));let z=await MZ(Y,X);return{sock:Y,conn:J,ack:z}}catch(z){throw Y.close(),z}}async readLoop($,Z){try{for(;;){let J=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:QZ});if(!await this.dispatch(J,$,Z)){if(this.sock===$&&this.generation===Z)this.closeStarted=!0;break}}}catch(J){if(this.sock===$&&this.generation===Z&&!this.closeStarted){this.handleUnexpectedDrop($,Z,J instanceof Error?J:new g(String(J)));return}}finally{if(this.sock===$&&this.generation===Z){if($.close(),this.closeStarted)this.finishClosed()}}}async dispatch($,Z,J){let X=null;if($.header.channel!==0){if(X=this.liveRoutes.get($.header.channel)??null,!X||X.epoch!==$.header.epoch)return this.ingressEpochDropCount+=1,!0}if(X){let G=J6(X,$.header.corr),Y=this.pending.get(G);if(Y){if($.header.ty===C.Push||$.header.ty===C.StreamData)return!0;if($.header.ty===C.Response||$.header.ty===C.StreamEnd)return this.pending.delete(G),clearTimeout(Y.timer),Y.resolve($),!0;if($.header.ty===C.Error)return this.pending.delete(G),clearTimeout(Y.timer),Y.reject(HZ($)),!0}}switch($.header.ty){case C.Ping:if($.header.channel===0)await this.sendOn(Z,J,b0($.header.ver,C.Pong,$.header.flags,0,0,$.header.corr,new Uint8Array(0)));return!0;case C.Goodbye:if(!X)return!1;return this.liveRoutes.delete(X.channel),this.abortHandle(X),await this.opts.onRouteGone?.(X),!0;case C.Cancel:if(X)this.inflight.get(J6(X,$.header.corr))?.abort();return!0;case C.Request:if($.header.channel===0)await this.handleControlRequest($,Z,J);else if(X)this.handleDataRequest($,X,Z,J).catch((G)=>{if(!this.closeStarted&&this.sock===Z&&this.generation===J)console.warn("SubcProvider handler failed after its request was dispatched",G)});return!0;default:return!0}}abortHandle($){let Z=`${$.channel}:${$.epoch}:`;for(let[J,X]of this.inflight)if(J.startsWith(Z))X.abort();for(let[J,X]of this.pending){if(!J.startsWith(Z))continue;this.pending.delete(J),clearTimeout(X.timer),X.reject(new s0($))}}abortGeneration($){this.abortAllInflight();for(let[Z,J]of this.pending)this.pending.delete(Z),clearTimeout(J.timer),J.reject(new g("provider connection dropped","connection_dropped"));this.liveRoutes.clear()}abortAllInflight(){for(let $ of this.inflight.values())$.abort()}async handleControlRequest($,Z,J){let X=Y6($.body);if(X.op===P2){this.handleHealthRequest($,Z,J).catch((j)=>{if(!this.closeStarted&&this.sock===Z&&this.generation===J)console.warn("SubcProvider health handler failed after its request was dispatched",j)});return}if(X.op!=="route.bind")throw new g(`unsupported module control request ${X.op??"<missing op>"}`);let G=h3(X.route_channel,"route_channel"),Y=h3(X.epoch,"epoch"),z=this.liveRoutes.get(G);if(z){if(Y<=z.epoch){await this.sendError($,"route_rejected",`route.bind epoch ${Y} does not supersede installed epoch ${z.epoch} on channel ${G}`,h0(),Z,J);return}this.liveRoutes.delete(z.channel),this.abortHandle(z),await this.opts.onRouteGone?.(z)}let K=a$(G,Y,this.connectionToken),W={handle:K,target:X.target,identity:X.identity,principal:X.principal,consumer_capabilities:X.consumer_capabilities},Q;try{Q=await this.opts.onBind?.(W)}catch(j){try{await this.sendError($,"route_rejected",j instanceof Error?j.message:String(j),h0(),Z,J)}finally{await this.opts.onRouteGone?.(K)}return}let V=_Z(Q);if(V){try{await this.sendError($,V.code,V.message,h0(),Z,J)}finally{await this.opts.onRouteGone?.(K)}return}try{await this.sendOn(Z,J,b0($.header.ver,C.Response,h0(),0,0,$.header.corr,G6({op:"route.bind"})))}catch(j){throw await this.opts.onRouteGone?.(K),j}if(this.sock!==Z||this.generation!==J||this.closeStarted||this.closedErr){await this.opts.onRouteGone?.(K);return}this.liveRoutes.set(K.channel,K),await this.opts.onBound?.(K)}async handleDataRequest($,Z,J,X){let{corr:G,ver:Y}=$.header,z=J6(Z,G),K=new AbortController;this.inflight.set(z,K);let W={handle:Z,signal:K.signal,currentEpoch:()=>this.connectionEpoch,emit:async(j,B={})=>{if(this.assertLiveHandle(Z),K.signal.aborted)return;await this.sendOn(J,X,b0(Y,C.StreamData,B0(!1,B.priority??r.Interactive,!1,B.admissionClass??G0.Normal),Z.channel,Z.epoch,G,j))}},Q=await(this.requestGate??new X6(C2)).acquire(),V=B0(!1,r.Interactive,!1);try{if(K.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,J,X);return}let j=await this.opts.handler(Z,$.body,W);if(K.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,J,X);return}if(this.assertLiveHandle(Z),j===void 0)await this.sendOn(J,X,b0(Y,C.StreamEnd,V,Z.channel,Z.epoch,G,new Uint8Array(0)));else if(j instanceof Uint8Array)await this.sendOn(J,X,b0(Y,C.Response,V,Z.channel,Z.epoch,G,j));else throw new g("provider handler must return a Uint8Array or void","invalid_handler_response")}catch(j){if(j instanceof s0)return;if(K.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,J,X);return}await this.sendError($,j instanceof g&&j.code?j.code:"handler_error",j instanceof Error?j.message:String(j),V,J,X)}finally{if(Q(),this.inflight.get(z)===K)this.inflight.delete(z)}}async handleHealthRequest($,Z,J){let{corr:X,ver:G}=$.header,Y=`control:${J}:${X}`,z=new AbortController;this.inflight.set(Y,z);let K=await(this.requestGate??new X6(C2)).acquire();try{if(z.signal.aborted)return;let W=await this.opts.health();await this.sendOn(Z,J,b0(G,C.Response,h0(),0,0,X,G6({op:P2,status:W.status,...W.detail===void 0?{}:{detail:W.detail},...W.metrics===void 0?{}:{metrics:W.metrics}})))}catch(W){await this.sendError($,W instanceof g&&W.code?W.code:"health_error",W instanceof Error?W.message:String(W),h0(),Z,J)}finally{if(K(),this.inflight.get(Y)===z)this.inflight.delete(Y)}}async sendError($,Z,J,X,G,Y){if($.header.channel!==0){let z=this.liveRoutes.get($.header.channel);if(!z||z.epoch!==$.header.epoch||!this.isLiveHandle(z))return}await this.sendOn(G,Y,b0($.header.ver,C.Error,X,$.header.channel,$.header.epoch,$.header.corr,G6({code:Z,message:J})))}async sendOn($,Z,J){if(this.sock!==$||this.generation!==Z||this.closeStarted||this.closedErr)return;await R2($,J)}handleUnexpectedDrop($,Z,J){if(this.closeStarted||this.sock!==$||this.generation!==Z)return;this.cancelRestoredDebounce(),this.abortGeneration(Z),this.generation+=1,$.close(),this.scheduleReconnectAfterDrop(J,this.generation,$)}scheduleReconnectAfterDrop($,Z,J){if(this.closeStarted)return;let X=this.reconnecting;if(X){if(!this.shouldSupersedeReconnect(X,Z,J))return;X.superseded=!0,X.socket?.close()}let G={generation:Z,socket:null,socketDied:!1,superseded:!1};this.reconnecting=G,this.enqueueConnectionState({state:"down",cause:$}),this.reconnectWithRetry(G).catch((Y)=>{if(this.isCurrentReconnect(G)&&!this.closeStarted)this.failFatal(Y instanceof Error?Y:new g(String(Y)))}).finally(()=>{if(this.isCurrentReconnect(G))this.reconnecting=null})}async reconnectWithRetry($){let Z=0,J=this.opts.reconnectBackoff.baseMs;for(;;){if(!this.isCurrentReconnect($))return;if(this.closeStarted)throw new g("provider closed");$.socket=null,$.socketDied=!1,Z+=1,this.enqueueReconnectState($,Z);try{let X=await H$.openConnection(this.opts,(Y)=>{if(!this.isCurrentReconnect($)){Y.close();return}$.socket=Y});if(!this.isCurrentReconnect($)||this.closeStarted){if(X.sock.close(),this.closeStarted)throw new g("provider closed");return}let G=this.replaceConnection(X,$.generation);if(this.reconnecting=null,this.reconnecting!==null)throw new g("reconnect state must clear before restored","reconnect_state");this.scheduleRestored($.generation,G);return}catch(X){if(!this.isCurrentReconnect($))return;if($.socket)$.socketDied=!0;if(this.closeStarted)throw X;if(!xZ(X))throw X;await this.opts.sleep(J),J=Math.min(J*2,this.opts.reconnectBackoff.capMs)}}}isCurrentReconnect($){return!$.superseded&&this.reconnecting===$&&this.generation===$.generation}shouldSupersedeReconnect($,Z,J){return $.generation<Z||$.socketDied||$.socket===J}enqueueReconnectState($,Z){if(!this.isCurrentReconnect($))return;this.enqueueConnectionState({state:"reconnecting",attempt:Z},$.generation,$)}replaceConnection($,Z){return this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.storage=$.ack.storage,this.closedErr=null,this.connectionEpoch+=1,this.connectionToken=b1(),this.liveRoutes.clear(),this.nextCorr=1n,this.readLoop($.sock,Z),this.connectionEpoch}scheduleRestored($,Z){if(!this.opts.onConnectionState)return;let J=++this.restoredDebounceToken;this.opts.sleep(this.opts.restoredDebounceMs).then(()=>{if(J===this.restoredDebounceToken&&!this.closeStarted&&this.sock&&this.generation===$&&this.connectionEpoch===Z)this.enqueueConnectionState({state:"restored",epoch:Z},$)}).catch((X)=>{if(J===this.restoredDebounceToken&&!this.closeStarted)console.warn("SubcProvider restored debounce timer failed",X)})}cancelRestoredDebounce(){this.restoredDebounceToken+=1}enqueueConnectionState($,Z,J){if(!this.opts.onConnectionState)return;if(this.stateQueue.push({event:$,generation:Z,reconnect:J}),!this.drainingStateQueue)this.drainConnectionStateQueue()}async drainConnectionStateQueue(){if(this.drainingStateQueue)return;this.drainingStateQueue=!0;try{while(this.stateQueue.length>0){let $=this.stateQueue[0];if(this.closeStarted||$.generation!==void 0&&$.generation!==this.generation||$.reconnect?.superseded){this.stateQueue.shift();continue}let{event:Z}=$;try{await this.opts.onConnectionState?.(Z),this.stateQueue.shift()}catch(J){if(Z.state==="restored"){console.warn("SubcProvider restored callback failed; retrying delivery",J),await DZ();continue}console.warn("SubcProvider connection-state callback failed",J),this.stateQueue.shift()}}}finally{if(this.drainingStateQueue=!1,this.stateQueue.length>0)this.drainConnectionStateQueue()}}isLiveHandle($){return Q$($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveHandle($){if(!this.isLiveHandle($))throw new s0($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let J=new g("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.handleUnexpectedDrop(this.sock,this.generation,J),J}let Z=this.nextCorr;return this.nextCorr+=1n,Z}failFatal($){if(!this.closedErr)this.closedErr=$;this.closeStarted=!0,this.cancelRestoredDebounce(),this.abortAllInflight(),this.sock.close(),this.finishClosed()}finishClosed(){this.resolveClosed()}}function J6($,Z){return`${$.channel}:${$.epoch}:${Z}`}function HZ($){try{let Z=Y6($.body);return new g(Z.message??"subc error",Z.code,Z.code==="stale_route_epoch"||Z.code==="unknown_channel"?"not_sent":"terminal",Z.detail)}catch{return new g(F2.from($.body).toString("utf8")||"subc error")}}function BZ($){let Z=$.launchNonce??process.env[qZ];return Z&&Z.length>0?Z:void 0}var qZ="SUBC_LAUNCH_NONCE";function UZ($){return{connectionFile:$.connectionFile,manifest:$.manifest,handler:$.handler,health:$.health??(()=>({status:"ok"})),handshakeTimeoutMs:$.handshakeTimeoutMs,controlOps:$.controlOps,onBind:$.onBind,onBound:$.onBound,onRouteGone:$.onRouteGone,reconnectBackoff:$.reconnectBackoff??Z6,sleep:$.sleep??((Z)=>new Promise((J)=>setTimeout(J,Z))),restoredDebounceMs:$.restoredDebounceMs??jZ,onConnectionState:$.onConnectionState,launchNonce:$.launchNonce}}function LZ($){if($===null)return null;let Z=new Set($??[]);return Z.add(P2),[...Z]}function NZ($){let Z=BZ($);return z0(C.Hello,h0(),0,0,g3,G6({manifest:CZ($.manifest),protocol_ver:D0,control_ops:LZ($.controlOps),...Z?{launch_nonce:Z}:{}}))}function xZ($){if($ instanceof g)return $.code==="duplicate_module_id";if($ instanceof c0||$ instanceof P0)return!0;if($ instanceof E0||$ instanceof e0)return!0;if($ instanceof K0)return!0;if($ instanceof e)return!1;let Z=OZ($);return Z==="ECONNREFUSED"||Z==="ECONNRESET"||Z==="EPIPE"||Z==="ETIMEDOUT"||Z==="ENOENT"}function OZ($){if(typeof $==="object"&&$!==null&&"code"in $){let Z=$.code;if(typeof Z==="string")return Z}return}async function DZ(){await new Promise(($)=>setTimeout($,0))}function h0(){return B0(!1,r.Passive,!1)}async function R2($,Z){await v0($,k0(Z),Date.now()+y3)}async function MZ($,Z){let J=await $.readFrame(Z,Z);switch(J.header.ty){case C.HelloAck:{let X=Y6(J.body);if(X.negotiated_ver!==D0)throw new g(`subc negotiated protocol ${X.negotiated_ver}; expected exactly ${D0}`,"unsupported_version");return X}case C.Error:{let X=Y6(J.body);throw new g(`subc rejected HELLO: ${X.code??"unknown"} — ${X.message??"subc error"}`,X.code)}default:throw new g(`unexpected frame ${C[J.header.ty]} awaiting HELLO_ACK`)}}function G6($){return new Uint8Array(F2.from(JSON.stringify($),"utf8"))}function Y6($){return JSON.parse(F2.from($).toString("utf8"))}function h3($,Z){if(typeof $!=="number"||!Number.isInteger($))throw new g(`route.bind ${Z} must be an integer`);return $}function _Z($){if($===void 0||$===!0)return null;if($===!1)return{code:"route_rejected",message:"route.bind rejected by provider"};if($.accept)return null;return{code:$.code??"route_rejected",message:$.message??"route.bind rejected by provider"}}function CZ($){return{module_id:$.module_id,module_version:$.module_version,protocol_ver:$.protocol_ver,trust_tier:$.trust_tier,provides:$.provides.map(RZ),consumes:$.consumes.map(PZ),bindings:{storage:{kind:$.bindings.storage.kind,scope:$.bindings.storage.scope,owns_schema:$.bindings.storage.owns_schema},vault_grants:$.bindings.vault_grants.map((Z)=>({secret:Z.secret,reason:Z.reason})),identity:{requires:[...$.bindings.identity.requires],optional:[...$.bindings.identity.optional]}}}}function RZ($){switch($.role){case"tool_provider":return{role:"tool_provider",tools:$.tools.map((Z)=>({name:Z.name,...Z.description===void 0?{}:{description:Z.description},execution_mode:Z.execution_mode,schema:Z.schema})),identity_scope:[...$.identity_scope],concurrency:$.concurrency,emits_push:$.emits_push,sub_supervises:$.sub_supervises};case"pipeline_stage":return{role:"pipeline_stage",stage:$.stage,applies_to:{provider:$.applies_to.provider,model:$.applies_to.model},interface:$.interface,declares_frozen_floor:$.declares_frozen_floor,needs_signals:[...$.needs_signals],conformance_class:$.conformance_class};case"management_surface":return{role:"management_surface",operations:$.operations.map((Z)=>({name:Z.name,kind:Z.kind})),config_schema:$.config_schema,observability:$.observability.map((Z)=>({name:Z.name,kind:Z.kind})),identity_scope:[...$.identity_scope],concurrency:$.concurrency};case"internal_service":return{role:"internal_service",service_id:$.service_id,transport:$.transport,agent_facing:$.agent_facing,operations:[...$.operations]}}}function PZ($){switch($.role){case"tool_client":return{role:"tool_client",of:[...$.of]};case"llm_client":return{role:"llm_client",via:$.via,auth:$.auth};case"service_client":return{role:"service_client",of:[...$.of]}}}function q0($){try{return JSON.parse($)}catch(Z){if(Z instanceof SyntaxError)throw SyntaxError("invalid JSON");throw Z}}var k1="subc-connection.json",fZ="subc-",bZ=".connection.json";function U$($){try{return AZ($).isFile()}catch{return!1}}function kZ($){let Z;try{Z=FZ($)}catch{return[]}let J=[];for(let X of Z){if(typeof X!=="string")continue;if(!X.startsWith(fZ)||!X.endsWith(bZ))continue;let G=M0($,X);if(U$(G))J.push(G)}return J.sort(),J}function EZ($=process.env){let Z=$.XDG_RUNTIME_DIR?.trim();if(Z){let z=M0(Z,k1);if(U$(z))return z}let J=$.HOME?.trim();if(J){let z=M0(J,".local","share","cortexkit","run",k1);if(U$(z))return z}let G=`/run/user/${process.getuid?.()??v1().uid}/${k1}`;if(U$(G))return G;let Y=kZ(TZ());if(Y.length===1)return Y[0];return}function vZ($=process.env){let Z=EZ($);if(Z)return Z;let J=$.XDG_RUNTIME_DIR?.trim();if(J&&(process.platform!=="darwin"||U$(J)))return M0(J,k1);if(process.platform==="darwin"){let G=$.HOME?.trim()||v1().homedir;return M0(G,".local","share","cortexkit","run",k1)}return`/run/user/${process.getuid?.()??v1().uid}/${k1}`}function W6($,Z=process.env){return $?.trim()||Z.OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE?.trim()||Z.CLAUSTRUM_SUBC_CONNECTION?.trim()||vZ(Z)}function hZ($,Z){let J=$?.handlesFile?.trim();if(J)return J;let X=Z.CLAUSTRUM_OPENCODE_HANDLES;if(X&&IZ(X))return X;let G=Z.XDG_CONFIG_HOME?.trim()||M0(Z.HOME||wZ(),".config");return M0(G,"cortexkit","opencode-handles.json")}function iV(){return hZ(void 0,process.env)}function k($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function yZ($){return k($)&&typeof $.host==="string"&&$.host.trim().length>0&&typeof $.port==="number"&&Number.isInteger($.port)&&$.port>0&&$.port<=65535}async function cV($){let Z=W6($),J;try{J=await T.readFile(Z,"utf8")}catch(G){let Y=s(G);if(Y==="ENOENT")return{status:"absent",path:Z};return{status:"malformed",path:Z,reason:`unreadable (${Y})`}}let X;try{X=JSON.parse(J)}catch{return{status:"malformed",path:Z,reason:"invalid JSON"}}if(!k(X)||typeof X.schema!=="number"||!Number.isFinite(X.schema)||typeof X.wire_version!=="number"||!Number.isFinite(X.wire_version)||!Array.isArray(X.endpoints)||X.endpoints.length===0||!X.endpoints.every(yZ))return{status:"malformed",path:Z,reason:"connection file has an invalid schema, wire_version, or endpoints"};return{status:"available",schema:X.schema,wireVersion:X.wire_version,endpoints:X.endpoints.map((G)=>({host:G.host,port:G.port}))}}var V6="claustrum-tombstone:v1:";function x$($){return`${V6}${$}`}function sV($){return{type:"oauth",access:"",refresh:x$($),expires:0}}function A2($){return typeof $==="string"&&$.startsWith(V6)}function nV($,Z){if(!k($)||$.type!=="oauth")return!1;return $.refresh===x$(Z)}class O$ extends Error{provider;code="custody_tombstone_refresh";constructor($){super(`${$} main slot is vault-custodied; local refresh is forbidden — the vault-served main path is not yet implemented`);this.provider=$,this.name="CustodyTombstoneRefreshError"}}class gZ extends Error{provider;code="custody_tombstone_login";constructor($){super(`${$} main slot is custodied; run /login to sign in locally`);this.provider=$,this.name="CustodyTombstoneLoginError"}}function y1($,Z){if(A2($))throw new O$(Z)}var mZ=/^[a-z0-9][a-z0-9._-]{0,63}$/,pZ=new Set(["__proto__","constructor","prototype"]),uZ="oauth:anthropic:";function q1($){return typeof $==="string"&&mZ.test($)&&!pZ.has($)}function z6($){return typeof $==="string"&&i3.test($)}function p3($){if(!q1($))throw new N$("invalid-label");return`${uZ}${$}`}function aV($,Z){if($.status==="resolved"&&$.source==="manifest")return $.credentialId??p3(Z);return p3(Z)}function lZ($){return typeof $==="string"&&$.length>0}function c3($,Z){if(typeof $!=="string"||$.length===0)return!1;return $.split(":")[1]===Z}function B$($,Z){if($.claustrumHandle)return{status:"resolved",source:"legacy",handle:$.claustrumHandle};return{status:"unresolved",reason:Z}}function tV($){let{account:Z,manifest:J,duplicateOAuthLabels:X}=$;if(J&&J.serve!=="anthropic-auth")return{status:"unresolved",reason:"foreign-serve"};if(!Z.label)return B$(Z,"missing-label");if(!q1(Z.label))return B$(Z,"invalid-label");if(X?.has(Z.label))return B$(Z,"duplicate-label");if(!J)return B$(Z,"missing-entry");if(J.corruptLabels?.has(Z.label))return{status:"unresolved",reason:"corrupt-binding"};let G=J.accounts.find((Y)=>Y.label===Z.label);if(!G)return B$(Z,"missing-entry");if(J.superseded.has(G.handle))return{status:"unresolved",reason:"superseded"};return{status:"resolved",source:"manifest",handle:G.handle,credentialId:G.credentialId}}function w2($,Z,J){if(!q1(Z))throw Error("invalid manifest provider");if(!k($)||!Object.hasOwn($,"version")||$.version!==1)throw Error("invalid manifest version");if(!Object.hasOwn($,"providers")||!Array.isArray($.providers))throw Error("missing manifest providers");let X=$.providers.filter((V)=>k(V)&&Object.hasOwn(V,"provider")&&V.provider===Z);if(X.length===0)throw new N$("missing-provider");let G=X.find((V)=>Object.hasOwn(V,"serve")&&V.serve===J);if(!G)throw new N$("foreign-serve");if(!Object.hasOwn(G,"accounts")||!Array.isArray(G.accounts))throw Error("invalid manifest accounts");let Y=new Map;for(let V of G.accounts){if(!k(V)||!Object.hasOwn(V,"label")||typeof V.label!=="string"||!q1(V.label))continue;Y.set(V.label,(Y.get(V.label)??0)+1)}let z=new Set([...Y].filter(([,V])=>V>1).map(([V])=>V)),K=new Set,W=new Set,Q=[];for(let V of G.accounts){if(!k(V))throw Error("invalid account entry");if(!Object.hasOwn(V,"label")||typeof V.label!=="string")throw Error("invalid account label");if(!q1(V.label))throw Error("invalid account label");if(!Object.hasOwn(V,"handle")||!Object.hasOwn(V,"credential_id")||typeof V.handle!=="string"||!z6(V.handle)||!c3(V.credential_id,Z)){W.add(V.label);continue}if(z.has(V.label)){W.add(V.label);continue}if(Object.hasOwn(V,"superseded")){if(!Array.isArray(V.superseded)){W.add(V.label);continue}let j=!1;for(let B of V.superseded)if(!z6(B)){j=!0;break}if(j){W.add(V.label);continue}for(let B of V.superseded)K.add(B)}Q.push({label:V.label,handle:V.handle,credentialId:V.credential_id})}return{version:1,provider:Z,serve:J,accounts:Q,superseded:K,corruptLabels:W}}var oV=["foreign-serve","invalid-label","missing-provider"];class N$ extends Error{code;constructor($){super($);this.code=$}}var $1=262144;function s($){let Z=$.code;return typeof Z==="string"?Z:"unknown"}function h1($,Z){let J=Number($.mode);if($.isSymbolicLink())return"manifest is a symlink";if(!$.isFile())return"manifest is not a regular file";if((J&511)!==384)return"manifest mode must be 0600";if($.uid!==Z)return"manifest owner does not match";return null}function T2($,Z){let J=Number($.mode);if($.uid!==Z)return"manifest parent owner does not match";if((J&512)!==0)return null;if((J&2)!==0)return"manifest parent is world-writable";if((J&16)!==0)return"manifest parent is group-writable";return null}class dZ{#$;#Z;constructor($){this.#Z=$}async read(){let $=this.#Z.expectedUid??process.getuid?.()??v1().uid,Z;try{Z=await T.lstat(this.#Z.path)}catch(G){if(s(G)==="ENOENT")return{status:"absent"};return{status:"invalid",reason:`unreadable (${s(G)})`}}let J=h1(Z,$);if(J)return{status:"invalid",reason:J};try{let G=T2(await T.lstat(K6(this.#Z.path)),$);if(G)return{status:"invalid",reason:G}}catch(G){return{status:"invalid",reason:`unreadable (${s(G)})`}}let X;try{X=await T.open(this.#Z.path,W0.O_RDONLY|W0.O_NOFOLLOW);let G=await X.stat(),Y=h1(G,$);if(Y)return{status:"invalid",reason:Y};if(this.#$?.mtimeMs===G.mtimeMs&&this.#$.size===G.size)return this.#$.result;let z=new Uint8Array($1+1),{bytesRead:K}=await X.read(z,0,z.byteLength,0);if(K>$1)return{status:"invalid",reason:"manifest exceeds maximum size"};let W;try{W=q0(new TextDecoder().decode(z.subarray(0,K)))}catch(B){return{status:"invalid",reason:B instanceof Error?B.message:"invalid JSON"}}let Q;try{Q=w2(W,this.#Z.provider,this.#Z.serve)}catch(B){if(B instanceof N$){if(B.code!=="invalid-label"){let q={status:"ignored",reason:B.code};return this.#$={mtimeMs:G.mtimeMs,size:G.size,result:q},q}}return{status:"invalid",reason:B instanceof Error?B.message:"invalid manifest"}}let j={status:"ready",manifest:{version:Q.version,provider:this.#Z.provider,serve:this.#Z.serve,accounts:Q.accounts,superseded:Q.superseded,corruptLabels:Q.corruptLabels}};return this.#$={mtimeMs:G.mtimeMs,size:G.size,result:j},j}catch(G){return{status:"invalid",reason:`unreadable (${s(G)})`}}finally{await X?.close().catch(()=>{})}}}var iZ=30000,cZ=1e4,sZ=50,nZ=150,aZ=86400000,tZ=32,F0;function rV($){F0=$}var eV=["lock_busy","owner_invalid","renewal_failed"];class D$ extends Error{code;constructor($,Z){super($);this.code=Z}}class S2 extends D${constructor($){super($,"lock_busy")}}class I2 extends D${constructor($){super($,"owner_invalid")}}class U1 extends D${constructor($){super($,"renewal_failed")}}function oZ($){for(let Z of $){let J=Z.charCodeAt(0);if(J<32||J===127)return!1}return $.length>0&&$.length<=128&&$!=="."&&$!==".."&&!/[\\/:*?"<>|]/.test($)&&!/[. ]$/.test($)}function rZ($,Z){return`${Z($)}.stale-`}async function eZ($){let Z=K6($),J=rZ($,SZ),X;try{X=await T.readdir(Z,{withFileTypes:!0})}catch(Y){P.debug("claustrum","stale manifest lock reaper failed",{error:s(Y)});return}let G=0;for(let Y of X){if(G>=tZ)return;if(!Y.isDirectory()||!Y.name.startsWith(J))continue;let z=M0(Z,Y.name);try{let K=await T.lstat(z);if(!K.isDirectory()||Date.now()-K.mtimeMs<aZ)continue;await T.rm(z,{recursive:!0,force:!0}),G+=1}catch(K){P.debug("claustrum","stale manifest lock reaper failed",{error:s(K)})}}}async function s3($,Z){let J=`${$}.lock`,X=F0?.now??Date.now,G=F0?.setIntervalImpl??globalThis.setInterval,Y=F0?.clearIntervalImpl??globalThis.clearInterval,z=F0?.ttlMs??iZ,K=F0?.retryMinMs??sZ,W=F0?.retryMaxMs??nZ,Q=X(),V=m3(),j=M0(J,"owner");async function B(N){let D=M0(J,`owner.${process.pid}.${m3()}.tmp`),w;try{w=await T.open(D,W0.O_CREAT|W0.O_EXCL|W0.O_WRONLY,384),await w.writeFile(`${JSON.stringify({tenant:"anthropic-auth",pid:process.pid,claimed_at_ms:N,nonce:V})}
2
- `),await w.sync(),await w.close(),w=void 0,await T.rename(D,j)}finally{await w?.close().catch(()=>{}),await T.unlink(D).catch(()=>{})}}async function q(){try{await T.mkdir(J,{mode:448})}catch(N){if(s(N)!=="EEXIST")throw N;return!1}try{await B(X())}catch(N){throw await T.rm(J,{recursive:!0,force:!0}).catch(()=>{}),N}return!0}let H=Q+z,U=!1;while(!U){if(U=await q(),U)break;let N,D,w=!1;try{let v=JSON.parse(await T.readFile(j,"utf8"));if(k(v)&&typeof v.claimed_at_ms==="number"&&Number.isFinite(v.claimed_at_ms)&&typeof v.nonce==="string"&&oZ(v.nonce))N=v.claimed_at_ms,D=v.nonce,await F0?.afterStaleOwnerRead?.();else w=!0}catch(v){if(s(v)!=="ENOENT")w=!0}if(N!==void 0&&D!==void 0&&X()-N>=z){let v=`${J}.stale-${N}-${D}`;try{await T.rename(J,v)}catch(R0){if(!["ENOENT","EEXIST","ENOTEMPTY"].includes(s(R0)))throw R0}continue}if(X()>=H&&w)throw new I2("manifest lock owner invalid");if(X()>=H)throw new S2("manifest lock busy");let E=K+Math.floor(Math.random()*(W-K+1));await new Promise((v)=>setTimeout(v,Math.min(E,Math.max(1,H-X()))))}let x=!1,O;async function L(){if(x)return!1;try{let N=JSON.parse(await T.readFile(j,"utf8"));return k(N)&&N.pid===process.pid&&N.nonce===V&&typeof N.claimed_at_ms==="number"&&Number.isFinite(N.claimed_at_ms)&&X()-N.claimed_at_ms<z}catch{return!1}}async function M(){if(await O,!await L())throw new U1("manifest lock renewal failed; write aborted")}let F=G(()=>{O=B(X()).catch(()=>{x=!0})},F0?.renewalIntervalMs??Math.min(cZ,Math.floor(z/3)));if("unref"in F)F.unref();try{return await Z(M,V)}finally{if(Y(F),!await L())P.warn("claustrum","manifest lock lease lost, not releasing",{id:$});else await T.rm(J,{recursive:!0,force:!0}).catch(()=>{});await eZ(J)}}function t($,Z){return Z===void 0?{status:"refused",reason:$}:{status:"refused",reason:$,code:Z}}function E1($){return k($)&&$.provider==="anthropic"&&$.serve==="anthropic-auth"}async function $Q($){if(!q1($.entry.label)||!z6($.entry.handle)||!c3($.entry.credentialId,"anthropic"))return t("invalid entry");try{return await s3($.path,(Z,J)=>$J($,Z,J))}catch(Z){if(Z instanceof S2)return t("manifest lock busy",Z.code);if(Z instanceof I2)return t("manifest lock owner invalid",Z.code);if(Z instanceof U1)return t("manifest lock renewal failed; write aborted",Z.code);return t(`unreadable (${s(Z)})`)}}async function ZQ($){if(!q1($.entry.label)||!z6($.entry.handle)||!lZ($.entry.credentialId))return{status:"refused"};try{let Z=await s3($.path,async(J,X)=>{let G=$.expectedUid??process.getuid?.()??v1().uid,Y=K6($.path);try{if(T2(await T.lstat(Y),G))return"refused"}catch(O){return s(O)==="ENOENT"?"missing":"refused"}let z,K;try{let O=await T.lstat($.path);if(h1(O,G))return"refused";if(K=await T.open($.path,W0.O_RDONLY|W0.O_NOFOLLOW),h1(await K.stat(),G))return"refused";let F=new Uint8Array($1+1),{bytesRead:N}=await K.read(F,0,F.byteLength,0);if(N>$1)return"refused";let D=q0(new TextDecoder().decode(F.subarray(0,N)));if(!k(D)||D.version!==1||!Array.isArray(D.providers))return"refused";if(z=D,D.providers.some(E1))try{w2(D,"anthropic","anthropic-auth")}catch{return"refused"}}catch(O){if(s(O)==="ENOENT")return"missing";return"refused"}finally{await K?.close().catch(()=>{})}let W=z.providers;if(!Array.isArray(W))return"refused";let Q=W.findIndex(E1);if(Q===-1)return"missing";let V=W[Q];if(!E1(V)||!Array.isArray(V.accounts))return"refused";let j=(O)=>k(O)&&O.label===$.entry.label&&O.handle===$.entry.handle&&O.credential_id===$.entry.credentialId;if(V.accounts.findIndex(j)===-1)return"missing";let q=V.accounts.filter((O)=>!j(O)),H=JSON.stringify({...z,providers:W.map((O,L)=>L===Q?{...V,accounts:q}:O)},null,2);if(new TextEncoder().encode(H).byteLength>$1)return"refused";let U=M0(`${$.path}.lock`,`manifest.${X}.tmp`),x;try{x=await T.open(U,W0.O_CREAT|W0.O_EXCL|W0.O_WRONLY,384),await x.writeFile(H),await x.sync(),await x.close(),x=void 0,await J(),await F0?.beforeRename?.();try{await T.rename(U,$.path)}catch(O){if(s(O)==="ENOENT")throw new U1("manifest lock renewal failed; write aborted");throw O}return"removed"}catch(O){if(O instanceof U1)throw O;return"refused"}finally{await x?.close().catch(()=>{}),await T.unlink(U).catch(()=>{})}});return Z==="refused"?{status:"refused"}:Z}catch(Z){if(Z instanceof D$)return{status:"refused",code:Z.code};return{status:"refused"}}}async function $J($,Z,J){let X=$.expectedUid??process.getuid?.()??v1().uid,G=K6($.path);try{let H=T2(await T.lstat(G),X);if(H)return t(H)}catch(H){return t(`unreadable (${s(H)})`)}let Y,z=new Set,K;try{let H=await T.lstat($.path),U=h1(H,X);if(U)return t(U);K=await T.open($.path,W0.O_RDONLY|W0.O_NOFOLLOW);let x=h1(await K.stat(),X);if(x)return t(x);let O=new Uint8Array($1+1),{bytesRead:L}=await K.read(O,0,O.byteLength,0);if(L>$1)return t("manifest exceeds maximum size");let M=q0(new TextDecoder().decode(O.subarray(0,L)));if(!k(M)||M.version!==1||!Array.isArray(M.providers))return t("invalid manifest");if(Y=M,M.providers.some(E1))try{z=w2(M,"anthropic","anthropic-auth").corruptLabels}catch{return t("invalid manifest")}}catch(H){if(s(H)==="ENOENT")Y={version:1,providers:[]};else if(H instanceof SyntaxError)return t("invalid JSON");else return t(`unreadable (${s(H)})`)}finally{await K?.close().catch(()=>{})}let W=Y.providers;if(!Array.isArray(W))return t("invalid manifest");let Q=W.findIndex(E1),V;if(Q===-1)V=[...W,{provider:"anthropic",shape:"oauth",serve:"anthropic-auth",accounts:[{label:$.entry.label,handle:$.entry.handle,credential_id:$.entry.credentialId}]}];else{let H=W[Q];if(!E1(H)||!Array.isArray(H.accounts))return t("invalid manifest");let U=H.accounts.filter((M)=>k(M)&&M.label===$.entry.label);if(U.length===1&&U[0]?.handle===$.entry.handle&&U[0]?.credential_id===$.entry.credentialId&&H.shape==="oauth"&&!z.has($.entry.label))return{status:"unchanged"};let x={...z.has($.entry.label)?{}:U.find(k)??{},label:$.entry.label,handle:$.entry.handle,credential_id:$.entry.credentialId},O=H.accounts.flatMap((M)=>k(M)&&M.label===$.entry.label?[]:[M]),L=H.accounts.findIndex((M)=>k(M)&&M.label===$.entry.label);O.splice(L===-1?O.length:L,0,x),V=W.map((M,F)=>F===Q?{...H,shape:"oauth",accounts:O}:M)}let j=JSON.stringify({...Y,providers:V},null,2);if(new TextEncoder().encode(j).byteLength>$1)return t("manifest exceeds maximum size");let B=M0(`${$.path}.lock`,`manifest.${J}.tmp`),q;try{q=await T.open(B,W0.O_CREAT|W0.O_EXCL|W0.O_WRONLY,384),await q.writeFile(j),await q.sync(),await q.close(),q=void 0,await Z(),await F0?.beforeRename?.();try{await T.rename(B,$.path)}catch(H){if(s(H)==="ENOENT")throw new U1("manifest lock renewal failed; write aborted");throw H}return{status:"written"}}catch(H){if(H instanceof U1)throw H;return t(`unreadable (${s(H)})`)}finally{await q?.close().catch(()=>{}),await T.unlink(B).catch(()=>{})}}class f2{#$;#Z;#G;#Y;#z=null;#J=0;#X=!1;constructor($,Z,J,X){this.#$=$,this.#Z=Z,this.#G=J,this.#Y=X}static async connect($={}){let Z=$.connectionFile??W6(),J=$.connector??((G)=>B1.connect(G)),X=await J({connectionFile:Z,handshakeTimeoutMs:$.handshakeTimeoutMs});return new f2(X,J,Z,$.handshakeTimeoutMs)}async catalogList($){return this.#$.catalogList($)}async routeOpen($,Z,J={}){return this.#$.routeOpen($,Z,{...J,consumerIdentity:null})}async request($,Z,J={}){return this.#$.request($,Z,J)}async call($,Z,J,X={}){try{return await this.#$.call($,Z,J,{...X,consumerIdentity:null})}catch(G){if(!this.#V(G))throw G;return await this.#K(),this.#$.call($,Z,J,{...X,consumerIdentity:null})}}subscribe($,Z,J,X={}){return this.#$.subscribe($,Z,J,X)}async closeRoute($,Z={}){return this.#$.closeRoute($,Z)}async closeManagedRoute($,Z,J={}){return this.#$.closeManagedRoute($,Z,{...J,consumerIdentity:null})}close(){this.#X=!0,this.#$.close()}#V($){return!this.#X&&$ instanceof $0&&$.kind==="terminal"&&$.code!=="missing_identity"&&$.code!=="invalid_control_body"}async#K(){if(this.#X)throw Error("Claustrum client is closed");if(this.#z){await this.#z;return}let $=Date.now();if($<this.#J)throw Error("Claustrum client reconnect is backed off");this.#J=$+n3,this.#z=this.#Z({connectionFile:this.#G,handshakeTimeoutMs:this.#Y}).then((Z)=>{if(this.#X)throw Z.close(),Error("Claustrum client is closed");let J=this.#$;this.#$=Z,J.close()}).finally(()=>{this.#z=null}),await this.#z}}function ZJ($={}){return f2.connect($)}var u3="claustrum",JJ=120000,n3=60000,l3=["transient","permanent","auth_required","context_overflow"];class L$ extends Error{code;action;errorClass;constructor($,Z,J,X){super($);this.code=Z,this.action=X,this.name="ClaustrumCredentialError",this.errorClass=J}}function XJ($){switch($){case"permanent":return"gone";case"auth_required":return"reauth";case"context_overflow":return"reduce_and_retry";case"transient":return"retry"}}function q$($,Z="invalid_response"){let J=k($)&&k($.result)?$.result:void 0,X=J&&k(J.error)?J.error:void 0,G=X?.class,Y=typeof G==="string"&&l3.includes(G)?G:"transient";if(typeof G!=="string"||!l3.includes(G))P.warn("claustrum","unrecognised credential error class",{errorClass:G??null});let z=X&&typeof X.code==="string"?X.code:Z;return new L$(`Claustrum credential request failed: ${z}`,z,Y,XJ(Y))}function d3($){if($ instanceof L$)return $;if($ instanceof $0&&$.kind==="terminal")return P.warn("claustrum","terminal credential call failed",{code:$.code??null,message:$.message}),new L$(`Claustrum credential request failed: ${$.message}`,$.code??"terminal_error","transient","retry");let Z=$ instanceof Error?$.message:String($),J=k($)&&typeof $.code==="string"?$.code:"transport_error";return new L$(`Claustrum credential request failed: ${Z}`,J,"transient","retry")}function GJ($){let Z=k($)&&k($.result)?$.result:void 0;if(Z&&k(Z.error))throw q$($);let J=Z?.payload;if(!Array.isArray(J)||J.length===0||!J.every((K)=>typeof K==="number"&&Number.isInteger(K)&&K>=0&&K<=255))throw q$($);let X=Z?.record_version;if(typeof X!=="number"||!Number.isSafeInteger(X)||X<0)throw q$($,"invalid_record_version");let G=Z?.expires_at_ms,Y=G===null||G===void 0?null:typeof G==="number"&&Number.isFinite(G)?G:void 0;if(Y===void 0)throw q$($,"invalid_expiry");return{payload:new TextDecoder().decode(Uint8Array.from(J)),expiresAtMs:Y,recordVersion:X,...typeof Z?.project_id==="string"&&{projectId:Z.project_id},...typeof Z?.account_id==="string"&&{accountId:Z.account_id},...typeof Z?.credential_id==="string"&&{credentialId:Z.credential_id}}}class a3{#$=new Map;#Z=new Map;#G;#Y;#z;#J=new Map;#X;constructor($,Z={}){if(this.#G=$,this.#Y=Z.identity,this.#z=Z.now??Date.now,this.#X=Z.minTtlMs??JJ,!Number.isSafeInteger(this.#X)||this.#X<0)throw RangeError("minTtlMs must be a non-negative safe integer")}async get($,Z=this.#X,J={}){if(!Number.isSafeInteger(Z)||Z<0)throw RangeError("minTtlMs must be a non-negative safe integer");let X=this.#z(),G=this.#$.get($);if(G&&G.expiresAtMs!==null&&G.expiresAtMs>X){if(G.expiresAtMs-X<=Z)this.#V($,X,Z);return G}if(G)this.#$.delete($),this.#J.delete($);let Y=this.#Z.get($);if(Y)return Y;let z=this.#K($,Z,J.cacheIf);this.#Z.set($,z);try{return await z}finally{if(this.#Z.get($)===z)this.#Z.delete($)}}peek($){return this.#$.get($)}abandonPending($){this.#Z.delete($)}seedForTest($,Z){this.#$.set($,Z)}reduceMinTtlMs(){return this.#X=Math.floor(this.#X/2),this.#X}async reportAuthFailure($,Z,J,X){let G=typeof Z==="number"?Z:typeof J==="number"?J:401,z=(typeof Z==="number"?typeof J==="object"&&J!==null?J:void 0:Z)?.recordVersion;if(typeof z!=="number"||!Number.isSafeInteger(z)||z<0)throw TypeError("record_version is required from the credential served to the provider");try{let K;try{K=await this.#G.call(u3,"credential.report_auth_failure",{handle:$,provider_status:G,record_version:z,...X?{reporter_source:X}:{}},{identity:this.#Y})}catch(Q){throw d3(Q)}let W=k(K)&&k(K.result)?K.result:void 0;if(W&&k(W.error))throw q$(K)}finally{this.invalidate($,z)}}invalidate($,Z){let J=this.#$.get($);if(J&&(Z===void 0||J.recordVersion===Z))this.#$.delete($)}close(){this.#G.close()}#V($,Z,J){if(this.#Z.has($))return;let X=this.#J.get($);if(X!==void 0&&X>Z)return;this.#J.set($,Z+n3);let G=this.#K($,J);this.#Z.set($,G),G.catch(()=>{}).finally(()=>{if(this.#Z.get($)===G)this.#Z.delete($)})}async#K($,Z,J){let X;try{X=await this.#G.call(u3,"credential.get",{handle:$,force_refresh:!1,min_ttl_ms:Z},{identity:this.#Y})}catch(z){throw d3(z)}let G=GJ(X),Y={payload:G.payload,expiresAtMs:G.expiresAtMs,recordVersion:G.recordVersion,...G.projectId!==void 0&&{projectId:G.projectId},...G.accountId!==void 0&&{accountId:G.accountId},...G.credentialId!==void 0&&{credentialId:G.credentialId}};if(Y.expiresAtMs!==null&&Y.expiresAtMs>this.#z()&&(J?.()??!0))this.#$.set($,Y);return Y}}async function JQ($={}){if($.enabled!==!0)return null;let{enabled:Z,identity:J,now:X,minTtlMs:G,...Y}=$,z=await ZJ(Y);return new a3(z,{identity:J,now:X,minTtlMs:G})}var t3=new Set(["EAI_AGAIN","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETUNREACH","ENOTFOUND","ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT"]);function o3($,Z){if(!$||typeof $!=="object")return;let J=$[Z];return typeof J==="string"?J:void 0}function Z1($){let Z=o3($,"code");if(Z&&t3.has(Z))return!0;let J=$ instanceof Error?$.message:o3($,"message")??String($);if(J.includes("fetch failed"))return!0;return[...t3].some((X)=>J.includes(X))}function r3($){let Z="";for(let J of $)Z+=String.fromCharCode(J);return btoa(Z).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function e3(){let $=new Uint8Array(64);crypto.getRandomValues($);let Z=r3($),J=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z));return{verifier:Z,challenge:r3(new Uint8Array(J)),method:"S256"}}function h2($){if(!$)return;let Z=Number($);if(Number.isFinite(Z)&&Z>0)return Math.ceil(Z);let J=Date.parse($);if(Number.isFinite(J)){let X=Math.ceil((J-Date.now())/1000);return X>0?X:void 0}return}class k2 extends Error{status;body;retryAfter;isRefreshError=!0;constructor($,Z,J){super(`Claude OAuth refresh failed: ${$} — ${Z}`);this.status=$,this.body=Z,this.name="ClaudeOAuthRefreshError",this.retryAfter=h2(J??void 0)}}async function X5($){if(y1($.refreshToken,"anthropic"),typeof $.refreshToken!=="string"||!$.refreshToken.trim())throw Error("Local OAuth refresh credential is unavailable");let Z=$.fetchImpl??fetch,J=$.maxRetries??2,X=$.baseDelayMs??500,G=$.setTimeoutImpl??globalThis.setTimeout;for(let Y=0;Y<=J;Y++)try{if(Y>0){let Q=X*2**(Y-1);await new Promise((V)=>G(V,Q))}let z=await Z(E2,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":v2},body:JSON.stringify({grant_type:"refresh_token",refresh_token:$.refreshToken,client_id:Q6,scope:J5})});if(!z.ok){if(z.status>=500&&Y<J){await z.body?.cancel().catch(()=>{});continue}let Q=await z.text().catch(()=>"");throw new k2(z.status,Q,z.headers.get("retry-after"))}let K=await z.json(),W=$.now?.()??Date.now();return{access:K.access_token,refresh:K.refresh_token??$.refreshToken,expires:W+K.expires_in*1000,expiresIn:K.expires_in,authLineageId:$.authLineageId}}catch(z){if(z instanceof k2)throw z;if(Y<J&&Z1(z))continue;throw z}throw Error("Token refresh exhausted all retries")}function YJ(){return crypto.randomUUID().replace(/-/g,"")}function zJ($){let Z=$.trim();try{let z=new URL(Z),K=z.searchParams.get("code"),W=z.searchParams.get("state");if(K&&W)return{code:K,state:W}}catch{}let J=Z.split("#");if(J.length===2&&J[0]&&J[1])return{code:J[0],state:J[1]};let X=new URLSearchParams(Z),G=X.get("code"),Y=X.get("state");if(G&&Y)return{code:G,state:Y};return null}async function KJ($,Z,J){let X=await fetch(E2,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":v2},body:JSON.stringify({code:$.code,state:$.state,grant_type:"authorization_code",client_id:Q6,redirect_uri:J,code_verifier:Z})});if(!X.ok)return{type:"failed"};let G=await X.json();return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+G.expires_in*1000}}async function QQ($){let Z=await e3(),J=YJ(),X=new URL($5[$],import.meta.url);return X.searchParams.set("code","true"),X.searchParams.set("client_id",Q6),X.searchParams.set("response_type","code"),X.searchParams.set("redirect_uri",b2),X.searchParams.set("scope",Z5.join(" ")),X.searchParams.set("code_challenge",Z.challenge),X.searchParams.set("code_challenge_method","S256"),X.searchParams.set("state",J),{url:X.toString(),redirectUri:b2,state:J,verifier:Z.verifier}}async function jQ($,Z,J,X){let G=zJ($);if(!G)return{type:"failed"};if(X&&G.state!==X)return{type:"failed"};return KJ(G,Z,J)}import{createHash as WJ}from"node:crypto";function A0($){return WJ("sha256").update($).digest("hex").slice(0,16)}var HJ=globalThis.setTimeout.bind(globalThis),BJ=globalThis.clearTimeout.bind(globalThis),D5="anthropic-auth.json",qJ="anthropic-auth-state.json",UJ="https://api.anthropic.com/api/oauth/usage",d1=["five_hour","seven_day","scoped","extraUsage","bindingWindow","fallbackAdvised"];function p2($){return $.access==null&&($.refresh==null||$.refresh==="")}function A($){return $.type==="oauth"}function u2($){return $.type==="api"}function M5($){let Z=$?.trim();if(!Z)return!1;try{let J=new URL(Z);return(J.protocol==="http:"||J.protocol==="https:")&&!J.username&&!J.password}catch{return!1}}function FQ($){return $.costZeroing?.enabled!==!1}var LJ=[401,403,429],_5=240,NJ=_5,xJ=10,l2=300000,OJ=3600000,C5=86400000,DJ=60000,MJ=900000,_J=300000,CJ=5,Y5={five_hour:0,seven_day:0},RJ=!0,PJ=60000,FJ=60000,j6=600000,AJ=1e4,wJ=100;function TJ(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return p1(process.env.XDG_CONFIG_HOME||p1(QJ(),".config"),"opencode")}function I(){return process.env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim()||p1(TJ(),D5)}function P$($=I()){let Z=process.env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim();if(Z)return Z;return $.endsWith(D5)?p1(n2($),qJ):`${$}.state.json`}function _($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function z5($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():J1(),label:typeof $.label==="string"?$.label:void 0,enabled:typeof $.enabled==="boolean"?$.enabled:void 0,addedAt:typeof $.addedAt==="number"?$.addedAt:void 0,lastUsed:typeof $.lastUsed==="number"?$.lastUsed:void 0}}function R5($){if(!_($))return null;if($.type==="api"){let G=typeof $.baseURL==="string"?$.baseURL.trim():"",Y=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!M5(G))return null;let z=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...z5($),type:"api",apiKey:Y||void 0,baseURL:G,authHeader:z}}if($.type!=="oauth")return null;let Z=typeof $.refresh==="string"?$.refresh:"",J=$.enabled===!0&&typeof $.id==="string"&&Boolean($.id.trim())&&typeof $.label==="string"&&Boolean($.label.trim())&&p2($),X=typeof $.claustrumScopedCredentialId==="string"&&Boolean($.claustrumScopedCredentialId.trim())&&typeof $.anthropicAccountUuid==="string"&&Boolean($.anthropicAccountUuid.trim())&&p2($);if(!Z.trim()&&!J&&!X)return null;return{...z5($),type:"oauth",authLineageId:typeof $.authLineageId==="string"&&$.authLineageId.trim()?$.authLineageId:void 0,anthropicAccountUuid:typeof $.anthropicAccountUuid==="string"&&$.anthropicAccountUuid.trim()?$.anthropicAccountUuid.trim():void 0,claustrumHandle:typeof $.claustrumHandle==="string"&&$.claustrumHandle.trim()?$.claustrumHandle.trim():void 0,claustrumScopedCredentialId:typeof $.claustrumScopedCredentialId==="string"&&$.claustrumScopedCredentialId.trim()?$.claustrumScopedCredentialId.trim():void 0,claustrumScopedState:typeof $.claustrumScopedState==="string"&&$.claustrumScopedState.trim()?$.claustrumScopedState.trim():void 0,access:typeof $.access==="string"?$.access:void 0,refresh:Z,expires:typeof $.expires==="number"?$.expires:void 0,lastRefreshedAt:typeof $.lastRefreshedAt==="number"?$.lastRefreshedAt:void 0,lastRefreshError:K5($.lastRefreshError),lastQuotaRefreshError:K5($.lastQuotaRefreshError),quota:SJ($.quota),profile:M$($.profile),prime:a2($.prime)}}function M$($){if(!_($))return;if(typeof $.tier!=="string"||!$.tier.trim()||typeof $.orgType!=="string"||!$.orgType.trim()||typeof $.checkedAt!=="number"||!Number.isFinite($.checkedAt))return;return{tier:$.tier.trim(),orgType:$.orgType.trim(),checkedAt:$.checkedAt,...typeof $.accountIdentity==="string"&&$.accountIdentity.trim()&&{accountIdentity:$.accountIdentity.trim()},...typeof $.providerAccountUuid==="string"&&$.providerAccountUuid.trim()&&{providerAccountUuid:$.providerAccountUuid.trim()},...typeof $.tokenFingerprint==="string"&&$.tokenFingerprint.trim()&&{tokenFingerprint:$.tokenFingerprint.trim()}}}function K5($){if(!_($))return;if(typeof $.message!=="string")return;let Z=Number($.checkedAt);if(!Number.isFinite(Z))return;let J=Number($.nextRetryAt),X=Number($.retryCount),G=Number($.status);return{message:$.message,checkedAt:Z,nextRetryAt:Number.isFinite(J)?J:void 0,retryCount:Number.isFinite(X)?X:void 0,accountIdentity:typeof $.accountIdentity==="string"&&$.accountIdentity.trim()?$.accountIdentity.trim():void 0,tokenHash:typeof $.tokenHash==="string"?$.tokenHash:void 0,refreshTokenFingerprint:typeof $.refreshTokenFingerprint==="string"&&$.refreshTokenFingerprint.trim()?$.refreshTokenFingerprint.trim():void 0,status:Number.isFinite(G)?G:void 0,permanent:typeof $.permanent==="boolean"?$.permanent:void 0}}function W5($){if(!_($))return;let Z=Number($.usedPercent),J=Number($.remainingPercent),X=Number($.checkedAt);if(!Number.isFinite(Z)||!Number.isFinite(J)||!Number.isFinite(X))return;return{usedPercent:Z,remainingPercent:J,checkedAt:X,resetsAt:typeof $.resetsAt==="string"?$.resetsAt:void 0}}function a2($){if(!_($))return;let Z=Number($.count),J=Number($.inputTokens),X=Number($.outputTokens),G=Number($.since);if(![Z,J,X,G].every(Number.isFinite)||Z<0||J<0||X<0||G<0)return;return{count:Math.floor(Z),inputTokens:Math.floor(J),outputTokens:Math.floor(X),since:Math.floor(G)}}function SJ($){if(!_($))return;let Z={};for(let J of["five_hour","seven_day"]){let X=W5($[J]);if(X)Z[J]=X}if(typeof $.checkedAt==="number"&&Number.isFinite($.checkedAt))Z.checkedAt=$.checkedAt;if(typeof $.accountIdentity==="string"&&$.accountIdentity.trim())Z.accountIdentity=$.accountIdentity.trim();if(Array.isArray($.scoped)){let J=$.scoped.map((X)=>{if(!_(X))return;let G=W5(X);if(!G)return;if(typeof X.id!=="string"||!X.id.trim())return;if(typeof X.title!=="string"||!X.title.trim())return;if(typeof X.modelName!=="string"||!X.modelName.trim())return;let Y=typeof X.modelId==="string"&&X.modelId.trim()?X.modelId.trim():void 0;return{...G,id:X.id.trim(),title:X.title.trim(),...Y&&{modelId:Y},modelName:X.modelName.trim()}}).filter((X)=>X!=null);Z.scoped=J}if(_($.extraUsage)){let J=V5($.extraUsage.used),X=V5($.extraUsage.limit);if(J&&X&&typeof $.extraUsage.exhausted==="boolean")Z.extraUsage={used:J,limit:X,...typeof $.extraUsage.utilizationPercent==="number"&&Number.isFinite($.extraUsage.utilizationPercent)&&{utilizationPercent:$.extraUsage.utilizationPercent},...typeof $.extraUsage.severity==="string"&&{severity:$.extraUsage.severity},exhausted:$.extraUsage.exhausted}}if(typeof $.bindingWindow==="string"&&$.bindingWindow.trim())Z.bindingWindow=$.bindingWindow.trim();if($.bindingWindowSource==="poll"||$.bindingWindowSource==="headers")Z.bindingWindowSource=$.bindingWindowSource;if(typeof $.fallbackAdvised==="boolean")Z.fallbackAdvised=$.fallbackAdvised;if($.source==="poll"||$.source==="headers")Z.source=$.source;if(_($.fieldSources)){let J={};for(let X of d1){if(Z[X]===void 0)continue;let G=$.fieldSources[X];if(G==="poll"||G==="headers")J[X]=G}if(Object.keys(J).length>0)Z.fieldSources=J}return Object.keys(Z).length?Z:void 0}function V5($){if(!_($))return;if(typeof $.amountMinor!=="number"||!Number.isFinite($.amountMinor)||typeof $.currency!=="string"||!$.currency.trim()||typeof $.exponent!=="number"||!Number.isFinite($.exponent))return;return{amountMinor:$.amountMinor,currency:$.currency.trim(),exponent:$.exponent}}function a(){return{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]}}function IJ($){if(!_($)||!Array.isArray($.accounts))return null;return{version:1,mainAccountId:typeof $.mainAccountId==="string"&&$.mainAccountId.trim()?$.mainAccountId.trim():void 0,main:{type:"opencode",provider:"anthropic",profile:M$(_($.main)?$.main.profile:void 0)},routing:_($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((Z)=>Number.isInteger(Z)):void 0,refresh:_($.refresh)?$.refresh:void 0,quota:_($.quota)?$.quota:void 0,quotaHeaderFeed:_($.quotaHeaderFeed)?$.quotaHeaderFeed:void 0,claudeCache:_($.claudeCache)?$.claudeCache:void 0,dump:_($.dump)?$.dump:void 0,claudeFast:_($.claudeFast)?$.claudeFast:void 0,thinkingBinding:_($.thinkingBinding)?$.thinkingBinding:void 0,costZeroing:_($.costZeroing)?$.costZeroing:void 0,cacheKeep:_($.cacheKeep)?$.cacheKeep:void 0,relay:_($.relay)?$.relay:void 0,claustrum:P5($.claustrum),logging:_($.logging)?$.logging:void 0,killswitch:_($.killswitch)?$.killswitch:void 0,prime:(()=>{if(!_($.prime))return;let Z=typeof $.prime.enabled==="boolean"?$.prime.enabled:void 0,J=a2($.prime.main),X=typeof $.prime.mainAuthLineageId==="string"&&$.prime.mainAuthLineageId.trim()?$.prime.mainAuthLineageId:void 0,G=typeof $.prime.mainAuthLineageRefreshTokenFingerprint==="string"&&$.prime.mainAuthLineageRefreshTokenFingerprint.trim()?$.prime.mainAuthLineageRefreshTokenFingerprint:void 0;if(Z===void 0&&!J&&!X&&!G)return;return{...Z!==void 0&&{enabled:Z},...J&&{main:J},...X&&{mainAuthLineageId:X},...G&&{mainAuthLineageRefreshTokenFingerprint:G}}})(),accounts:$.accounts.map(R5).filter((Z)=>Z!=null)}}function P5($){if(!_($))return;let Z=$.mode==="local"||$.mode==="claustrum"?$.mode:void 0,J=typeof $.handlesFile==="string"&&$.handlesFile.trim()?$.handlesFile.trim():void 0,X=_($.primaryAccount)?$.primaryAccount:void 0,G=X&&typeof X.credentialId==="string"&&X.credentialId.trim()&&typeof X.accountId==="string"&&X.accountId.trim()&&typeof X.state==="string"?{credentialId:X.credentialId.trim(),accountId:X.accountId.trim(),state:X.state}:void 0,Y=$.scopedRoster===!0,z=Array.isArray($.disabledAccountIdentities)?[...new Set($.disabledAccountIdentities.filter((W)=>typeof W==="string"&&W.trim().length>0).map((W)=>W.trim()))]:[],K=_($.accounts)?Object.fromEntries(Object.entries($.accounts).flatMap(([W,Q])=>{if(!_(Q))return[];return[[W,{...typeof Q.enabled==="boolean"&&{enabled:Q.enabled}}]]})):void 0;if(!Z&&!J&&!Y&&z.length===0&&(!K||Object.keys(K).length===0))return;return{...Z&&{mode:Z},...Y&&{scopedRoster:!0},...G&&{primaryAccount:G},...z.length>0&&{disabledAccountIdentities:z},...J&&{handlesFile:J},...K&&Object.keys(K).length>0&&{accounts:K}}}async function G1($){try{return{exists:!0,value:q0(await B6($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};let J=Z instanceof Error?Z.message:String(Z);throw Error(`account store at ${$} is corrupt or unreadable (${J}) — fix or remove it`)}}function x1($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function U6($){return typeof $==="number"&&Number.isFinite($)?$:0}function M1($,Z){if(Z===void 0||!Number.isFinite(Z))return $;if($===void 0||!Number.isFinite($))return Z;return Math.max($,Z)}function fJ($,Z){if(Z===void 0||!Number.isFinite(Z))return $;if($===void 0||!Number.isFinite($))return Z;return Math.max($,Z)}function d2($){return Math.max(U6($.lastRefreshedAt),U6($.lastUsed),U6($.addedAt))}function bJ($,Z){if($.type!=="oauth")return!1;if(typeof $.refresh!=="string"||!$.refresh.trim())return!1;if(!Boolean(typeof $.access==="string"&&typeof Z.access==="string"&&$.access!==Z.access||typeof $.refresh==="string"&&typeof Z.refresh==="string"&&$.refresh!==Z.refresh))return!1;return d2($)>d2(Z)}function F5($,Z){if(typeof $.claustrumScopedCredentialId==="string"&&typeof $.anthropicAccountUuid==="string"){let X={...Z.claustrumScopedCredentialId===$.claustrumScopedCredentialId&&Z.anthropicAccountUuid===$.anthropicAccountUuid?Z:{},...$,refresh:""};return delete X.access,delete X.expires,delete X.lastRefreshedAt,delete X.lastRefreshError,delete X.claustrumHandle,X}if(bJ($,Z)){let J={...Z,...$},X=d2($);if(X>U6(J.lastRefreshedAt))J.lastRefreshedAt=X;return delete J.quota,delete J.lastRefreshError,delete J.lastQuotaRefreshError,J}return{...$,...Z}}function kJ($){if($.type!=="api"&&$.type!=="oauth")return!0;if($.type==="api"&&"baseURL"in $&&(typeof $.baseURL!=="string"||!M5($.baseURL)))return!0;if($.type==="oauth"&&"refresh"in $&&(typeof $.refresh!=="string"||!$.refresh.trim()))return!0;return!1}function EJ($,Z){if(!_($))return $;let J=_(Z)?Z:{},X=_(J.main)?J.main:void 0,G=_(J.accounts)?J.accounts:{},Y=_($.quota)?$.quota:{},z=_($.refresh)?$.refresh:{},K=X??Y,W=X??z,Q=typeof X?.quotaErrorClearedAt==="number"&&Number.isFinite(X.quotaErrorClearedAt)&&X.quotaErrorClearedAt>=0?X.quotaErrorClearedAt:void 0,V=typeof X?.refreshErrorClearedAt==="number"&&Number.isFinite(X.refreshErrorClearedAt)&&X.refreshErrorClearedAt>=0?X.refreshErrorClearedAt:void 0,j=Y.mainLastQuotaApiError,B=X?.lastQuotaApiError??(Q!==void 0&&_(j)&&typeof j.checkedAt==="number"&&j.checkedAt<=Q?void 0:j),q=z.mainLastRefreshError,H=X?.lastRefreshError??(V!==void 0&&_(q)&&typeof q.checkedAt==="number"&&q.checkedAt<=V?void 0:q),U=Array.isArray($.accounts)?$.accounts.map((x)=>{if(!_(x))return x;let O=typeof x.id==="string"?x.id:void 0,L=O?G[O]??G[O.trim()]:void 0,M=_(L)?L:{};return F5(x,M)}):[];return{...$,main:{type:"opencode",provider:"anthropic",profile:M$(X?.profile)},refresh:x1({...z,mainLastRefreshError:H,mainRefreshErrorClearedAt:W.refreshErrorClearedAt,mainRefreshLeaseId:W.refreshLeaseId,mainRefreshLeaseUntil:W.refreshLeaseUntil,mainRefreshLeaseTokenHash:W.refreshLeaseTokenHash}),quota:x1({...Y,mainQuota:K.quota,mainQuotaCheckedAt:K.quotaCheckedAt,mainQuotaToken:K.quotaToken,mainLastQuotaApiError:B,mainQuotaErrorGeneration:K.quotaErrorGeneration,mainQuotaErrorClearedAt:K.quotaErrorClearedAt}),prime:(()=>{let x=_($.prime)?$.prime:void 0,O=a2(X?.prime),L=typeof X?.primeAuthLineageId==="string"&&X.primeAuthLineageId.trim()?X.primeAuthLineageId:void 0,M=typeof X?.primeAuthLineageRefreshTokenFingerprint==="string"&&X.primeAuthLineageRefreshTokenFingerprint.trim()?X.primeAuthLineageRefreshTokenFingerprint:void 0;if(!x&&!O&&!L&&!M)return;return{...x&&typeof x.enabled==="boolean"&&{enabled:x.enabled},...O&&{main:O},...L&&{mainAuthLineageId:L},...M&&{mainAuthLineageRefreshTokenFingerprint:M}}})(),accounts:U}}async function f($=I()){let Z=await G1($),J=await G1(P$($));if(!Z.exists&&!J.exists)return null;let X=Z.exists?Z.value:a();return IJ(EJ(X,J.value))}async function O6($){let Z=await G1($);return _(Z.value)?Z.value:{}}function vJ($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function hJ($){return x1({id:$.id,label:$.label,type:$.type,enabled:$.enabled,addedAt:$.addedAt,baseURL:$.type==="api"?$.baseURL:void 0,authHeader:$.type==="api"?$.authHeader:void 0,claustrumScopedCredentialId:$.type==="oauth"?$.claustrumScopedCredentialId:void 0,anthropicAccountUuid:$.type==="oauth"&&$.claustrumScopedCredentialId?$.anthropicAccountUuid:void 0})}function y2($){if($.type==="api")return x1({apiKey:$.apiKey,lastUsed:$.lastUsed});return x1({authLineageId:$.authLineageId,anthropicAccountUuid:$.anthropicAccountUuid,claustrumHandle:$.claustrumHandle,claustrumScopedCredentialId:$.claustrumScopedCredentialId,claustrumScopedState:$.claustrumScopedState,access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota,profile:$.profile,prime:$.prime})}function T0($){return Math.max($?.five_hour?.checkedAt??0,$?.seven_day?.checkedAt??0,...$?.scoped?.map((Z)=>Z.checkedAt)??[],$?.checkedAt??0)}function u1($){if($?.source==="poll")return 2;if($?.source==="headers")return 1;return 0}function yJ($,Z){if(!("scoped"in $))return Z.scoped;if(!Array.isArray($.scoped)||$.scoped.length===0)return $.scoped;if(!Array.isArray(Z.scoped)||Z.scoped.length===0)return $.scoped;let J=new Map(Z.scoped.map((X)=>[X.id,X]));for(let X of $.scoped){let G=J.get(X.id);if(!G||X.checkedAt>=G.checkedAt)J.set(X.id,X)}return[...J.values()]}function Q5($,Z,J){let X=$[J],G=Z[J];if(!G)return X;if(!X)return G;if(G.checkedAt>X.checkedAt)return G;if(G.checkedAt<X.checkedAt)return X;return u1($)>u1(Z)?X:G}function n0($,Z){if(!$||$[Z]===void 0)return;return $.fieldSources?.[Z]??($.source==="poll"||$.source==="headers"?$.source:void 0)}function gJ($,Z,J){let X={};for(let G of d1){if(J[G]===void 0)continue;if(G==="scoped"||G==="extraUsage"){X[G]="poll";continue}if(G==="bindingWindow"&&$.bindingWindowSource==="poll"&&$.bindingWindow===J.bindingWindow){X[G]="poll";continue}if(G==="fallbackAdvised"&&Z.fieldSources?.fallbackAdvised===void 0){let z=n0($,G);if(z)X[G]=z;continue}let Y=Z[G]===J[G]?n0(Z,G):$[G]===J[G]?n0($,G):n0($,G)??n0(Z,G);if(Y)X[G]=Y}return Object.keys(X).length>0?X:void 0}function A5($,Z){if(!$||Z.source!=="headers")return Z;let J=$.bindingWindowSource==="poll",X={...$,...Z,five_hour:Q5($,Z,"five_hour"),seven_day:Q5($,Z,"seven_day"),scoped:yJ($,Z),extraUsage:$.extraUsage??Z.extraUsage,fallbackAdvised:Z.fieldSources?.fallbackAdvised!==void 0?Z.fallbackAdvised:$.fallbackAdvised??Z.fallbackAdvised,bindingWindow:J?$.bindingWindow:Z.bindingWindow??$.bindingWindow,bindingWindowSource:J?"poll":Z.bindingWindowSource??$.bindingWindowSource},G=gJ($,Z,X);return{...X,...G&&{fieldSources:G}}}function i2($,Z,J=!1){if(!_($))return Z;let X={...Z};if(!J)delete X.claustrumHandle;let G=$,Y=Boolean(G.access&&X.access&&G.access!==X.access||G.refresh&&X.refresh&&G.refresh!==X.refresh),z=Boolean(!Y&&X.quota?.source==="headers"),K=z&&X.quota?{...X,quota:A5(G.quota,X.quota)}:X;if(G.refresh===x$("anthropic")&&(typeof K.access==="string"&&K.access.length>0||typeof K.refresh==="string"&&K.refresh!==x$("anthropic"))&&(!K.authLineageId||K.authLineageId===G.authLineageId)){P.warn("accounts","discarded stale credential write over a custody tombstone");let{access:q,refresh:H,expires:U,...x}=K;return i2(G,x,J)}let W=(()=>{let q=G.lastRefreshError,H=K.lastRefreshError;if(!q)return H;if(H)return H.checkedAt>=q.checkedAt?H:q;return(K.lastRefreshedAt??0)>(G.lastRefreshedAt??0)?void 0:q})(),Q=T0(G.quota),V=T0(K.quota),j=Boolean(Q===V&&u1(G.quota)>u1(K.quota));if(!z&&(Q>V||j)){let q=G.lastRefreshedAt??0,H=K.lastRefreshedAt??0;if(Y&&H<=q){let x={...G};if(typeof K.lastUsed==="number"&&(typeof G.lastUsed!=="number"||K.lastUsed>G.lastUsed))x.lastUsed=K.lastUsed;return x}let U={...G,...K};if(Y){if(!("profile"in K))delete U.profile;if(K.quota?.source)U.quota=K.quota;else delete U.quota;if(!("lastQuotaRefreshError"in K))delete U.lastQuotaRefreshError;return U.lastRefreshError=W,U}return{...U,quota:G.quota,lastQuotaRefreshError:G.lastQuotaRefreshError,lastRefreshError:W}}let B={...G,...K};if(Y){if(!("profile"in K))delete B.profile;if(!K.quota?.source)delete B.quota}if(!("lastQuotaRefreshError"in K))delete B.lastQuotaRefreshError;return B.lastRefreshError=W,B}function D6($){let Z=$.refresh?x1({enabled:$.refresh.enabled,intervalMinutes:$.refresh.intervalMinutes,refreshBeforeExpiryMinutes:$.refresh.refreshBeforeExpiryMinutes}):void 0,J=$.quota?x1({enabled:$.quota.enabled,checkIntervalMinutes:$.quota.checkIntervalMinutes,refreshEveryNRequests:$.quota.refreshEveryNRequests,minimumRemaining:$.quota.minimumRemaining,failClosedOnUnknownQuota:$.quota.failClosedOnUnknownQuota,showToasts:$.quota.showToasts}):void 0;return vJ({version:1,mainAccountId:$.mainAccountId,main:{type:"opencode",provider:"anthropic"},routing:$.routing,fallbackOn:$.fallbackOn,refresh:Z,quota:J,quotaHeaderFeed:$.quotaHeaderFeed,claudeCache:$.claudeCache,dump:$.dump,logging:$.logging,claudeFast:$.claudeFast,thinkingBinding:$.thinkingBinding,costZeroing:$.costZeroing,cacheKeep:$.cacheKeep,relay:$.relay,claustrum:$.claustrum,killswitch:$.killswitch,prime:(()=>{if(typeof $.prime?.enabled!=="boolean")return;return{enabled:$.prime.enabled}})(),accounts:$.accounts.map(hJ)})}function n($){return $?.claustrum?.mode==="claustrum"?"claustrum":"local"}function w5($,Z,J){return n($)==="claustrum"&&A(Z)&&Z.enabled!==!1&&(J?.status==="resolved"||Boolean($?.claustrum?.scopedRoster&&Z.claustrumScopedCredentialId))}async function AQ($,Z=I()){return S0(async()=>{let J=await m0(Z);try{let X=await f(Z),G=X??a();if(X&&n(G)===$)return"unchanged";return G.claustrum={...G.claustrum,mode:$},await t2(G,Z,{[T5]:!0}),"changed"}finally{await J.release()}})}async function wQ($){let Z=$.path??I();return S0(async()=>{let J=await m0(Z);try{let X=await K1(Z);try{let G=await f(Z);if(!G)return"missing";let Y=P$(Z),z=(await G1(Y)).value,K=_(z)&&_(z.accounts)?z.accounts:void 0,W=Object.keys(K??{}).filter((j)=>j.trim()===$.id.trim()),Q=G.accounts.find((j)=>j.id===$.id);if(!Q){if(W.length===0)return"missing";for(let j of W){let B=K?.[j];if(_(B))delete B.claustrumHandle}return await y0(Y,Y1(z)),"updated"}if(!A(Q))return"ineligible";if(!Q.claustrumHandle)return"updated";delete Q.claustrumHandle;let V=await O6(Z);if(await y0(Z,{...V,...D6(G)}),W.length>0){for(let j of W){let B=K?.[j];if(_(B))delete B.claustrumHandle}await y0(Y,Y1(z))}return"updated"}finally{await X.release()}}finally{await J.release()}})}var j5=Promise.resolve();function S0($){return new Promise((Z,J)=>{j5=j5.then(()=>$().then(Z,J),()=>$().then(Z,J))})}async function y0($,Z){await s2(n2($),{recursive:!0});let J=`${$}.${J1()}.tmp`;await q6(J,`${JSON.stringify(Z,null,2)}
3
- `,{encoding:"utf8",mode:384});try{await O5(J,$)}catch(X){throw await m1(J,{force:!0}).catch(()=>{}),X}}var T5=Symbol("writeClaustrumMode"),S5=Symbol("mutateAccountRoster");function H5($,Z){return $.id===Z.id||Boolean($.label&&Z.label&&$.label===Z.label)}function I5($,Z,J){let X=new Set(J.removedAccountIds??[]),G=$.filter((Q)=>!X.has(Q.id)),Y=Z.filter((Q)=>!X.has(Q.id)),z=G.filter((Q)=>!Y.some((V)=>H5(V,Q)));if(!z.length)return[...Y];if(J.preserveExistingAccountOrder===!1)return[...Y,...z];let K=new Set,W=G.map((Q)=>{let V=Y.findIndex((B,q)=>!K.has(q)&&H5(B,Q)),j=Y[V];if(!j)return Q;return K.add(V),j});for(let Q=0;Q<Y.length;Q++){let V=Y[Q];if(!K.has(Q)&&V)W.push(V)}return W}function mJ($,Z,J){let X=I5($.filter(u2),Z.filter(u2),J),G=new Map(X.map((z)=>[z.id,z])),Y=$.flatMap((z)=>{if(A(z))return[z];let K=G.get(z.id);if(!K)return[];return G.delete(z.id),[K]});return Y.push(...G.values()),Y}var pJ=1e4,uJ=12000,lJ=1e4,dJ=12000;async function f5($){let{path:Z,name:J,ttlMs:X,waitMs:G,description:Y}=$;await s2(n2(Z),{recursive:!0});let z=Date.now()+G;while(!0){let K=await Q0({name:J,ttlMs:X,path:Z,renew:!0});if(K)return K;if(Date.now()>=z)throw Error(`Timed out waiting for the account ${Y} lock`);await new Promise((W)=>setTimeout(W,25))}}function m0($){return f5({path:$,name:"config-write",ttlMs:pJ,waitMs:uJ,description:"configuration write"})}function K1($){return f5({path:$,name:"state-write",ttlMs:lJ,waitMs:dJ,description:"state write"})}function L0($,Z=I(),J={}){let X=Z;return S0(()=>iJ($,X,J))}function i1($,Z,J={}){let X=jJ($);return S0(async()=>{let G=await m0(X);try{let Y=await f(X)??a(),z=Z(Y);if(z.save!==!1)await J.assertAuthority?.(),await t2(z.storage,X,{...z.options,[S5]:!0});return z.result}finally{await G.release()}})}async function TQ($=I(),Z=J1){return S0(async()=>{let J=await m0($);try{let X=await f($)??a();if(X.mainAccountId)return X.mainAccountId;let G=Z(),Y={...X,mainAccountId:G},z=await O6($);return await y0($,{...z,...D6(Y)}),G}finally{await J.release()}})}async function iJ($,Z,J){let X=await m0(Z);try{await t2($,Z,J)}finally{await X.release()}}async function t2($,Z,J){let X=await f(Z),G=X?.claustrum?.scopedRoster===!0&&!J[S5],Y=G?{...J,removedAccountIds:J.removedAccountIds?.filter((V)=>X?.accounts.some((j)=>j.id===V&&u2(j)))}:J,z={...$,...$.claustrum&&{claustrum:{...X?.claustrum,...$.claustrum,...G&&X?.claustrum,...J[T5]?{mode:$.claustrum.mode}:X?.claustrum?.mode?{mode:X.claustrum.mode}:{}}},...!$.claustrum&&X?.claustrum&&{claustrum:X.claustrum},accounts:G?mJ(X?.accounts??[],$.accounts,Y):I5(X?.accounts??[],$.accounts,Y)},W={...await O6(Z),...D6(z)};if(!z.claustrum)delete W.claustrum;await y0(Z,W);let Q=await K1(Z);try{await z1(z,Z,{mainQuota:!0,mainRefresh:!0,accounts:!0,setClaustrumHandleAccountIds:J.setClaustrumHandleAccountIds})}finally{await Q.release()}}function cJ($,Z){$.main=$.main??{},$.main.profile=Z.main?.profile}function sJ($,Z){$.main=$.main??{};let J=Z.quota?.mainLastQuotaApiError,X=typeof Z.quota?.mainQuotaErrorGeneration==="number"&&Number.isSafeInteger(Z.quota.mainQuotaErrorGeneration)&&Z.quota.mainQuotaErrorGeneration>=0?Z.quota.mainQuotaErrorGeneration:void 0,G=typeof Z.quota?.mainQuotaErrorClearedAt==="number"&&Number.isFinite(Z.quota.mainQuotaErrorClearedAt)&&Z.quota.mainQuotaErrorClearedAt>=0?Z.quota.mainQuotaErrorClearedAt:void 0,Y=typeof $.main.quotaErrorGeneration==="number"&&Number.isSafeInteger($.main.quotaErrorGeneration)&&$.main.quotaErrorGeneration>=0?$.main.quotaErrorGeneration:0,z=typeof $.main.lastQuotaApiError?.checkedAt==="number"&&Number.isFinite($.main.lastQuotaApiError.checkedAt)&&$.main.lastQuotaApiError.checkedAt>=0?$.main.lastQuotaApiError.checkedAt:void 0,K=typeof $.main.quotaErrorClearedAt==="number"&&Number.isFinite($.main.quotaErrorClearedAt)&&$.main.quotaErrorClearedAt>=0?$.main.quotaErrorClearedAt:void 0,W=Math.max(z??0,K??0),Q=typeof J?.checkedAt==="number"&&Number.isFinite(J.checkedAt)&&J.checkedAt>=0?J.checkedAt:void 0;if(J===void 0&&G!==void 0&&G>=W){if($.main.lastQuotaApiError=void 0,$.main.quotaErrorClearedAt=M1(K,G),X!==void 0&&X>=Y)$.main.quotaErrorGeneration=X}else if(J&&typeof J.checkedAt==="number"&&Number.isFinite(J.checkedAt)&&J.checkedAt>W){let O=Q!==void 0&&Q>W,L=Q!==void 0&&Q===W&&z!==void 0&&K===void 0&&X!==void 0&&X>=Y,M=Q===void 0&&G===void 0&&X!==void 0&&X>=Y&&K===void 0;if(O||L||M){if($.main.lastQuotaApiError=J,X!==void 0)$.main.quotaErrorGeneration=Math.max(Y,X)}}let V=Z.quota?.mainQuota,j=Boolean($.main.quotaToken&&Z.quota?.mainQuotaToken&&$.main.quotaToken===Z.quota.mainQuotaToken),B=j&&V?.source==="headers"?A5($.main.quota,V):V,q=Boolean(j&&V?.source==="headers"),H=T0($.main.quota),U=T0(B);if(!q&&(H>U||H===U&&u1($.main.quota)>u1(B)))return;$.main.quota=B;let x=T0(B);$.main.quotaCheckedAt=x>0?x:void 0,$.main.quotaToken=Z.quota?.mainQuotaToken}function nJ($,Z){$.main=$.main??{};let J=Z.refresh?.mainLastRefreshError,X=Z.refresh?.mainRefreshErrorClearedAt,G=$.main.lastRefreshError?.checkedAt,Y=$.main.refreshErrorClearedAt,z=Math.max(G??0,Y??0);if(J===void 0&&X!==void 0&&X>=z)$.main.lastRefreshError=void 0,$.main.refreshErrorClearedAt=fJ(Y,X);else if(J&&typeof J.checkedAt==="number"&&Number.isFinite(J.checkedAt)&&J.checkedAt>z)$.main.lastRefreshError=J;$.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function aJ($,Z){let J=Z.prime?.main,X=Z.prime?.mainAuthLineageId,G=Z.prime?.mainAuthLineageRefreshTokenFingerprint;if(!J&&!X&&!G)return;if($.main=$.main??{},J)$.main.prime=J;if(X)$.main.primeAuthLineageId=X;if(G)$.main.primeAuthLineageRefreshTokenFingerprint=G}function Y1($){if(Array.isArray($))return $.map(Y1);if(!_($))return $;return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0).map(([Z,J])=>[Z,Y1(J)]))}function tJ($,Z=I(),J={mainProfile:!0,mainQuota:!0,mainRefresh:!0,accounts:!0}){let X=Z;return S0(async()=>{let G=await K1(X);try{await z1($,X,J)}finally{await G.release()}})}function SQ($,Z=I()){let J=Z;return S0(async()=>{let X=await m0(J);try{let G=await K1(J);try{let Y=await f(J),z=P$(J),K=(await G1(z)).value,W=_(K)?{...K,version:1}:{version:1},{accountId:Q,accountIdentity:V,profile:j}=$;if(Y?.claustrum?.scopedRoster&&n(Y)==="claustrum"){let B=Y.accounts.find((H)=>H.id===Q),q=Q==="main"?Y.claustrum.primaryAccount?.accountId:B&&A(B)?B.anthropicAccountUuid:void 0;if(!q||V!==q||j?.accountIdentity!==void 0&&j.accountIdentity!==q||j?.providerAccountUuid!==void 0&&j.providerAccountUuid!==q)return!1}if(Q==="main"){W.main={...W.main??{}};let B=M$(W.main.profile);if(!j){if(B&&(V===void 0||B.accountIdentity===void 0||B.accountIdentity===V))return!1;return W.main.profile=void 0,await y0(z,Y1(W)).then(()=>!0)}if(j.accountIdentity!==void 0&&j.accountIdentity!==V)return!1;let q=V===void 0||j.accountIdentity===V?j:{...j,accountIdentity:V};if(B&&(V===void 0||B.accountIdentity===void 0||B.accountIdentity===V)&&B.checkedAt>q.checkedAt)return!1;W.main.profile=q}else{if(!Y?.accounts.find((U)=>U.id===Q&&A(U)))return!1;W.accounts={..._(W.accounts)?W.accounts:{}};let q=_(W.accounts[Q])?{...W.accounts[Q]}:{},H=M$(q.profile);if(!j){if(H&&(V===void 0||H.accountIdentity===void 0||H.accountIdentity===V))return!1;q.profile=void 0}else{if(j.accountIdentity!==void 0&&j.accountIdentity!==V)return!1;let U=V===void 0||j.accountIdentity===V?j:{...j,accountIdentity:V};if(H&&(V===void 0||H.accountIdentity===void 0||H.accountIdentity===V)&&H.checkedAt>U.checkedAt)return!1;q.profile=U}W.accounts[Q]=q}return await y0(z,Y1(W)),!0}finally{await G.release()}}finally{await X.release()}})}function IQ($,Z,J=I()){return S0(async()=>{let X=await m0(J);try{let G=await K1(J);try{let Y=await f(J),z=Y?.accounts.find((Q)=>Q.id===$&&A(Q));if(!Y||!z||z.claustrumHandle!==Z||!z.lastRefreshError)return!1;z.lastRefreshError=void 0,await z1(Y,J,{accounts:[$]});let K=P$(J),W=(await G1(K)).value;if(_(W)&&_(W.accounts)){let Q=W.accounts[$];if(_(Q))delete Q.lastRefreshError,await y0(K,Y1(W))}return!0}finally{await G.release()}}finally{await X.release()}})}function oJ($,Z){if(!_($.main))$.main={};let J=$.main;if(!Z||J.scopedAccountIdentity!==Z)delete J.prime,delete J.primeAuthLineageId,delete J.primeAuthLineageRefreshTokenFingerprint,delete J.quotaErrorGeneration,delete J.quotaErrorClearedAt;if(J.scopedAccountIdentity=Z,!Z||J.quota?.accountIdentity!==Z)delete J.quota,delete J.quotaCheckedAt,delete J.quotaToken;if(!Z||J.lastQuotaApiError?.accountIdentity!==Z)delete J.lastQuotaApiError;if(!Z||(J.profile?.providerAccountUuid??J.profile?.accountIdentity)!==Z)delete J.profile,delete J.profileToken;delete J.lastRefreshError,delete J.refreshErrorClearedAt,delete J.refreshLeaseId,delete J.refreshLeaseUntil,delete J.refreshLeaseTokenHash}async function z1($,Z,J){let X=P$(Z),G=(await G1(X)).value,Y=_(G)?{...G,version:1}:{version:1},z=(await G1(Z)).value,K=_(z)?P5(z.claustrum):void 0,W=K?.mode==="claustrum"&&K.scopedRoster===!0,Q=K?.primaryAccount?.accountId,V=Boolean(Q&&$.claustrum?.primaryAccount?.accountId===Q);if(W)oJ(Y,Q);let j=$.main?.profile?.providerAccountUuid??$.main?.profile?.accountIdentity;if(J.mainProfile&&(!W||V&&(!$.main?.profile||j===Q)))cJ(Y,$);let B=V&&(!$.quota?.mainQuota||$.quota.mainQuota.accountIdentity===Q)&&(!$.quota?.mainLastQuotaApiError||$.quota.mainLastQuotaApiError.accountIdentity===Q);if(J.mainQuota&&(!W||B))sJ(Y,W?{...$,quota:{...$.quota,mainQuotaToken:Q}}:$);if(J.mainRefresh&&!W)nJ(Y,$);if(J.mainPrime&&(!W||V))aJ(Y,$);if(J.accounts){let q=J.accounts===!0?null:new Set(J.accounts),H=new Set(J.setClaustrumHandleAccountIds??[]),U=z,x=_(U)&&Array.isArray(U.accounts)?new Map(U.accounts.filter(_).map((L)=>[String(L.id??"").trim(),L])):new Map,O=(()=>{if(!_(U)||!Array.isArray(U.accounts))return null;if(U.accounts.length===0)return new Set;let L=_(Y.accounts)?Y.accounts:{},M=Object.fromEntries($.accounts.map((N)=>[N.id.trim(),y2(N)])),F=U.accounts.map((N)=>{if(!_(N)||typeof N.id!=="string")return null;let D=N.id.trim();if(!D)return null;if(kJ(N))return null;let w=L[N.id]??L[D],E=_(w)?w:{},v=M[D];return R5(F5(N,v??E))?[N.id,D]:null});return F.every((N)=>N!==null)?new Set(F.flatMap((N)=>N??[])):null})();Y.accounts={..._(Y.accounts)?Y.accounts:{}};for(let L of $.accounts){let M=L.id.trim();if(q&&!q.has(L.id)&&!q.has(M))continue;if(O&&!O.has(L.id)&&!O.has(M))continue;let F=Object.keys(Y.accounts).filter((E)=>E!==M&&E.trim()===M),N=F[0],D=Y.accounts[M]??(N?Y.accounts[N]:void 0);for(let E of F)delete Y.accounts[E];let w=x.get(M);if(w&&typeof w.claustrumScopedCredentialId==="string"&&typeof w.anthropicAccountUuid==="string"){let E=(u)=>_(u)&&u.claustrumScopedCredentialId===w.claustrumScopedCredentialId&&u.anthropicAccountUuid===w.anthropicAccountUuid,v=y2(L),R0=i2(E(D)?D:void 0,E(v)?v:{});Y.accounts[M]={...R0,claustrumScopedCredentialId:w.claustrumScopedCredentialId,anthropicAccountUuid:w.anthropicAccountUuid,refresh:""};let o=Y.accounts[M];delete o.access,delete o.expires,delete o.lastRefreshedAt,delete o.lastRefreshError,delete o.claustrumHandle}else{let E=i2(D,y2(L),H.has(L.id)||H.has(M));if(w)delete E.claustrumScopedCredentialId,delete E.claustrumScopedState;Y.accounts[M]=E}}if(O){for(let L of Object.keys(Y.accounts))if(!O.has(L))delete Y.accounts[L]}if(q){for(let L of q)if(!$.accounts.some((M)=>M.id===L))delete Y.accounts[L]}}await y0(X,Y1(Y))}async function Q0($){let J=`${$.path??I()}.${$.name}.lock`,X=p1(J,"owner.json"),G=J1(),Y=$.now??Date.now,z=null,K=!1;async function W(){try{return JSON.parse(await B6(J,"utf8"))}catch(q){if(q.code!=="EISDIR")throw q;return JSON.parse(await B6(X,"utf8"))}}async function Q(){await q6(J,`${JSON.stringify({ownerId:G,expiresAt:Y()+$.ttlMs})}
4
- `,{encoding:"utf8",mode:384})}async function V(){try{return await q6(J,`${JSON.stringify({ownerId:G,expiresAt:Y()+$.ttlMs})}
5
- `,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(q){let H=q.code;if(H==="EEXIST"||H==="EISDIR")return!1;throw q}}function j(){if(!$.renew||K)return;let q=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(z=HJ(()=>{(async()=>{try{let H=await W(),U=Y();if(K||H?.ownerId!==G||Number(H?.expiresAt)<=U)return;await Q(),j()}catch{}})()},q),"unref"in z)z.unref()}let B=await V();if(!B){let q=`${J}.evicting`,H=p1(q,"owner.json"),U=J1(),x=5000,O=8;async function L(){await new Promise((w)=>setTimeout(w,Math.floor(Math.random()*4)))}async function M(){try{let w=await W();return Number(w?.expiresAt)>Y()}catch{try{return(await G5(J)).mtimeMs+$.ttlMs>Y()}catch{return!1}}}async function F(){try{return JSON.parse(await B6(H,"utf8"))?.ownerId===U}catch{return!1}}async function N(){await s2(q);try{await q6(H,`${JSON.stringify({ownerId:U,createdAt:Y()})}
6
- `,{encoding:"utf8",mode:384,flag:"wx"})}catch(w){let E=w.code;if(E==="ENOENT"||E==="EINVAL")return!1;throw await D(),w}return await $.onStep?.("eviction-marker-acquired"),!0}async function D(){if(await F())await m1(q,{recursive:!0,force:!0}).catch(()=>{})}for(let w=0;w<8;w++){if(B=await V(),B)break;if(await M())return null;try{if(!await N()){await L();continue}}catch(E){if(E.code!=="EEXIST")throw E;let R0;try{R0=await G5(q)}catch(u){if(u.code==="ENOENT"){await L();continue}throw u}if(R0.mtimeMs+5000>Y())return null;await $.onStep?.("stale-marker-stat");let o=`${q}.${J1()}`;try{await O5(q,o)}catch(u){if(u.code==="ENOENT"){await L();continue}throw u}await $.onStep?.("stale-marker-claimed"),await m1(o,{recursive:!0,force:!0}).catch(()=>{}),await L();continue}try{if(await M())return null;if(!await F())return null;if(await $.onStep?.("stale-lock-confirmed"),!await F())return null;if(await m1(J,{recursive:!0,force:!0}).catch(()=>{}),!await F())return null;if(B=await V(),!B)return null;if(!await F())return await m1(J,{recursive:!0,force:!0}).catch(()=>{}),B=!1,null;break}finally{await D()}}}if(!B)return null;return j(),{assertOwned:async()=>{let q=await W().catch(()=>{return});if(K||q?.ownerId!==G)throw Error("Account file lock ownership was lost")},release:async()=>{if(K=!0,z)BJ(z),z=null;try{if((await W())?.ownerId!==G)return}catch{return}await m1(J,{recursive:!0,force:!0}).catch(()=>{})}}}function fQ($){return $?.claudeCache?.enabled===!0}function rJ($){return typeof $==="string"&&N5.includes($)?$:R$}function eJ($){return rJ($?.claudeCache?.mode)}async function bQ($,Z,J=I()){let X=await f(J)??a();return X.claudeCache={...X.claudeCache??{},enabled:$,mode:Z??eJ(X)},await L0(X,J),X}async function kQ($,Z=I()){let J=await f(Z)??a();return J.claudeCache={...J.claudeCache??{},enabled:J.claudeCache?.enabled===!0,mode:$},await L0(J,Z),J}function EQ($){return $?.dump?.enabled===!0}async function vQ($,Z=I()){let J=await f(Z)??a();return J.dump={...J.dump??{},enabled:$},await L0(J,Z),J}function hQ($){return $?.claudeFast?.enabled===!0}async function yQ($,Z=I()){let J=await f(Z)??a();return J.claudeFast={...J.claudeFast??{},enabled:$},await L0(J,Z),J}async function gQ($,Z,J=I()){let X=await f(J)??a();return X.cacheKeep={...X.cacheKeep??{},enabled:!0,always:!1,startHour:$,endHour:Z},await L0(X,J),X}async function mQ($=I()){let Z=await f($)??a();return Z.cacheKeep={...Z.cacheKeep??{},enabled:!0,always:!0},delete Z.cacheKeep.startHour,delete Z.cacheKeep.endHour,await L0(Z,$),Z}async function pQ($,Z=I()){let J=await f(Z)??a();return J.cacheKeep={...J.cacheKeep??{},enabled:$},await L0(J,Z),J}function uQ($){return $?.cacheKeep?.subagents===!0}async function lQ($,Z=I()){let J=await f(Z)??a();return J.cacheKeep={...J.cacheKeep??{},subagents:$},await L0(J,Z),J}function dQ($){return $?.prime?.enabled===!0}async function iQ($,Z=I()){let J=await f(Z)??a();return J.prime={...J.prime??{},enabled:$},await L0(J,Z),J}async function cQ($,Z=I()){return S0(async()=>{let J=await m0(Z);try{let X=await K1(Z);try{let G=await f(Z)??a();if($==="main"){let K=G.prime?.mainAuthLineageId;if(K)return K;let W=G.mainAccountId??J1();if(!G.mainAccountId){let Q=await O6(Z);await y0(Z,{...Q,...D6({...G,mainAccountId:W})}),G.mainAccountId=W}return G.prime={...G.prime??{},mainAuthLineageId:W},await z1(G,Z,{mainPrime:!0}),W}let Y=G.accounts.find((K)=>K.id===$&&A(K));if(!Y)throw Error(`getOrCreatePrimeAuthLineageId: OAuth account "${$}" not found`);if(Y.authLineageId)return Y.authLineageId;let z=J1();return Y.authLineageId=z,await z1(G,Z,{accounts:[$]}),z}finally{await X.release()}}finally{await J.release()}})}async function sQ($,Z,J=I(),X=Date.now()){let G=Number.isFinite(Z?.inputTokens)?Math.max(0,Math.floor(Z.inputTokens)):0,Y=Number.isFinite(Z?.outputTokens)?Math.max(0,Math.floor(Z.outputTokens)):0;return S0(async()=>{let z=await m0(J);try{let K=await K1(J);try{let W=await f(J)??a();if($==="main"){let q=W.prime?.main,H={count:(q?.count??0)+1,inputTokens:(q?.inputTokens??0)+G,outputTokens:(q?.outputTokens??0)+Y,since:q?.since??Math.floor(X)};return W.prime={...W.prime??{},main:H},await z1(W,J,{mainPrime:!0}),H}let Q=W.accounts.findIndex((q)=>q.id===$);if(Q<0)throw Error(`incrementPrimeUsagePersistent: account "${$}" not found`);let V=W.accounts[Q],j=V.prime,B={count:(j?.count??0)+1,inputTokens:(j?.inputTokens??0)+G,outputTokens:(j?.outputTokens??0)+Y,since:j?.since??Math.floor(X)};return W.accounts[Q]={...V,prime:B},await z1(W,J,{accounts:[$]}),B}finally{await K.release()}}finally{await z.release()}})}function $X($){return $?.fallbackOn?.length?$.fallbackOn:LJ}function nQ($,Z){return $X(Z).includes($)}function M6($){let Z=$?.quota?.minimumRemaining||{};return{five_hour:Z.five_hour??Z["5h"]??Y5.five_hour,seven_day:Z.seven_day??Z["1w"]??Y5.seven_day}}function _$($){return $?.quota?.enabled!==!1}function ZX($){return $?.refresh?.enabled!==!1}function JX($){return Math.floor(Math.random()*Math.max(0,$))}function b5($){let Z=$?.refresh?.refreshBeforeExpiryMinutes??NJ;return Math.max(_5,Z)*60000}function aQ($){return b5($)}function tQ($){let Z=$?.refresh?.intervalMinutes??xJ;return Math.max(1,Z)*60000}function oQ($){return x5("sha256").update($).digest("hex")}function XX($){let Z=$.status;if(typeof Z==="number"&&Number.isFinite(Z))return Z===429||Z>=500;return Z1($)}function GX($){let J=($.previous?.accountIdentity===$.accountIdentity&&$.previous?.refreshTokenFingerprint===$.refreshTokenFingerprint?$.previous?.retryCount??0:0)+1,X=$.error.retryAfter,G;if(typeof X==="number"&&X>0)G=X*1000;else if(Z1($.error))G=l2;else if(XX($.error))G=Math.min(OJ,l2*2**Math.min(J-1,6));else G=C5;let Y=$.error.status,z=typeof Y==="number"&&Number.isFinite(Y)?Y:void 0,K=l1($.error),Q=(typeof $.error.body==="string"?$.error.body:"").includes("invalid_grant")||K.includes("invalid_grant");return{message:K,checkedAt:$.now,nextRetryAt:$.now+G,retryCount:J,accountIdentity:$.accountIdentity,refreshTokenFingerprint:$.refreshTokenFingerprint,status:z,permanent:z===400&&Q}}function c1($){if(!$)return!1;if(typeof $.permanent==="boolean")return $.permanent;if(typeof $.status==="number")return $.status===400;if(Z1($))return!1;if(typeof $.nextRetryAt==="number")return $.nextRetryAt-$.checkedAt>=C5;return!1}function k5($){let Z=$.nextRetryAt;if(!Z||!Z1($))return Z;return Math.min(Z,$.checkedAt+l2)}function g1($,Z,J,X){if(!$)return!1;let G=k5($);if(!G||G<=J)return!1;if($.refreshTokenFingerprint&&X&&$.refreshTokenFingerprint!==X)return!1;if(!$.accountIdentity)return!0;if(!Z)return!0;return $.accountIdentity===Z}function YX($,Z){return`Claude OAuth refresh is backed off for ${Math.max(1,Math.ceil(((k5($)??Z)-Z)/1000))}s after: ${$.message}`}function g2($,Z){return Object.assign(Error(YX($,Z)),{refreshBackoffError:$})}function E5($){if(!$||typeof $!=="object")return;let Z=$.refreshBackoffError;return Z&&typeof Z.message==="string"?Z:void 0}function rQ($){if(!$)return[];return $.accounts.filter((Z)=>Z.enabled!==!1&&A(Z)&&c1(Z.lastRefreshError)).map((Z)=>Z.label?.trim()||Z.id)}function o2($){if($.status===403)return!0;return/Claude quota check failed: 403\b/.test(l1($))}function _6($){let J=($.previous?.accountIdentity===$.accountIdentity?$.previous?.retryCount??0:0)+1,X=l5($.error)?Math.min(MJ,DJ*2**Math.min(J-1,6)):_J;return{message:l1($.error),checkedAt:$.now,nextRetryAt:$.now+X,retryCount:J,...$.accountIdentity!==void 0&&{accountIdentity:$.accountIdentity}}}function O1($,Z){if(!$?.nextRetryAt||$.nextRetryAt<=Z)return!1;return!0}function eQ($,Z){return`Quota API backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??Z)-Z)/1000))}s after: ${$.message}`}function g0($){let Z=$?.quota?.checkIntervalMinutes??CJ;return Math.max(1,Z)*60000}function $j($){return $?.logging?.level}async function Zj($,Z=I()){let{setLogLevel:J}=await import("./logger-kk9vyem9.js"),X=await f(Z)??a();X.logging={...X.logging??{},level:$},await L0(X,Z),J($)}function v5($){let Z=$?.quota?.mainQuota;if(!Z)return null;return{quota:Z,checkedAt:T0(Z),tokenFingerprint:$.quota?.mainQuotaToken,accountIdentity:Z.accountIdentity}}function h5($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function L6($){return $?.quota?.failClosedOnUnknownQuota??RJ}function y5($){return $.toLowerCase().replace(/[^a-z0-9]/g,"")}function zX($){if(typeof $!=="string")return null;let Z=y5($);if(Z.includes("fable"))return"fable";if(Z.includes("mythos"))return"mythos";return Z}function _0($,Z){let J=zX(Z);if(!J)return;return $?.scoped?.find((X)=>{return[X.modelId,X.modelName,X.title].filter((Y)=>typeof Y==="string").map(y5).join(" ").includes(J)})}function KX($,Z){let J=_0($,Z);return Boolean(J&&Number.isFinite(J.remainingPercent)&&J.remainingPercent<=0)}function N6($,Z){return!KX($,Z)}function g5($,Z){if(!_$(Z))return!0;let J=M6(Z);for(let X of["five_hour","seven_day"]){let G=$?.[X];if(!G)return!L6(Z);if(!Number.isFinite(G.remainingPercent))return!L6(Z);if(G.remainingPercent<J[X])return!1}return!0}function Jj($){return Boolean($?.five_hour&&$.seven_day)}var N1={five_hour:5,seven_day:10,scoped:0};function C$($){let Z=$?.five_hour??$?.["5h"],J=$?.seven_day??$?.["1w"],X=$?.scoped;return{five_hour:typeof Z==="number"&&Number.isFinite(Z)?Z:N1.five_hour,seven_day:typeof J==="number"&&Number.isFinite(J)?J:N1.seven_day,scoped:typeof X==="number"&&Number.isFinite(X)?X:N1.scoped}}function C6($){return $?.killswitch?.enabled===!0}function r2($,Z){if(!$?.killswitch)return N1;if(Z&&$.killswitch.accounts?.[Z])return C$($.killswitch.accounts[Z]);return C$($.killswitch.main)}function m5($,Z,J,X){if(!C6(Z))return!0;let G=r2(Z,J),Y=!1;for(let z of["five_hour","seven_day"]){let K=$?.[z];if(!K){Y=!0;continue}if(!Number.isFinite(K.remainingPercent)){Y=!0;continue}if(K.remainingPercent<G[z])return!1}if(X){let z=_0($,X);if(z&&Number.isFinite(z.remainingPercent)&&z.remainingPercent<=G.scoped)return!1}if(Y)return!L6(Z);return!0}function p5($,Z,J,X){let G=[],Y=[$,...Z.map((z)=>z.quota)];for(let z of Y)if(X){let W=_0(z,X)?.resetsAt;if(!W)continue;let Q=Date.parse(W);if(Number.isFinite(Q)&&Q>J)G.push(Q)}else for(let K of["five_hour","seven_day"]){let W=z?.[K]?.resetsAt;if(!W)continue;let Q=Date.parse(W);if(Number.isFinite(Q)&&Q>J)G.push(Q)}if(!G.length)return 300;return Math.max(1,Math.ceil((Math.min(...G)-J)/1000))+60}function Xj($){return $?.killswitch??{enabled:!1}}async function Gj($,Z=I()){let J=await f(Z)??a();return J.killswitch=$,await L0(J,Z),J}async function Yj($,Z=I()){return i1(Z,(J)=>{let X=J.accounts.find((Y)=>Y.id===$);if(X&&A(X)&&X.claustrumScopedCredentialId&&n(J)==="claustrum")throw Error("Disable this account or remove it from Claustrum; scoped membership is managed by the vault");let G=UX(J,$);return{storage:J,result:G,save:G,options:{removedAccountIds:[$]}}})}async function zj($,Z=I()){await i1(Z,(J)=>{return LX(J,$),{storage:J,result:void 0,options:{preserveExistingAccountOrder:!1}}})}async function Kj($,Z,J=I()){return i1(J,(X)=>{let G=NX(X,$,Z),Y=X.accounts.find((z)=>z.id===$);if(Y&&A(Y)&&(Y.claustrumScopedCredentialId||X.claustrum?.scopedRoster)&&Y.anthropicAccountUuid){let z=new Set(X.claustrum?.disabledAccountIdentities??[]);if(Z)z.delete(Y.anthropicAccountUuid);else z.add(Y.anthropicAccountUuid);X.claustrum={...X.claustrum,disabledAccountIdentities:[...z]}}return{storage:X,result:G,save:G}})}async function Wj($,Z=I()){await i1(Z,(J)=>{if(J.claustrum?.scopedRoster&&n(J)==="claustrum"&&A($))throw Error("Claustrum account membership is managed by the vault; add accounts with ck auth login");if(qX(J,$),A($)&&n(J)==="local"&&$.refresh&&!A2($.refresh)){let X=J.accounts.find((G)=>G.id===$.id||$.label&&G.label===$.label);if(X&&A(X))delete X.claustrumScopedCredentialId,delete X.claustrumScopedState}return{storage:J,result:void 0,options:{setClaustrumHandleAccountIds:$.type==="oauth"&&$.claustrumHandle?[$.id]:void 0}}})}function _1($,Z,J){let X=g0(Z);if(!_$(Z))return J+X;let G=Math.min(...[...["five_hour","seven_day"].map((W)=>$?.[W]?.checkedAt),...($?.scoped??[]).map((W)=>W.checkedAt)].filter((W)=>Number.isFinite(W)).map((W)=>W+X)),Y=(W)=>Number.isFinite(G)?Math.min(W,G):W,z=M6(Z),K=[];for(let W of["five_hour","seven_day"]){let Q=$?.[W];if(!Q)return Y(J+X);if(Q.remainingPercent>=z[W])continue;let V=Q.resetsAt?Date.parse(Q.resetsAt):Number.NaN;if(!Number.isFinite(V)||V<=J)return Y(J+X);K.push(V)}if(!K.length)return Y(J+X);return Y(Math.min(...K)+60000)}function L1($,Z,J){return!$.access||!$.expires||$.expires-J<=b5(Z)}function u5($,Z,J){if(!_$(Z))return!0;let X=g0(Z);return["five_hour","seven_day"].every((G)=>{let Y=$?.[G];return Boolean(Y&&J-Y.checkedAt<X)})}function m2($,Z,J,X){if(!u5($.quota,Z,J))return!0;let G=_0($.quota,X);return Boolean(G&&J-G.checkedAt>=g0(Z))}function WX($,Z){if(!$)return!1;if(!$.resetsAt)return!0;let J=Date.parse($.resetsAt);return!Number.isFinite(J)||J>Z}function VX($,Z){return["five_hour","seven_day"].every((J)=>WX($?.[J],Z))}function l5($){let Z=$.status;if(typeof Z==="number"&&Number.isFinite(Z)){if(Z===429||Z>=500)return!0}let J=l1($);if(/Claude quota check failed: (429|5\d\d)\b/.test(J))return!0;if(J.includes("Quota refresh is already in progress"))return!0;return Z1($)}function QX($,Z,J,X){return Boolean($.access&&$.expires&&$.expires>X)&&l5(J)&&g5($.quota,Z)&&VX($.quota,X)}function x6($){if(!Number.isFinite($))return 0;if($<0)return 0;if($>100)return 100;return $}function X1($){return typeof $==="string"&&$.trim()?$.trim():void 0}function d5($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function jX($,Z){if(!Array.isArray($))return[];let J=new Set,X=[];for(let G of $){if(G?.kind!=="weekly_scoped"||G.group!=="weekly")continue;if(typeof G.percent!=="number"||!Number.isFinite(G.percent))continue;let Y=X1(G.scope?.model?.display_name);if(!Y)continue;let z=X1(G.scope?.model?.id)??Y,K=d5(z);if(!K)continue;let W=`claude-weekly-scoped-${K}`;if(J.has(W))continue;J.add(W);let Q=x6(G.percent),V=X1(G.scope?.model?.id);X.push({id:W,title:`${Y} only`,...V&&{modelId:V},modelName:Y,usedPercent:Q,remainingPercent:x6(100-Q),resetsAt:G.resets_at,checkedAt:Z})}return X}function HX($){if($.extra_usage?.is_enabled!==!0)return;let Z=$.extra_usage.used_credits,J=$.extra_usage.monthly_limit;if(typeof Z!=="number"||!Number.isFinite(Z)||typeof J!=="number"||!Number.isFinite(J))return;let X=$.spend?.limit?.currency,G=X==null?"USD":X1(X),Y=$.spend?.limit?.exponent,z=Y==null?2:Y;if(!G||!/^[A-Za-z]{3}$/.test(G)||!Number.isInteger(z)||z<0||z>20)return;return{used:{amountMinor:Z,currency:G,exponent:z},limit:{amountMinor:J,currency:G,exponent:z},...typeof $.extra_usage.utilization==="number"&&Number.isFinite($.extra_usage.utilization)&&{utilizationPercent:$.extra_usage.utilization},...X1($.spend?.severity)&&{severity:X1($.spend?.severity)},exhausted:Z>=J}}function BX($){if(!Array.isArray($))return;let Z=$.find((Y)=>Y?.is_active===!0);if(!Z)return;if(Z.kind==="session")return"five_hour";if(Z.kind==="weekly_all")return"seven_day";if(Z.kind!=="weekly_scoped"||Z.group!=="weekly")return;let J=X1(Z.scope?.model?.display_name);if(!J)return;let X=X1(Z.scope?.model?.id)??J,G=d5(X);return G?`claude-weekly-scoped-${G}`:void 0}function B5($,Z){if(typeof $?.utilization!=="number")return;if(!Number.isFinite($.utilization))return;let J=x6($.utilization);return{usedPercent:J,remainingPercent:x6(100-J),resetsAt:$.resets_at,checkedAt:Z}}async function s1($){y1($.accessToken,"anthropic");let J=await($.fetchImpl??fetch)(UJ,{method:"GET",headers:{Authorization:`Bearer ${$.accessToken}`,Accept:"application/json","Content-Type":"application/json","anthropic-beta":"oauth-2025-04-20","User-Agent":`claude-code/${D1}`}});if(!J.ok){let W=await J.text().catch(()=>"");throw Object.assign(Error(`Claude quota check failed: ${J.status} — ${W}`),{status:J.status,retryAfter:h2(J.headers.get("Retry-After"))})}let X=$.now?.()??Date.now(),G=await J.json(),Y=BX(G.limits),z={five_hour:B5(G.five_hour,X),seven_day:B5(G.seven_day,X),scoped:jX(G.limits,X),extraUsage:HX(G),...Y&&{bindingWindow:Y,bindingWindowSource:"poll"},source:"poll",checkedAt:X},K={...z.five_hour&&{five_hour:"poll"},...z.seven_day&&{seven_day:"poll"},...z.scoped&&{scoped:"poll"},...z.extraUsage&&{extraUsage:"poll"},...z.bindingWindow&&{bindingWindow:"poll"}};return{...z,...Object.keys(K).length>0&&{fieldSources:K}}}function V0($,Z){let J=$.accounts.findIndex((X)=>X.id===Z.id);if(J>=0)$.accounts[J]=Z}function qX($,Z){let J=$.accounts.findIndex((X)=>X.id===Z.id||Z.label&&X.label===Z.label);if(J>=0){let X=$.accounts[J];if(!X)return;let G=X.type==="oauth"&&Z.type==="oauth"&&X.authLineageId!==Z.authLineageId,Y={...X,...Z,addedAt:X.addedAt??Z.addedAt,...Z.type==="oauth"&&{quota:Z.quota,profile:Z.profile,lastRefreshedAt:Z.lastRefreshedAt,lastRefreshError:Z.lastRefreshError,lastQuotaRefreshError:Z.lastQuotaRefreshError}};if(G&&Y.type==="oauth")P.debug("accounts","cleared provider UUID after auth lineage change"),delete Y.anthropicAccountUuid;$.accounts[J]=Y;return}$.accounts.push(Z)}function Vj($,Z=I()){return S0(async()=>{let J=await m0(Z);try{let X=await K1(Z);try{let G=await f(Z),Y=G?.accounts.find((z)=>z.id===$.accountId&&A(z));if(!G||!Y||Y.authLineageId!==$.authLineageId)return!1;if(Y.quota={...$.quota,accountIdentity:Y.id},$.anthropicAccountUuid!==void 0)Y.anthropicAccountUuid=$.anthropicAccountUuid;return await z1(G,Z,{accounts:[$.accountId]}),!0}finally{await X.release()}}finally{await J.release()}})}function Qj($,Z){if(!$||$.authLineageId!==Z)return null;return $.anthropicAccountUuid??null}function UX($,Z){let J=$.accounts.findIndex((X)=>X.id===Z);if(J<0)return!1;return $.accounts.splice(J,1),!0}function LX($,Z){let J=new Map(Z.map((Y,z)=>[Y,z])),X=$.accounts.filter((Y)=>J.has(Y.id)),G=$.accounts.filter((Y)=>!J.has(Y.id));X.sort((Y,z)=>(J.get(Y.id)??0)-(J.get(z.id)??0)),$.accounts=[...X,...G]}function NX($,Z,J){let X=$.accounts.find((G)=>G.id===Z);if(!X)return!1;return X.enabled=J,!0}function l1($){return $ instanceof Error?$.message:String($)}function c2($,Z,J){if(Z instanceof O$)return;let X=E5(Z);if(X){$.lastRefreshError=X;return}$.lastRefreshError=GX({error:Z,now:J,accountIdentity:$.id,refreshTokenFingerprint:A0($.refresh),previous:$.lastRefreshError})}function q5($,Z,J){if(Z instanceof O$)return;if(o2(Z)||E5(Z))return;if($.lastQuotaRefreshError=_6({error:Z,now:J,previous:$.lastQuotaRefreshError}),Z.isRefreshError)c2($,Z,J)}function H6($){return`fallback-oauth-refresh-${x5("sha256").update($).digest("hex").slice(0,16)}`}class xX{now;fetchImpl;configPath;refreshPromises=new Map;custodyVerificationAccounts=new Set;refreshTimer=null;quotaTimer=null;quotaManager;isFallbackAccountVaultServed;isFallbackAccountVaultEnabled;resolveFallbackAccessToken;onBackgroundRefresh;onFallbackStorageChanged;setIntervalImpl;clearIntervalImpl;constructor($={}){this.now=$.now??Date.now,this.fetchImpl=$.fetchImpl??fetch,this.configPath=$.configPath??I(),this.quotaManager=$.quotaManager??null,this.isFallbackAccountVaultServed=$.isFallbackAccountVaultServed??(()=>!1),this.isFallbackAccountVaultEnabled=$.isFallbackAccountVaultEnabled??(()=>!1),this.resolveFallbackAccessToken=$.resolveFallbackAccessToken??((Z)=>{if(!Z.access||Z.expires===void 0||Z.expires<=this.now())return;return{token:Z.access,source:"sidecar"}}),this.onBackgroundRefresh=$.onBackgroundRefresh,this.onFallbackStorageChanged=$.onFallbackStorageChanged,this.setIntervalImpl=$.setIntervalImpl??globalThis.setInterval,this.clearIntervalImpl=$.clearIntervalImpl??globalThis.clearInterval}seedFallbackQuota($,Z){if(!this.quotaManager)return;if(!$.quota)return;let J=T0($.quota);if(J<=0)return;let X=this.quotaManager.getFallback($.id,$);if(X&&X.checkedAt>=J)return;let G=g0(Z);this.quotaManager.setFallback($.id,{quota:$.quota,refreshAfter:J+G,checkedAt:J},$)}async load(){return f(this.configPath)}async save($,Z){await tJ($,this.configPath,{accounts:Z??!0})}startBackgroundRefresh(){let $=async(J=!1)=>{await this.onBackgroundRefresh?.(J),await this.refreshDueAccounts(),await this.refreshQuotaForDueAccounts()},Z=$(!0).catch(()=>{});if(!this.refreshTimer){if(this.refreshTimer=this.setIntervalImpl(()=>$().catch(()=>{}),PJ+JX(FJ)),"unref"in this.refreshTimer)this.refreshTimer.unref()}return Z}stopBackgroundRefresh(){if(this.refreshTimer)this.clearIntervalImpl(this.refreshTimer);if(this.quotaTimer)this.clearIntervalImpl(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async withAccountRefreshLock($,Z){let J=await Q0({name:H6($),ttlMs:j6,path:this.configPath,now:this.now,renew:!0});if(!J)throw Error("Fallback OAuth refresh is already in progress");this.custodyVerificationAccounts.add($);try{return await Z()}finally{this.custodyVerificationAccounts.delete($),await J.release()}}async getUsableFallbackAccounts($,Z={}){let J=$!==void 0?$:await this.load();if(!J)return[];let X=[],G=!1;for(let Y of J.accounts){if(Y.enabled===!1||!A(Y))continue;if(this.isFallbackAccountVaultEnabled(Y.id,J)){if(!this.isFallbackAccountVaultServed(Y.id,J))continue;if(p2(Y)&&!J.quota?.minimumRemaining&&!C6(J)){X.push(Y);continue}}let z=Y;try{if(L1(z,J,this.now())&&!this.isFallbackAccountVaultEnabled(z.id,J)&&!this.isFallbackAccountVaultServed(z.id,J)){let W=z.lastRefreshError;if(W&&g1(W,z.id,this.now(),A0(z.refresh)))throw g2(W,this.now());z=await this.refreshAccount(z,J),G=!0}if(this.seedFallbackQuota(z,J),(this.quotaManager?this.quotaManager.isFallbackStale(z.id,z.access,Z.modelId,z):m2(z,J,this.now(),Z.modelId))&&!O1(z.lastQuotaRefreshError,this.now())){let W=await this.refreshAccountQuota(z,J);z=W.account,G||=W.changed}if(this.accountPassesQuotaPolicy(this.quotaPolicyAccount(z),J,{modelId:Z.modelId}))X.push(z)}catch(K){if(QX(z,J,K,this.now())){if(w0("[refresh] fallback quota using cached quota after refresh error",{accountId:z.id,error:l1(K)}),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(z),J,{modelId:Z.modelId}))X.push(z)}else if(!L6(J)&&!g1(z.lastRefreshError,z.id,this.now(),A0(z.refresh))&&N6(z.quota,Z.modelId))X.push(z)}}if(G)await this.save(J);return X}async markUsed($){let Z=await this.load();if(!Z)return;let J=Z.accounts.find((X)=>X.id===$.id);if(!J)return;J.lastUsed=this.now(),await this.save(Z)}accountPassesQuotaPolicy($,Z,J={}){return g5($.quota,Z)&&N6($.quota,J.modelId)}quotaPolicyAccount($){if(!this.quotaManager)return $;let Z=this.quotaManager.getFallback($.id,$)?.quota;return Z?{...$,quota:Z}:$}async refreshDueAccounts(){let $=await this.load();if(!$||!ZX($))return;let Z=!1;for(let J of $.accounts){if(J.enabled===!1||!A(J))continue;if(this.custodyVerificationAccounts.has(J.id)){P.debug("refresh","fallback OAuth background skipped vault-service verification",{accountId:J.id});continue}if(!L1(J,$,this.now())||this.isFallbackAccountVaultEnabled(J.id,$)||this.isFallbackAccountVaultServed(J.id,$))continue;if(g1(J.lastRefreshError,J.id,this.now(),A0(J.refresh)))continue;try{w0("[refresh] fallback oauth background due",{accountId:J.id,expiresInMs:J.expires?J.expires-this.now():void 0}),await this.refreshAccount(J,$),Z=!0}catch(X){P.warn("refresh","fallback oauth background failed",{accountId:J.id,error:X instanceof Error?X.message:String(X)}),c2(J,X,this.now()),V0($,J),Z=!0}}if(Z)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!_$($))return;let Z=!1;for(let J of $.accounts){if(J.enabled===!1||!A(J))continue;if(this.custodyVerificationAccounts.has(J.id))continue;let X=J;try{if(L1(X,$,this.now())&&!this.isFallbackAccountVaultEnabled(X.id,$)&&!this.isFallbackAccountVaultServed(X.id,$)){if(g1(X.lastRefreshError,X.id,this.now(),A0(X.refresh)))continue;X=await this.refreshAccount(X,$),Z=!0}if(O1(X.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(X,$),!(this.quotaManager?this.quotaManager.isFallbackStale(X.id,X.access):m2(X,$,this.now())))continue;let Y=await this.refreshAccountQuota(X,$);Z||=Y.changed}catch(G){q5(J,G,this.now()),V0($,J),Z=!0}}if(Z)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let Z=await this.load(),J=[];if(!Z||!_$(Z))return{storage:Z,errors:J};let X=$.force??!1,G=!1;for(let Y of Z.accounts){if(Y.enabled===!1||!A(Y))continue;let z=Y;try{if(L1(z,Z,this.now())&&!this.isFallbackAccountVaultServed(z.id,Z)&&!this.isFallbackAccountVaultEnabled(z.id,Z)){let W=z.lastRefreshError;if(W&&g1(W,z.id,this.now(),A0(z.refresh)))throw g2(W,this.now());z=await this.refreshAccount(z,Z),G=!0}if(!X&&!m2(z,Z,this.now())){if(z.lastQuotaRefreshError)z.lastQuotaRefreshError=void 0,V0(Z,z),G=!0;continue}let K=await this.refreshAccountQuota(z,Z);G||=K.changed}catch(K){q5(Y,K,this.now()),V0(Z,Y),G=!0,J.push({accountId:Y.id,message:l1(K)})}}if(G)await this.save(Z);return{storage:Z,errors:J}}async refreshAccount($,Z,J={}){if(this.isFallbackAccountVaultServed($.id,Z)||this.isFallbackAccountVaultEnabled($.id,Z))return $;let X=this.refreshPromises.get($.id);if(X){let Y=await X;return V0(Z,Y),Y}let G=this.refreshAccountNow($,Z,J).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,G);try{let Y=await G;return V0(Z,Y),Y}catch(Y){if(J.persistError)c2($,Y,this.now()),V0(Z,$),await this.save(Z);throw Y}}async waitForConcurrentFallbackRefresh($,Z,J,X){let G=Date.now()+AJ;while(Date.now()<G){await new Promise((Q)=>setTimeout(Q,wJ));let Y=await this.load(),z=Y?.accounts.find((Q)=>Q.id===$.id&&A(Q));if(!z)continue;if((z.access!==J.access||z.refresh!==J.refresh||(z.expires??0)>(J.expires??0)+60000)&&(X.force||!L1(z,Y,this.now())))return V0(Z,z),w0("[refresh] fallback oauth joined concurrent refresh",{accountId:z.id,expiresInMs:z.expires?z.expires-this.now():void 0}),z;let W=z.lastRefreshError;if(W&&g1(W,z.id,this.now(),A0(z.refresh)))throw V0(Z,z),g2(W,this.now())}return null}async refreshAccountNow($,Z,J){let X=await this.load(),G=X?.accounts.find((K)=>K.id===$.id&&A(K));if(G&&!J.force&&!L1(G,X,this.now()))return V0(Z,G),G;let Y=G??$,z=await Q0({name:H6(Y.id),ttlMs:j6,path:this.configPath,now:this.now,renew:!0});if(!z){w0("[refresh] fallback oauth refresh skipped file lock",{accountId:Y.id});let K=await this.waitForConcurrentFallbackRefresh($,Z,Y,J);if(K)return K;throw Error("Fallback OAuth refresh is already in progress")}try{if(X=await this.load(),G=X?.accounts.find((Q)=>Q.id===$.id&&A(Q)),G&&!J.force&&!L1(G,X,this.now()))return V0(Z,G),G;Y=G??Y;let K=Y.refresh;w0("[refresh] fallback oauth refresh request start",{accountId:Y.id,force:J.force===!0,expiresInMs:Y.expires?Y.expires-this.now():void 0});let W=await X5({refreshToken:K,authLineageId:Y.authLineageId,fetchImpl:this.fetchImpl,now:this.now});return Y.access=W.access,Y.refresh=W.refresh,Y.authLineageId=W.authLineageId??Y.authLineageId,Y.expires=W.expires,Y.lastRefreshedAt=W.expires-W.expiresIn*1000,Y.lastRefreshError=void 0,V0(Z,Y),await this.save(Z),w0("[refresh] fallback oauth refresh succeeded",{accountId:Y.id,expiresInMs:Y.expires?Y.expires-this.now():void 0}),Y}finally{await z.release()}}async refreshAccountQuota($,Z){let U=[];try{let J=JSON.stringify([$.quota,$.lastQuotaRefreshError]);let X=!1;let G=$;let Y=this.isFallbackAccountVaultEnabled(G.id,Z);let z=this.resolveFallbackAccessToken(G,Z);if(!z&&!Y)G=await this.refreshAccount($,Z,{force:!0}),X=!0,z=this.resolveFallbackAccessToken(G,Z);let K=Z?.claustrum?.scopedRoster===!0&&this.quotaManager?.canFetchWithoutAccessToken()===!0;if(!z&&!K)return w0("[quota] fallback quota poll skipped: no usable credential",{accountId:G.id}),{account:G,fetched:!1,changed:X};let W=await Q0({name:H6(G.id),ttlMs:j6,path:this.configPath,now:this.now});if(!W)return w0("[quota] fallback quota poll skipped refresh lock",{accountId:G.id}),{account:G,fetched:!1,changed:X};const Q=U5(U,{[Symbol.asyncDispose]:async()=>W?.release()},1);let V=(F)=>this.quotaManager?this.quotaManager.refreshFallbackWithMetadata(G.id,F,G):s1({accessToken:F,fetchImpl:this.fetchImpl,now:this.now}).then((N)=>({quota:N,fetched:!0}));let j=this.now();let B=!1;try{let F=await V(z?.token??"");G.quota=F.quota,B=F.fetched}catch(F){if(!(F instanceof Error?F.message:String(F)).includes("Claude quota check failed: 401")||Y||z?.source!=="sidecar")throw F;if(await W.release(),W=null,G=await this.refreshAccount($,Z,{force:!0}),X=!0,z=this.resolveFallbackAccessToken(G,Z),!z)return w0("[quota] fallback quota poll skipped after refresh: no usable credential",{accountId:G.id}),{account:G,fetched:!1,changed:X};if(W=await Q0({name:H6(G.id),ttlMs:j6,path:this.configPath,now:this.now}),!W)return w0("[quota] fallback quota poll skipped refresh lock",{accountId:G.id}),{account:G,fetched:!1,changed:X};let D=await V(z.token);G.quota=D.quota,B=D.fetched}let q=await this.load();let H=q?.accounts.find((F)=>F.id===G.id&&A(F));if(q&&H&&H.access!==G.access)return this.seedFallbackQuota(H,q),V0(Z,H),{account:H,fetched:!1,changed:!1};if(q&&H&&H.access===G.access&&H.quota&&T0(H.quota)>=j&&u5(H.quota,q,this.now()))return this.seedFallbackQuota(H,q),V0(Z,H),{account:H,fetched:B,changed:!1};G.lastQuotaRefreshError=void 0;V0(Z,G);if(this.quotaManager&&G.quota){let F=this.now();this.quotaManager.setFallback(G.id,{quota:G.quota,refreshAfter:F+g0(Z),checkedAt:F},G)}return{account:G,fetched:B,changed:X||JSON.stringify([G.quota,G.lastQuotaRefreshError])!==J}}catch(x){var O=x,L=1}finally{var M=L5(U,O,L);M&&await M}}}var qj="claude-cache",i5="## Claude Cache Status",OX="## Claude Cache Enabled",DX="## Claude Cache Disabled",MX="## Claude Cache Usage",_X="Usage: `/claude-cache`, `/claude-cache on`, `/claude-cache off`, or `/claude-cache mode explicit|automatic|hybrid`.",n1=!1,a1=R$;function Uj(){return n1}function Lj(){return a1}function Nj($){n1=$}function xj($){a1=$}function Oj($){n1=$.enabled,a1=$.mode}function Dj(){n1=!1,a1=R$}function CX($){let Z=$.trim().split(/\s+/).filter(Boolean);if(Z.length===0)return{type:"status"};if(Z.length===1&&Z[0]==="on")return{type:"enable"};if(Z.length===1&&Z[0]==="off")return{type:"disable"};if(Z.length===2&&Z[0]==="mode"&&(Z[1]==="explicit"||Z[1]==="automatic"||Z[1]==="hybrid"))return{type:"mode",mode:Z[1]};return{type:"usage"}}function F$($){let Z=$?.enabled??n1,J=$?.mode??a1;return[i5,"",`- Enabled: ${Z?"enabled":"disabled"}`,`- Mode: ${J}`,"- Persisted: ~/.config/opencode/anthropic-auth.json","- Scope: main sessions only; subagent sessions keep default ephemeral cache behavior","- Modes: explicit = existing OpenCode breakpoints; automatic = top-level cache_control only; hybrid = system + messages[0] + top-level cache_control","- TTL: 1h when enabled for main sessions; default ephemeral cache behavior otherwise"].join(`
7
- `)}function Mj($){let Z=CX($.argumentsText),J=$.enabled??n1,X=$.mode??a1;if(Z.type==="status")return F$({enabled:J,mode:X});if(Z.type==="enable")return[OX,"",F$({enabled:!0,mode:X})].join(`
8
- `);if(Z.type==="disable")return[DX,"",F$({enabled:!1,mode:X})].join(`
9
- `);if(Z.type==="mode")return[i5,"",`Mode updated to \`${Z.mode}\`.`,"",F$({enabled:J,mode:Z.mode})].join(`
10
- `);return[MX,"",_X,"",F$({enabled:J,mode:X})].join(`
11
- `)}import{createHash as PX}from"node:crypto";var RX=new Uint8Array([0,97,115,109,1,0,0,0,1,48,8,96,3,127,127,127,1,127,96,3,127,127,127,0,96,2,127,127,0,96,1,127,1,127,96,3,127,127,126,1,126,96,3,126,127,127,1,126,96,2,127,126,0,96,1,127,1,126,3,11,10,0,0,2,1,3,4,5,6,1,7,5,3,1,0,1,7,85,9,3,109,101,109,2,0,5,120,120,104,51,50,0,0,6,105,110,105,116,51,50,0,2,8,117,112,100,97,116,101,51,50,0,3,8,100,105,103,101,115,116,51,50,0,4,5,120,120,104,54,52,0,5,6,105,110,105,116,54,52,0,7,8,117,112,100,97,116,101,54,52,0,8,8,100,105,103,101,115,116,54,52,0,9,10,251,22,10,242,1,1,4,127,32,0,32,1,106,33,3,32,1,65,16,79,4,127,32,3,65,16,107,33,6,32,2,65,168,136,141,161,2,106,33,3,32,2,65,137,235,208,208,7,107,33,4,32,2,65,207,140,162,142,6,106,33,5,3,64,32,3,32,0,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,3,32,4,32,0,65,4,106,34,0,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,4,32,2,32,0,65,4,106,34,0,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,2,32,5,32,0,65,4,106,34,0,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,5,32,6,32,0,65,4,106,34,0,79,13,0,11,32,2,65,12,119,32,5,65,18,119,106,32,4,65,7,119,106,32,3,65,1,119,106,5,32,2,65,177,207,217,178,1,106,11,32,1,106,32,0,32,1,65,15,113,16,1,11,146,1,0,32,1,32,2,106,33,2,3,64,32,1,65,4,106,32,2,75,69,4,64,32,0,32,1,40,2,0,65,189,220,202,149,124,108,106,65,17,119,65,175,214,211,190,2,108,33,0,32,1,65,4,106,33,1,12,1,11,11,3,64,32,1,32,2,79,69,4,64,32,0,32,1,45,0,0,65,177,207,217,178,1,108,106,65,11,119,65,177,243,221,241,121,108,33,0,32,1,65,1,106,33,1,12,1,11,11,32,0,32,0,65,15,118,115,65,247,148,175,175,120,108,34,0,65,13,118,32,0,115,65,189,220,202,149,124,108,34,0,65,16,118,32,0,115,11,63,0,32,0,65,8,106,32,1,65,168,136,141,161,2,106,54,2,0,32,0,65,12,106,32,1,65,137,235,208,208,7,107,54,2,0,32,0,65,16,106,32,1,54,2,0,32,0,65,20,106,32,1,65,207,140,162,142,6,106,54,2,0,11,195,4,1,6,127,32,1,32,2,106,33,6,32,0,65,24,106,33,4,32,0,65,40,106,40,2,0,33,3,32,0,32,0,40,2,0,32,2,106,54,2,0,32,0,65,4,106,34,5,32,5,40,2,0,32,2,65,16,79,32,0,40,2,0,65,16,79,114,114,54,2,0,32,2,32,3,106,65,16,73,4,64,32,3,32,4,106,32,1,32,2,252,10,0,0,32,0,65,40,106,32,2,32,3,106,54,2,0,15,11,32,3,4,64,32,3,32,4,106,32,1,65,16,32,3,107,34,2,252,10,0,0,32,0,65,8,106,34,3,32,3,40,2,0,32,4,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,54,2,0,32,0,65,12,106,34,3,32,3,40,2,0,32,4,65,4,106,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,54,2,0,32,0,65,16,106,34,3,32,3,40,2,0,32,4,65,8,106,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,54,2,0,32,0,65,20,106,34,3,32,3,40,2,0,32,4,65,12,106,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,54,2,0,32,0,65,40,106,65,0,54,2,0,32,1,32,2,106,33,1,11,32,1,32,6,65,16,107,77,4,64,32,6,65,16,107,33,8,32,0,65,8,106,40,2,0,33,2,32,0,65,12,106,40,2,0,33,3,32,0,65,16,106,40,2,0,33,5,32,0,65,20,106,40,2,0,33,7,3,64,32,2,32,1,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,2,32,3,32,1,65,4,106,34,1,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,3,32,5,32,1,65,4,106,34,1,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,5,32,7,32,1,65,4,106,34,1,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,7,32,8,32,1,65,4,106,34,1,79,13,0,11,32,0,65,8,106,32,2,54,2,0,32,0,65,12,106,32,3,54,2,0,32,0,65,16,106,32,5,54,2,0,32,0,65,20,106,32,7,54,2,0,11,32,1,32,6,73,4,64,32,4,32,1,32,6,32,1,107,34,1,252,10,0,0,32,0,65,40,106,32,1,54,2,0,11,11,97,1,1,127,32,0,65,16,106,40,2,0,33,1,32,0,65,4,106,40,2,0,4,127,32,1,65,12,119,32,0,65,20,106,40,2,0,65,18,119,106,32,0,65,12,106,40,2,0,65,7,119,106,32,0,65,8,106,40,2,0,65,1,119,106,5,32,1,65,177,207,217,178,1,106,11,32,0,40,2,0,106,32,0,65,24,106,32,0,65,40,106,40,2,0,16,1,11,255,3,2,3,126,1,127,32,0,32,1,106,33,6,32,1,65,32,79,4,126,32,6,65,32,107,33,6,32,2,66,214,235,130,238,234,253,137,245,224,0,124,33,3,32,2,66,177,169,172,193,173,184,212,166,61,125,33,4,32,2,66,249,234,208,208,231,201,161,228,225,0,124,33,5,3,64,32,3,32,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,3,32,4,32,0,65,8,106,34,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,4,32,2,32,0,65,8,106,34,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,2,32,5,32,0,65,8,106,34,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,5,32,6,32,0,65,8,106,34,0,79,13,0,11,32,2,66,12,137,32,5,66,18,137,124,32,4,66,7,137,124,32,3,66,1,137,124,32,3,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,4,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,2,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,5,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,5,32,2,66,197,207,217,178,241,229,186,234,39,124,11,32,1,173,124,32,0,32,1,65,31,113,16,6,11,134,2,0,32,1,32,2,106,33,2,3,64,32,2,32,1,65,8,106,79,4,64,32,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,32,0,133,66,27,137,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,33,0,32,1,65,8,106,33,1,12,1,11,11,32,1,65,4,106,32,2,77,4,64,32,0,32,1,53,2,0,66,135,149,175,175,152,182,222,155,158,127,126,133,66,23,137,66,207,214,211,190,210,199,171,217,66,126,66,249,243,221,241,153,246,153,171,22,124,33,0,32,1,65,4,106,33,1,11,3,64,32,1,32,2,73,4,64,32,0,32,1,49,0,0,66,197,207,217,178,241,229,186,234,39,126,133,66,11,137,66,135,149,175,175,152,182,222,155,158,127,126,33,0,32,1,65,1,106,33,1,12,1,11,11,32,0,32,0,66,33,136,133,66,207,214,211,190,210,199,171,217,66,126,34,0,32,0,66,29,136,133,66,249,243,221,241,153,246,153,171,22,126,34,0,32,0,66,32,136,133,11,77,0,32,0,65,8,106,32,1,66,214,235,130,238,234,253,137,245,224,0,124,55,3,0,32,0,65,16,106,32,1,66,177,169,172,193,173,184,212,166,61,125,55,3,0,32,0,65,24,106,32,1,55,3,0,32,0,65,32,106,32,1,66,249,234,208,208,231,201,161,228,225,0,124,55,3,0,11,244,4,2,3,127,4,126,32,1,32,2,106,33,5,32,0,65,40,106,33,4,32,0,65,200,0,106,40,2,0,33,3,32,0,32,0,41,3,0,32,2,173,124,55,3,0,32,2,32,3,106,65,32,73,4,64,32,3,32,4,106,32,1,32,2,252,10,0,0,32,0,65,200,0,106,32,2,32,3,106,54,2,0,15,11,32,3,4,64,32,3,32,4,106,32,1,65,32,32,3,107,34,2,252,10,0,0,32,0,65,8,106,34,3,32,3,41,3,0,32,4,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,55,3,0,32,0,65,16,106,34,3,32,3,41,3,0,32,4,65,8,106,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,55,3,0,32,0,65,24,106,34,3,32,3,41,3,0,32,4,65,16,106,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,55,3,0,32,0,65,32,106,34,3,32,3,41,3,0,32,4,65,24,106,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,55,3,0,32,0,65,200,0,106,65,0,54,2,0,32,1,32,2,106,33,1,11,32,1,65,32,106,32,5,77,4,64,32,5,65,32,107,33,2,32,0,65,8,106,41,3,0,33,6,32,0,65,16,106,41,3,0,33,7,32,0,65,24,106,41,3,0,33,8,32,0,65,32,106,41,3,0,33,9,3,64,32,6,32,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,6,32,7,32,1,65,8,106,34,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,7,32,8,32,1,65,8,106,34,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,8,32,9,32,1,65,8,106,34,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,9,32,2,32,1,65,8,106,34,1,79,13,0,11,32,0,65,8,106,32,6,55,3,0,32,0,65,16,106,32,7,55,3,0,32,0,65,24,106,32,8,55,3,0,32,0,65,32,106,32,9,55,3,0,11,32,1,32,5,73,4,64,32,4,32,1,32,5,32,1,107,34,1,252,10,0,0,32,0,65,200,0,106,32,1,54,2,0,11,11,188,2,1,5,126,32,0,65,24,106,41,3,0,33,1,32,0,41,3,0,34,2,66,32,90,4,126,32,0,65,8,106,41,3,0,34,3,66,1,137,32,0,65,16,106,41,3,0,34,4,66,7,137,124,32,1,66,12,137,32,0,65,32,106,41,3,0,34,5,66,18,137,124,124,32,3,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,4,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,1,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,5,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,5,32,1,66,197,207,217,178,241,229,186,234,39,124,11,32,2,124,32,0,65,40,106,32,2,66,31,131,167,16,6,11]);async function c5(){return function($){let{exports:{mem:Z,xxh32:J,xxh64:X,init32:G,update32:Y,digest32:z,init64:K,update64:W,digest64:Q}}=$,V=new Uint8Array(Z.buffer);function j(N,D){if(Z.buffer.byteLength<N+D){let w=Math.ceil((N+D-Z.buffer.byteLength)/65536);Z.grow(w),V=new Uint8Array(Z.buffer)}}function B(N,D,w,E,v,R0){j(N);let o=new Uint8Array(N);return V.set(o),w(0,D),o.set(V.subarray(0,N)),{update(u){let Q2;return V.set(o),typeof u=="string"?(j(3*u.length,N),Q2=x.encodeInto(u,V.subarray(N)).written):(j(u.byteLength,N),V.set(u,N),Q2=u.byteLength),E(0,N,Q2),o.set(V.subarray(0,N)),this},digest:()=>(V.set(o),R0(v(0)))}}function q(N){return N>>>0}let H=2n**64n-1n;function U(N){return N&H}let x=new TextEncoder,O=0,L=0n;function M(N,D=O){return j(3*N.length,0),q(J(0,x.encodeInto(N,V).written,D))}function F(N,D=L){return j(3*N.length,0),U(X(0,x.encodeInto(N,V).written,D))}return{h32:M,h32ToString:(N,D=O)=>M(N,D).toString(16).padStart(8,"0"),h32Raw:(N,D=O)=>(j(N.byteLength,0),V.set(N),q(J(0,N.byteLength,D))),create32:(N=O)=>B(48,N,G,Y,z,q),h64:F,h64ToString:(N,D=L)=>F(N,D).toString(16).padStart(16,"0"),h64Raw:(N,D=L)=>(j(N.byteLength,0),V.set(N),U(X(0,N.byteLength,D))),create64:(N=L)=>B(88,N,K,W,Q,U)}}((await WebAssembly.instantiate(RX)).instance)}var FX=/^req_[A-Za-z0-9_-]{8,128}$/,AX=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,wX=/ cc_(?:prev_req|prompt_id)=[^;\r\n]*;/g;function TX($){return FX.test($)}function SX($){return AX.test($)}var IX=0x4d659218e32a3268n,fX="cch=00000;",Aj=/\bcch=([0-9a-f]{5});/,e2=/("system":\[\{"type":"text","text":"x-anthropic-billing-header: cc_version=[^;"]+; cc_entrypoint=[^;"]+; )cch=([0-9a-f]{5});/,bX=/("system":\[\{"type":"text","text":"x-anthropic-billing-header: cc_version=[^;"]+; cc_entrypoint=[^;"]+; )cch=00000;/,s5=null,R6=null;async function t5(){if(R6)return;s5??=(async()=>{R6=(await c5()).h64Raw})(),await s5}function o5($){let Z=$.find((X)=>X.role==="user");if(!Z)return"";let{content:J}=Z;if(typeof J==="string")return J;if(Array.isArray(J)){let X=J.filter((z)=>z.type==="text"),G=X.find((z)=>z.text?.includes("<command-name>"));if(G?.text)return G.text.slice(G.text.indexOf("<command-name>"));let Y=X.findLast((z)=>typeof z.text==="string"&&z.text.length>0);if(Y?.text)return Y.text}return""}class kX{limit;#$=new Map;constructor($=1000){this.limit=$}resolve($,Z,J=!0){let X=this.#$.get($);if(X!==void 0)return this.#$.delete($),this.#$.set($,X),X;let G=o5(Z);if(J){if(!this.#$.has($)&&this.#$.size>=this.limit){let Y=this.#$.keys().next().value;if(Y!==void 0)this.#$.delete(Y)}this.#$.set($,G)}return G}has($){return this.#$.has($)}clear(){this.#$.clear()}}async function EX($){return await t5(),((R6?.($,IX)??0n)&0xfffffn).toString(16).padStart(5,"0")}async function wj($){return await t5(),(R6?.(new TextEncoder().encode($),0n)??0n).toString(16).padStart(16,"0").slice(0,16)}function vX($){return $.replace(e2,`$1${fX}`)}function r5($){return e2.exec($)?.[2]??null}async function e5($){if(!e2.test($))return $;let Z=vX($),J=JSON.parse(Z);if("model"in J)J.model="";delete J.max_tokens;let X=await EX(new TextEncoder().encode(JSON.stringify(J)));return Z.replace(bX,`$1cch=${X};`)}function hX($,Z=D1){let J=a5.map((X)=>$[X]??"0").join("");return PX("sha256").update(`${n5}${J}${Z}`).digest("hex").slice(0,3)}function Tj($,Z=D1,J,X,G){let Y=hX(X??o5($),Z),z=`x-anthropic-billing-header: cc_version=${Z}.${Y}; cc_entrypoint=${J}; cch=00000;`;if(G?.previousRequestId&&TX(G.previousRequestId))z+=` cc_prev_req=${G.previousRequestId};`;if(G?.promptId&&SX(G.promptId))z+=` cc_prompt_id=${G.promptId};`;return z}function yX($){return $.replace(wX,"")}function $8($){if(!$||typeof $!=="object")return 0;let Z=$.system;if(!Array.isArray(Z))return 0;let J=0;for(let X of Z){if(!X||typeof X!=="object")continue;let G=X.text;if(typeof G!=="string"||!G.startsWith("x-anthropic-billing-header:"))continue;let Y=yX(G);if(Y===G)continue;X.text=Y,J+=1}return J}import{randomBytes as gX,randomUUID as z8}from"node:crypto";var mX=1000,d=new Map;function I0($,Z,J,X=mX){if(!$.has(Z)&&$.size>=X){let G=$.keys().next().value;if(G!==void 0)$.delete(G)}$.set(Z,J)}function $4($,Z){if(!Z.accountUuid)return Z;if(d.get($)!==Z)return{...Z,accountUuid:void 0};let J={...Z,accountUuid:void 0};return I0(d,$,J),J}function F6($){let Z=$||"anonymous",J=d.get(Z);if(J)return J;let X={deviceId:gX(32).toString("hex"),sessionId:z8()};return I0(d,Z,X),X}var pX=86400000,uX=300000,A$=new Map,Z4=new Map;function bj(){d.clear(),A$.clear(),Z4.clear()}function lX($){return`compat:${$||"anonymous"}`}function X4($){return`identity:${$}`}function A6($,Z){return`account:${$}:${Z}`}function P6($,Z,J){if(!$)return;if($.accountIdentity!==void 0&&$.accountIdentity!==Z)return;if(J!==void 0&&$.accountUuid!==void 0&&$.accountUuid!==J)return;if($.accountIdentity===Z&&(J===void 0||$.accountUuid===J))return $;return{...$,accountIdentity:Z,...J!==void 0&&{accountUuid:J}}}function w$($,Z,J){I0(d,X4(Z),$),I0(d,A6(J,Z),$)}async function dX($,Z){if(!$.startsWith("sk-ant-oat"))return null;let J=new AbortController,X=setTimeout(()=>J.abort(),5000);try{let G=new URL("https://api.anthropic.com/api/claude_cli/bootstrap");if(G.searchParams.set("entrypoint",J4),Z)G.searchParams.set("model",Z);let Y=await fetch(G,{method:"GET",headers:{accept:"application/json, text/plain, */*",authorization:`Bearer ${$}`,"content-type":"application/json","anthropic-beta":"oauth-2025-04-20","user-agent":`claude-code/${D1}`},signal:J.signal});if(!Y.ok)return null;let K=(await Y.json().catch(()=>null))?.oauth_account?.account_uuid;return typeof K==="string"&&K?K:null}catch{return null}finally{clearTimeout(X)}}function kj($,Z){if(!$.trim()||!Z.trim())throw Error("A verified provider account identity is required");let X={...d.get(A6(Z,$))??F6(X4($)),accountIdentity:$,accountUuid:Z};return w$(X,$,Z),X}async function Ej($,Z,J){let X=J?.trim()||void 0,G=X?X4(X):lX($),Y;if(X)Y=P6(d.get(G)??d.get($),X)??F6(G),Y=P6(Y,X)??Y,I0(d,G,Y);else Y=d.get(G)??d.get($)??F6(G),I0(d,G,Y),I0(d,$,Y);if(!$.startsWith("sk-ant-oat"))return $4(G,Y);let z=Date.now(),K=`${G}:${$}`,W=Z4.get(K);if(W&&W.expiresAt>z){if(!W.accountUuid)return Y=$4(G,Y),Y;if(!X){if(Y.accountUuid===W.accountUuid)return Y;return Y={...Y,accountUuid:W.accountUuid},I0(d,K,Y),Y}let B=P6(d.get(A6(W.accountUuid,X))??d.get(`account:${W.accountUuid}`),X,W.accountUuid);if(B)return Y=B,w$(Y,X,W.accountUuid),Y;if(Y.accountUuid===W.accountUuid)return Y;return Y={...Y,accountIdentity:X,accountUuid:W.accountUuid},w$(Y,X,W.accountUuid),Y}let Q=A$.get(K);if(!Q)Q=dX($,Z),I0(A$,K,Q);let V=await Q.finally(()=>{if(A$.get(K)===Q)A$.delete(K)});if(I0(Z4,K,{accountUuid:V,expiresAt:z+(V?pX:uX)}),!V)return Y=$4(G,Y),Y;if(!X)return Y={...Y,accountUuid:V},I0(d,K,Y),Y;let j=P6(d.get(A6(V,X))??d.get(`account:${V}`),X,V);if(j)return Y=j,w$(Y,X,V),Y;return Y={...Y,accountIdentity:X,accountUuid:V},w$(Y,X,V),Y}function C1($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function iX($){if(!$.accountUuid)return null;return JSON.stringify({device_id:$.deviceId,account_uuid:$.accountUuid,session_id:$.sessionId})}function vj($,Z){let J=iX(Z);if(!J){if(C1($.metadata))delete $.metadata.user_id;return!1}if(!C1($.metadata))$.metadata={};let X=$.metadata;if(C1(X))X.user_id=J;return!0}var cX=["oauth-2025-04-20","interleaved-thinking-2025-05-14","thinking-token-count-2026-05-13","context-management-2025-06-27","prompt-caching-scope-2026-01-05","claude-code-20250219","advisor-tool-2026-03-01","advanced-tool-use-2025-11-20","mid-conversation-system-2026-04-07","effort-2025-11-24","fallback-credit-2026-06-01","extended-cache-ttl-2025-04-11","cache-diagnosis-2026-04-07"],sX=["oauth-2025-04-20","interleaved-thinking-2025-05-14","thinking-token-count-2026-05-13","context-management-2025-06-27","prompt-caching-scope-2026-01-05","advisor-tool-2026-03-01","structured-outputs-2025-12-15","cache-diagnosis-2026-04-07"],Z8=["oauth-2025-04-20","interleaved-thinking-2025-05-14","thinking-token-count-2026-05-13","context-management-2025-06-27","prompt-caching-scope-2026-01-05","advisor-tool-2026-03-01","advanced-tool-use-2025-11-20","extended-cache-ttl-2025-04-11","cache-diagnosis-2026-04-07"];function nX($){return $.output_config?.format?.type==="json_schema"}function aX($){return Array.isArray($.tools)&&$.tools.length>0&&Array.isArray($.system)&&C1($.thinking)&&C1($.context_management)&&C1($.output_config)&&C1($.diagnostics)}function tX($,Z=[]){let J=$?aX($)?[...cX]:nX($)?[...sX]:[...Z8]:[...Z8];if($?.speed==="fast")J.push(J8);for(let X of Z){let G=X.trim();if(G)J.push(G)}return[...new Set(J)].join(",")}function oX(){switch(process.platform){case"darwin":return"MacOS";case"win32":return"Windows";case"linux":return"Linux";case"freebsd":return"FreeBSD";default:return"Unknown"}}function rX(){switch(process.arch){case"arm64":return"arm64";case"x64":return"x64";case"ia32":return"x32";default:return process.arch}}function hj($,Z,J={}){let X=J.identity??F6(Z),Y=[...($.get("anthropic-beta")??"").split(",").map((z)=>z.trim()).filter(Boolean),...J.extraBetas??[]];return $.set("accept","application/json"),$.set("authorization",`Bearer ${Z}`),$.set("content-type","application/json"),$.set("user-agent",Y8),$.set("anthropic-beta",tX(J.body,Y)),$.set("anthropic-dangerous-direct-browser-access","true"),$.set("anthropic-version","2023-06-01"),$.set("x-app","cli"),$.set("x-client-request-id",z8()),$.set("x-claude-code-session-id",X.sessionId),$.set("x-stainless-arch",rX()),$.set("x-stainless-lang","js"),$.set("x-stainless-os",oX()),$.set("x-stainless-package-version",X8),$.set("x-stainless-retry-count","0"),$.set("x-stainless-runtime","node"),$.set("x-stainless-runtime-version",G8),$.set("x-stainless-timeout","600"),$.delete("x-api-key"),$}var eX=["model","messages","system","tools","tool_choice","metadata","max_tokens","temperature","thinking","context_management","output_config","diagnostics","stream","speed"];function K8($){let Z={};for(let J of eX)if(Object.hasOwn($,J))Z[J]=$[J];for(let[J,X]of Object.entries($))if(!Object.hasOwn(Z,J))Z[J]=X;return Z}function yj(){return J4}import{createHash as $G,randomBytes as ZG}from"node:crypto";import{lstat as Y4,mkdir as JG,readdir as Q8,readFile as W8,rename as XG,unlink as j8,writeFile as GG}from"node:fs/promises";import{tmpdir as YG}from"node:os";import{join as f6,resolve as S$}from"node:path";var sj="claude-dump",zG="## Claude Dump Status",KG="## Claude Dump Enabled",WG="## Claude Dump Disabled",VG="## Claude Dump Usage",QG="Usage: `/claude-dump`, `/claude-dump on`, or `/claude-dump off`.",jG="OPENCODE_ANTHROPIC_AUTH_DUMP_DIR",HG="OPENCODE_ANTHROPIC_AUTH_DUMP_MAX_BYTES",BG=f6(YG(),"opencode-anthropic-auth-dumps"),qG=536870912,UG=300000,LG=60000,NG=600000,Q4=/\.(body|meta|relay|request|response)\.json$/,H8=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d{5,}-(.+)$/,T6="[a-zA-Z0-9._-]",B8=new RegExp(`^${T6}{1,80}-direct(?:-${T6}{1,80})?$`),q8=new RegExp(`^${T6}{1,80}-(?:http|websocket)-p[12]-(?:full_sync|patch)$`),xG=new RegExp(`^-direct(?:-${T6}{1,80})?$`),OG=/^-(?:http|websocket)-p[12]-(?:full_sync|patch)$/,P1=!1,z4=0,K4=0,DG=100,R1=new Map;function nj(){return P1}function aj($){P1=$}function tj(){P1=!1,z4=0,K4=0,R1.clear()}function I$(){return process.env[jG]||BG}function MG(){let $=Number(process.env[HG]);return Number.isFinite($)&&$>=0?Math.floor($):qG}function _G($){return S$($)===S$(I$())}function W4($){let Z=$.replace(Q4,"");if(Z===$)return!1;let X=H8.exec(Z)?.[1];if(!X)return!1;return B8.test(X)||q8.test(X)}function CG($){if(!$.endsWith(".partial"))return!1;let Z=$.slice(0,-8);if(W4(Z))return!0;let J=Z.lastIndexOf(".");if(J<0)return!1;let X=Z.slice(J+1);return/^[a-f0-9]{24}$/.test(X)&&W4(Z.slice(0,J))}async function T$($,Z){for(let J=0;J<2;J+=1){let X=ZG(12).toString("hex"),G=`${$}.${X}.partial`,Y=!1;try{return await GG(G,Z,{encoding:"utf8",flag:"wx"}),Y=!0,await XG(G,$),!0}catch(z){if(z.code==="EEXIST")continue;if(Y)await j8(G).catch(()=>{});throw z}}return!1}async function RG($){let Z=$.dumpDir??I$(),J=$.maxBytes??MG(),X=$.now??Date.now(),G=$.minAgeMs??LG,Y=$.partialStaleMs??NG,z={removed:0,freedBytes:0};if(!_G(Z)||J<=0)return z;try{if((await Y4(Z)).isSymbolicLink())return z;let W=new Set(($.protectedPaths??[]).map((L)=>S$(L))),Q=await Q8(Z,{withFileTypes:!0}),V=[];await Promise.all(Q.map(async(L)=>{if(!L.isFile())return;let M=CG(L.name);if(!M&&!W4(L.name))return;let F=f6(Z,L.name);try{let N=await Y4(F);if(!N.isFile()||N.isSymbolicLink())return;V.push({path:F,size:N.size,mtimeMs:N.mtimeMs,partial:M,...!M&&{artifactGroup:L.name.replace(Q4,"")}})}catch{}}));let j=V.reduce((L,M)=>L+M.size,0),B=0,q=0,H=async(L)=>{try{await j8(L.path),j-=L.size,q+=L.size,B+=1}catch{}},U=V.filter((L)=>L.partial).sort((L,M)=>L.mtimeMs-M.mtimeMs||L.path.localeCompare(M.path));for(let L of U){if(W.has(S$(L.path)))continue;if(X-L.mtimeMs<Y)continue;await H(L)}let x=new Map;for(let L of V){if(L.partial||!L.artifactGroup)continue;let M=x.get(L.artifactGroup)??{files:[],newestMtimeMs:0};M.files.push(L),M.newestMtimeMs=Math.max(M.newestMtimeMs,L.mtimeMs),x.set(L.artifactGroup,M)}let O=[...x.entries()].sort(([L,M],[F,N])=>M.newestMtimeMs-N.newestMtimeMs||L.localeCompare(F));for(let[,L]of O){if(j<=J)break;if(X-L.newestMtimeMs<G)continue;if(L.files.some((M)=>W.has(S$(M.path))))continue;for(let M of L.files)await H(M)}if(B>0)P.debug("dump","removed old dump files",{removed:B,freedBytes:q});return{removed:B,freedBytes:q}}catch{return z}}function PG($,Z){let J=Date.now();if(J-K4<UG)return;K4=J,RG({dumpDir:$,protectedPaths:Z}).catch(()=>{})}function FG($){let Z=$.trim().split(/\s+/).filter(Boolean);if(Z.length===0)return{type:"status"};if(Z.length===1&&Z[0]==="on")return{type:"enable"};if(Z.length===1&&Z[0]==="off")return{type:"disable"};return{type:"usage"}}function w6($){let Z=$?.enabled??P1;return[zG,"",`- Enabled: ${Z?"enabled":"disabled"}`,`- Directory: ${I$()}`,"- Persisted: ~/.config/opencode/anthropic-auth.json","- Captures: final rewritten Anthropic body in direct and relay modes; request/relay metadata is redacted","- Warning: body dumps may contain prompt/session content; turn this off after debugging"].join(`
12
- `)}function oj($){let Z=FG($.argumentsText),J=$.enabled??P1;if(Z.type==="status")return w6({enabled:J});if(Z.type==="enable")return[KG,"",w6({enabled:!0})].join(`
13
- `);if(Z.type==="disable")return[WG,"",w6({enabled:!1})].join(`
14
- `);return[VG,"",QG,"",w6({enabled:J})].join(`
15
- `)}function V4($){return $.length<=16?$:`${$.slice(0,12)}…`}function S6($,Z=80){let J=$.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!J)return"session-unknown";return J.length<=Z?J:J.slice(0,Z)}function AG($){if($.transport!=="direct")return`${$.transport}-p${$.protocol}-${$.mode}`;return`direct${$.route?`-${S6($.route)}`:""}`}function U8($){if($==="cachekeep")return"-prewarm-cachekeep";if($==="start")return"-start";return""}function wG($){let Z=$.affinity?.trim();if(Z)return`session:${Z}`;return`request:${$.route??"direct"}:${$.url??""}`}function TG($,Z){if(!$.endsWith(".body.json"))return;let J=$.replace(Q4,""),X=H8.exec(J)?.[1];if(!X||!B8.test(X)&&!q8.test(X))return;let G=U8("cachekeep"),Y=[{prefix:S6(Z),tag:null},{prefix:`${S6(Z,80-G.length)}${G}`,tag:"cachekeep"}];for(let z of Y){if(!X.startsWith(`${z.prefix}-`))continue;let K=X.slice(z.prefix.length);if(xG.test(K)||OG.test(K))return z.tag}return}async function SG($){let Z=$.affinity?.trim();if(!Z)return;let J=I$(),X;try{X=await Q8(J)}catch{return}let G=X.map((Y)=>({name:Y,tag:TG(Y,Z)})).filter((Y)=>Y.tag!==void 0).sort((Y,z)=>z.name.localeCompare(Y.name));for(let Y of G)try{let z=f6(J,Y.name),K=z.replace(/\.body\.json$/,".meta.json");if(!(await Y4(z)).isFile())continue;let W=JSON.parse(await W8(K,"utf8"));if(W.session!==V4(Z)||(Y.tag===null?W.tag!=null:W.tag!==Y.tag))continue;return await W8(z,"utf8")}catch{}return}function IG($,Z){if(!R1.has($))while(R1.size>=DG){let J=R1.keys().next().value;if(J===void 0)break;R1.delete(J)}R1.set($,Z)}function fG($){if($==null)return;return Object.fromEntries(new Headers($).entries())}function L8($){return $G("sha256").update($).digest("hex")}function bG($){return r5($)}function kG($,Z){if($==null)return null;if($===Z)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:$.length,currentBytes:Z.length};let J=0;while(J<$.length&&J<Z.length&&$[J]===Z[J])J+=1;let X=$.length-1,G=Z.length-1;while(X>=J&&G>=J&&$[X]===Z[G])X-=1,G-=1;return{changed:!0,firstByte:J,lastPreviousByte:X,lastCurrentByte:G,changedPreviousBytes:X-J+1,changedCurrentBytes:G-J+1,previousBytes:$.length,currentBytes:Z.length}}function EG($){try{let Z=q0($);return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)?Z:null}catch(Z){return l(`dump body parse failed: ${Z instanceof Error?Z.message:String(Z)}`),null}}function G4($){return L8(JSON.stringify($))}function vG($){let Z=EG($);if(!Z)return{parseable:!1};let J=Array.isArray(Z.messages)?Z.messages:[],X=Array.isArray(Z.system)?Z.system:[],G=J[0],Y=J.slice(1);return{parseable:!0,model:typeof Z.model==="string"?Z.model:void 0,stream:Z.stream,systemCount:X.length,messagesCount:J.length,systemHash:G4(X),message0Hash:G===void 0?null:G4(G),message0Bytes:G===void 0?0:JSON.stringify(G).length,messagesAfter0Hash:G4(Y),messagesAfter0Bytes:JSON.stringify(Y).length,cch:bG($)}}function I6($){if(Array.isArray($))return $.map(I6);if($==null||typeof $!=="object")return $;let Z={};for(let[J,X]of Object.entries($)){let G=J.toLowerCase();if(G==="authorization"||G==="x-api-key"||G==="cookie"||G==="set-cookie"||V8(J)){Z[J]="[redacted]";continue}Z[J]=I6(X)}return Z}async function N8($){if(!P1)return null;z4+=1;let Z=$.affinity?.trim()||"session-unknown",J=U8($.tag),X=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(z4).padStart(6,"0")}-${S6(Z,80-J.length)}${J}-${AG($)}`,G=I$(),Y=f6(G,X),z={body:`${Y}.body.json`,metadata:`${Y}.meta.json`,response:`${Y}.response.json`};if($.payload!==void 0)z.relay=`${Y}.relay.json`;if($.request!==void 0)z.request=`${Y}.request.json`;try{await JG(G,{recursive:!0});let K=$.previousBodyText??await SG($),W={id:X,createdAt:new Date().toISOString(),session:V4(Z),transport:$.transport,protocol:$.protocol,mode:$.mode,route:$.route,status:$.status,error:$.error,tag:$.tag,bodyBytes:$.bodyText.length,relayBytes:$.relayBytes,bodyHash:L8($.bodyText),diff:kG(K,$.bodyText),body:vG($.bodyText),files:z},Q=[T$(z.body,$.bodyText),T$(z.metadata,`${JSON.stringify(W,null,2)}
16
- `)];if($.payload!==void 0&&z.relay)Q.push(T$(z.relay,`${JSON.stringify(I6($.payload),null,2)}
17
- `));if($.request!==void 0&&z.request)Q.push(T$(z.request,`${JSON.stringify(I6({...$.request,headers:fG($.request.headers)}),null,2)}
18
- `));await Promise.all(Q),PG(G,Object.values(z)),l(`dumped request id=${X} session=${V4(Z)} body=${z.body} meta=${z.metadata}`)}catch(K){return l(`dump failed: ${K instanceof Error?K.message:String(K)}`),null}return{responsePath:z.response,...$.tag?{tag:$.tag}:{}}}async function x8($){if(!P1)return null;let Z=wG($),J=R1.get(Z),X=await N8({affinity:$.affinity,transport:"direct",route:$.route,status:$.status,error:$.error,bodyText:$.bodyText,previousBodyText:J,request:{url:$.url,method:$.method,headers:$.headers},tag:$.tag});return IG(Z,$.bodyText),X}async function O8($){return N8({affinity:$.affinity,transport:$.transport,protocol:$.protocol,mode:$.mode,status:$.status,bodyText:$.bodyText,previousBodyText:$.previousBodyText,payload:$.payload,relayBytes:$.relayBytes,tag:$.tag})}async function D8($,Z){if(!$)return;let J=Z.message!=null&&typeof Z.message==="object"&&!Array.isArray(Z.message)?Z.message:{},X={status:Z.status,stream_complete:Z.complete??!0};if(typeof J.id==="string"&&J.id.length>0)X.message_id=J.id;if(typeof J.model==="string"&&J.model.length>0)X.model=J.model;if(Object.hasOwn(J,"usage"))X.usage=J.usage;if(Object.hasOwn(J,"diagnostics"))X.diagnostics=J.diagnostics;if(typeof J.stop_reason==="string"&&J.stop_reason.length>0)X.stop_reason=J.stop_reason;try{await T$($.responsePath,`${JSON.stringify(X,null,2)}
19
- `)}catch(G){l(`dump response failed: ${G instanceof Error?G.message:String(G)}`)}}var XH="claude-cachekeep",j4=3600000,M8=300000,hG=60000,GH="extended-cache-ttl-2025-04-11",yG=32,_8=16777216,gG=30000,mG=60000,pG=900000,uG=30000,C8="## Claude Cache Keep Status",R8="## Claude Cache Keep Enabled",lG="## Claude Cache Keep Disabled",dG="## Claude Cache Keep Usage",iG="Usage: `/claude-cachekeep`, `/claude-cachekeep always`, `/claude-cachekeep off`, or `/claude-cachekeep HH-HH`.";function b6($){return String($).padStart(2,"0")}function cG($){let Z=$.trim();if(!Z)return{type:"status"};if(Z==="off")return{type:"disable"};if(Z==="always")return{type:"always"};if(Z==="subagents on")return{type:"subagents",enabled:!0};if(Z==="subagents off")return{type:"subagents",enabled:!1};let J=/^(\d{1,2})-(\d{1,2})$/.exec(Z);if(!J)return{type:"usage"};let X=Number(J[1]),G=Number(J[2]);if(!Number.isInteger(X)||!Number.isInteger(G)||X<0||X>23||G<0||G>23||X===G)return{type:"usage"};return{type:"window",startHour:X,endHour:G}}function k6($){let Z=Number($?.cacheKeep?.startHour),J=Number($?.cacheKeep?.endHour);if(!Number.isInteger(Z)||!Number.isInteger(J)||Z<0||Z>23||J<0||J>23||Z===J)return;return{startHour:Z,endHour:J}}function E6($){return $?.cacheKeep?.enabled===!0&&$.cacheKeep.always===!0}function T8($){return $?.cacheKeep?.enabled===!0&&(E6($)||!!k6($))}function sG($){return T8($)&&$?.claudeCache?.enabled===!0&&$.claudeCache.mode==="hybrid"}function nG($,Z=new Date){if(!$)return!1;let J=Z.getHours();if($.startHour<$.endHour)return J>=$.startHour&&J<$.endHour;return J>=$.startHour||J<$.endHour}function P8($,Z=new Date){if($?.cacheKeep?.enabled!==!0)return!1;return E6($)||nG(k6($),Z)}function F8($=new Date){return`${$.getFullYear()}-${b6($.getMonth()+1)}-${b6($.getDate())}`}function S8($,Z=new Date){if($&&$.startHour>$.endHour&&Z.getHours()<$.endHour){let J=new Date(Z);return J.setDate(J.getDate()-1),F8(J)}return F8(Z)}function A8($,Z,J=new Date){return E6($)?"always":S8(Z,J)}function t1($){let Z=$.always?"always (while this process is running)":$.window?`${b6($.window.startHour)}-${b6($.window.endHour)}`:"not configured",J=[`Cache keep: ${$.enabled?"enabled":"disabled"}`,`Schedule: ${Z}`,"Mode requirement: `/claude-cache mode hybrid` must be active."];if(typeof $.hybridActive==="boolean")J.push(`Hybrid active: ${$.hybridActive?"yes":"no"}`);if(typeof $.trackedSessions==="number")J.push(`Tracked sessions: ${$.trackedSessions}`);if($.trackedSessionDetails?.length){J.push("Sessions:");for(let X of $.trackedSessionDetails)J.push(`- ${X.id}`)}if($.nextPrewarmAt)J.push(`Next prewarm: ${new Date($.nextPrewarmAt).toLocaleString()}`);return J.join(`
20
- `)}function YH($){let Z=cG($.argumentsText),J={enabled:$.enabled??!1,always:$.always,window:$.window,trackedSessions:$.trackedSessions,trackedSessionDetails:$.trackedSessionDetails,nextPrewarmAt:$.nextPrewarmAt,hybridActive:$.hybridActive};if(Z.type==="status")return[C8,"",t1(J)].join(`
21
- `);if(Z.type==="disable")return[lG,"",t1({...J,enabled:!1})].join(`
22
- `);if(Z.type==="always")return[R8,"",t1({...J,enabled:!0,always:!0,window:void 0})].join(`
23
- `);if(Z.type==="window")return[R8,"",t1({...J,enabled:!0,always:!1,window:{startHour:Z.startHour,endHour:Z.endHour}})].join(`
24
- `);if(Z.type==="subagents")return[C8,"",t1(J),"",`Subagent tracking: ${Z.enabled?"enabled":"disabled"}`].join(`
25
- `);return[dG,"",iG,"",t1(J)].join(`
26
- `)}function H4($){if(!$||typeof $!=="object")return!1;if(Array.isArray($))return $.some(H4);let Z=$,J=Z.cache_control;if(J&&typeof J==="object"&&J.type==="ephemeral")return!0;return Object.values(Z).some(H4)}async function aG($){let Z;try{Z=JSON.parse($)}catch{return{ok:!1,reason:"body is not valid JSON"}}if(!H4(Z))return{ok:!1,reason:"body has no explicit cache breakpoints"};let J=structuredClone(Z);if($8(J),J.max_tokens=0,delete J.stream,J.thinking?.type==="enabled")delete J.thinking;if(J.output_config?.format)delete J.output_config;let Y=J.tool_choice;if(Y?.type==="tool"||Y?.type==="any")delete J.tool_choice;return{ok:!0,bodyText:await e5(JSON.stringify(K8(J)))}}function w8($,Z){let J=Math.min(pG,mG*2**Math.min(Math.max(Z-1,0),8)),X=2166136261;for(let Y of`${$}:${Z}`)X^=Y.charCodeAt(0),X=Math.imul(X,16777619);let G=(X>>>0)%(Math.min(uG,J/4)+1);return J+G}class tG{options;targets=new Map;timer=null;tickPromise=null;nextPrewarmAttemptId=0;constructor($){this.options=$}start(){if(this.timer)return;if(P.debug("cachekeep","started"),this.timer=(this.options.setIntervalImpl??globalThis.setInterval)(()=>{this.tick().catch(($)=>{P.warn("cachekeep","tick failed",{error:$ instanceof Error?$.message:String($)})})},hG),"unref"in this.timer)this.timer.unref()}stop(){if(!this.timer)return;P.debug("cachekeep","stopped"),(this.options.clearIntervalImpl??globalThis.clearInterval)(this.timer),this.timer=null}stats($,Z=this.options.now?.()??Date.now(),J=!1){let X=J?"always":S8($,new Date(Z)),G=[...this.targets.values()].filter((z)=>z.dayKey===X),Y=G.length?Math.min(...G.map((z)=>z.nextPrewarmAt)):void 0;return{trackedSessions:G.length,nextPrewarmAt:Y}}trackedSessions(){return[...this.targets.values()].map(($)=>({id:$.id,cacheExpiresAt:$.cacheExpiresAt,nextPrewarmAt:$.nextPrewarmAt})).sort(($,Z)=>$.id.localeCompare(Z.id))}trackedOAuthRoute($){let Z=this.targets.get($);return Z?{oauthAccountId:Z.oauthAccountId}:void 0}trackedCount(){return this.targets.size}publishTrackedSessions(){let $=this.options.onTrackedSessionsChanged;if(!$)return;try{Promise.resolve($(this.trackedSessions())).catch((Z)=>{P.warn("cachekeep","failed to publish tracked sessions",{error:Z instanceof Error?Z.message:String(Z)})})}catch(Z){P.warn("cachekeep","failed to publish tracked sessions",{error:Z instanceof Error?Z.message:String(Z)})}}totalBodyBytes(){return[...this.targets.values()].reduce(($,Z)=>$+Z.bodyText.length,0)}evictOldestTarget(){let $=this.targets.keys().next().value;if($!==void 0)this.targets.delete($)}pruneTargets($,Z){for(let[J,X]of this.targets){if(Z&&X.dayKey!==Z){this.targets.delete(J);continue}if($>=X.cacheExpiresAt)this.targets.delete(J)}while(this.targets.size>yG)this.evictOldestTarget();while(this.totalBodyBytes()>_8){let J=this.targets.size;if(this.evictOldestTarget(),this.targets.size===J)break}}track($){if(!$.sessionId)return{tracked:!1,reason:"missing session id"};if(!T8($.storage))return{tracked:!1,reason:"cachekeep disabled"};if($.cacheMode!=="hybrid")return{tracked:!1,reason:"cache mode is not hybrid"};if($.bodyText.length>_8)return{tracked:!1,reason:"body exceeds cachekeep memory budget"};let Z=this.options.now?.()??Date.now(),J=k6($.storage);if(!P8($.storage,new Date(Z)))return{tracked:!1,reason:"outside configured schedule"};let X=A8($.storage,J,new Date(Z));if(this.pruneTargets(Z,X),this.targets.has($.sessionId))this.targets.delete($.sessionId);let G={};return $.headers.forEach((Y,z)=>{G[z]=Y}),this.targets.set($.sessionId,{id:$.sessionId,url:$.url,headers:G,bodyText:$.bodyText,cacheExpiresAt:Z+j4,nextPrewarmAt:Z+j4-M8,consecutiveFailures:0,dayKey:X,oauthAccountId:$.oauthAccountId,oauthAccountIdentity:$.oauthAccountIdentity,accountStoragePath:$.accountStoragePath,isSubagent:$.isSubagent??!1}),this.pruneTargets(Z,X),this.publishTrackedSessions(),this.start(),{tracked:!0}}async prewarmNow($){let Z={};$.headers.forEach((X,G)=>{Z[G]=X});let J={id:$.sessionId,url:$.url,headers:Z,bodyText:$.bodyText,cacheExpiresAt:this.options.now?.()??Date.now(),nextPrewarmAt:this.options.now?.()??Date.now(),consecutiveFailures:0,dayKey:"",oauthAccountId:$.oauthAccountId,oauthAccountIdentity:$.oauthAccountIdentity,accountStoragePath:$.accountStoragePath,isSubagent:$.isSubagent??!1};return this.sendPrewarm(J)}tick(){if(this.tickPromise)return this.tickPromise;let $;return $=this.runTick().finally(()=>{if(this.tickPromise===$)this.tickPromise=null}),this.tickPromise=$,$}async runTick(){let $=await this.options.loadStorage(),Z=k6($),J=this.options.now?.()??Date.now(),X=A8($,Z,new Date(J));if(E6($))for(let G of this.targets.values())G.dayKey="always";if(this.pruneTargets(J,X),!this.targets.size){this.publishTrackedSessions(),this.stop();return}if(!sG($)){this.publishTrackedSessions();return}if(!P8($,new Date(J))){this.publishTrackedSessions();return}P.debug("cachekeep","fired",{targets:this.targets.size});for(let G of this.targets.values()){if(G.nextPrewarmAt>J)continue;try{await this.prewarm(G,J)}catch(Y){P.warn("cachekeep","prewarm failed",{session:G.id,reason:Y instanceof Error?Y.message:String(Y)}),G.consecutiveFailures+=1,G.nextPrewarmAt=J+w8(G.id,G.consecutiveFailures)}}this.publishTrackedSessions()}async sendPrewarm($){let Z={id:++this.nextPrewarmAttemptId,signal:AbortSignal.timeout(this.options.prewarmTimeoutMs??gG)};try{let J=$.bodyText;if(this.options.prepareBody)try{J=await this.options.prepareBody(J,$)}catch(H){P.warn("cachekeep","prepare body failed",{session:$.id,error:H instanceof Error?H.message:String(H)})}let X={...$,bodyText:J},G=await aG(J);if(!G.ok)return G;let Y=this.options.fetchImpl??fetch,z={...X,bodyText:G.bodyText},K=this.options.prepareHeaders?await this.options.prepareHeaders(new Headers($.headers),z,Z):new Headers($.headers);if(!K)return{ok:!1,reason:"OAuth cache prewarm credential is unavailable",transient:!0};K.delete("content-length"),K.delete("transfer-encoding");let W;try{W=await Y($.url,{method:"POST",headers:K,body:G.bodyText,signal:Z.signal})}catch(H){return{ok:!1,reason:H instanceof Error?H.message:String(H),transient:!0}}let Q=this.options.now?.()??Date.now(),V=await W.text().catch(()=>""),j=null;try{j=V?JSON.parse(V):null}catch{}try{await this.options.onResponse?.({target:$,bodyText:G.bodyText,status:W.status,data:j,receivedAt:Q,attempt:Z})}catch{}try{let H=await x8({affinity:$.id,route:"cachekeep",status:W.status,bodyText:G.bodyText,url:$.url,method:"POST",headers:K,tag:"cachekeep"});await D8(H,{status:W.status,message:j})}catch(H){P.debug("cachekeep","dump failed",{session:$.id,error:H instanceof Error?H.message:String(H)})}if(!W.ok)return{ok:!1,reason:V||`HTTP ${W.status}`,status:W.status};let q=(j&&typeof j==="object"&&!Array.isArray(j)?j:null)?.usage;return{ok:!0,...q&&{usage:q}}}finally{try{await this.options.onComplete?.({target:$,attempt:Z})}catch{}}}async prewarm($,Z){let J=await this.sendPrewarm($);if(!J.ok){if(J.status==null&&!J.transient)P.debug("cachekeep","prewarm skipped",{session:$.id,reason:J.reason}),this.targets.delete($.id);else P.warn("cachekeep","prewarm failed",{session:$.id,status:J.status,reason:J.reason}),$.consecutiveFailures+=1,$.nextPrewarmAt=Z+w8($.id,$.consecutiveFailures);return}$.cacheExpiresAt=Z+j4,$.nextPrewarmAt=$.cacheExpiresAt-M8,$.consecutiveFailures=0,P.debug("cachekeep","prewarm succeeded",{session:$.id,...J.usage&&{usage:J.usage}})}}import{randomUUID as I8}from"node:crypto";import{mkdir as oG,readdir as rG,readFile as eG,rename as $Y,rm as f8,writeFile as ZY}from"node:fs/promises";import{tmpdir as JY}from"node:os";import{join as B4}from"node:path";var XY=180000;function GY($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=$;if(typeof Z.id!=="string"||Z.id.length===0||typeof Z.cacheExpiresAt!=="number"||!Number.isFinite(Z.cacheExpiresAt)||typeof Z.nextPrewarmAt!=="number"||!Number.isFinite(Z.nextPrewarmAt))return;return{id:Z.id,cacheExpiresAt:Z.cacheExpiresAt,nextPrewarmAt:Z.nextPrewarmAt}}function YY($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=$;if(Z.version!==1||typeof Z.updatedAt!=="number"||!Number.isFinite(Z.updatedAt)||!Array.isArray(Z.sessions))return;return{version:1,updatedAt:Z.updatedAt,sessions:Z.sessions.flatMap((J)=>{let X=GY(J);return X?[X]:[]})}}function jH($){return B4(JY(),"opencode-anthropic-auth","cachekeep-sessions",$)}class zY{options;filePath;writeChain=Promise.resolve();constructor($){this.options=$;let Z=$.instanceId??`${process.pid}-${I8()}`;this.filePath=B4($.directory,`${Z}.json`)}publish($){let Z=$.map((J)=>({...J}));return this.writeChain=this.writeChain.catch(()=>{}).then(async()=>{if(Z.length===0){await f8(this.filePath,{force:!0});return}await oG(this.options.directory,{recursive:!0,mode:448});let J=`${this.filePath}.${I8()}.tmp`,X={version:1,updatedAt:this.options.now?.()??Date.now(),sessions:Z};await ZY(J,`${JSON.stringify(X)}
27
- `,{mode:384}),await $Y(J,this.filePath)}),this.writeChain}async list($=[]){await this.writeChain.catch(()=>{});let Z=this.options.now?.()??Date.now(),J=this.options.leaseMs??XY,X;try{X=(await rG(this.options.directory)).filter((z)=>z.endsWith(".json"))}catch{X=[]}let G=await Promise.all(X.map(async(z)=>{try{let K=await eG(B4(this.options.directory,z),"utf8");return YY(JSON.parse(K))}catch{return}})),Y=new Map;for(let z of G){if(!z||Z-z.updatedAt>J||z.updatedAt>Z)continue;for(let K of z.sessions){let W=Y.get(K.id);if(!W||K.cacheExpiresAt>W.cacheExpiresAt)Y.set(K.id,K)}}for(let z of $){let K=Y.get(z.id);if(!K||z.cacheExpiresAt>K.cacheExpiresAt)Y.set(z.id,{...z})}return[...Y.values()].sort((z,K)=>z.id.localeCompare(K.id))}async dispose(){await this.writeChain.catch(()=>{}),await f8(this.filePath,{force:!0})}}import{createHash as Rz,randomBytes as Pz,randomUUID as Fz}from"node:crypto";import{constants as U9}from"node:fs";import{chmod as Az,mkdir as E4,open as N9,realpath as wz,rename as Tz,stat as Sz,unlink as x9}from"node:fs/promises";import{basename as O9,dirname as h$,extname as L9,join as D9}from"node:path";import{readdirSync as iY,statSync as cY}from"node:fs";import{tmpdir as sY,userInfo as nY}from"node:os";import{join as v$}from"node:path";import{debuglog as xY}from"node:util";import{createHmac as jY,randomBytes as HY,timingSafeEqual as BY}from"node:crypto";import QY from"node:net";var N0=2,v6=21,h6=5,q4=67108864,R;(function($){$[$.Request=0]="Request",$[$.Response=1]="Response",$[$.Push=2]="Push",$[$.StreamData=3]="StreamData",$[$.StreamEnd=4]="StreamEnd",$[$.Error=5]="Error",$[$.Cancel=6]="Cancel",$[$.Ping=7]="Ping",$[$.Pong=8]="Pong",$[$.Hello=9]="Hello",$[$.HelloAck=10]="HelloAck",$[$.Goodbye=11]="Goodbye"})(R||(R={}));var b8=R.Goodbye;function k8($){return $===R.Cancel||$===R.Ping||$===R.Pong||$===R.Goodbye}var Z0;(function($){$[$.Passive=0]="Passive",$[$.Interactive=1]="Interactive",$[$.Background=2]="Background"})(Z0||(Z0={}));var Y0;(function($){$[$.Normal=0]="Normal",$[$.Expedite=1]="Expedite",$[$.Sheddable=2]="Sheddable"})(Y0||(Y0={}));var KY=1,E8=6,U4=1,WY=8,v8=48,L4=4,h8=192;function U0($,Z,J,X=Y0.Normal){let G=0;if($)G|=KY;if(G|=Z<<U4,J)G|=WY;return G|=X<<L4,G}function y8($){let Z=new Uint8Array(21),J=new DataView(Z.buffer);return J.setUint32(0,$.len,!0),Z[4]=$.ver,Z[5]=$.ty,Z[6]=$.flags,J.setUint16(7,$.channel,!0),J.setUint32(9,$.epoch,!0),J.setBigUint64(13,$.corr,!0),Z}class y extends Error{code;constructor($,Z){super($);this.code=Z,this.name="DecodeError"}}function VY($){let Z=$.len>>>0,J=$.ver>>>0&255,X=$.ty>>>0&255,G=$.flags>>>0&255,Y=$.channel>>>0&65535,z=$.epoch>>>0;if(BigInt.asUintN(64,$.corr),J!==2)throw new y(`unsupported envelope version ${J}`,"unsupported_version");if(X>b8)throw new y(`unknown frame type byte ${X}`,"unknown_frame_type");let K=X;if((G&h8)!==0)throw new y(`reserved flag bits set in flags 0b${G.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((G&E8)>>U4===3)throw new y(`reserved priority bits set in flags 0b${G.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let W=(G&v8)>>L4;if(W===3)throw new y(`reserved admission class set in flags 0b${G.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(W===Y0.Sheddable&&K!==R.Push&&K!==R.StreamData)throw new y(`SHEDDABLE admission class is illegal on ${R[K]} in flags 0b${G.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");if(Y===0&&z!==0)throw new y(`control channel carried nonzero epoch ${z}`,"nonzero_epoch_on_control_channel");if(k8(K)&&Z!==0)throw new y(`pure-header frame ${R[K]} declared non-zero body length ${Z}`,"pure_header_frame_with_body")}function N4($){if($.length<5)throw new y(`header shorter than frozen prefix: have ${$.length} bytes`,"too_short_for_prefix");let Z=$[4];if(Z!==2)throw new y(`unsupported envelope version ${Z}`,"unsupported_version");if($.length<21)throw new y(`header too short for version: have ${$.length} bytes, need 21`,"too_short_for_header");let J=new DataView($.buffer,$.byteOffset,$.byteLength),X=J.getUint32(0,!0),G=$[5];if(G>b8)throw new y(`unknown frame type byte ${G}`,"unknown_frame_type");let Y=G,z=$[6];if((z&h8)!==0)throw new y(`reserved flag bits set in flags 0b${z.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((z&E8)>>U4===3)throw new y(`reserved priority bits set in flags 0b${z.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let K=(z&v8)>>L4;if(K===3)throw new y(`reserved admission class set in flags 0b${z.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(K===Y0.Sheddable&&Y!==R.Push&&Y!==R.StreamData)throw new y(`SHEDDABLE admission class is illegal on ${R[Y]} in flags 0b${z.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");let W=J.getUint16(7,!0),Q=J.getUint32(9,!0);if(W===0&&Q!==0)throw new y(`control channel carried nonzero epoch ${Q}`,"nonzero_epoch_on_control_channel");if(k8(Y)&&X!==0)throw new y(`pure-header frame ${R[Y]} declared non-zero body length ${X}`,"pure_header_frame_with_body");return{len:X,ver:Z,ty:Y,flags:z,channel:W,epoch:Q,corr:J.getBigUint64(13,!0)}}function j0($,Z,J,X,G,Y){return p0(2,$,Z,J,X,G,Y)}function p0($,Z,J,X,G,Y,z){if(z.length>67108864)throw new y(`frame body ${z.length} exceeds max 67108864`,"frame_body_too_large");let K={len:z.length,ver:$,ty:Z,flags:J,channel:X,epoch:G,corr:Y};return VY(K),{header:K,body:z}}function u0($){if($.header.len!==$.body.length)throw new y(`frame header length ${$.header.len} does not match body length ${$.body.length}`,"frame_length_mismatch");let Z=y8($.header),J=new Uint8Array(Z.length+$.body.length);return J.set(Z,0),J.set($.body,Z.length),J}class a0 extends Error{}class f0 extends Error{}class l0 extends Error{cause;constructor($,Z){super($);this.cause=Z}}class W1 extends Error{cause;constructor($,Z){super($);this.cause=Z}}function g8($){return Buffer.from($.buffer,$.byteOffset,$.byteLength)}var m8=Symbol("subc.socket.writeBorrowed"),p8=Symbol("subc.socket.writeTrackedBorrowed");function d0($,Z,J){let X=$[m8];return X?X.call($,Z,J):$.write(Z,J)}function x4($,Z,J){let X=$[p8];return X?X.call($,Z,J):$.writeTracked(Z,J)}class F1{sock;chunks=[];buffered=0;waiter=null;closedErr=null;bufferedBytes(){return this.buffered}constructor($){this.sock=$,$.on("data",(J)=>{this.chunks.push(J),this.buffered+=J.length,this.tryServe()});let Z=(J)=>{if(!this.closedErr)this.closedErr=J;this.tryServe()};$.on("error",(J)=>Z(J instanceof Error?J:Error(String(J)))),$.on("end",()=>Z(new a0("subc closed the connection"))),$.on("close",()=>Z(new a0("subc connection closed")))}localPort(){return this.sock.localPort??null}static connect($,Z,J){return new Promise((X,G)=>{let Y=QY.connect({host:$,port:Z});Y.setNoDelay(!0);let z=setTimeout(()=>{Y.destroy(),G(new f0(`timed out connecting to ${$}:${Z}`))},Math.max(0,J-Date.now()));Y.once("connect",()=>{clearTimeout(z),X(new F1(Y))}),Y.once("error",(K)=>{clearTimeout(z),G(K)})})}async readFrame($,Z,J){let X=await this.readExact(h6,$),G=X[4];if(G!==N0)throw new y(`unsupported envelope version ${G}`,"unsupported_version");let Y=await this.readExact(v6-h6,$),z=new Uint8Array(v6);z.set(X),z.set(Y,h6);let K=N4(z);if(K.len>q4)throw new y(`frame body ${K.len} exceeds max ${q4}`,"frame_body_too_large");J?.();let W=typeof Z==="number"?Z:Date.now()+Z.afterHeaderMs,Q=K.len===0?new Uint8Array(0):await this.readExact(K.len,W);return{header:K,body:Q}}readExact($,Z){if(this.waiter)return Promise.reject(Error("concurrent readExact is not supported"));if($===0)return Promise.resolve(new Uint8Array(0));return new Promise((J,X)=>{let G=null;if(Number.isFinite(Z)){let Y=Z-Date.now();if(Y<=0){X(new f0(`timed out waiting for ${$} bytes`));return}G=setTimeout(()=>{this.waiter=null,X(new f0(`timed out waiting for ${$} bytes`))},Y)}this.waiter={need:$,resolve:J,reject:X,timer:G},this.tryServe()})}async write($,Z){await this.writeBuffer(Buffer.from($),Z)}writeTracked($,Z){return this.writeTrackedBuffer(Buffer.from($),Z)}async[m8]($,Z){await this.writeBuffer(g8($),Z)}[p8]($,Z){return this.writeTrackedBuffer(g8($),Z)}async writeBuffer($,Z){try{await this.writeTrackedBuffer($,Z).completed}catch(J){if(J instanceof l0||J instanceof W1)throw J.cause??J;throw J}}writeTrackedBuffer($,Z){if(this.closedErr)return{queued:!1,completed:Promise.reject(new l0("subc socket was closed before bytes could be queued",this.closedErr))};let J=!1,X=!1,G=null,Y=new Promise((z,K)=>{let W=(V)=>{if(X)return;if(X=!0,G)clearTimeout(G);V()},Q=Z-Date.now();if(Q<=0){W(()=>K(new l0("timed out before bytes could be queued to subc",new f0("timed out writing to subc"))));return}G=setTimeout(()=>{let V=new f0("timed out writing to subc");W(()=>K(J?new W1("timed out after bytes were handed to the subc socket",V):new l0("timed out before bytes could be queued to subc",V)))},Q);try{this.sock.write($,(V)=>{W(()=>{if(V)K(new W1("subc socket reported a write error after bytes were handed to the socket",V instanceof Error?V:Error(String(V))));else z()})}),J=!0}catch(V){W(()=>K(new l0("subc socket write threw before bytes could be queued",V instanceof Error?V:Error(String(V)))))}});return{queued:J,completed:Y}}close(){this.sock.destroy()}tryServe(){let $=this.waiter;if(!$)return;if(this.buffered>=$.need){let Z=this.take($.need);if(this.waiter=null,$.timer)clearTimeout($.timer);$.resolve(Z);return}if(this.closedErr){if(this.waiter=null,$.timer)clearTimeout($.timer);$.reject(this.closedErr)}}take($){let Z=Buffer.allocUnsafe($),J=0;while(J<$){let X=this.chunks[0],G=$-J;if(X.length<=G)X.copy(Z,J),J+=X.length,this.chunks.shift();else X.copy(Z,J,0,G),this.chunks[0]=X.subarray(G),J+=G}return this.buffered-=$,Z}}var d8=32;var y6=4096,i8="subc-server-v1",c8="subc-client-v1",qY="client";class H0 extends Error{}function D4($,Z,J,X,G){let Y=jY("sha256",Buffer.from($));return Y.update(Buffer.from(Z,"utf8")),Y.update(Buffer.from(J)),Y.update(Buffer.from(X)),Y.update(Buffer.from(G)),new Uint8Array(Y.digest())}function u8($,Z){if($.length!==Z.length)return!1;return BY(Buffer.from($),Buffer.from(Z))}async function l8($,Z,J){let X=Buffer.from(JSON.stringify(Z),"utf8");if(X.length>y6)throw new H0(`auth message too large: ${X.length} > ${y6}`);let G=new Uint8Array(4);new DataView(G.buffer).setUint32(0,X.length,!0),await d0($,G,J),await d0($,X,J)}async function UY($,Z){let J=await $.readExact(4,Z),X=new DataView(J.buffer,J.byteOffset,4).getUint32(0,!0);if(X>y6)throw new H0(`auth message too large: ${X} > ${y6}`);let G=X===0?new Uint8Array(0):await $.readExact(X,Z);try{return JSON.parse(Buffer.from(G).toString("utf8"))}catch(Y){throw new H0(`auth message JSON decode failed: ${String(Y)}`)}}function O4($,Z){if(!Array.isArray($))throw new H0(`auth field '${Z}' must be a byte array`);for(let J of $)if(typeof J!=="number"||!Number.isInteger(J)||J<0||J>255)throw new H0(`auth field '${Z}' has invalid byte ${String(J)}`);return Uint8Array.from($)}async function f$($,Z,J){let X=new Uint8Array(HY(d8));await l8($,{client_nonce:Array.from(X),role:qY},J);let G=await UY($,J),Y=O4(G.server_nonce,"server_nonce"),z=O4(G.daemon_id,"daemon_id"),K=O4(G.server_proof,"server_proof"),W=D4(Z.key,i8,X,Y,z);if(!u8(W,K))throw new H0("server proof mismatch — wrong key or impostor daemon");if(!u8(z,Z.daemonId))throw new H0("daemon id mismatch — connection file points at a different daemon");let Q=D4(Z.key,c8,X,Y,z);await l8($,{client_auth:Array.from(Q)},J)}import{promises as M4}from"node:fs";var s8=1,n8=32,a8=16;class J0 extends Error{}function t8($,Z){if(!Array.isArray($))throw new J0(`connection file field '${Z}' must be a JSON array of bytes`);for(let J of $)if(typeof J!=="number"||!Number.isInteger(J)||J<0||J>255)throw new J0(`connection file field '${Z}' has invalid byte ${String(J)}`);return Uint8Array.from($)}function LY($){if($.schema!==s8)throw new J0(`unsupported connection file schema ${$.schema}; expected ${s8}`);if($.endpoints.length===0)throw new J0("connection file must include at least one endpoint");if($.key.length<n8)throw new J0(`connection file key is too short: ${$.key.length} bytes, need at least ${n8}`);if($.daemonId.length!==a8)throw new J0(`connection file daemon_id must be ${a8} bytes, got ${$.daemonId.length}`)}async function NY($){if(process.platform==="win32")return;let J=(await M4.stat($)).mode&511;if((J&63)!==0)throw new J0(`connection file ${$} has insecure permissions 0o${J.toString(8)}; expected owner-only 0600`)}async function o1($){await NY($);let Z=await M4.readFile($,"utf8"),J;try{J=JSON.parse(Z)}catch(K){throw new J0(`connection file JSON read failed for ${$}: ${String(K)}`)}let X=J.wire_version;if(X!==void 0&&X!==N0)throw new J0(`connection file wire_version ${String(X)} but this client speaks ${N0}; the client library must be upgraded`);let G=J.endpoints;if(!Array.isArray(G))throw new J0("connection file 'endpoints' must be an array");let Y=G.map((K)=>{let W=K;if(typeof W.host!=="string"||typeof W.port!=="number")throw new J0("connection file endpoint must be { host: string, port: number }");return{host:W.host,port:W.port}}),z={schema:J.schema,endpoints:Y,key:t8(J.key,"key"),daemonId:t8(J.daemon_id,"daemon_id"),pid:J.pid,daemonVer:J.daemon_ver??""};return LY(z),z}var o8=new WeakMap;class g6{channel;epoch;constructor($,Z,J){if(!Number.isInteger($)||$<=0||$>65535)throw RangeError(`route channel must be an integer in 1..65535, got ${$}`);if(!Number.isInteger(Z)||Z<=0||Z>4294967295)throw RangeError(`route epoch must be an integer in 1..4294967295, got ${Z}`);this.channel=$,this.epoch=Z,o8.set(this,J),Object.freeze(this)}static create($,Z,J){return new g6($,Z,J)}}function m6($,Z,J){return g6.create($,Z,J)}class t0 extends Error{handle;code="stale_route_handle";constructor($){super(`route handle (${$.channel}, ${$.epoch}) is not live on the current connection`);this.handle=$,this.name="StaleRouteHandleError"}}function r1(){return Object.freeze({})}function b$($,Z){return o8.get($)===Z}function p6($,Z){return $===Z}var OY=xY("subc-client"),DY=1e4,k$=30000,MY=50,_Y=2000,r8="request_deadline",_4="deadline_exceeded_no_drop_observed",CY=30000,RY=30000,e8=new Uint8Array(0),PY="management_surface",Z9="SUBC_MODULE_ID",J9="SUBC_LAUNCH_NONCE",c6={baseMs:100,capMs:2000,maxAttempts:6};class X0 extends Error{kind;code;cause;constructor($,Z,J,X){super(Z);this.kind=$,this.code=J,this.cause=X,this.name="SubcCallError"}}class m extends Error{code;constructor($,Z){super($);this.code=Z}}class A1{sock;currentConn;opts;nextCorr=1n;pending=new Map;lateResponses=new Map;routes=new Map;liveRoutes=new Map;connectionToken=r1();ingressEpochDropCount=0;closedErr=null;closeStarted=!1;reconnecting=null;generation=1;readerActive=!1;constructor($,Z,J){this.sock=$,this.currentConn=Z,this.opts=J,this.readLoop($,this.generation)}get conn(){return this.currentConn}static async connect($){let Z=AY($),J=await A1.openConnection(Z);return new A1(J.sock,J.conn,Z)}async catalogList($){let Z=this.encode($===void 0?{op:"catalog.list"}:{op:"catalog.list",module_id:$}),J=await this.controlRpc(Z);return this.parseJson(J).modules??[]}async routeOpen($,Z,J={}){let X=C4(J),G=J.consumerCapabilities,Y=this.encode({op:"route.open",target:$,identity:Z,...X?{consumer_identity:X}:{},...G!==void 0?{consumer_capabilities:G}:{}}),z=null,K=(Q)=>{if(Q.header.ty!==R.Response)return!0;let V=this.parseJson(Q);if(typeof V.route_channel!=="number"||typeof V.route_epoch!=="number")throw new m(`route.open returned no route handle: ${JSON.stringify(V)}`);return z=this.installRoute(V.route_channel,V.route_epoch),!0},W=(Q)=>{if(Q.header.ty!==R.Response)return;try{let V=this.parseJson(Q);if(typeof V.route_channel!=="number"||typeof V.route_epoch!=="number")return;let j=this.installRoute(V.route_channel,V.route_epoch);this.failHandle(j,new m("late route.open was closed","route_closed")),this.liveRoutes.delete(j.channel),this.sendRouteGoodbye(j,!0)}catch{this.closeConnectionAfterCleanupFailure()}};if(await this.controlRpc(Y,K,W),!z)throw new m("route.open response was not installed");return z}async request($,Z,J={}){this.assertLiveHandle($);let X=Z instanceof Uint8Array?Z:this.encode(Z),G=J.priority??Z0.Interactive,Y=J.admissionClass??Y0.Normal,z=await this.send($,X,G,Y,J.timeoutMs,J.onProgress);return this.parseJson(z)}async call($,Z,J,X={}){let G=J===void 0?{method:Z}:{method:Z,params:J},Y=!1;for(;;){let z=await this.cachedRouteHandle($,X);try{return await this.managedRequest(z,G,X)}catch(K){if(!(K instanceof X0))throw this.terminalCallError("managed call failed",K);let W=K.code==="unknown_channel"||K.code==="stale_route_epoch";if(W&&!Y&&!this.closeStarted){Y=!0,this.evictRouteHandle(z);continue}if(W&&Y)this.evictRouteHandle(z);if(K.kind==="not_sent"){try{await this.reconnectAfterDrop(K)}catch(Q){throw this.notSentRecoveryError("managed call was not sent",Q)}continue}if(K.kind==="outcome_unknown"&&K.code!==_4)this.scheduleReconnectAfterDrop(K);else if(K.kind==="outcome_unknown"&&K.code===_4)this.probeLivenessAfterDeadline();throw K}}}subscribe($,Z,J,X={}){this.assertLiveHandle($);let G=Z instanceof Uint8Array?Z:this.encode(Z),Y=X.priority??Z0.Interactive,z=X.admissionClass??Y0.Normal,K=this.allocateCorr(),W=l6($,K),Q=null,V=null,j=new Promise((H,U)=>{if(this.closedErr){U(this.closedErr);return}V=H,Q={handle:$,resolve:()=>H(),reject:U,onProgress:J,timer:null,subscription:!0},this.pending.set(W,Q);let x=j0(R.Request,U0(!1,Y,!1,z),$.channel,$.epoch,K,G);d0(this.sock,u0(x),Date.now()+k$).catch((O)=>{let L=this.pending.get(W);if(L)this.rejectPending(W,L,O instanceof Error?O:new m(String(O)))})}),B=!1;return{unsubscribe:()=>{if(B)return;if(B=!0,Q&&V)this.settle(W,Q,V);if(this.isLiveHandle($))this.cancel($,K,Y)},closed:j}}cancel($,Z,J=Z0.Interactive){this.assertLiveHandle($);let X=j0(R.Cancel,U0(!1,J,!1),$.channel,$.epoch,Z,e8);d0(this.sock,u0(X),Date.now()+k$).catch(()=>{return})}async routePoll($,Z){this.assertLiveHandle($);let J=this.encode({op:"route.poll",route_channel:$.channel,route_epoch:$.epoch,kind:Z}),X=await this.controlRpc(J,(G)=>{if(G.header.ty!==R.Response)return!0;let Y=this.parseJson(G);return Y.route_channel===$.channel&&Y.route_epoch===$.epoch});return this.parseJson(X)}async closeRoute($,Z={}){this.assertLiveHandle($);for(let[J,X]of this.routes)if(X.handle&&p6(X.handle,$))X.closed=!0,X.handle=null,this.routes.delete(J);if(Z.drain)await this.drainUnaryOnHandle($);if(this.failHandle($,new m("route closed by closeRoute","route_closed")),this.liveRoutes.get($.channel)===$)this.liveRoutes.delete($.channel);this.sendRouteGoodbye($)}async closeManagedRoute($,Z,J={}){let X=$9($,Z,C4(J)),G=this.routes.get(X);if(!G)return;G.closed=!0,this.routes.delete(X);let Y=G.handle;if(G.handle=null,Y)await this.closeRoute(Y,J)}async closeRouteChannel($,Z={}){await this.closeRoute($,Z)}close(){this.closeStarted=!0,this.fail(new m("client closed")),this.sock.close()}drainUnaryOnHandle($){let Z=[];for(let J of this.pending.values())if(J.handle===$&&!J.subscription)Z.push(new Promise((X)=>{let G=J.onSettle;J.onSettle=()=>{G?.(),X()}}));return Promise.all(Z).then(()=>{return})}sendRouteGoodbye($,Z=!1){if(this.assertLiveConnection($),this.closedErr){if(Z)this.closeConnectionAfterCleanupFailure();return}let J=j0(R.Goodbye,U0(!1,Z0.Interactive,!1),$.channel,$.epoch,0n,e8),X=x4(this.sock,u0(J),Date.now()+k$);if(!X.queued&&Z)this.closeConnectionAfterCleanupFailure();X.completed.catch(()=>{if(Z&&!X.queued)this.closeConnectionAfterCleanupFailure()})}static async openConnection($){let Z=await o1($.connectionFile),J=Date.now()+($.handshakeTimeoutMs??DY),X=Z.endpoints[0],G=await F1.connect(X.host,X.port,J);try{await f$(G,Z,J)}catch(Y){throw G.close(),Y}return{sock:G,conn:Z}}async controlRpc($,Z,J){return this.send(null,$,Z0.Interactive,Y0.Normal,void 0,void 0,Z,J)}send($,Z,J,X,G,Y,z,K){if($)this.assertLiveHandle($);if(this.closedErr)return Promise.reject(this.closedErr);let W;try{W=this.allocateCorr()}catch(q){return Promise.reject(q)}let Q=l6($,W),V=$?.channel??0,j=$?.epoch??0,B=j0(R.Request,U0(!1,J,!1,X),V,j,W,Z);return new Promise((q,H)=>{let U=G??k$,x={handle:$,resolve:q,reject:H,onProgress:Y,timer:null,acceptFrame:z,onLateResponse:K};x.timer=setTimeout(()=>this.arbitrateTimeout(Q,x,V,W,U),U),this.pending.set(Q,x),d0(this.sock,u0(B),Date.now()+U).catch((O)=>{let L=this.pending.get(Q);if(L)this.rejectPending(Q,L,O instanceof Error?O:new m(String(O)))})})}arbitrateTimeout($,Z,J,X,G){let Y=()=>{if(Z.onLateResponse)this.lateResponses.set($,Z.onLateResponse);this.rejectPending($,Z,new m(this.timeoutMessage(J,X,G),r8))},z=Date.now()+this.opts.timeoutArbitrationGraceMs,K=()=>{if(this.pending.get($)!==Z)return;if((this.readerActive||this.sock.bufferedBytes()>0)&&Date.now()<z){setImmediate(K);return}Y()};setImmediate(K)}async managedRequest($,Z,J){let X=Z instanceof Uint8Array?Z:this.encode(Z),G=J.priority??Z0.Interactive,Y=J.admissionClass??Y0.Normal;try{let z=await this.sendManaged($,X,G,Y,J.timeoutMs,J.onProgress);return this.parseJson(z)}catch(z){if(z instanceof X0)throw z;throw this.terminalCallError("managed call failed",z)}}sendManaged($,Z,J,X,G,Y){try{this.assertLiveHandle($)}catch(j){return Promise.reject(this.notSentCallError("request used a stale route handle",j))}if(this.closedErr)return Promise.reject(this.notSentCallError("request was not sent because the subc connection was already closed",this.closedErr));let z;try{z=this.allocateCorr()}catch(j){return Promise.reject(this.notSentCallError("request correlation allocator was exhausted",j))}let K=l6($,z),W=j0(R.Request,U0(!1,J,!1,X),$.channel,$.epoch,z,Z),Q=!1,V=(j)=>{if(!Q)return this.notSentCallError("request bytes were not queued to the subc socket",j);if(j instanceof m&&j.code===r8)return new X0("outcome_unknown",`managed call deadline exceeded after request bytes were queued to the local socket; no terminal response was observed; outcome unknown${u6(j)}`,_4,j);return this.outcomeUnknownCallError("connection dropped before the managed call returned a response",j)};return new Promise((j,B)=>{let q=G??k$,H={handle:$,resolve:j,reject:B,onProgress:Y,timer:null,classifyFailure:V};H.timer=setTimeout(()=>this.arbitrateTimeout(K,H,$.channel,z,q),q),this.pending.set(K,H);let U=x4(this.sock,u0(W),Date.now()+q);Q=U.queued,U.completed.catch((x)=>{let O=this.pending.get(K);if(O)this.rejectPending(K,O,x instanceof Error?x:new m(String(x)))})})}async cachedRouteHandle($,Z){let J=Z.identity??this.opts.identity;if(!J)throw new X0("terminal","managed call requires a BindIdentity in SubcClient.connect({ identity }) or call(..., { identity })","missing_identity");let X={kind:Z.targetKind??this.opts.targetKind,module_id:$},G=C4(Z),Y=$9(X,J,G),z=this.routes.get(Y);if(!z)z={key:Y,moduleId:$,target:X,identity:J,consumerIdentity:G,handle:null,opening:null},this.routes.set(Y,z);if(z.handle&&this.isLiveHandle(z.handle))return z.handle;if(!z.opening)z.opening=this.openCachedRoute(z).finally(()=>{z.opening=null});return z.opening}async openCachedRoute($){let Z=Date.now()+CY,J=this.opts.reconnectBackoff.baseMs,X=0;for(;;){if($.closed)throw this.routeClosedDuringOpen();try{await this.ensureConnectedForManaged()}catch(G){throw this.notSentRecoveryError("route.open could not run because reconnect failed",G)}if($.handle&&this.isLiveHandle($.handle))return $.handle;try{let G=await this.routeOpen($.target,$.identity,{consumerIdentity:$.consumerIdentity??null});if($.closed)throw this.liveRoutes.delete(G.channel),this.sendRouteGoodbye(G),this.routeClosedDuringOpen();return $.handle=G,G}catch(G){if(G instanceof X0&&G.code==="route_closed")throw G;if(!this.closeStarted&&d6(G)){try{await this.reconnectAfterDrop(G)}catch(Y){throw this.notSentRecoveryError("route.open was not sent and reconnect failed",Y)}continue}if(!this.closeStarted&&G instanceof m&&FY(G.code)){if(X+=1,X<this.opts.reconnectBackoff.maxAttempts&&Date.now()<Z){await this.opts.sleep(J),J=Math.min(J*2,this.opts.reconnectBackoff.capMs);continue}throw this.notSentCallError(`route.open failed for module ${$.moduleId}: ${G.code} (retry budget exhausted)`,G)}throw this.terminalCallError(`route.open failed for module ${$.moduleId}`,G)}}}lastInboundAtMs=0;livenessProbe=null;hasControlPending(){for(let $ of this.pending.values())if($.handle===null)return!0;return!1}probeLivenessAfterDeadline(){if(this.livenessProbe||this.closeStarted||this.closedErr)return;if(this.hasControlPending())return;let $=this.sock,Z=this.generation,J;try{J=this.allocateCorr()}catch{return}let X=Date.now(),G=j0(R.Ping,U0(!1,Z0.Interactive,!1,Y0.Normal),0,0,J,new Uint8Array),Y=(async()=>{if(await d0($,u0(G),X+this.opts.livenessProbeWindowMs).catch(()=>{}),await this.opts.sleep(this.opts.livenessProbeWindowMs),this.sock!==$||this.generation!==Z||this.closeStarted)return;if(this.lastInboundAtMs>=X)return;if(this.hasControlPending())return;this.fail(new a0(`liveness probe convicted a half-open socket: no inbound frame for ${this.opts.livenessProbeWindowMs}ms after a channel-0 Ping (deadline-no-drop settles preceded this); closing so the next call reconnects`)),$.close()})().finally(()=>{this.livenessProbe=null});this.livenessProbe=Y}async ensureConnectedForManaged(){if(this.closeStarted)throw new m("client closed");if(this.reconnecting)await this.reconnecting;if(this.closedErr)await this.reconnectAfterDrop(this.closedErr)}scheduleReconnectAfterDrop($){if(this.closeStarted||this.reconnecting)return;this.reconnectAfterDrop($).catch(()=>{})}reconnectAfterDrop($){if(this.closeStarted)return Promise.reject(new m("client closed"));if(this.reconnecting)return this.reconnecting;let Z=this.reconnectWithRetry($).finally(()=>{if(this.reconnecting===Z)this.reconnecting=null});return this.reconnecting=Z,Z}async reconnectWithRetry($){let Z=0,J=this.opts.reconnectBackoff.baseMs;for(;;){if(this.closeStarted)throw new m("client closed");Z+=1;try{let X=await A1.openConnection(this.opts);if(this.closeStarted)throw X.sock.close(),new m("client closed");this.replaceConnection(X),await this.reopenCachedRoutes();return}catch(X){if(!d6(X)||Z>=this.opts.reconnectBackoff.maxAttempts){if(X instanceof H0&&Z>1)throw new H0(`reconnect gave up after ${Z} attempts: ${X.message} — the connection file and the daemon's key disagree persistently `+"(daemon restarting in a loop, split connection-file paths, or a genuinely foreign daemon on this port); check the daemon, then restart this host app");throw X}await this.opts.sleep(J),J=Math.min(J*2,this.opts.reconnectBackoff.capMs)}}}replaceConnection($){this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.closedErr=null,this.generation+=1,this.connectionToken=r1(),this.liveRoutes.clear(),this.lateResponses.clear(),this.nextCorr=1n,this.readLoop($.sock,this.generation)}async reopenCachedRoutes(){for(let $ of this.routes.values())$.handle=null;for(let $ of this.routes.values()){if($.closed)continue;let Z=await this.routeOpen($.target,$.identity,{consumerIdentity:$.consumerIdentity??null});if($.closed){this.liveRoutes.delete(Z.channel),this.sendRouteGoodbye(Z);continue}$.handle=Z}}timeoutMessage($,Z,J){let X=this.sock.localPort();return`request on ${X===null?"channel":`local_port=${X} channel`} ${$} corr ${Z} timed out after ${J}ms`}routeClosedDuringOpen(){return new X0("not_sent","route was closed before route.open completed","route_closed")}async readLoop($,Z){try{for(;;){this.readerActive=!1;let J=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:RY},()=>{this.readerActive=!0});try{if(this.sock===$&&this.generation===Z)this.dispatch(J)}finally{this.readerActive=!1}}}catch(J){if(this.sock===$&&this.generation===Z)this.fail(J instanceof Error?J:new m(String(J)))}}dispatch($){if(this.lastInboundAtMs=Date.now(),$.header.channel===0&&$.header.ty===R.Push){let Y=this.opts.onControlPush;if(Y){let z=null;try{let K=this.parseJson($);if(K&&typeof K.op==="string")z={op:K.op,body:K}}catch{}if(z)try{Y(z)}catch{}}return}let Z=null;if($.header.channel!==0){if(Z=this.liveRoutes.get($.header.channel)??null,!Z||Z.epoch!==$.header.epoch){this.ingressEpochDropCount+=1;return}}let J=l6(Z,$.header.corr),X=this.pending.get(J);if(X){if(X.acceptFrame&&!X.acceptFrame($))return;switch($.header.ty){case R.Push:case R.StreamData:try{X.onProgress?.($.body)}catch{}return;case R.Response:case R.StreamEnd:this.settle(J,X,()=>X.resolve($));return;case R.Error:this.settle(J,X,()=>X.reject(this.errorFromFrame($)));return;default:return}}let G=this.lateResponses.get(J);if(G&&($.header.ty===R.Response||$.header.ty===R.Error)){this.lateResponses.delete(J),G($);return}if($.header.ty===R.Goodbye&&Z){if(this.failHandle(Z,new m("route closed by subc (GOODBYE)","route_closed")),this.liveRoutes.get(Z.channel)===Z)this.liveRoutes.delete(Z.channel);this.evictRouteHandle(Z);return}if($.header.ty===R.Response||$.header.ty===R.Error||$.header.ty===R.StreamEnd)OY("dropped terminal frame with no waiter: type=%d channel=%d epoch=%d corr=%s port=%s",$.header.ty,$.header.channel,$.header.epoch,$.header.corr,this.sock.localPort()??"?")}settle($,Z,J){if(this.pending.get($)!==Z)return!1;if(this.pending.delete($),Z.timer)clearTimeout(Z.timer);return J(),Z.onSettle?.(),!0}rejectPending($,Z,J){this.settle($,Z,()=>Z.reject(Z.classifyFailure?.(J)??J))}errorFromFrame($){try{let Z=JSON.parse(Buffer.from($.body).toString("utf8"));return new m(Z.message??"subc error",Z.code)}catch{return new m(Buffer.from($.body).toString("utf8")||"subc error")}}evictRouteHandle($){for(let Z of this.routes.values())if(Z.handle&&p6(Z.handle,$))Z.handle=null}failHandle($,Z){for(let[J,X]of this.pending)if(X.handle&&p6(X.handle,$))this.rejectPending(J,X,Z)}fail($){if(!this.closedErr)this.closedErr=$;for(let[Z,J]of this.pending)this.rejectPending(Z,J,$)}notSentCallError($,Z){return new X0("not_sent",`${$}${u6(Z)}`,i6(Z),Z)}outcomeUnknownCallError($,Z){return new X0("outcome_unknown",`${$}${u6(Z)}`,i6(Z),Z)}terminalCallError($,Z){if(Z instanceof X0)return Z;return new X0("terminal",`${$}${u6(Z)}`,i6(Z),Z)}notSentRecoveryError($,Z){if(Z instanceof X0)return Z;if(d6(Z))return this.notSentCallError($,Z);return this.terminalCallError($,Z)}get droppedIngressFrames(){return this.ingressEpochDropCount}installRoute($,Z){let J=m6($,Z,this.connectionToken);return this.liveRoutes.set($,J),J}isLiveHandle($){return b$($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveConnection($){if(!b$($,this.connectionToken))throw new t0($)}assertLiveHandle($){if(!this.isLiveHandle($))throw new t0($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let J=new m("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.fail(J),this.sock.close(),this.scheduleReconnectAfterDrop(J),J}let Z=this.nextCorr;return this.nextCorr+=1n,Z}closeConnectionAfterCleanupFailure(){let $=new m("late route cleanup could not be queued","late_route_cleanup_failed");this.fail($),this.sock.close(),this.scheduleReconnectAfterDrop($)}encode($){return Buffer.from(JSON.stringify($),"utf8")}parseJson($){let Z=$.body;return JSON.parse(Buffer.from(Z.buffer,Z.byteOffset,Z.byteLength).toString("utf8"))}}function d6($){if($ instanceof a0||$ instanceof f0)return!0;if($ instanceof l0||$ instanceof W1)return!0;if($ instanceof X0)return $.kind==="not_sent"||$.kind==="outcome_unknown";if($ instanceof H0)return!0;if($ instanceof m||$ instanceof J0)return!1;let Z=i6($);return Z==="ECONNREFUSED"||Z==="ECONNRESET"||Z==="EPIPE"||Z==="ETIMEDOUT"||Z==="ENOENT"}function FY($){return $==="unknown_module"||$==="module_reloading"||$==="module_warming"||$==="target_unavailable"||$==="module_timeout"}function AY($){return{connectionFile:$.connectionFile,handshakeTimeoutMs:$.handshakeTimeoutMs,identity:$.identity,targetKind:$.targetKind??PY,reconnectBackoff:$.reconnectBackoff??c6,sleep:$.sleep??((Z)=>new Promise((J)=>setTimeout(J,Z))),timeoutArbitrationGraceMs:$.timeoutArbitrationGraceMs??MY,livenessProbeWindowMs:$.livenessProbeWindowMs??_Y,onControlPush:$.onControlPush}}function $9($,Z,J){let X=J?`${J.module_id}\x00${J.launch_nonce}`:"";return`${$.kind}\x00${$.module_id}\x00${Z.project_root}\x00${Z.harness}\x00${Z.session}\x00${X}`}function C4($={}){if($.consumerIdentity!==void 0)return $.consumerIdentity??void 0;let Z=process.env[Z9],J=process.env[J9];if(!Z||!J)return;return{module_id:Z,launch_nonce:J}}function i6($){if(typeof $==="object"&&$!==null&&"code"in $){let Z=$.code;if(typeof Z==="string")return Z}return}function u6($){if($===void 0)return"";return`: ${$ instanceof Error?$.message:String($)}`}function l6($,Z){return $?`${$.channel}:${$.epoch}:${Z}`:`0:0:${Z}`}import{Buffer as A4}from"node:buffer";var wY=1e4,TY=30000,G9=30000,SY=250,R4=64,F4="health.check",Y9=1n;class n6{available;waiters=[];constructor($){if(!Number.isInteger($)||$<=0)throw new p("provider handler capacity must be a positive integer","invalid_handler_capacity");this.available=$}async acquire(){if(this.available>0)return this.available-=1,this.releaseOnce();return await new Promise(($)=>{this.waiters.push($)}),this.releaseOnce()}releaseOnce(){let $=!1;return()=>{if($)return;$=!0;let Z=this.waiters.shift();if(Z)Z();else this.available+=1}}}class p extends Error{code;kind;constructor($,Z,J="terminal"){super($);this.code=Z,this.kind=J}}class E${sock;currentConn;opts;closed;resolveClosed=()=>{return};closeStarted=!1;closedErr=null;inflight=new Map;pending=new Map;liveRoutes=new Map;connectionToken=r1();nextCorr=1n;ingressEpochDropCount=0;requestGate=new n6(R4);reconnecting=null;generation=1;connectionEpoch=1;stateQueue=[];drainingStateQueue=!1;restoredDebounceToken=0;storage;constructor($,Z,J,X){this.sock=$,this.currentConn=Z,this.opts=J,this.storage=X,this.closed=new Promise((G)=>{this.resolveClosed=G}),this.readLoop($,this.generation),this.enqueueConnectionState({state:"connected",epoch:this.connectionEpoch})}get droppedIngressFrames(){return this.ingressEpochDropCount}get conn(){return this.currentConn}currentEpoch(){return this.connectionEpoch}async request($,Z,J={}){this.assertLiveHandle($);let X=this.allocateCorr(),G=s6($,X),Y=J.timeoutMs??G9,z=j0(R.Request,U0(!1,J.priority??Z0.Interactive,!1,J.admissionClass??Y0.Normal),$.channel,$.epoch,X,Z);return await new Promise((K,W)=>{let Q=setTimeout(()=>{if(this.pending.delete(G))W(new p("reverse request timed out","request_timeout"))},Y);this.pending.set(G,{resolve:(V)=>K(V.body),reject:W,timer:Q}),this.sendOn(this.sock,this.generation,z).catch((V)=>{let j=this.pending.get(G);if(!j)return;this.pending.delete(G),clearTimeout(j.timer),W(V instanceof Error?V:new p(String(V)))})})}async push($,Z,J={}){this.assertLiveHandle($),await this.sendOn(this.sock,this.generation,j0(R.Push,U0(!1,J.priority??Z0.Interactive,!1,J.admissionClass??Y0.Normal),$.channel,$.epoch,0n,Z))}cancel($,Z){this.assertLiveHandle($),this.sendOn(this.sock,this.generation,j0(R.Cancel,i0(),$.channel,$.epoch,Z,new Uint8Array(0))).catch(()=>{return})}closeRoute($){this.assertLiveHandle($),this.liveRoutes.delete($.channel),this.abortHandle($),this.sendOn(this.sock,this.generation,j0(R.Goodbye,i0(),$.channel,$.epoch,0n,new Uint8Array(0))).catch(()=>{return})}static async connect($){if($.manifest.protocol_ver!==N0)throw new p(`manifest protocol_ver ${$.manifest.protocol_ver} does not match client protocol ${N0}`,"invalid_manifest");let Z=kY($),J=await E$.openConnection(Z);return new E$(J.sock,J.conn,Z,J.ack.storage)}async close(){if(!this.closeStarted){this.closeStarted=!0,this.cancelRestoredDebounce();let $=this.sock;try{await P4($,j0(R.Goodbye,i0(),0,0,0n,new Uint8Array(0)))}catch{}finally{$.close(),this.finishClosed()}}await this.closed}static async openConnection($,Z){let J=await o1($.connectionFile),X=Date.now()+($.handshakeTimeoutMs??wY),G=J.endpoints[0],Y=await F1.connect(G.host,G.port,X);try{Z?.(Y),await f$(Y,J,X),await P4(Y,vY($));let z=await mY(Y,X);return{sock:Y,conn:J,ack:z}}catch(z){throw Y.close(),z}}async readLoop($,Z){try{for(;;){let J=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:TY});if(!await this.dispatch(J,$,Z)){if(this.sock===$&&this.generation===Z)this.closeStarted=!0;break}}}catch(J){if(this.sock===$&&this.generation===Z&&!this.closeStarted){this.handleUnexpectedDrop($,Z,J instanceof Error?J:new p(String(J)));return}}finally{if(this.sock===$&&this.generation===Z){if($.close(),this.closeStarted)this.finishClosed()}}}async dispatch($,Z,J){let X=null;if($.header.channel!==0){if(X=this.liveRoutes.get($.header.channel)??null,!X||X.epoch!==$.header.epoch)return this.ingressEpochDropCount+=1,!0}if(X){let G=s6(X,$.header.corr),Y=this.pending.get(G);if(Y){if($.header.ty===R.Push||$.header.ty===R.StreamData)return!0;if($.header.ty===R.Response||$.header.ty===R.StreamEnd)return this.pending.delete(G),clearTimeout(Y.timer),Y.resolve($),!0;if($.header.ty===R.Error)return this.pending.delete(G),clearTimeout(Y.timer),Y.reject(IY($)),!0}}switch($.header.ty){case R.Ping:if($.header.channel===0)await this.sendOn(Z,J,p0($.header.ver,R.Pong,$.header.flags,0,0,$.header.corr,new Uint8Array(0)));return!0;case R.Goodbye:if(!X)return!1;return this.liveRoutes.delete(X.channel),this.abortHandle(X),await this.opts.onRouteGone?.(X),!0;case R.Cancel:if(X)this.inflight.get(s6(X,$.header.corr))?.abort();return!0;case R.Request:if($.header.channel===0)await this.handleControlRequest($,Z,J);else if(X)this.handleDataRequest($,X,Z,J).catch((G)=>{if(!this.closeStarted&&this.sock===Z&&this.generation===J)console.warn("SubcProvider handler failed after its request was dispatched",G)});return!0;default:return!0}}abortHandle($){let Z=`${$.channel}:${$.epoch}:`;for(let[J,X]of this.inflight)if(J.startsWith(Z))X.abort();for(let[J,X]of this.pending){if(!J.startsWith(Z))continue;this.pending.delete(J),clearTimeout(X.timer),X.reject(new t0($))}}abortGeneration($){this.abortAllInflight();for(let[Z,J]of this.pending)this.pending.delete(Z),clearTimeout(J.timer),J.reject(new p("provider connection dropped","connection_dropped"));this.liveRoutes.clear()}abortAllInflight(){for(let $ of this.inflight.values())$.abort()}async handleControlRequest($,Z,J){let X=t6($.body);if(X.op===F4){this.handleHealthRequest($,Z,J).catch((j)=>{if(!this.closeStarted&&this.sock===Z&&this.generation===J)console.warn("SubcProvider health handler failed after its request was dispatched",j)});return}if(X.op!=="route.bind")throw new p(`unsupported module control request ${X.op??"<missing op>"}`);let G=X9(X.route_channel,"route_channel"),Y=X9(X.epoch,"epoch"),z=this.liveRoutes.get(G);if(z){if(Y<=z.epoch){await this.sendError($,"route_rejected",`route.bind epoch ${Y} does not supersede installed epoch ${z.epoch} on channel ${G}`,i0(),Z,J);return}this.liveRoutes.delete(z.channel),this.abortHandle(z),await this.opts.onRouteGone?.(z)}let K=m6(G,Y,this.connectionToken),W={handle:K,target:X.target,identity:X.identity,principal:X.principal,consumer_capabilities:X.consumer_capabilities},Q;try{Q=await this.opts.onBind?.(W)}catch(j){try{await this.sendError($,"route_rejected",j instanceof Error?j.message:String(j),i0(),Z,J)}finally{await this.opts.onRouteGone?.(K)}return}let V=pY(Q);if(V){try{await this.sendError($,V.code,V.message,i0(),Z,J)}finally{await this.opts.onRouteGone?.(K)}return}try{await this.sendOn(Z,J,p0($.header.ver,R.Response,i0(),0,0,$.header.corr,a6({op:"route.bind"})))}catch(j){throw await this.opts.onRouteGone?.(K),j}if(this.sock!==Z||this.generation!==J||this.closeStarted||this.closedErr){await this.opts.onRouteGone?.(K);return}this.liveRoutes.set(K.channel,K),await this.opts.onBound?.(K)}async handleDataRequest($,Z,J,X){let{corr:G,ver:Y}=$.header,z=s6(Z,G),K=new AbortController;this.inflight.set(z,K);let W={handle:Z,signal:K.signal,currentEpoch:()=>this.connectionEpoch,emit:async(j,B={})=>{if(this.assertLiveHandle(Z),K.signal.aborted)return;await this.sendOn(J,X,p0(Y,R.StreamData,U0(!1,B.priority??Z0.Interactive,!1,B.admissionClass??Y0.Normal),Z.channel,Z.epoch,G,j))}},Q=await(this.requestGate??new n6(R4)).acquire(),V=U0(!1,Z0.Interactive,!1);try{if(K.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,J,X);return}let j=await this.opts.handler(Z,$.body,W);if(K.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,J,X);return}if(this.assertLiveHandle(Z),j===void 0)await this.sendOn(J,X,p0(Y,R.StreamEnd,V,Z.channel,Z.epoch,G,new Uint8Array(0)));else if(j instanceof Uint8Array)await this.sendOn(J,X,p0(Y,R.Response,V,Z.channel,Z.epoch,G,j));else throw new p("provider handler must return a Uint8Array or void","invalid_handler_response")}catch(j){if(j instanceof t0)return;if(K.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,J,X);return}await this.sendError($,j instanceof p&&j.code?j.code:"handler_error",j instanceof Error?j.message:String(j),V,J,X)}finally{if(Q(),this.inflight.get(z)===K)this.inflight.delete(z)}}async handleHealthRequest($,Z,J){let{corr:X,ver:G}=$.header,Y=`control:${J}:${X}`,z=new AbortController;this.inflight.set(Y,z);let K=await(this.requestGate??new n6(R4)).acquire();try{if(z.signal.aborted)return;let W=await this.opts.health();await this.sendOn(Z,J,p0(G,R.Response,i0(),0,0,X,a6({op:F4,status:W.status,...W.detail===void 0?{}:{detail:W.detail},...W.metrics===void 0?{}:{metrics:W.metrics}})))}catch(W){await this.sendError($,W instanceof p&&W.code?W.code:"health_error",W instanceof Error?W.message:String(W),i0(),Z,J)}finally{if(K(),this.inflight.get(Y)===z)this.inflight.delete(Y)}}async sendError($,Z,J,X,G,Y){if($.header.channel!==0){let z=this.liveRoutes.get($.header.channel);if(!z||z.epoch!==$.header.epoch||!this.isLiveHandle(z))return}await this.sendOn(G,Y,p0($.header.ver,R.Error,X,$.header.channel,$.header.epoch,$.header.corr,a6({code:Z,message:J})))}async sendOn($,Z,J){if(this.sock!==$||this.generation!==Z||this.closeStarted||this.closedErr)return;await P4($,J)}handleUnexpectedDrop($,Z,J){if(this.closeStarted||this.sock!==$||this.generation!==Z)return;this.cancelRestoredDebounce(),this.abortGeneration(Z),this.generation+=1,$.close(),this.scheduleReconnectAfterDrop(J,this.generation,$)}scheduleReconnectAfterDrop($,Z,J){if(this.closeStarted)return;let X=this.reconnecting;if(X){if(!this.shouldSupersedeReconnect(X,Z,J))return;X.superseded=!0,X.socket?.close()}let G={generation:Z,socket:null,socketDied:!1,superseded:!1};this.reconnecting=G,this.enqueueConnectionState({state:"down",cause:$}),this.reconnectWithRetry(G).catch((Y)=>{if(this.isCurrentReconnect(G)&&!this.closeStarted)this.failFatal(Y instanceof Error?Y:new p(String(Y)))}).finally(()=>{if(this.isCurrentReconnect(G))this.reconnecting=null})}async reconnectWithRetry($){let Z=0,J=this.opts.reconnectBackoff.baseMs;for(;;){if(!this.isCurrentReconnect($))return;if(this.closeStarted)throw new p("provider closed");$.socket=null,$.socketDied=!1,Z+=1,this.enqueueReconnectState($,Z);try{let X=await E$.openConnection(this.opts,(Y)=>{if(!this.isCurrentReconnect($)){Y.close();return}$.socket=Y});if(!this.isCurrentReconnect($)||this.closeStarted){if(X.sock.close(),this.closeStarted)throw new p("provider closed");return}let G=this.replaceConnection(X,$.generation);if(this.reconnecting=null,this.reconnecting!==null)throw new p("reconnect state must clear before restored","reconnect_state");this.scheduleRestored($.generation,G);return}catch(X){if(!this.isCurrentReconnect($))return;if($.socket)$.socketDied=!0;if(this.closeStarted)throw X;if(!hY(X))throw X;await this.opts.sleep(J),J=Math.min(J*2,this.opts.reconnectBackoff.capMs)}}}isCurrentReconnect($){return!$.superseded&&this.reconnecting===$&&this.generation===$.generation}shouldSupersedeReconnect($,Z,J){return $.generation<Z||$.socketDied||$.socket===J}enqueueReconnectState($,Z){if(!this.isCurrentReconnect($))return;this.enqueueConnectionState({state:"reconnecting",attempt:Z},$.generation,$)}replaceConnection($,Z){return this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.storage=$.ack.storage,this.closedErr=null,this.connectionEpoch+=1,this.connectionToken=r1(),this.liveRoutes.clear(),this.nextCorr=1n,this.readLoop($.sock,Z),this.connectionEpoch}scheduleRestored($,Z){if(!this.opts.onConnectionState)return;let J=++this.restoredDebounceToken;this.opts.sleep(this.opts.restoredDebounceMs).then(()=>{if(J===this.restoredDebounceToken&&!this.closeStarted&&this.sock&&this.generation===$&&this.connectionEpoch===Z)this.enqueueConnectionState({state:"restored",epoch:Z},$)}).catch((X)=>{if(J===this.restoredDebounceToken&&!this.closeStarted)console.warn("SubcProvider restored debounce timer failed",X)})}cancelRestoredDebounce(){this.restoredDebounceToken+=1}enqueueConnectionState($,Z,J){if(!this.opts.onConnectionState)return;if(this.stateQueue.push({event:$,generation:Z,reconnect:J}),!this.drainingStateQueue)this.drainConnectionStateQueue()}async drainConnectionStateQueue(){if(this.drainingStateQueue)return;this.drainingStateQueue=!0;try{while(this.stateQueue.length>0){let $=this.stateQueue[0];if(this.closeStarted||$.generation!==void 0&&$.generation!==this.generation||$.reconnect?.superseded){this.stateQueue.shift();continue}let{event:Z}=$;try{await this.opts.onConnectionState?.(Z),this.stateQueue.shift()}catch(J){if(Z.state==="restored"){console.warn("SubcProvider restored callback failed; retrying delivery",J),await gY();continue}console.warn("SubcProvider connection-state callback failed",J),this.stateQueue.shift()}}}finally{if(this.drainingStateQueue=!1,this.stateQueue.length>0)this.drainConnectionStateQueue()}}isLiveHandle($){return b$($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveHandle($){if(!this.isLiveHandle($))throw new t0($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let J=new p("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.handleUnexpectedDrop(this.sock,this.generation,J),J}let Z=this.nextCorr;return this.nextCorr+=1n,Z}failFatal($){if(!this.closedErr)this.closedErr=$;this.closeStarted=!0,this.cancelRestoredDebounce(),this.abortAllInflight(),this.sock.close(),this.finishClosed()}finishClosed(){this.resolveClosed()}}function s6($,Z){return`${$.channel}:${$.epoch}:${Z}`}function IY($){try{let Z=t6($.body);return new p(Z.message??"subc error",Z.code,Z.code==="stale_route_epoch"||Z.code==="unknown_channel"?"not_sent":"terminal")}catch{return new p(A4.from($.body).toString("utf8")||"subc error")}}function fY($){let Z=$.launchNonce??process.env[bY];return Z&&Z.length>0?Z:void 0}var bY="SUBC_LAUNCH_NONCE";function kY($){return{connectionFile:$.connectionFile,manifest:$.manifest,handler:$.handler,health:$.health??(()=>({status:"ok"})),handshakeTimeoutMs:$.handshakeTimeoutMs,controlOps:$.controlOps,onBind:$.onBind,onBound:$.onBound,onRouteGone:$.onRouteGone,reconnectBackoff:$.reconnectBackoff??c6,sleep:$.sleep??((Z)=>new Promise((J)=>setTimeout(J,Z))),restoredDebounceMs:$.restoredDebounceMs??SY,onConnectionState:$.onConnectionState,launchNonce:$.launchNonce}}function EY($){if($===null)return null;let Z=new Set($??[]);return Z.add(F4),[...Z]}function vY($){let Z=fY($);return j0(R.Hello,i0(),0,0,Y9,a6({manifest:uY($.manifest),protocol_ver:N0,control_ops:EY($.controlOps),...Z?{launch_nonce:Z}:{}}))}function hY($){if($ instanceof p)return $.code==="duplicate_module_id";if($ instanceof a0||$ instanceof f0)return!0;if($ instanceof l0||$ instanceof W1)return!0;if($ instanceof H0)return!0;if($ instanceof J0)return!1;let Z=yY($);return Z==="ECONNREFUSED"||Z==="ECONNRESET"||Z==="EPIPE"||Z==="ETIMEDOUT"||Z==="ENOENT"}function yY($){if(typeof $==="object"&&$!==null&&"code"in $){let Z=$.code;if(typeof Z==="string")return Z}return}async function gY(){await new Promise(($)=>setTimeout($,0))}function i0(){return U0(!1,Z0.Passive,!1)}async function P4($,Z){await d0($,u0(Z),Date.now()+G9)}async function mY($,Z){let J=await $.readFrame(Z,Z);switch(J.header.ty){case R.HelloAck:{let X=t6(J.body);if(X.negotiated_ver!==N0)throw new p(`subc negotiated protocol ${X.negotiated_ver}; expected exactly ${N0}`,"unsupported_version");return X}case R.Error:{let X=t6(J.body);throw new p(`subc rejected HELLO: ${X.code??"unknown"} — ${X.message??"subc error"}`,X.code)}default:throw new p(`unexpected frame ${R[J.header.ty]} awaiting HELLO_ACK`)}}function a6($){return new Uint8Array(A4.from(JSON.stringify($),"utf8"))}function t6($){return JSON.parse(A4.from($).toString("utf8"))}function X9($,Z){if(typeof $!=="number"||!Number.isInteger($))throw new p(`route.bind ${Z} must be an integer`);return $}function pY($){if($===void 0||$===!0)return null;if($===!1)return{code:"route_rejected",message:"route.bind rejected by provider"};if($.accept)return null;return{code:$.code??"route_rejected",message:$.message??"route.bind rejected by provider"}}function uY($){return{module_id:$.module_id,module_version:$.module_version,protocol_ver:$.protocol_ver,trust_tier:$.trust_tier,provides:$.provides.map(lY),consumes:$.consumes.map(dY),bindings:{storage:{kind:$.bindings.storage.kind,scope:$.bindings.storage.scope,owns_schema:$.bindings.storage.owns_schema},vault_grants:$.bindings.vault_grants.map((Z)=>({secret:Z.secret,reason:Z.reason})),identity:{requires:[...$.bindings.identity.requires],optional:[...$.bindings.identity.optional]}}}}function lY($){switch($.role){case"tool_provider":return{role:"tool_provider",tools:$.tools.map((Z)=>({name:Z.name,...Z.description===void 0?{}:{description:Z.description},execution_mode:Z.execution_mode,schema:Z.schema})),identity_scope:[...$.identity_scope],concurrency:$.concurrency,emits_push:$.emits_push,sub_supervises:$.sub_supervises};case"pipeline_stage":return{role:"pipeline_stage",stage:$.stage,applies_to:{provider:$.applies_to.provider,model:$.applies_to.model},interface:$.interface,declares_frozen_floor:$.declares_frozen_floor,needs_signals:[...$.needs_signals],conformance_class:$.conformance_class};case"management_surface":return{role:"management_surface",operations:$.operations.map((Z)=>({name:Z.name,kind:Z.kind})),config_schema:$.config_schema,observability:$.observability.map((Z)=>({name:Z.name,kind:Z.kind})),identity_scope:[...$.identity_scope],concurrency:$.concurrency};case"internal_service":return{role:"internal_service",service_id:$.service_id,transport:$.transport,agent_facing:$.agent_facing,operations:[...$.operations]}}}function dY($){switch($.role){case"tool_client":return{role:"tool_client",of:[...$.of]};case"llm_client":return{role:"llm_client",via:$.via,auth:$.auth};case"service_client":return{role:"service_client",of:[...$.of]}}}var o6="subc-connection.json",aY="subc-",tY=".connection.json";function z9(){let $=process.env.HOME;return $?v$($,".local","share","cortexkit","run",o6):void 0}function oY(){let $=process.env.XDG_RUNTIME_DIR?.trim();if($)return v$($,o6);let Z=z9();if(Z)return Z;return v$(nY().homedir,".local","share","cortexkit","run",o6)}function rY(){let $=process.env.XDG_RUNTIME_DIR?.trim();if($){let X=v$($,o6);if(w4(X))return X}let Z=z9();if(Z&&w4(Z))return Z;let J=eY(sY());return J.length===1?J[0]:void 0}function K9(){return rY()??oY()}function T4($){return $?.trim()||process.env.CLAUSTRUM_SUBC_CONNECTION?.trim()||K9()}function w4($){try{return cY($).isFile()}catch{return!1}}function eY($){let Z;try{Z=iY($)}catch{return[]}let J=[];for(let X of Z){if(typeof X!=="string")continue;if(!X.startsWith(aY)||!X.endsWith(tY))continue;let G=v$($,X);if(w4(G))J.push(G)}return J.sort(),J}import{createHash as $z}from"node:crypto";import{existsSync as Zz,realpathSync as W9}from"node:fs";import{dirname as Jz,relative as Xz,resolve as Gz}from"node:path";function V9($){let Z=$,J;try{J=W9(Z)}catch(X){if(X.code!=="ENOENT")throw X;let G=Z;while(!Zz(G)){let Y=Jz(G);if(Y===G)break;G=Y}J=Gz(W9(G),Xz(G,Z))}return $z("sha256").update(J).digest("hex")}function S4($,Z){return{project_root:$,harness:"opencode",session:`store-${V9(Z)}`}}import{randomBytes as Yz}from"node:crypto";import{chmod as zz,mkdir as Kz,open as Wz,realpath as Vz,rename as Qz,stat as jz,unlink as Hz}from"node:fs/promises";import{basename as Bz,dirname as Q9,join as qz}from"node:path";var Uz=/^[0-9a-f]{64}$/;function Lz($){if(!Uz.test($.token))throw Error("enrollment token must be exactly 64 lowercase hex characters");if(!Number.isSafeInteger($.token_generation)||$.token_generation<1)throw Error("enrollment token generation must be a positive safe integer")}async function Nz($){let Z;try{Z=await Vz($)}catch{return}for(;;){let J=await jz(Z).catch(()=>{return});if(J&&(J.mode&18)!==0&&(J.mode&512)===0)throw Error(`enrollment token ancestor ${Z} is group- or world-writable without sticky bit`);let X=Q9(Z);if(X===Z)return;Z=X}}async function I4($,Z){Lz(Z);let J=Q9($);await Kz(J,{recursive:!0,mode:448}),await Nz(J);let X=qz(J,`.${Bz($)}.${process.pid}.${Yz(12).toString("hex")}.tmp`),G=!1;try{let Y=await Wz(X,"wx",384);G=!0;try{await Y.writeFile(`${JSON.stringify(Z)}
28
- `,"utf8"),await Y.sync(),await zz(X,384)}finally{await Y.close()}await Qz(X,$),G=!1}finally{if(G)await Hz(X).catch(()=>{return})}}var j9=["transient","permanent","auth_required","context_overflow"];class C0 extends Error{code;action;["class"];constructor($,Z,J){super(`Claustrum credential request failed: ${$}`);this.code=$,this.action=J,this.name="ClaustrumCredentialError",this.class=Z}}function e1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function H9($){switch($){case"permanent":return"gone";case"auth_required":return"reauth";case"context_overflow":return"reduce_and_retry";case"transient":return"retry"}}function b($,Z="invalid_response",J=(X)=>console.warn(X)){let X=e1($)&&e1($.result)?$.result:void 0,G=X&&e1(X.error)?X.error:void 0,Y=G?.class,z=G?.code,K=typeof Y==="string"&&j9.includes(Y),W=typeof z==="string",V=K&&W?Y:"transient";if(typeof Y!=="string")J("unknown");else if(!K)J(Y);return new C0(W?z:Z,V,H9(V))}function w1($){return e1($)&&e1($.result)&&e1($.result.error)}var B9="claustrum",Dz=60000;function x0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function b4($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0?$:void 0}function o0($){return $===void 0||typeof $==="string"}function q9($,Z){if(w1($))throw b($,"invalid_response",Z);let J=x0($)&&x0($.result)?$.result:void 0,X=J?.payload;if(!Array.isArray(X)||X.length===0||!X.every((B)=>typeof B==="number"&&Number.isInteger(B)&&B>=0&&B<=255))throw b($,"invalid_response",Z);let G=b4(J?.record_version);if(G===void 0)throw b($,"invalid_record_version",Z);let Y=J?.expires_at_ms,z=Y===void 0||Y===null?null:typeof Y==="number"&&Number.isFinite(Y)?Y:void 0;if(z===void 0)throw b($,"invalid_expiry",Z);let K=J?.credential_id,W=J?.project_id,Q=J?.account_id,V=J?.email,j=J?.org_name;if(!o0(K)||!o0(W)||!o0(Q)||!o0(V)||!o0(j))throw b($,"invalid_response",Z);return{material:new TextDecoder().decode(Uint8Array.from(X)),recordVersion:G,expiresAtMs:z,credentialId:K,projectId:W,accountId:Q,email:V,orgName:j}}function Mz($,Z){if(w1($))throw b($,"invalid_response",Z);let J=x0($)&&x0($.result)?$.result:void 0,X=b4(J?.record_version);if(typeof J?.ready!=="boolean"||J?.last_error_code!==void 0&&J?.last_error_code!==null&&typeof J?.last_error_code!=="string"||typeof J?.lease_held!=="boolean"||X===void 0||J?.stale_pending!==void 0&&typeof J.stale_pending!=="boolean")throw b($,"invalid_status",Z);return{ready:J.ready,lastErrorCode:J.last_error_code??null,leaseHeld:J.lease_held,recordVersion:X,...J.stale_pending===void 0?{}:{stalePending:J.stale_pending}}}class T1{#$;#Z;#G;#Y;#z;#J;#X=null;#V=0;#K=!1;constructor($,Z,J,X,G,Y){this.#$=$,this.#Z=Z,this.#G=J,this.#Y=X,this.#z=G,this.#J=Y}static async connect($={}){let Z=T4($.connectionFile),J=$.connector??((Y)=>A1.connect(Y)),X=$.identity??S4($.projectRoot??process.cwd(),$.storagePath??process.cwd()),G=await J({connectionFile:Z,handshakeTimeoutMs:$.handshakeTimeoutMs});return new T1(G,J,Z,$.handshakeTimeoutMs,X,$.logger??((Y)=>console.warn(Y)))}async getCredential($,Z){let J=await this.#W("credential.get",{handle:$,min_ttl_ms:Z,force_refresh:!1});return q9(J,this.#J)}async statusCredential($){let Z=await this.#W("credential.status",{handle:$});return Mz(Z,this.#J)}async reportAuthFailure($){let Z=await this.#W("credential.report_auth_failure",{handle:$.handle,provider_status:$.providerStatus,record_version:$.recordVersion,reporter_source:$.reporterSource});if(w1(Z))throw b(Z,"invalid_response",this.#J);if((x0(Z)&&x0(Z.result)?Z.result:void 0)?.accepted!==!0)throw b(Z,"invalid_response",this.#J)}async listScoped($){let Z=await this.#W("credential.list_scoped",$===void 0?{}:{enrollment_token:$});return _z(Z,this.#J)}async getScoped($){let Z=await this.#W("credential.get_scoped",{credential_id:$.credentialId,enrollment_token:$.enrollmentToken,min_ttl_ms:$.minTtlMs});return q9(Z,this.#J)}async reportAuthFailureScoped($){let Z=await this.#W("credential.report_auth_failure",{credential_id:$.credentialId,enrollment_token:$.enrollmentToken,provider_status:$.providerStatus,record_version:$.recordVersion,reporter_source:$.reporterSource});if(w1(Z))throw b(Z,"invalid_response",this.#J);if((x0(Z)&&x0(Z.result)?Z.result:void 0)?.accepted!==!0)throw b(Z,"invalid_response",this.#J)}async enrollPropose($){let Z=await this.#W("auth.enroll_propose",{proposed_name:$.name,request_secret_hash:$.requestSecretHash}),X=f4(Z,this.#J).request_id;if(typeof X!=="string"||X.length===0)throw b(Z,"invalid_response",this.#J);return{requestId:X}}async enrollPoll($){let Z=await this.#W("auth.enroll_poll",{request_id:$.requestId,request_secret:$.requestSecret});return Cz(Z,this.#J)}async enrollRotate($){let Z=await this.#W("auth.enroll_rotate",{token:$.token,expected_token_generation:$.expectedTokenGeneration}),J=f4(Z,this.#J),X=J.token,G=J.token_generation;if(typeof X!=="string"||X.length===0||typeof G!=="number")throw b(Z,"invalid_response",this.#J);return{token:X,tokenGeneration:G}}close(){this.#K=!0,this.#$.close()}async#W($,Z){try{return await this.#$.call(B9,$,Z,{identity:this.#z,consumerIdentity:null})}catch(J){if(this.#j(J)){try{await this.#H()}catch(X){throw this.#Q(X)}try{return await this.#$.call(B9,$,Z,{identity:this.#z,consumerIdentity:null})}catch(X){throw this.#Q(X)}}throw this.#Q(J)}}#Q($){if($ instanceof C0)return $;let Z=$ instanceof X0&&$.code?$.code:"transport_error";return new C0(Z,"transient","retry")}#j($){return!this.#K&&$ instanceof X0&&$.kind==="terminal"&&$.code!=="missing_identity"&&$.code!=="invalid_control_body"}async#H(){if(this.#K)throw Error("Claustrum client is closed");if(this.#X){await this.#X;return}let $=Date.now();if($<this.#V)throw Error("Claustrum client reconnect is backed off");this.#V=$+Dz,this.#X=this.#Z({connectionFile:this.#G,handshakeTimeoutMs:this.#Y}).then((Z)=>{if(this.#K)throw Z.close(),Error("Claustrum client is closed");let J=this.#$;this.#$=Z,J.close()}).finally(()=>{this.#X=null}),await this.#X}}function _z($,Z){if(w1($))throw b($,"invalid_response",Z);let J=x0($)&&x0($.result)?$.result:void 0,X=J?.credentials;if(!Array.isArray(X))throw b($,"invalid_response",Z);let G=J?.view;if(typeof G!=="string"||G.length===0)throw b($,"invalid_response",Z);return{rows:X.map((z)=>{if(!x0(z))throw b($,"invalid_response",Z);let K=b4(z.record_version);if(K===void 0)throw b($,"invalid_record_version",Z);let W=(V)=>{if(!Array.isArray(V)||!V.every((j)=>typeof j==="string"))throw b($,"invalid_response",Z);return V};if(typeof z.id!=="string"||typeof z.type!=="string"||typeof z.state!=="string")throw b($,"invalid_response",Z);let Q=z.created_at_ms===void 0||z.created_at_ms===null?null:typeof z.created_at_ms==="number"&&Number.isFinite(z.created_at_ms)?z.created_at_ms:void 0;if(Q===void 0)throw b($,"invalid_response",Z);if(!o0(z.refresh_adapter))throw b($,"invalid_response",Z);if(!o0(z.account_id)||!o0(z.email)||!o0(z.org_name))throw b($,"invalid_response",Z);return{id:z.id,categories:W(z.categories),credentialType:z.type,serves:W(z.serves),state:z.state,refreshAdapter:z.refresh_adapter,recordVersion:K,operations:W(z.operations),createdAtMs:Q,accountId:z.account_id,email:z.email,orgName:z.org_name}}),view:G}}function f4($,Z){if(w1($))throw b($,"invalid_response",Z);let J=x0($)&&x0($.result)?$.result:void 0;if(J===void 0)throw b($,"invalid_response",Z);return J}function Cz($,Z){let J=f4($,Z),X=J.status;if(X==="pending")return{status:"pending"};if(X==="denied")return{status:"denied"};if(X!=="approved")throw b($,"invalid_response",Z);let{name:G,token:Y,token_generation:z}=J;if(typeof G!=="string"||typeof Y!=="string"||Y.length===0||typeof z!=="number"||!Number.isInteger(z))throw b($,"invalid_response",Z);return{status:"approved",name:G,token:Y,tokenGeneration:z}}var Iz="anthropic-auth-opencode",iB="anthropic-auth-pi",fz=1,k4=16384,M9=30000,v4=/^[0-9a-f]{64}$/;function cB($={}){return T1.connect($)}function _9($){let Z=L9($)||".json",J=O9($,L9($));return{statePath:D9(h$($),`${J}-state${Z}`),tokenPath:$}}function C9($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function r6($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function R9($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function h4($){if(!C9($)||$.version!==fz||typeof $.proposedName!=="string"||$.proposedName.length===0)throw Error("invalid Claustrum enrollment state");if($.phase==="pending"){if(!v4.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!r6($.createdAt)||!r6($.updatedAt))throw Error("invalid Claustrum enrollment state");return{version:1,phase:"pending",proposedName:$.proposedName,requestSecret:$.requestSecret,...$.requestId!==void 0&&{requestId:$.requestId},createdAt:$.createdAt,updatedAt:$.updatedAt}}if($.phase==="approved"){if($.approvedName!==void 0&&(typeof $.approvedName!=="string"||$.approvedName.length===0)||!R9($.tokenGeneration)||!r6($.updatedAt))throw Error("invalid Claustrum enrollment state");return{version:1,phase:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration,updatedAt:$.updatedAt}}if($.phase==="denied"||$.phase==="blocked"){if($.errorCode!==void 0&&typeof $.errorCode!=="string"||!r6($.updatedAt))throw Error("invalid Claustrum enrollment state");return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw Error("invalid Claustrum enrollment state")}function y4($){if(!C9($)||!v4.test(String($.token??""))||!R9($.token_generation))throw Error("invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function bz($){if(!$.isFile())throw Error("Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw Error("Claustrum enrollment file must be owner-only");let Z=process.getuid?.();if(Z!==void 0&&$.uid!==Z)throw Error("Claustrum enrollment file must be owned by the current user")}async function S1($){let Z;try{Z=await N9($,U9.O_RDONLY|U9.O_NOFOLLOW)}catch(J){if(J.code==="ENOENT")return;throw Error("Claustrum enrollment file could not be opened safely")}try{bz(await Z.stat());let J=Buffer.alloc(k4+1),{bytesRead:X}=await Z.read(J,0,J.byteLength,0);if(X>k4)throw Error("Claustrum enrollment file is too large");return q0(J.subarray(0,X).toString("utf8"))}finally{await Z.close()}}async function P9($){let Z;try{Z=await wz($)}catch{return}for(;;){let J=await Sz(Z).catch(()=>{return});if(J&&(J.mode&18)!==0&&(J.mode&512)===0)throw Error("Claustrum enrollment path has an unsafe writable ancestor");let X=h$(Z);if(X===Z)return;Z=X}}async function V1($,Z){let J=h$($);await E4(J,{recursive:!0,mode:448}),await P9(J);let X=`${JSON.stringify(Z)}
29
- `;if(Buffer.byteLength(X)>k4)throw Error("Claustrum enrollment state is too large");let G=D9(J,`.${O9($)}.${process.pid}.${Fz()}.tmp`),Y;try{Y=await N9(G,"wx",384),await Y.writeFile(X,"utf8"),await Y.sync(),await Y.close(),Y=void 0,await Az(G,384),await Tz(G,$)}finally{await Y?.close().catch(()=>{}),await x9(G).catch(()=>{})}}async function kz($,Z=Iz){let J=await S1($.tokenPath),X=J===void 0?void 0:y4(J),G=await S1($.statePath),Y=G===void 0?void 0:h4(G);if(X)return{state:"approved",proposedName:Y?.proposedName??Z,...Y?.phase==="approved"&&Y.approvedName!==void 0&&{approvedName:Y.approvedName},tokenGeneration:X.token_generation};if(!Y)return{state:"idle"};if(Y.phase==="pending")return{state:"pending",proposedName:Y.proposedName,...Y.requestId!==void 0&&{requestId:Y.requestId}};if(Y.phase==="approved")return{state:"blocked",proposedName:Y.proposedName,code:"missing_token"};if(Y.phase==="denied")return{state:"denied",proposedName:Y.proposedName};return{state:"blocked",proposedName:Y.proposedName,code:Y.errorCode??"unknown"}}async function F9($){await P9($);let Z=await S1($);if(Z===void 0)throw Error("Claustrum enrollment is not configured");return y4(Z)}function Q1($){if($.phase==="pending")return{state:"pending",proposedName:$.proposedName,...$.requestId!==void 0&&{requestId:$.requestId}};if($.phase==="approved")return{state:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration};if($.phase==="denied")return{state:"denied",proposedName:$.proposedName};return{state:"blocked",proposedName:$.proposedName,code:$.errorCode??"unknown"}}class g4{#$;#Z;#G;#Y;#z;#J;constructor($){this.#$=$.client,this.#Z=$.paths,this.#G=$.proposedName,this.#Y=$.now??Date.now,this.#z=$.mintSecret??(()=>Pz(32).toString("hex")),this.#J=$.writeTokenFile??I4}async status(){return kz(this.#Z,this.#G)}async resetTerminal(){return Ez(this.#Z,this.#G)}async reconcile(){await E4(h$(this.#Z.statePath),{recursive:!0,mode:448});let $=await Q0({name:"ceremony",path:this.#Z.statePath,ttlMs:M9,renew:!0});if(!$)return{state:"busy"};try{let Z=await S1(this.#Z.tokenPath),J=Z===void 0?void 0:y4(Z),X=await S1(this.#Z.statePath),G=X===void 0?void 0:h4(X);if(G&&G.proposedName!==this.#G)throw Error("Claustrum enrollment state belongs to a different consumer");if(J){if(!G||G.phase==="pending"){let z={version:1,phase:"approved",proposedName:G?.proposedName??this.#G,tokenGeneration:J.token_generation,updatedAt:this.#Y()};await V1(this.#Z.statePath,z),G=z}return{state:"approved",proposedName:G.proposedName,...G.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:J.token_generation}}if(G?.phase==="approved"){let z={version:1,phase:"blocked",proposedName:G.proposedName,errorCode:"missing_token",updatedAt:this.#Y()};return await V1(this.#Z.statePath,z),Q1(z)}if(G&&G.phase!=="pending")return Q1(G);if(!G){let z=this.#Y();if(G={version:1,phase:"pending",proposedName:this.#G,requestSecret:this.#z(),createdAt:z,updatedAt:z},!v4.test(G.requestSecret))throw Error("invalid minted Claustrum enrollment secret");await V1(this.#Z.statePath,G)}if(!G.requestId)try{let z=Rz("sha256").update(Buffer.from(G.requestSecret,"hex")).digest("hex"),K=await this.#$.enrollPropose({name:G.proposedName,requestSecretHash:z});G={...G,requestId:K.requestId,updatedAt:this.#Y()},await V1(this.#Z.statePath,G)}catch(z){if(z instanceof C0){if(z.code==="pending_queue_full"||z.action==="retry")return{state:"pending",proposedName:G.proposedName,retryCode:z.code};let K={version:1,phase:"blocked",proposedName:G.proposedName,errorCode:z.code,updatedAt:this.#Y()};return await V1(this.#Z.statePath,K),Q1(K)}throw z}let Y=G.requestId;if(!Y)return Q1(G);try{let z=await this.#$.enrollPoll({requestId:Y,requestSecret:G.requestSecret});if(z.status==="pending")return Q1(G);if(z.status==="denied"){let W={version:1,phase:"denied",proposedName:G.proposedName,updatedAt:this.#Y()};return await V1(this.#Z.statePath,W),Q1(W)}await this.#J(this.#Z.tokenPath,{token:z.token,token_generation:z.tokenGeneration});let K={version:1,phase:"approved",proposedName:G.proposedName,approvedName:z.name,tokenGeneration:z.tokenGeneration,updatedAt:this.#Y()};return await V1(this.#Z.statePath,K),Q1(K)}catch(z){if(!(z instanceof C0))throw z;if(z.action==="retry")return{state:"pending",proposedName:G.proposedName,requestId:Y,retryCode:z.code};let K={version:1,phase:"blocked",proposedName:G.proposedName,errorCode:z.code,updatedAt:this.#Y()};return await V1(this.#Z.statePath,K),Q1(K)}}finally{await $.release()}}}async function Ez($,Z){await E4(h$($.statePath),{recursive:!0,mode:448});let J=await Q0({name:"ceremony",path:$.statePath,ttlMs:M9,renew:!0});if(!J)return"busy";try{if(await S1($.tokenPath)!==void 0)return"refused-approved";let X=await S1($.statePath);if(X===void 0)return"idle";let G=h4(X);if(G.proposedName!==Z)throw Error("Claustrum enrollment state belongs to a different consumer");if(G.phase==="pending")return"refused-pending";return await J.assertOwned(),await x9($.statePath),"reset"}finally{await J.release()}}import{homedir as vz}from"node:os";import{isAbsolute as hz,join as A9,resolve as S9}from"node:path";var m4=Symbol.for("cortexkit.anthropic-auth.claustrum-enrollments.v2"),yz=5000,gz=60000,I9=5000;function oB($,Z=process.env,J=process.cwd()){let X=Z[`${$.toUpperCase()}_ANTHROPIC_AUTH_CLAUSTRUM_ENROLLMENT_FILE`]?.trim(),G=X?hz(X)?X:S9(J,X):A9(Z.XDG_STATE_HOME||A9(vz(),".local","state"),"cortexkit","anthropic-auth",`${$}-enrollment.json`);return _9(G)}function mz(){let $=globalThis;if(!$[m4])$[m4]=new Map;return $[m4]}function p4($,Z){$.status=Z;for(let J of $.leases.values())J(Z)}function w9($,Z){if($.closed||$.timer)return;if($.timer=$.setTimeoutImpl(()=>{$.timer=void 0,e6($)},Z),typeof $.timer==="object"&&$.timer&&"unref"in $.timer)$.timer.unref()}function pz($,Z){if(Z===0||$.state==="approved"||$.state==="denied"||$.state==="blocked")return;if($.state==="pending")return $.retryCode?gz:Z;return I9}async function T9($){if($.closed)throw Error("Claustrum enrollment registry is closed");if($.client)return $.client;if(!$.clientPromise)$.clientPromise=$.connect().then((Z)=>{if($.closed)throw Z.close(),Error("Claustrum enrollment registry is closed");return $.client=Z,Z}).finally(()=>{$.clientPromise=void 0});return $.clientPromise}async function e6($){if($.closed)return;if($.run)return $.run;return $.run=(async()=>{let Z;try{Z=await $.manager.reconcile()}catch{if(Z={state:"unavailable",proposedName:$.proposedName,code:"unavailable"},$.closed)return;if(p4($,Z),$.pollIntervalMs!==0)w9($,I9);return}if($.closed)return;p4($,Z);let J=pz(Z,$.pollIntervalMs);if(J!==void 0)w9($,J)})().finally(()=>{$.run=void 0}),$.run}function rB($){let Z=S9($.paths.tokenPath),J=mz(),X=J.get(Z);if(X&&X.proposedName!==$.proposedName)throw Error("Claustrum enrollment path is already owned by a different consumer");if(!X){let z=$.connect,K=$.setTimeoutImpl??setTimeout,W=$.clearTimeoutImpl??clearTimeout,Q={enrollPropose:async(V)=>{let j=X,B=await T9(j);if(j.closed)throw Error("Claustrum enrollment registry is closed");return B.enrollPropose(V)},enrollPoll:async(V)=>{let j=X,B=await T9(j);if(j.closed)throw Error("Claustrum enrollment registry is closed");return B.enrollPoll(V)}};X={key:Z,proposedName:$.proposedName,leases:new Map,manager:new g4({client:Q,paths:$.paths,proposedName:$.proposedName}),connect:z,setTimeoutImpl:K,clearTimeoutImpl:W,pollIntervalMs:$.pollIntervalMs??yz,status:{state:"idle"},closed:!1},J.set(Z,X)}let G=Symbol(Z);X.leases.set(G,$.onStatus??(()=>{})),$.onStatus?.(X.status),e6(X);let Y=!1;return{status:()=>X?.status??{state:"idle"},reconcileNow:()=>X?e6(X):Promise.resolve(),resetTerminal:async()=>{if(!X)return"idle";let z=await X.manager.resetTerminal();if(z==="reset")p4(X,{state:"idle"}),await e6(X);return z},release:()=>{if(Y||!X)return;if(Y=!0,X.leases.delete(G),X.leases.size>0)return;if(X.closed=!0,X.timer)X.clearTimeoutImpl(X.timer),X.timer=void 0;X.client?.close(),J.delete(Z)}}}var f9=300000;function uz($){let Z=$.trim();if(Z.startsWith("{")){let J;try{J=q0(Z)}catch{throw Error("Claustrum returned invalid OAuth material")}if(!J||typeof J!=="object")throw Error("Claustrum returned invalid OAuth material");let X=J,G=X.access_token??X.access;Z=typeof G==="string"?G:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(V6))throw Error("Claustrum returned invalid OAuth material");return Z}class u4{#$;#Z;#G;#Y=new WeakMap;#z=new WeakMap;#J=!1;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>F9(Z);else throw Error("Claustrum enrollment token path is required");this.#$=$.client,this.#G=$.now??Date.now}#X($){if(this.#J)throw Error("Claustrum scoped custody is closed");$?.throwIfAborted()}async#V($){this.#X($);let Z=await this.#Z();if(this.#X($),!/^[0-9a-f]{64}$/.test(Z.token)||!Number.isSafeInteger(Z.token_generation)||Z.token_generation<1)throw Error("Invalid Claustrum enrollment token");return Z.token}async#K($,Z){this.#X(Z);let J,X;try{let G=$();J=Z?await Promise.race([G,new Promise((Y,z)=>{let K=()=>z(Z.reason);if(Z.addEventListener("abort",K,{once:!0}),X=()=>Z.removeEventListener("abort",K),Z.aborted)K()})]):await G}catch(G){if(this.#X(Z),G instanceof C0)throw G;throw Error("Claustrum scoped operation unavailable")}finally{X?.()}return this.#X(Z),J}async discover($){let Z=await this.#V($),J=await this.#K(()=>this.#$.listScoped(Z),$),X=new Set,G=[];for(let Y of J.rows){if(Y.refreshAdapter!=="anthropic"||Y.credentialType!=="oauth"||!Y.operations.includes("read"))continue;if(!Y.id||!Y.accountId?.trim()||X.has(Y.id))throw Error("Claustrum inventory has missing or ambiguous account identity");X.add(Y.id),G.push(Object.freeze({credentialId:Y.id,accountId:Y.accountId,state:Y.state,...Y.email!==void 0&&{email:Y.email},...Y.orgName!==void 0&&{orgName:Y.orgName}}))}return{view:J.view,accounts:Object.freeze(G)}}async authorize($,Z){if(!$.credentialId||!$.accountId)throw Error("Claustrum dispatch requires account identity");let{credentialId:J,accountId:X}=$,G=await this.#V(Z),Y=await this.#K(()=>this.#$.getScoped({credentialId:J,enrollmentToken:G,minTtlMs:f9}),Z);if(Y.credentialId!==J||Y.accountId!==X)throw Error("Claustrum served credential identity changed");if(!Number.isSafeInteger(Y.recordVersion)||Y.recordVersion<0||Y.expiresAtMs===null||!Number.isFinite(Y.expiresAtMs)||Y.expiresAtMs-this.#G()<f9)throw Error("Claustrum served credential has insufficient validity");let z=uz(Y.material),K=Object.freeze(Object.defineProperty({credentialId:J,accountId:X,recordVersion:Y.recordVersion,expiresAtMs:Y.expiresAtMs},"accessToken",{value:z,enumerable:!1}));return this.#Y.set(K,G),K}async reportFailure($,Z,J){if(Z!==401)return;this.#X();let X=this.#Y.get($);if(!X)throw Error("Claustrum failure report requires an original dispatch receipt");let G=this.#z.get($);if(G)return G;let Y=this.#K(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:X,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#z.set($,Y);try{await Y}catch(z){throw this.#z.delete($),z}}close(){if(this.#J)return;this.#J=!0,this.#$.close()}}import{createHash as b9}from"node:crypto";function k9($){let Z=$.split(":");return Z.length>=3&&Z[2]?.trim()?Z.slice(2).join(":").trim():void 0}function lz($){let Z=k9($.credentialId);if(Z)return Z;return`scoped-${b9("sha256").update($.accountId).digest("hex")}`}function dz($,Z){let J=new Set,X=new Map;for(let G of Z){if(!G.credentialId.trim()||!G.accountId.trim()||J.has(G.credentialId))throw Error("Claustrum returned an ambiguous account inventory");J.add(G.credentialId);let Y=X.get(G.accountId)??[];Y.push(G),X.set(G.accountId,Y)}return[...X.values()].map((G)=>{let Y=$.accounts.find((V)=>A(V)&&V.anthropicAccountUuid===G[0]?.accountId),z=G.toSorted((V,j)=>V.credentialId.localeCompare(j.credentialId)),K=z.filter((V)=>V.state==="active"),W=K.length?K:z,Q=W.find((V)=>V.credentialId==="oauth:anthropic")??W.find((V)=>V.credentialId===Y?.claustrumScopedCredentialId)??W[0];if(!Q)throw Error("Claustrum returned an empty account identity group");return Q}).sort((G,Y)=>G.credentialId.localeCompare(Y.credentialId))}function iz($,Z,J,X=Date.now()){if(new Set($.accounts.map((H)=>H.id)).size!==$.accounts.length)throw Error("Account configuration contains duplicate route identities");let G=dz($,Z),Y=Z.find((H)=>H.credentialId==="oauth:anthropic")?.accountId,z=G.find((H)=>H.accountId===Y),K=new Set($.claustrum?.disabledAccountIdentities??[]);for(let H of $.accounts){if(!A(H)||!H.anthropicAccountUuid)continue;if(H.enabled===!1)K.add(H.anthropicAccountUuid);else K.delete(H.anthropicAccountUuid)}let W=new Set($.accounts.filter(A).map((H)=>H.id)),Q=new Set($.accounts.map((H)=>H.id)),V=G.filter((H)=>H!==z).map((H)=>{let U=$.accounts.find((O)=>A(O)&&W.has(O.id)&&O.anthropicAccountUuid===H.accountId),x=U?.id??lz(H);while(x!==U?.id&&Q.has(x)||x==="main")x=`scoped-${x}`;if(Q.add(x),U)W.delete(U.id);return{id:x,label:U?.label??k9(H.credentialId)??H.email??H.credentialId,type:"oauth",enabled:U?U.enabled!==!1:!K.has(H.accountId),addedAt:U?.addedAt??X,anthropicAccountUuid:H.accountId,claustrumScopedCredentialId:H.credentialId,claustrumScopedState:H.state,authLineageId:`scoped:${b9("sha256").update(H.accountId).digest("hex")}`,refresh:"",quota:U?.quota,profile:U?.profile,prime:U?.prime,lastUsed:U?.lastUsed,lastQuotaRefreshError:U?.lastQuotaRefreshError}}),j=new Map(V.map((H)=>[H.id,H])),B=$.accounts.flatMap((H)=>{if(!A(H))return[H];let U=j.get(H.id);if(!U)return[];return j.delete(H.id),[U]});B.push(...j.values());let q={...$,claustrum:{...$.claustrum,scopedRoster:!0,primaryAccount:z?{credentialId:z.credentialId,accountId:z.accountId,state:z.state}:void 0,disabledAccountIdentities:[...K].sort()},accounts:B};return{primary:z,accounts:V,storage:q,view:J}}async function E9($){if($.signal?.throwIfAborted(),n(await f($.path))!=="claustrum")return;let Z=await Q0({name:"scoped-roster",path:$.path,ttlMs:30000,renew:!0});if(!Z)throw Error("Claustrum account discovery is already in progress");try{if(n(await f($.path))!=="claustrum")return;let J=await $.custody.discover($.signal);$.signal?.throwIfAborted();let X=await i1($.path,(Y)=>{if(n(Y)!=="claustrum")return{storage:Y,result:void 0,save:!1};let z=iz(Y,J.accounts,J.view,$.now?.()),K=new Set(z.storage.accounts.map((Q)=>Q.id)),W=Y.accounts.filter((Q)=>A(Q)&&!K.has(Q.id)).map((Q)=>Q.id);return{storage:z.storage,result:z,options:{removedAccountIds:W,preserveExistingAccountOrder:!1},save:JSON.stringify(Y)!==JSON.stringify(z.storage)}},{assertAuthority:async()=>{$.signal?.throwIfAborted(),await Z.assertOwned()}});if(!X)return;let G=await f($.path);if($.signal?.throwIfAborted(),await Z.assertOwned(),!G||n(G)!=="claustrum")return;return{...X,storage:G,accounts:G.accounts.filter((Y)=>A(Y)&&Boolean(Y.claustrumScopedCredentialId))}}finally{await Z.release()}}var cz="https://api.anthropic.com/api/oauth/profile",sz=604800000;async function v9($){y1($.accessToken,"anthropic");let Z=await($.fetchImpl??fetch)(cz,{method:"GET",signal:$.signal,headers:{Authorization:`Bearer ${$.accessToken}`,Accept:"application/json","anthropic-beta":"oauth-2025-04-20"}});if(!Z.ok)throw Error(`Claude profile check failed: ${Z.status}`);let J=await Z.json(),X=J.organization?.rate_limit_tier,G=J.organization?.organization_type;if(typeof X!=="string"||X.trim()===""||typeof G!=="string"||G.trim()==="")throw Error("Claude profile response is missing account metadata");return{tier:X,orgType:G,checkedAt:$.now?.()??Date.now(),...$.accountIdentity!==void 0&&{accountIdentity:$.accountIdentity},...$.providerAccountUuid!==void 0&&{providerAccountUuid:$.providerAccountUuid}}}function Vq($,Z){if(!$)return!1;if(Z===void 0)return!0;return $.accountIdentity===void 0||$.accountIdentity===Z}function Qq($,Z=Date.now()){return Boolean($&&Number.isFinite($.checkedAt)&&Z>=$.checkedAt&&Z-$.checkedAt<sz)}function $$($){let Z=$?.tier.match(/^default_claude_max_(\d+)x$/);if(!Z)return;let J=`Max ${Z[1]}x`;return $?.orgType==="claude_team"?`Team · ${J}`:J}function xq($={}){return T1.connect({...$,connectionFile:$.connectionFile??W6()})}class nz{#$;#Z=new AbortController;#G;#Y;#z;#J;#X;#V=!1;constructor($){this.#$=$}#K($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}#W($,Z){let J=AbortSignal.any([this.#Z.signal,...Z?[Z]:[]]);return new Promise((X,G)=>{let Y=()=>J.removeEventListener("abort",z),z=()=>{Y(),G(J.reason)};if(J.addEventListener("abort",z,{once:!0}),$.then((K)=>{if(Y(),J.aborted)G(J.reason);else X(K)},(K)=>{Y(),G(K)}),J.aborted)z()})}async#Q(){if(this.#K(),this.#G)return this.#G;if(!this.#Y)this.#Y=this.#$.connect().then(($)=>{if(this.#Z.signal.aborted)$.close(),this.#K();return this.#G=new u4({client:$,tokenPath:this.#$.tokenPath}),this.#G}).finally(()=>{this.#Y=void 0});return this.#W(this.#Y)}snapshot(){return this.#J}refresh(){if(this.#K(),this.#z)return this.#z;return this.#z=(async()=>{if(n(await f(this.#$.storagePath))!=="claustrum"){this.#J=void 0,this.#G?.close(),this.#G=void 0;return}let $=await this.#Q(),Z=await E9({path:this.#$.storagePath,custody:$,signal:this.#Z.signal});if(this.#K(),this.#J=Z,Z)this.#$.onRoster?.(Z);return Z})().finally(()=>{this.#z=void 0}),this.#z}start(){if(this.#V)return;this.#K(),this.#V=!0;let $=async()=>{try{await this.refresh()}catch{if(!this.#Z.signal.aborted)this.#$.onError?.()}if(this.#Z.signal.aborted)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#X=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#X=void 0,$()},Z),this.#X.unref?.()};$()}async authorize($,Z){this.#K(Z);let J=this.#J??await this.#W(this.refresh(),Z),X=await f(this.#$.storagePath);if(this.#K(Z),!J||n(X)!=="claustrum")throw Error("Claustrum scoped custody is not active");let G,Y;if($==="main"){let z=X?.claustrum?.primaryAccount;if(J.primary?.state!=="active"||z?.state!=="active"||z.accountId!==J.primary.accountId||z.credentialId!==J.primary.credentialId)throw Error("Claustrum primary account is unavailable or changed");if(G=J.primary.credentialId,Y=J.primary.accountId,X?.claustrum?.disabledAccountIdentities?.includes(Y))throw Error("Claustrum primary account is disabled")}else{let z=J.accounts.find((W)=>W.id===$),K=X?.accounts.find((W)=>W.id===$);if(!z||!K||!A(K)||K.enabled===!1||K.claustrumScopedState!=="active"||K.claustrumScopedCredentialId!==z.claustrumScopedCredentialId||K.anthropicAccountUuid!==z.anthropicAccountUuid)throw Error("Claustrum route is disabled, removed or changed");G=z.claustrumScopedCredentialId,Y=z.anthropicAccountUuid}if(!G||!Y)throw Error("Claustrum route has no verified identity");return(await this.#W(this.#Q(),Z)).authorize({credentialId:G,accountId:Y},AbortSignal.any([this.#Z.signal,...Z?[Z]:[]]))}async reportFailure($,Z,J){if(this.#K(),!this.#G)throw Error("Claustrum dispatch receipt has no active owner");await this.#G.reportFailure($,Z,J)}async fetchQuota($,Z=fetch){let J=await this.authorize($);return s1({accessToken:J.accessToken,fetchImpl:this.#j(J,Z)})}async fetchProfile($,Z=fetch,J){let X=await this.authorize($,J);return v9({accessToken:X.accessToken,accountIdentity:X.accountId,providerAccountUuid:X.accountId,signal:J,fetchImpl:this.#j(X,Z)})}#j($,Z){return Object.assign(async(J,X)=>{this.#K();let G=await Z(J,{...X,signal:AbortSignal.any([this.#Z.signal,...X?.signal?[X.signal]:[]])});if(G.status===401)await this.reportFailure($,G.status,"direct").catch(()=>this.#$.onError?.());return G},{preconnect:Z.preconnect})}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(Error("Claustrum scoped runtime is closed")),this.#X)(this.#$.clearTimeoutImpl??clearTimeout)(this.#X);this.#X=void 0,this.#G?.close(),this.#J=void 0}}var Cq="claude-account";function az($){let Z=$.trim().split(/\s+/).filter(Boolean);if(Z.length===0)return{type:"status"};let J=Z[0],X=Z.slice(1).join(" ");if(J==="enable"&&X)return{type:"enable",id:X};if(J==="disable"&&X)return{type:"disable",id:X};if(J==="remove"&&X)return{type:"remove",id:X};if(J==="move-up"&&X)return{type:"move-up",id:X};if(J==="move-down"&&X)return{type:"move-down",id:X};if(J==="reset-backoff"&&!X)return{type:"reset-backoff"};if(J==="enrollment-reset"&&!X)return{type:"enrollment-reset"};if(J==="claustrum"&&!X)return{type:"claustrum-mode",mode:"claustrum"};if(J==="local"&&!X)return{type:"claustrum-mode",mode:"local"};if(J==="add-apikey"&&X){let G=X,Y,z,K=G.match(/--base-url\s+(\S+)/);if(K)Y=K[1],G=G.replace(K[0],"").trim();let W=G.match(/--auth-header\s+(authorization-bearer|x-api-key)/);if(W)z=W[1],G=G.replace(W[0],"").trim();let Q,V=G.match(/--label\s+(.+)/);if(V)Q=V[1]?.trim()||void 0,G=G.replace(V[0],"").trim();let j=G.indexOf(" ");if(j===-1){if(!G)return{type:"usage"};return{type:"add-apikey",apiKey:G,baseURL:Y,authHeader:z,label:Q}}let B=G.slice(0,j),q=G.slice(j+1).trim();return{type:"add-apikey",apiKey:B,label:Q??(q||void 0),baseURL:Y,authHeader:z}}if(J==="add-oauth-start")return{type:"add-oauth-start"};if(J==="add-oauth-finish"&&X){let G=X,Y,z=G.match(/--label\s+(.+)/);if(z)Y=z[1]?.trim()||void 0,G=G.replace(z[0],"").trim();if(!G)return{type:"usage"};return{type:"add-oauth-finish",code:G,label:Y}}return{type:"usage"}}function h9($){switch($){case"na":return"n/a (OpenCode-managed)";case"off":return"not enrolled";case"on-vault-served":return"vault-served";case"on-vault-reauth":return"vault reauth";case"on-cold":return"vault cold";case"unknown-identity":return"unknown identity";case"on-identity-mismatch":return"identity mismatch";case"on-corrupt-binding":return"corrupt binding"}}function tz($,Z=!1){switch($.state){case"idle":return["- Enrollment: not enrolled"];case"busy":return["- Enrollment: another plugin process is reconciling"];case"unavailable":return["- Enrollment: temporarily unavailable"];case"pending":return $.requestId&&/^[A-Za-z0-9_-]{1,128}$/.test($.requestId)?[`- Enrollment: pending approval (${$.requestId})`,`- Approve: \`ck auth enroll approve --request-id ${$.requestId}\``]:$.requestId?["- Enrollment: pending approval; inspect it with `ck auth enroll list`"]:["- Enrollment: preparing request"];case"approved":{let J=$.approvedName??$.proposedName;return/^[A-Za-z0-9_-]{1,128}$/.test(J)?[`- Enrollment: approved as enrolled:${J} (generation ${$.tokenGeneration}${Z?"":"; scoped serving not active yet"})`,...Z?[]:[`- Grant: \`ck auth grant --principal enrolled:${J} --selector-kind category --selector anthropic-native --operation read\``]]:[`- Enrollment: approved (generation ${$.tokenGeneration}${Z?"":"; scoped serving not active yet"})`,...Z?[]:["- Inspect the approved name with `ck auth enroll list` before granting access."]]}case"denied":return["- Enrollment: denied by operator"];case"blocked":return[`- Enrollment: blocked (${$.code})`]}}function oz($){let Z=[],J=$.quota?.mainQuota?.five_hour;Z.push({id:"main",label:$.main?.provider==="anthropic"?"OpenCode anthropic":"Main",role:"main",enabled:!0,quotaPercent:J?.usedPercent??null,tierLabel:$$($.main?.profile)});for(let X of $.accounts){let G=X.quota?.five_hour;Z.push({id:X.id,label:X.label??X.id,role:"fallback",enabled:X.enabled!==!1,quotaPercent:G?.usedPercent??null,tierLabel:X.type==="oauth"?$$(X.profile):void 0})}return Z}var l4=["Usage:"," /claude-account Show account list"," /claude-account enable <id> Enable a fallback account"," /claude-account disable <id> Disable a fallback account"," /claude-account remove <id> Remove a fallback account"," /claude-account claustrum Enable Claustrum mode"," /claude-account local Enable local mode"," /claude-account move-up <id> Move a fallback account up"," /claude-account move-down <id> Move a fallback account down"," /claude-account reset-backoff Clear main OAuth refresh and quota backoff"," /claude-account enrollment-reset Retry a denied/blocked enrollment"," /claude-account add-apikey <key> Add an API key fallback account"," /claude-account add-oauth-start Start OAuth device flow"," /claude-account add-oauth-finish <code> Complete OAuth flow"].join(`
30
- `);async function Rq($){let Z=az($.argumentsText),J=$.storage.accounts,X="main";if(Z.type==="status"){let Y=$.statusProjection?.accounts??oz($.storage),z=$.statusProjection?.claustrumDetection??$.claustrum?.status??"unknown",K=["## Claude Accounts","",`- Custody mode: ${n($.storage)}`,`- Claustrum: ${z}`,...$.statusProjection?.claustrumEnrollment?tz($.statusProjection.claustrumEnrollment):[],""];for(let W of Y){let Q=W.quotaPercent!=null?` ${Math.round(W.quotaPercent)}%`:"",V=!W.enabled?" (disabled)":"",j=W.tierLabel?` · ${W.tierLabel}`:"",B=$.statusProjection?.accounts.find((x)=>x.id===W.id),q=$.storage.accounts.find((x)=>x.id===W.id),H=q?$.resolveCustodyBinding?.(q):void 0,U=B?h9(B.custodyState):W.id!=="main"&&q&&w5($.storage,q,H)?h9("on-cold"):"local";K.push(`- **${W.label}** [${W.role}]${j}${V}${Q} · ${U}`)}return K.push("",l4),{text:K.join(`
31
- `)}}if(Z.type==="usage")return{text:l4};if(Z.type==="claustrum-mode"){if(!$.transition)return{text:"Claustrum mode transition is unavailable."};return $.transition(Z.mode)}if(Z.type==="enrollment-reset"){if(n($.storage)!=="claustrum")return{text:"Claustrum enrollment is available only in Claustrum mode."};if(!$.resetEnrollment)return{text:"Claustrum enrollment reset is unavailable."};return $.resetEnrollment()}if(Z.type==="add-apikey")return{text:"add-apikey"};if(Z.type==="add-oauth-start")return{text:"add-oauth-start"};if(Z.type==="add-oauth-finish")return{text:"add-oauth-finish"};if(Z.type==="reset-backoff")return{text:"Main OAuth refresh and quota backoff cleared.",updated:{id:"main",action:"reset-backoff"}};let G=Z.id;if(G==="main")return{text:`Cannot ${Z.type} the main account (OpenCode managed).`};if(Z.type==="enable"||Z.type==="disable"){let Y=J.find((z)=>z.id===G);if(!Y)return{text:`Account "${G}" not found.`};return{text:`Account "${Y.label??G}" ${Z.type}d.`,updated:{id:G,action:Z.type,enabled:Z.type==="enable"}}}if(Z.type==="remove"){let Y=J.find((K)=>K.id===G);if(!Y)return{text:`Account "${G}" not found.`};if(n($.storage)==="claustrum"&&A(Y)&&Y.claustrumScopedCredentialId)return{text:`Account "${Y.label??G}" is managed by Claustrum. Disable it to stop routing, or remove it from the vault.`};let z=$.resolveCustodyBinding?.(Y);if(n($.storage)==="claustrum"&&A(Y)&&z?.status==="resolved"&&z.source==="manifest")return{text:`Account "${Y.label??G}" is bound by the Claustrum manifest. Disable it to stop routing, or remove its Claustrum binding before removing the routing row.`};return{text:`Account "${Y.label??G}" removed.`,updated:{id:G,action:"remove"}}}if(Z.type==="move-up"){let Y=J.findIndex((Q)=>Q.id===G);if(Y<0)return{text:`Account "${G}" not found.`};if(Y===0)return{text:`Account "${J[Y]?.label??G}" is already first.`};let z=J.map((Q)=>Q.id),K=[...J];[K[Y-1],K[Y]]=[K[Y],K[Y-1]];let W=K.map((Q)=>Q.id);return{text:`Account "${J[Y]?.label??G}" moved up.`,updated:{id:G,action:"reorder",previousOrder:z,newOrder:W}}}if(Z.type==="move-down"){let Y=J.findIndex((Q)=>Q.id===G);if(Y<0)return{text:`Account "${G}" not found.`};if(Y===J.length-1)return{text:`Account "${J[Y]?.label??G}" is already last.`};let z=J.map((Q)=>Q.id),K=[...J];[K[Y],K[Y+1]]=[K[Y+1],K[Y]];let W=K.map((Q)=>Q.id);return{text:`Account "${J[Y]?.label??G}" moved down.`,updated:{id:G,action:"reorder",previousOrder:z,newOrder:W}}}return{text:l4}}var rz="ANTHROPIC_CUSTOM_HEADERS",ez=64,I1=new Map,d4=new Set,$K=new Set(["authorization","proxy-authorization","x-api-key","host","content-length","content-type","connection","transfer-encoding","upgrade","keep-alive","te","trailer","anthropic-version","anthropic-beta","x-parent-session-id","x-session-affinity","x-opencode-session","x-anthropic-effort-plan","x-cortexkit-billing-lineage"]);function y9($,Z){I1.delete($),I1.set($,Z);while(I1.size>ez){let J=I1.keys().next().value;if(J===void 0)break;I1.delete(J),d4.delete(J)}}function g9($,Z,J){if($K.has(Z.trim().toLowerCase()))throw TypeError("protected header");$.set(Z,J)}function ZK($){if(!$?.trim())return new Headers;let Z=I1.get($);if(Z!==void 0||I1.has($))return new Headers(Z??[]);try{let J=new Headers,X=$.trim();if(!X.startsWith("{")&&!X.startsWith("["))for(let Y of X.split(/\r?\n|,\s*(?=[^,\s:]+:)/).map((z)=>z.trim()).filter(Boolean)){let z=Y.indexOf(":");if(z<=0)throw TypeError("invalid header entry");g9(J,Y.slice(0,z).trim(),Y.slice(z+1).trim())}else{let Y=q0(X);if(Y==null||typeof Y!=="object"||Array.isArray(Y))throw TypeError("invalid header object");for(let[z,K]of Object.entries(Y)){if(K==null)continue;g9(J,z,Array.isArray(K)?K.map(String).join(", "):String(K))}}let G=[...J.entries()];return y9($,G),new Headers(G)}catch{if(y9($,null),!d4.has($))d4.add($),P.warn("custom-headers","ignoring malformed ANTHROPIC_CUSTOM_HEADERS",{reason:"invalid or protected header configuration"});return new Headers}}function wq($,Z=process.env[rz]){return ZK(Z).forEach((X,G)=>{$.set(G,X)}),$}var Sq="claude-fast";var y$=!1;function Iq(){return y$}function fq($){y$=$}function bq(){y$=!1}function JK($){let Z=$.trim().split(/\s+/).filter(Boolean);if(Z.length===0)return{type:"status"};if(Z.length===1&&Z[0]==="on")return{type:"enable"};if(Z.length===1&&Z[0]==="off")return{type:"disable"};return{type:"usage"}}function $2($){return["## Claude Fast Mode Status","",`- Enabled: ${$?.enabled??y$?"enabled":"disabled"}`,"- Persisted: ~/.config/opencode/anthropic-auth.json","- Scope: adds Anthropic fast mode to supported Opus requests","- Supported models: claude-opus-4-6, claude-opus-4-7, claude-opus-4-8, claude-opus-5, and claude-opus-5-5",'- Request changes: adds `speed: "fast"` and the `fast-mode-2026-02-01` beta header',"- Note: fast and standard speeds do not share prompt-cache prefixes"].join(`
32
- `)}function kq($){let Z=JK($.argumentsText),J=$.enabled??y$;if(Z.type==="status")return $2({enabled:J});if(Z.type==="enable")return["## Claude Fast Mode Enabled","",$2({enabled:!0})].join(`
33
- `);if(Z.type==="disable")return["## Claude Fast Mode Disabled","",$2({enabled:!1})].join(`
34
- `);return["## Claude Fast Mode Usage","","Usage: `/claude-fast`, `/claude-fast on`, or `/claude-fast off`.","",$2({enabled:J})].join(`
35
- `)}var Z$="claude-killswitch";function XK($){let Z=$.trim().split(/\s+/).filter(Boolean);if(Z.length===0)return{type:"status"};if(Z.length===1&&Z[0]==="on")return{type:"on"};if(Z.length===1&&Z[0]==="off")return{type:"off"};if(Z[0]==="set"){let J=[];for(let X=1;X<Z.length;X++){let G=Z[X]?.match(/^([^:]+):(\d+),(\d+)(?:,(\d+))?$/);if(!G)return{type:"usage"};let[,Y,z,K,W]=G,Q=typeof W==="string"&&W.length>0?Number.parseInt(W,10):void 0,V={account:Y,fh:Number.parseInt(z,10),sd:Number.parseInt(K,10)};if(Q!==void 0)V.scoped=Q;J.push(V)}if(J.length===0)return{type:"usage"};return{type:"set",entries:J}}return{type:"usage"}}function Z2($,Z){let J=$.enabled===!0,X=["## Killswitch","",`Status: **${J?"ON":"OFF"}**`];if(J){X.push(""),X.push("| Account | 5h threshold | 1w threshold | Scoped |"),X.push("| ------- | ------------ | ------------ | ------ |");let G=C$($.main);X.push(`| main | ≥ ${G.five_hour}% | ≥ ${G.seven_day}% | ≤ ${G.scoped}% |`);for(let Y of Z){let z=C$($.accounts?.[Y]??$.main);X.push(`| ${Y} | ≥ ${z.five_hour}% | ≥ ${z.seven_day}% | ≤ ${z.scoped}% |`)}}return X.join(`
36
- `)}var m9=["## Killswitch Commands","","```",`/${Z$} — show status`,`/${Z$} on — enable with current or default thresholds`,`/${Z$} off — disable`,`/${Z$} set all:5,10 — set all accounts to 5h≥5%, 1w≥10%`,`/${Z$} set main:3,8,0 — set 5h≥3%, 1w≥8%, scoped≤0%`,`/${Z$} set main:3,8 work-alt:5,10 — per-account`,"```"].join(`
37
- `);function hq($){let Z=XK($.argumentsText);if(Z.type==="status")return{text:`${Z2($.config,$.accountIds)}
38
-
39
- ${m9}`};if(Z.type==="on"){let X={...$.config,enabled:!0,main:$.config.main??{five_hour:N1.five_hour,seven_day:N1.seven_day}};return{text:`## Killswitch Enabled
40
-
41
- ${Z2(X,$.accountIds)}`,updatedConfig:X}}if(Z.type==="off")return{text:"## Killswitch Disabled",updatedConfig:{...$.config,enabled:!1}};if(Z.type==="set"){let X={...$.config.accounts??{}},G={...$.config,enabled:!0,accounts:X};for(let z of Z.entries){let K={five_hour:z.fh,seven_day:z.sd};if(z.scoped!==void 0)K.scoped=z.scoped;if(z.account==="main")G.main=K;else if(z.account==="all"){G.main=K;for(let W of $.accountIds)X[W]=K}else X[z.account]=K}return{text:`## Killswitch Updated
42
-
43
- ${Z2(G,$.accountIds)}`,updatedConfig:G}}return{text:`${Z2($.config,$.accountIds)}
44
-
45
- ${m9}`}}var gq="claude-logging",GK=["error","warn","info","debug","trace"];function YK($){let Z=$.trim().toLowerCase().split(/\s+/).filter(Boolean);if(Z.length===0)return{type:"status"};if(Z.length===1&&GK.includes(Z[0]))return{type:"level",level:Z[0]};return{type:"usage"}}function i4($){return["## Claude Log Level","",`Current log level: \`${$?.level??"info"}\``,"- Persisted: ~/.config/opencode/anthropic-auth.json","- Valid levels: error, warn, info, debug, trace","","Usage: `/claude-logging`, `/claude-logging error|warn|info|debug|trace`."].join(`
46
- `)}function mq($){let Z=YK($.argumentsText),J=$.level??"info";if(Z.type==="status")return i4({level:J});if(Z.type==="level")return["## Claude Log Level Updated","",`Level set to \`${Z.level}\`.`,"",...i4({level:Z.level}).split(`
47
- `).slice(2)].join(`
48
- `);return["## Claude Log Level Usage","","Usage: `/claude-logging`, `/claude-logging error|warn|info|debug|trace`.","",...i4({level:J}).split(`
49
- `).slice(2)].join(`
50
- `)}var uq="claude-fable-5",lq="claude-mythos-5",dq="claude-fable-5-1",iq="claude-mythos-5-1",c4="claude-haiku-4-5";function J$($){return $.endsWith("[1m]")?$.slice(0,-4):$}var s4={input:1,output:5},i9=["claude-fable-5-1","claude-mythos-5-1"],zK=["claude-fable-5","claude-mythos-5",...i9],n4={type:"adaptive",display:"summarized"},cq={input:10,output:50,cacheRead:1,cacheWrite5m:12.5,cacheWrite1h:20},sq={input:10,output:50,cacheRead:0.25,cacheWrite5m:12.5,cacheWrite1h:20},nq=1e6,aq=128000,KK="2026-06-09",WK="2026-09-01",p9={["claude-fable-5"]:{id:"claude-fable-5",name:"Claude Fable 5"},["claude-mythos-5"]:{id:"claude-mythos-5",name:"Claude Mythos 5",limited:!0},["claude-fable-5-1"]:{id:"claude-fable-5-1",name:"Claude Fable 5.1"},["claude-mythos-5-1"]:{id:"claude-mythos-5-1",name:"Claude Mythos 5.1",limited:!0}},tq={["claude-fable-5-1"]:p9["claude-fable-5-1"],["claude-mythos-5-1"]:p9["claude-mythos-5-1"]};function c9($){if(typeof $!=="string")return!1;let Z=J$($);return zK.some((J)=>Z===J||Z.startsWith(`${J}-`))}function VK($){if(typeof $!=="string")return!1;let Z=J$($);return i9.some((J)=>Z===J||Z.startsWith(`${J}-`))}function J2($){if(typeof $!=="string")return!1;let Z=J$($);return Z==="claude-fable-5-1"||Z.startsWith("claude-fable-5-1-")}function oq($){return VK($)?WK:KK}var u9="claude-sonnet-5",rq=n4;function eq($){if(typeof $!=="string")return!1;let Z=J$($);return Z===u9||Z.startsWith(`${u9}-`)}var l9="claude-opus-5",$U=n4;function QK($){if(typeof $!=="string")return!1;let Z=J$($);return!s9(Z)&&(Z===l9||Z.startsWith(`${l9}-`))}var d9="claude-opus-5-5",ZU="2026-09-18",JU=1e6,XU=128000,GU={input:4,output:20,cacheRead:0.2,cacheWrite5m:5,cacheWrite1h:8},YU=n4;function s9($){if(typeof $!=="string")return!1;let Z=J$($);return Z===d9||Z.startsWith(`${d9}-`)}function zU($){return QK($)||s9($)}function KU($){if(typeof $!=="string")return!1;if($.startsWith("gAAAA"))return!0;if(!$.startsWith("{"))return!1;try{let Z=JSON.parse($);return Z.type==="reasoning"&&typeof Z.id==="string"&&Z.id.startsWith("rs_")&&typeof Z.encrypted_content==="string"&&Z.encrypted_content.startsWith("gAAAA")}catch{return!1}}var QU="mid-conversation-output-config-2026-07-01";function a4($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function n9($){if($==="minimal")return"low";if($==="low"||$==="medium"||$==="high"||$==="xhigh"||$==="max")return $;return}function jK($){return J2($.model)}function HK($){let Z=[];for(let J of $){if(!Number.isSafeInteger(J.afterAssistantMessages)||J.afterAssistantMessages<0||!n9(J.effort))continue;let X={afterAssistantMessages:J.afterAssistantMessages,effort:J.effort},G=Z.at(-1);if(G&&G.afterAssistantMessages===X.afterAssistantMessages){G.effort=X.effort;continue}if(G?.effort===X.effort)continue;Z.push(X)}return Z}function jU($,Z){if(!jK($)||!Array.isArray($.messages))return{applied:!1,inserted:0};let J=HK(Z),X=a4($.output_config)?$.output_config:{},G=J[0]?.effort??n9(X.effort)??"high";if($.output_config={...X,effort:G},J.length<2)return{applied:!0,inserted:0};let Y=$.messages,z=new Map;for(let j of J.slice(1))z.set(j.afterAssistantMessages,j.effort);let K=0,W=G,Q=0,V=[];for(let j of Y){if(a4(j)&&j.role==="user"&&z.has(K)){let B=z.get(K);if(B&&B!==W)V.push({role:"system",content:[],output_config:{effort:B}}),W=B,Q++}if(V.push(j),a4(j)&&j.role==="assistant")K++}return $.messages=V,{applied:!0,inserted:Q}}function a9($){return process.env[$]?.trim()||void 0}function BK($){if(/^claude-sonnet(?:-|$)/.test($))return"sonnet";if(/^claude-opus(?:-|$)/.test($))return"opus";if(/^claude-haiku(?:-|$)/.test($))return"haiku";if(/^claude-(?:fable|mythos)(?:-|$)/.test($))return"fable";return null}var qK={sonnet:"ANTHROPIC_DEFAULT_SONNET_MODEL",opus:"ANTHROPIC_DEFAULT_OPUS_MODEL",haiku:"ANTHROPIC_DEFAULT_HAIKU_MODEL",fable:"ANTHROPIC_DEFAULT_FABLE_MODEL"};function UK($){if(typeof $!=="string"||!$)return $;let Z=BK($);if(Z){let J=a9(qK[Z]);if(J)return J}if($.startsWith("claude-")){let J=a9("ANTHROPIC_MODEL");if(J)return J}return $}function BU($){if(typeof $.model!=="string")return!1;let Z=UK($.model);if(Z===$.model)return!1;return $.model=Z,!0}import{createHash as LK}from"node:crypto";import{realpathSync as NK}from"node:fs";import{mkdir as xK,readdir as t9,rm as X2,stat as o9,writeFile as OK}from"node:fs/promises";import{tmpdir as DK}from"node:os";import{join as X$,resolve as MK}from"node:path";var CU="claude-prime",_K=60000,G7=60000,CK=21600000,RK=90000,PK=300000;function FK($){let Z=$.trim().split(/\s+/).filter(Boolean);if(Z.length===0)return{type:"status"};if(Z.length===1&&Z[0]==="on")return{type:"enable"};if(Z.length===1&&Z[0]==="off")return{type:"disable"};return{type:"usage"}}function o4($){if(!$)return 0;return($.inputTokens*s4.input+$.outputTokens*s4.output)/1e6}function AK($,Z,J){if(J?.label?.trim())return J.label;if($==="main")return"main";let X=Z?.accounts?.find((G)=>G.id===$);if(X?.label?.trim())return X.label;return $}function wK($,Z){let J=Z?.transient,X=$?.quota?.mainQuota,G=$?.prime?.main,Y={id:"main",label:"main",nextDueAt:r9(X?.five_hour),lastPrimedAt:J?.get("main")?.lastPrimedAt??null,lastResult:J?.get("main")?.lastResult,usage:G,estimatedCostUsd:o4(G)},z=($?.accounts??[]).filter(A).filter((K)=>K.id!=="main").filter((K)=>K.enabled!==!1).map((K)=>({id:K.id,label:AK(K.id,$,K),nextDueAt:r9(K.quota?.five_hour),lastPrimedAt:J?.get(K.id)?.lastPrimedAt??null,lastResult:J?.get(K.id)?.lastResult,usage:K.prime,estimatedCostUsd:o4(K.prime)}));return[Y,...z]}function r9($){if(!$?.resetsAt)return;let Z=Date.parse($.resetsAt);if(!Number.isFinite(Z))return;return Z+G7}function G2($){let J=[$.enabled?"## Claude Prime Status":"## Claude Prime Disabled",""];J.push(`Status: ${$.enabled?"enabled":"disabled"}`),J.push(""),J.push("Accounts:");for(let X of $.accounts){let Y=X.usage?.count??0,z=TK(X.nextDueAt),K=SK(X.lastPrimedAt,X.lastResult),W=[`${X.label}`];if(z)W.push(`next prime ${z}`);if(K)W.push(K);if(Y>0)W.push(`${Y} ${Y===1?"prime":"primes"} ≈ $${IK(X.estimatedCostUsd??0)}`);J.push(`- ${W.join(" · ")}`)}return J.push(""),J.push("Usage: `/claude-prime on`, `/claude-prime off`, or status."),J.join(`
51
- `)}function TK($){if(typeof $!=="number")return"";return new Date($).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function SK($,Z){if(typeof $!=="number")return"";let J=new Date($).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});if(Z==="error")return`primed ${J} err`;if(Z==="skipped")return`primed ${J} skipped`;return`primed ${J} ✓`}function IK($){if($===0)return"0";if($<0.0001)return $.toExponential(2);return $.toFixed(Math.min(6,Math.max(0,4)))}function RU($){let Z=FK($.argumentsText);if(Z.type==="status")return{text:G2({enabled:$.enabled,accounts:$.accounts})};if(Z.type==="enable")return{text:G2({enabled:!0,accounts:$.accounts}),updated:{enabled:!0}};if(Z.type==="disable")return{text:G2({enabled:!1,accounts:$.accounts}),updated:{enabled:!1}};return{text:["## Claude Prime Usage","","Usage: `/claude-prime`, `/claude-prime on`, or `/claude-prime off`.","",G2({enabled:$.enabled,accounts:$.accounts})].join(`
52
- `)}}var fK={"not-oauth":"API-key account",disabled:"disabled","needs-reauth":"needs re-login",killswitch:"killswitch"};function bK($){if(!$.isOAuth)return{eligible:!1,reason:"not-oauth"};if(!$.isEnabled)return{eligible:!1,reason:"disabled"};if($.hasPermanentRefreshError)return{eligible:!1,reason:"needs-reauth"};return{eligible:!0}}function e9($){return fK[$]}var kK={model:c4,max_tokens:1,system:"Reply with 1 when you receive 0.",messages:[{role:"user",content:"0"}]};function PU(){return JSON.parse(JSON.stringify(kK))}function $7(){return X$(DK(),"opencode-anthropic-auth","prime")}function EK($){let Z=MK($),J;try{J=NK(Z)}catch(X){if(X.code!=="ENOENT")throw X;J=Z}return LK("sha256").update(J).digest("hex").slice(0,12)}function Y7($,Z){return X$($,EK(Z))}function vK($,Z,J){if(!/^[a-f0-9]{12,}$/i.test(J))throw Error("Prime account fingerprint must be a hexadecimal digest");return X$(Y7($,Z),J.toLowerCase().slice(0,12))}function Z7($,Z,J){return X$($,`${encodeURIComponent(Z)}-${J}`)}function J7($,Z){return X$($,`${encodeURIComponent(Z)}-bootstrap`)}function t4($,Z){if($==="main")return"main";if(Z&&"label"in Z&&Z.label?.trim())return Z.label;return $}function hK($){let Z=[],J=$.refresh?.mainLastRefreshError;Z.push({id:"main",label:"main",isOAuth:!0,isEnabled:!0,hasPermanentRefreshError:c1(J),storedQuota:$.quota?.mainQuota,storedFiveHour:$.quota?.mainQuota?.five_hour});for(let X of $.accounts??[]){if(X.id==="main"){P.debug("prime","ineligible",{account:t4(X.id,X),reason:"reserved-id"});continue}if(!A(X)){Z.push({id:X.id,label:t4(X.id,X),isOAuth:!1,isEnabled:X.enabled!==!1,hasPermanentRefreshError:!1});continue}Z.push({id:X.id,label:t4(X.id,X),isOAuth:!0,isEnabled:X.enabled!==!1,hasPermanentRefreshError:c1(X.lastRefreshError),storedQuota:X.quota,storedFiveHour:X.quota?.five_hour})}return Z}function X7($){if(!$?.resetsAt)return;let Z=Date.parse($.resetsAt);return Number.isFinite(Z)?Z:void 0}class yK{timer=null;setIntervalImpl;clearIntervalImpl;setTimeoutImpl;clearTimeoutImpl;postFireRefreshTimers=new Set;lastForcedCheck=new Map;stopped=!1;options;transient=new Map;counters=new Map;windowActive=new Map;constructor($){this.options=$,this.setIntervalImpl=$.setIntervalImpl??globalThis.setInterval,this.clearIntervalImpl=$.clearIntervalImpl??globalThis.clearInterval,this.setTimeoutImpl=$.setTimeoutImpl??globalThis.setTimeout,this.clearTimeoutImpl=$.clearTimeoutImpl??globalThis.clearTimeout}updateOptions($){this.options=$}start(){if(this.timer)return;if(this.stopped=!1,P.trace("prime","manager started"),this.timer=this.setIntervalImpl(()=>{this.tick().catch(($)=>{P.warn("prime","tick failed",{error:$ instanceof Error?$.message:String($)})})},_K),typeof this.timer==="object"&&"unref"in this.timer)this.timer.unref?.()}stop(){let $=this.timer!==null,Z=this.postFireRefreshTimers.size>0;if(this.stopped=!0,this.timer)this.clearIntervalImpl(this.timer),this.timer=null;for(let J of this.postFireRefreshTimers)this.clearTimeoutImpl(J);if(this.postFireRefreshTimers.clear(),this.lastForcedCheck.clear(),!$&&!Z)return;P.trace("prime","manager stopped")}isStopped(){return this.stopped}async tick(){let $=this.options.now?.()??Date.now();if(P.trace("prime","tick start",{now:$}),await this.sweepMarkers($),this.stopped){P.trace("prime","tick: stopped, aborting");return}let Z=await this.options.loadStorage();if(!Z){P.trace("prime","tick: no storage, skipping");return}if(Z.prime?.enabled!==!0){P.trace("prime","tick: feature disabled, skipping");return}let J=hK(Z);await Promise.all(J.map((X)=>this.runForAccount(X,Z,$))),P.trace("prime","tick end")}stats($,Z){let J=wK($??null,{now:Z,transient:this.transient});if(this.counters.size===0)return J;return J.map((X)=>{let G=this.counters.get(X.id);if(!G)return X;return{...X,usage:G,estimatedCostUsd:o4(G)}})}isWindowActive($){return this.windowActive.has($)}async runForAccount($,Z,J){try{if(this.stopped)return;let X=bK({storage:Z,accountId:$.id,isOAuth:$.isOAuth,isEnabled:$.isEnabled,hasPermanentRefreshError:$.hasPermanentRefreshError,quota:$.storedQuota});if(!X.eligible){P.debug("prime","ineligible",{account:$.label,reason:e9(X.reason)});return}let G=X7($.storedFiveHour);if(G!==void 0&&J<G+G7){P.trace("prime","not due",{account:$.label});return}let Y=await this.options.getAccountFingerprint($.id);if(!Y){P.debug("prime","credential identity unavailable",{account:$.label});return}let z=`${$.id}:${Y.toLowerCase().slice(0,12)}`,K=this.markerDir(Y),W=J7(K,$.id),Q=G===void 0?W:Z7(K,$.id,G);try{await o9(Q);return}catch(L){if(L.code!=="ENOENT")throw L}if(G===void 0&&await this.hasAnyClaimMarker($.id,Y))return;if(this.stopped)return;let V=this.lastForcedCheck.get(z);if(V!==void 0&&V.resetEpoch===G&&J<V.at+PK)return;this.lastForcedCheck.set(z,{at:J,resetEpoch:G});let j;try{j=await this.options.refreshQuota($.id)}catch(L){P.warn("prime","refresh failed",{account:$.label,error:L instanceof Error?L.message:String(L)});return}if(this.stopped)return;let B=await this.options.loadStorage();if(B?.prime?.enabled!==!0)return;let q=j.quota;if(!j.fresh){P.debug("prime","stale fresh-check",{account:$.label});return}if(!m5(q,B,$.id,c4)){P.debug("prime","ineligible",{account:$.label,reason:e9("killswitch")});return}let H=X7(q?.five_hour);if(H!==void 0&&H>J){P.debug("prime","window active",{account:$.label,resetsAt:q.five_hour?.resetsAt}),this.windowActive.set($.id,J);return}this.windowActive.delete($.id);let U=H??G,x=U===void 0?await this.tryClaimBootstrap($.id,Y):await this.tryClaim($.id,Y,U);if(!x){P.debug("prime","claim lost",{account:$.label,marker:`${$.id}-${U??"bootstrap"}`});return}let O=await this.options.loadStorage();if(this.stopped||O?.prime?.enabled!==!0){await X2(x,{force:!0});return}if(U!==void 0){if(await X2(W,{force:!0}),this.stopped){await X2(x,{force:!0});return}}await this.fire($,J,O)}catch(X){P.warn("prime","account evaluation failed",{account:$.label,error:X instanceof Error?X.message:String(X)})}}async tryClaim($,Z,J){let X=this.markerDir(Z),G=Z7(X,$,J);return this.tryClaimPath(X,G)}async tryClaimBootstrap($,Z){let J=this.markerDir(Z),X=J7(J,$);return this.tryClaimPath(J,X)}async tryClaimPath($,Z){try{await xK($,{recursive:!0})}catch{}try{return await OK(Z,"",{encoding:"utf8",flag:"wx"}),Z}catch(J){if(J.code==="EEXIST")return null;throw J}}async hasAnyClaimMarker($,Z){let J=this.markerDir(Z),X=`${encodeURIComponent($)}-`;try{return(await t9(J)).some((G)=>G.startsWith(X))}catch(G){if(G.code==="ENOENT")return!1;throw G}}async fire($,Z,J){let X;try{X=await this.options.sendPrime($.id)}catch(Y){let z=Y instanceof Error?Y.message:String(Y);P.warn("prime","prime fire threw",{account:$.label,error:z}),this.transient.set($.id,{lastPrimedAt:Z,lastResult:"error"});return}if(this.stopped)return;if(!X.ok){if(X.reason==="token-refresh")P.warn("prime","prime token refresh failed",{account:$.label,error:X.error});else if(X.reason==="vault-cold")P.debug("prime","prime vault credential cold",{account:$.label,reason:X.reason});else P.warn("prime","prime fire failed",{account:$.label,status:X.status,error:X.error});this.transient.set($.id,{lastPrimedAt:Z,lastResult:X.reason==="vault-cold"?"skipped":"error"});return}let G={inputTokens:X.usage?.inputTokens,outputTokens:X.usage?.outputTokens};try{let Y=await this.options.recordSuccess($.id,G);if(this.stopped){this.transient.delete($.id),this.counters.delete($.id);return}this.counters.set($.id,Y),this.transient.set($.id,{lastPrimedAt:Z,lastResult:"ok"}),P.info("prime","prime fired",{account:$.label,status:X.status,ms:X.ms,usage:{inputTokens:Y.inputTokens,outputTokens:Y.outputTokens}}),this.schedulePostFireRefresh($)}catch(Y){P.warn("prime","recordSuccess failed",{account:$.label,error:Y instanceof Error?Y.message:String(Y)}),this.transient.set($.id,{lastPrimedAt:Z,lastResult:"error"})}}schedulePostFireRefresh($){let Z=this.setTimeoutImpl(()=>{if(this.postFireRefreshTimers.delete(Z),this.stopped)return;(async()=>{let J=await this.options.loadStorage();if(this.stopped||J?.prime?.enabled!==!0)return;await this.options.refreshQuota($.id)})().catch((J)=>{P.debug("prime","post-fire refresh failed",{account:$.label,error:J instanceof Error?J.message:String(J)})})},RK);if(this.postFireRefreshTimers.add(Z),typeof Z==="object"&&"unref"in Z)Z.unref?.()}async sweepMarkers($){let Z=this.storageMarkerDir(),J=await this.sweepMarkerDirectory(Z,$);if(J>0)P.trace("prime","swept stale markers",{swept:J})}async sweepMarkerDirectory($,Z){let J;try{J=await t9($)}catch{return 0}let X=0;for(let G of J)try{let Y=X$($,G),z=await o9(Y);if(z.isDirectory()){X+=await this.sweepMarkerDirectory(Y,Z);continue}if(Z-z.mtimeMs>CK)await X2(Y,{force:!0}),X+=1}catch{}return X}storageMarkerDir(){return Y7(this.options.markerDir??$7(),this.options.storagePath)}markerDir($){return vK(this.options.markerDir??$7(),this.options.storagePath,$)}}import{randomUUID as z7}from"node:crypto";import{chmod as K7,lstat as gK,mkdir as mK,readdir as W7,readFile as V7,rename as pK,rm as r4,stat as uK,writeFile as lK}from"node:fs/promises";import{tmpdir as dK}from"node:os";import{join as Y2}from"node:path";var G$=3,e4=180000;function $3(){return process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR??Y2(dK(),"opencode-anthropic-auth","quota-header-feed")}function kU($){return($.storage?.accounts.filter(A).length??0)+($.mainOAuthConfigured?1:0)}function j7($){if($.schema_version!==G$||$.provider!=="anthropic")return!1;if(!Number.isFinite($.configured_account_count)||!Number.isFinite($.observed_at_ms))return!1;if(!$.quota||typeof $.quota!=="object")return!1;if(!Object.hasOwn($,"anthropic_account_uuid")||$.anthropic_account_uuid!==null&&typeof $.anthropic_account_uuid!=="string")return!1;if($.identity_source==="none")return!("credential_id"in $)&&!("account_ref"in $);if($.identity_source==="credential_id")return typeof $.credential_id==="string"&&$.credential_id.length>0&&$.credential_id!=="main"&&!("account_ref"in $);if($.identity_source==="account_ref")return typeof $.account_ref==="string"&&$.account_ref.length>0&&$.account_ref!=="main"&&!("credential_id"in $);return!1}function iK($){if($.schema_version!==G$||$.provider!=="anthropic"||!j7($))throw Error("Invalid quota header feed entry")}function Y$($){return typeof $==="number"&&Number.isFinite($)}function Z3($){if(!$||typeof $!=="object")return;let Z=$;if(!Y$(Z.usedPercent)||!Y$(Z.remainingPercent)||!Y$(Z.checkedAt))return;return{usedPercent:Z.usedPercent,remainingPercent:Z.remainingPercent,...typeof Z.resetsAt==="string"&&{resetsAt:Z.resetsAt},checkedAt:Z.checkedAt}}function cK($){if(!$||typeof $!=="object")return;let Z=$,J=Z3(Z);if(!J||typeof Z.id!=="string"||!Z.id.trim()||typeof Z.title!=="string"||!Z.title.trim()||typeof Z.modelName!=="string"||!Z.modelName.trim())return;return{...J,id:Z.id,title:Z.title,...typeof Z.modelId==="string"&&Z.modelId.trim()&&{modelId:Z.modelId},modelName:Z.modelName}}function Q7($){if(!$||typeof $!=="object")return;let Z=$;if(!Y$(Z.amountMinor)||typeof Z.currency!=="string"||!Z.currency.trim()||!Y$(Z.exponent))return;return{amountMinor:Z.amountMinor,currency:Z.currency,exponent:Z.exponent}}function sK($){if(!$||typeof $!=="object")return;let Z=$,J=Q7(Z.used),X=Q7(Z.limit);if(!J||!X||typeof Z.exhausted!=="boolean")return;return{used:J,limit:X,...Y$(Z.utilizationPercent)&&{utilizationPercent:Z.utilizationPercent},...typeof Z.severity==="string"&&{severity:Z.severity},exhausted:Z.exhausted}}function nK($,Z){if(!$||typeof $!=="object")return;let J=$,X={};for(let G of d1){if(!Z.has(G))continue;let Y=J[G];if(Y==="poll"||Y==="headers")X[G]=Y}return Object.keys(X).length>0?X:void 0}function aK($){let Z=Z3($.five_hour),J=Z3($.seven_day),X=Array.isArray($.scoped)?$.scoped.map(cK).filter((K)=>K!=null):void 0,G=sK($.extraUsage),Y=new Set;if(Z)Y.add("five_hour");if(J)Y.add("seven_day");if(typeof $.bindingWindow==="string")Y.add("bindingWindow");if(typeof $.fallbackAdvised==="boolean")Y.add("fallbackAdvised");if(X)Y.add("scoped");if(G)Y.add("extraUsage");let z=nK($.fieldSources,Y);return{...Z&&{five_hour:Z},...J&&{seven_day:J},...typeof $.bindingWindow==="string"&&{bindingWindow:$.bindingWindow},...typeof $.fallbackAdvised==="boolean"&&{fallbackAdvised:$.fallbackAdvised},...X&&{scoped:X},...G&&{extraUsage:G},...z&&{provenance:z}}}class tK{options;filePath;writeChain=Promise.resolve();constructor($={}){this.options=$;let Z=$.instanceId??`${process.pid}-${z7()}`;this.filePath=Y2($.directory??$3(),`${Z}.json`)}publish($){let{accountKey:Z,quota:J}=$;try{iK($)}catch(Y){return Promise.reject(Y)}let G={...$.identity_source==="credential_id"?{identity_source:"credential_id",credential_id:$.credential_id}:$.identity_source==="account_ref"?{identity_source:"account_ref",account_ref:$.account_ref}:{identity_source:"none"},schema_version:$.schema_version,provider:$.provider,configured_account_count:$.configured_account_count,observed_at_ms:$.observed_at_ms,anthropic_account_uuid:$.anthropic_account_uuid,quota:aK(J)};if(!Z)return Promise.reject(Error("Invalid quota header feed account key"));return this.writeChain=this.writeChain.catch(()=>{}).then(async()=>{let Y=this.options.directory??$3();await mK(Y,{recursive:!0,mode:448}),await K7(Y,448),await this.reapStaleSiblingLeases(Y);let z={};try{let W=JSON.parse(await V7(this.filePath,"utf8"));if(W.version===G$&&W.entries&&typeof W.entries==="object")z=W.entries}catch{}z[Z]=G;let K=`${this.filePath}.${z7()}.tmp`;try{await lK(K,`${JSON.stringify({version:G$,lease_horizon_ms:this.options.leaseMs??e4,entries:z})}
53
- `,{mode:384}),await K7(K,384),await pK(K,this.filePath)}finally{await r4(K,{force:!0})}}),this.writeChain}async reapStaleSiblingLeases($){let Z=this.options.now?.()??Date.now(),J=this.options.leaseMs??e4,X;try{X=await W7($)}catch{return}await Promise.all(X.filter((G)=>/^\d+-[0-9a-f-]+\.json$/i.test(G)).map(async(G)=>{let Y=Y2($,G);if(Y===this.filePath)return;try{let z=await uK(Y);if(z.mtimeMs>Z||Z-z.mtimeMs<J)return;await this.options.beforeRemoveFile?.(Y);let K=await gK(Y);if(K.ino!==z.ino||K.mtimeMs!==z.mtimeMs)return;await(this.options.removeFile??((W)=>r4(W)))(Y)}catch{}}))}async list(){await this.writeChain.catch(()=>{});let $=this.options.directory??$3(),Z=this.options.now?.()??Date.now(),J=this.options.leaseMs??e4,X;try{X=(await W7($)).filter((Y)=>Y.endsWith(".json"))}catch{return[]}let G=new Map;return await Promise.all(X.map(async(Y)=>{try{let z=JSON.parse(await V7(Y2($,Y),"utf8"));if(z.version!==G$||!z.entries||typeof z.entries!=="object")return;for(let[K,W]of Object.entries(z.entries)){if(!W||typeof W!=="object"||W.schema_version!==G$||W.provider!=="anthropic"||!j7(W))continue;let Q=W.observed_at_ms;if(Q>Z||Z-Q>=J)continue;let V=G.get(K);if(!V||Q>V.observed_at_ms)G.set(K,W)}}catch{}})),[...G.values()].sort((Y,z)=>Y.observed_at_ms-z.observed_at_ms)}async dispose(){await this.writeChain.catch(()=>{}),await r4(this.filePath,{force:!0})}}var g$="anthropic-ratelimit-unified-",H7={"5h":"five_hour","7d":"seven_day"};function hU($){return Object.keys(H7).some((Z)=>Number.isFinite(J3($,`${g$}${Z}-utilization`)))}function J3($,Z){let J=$.get(Z);if(J==null||J.trim()==="")return;let X=Number(J);return Number.isFinite(X)?X:void 0}function oK($,Z,J){let X=J3($,`${g$}${Z}-utilization`);if(X==null)return;let G=Math.min(100,Math.max(0,Math.round(X*100))),Y=J3($,`${g$}${Z}-reset`),z=Y==null?void 0:new Date(Y*1000),K=z&&Number.isFinite(z.getTime())?z.toISOString():void 0;return{usedPercent:G,remainingPercent:100-G,...K&&{resetsAt:K},checkedAt:J}}function yU($,Z=Date.now()){let J={},X=$.get(`${g$}fallback`),G={fallbackAdvised:X==="available",source:"headers",checkedAt:Z};for(let[z,K]of Object.entries(H7)){let W=oK($,z,Z);if(W)G[K]=W,J[K]="headers"}let Y=$.get(`${g$}representative-claim`);if(Y)G.bindingWindow=Y,G.bindingWindowSource="headers",J.bindingWindow="headers";if(X!==null)J.fallbackAdvised="headers";return{...G,fieldSources:J}}function m$($,Z){let{scoped:J,extraUsage:X,fieldSources:G,...Y}=$??{},{scoped:z,extraUsage:K,fieldSources:W,...Q}=Z,V={};for(let j of d1){let B=j==="scoped"?J:j==="extraUsage"?X:j==="fallbackAdvised"?W?.fallbackAdvised!==void 0?Z.fallbackAdvised:$?.fallbackAdvised??Z.fallbackAdvised:j==="bindingWindow"?$?.bindingWindowSource==="poll"?$?.bindingWindow:Z.bindingWindow??$?.bindingWindow:Z[j]??$?.[j];if(B===void 0)continue;let q=j==="fallbackAdvised"?W?.fallbackAdvised??($?.fallbackAdvised!==void 0?G?G.fallbackAdvised:n0($,j):void 0):(j==="scoped"||j==="extraUsage")&&B!==void 0?"poll":j==="bindingWindow"&&$?.bindingWindowSource==="poll"&&$.bindingWindow!==void 0?"poll":Z[j]!==void 0?W?.[j]??n0(Z,j):G?.[j]??n0($,j);if(q)V[j]=q}return{...Y,...Q,...Array.isArray(J)&&{scoped:J},...X!=null&&{extraUsage:X},fallbackAdvised:W?.fallbackAdvised!==void 0?Z.fallbackAdvised:$?.fallbackAdvised??Z.fallbackAdvised,bindingWindow:$?.bindingWindowSource==="poll"?$.bindingWindow:Z.bindingWindow??$?.bindingWindow,bindingWindowSource:$?.bindingWindowSource==="poll"?"poll":Z.bindingWindowSource??$?.bindingWindowSource,...Object.keys(V).length>0&&{fieldSources:V},source:"headers"}}var rK=globalThis.setTimeout;function B7($,Z){if($?.source!=="headers")return Z;let J=Boolean($.five_hour&&$.five_hour.checkedAt>(Z.five_hour?.checkedAt??0)),X=Boolean($.seven_day&&$.seven_day.checkedAt>(Z.seven_day?.checkedAt??0));if(!J&&!X)return Z;return m$(Z,{...J&&{five_hour:$.five_hour},...X&&{seven_day:$.seven_day},fallbackAdvised:$.fallbackAdvised,...$.bindingWindowSource==="headers"&&{bindingWindow:$.bindingWindow,bindingWindowSource:$.bindingWindowSource},source:"headers",checkedAt:Math.max(J?$.five_hour?.checkedAt??0:0,X?$.seven_day?.checkedAt??0:0)})}class j1{main=null;mainAccountId;mainQuotaIdentityKnown=!1;mainQuotaIdentityStrict=!1;mainGeneration=0;mainQuotaErrorGeneration=0;mainQuotaErrorClearedAt;fallbacks=new Map;fallbackAuthLineages=new Map;fallbackGenerations=new Map;inflightMain=null;inflightMainAccountId;inflightMainAccessToken;inflightMainToken=0;inflightFallbacks=new Map;mainLastApiError=void 0;fallbackApiErrors=new Map;apiGate=Promise.resolve();lastApiCallAt=0;storage;fetchImpl;fetchQuotaSnapshot;now;onMainQuotaFetched;onApiError;onFallbackQuotaFetched;onFallbackApiError;constructor($){this.storage=$.storage,this.fetchImpl=$.fetchImpl??fetch,this.fetchQuotaSnapshot=$.fetchQuotaSnapshot,this.now=$.now??Date.now,this.onMainQuotaFetched=$.onMainQuotaFetched,this.onApiError=$.onApiError,this.onFallbackQuotaFetched=$.onFallbackQuotaFetched,this.onFallbackApiError=$.onFallbackApiError,this.seedMainFromStorage($.storage,$.storage?.mainAccountId),this.seedMainBackoffFromStorage($.storage)}getMain($){if(this.mainAccountId!==$)return null;if(this.mainQuotaIdentityKnown&&this.mainQuotaIdentityStrict&&($===void 0||this.main?.quota.accountIdentity!==$))return null;return this.main}getFallback($,Z){return this.bindFallbackLineage($,Z),this.fallbacks.get($)??null}canFetchWithoutAccessToken(){return Boolean(this.fetchQuotaSnapshot&&(this.storage===null||this.storage?.claustrum?.scopedRoster===!0))}getAllFallbacks(){return this.fallbacks}setMain($,Z){this.mainAccountId=$,this.main=Z}clearMain(){this.mainAccountId=void 0,this.main=null}setMainQuotaAccountIdentity($,Z=!0,J=!1){let X=this.mainQuotaIdentityKnown,G=this.mainAccountId,Y=J||!X||this.mainAccountId!==$||this.mainQuotaIdentityStrict!==Z;if(this.mainQuotaIdentityKnown=!0,this.mainQuotaIdentityStrict=Z,!Y)return;if(this.mainGeneration+=1,this.mainAccountId=$,J)this.main=null,this.mainLastApiError=void 0,this.mainQuotaErrorGeneration+=1,this.mainQuotaErrorClearedAt=M1(this.mainQuotaErrorClearedAt,this.now());else if($!==void 0&&this.main?.quota.accountIdentity!==$)this.main=null;if($!==void 0&&this.mainLastApiError&&(this.mainLastApiError.accountIdentity!==void 0?this.mainLastApiError.accountIdentity!==$:X&&G!==void 0&&G!==$))return this.mainLastApiError=void 0,this.mainQuotaErrorGeneration+=1,this.mainQuotaErrorClearedAt=M1(this.mainQuotaErrorClearedAt,this.now()),this.mainQuotaErrorGeneration;return}setFallback($,Z,J){this.bindFallbackLineage($,J),this.fallbacks.set($,Z)}clearFallback($){this.fallbackGenerations.set($,(this.fallbackGenerations.get($)??0)+1),this.fallbacks.delete($),this.fallbackApiErrors.delete($),this.inflightFallbacks.delete(j1.fallbackInflightKey($))}pushMainFromHeaders($,Z){let J=Z.checkedAt??this.now(),X=m$(this.mainAccountId===$&&(!this.mainQuotaIdentityKnown||!this.mainQuotaIdentityStrict||this.main?.quota.accountIdentity===$)?this.main?.quota:void 0,{...Z,...$!==void 0&&{accountIdentity:$}}),G={quota:X,checkedAt:J,refreshAfter:_1(X,this.storage,J)};return this.setMain($,G),G}pushFallbackFromHeaders($,Z,J){if(!this.acceptFallbackQuotaObservation($,J))return null;let X=Z.checkedAt??this.now(),G=m$(this.fallbacks.get($)?.quota,{...Z,accountIdentity:$}),Y={quota:G,checkedAt:X,refreshAfter:_1(G,this.storage,X)};return this.fallbacks.set($,Y),Y}async refreshMain($,Z,J){let X=$,G=Z??$;if(!G&&!this.canFetchWithoutAccessToken())throw Error("Main OAuth access token is unavailable");return(await this.refreshMainWithMetadata(X,G,J)).quota}async refreshMainWithMetadata($,Z,J){let X=$,G=Z??$;if(!G&&!this.canFetchWithoutAccessToken())throw Error("Main OAuth access token is unavailable");if(J!==void 0&&(this.mainGeneration!==J||this.mainAccountId!==X))throw Error("Main quota identity changed before refresh");if(this.mainAccountId!==X){if(this.main=null,this.mainAccountId=X,this.mainQuotaIdentityKnown)this.mainGeneration+=1}if(this.inflightMain&&this.inflightMainAccountId===X&&this.inflightMainAccessToken===G)return this.inflightMain;if(this.isBackedOff()){if(this.main&&this.mainAccountId===X)return{quota:this.main.quota,fetched:!1};throw Error("Quota API rate-limited — try again later")}this.inflightMainAccountId=X,this.inflightMainAccessToken=G;let Y=this.mainGeneration,z=++this.inflightMainToken;return this.inflightMain=this._fetchMain(X,G??"",Y,z),this.inflightMain}async refreshFallback($,Z,J){return(await this.refreshFallbackWithMetadata($,Z,J)).quota}async refreshFallbackWithMetadata($,Z,J){if(!Z&&!this.canFetchWithoutAccessToken())throw Error("Fallback OAuth access token is unavailable");this.bindFallbackLineage($,J);let X=j1.fallbackInflightKey($),G=this.inflightFallbacks.get(X);if(G)return G;if(this.isFallbackBackedOff($)){let K=this.getFallback($);if(K)return{quota:K.quota,fetched:!1};throw Error("Quota API rate-limited — try again later")}let Y=this.fallbackGenerations.get($)??0,z=this._fetchFallback($,Z,Y,J);return this.inflightFallbacks.set(X,z),z.then(()=>{if(this.inflightFallbacks.get(X)===z)this.inflightFallbacks.delete(X)},()=>{if(this.inflightFallbacks.get(X)===z)this.inflightFallbacks.delete(X)}),z}async refreshAllFallbacks($,Z){let J=this.now();for(let X of $){if(X.enabled===!1)continue;let G=Z!==void 0?Z(X):X.access&&X.expires!==void 0&&X.expires>J?X.access:void 0;if(!G)continue;this.bindFallbackLineage(X.id,X);let Y=this.getFallback(X.id);if(Y&&J<Y.refreshAfter)continue;try{await this.refreshFallback(X.id,G,X)}catch{}}}refreshMainInBackground($){if(this.inflightMain)return;if(this.isBackedOff())return;this.refreshMain(this.mainAccountId,$).catch(()=>{})}scopedWindowIsStale($,Z){let J=_0($.quota,Z);return Boolean(J&&this.now()-J.checkedAt>=g0(this.storage))}isMainStale($){if(!this.main)return!0;if(this.mainQuotaIdentityKnown&&this.mainQuotaIdentityStrict&&(this.mainAccountId===void 0||this.main.quota.accountIdentity!==this.mainAccountId))return!0;return this.now()>=this.main.refreshAfter||this.scopedWindowIsStale(this.main,$)}isFallbackStale($,Z,J,X){let G=this.getFallback($,X);if(!G)return!0;return this.now()>=G.refreshAfter||this.scopedWindowIsStale(G,J)}shouldRefreshOnRequestCount($){let Z=h5(this.storage);if(Z<=0)return!1;return $>0&&$%Z===0}needsRefresh($,Z){return this.isMainStale(Z)||this.shouldRefreshOnRequestCount($)}updateStorage($){this.storage=$,this.seedMainFromStorage($,this.mainQuotaIdentityKnown?this.mainAccountId:$?.mainAccountId),this.seedMainBackoffFromStorage($)}seedMainFromStorage($,Z){let J=v5($);if(!J)return;let X={quota:{...J.quota,...(!this.mainQuotaIdentityKnown||!this.mainQuotaIdentityStrict)&&Z!==void 0&&J.accountIdentity===void 0&&{accountIdentity:Z}},refreshAfter:_1(J.quota,$,J.checkedAt),checkedAt:J.checkedAt},G=this.main&&this.mainAccountId===Z&&(!this.mainQuotaIdentityKnown||!this.mainQuotaIdentityStrict||this.main.quota.accountIdentity===Z)?this.main:void 0;if(G&&G.checkedAt>=X.checkedAt&&G.quota.source==="headers"&&X.quota.source==="poll"){let Y=m$(X.quota,G.quota);this.main={quota:Y,refreshAfter:_1(Y,$,G.checkedAt),checkedAt:G.checkedAt};return}if(this.main&&this.mainAccountId===Z&&this.main.checkedAt>=X.checkedAt)return;if(this.main=X,Z!==void 0)this.mainAccountId=Z}seedMainBackoffFromStorage($){let Z=$?.quota?.mainLastQuotaApiError,J=Z?.accountIdentity,X=typeof $?.quota?.mainQuotaErrorGeneration==="number"&&Number.isSafeInteger($.quota.mainQuotaErrorGeneration)&&$.quota.mainQuotaErrorGeneration>=0?$.quota.mainQuotaErrorGeneration:void 0,G=typeof $?.quota?.mainQuotaErrorClearedAt==="number"&&Number.isFinite($.quota.mainQuotaErrorClearedAt)&&$.quota.mainQuotaErrorClearedAt>=0?$.quota.mainQuotaErrorClearedAt:void 0;if(G!==void 0&&(this.mainQuotaErrorClearedAt===void 0||G>this.mainQuotaErrorClearedAt)){if(this.mainQuotaErrorClearedAt=M1(this.mainQuotaErrorClearedAt,G),(!Z||typeof Z.checkedAt==="number"&&Z.checkedAt<=G)&&(this.mainLastApiError?.checkedAt===void 0||this.mainLastApiError.checkedAt<=G))this.mainLastApiError=void 0}if(X!==void 0&&X>this.mainQuotaErrorGeneration){if(this.mainQuotaErrorGeneration=X,!Z&&(this.mainLastApiError?.checkedAt===void 0||this.mainQuotaErrorClearedAt===void 0||this.mainLastApiError.checkedAt<=this.mainQuotaErrorClearedAt))this.mainLastApiError=void 0}if(Z&&(!this.mainQuotaIdentityKnown||J===void 0||J===this.mainAccountId)&&(this.mainQuotaErrorClearedAt===void 0||typeof Z.checkedAt!=="number"||Z.checkedAt>this.mainQuotaErrorClearedAt)&&(this.mainLastApiError?.checkedAt===void 0||Z.checkedAt>=this.mainLastApiError.checkedAt)&&O1(Z,this.now())){if(this.mainLastApiError=Z,X!==void 0)this.mainQuotaErrorGeneration=X;return}if(this.mainAccountId!==void 0&&this.mainLastApiError?.accountIdentity!==void 0&&this.mainLastApiError.accountIdentity!==this.mainAccountId)this.mainLastApiError=void 0}seedFallbacksFromAccounts($){let Z=g0(this.storage),J=new Set($.map((X)=>X.id));for(let X of this.fallbackAuthLineages.keys())if(!J.has(X))this.clearFallback(X),this.fallbackAuthLineages.delete(X);for(let X of $){if(this.bindFallbackLineage(X.id,X))continue;if(X.enabled===!1)continue;let Y=X.lastQuotaRefreshError,z=T0(X.quota),K=this.fallbackApiErrors.get(X.id);if(Y&&O1(Y,this.now())&&z<=(Y.checkedAt??0)&&(!K||Y.checkedAt>=K.checkedAt))this.fallbackApiErrors.set(X.id,Y);else if(K&&z>=K.checkedAt)this.fallbackApiErrors.delete(X.id);if(!X.quota)continue;let W=T0(X.quota);if(W<=0)continue;let Q=this.getFallback(X.id);if(Q&&Q.checkedAt>=W)continue;this.setFallback(X.id,{quota:{...X.quota,accountIdentity:X.id},refreshAfter:W+Z,checkedAt:W},X)}}isBackedOff(){return O1(this.mainLastApiError,this.now())}isFallbackBackedOff($){return O1(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}getMainQuotaErrorGeneration(){return this.mainQuotaErrorGeneration}getMainQuotaIdentityGeneration(){return this.mainGeneration}getMainQuotaErrorClearedAt(){return this.mainQuotaErrorClearedAt}clearMainBackoff(){if(!this.mainLastApiError)return;return this.mainLastApiError=void 0,this.mainQuotaErrorGeneration+=1,this.mainQuotaErrorClearedAt=M1(this.mainQuotaErrorClearedAt,this.now()),this.mainQuotaErrorGeneration}static API_CALL_GAP_MS=1000;static fallbackInflightKey($){return $}static quotaLockName($){return`opencode-fallback-quota-refresh-${$.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}bindFallbackLineage($,Z){if(!Z)return!1;let J=this.fallbackAuthLineages.has($),X=this.fallbackAuthLineages.get($),G=J&&Z.authLineageId!==void 0&&X!==Z.authLineageId;if(G)this.clearFallback($);return this.fallbackAuthLineages.set($,Z.authLineageId),G}acceptFallbackQuotaObservation($,Z){let J=this.fallbackAuthLineages.has($),X=this.fallbackAuthLineages.get($),G=Z?.authLineageId;if(J&&X!==G)return P.trace("quota","skipped stale fallback quota observation after lineage change",{accountId:$,storedLineage:X,servedLineage:G}),!1;if(!J)this.fallbackAuthLineages.set($,G);return!0}isClosed=!1;close(){this.isClosed=!0,this.inflightFallbacks.clear(),this.inflightMain=null}_enqueueApiFetch($){let Z=async()=>{if(this.isClosed)throw Error("QuotaManager is closed");let X=this.now()-this.lastApiCallAt;if(X<j1.API_CALL_GAP_MS)await new Promise((G)=>{let Y=rK(G,j1.API_CALL_GAP_MS-X);if(typeof Y==="object"&&"unref"in Y)Y.unref()});if(this.isClosed)throw Error("QuotaManager is closed");return this.lastApiCallAt=this.now(),$()},J=this.apiGate.then(Z,Z);return this.apiGate=J.catch(()=>{}),J}async _fetchMain($,Z,J,X){return this._enqueueApiFetch(async()=>{try{if(this.isBackedOff()){if(this.main&&this.mainAccountId===$)return{quota:this.main.quota,fetched:!1};throw Error("Quota API rate-limited — try again later")}if(this.mainQuotaIdentityKnown&&this.mainQuotaIdentityStrict&&this.mainGeneration!==J)return{quota:{accountIdentity:$},fetched:!1};let G=await Q0({name:"opencode-main-quota-refresh",ttlMs:30000});if(!G){let Y=this.main;if(Y&&this.mainAccountId===$&&this.now()<Y.refreshAfter)return{quota:Y.quota,fetched:!1};throw Error("Quota refresh is already in progress")}try{let Y=this.now(),z=this.fetchQuotaSnapshot?await this.fetchQuotaSnapshot({kind:"main",accountId:$,accessToken:Z}):await s1({accessToken:Z,fetchImpl:this.fetchImpl,now:this.now}),K=this.now();if(this.mainQuotaIdentityKnown&&this.mainQuotaIdentityStrict&&this.mainGeneration!==J)return{quota:{...z,...$!==void 0&&{accountIdentity:$}},fetched:!0};let W=B7(this.mainAccountId===$&&(!this.mainQuotaIdentityKnown||!this.mainQuotaIdentityStrict||this.main?.quota.accountIdentity===$)?this.main?.quota:void 0,{...z,...$!==void 0&&{accountIdentity:$}});if(this.mainAccountId=$,this.main={quota:W,refreshAfter:_1(W,this.storage,K),checkedAt:W.checkedAt??K},this.mainLastApiError)this.mainLastApiError=void 0,this.mainQuotaErrorGeneration+=1,this.mainQuotaErrorClearedAt=M1(this.mainQuotaErrorClearedAt,K);return this.onMainQuotaFetched?.(W,K,A0(Z),Y,this.mainQuotaErrorGeneration,this.mainQuotaErrorClearedAt),{quota:W,fetched:!0}}catch(Y){throw this._handleMainFetchError(Y,J),Y}finally{await G.release()}}finally{if(this.inflightMainToken===X)this.inflightMain=null,this.inflightMainAccountId=void 0}})}async _fetchFallback($,Z,J,X){return this._enqueueApiFetch(async()=>{try{if((this.fallbackGenerations.get($)??0)!==J)return{quota:{accountIdentity:$},fetched:!1};if(this.isFallbackBackedOff($)){let Y=this.getFallback($,X);if(Y)return{quota:Y.quota,fetched:!1};throw Error("Quota API rate-limited — try again later")}let G=await Q0({name:j1.quotaLockName($),ttlMs:30000});if(!G){let Y=this.getFallback($,X);if(Y&&this.now()<Y.refreshAfter)return{quota:Y.quota,fetched:!1};throw Error("Quota refresh is already in progress")}try{let Y=this.now(),z=this.fetchQuotaSnapshot?await this.fetchQuotaSnapshot({kind:"fallback",accountId:$,accessToken:Z}):await s1({accessToken:Z,fetchImpl:this.fetchImpl,now:this.now}),K=this.now();if((this.fallbackGenerations.get($)??0)!==J)return{quota:{...z,accountIdentity:$},fetched:!0};let W=B7(this.getFallback($,X)?.quota,{...z,accountIdentity:$});return this.setFallback($,{quota:W,refreshAfter:_1(W,this.storage,K),checkedAt:W.checkedAt??K},X),this.fallbackApiErrors.delete($),this.onFallbackQuotaFetched?.($,W,K,Y),{quota:W,fetched:!0}}finally{await G.release()}}catch(G){throw this._handleFallbackFetchError($,G,J),G}})}static isAuthError($){if($.status===401||o2($))return!0;let J=$ instanceof Error?$.message:String($);return/quota check failed: 401\b/.test(J)}_handleMainFetchError($,Z){if(this.mainGeneration!==Z)return;if(this.mainQuotaIdentityKnown&&this.mainQuotaIdentityStrict&&this.mainAccountId===void 0)return;if(j1.isAuthError($))return;this.mainLastApiError=_6({error:$,now:this.now(),accountIdentity:this.mainAccountId,previous:this.mainLastApiError}),this.mainQuotaErrorGeneration+=1,this.onApiError?.(this.mainLastApiError,this.mainQuotaErrorGeneration)}_handleFallbackFetchError($,Z,J){if((this.fallbackGenerations.get($)??0)!==J)return;if(j1.isAuthError(Z))return;let X=this.fallbackApiErrors.get($),G=_6({error:Z,now:this.now(),previous:X,accountIdentity:$});this.fallbackApiErrors.set($,G),this.onFallbackApiError?.($,G)}}var nU="claude-quota",q7={five_hour:"5h",seven_day:"1w"};function z2($){return`${Math.round($*10)/10}%`}function K2($,Z){let J=Math.max(0,Z-$),X=Math.floor(J/60000);if(X<1)return"just now";if(X===1)return"1m ago";if(X<60)return`${X}m ago`;let G=Math.floor(X/60),Y=X%60;if(Y===0)return`${G}h ago`;return`${G}h ${Y}m ago`}function eK($,Z){let J=Date.parse($);if(!Number.isFinite(J))return $;let X=J-Z;if(X<=0)return"now";let G=Math.max(1,Math.ceil(X/60000));if(G<60)return`in ${G}m`;let Y=Math.floor(G/60),z=G%60;if(z===0)return`in ${Y}h`;return`in ${Y}h ${z}m`}function N7($,Z){if(!$)return"";return`, resets ${eK($,Z)}`}function U7($,Z,J,X){if(!Z)return` - ${q7[$]}: unknown`;let G=[` - ${q7[$]}: ${z2(Z.remainingPercent)} remaining`,` (${z2(Z.usedPercent)} used`,`${N7(Z.resetsAt,J)}, checked ${K2(Z.checkedAt,J)})`].join("");return X===$?`${G} •`:G}function L7($){try{return new Intl.NumberFormat("en-US",{style:"currency",currency:$.currency,minimumFractionDigits:$.exponent,maximumFractionDigits:$.exponent}).format($.amountMinor/10**$.exponent)}catch{return`${$.amountMinor} ${$.currency}`}}function $W($,Z){return[` - ${$.title}: ${z2($.remainingPercent)} remaining`,` (${z2($.usedPercent)} used`,`${N7($.resetsAt,Z)}, checked ${K2($.checkedAt,Z)})`].join("")}function ZW($){return $.label?.trim()||$.id}function JW($){return $.lastQuotaRefreshError?.message??$.lastRefreshError?.message}function aU($,Z=new Map){if(!$?.accounts.length)return[];return $.accounts.filter(A).map((J)=>{let X=Z.get(J.id)??JW(J);return{name:ZW(J),role:"fallback",enabled:J.enabled!==!1,quota:J.quota,...$$(J.profile)&&{tierLabel:$$(J.profile)},lastRefreshedAt:J.lastRefreshedAt,...X&&{error:X}}})}function tU($){let Z=$.now??Date.now(),J=["## Claude Quotas",""];if($.refreshedAt)J.push(`Refreshed: ${K2($.refreshedAt,Z)}`,"");if(!$.accounts.length)return J.push("No Claude OAuth accounts found yet."),J.join(`
54
- `);for(let X of $.accounts){let G=X.role==="main"?"main":"fallback",Y=X.enabled===!1?" disabled":"";if(J.push(`### ${X.name} (${G}${Y})`),X.tierLabel)J.push(` - Tier: ${X.tierLabel}`);if(X.lastRefreshedAt)J.push(` - Last token refresh: ${K2(X.lastRefreshedAt,Z)}`);if(X.error)J.push(` - Error: ${X.error}`);J.push(U7("five_hour",X.quota?.five_hour,Z,X.quota?.bindingWindow)),J.push(U7("seven_day",X.quota?.seven_day,Z,X.quota?.bindingWindow));for(let K of X.quota?.scoped??[]){let W=$W(K,Z);J.push(X.quota?.bindingWindow===K.id?`${W} •`:W)}let z=X.quota?.extraUsage;if(z){let K=L7(z.used),W=L7(z.limit);J.push(` - credits ${K}/${W}${z.exhausted?" · exhausted":""}`)}if(X.quota?.fallbackAdvised===!0)J.push(" - → fallback advised");J.push("")}return J.join(`
55
- `).trimEnd()}import{Buffer as P7}from"node:buffer";import{createHash as XW,randomBytes as GW}from"node:crypto";class u$ extends Error{failure;constructor($){super("Relay request authorization failed");this.failure=$}}async function p$($,Z){if(!Z)return;try{let J=await Z();return $.upstream={...$.upstream,headers:A7(J.headers)},J}catch(J){throw new u$(J)}}class G3 extends Error{}class Y3 extends Error{code="ECONNRESET";syscall="websocket";closeCode;closeReason;wasClean;constructor($,Z){super($);this.name="RelayWebSocketConnectionResetError",this.closeCode=Z?.code,this.closeReason=Z?.reason,this.wasClean=Z?.wasClean}}var r0=new Map,f1=new Map,x7=new Set,YW=7200000,zW=1800000,KW=128,WW=32,O7=0;function X3(){return O7+=1,`req_${Date.now().toString(36)}_${O7.toString(36)}`}function W2($){if(x7.has($))return;x7.add($),l($)}function JL($){let Z=$?.relay;if(!Z)return W2("disabled: no relay config found"),null;if(Z.enabled!==!0)return W2("disabled: relay.enabled is not true"),null;if(!Z.url?.trim()||!Z.token?.trim())return W2("disabled: missing relay url or token"),null;let J=Z.transport==="http"?"http":"websocket";return W2(`configured transport=${J} protocol=${J==="websocket"?2:1} url=${Z.url.trim()} fallbackToDirect=${Z.fallbackToDirect!==!1}`),{enabled:!0,url:Z.url.trim(),token:Z.token.trim(),fallbackToDirect:Z.fallbackToDirect!==!1,transport:J}}function XL(){return GW(32).toString("base64url")}function VW($){return`sha256:${XW("sha256").update($).digest("hex")}`}function D7($,Z){let J=0,X=Math.min($.length,Z.length);while(J<X&&$.charCodeAt(J)===Z.charCodeAt(J))J++;let G=$.length,Y=Z.length;while(G>J&&Y>J&&$.charCodeAt(G-1)===Z.charCodeAt(Y-1))G--,Y--;return{start:J,deleteCount:G-J,insert:Z.slice(J,Y)}}function QW($){return $.deleteCount===0&&$.insert.length===0}function M7($){let Z=$.match(/\bcch=([0-9a-f]{5});/),J=Z?.[1];if(!J||Z.index==null)return null;let X=Z.index+4;return{start:X,end:X+J.length,token:J}}function jW($,Z,J,X){return`${$.slice(0,Z)}${X}${$.slice(J)}`}function F7($,Z){let J=M7($),X=M7(Z);if(J&&X&&J.start===X.start&&J.end-J.start===X.end-X.start&&J.token!==X.token){let G={start:J.start,deleteCount:J.end-J.start,insert:X.token},Y=jW($,J.start,J.end,X.token),z=D7(Y,Z);return QW(z)?G:[G,z]}return D7($,Z)}function HW($,Z){if(typeof Z!=="string")return!1;try{let J=$ instanceof Request?new URL($.url):new URL($.toString());return J.pathname==="/v1/messages"||J.pathname==="/messages"}catch{return!1}}function A7($){let Z={};for(let[J,X]of $.entries()){if(J==="x-session-affinity"||J==="x-opencode-session")continue;Z[J]=X}return Z}async function _7($,Z,J){let X=i(),G=JSON.stringify(Z);return z$("http_payload_stringify",{session:c(Z.affinity),ms:O0(i()-X),relayBytes:G.length,mode:Z.mode}),fetch($.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":$.token},body:G,signal:J??void 0})}function c($){return $.length>12?`${$.slice(0,12)}…`:$}function i(){return performance.now()}function O0($){return Math.round($*10)/10}function BW(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function z$($,Z){if(!BW())return;l(`[perf] relay ${$} ${JSON.stringify(Z)}`)}function qW($){let{input:Z,init:J,headers:X,bodyText:G,affinity:Y,previous:z,nextHash:K}=$,W=Z instanceof Request?Z.url:Z.toString(),Q={protocol:1,type:"request",affinity:Y,upstream:{url:W,method:J?.method||(Z instanceof Request?Z.method:"POST"),headers:A7(X)},next_hash:K};return z?{...Q,mode:"patch",base_hash:z.hash,revision:z.revision+1,patch:F7(z.body,G)}:{...Q,mode:"full_sync",revision:1,body:G}}function z3($,Z){return{protocol:$.protocol,type:"request",affinity:$.affinity,upstream:$.upstream,next_hash:$.next_hash,mode:"full_sync",revision:1,body:Z}}function w7($,Z,J,X){let G=Date.now();r0.delete($),r0.set($,{body:Z,hash:J,revision:X,updatedAt:G}),K3(G)}async function C7($){let{config:Z,payload:J,bodyText:X,fallback:G,signal:Y,authorizeAttempt:z}=$,K=J,W=z?await p$(K,z):void 0,Q=await _7(Z,K,Y);if(Q.status===409&&K.mode==="patch")l(`state mismatch from relay session=${c(K.affinity)}; retrying full_sync`),await Q.body?.cancel().catch(()=>{}),K=z3(K,X),W=z?await p$(K,z):void 0,Q=await _7(Z,K,Y);if(/^req_[A-Za-z0-9_-]+$/.test(Q.headers.get("request-id")??""))try{W?.onUpstreamStatus?.(Q.status)}catch{}if(!Q.ok&&Q.status>=500&&Z.fallbackToDirect)return l(`relay returned ${Q.status}; falling back direct session=${c(K.affinity)}`),await Q.body?.cancel().catch(()=>{}),{response:await G(),payload:K,transport:"http",protocol:K.protocol,usedRelay:!1};return{response:Q,payload:K,transport:"http",protocol:K.protocol,usedRelay:!0}}function UW($,Z){let J=new URL($);return J.protocol=J.protocol==="http:"?"ws:":"wss:",J.pathname="/ws",J.searchParams.set("token",Z),J.toString()}function LW($){return new Uint8Array(P7.from($,"base64"))}function NW($){if($ instanceof Uint8Array)return $;if($ instanceof ArrayBuffer)return new Uint8Array($);if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);return new Uint8Array(P7.from(String($)))}function xW($){return JSON.parse($)}function R7($){let Z=$,J=[`code=${Z.code??"unknown"}`,`wasClean=${Z.wasClean??"unknown"}`];if(Z.reason)J.push(`reason=${JSON.stringify(Z.reason)}`);return J.join(" ")}function OW($){let Z=$.message||"relay websocket error";return $.status?`relay websocket error ${$.status}: ${Z}`:Z}class T7{config;affinity;timers;socket;connecting;queue=Promise.resolve();pending;serverState;lastUsedAt=Date.now();constructor($,Z,J){this.config=$,this.affinity=Z,this.timers=J}touch($=Date.now()){this.lastUsedAt=$}canEvict($=Date.now()){return!this.pending&&!this.connecting&&$-this.lastUsedAt>zW}dispose(){this.socket?.close(),this.socket=void 0,this.serverState=void 0,this.connecting=void 0}send($,Z,J=!1,X,G){this.touch();let Y=i(),z=this.queue.catch(()=>{}).then(()=>this.startQueued($,Z,Y,J,X,G)),K=z.then(async({response:W,getPayload:Q})=>({response:await W,payload:Q(),transport:"websocket",protocol:2,usedRelay:!0}));return this.queue=z.then(({done:W})=>W.catch(()=>{}),()=>{}),K}async startQueued($,Z,J,X,G,Y){let z=i();await this.ensureConnected();let K=i(),W=r0.get(this.affinity),Q=this.serverState?.hash,V={...$,protocol:2,id:X3()};if(V.mode==="patch"&&(!Q||Q!==V.base_hash))V.mode="full_sync",V.revision=(this.serverState?.revision??0)+1,delete V.base_hash,delete V.patch,V.body=Z;if(V.mode==="patch"&&W)V.patch=F7(W.body,Z);l(`perf websocket send_start session=${c(this.affinity)} request=${V.id} mode=${V.mode} queueMs=${O0(K-J)} connectMs=${O0(K-z)} bodyBytes=${Z.length} relayBytes=${JSON.stringify(V).length}`);let j=Y?await p$(V,Y):void 0,B=V,q=this.sendPayload(V,Z,X,G,Y,j);q.done.catch(()=>{});let H=q.done,U=q.response.catch(async(O)=>{if(!(O instanceof G3)||V.mode!=="patch")throw O;let L=z3(V,Z);L.protocol=2,L.id=X3(),L.revision=(this.serverState?.revision??0)+1;let M=Y?await p$(L,Y):void 0;B=L;let F=this.sendPayload(L,Z,X,G,Y,M);return F.done.catch(()=>{}),H=F.done,F.response}),x=U.then(()=>H,()=>H.catch(()=>{}));return{response:U,done:x,getPayload:()=>B}}async ensureConnected(){if(this.socket?.readyState===WebSocket.OPEN&&this.serverState!==void 0)return;if(this.connecting)return await this.connecting;this.connecting=new Promise(($,Z)=>{let J=UW(this.config.url,this.config.token),X=new URL(J);X.searchParams.set("affinity",this.affinity);let G=new WebSocket(X.toString());this.socket=G,this.serverState=void 0;let Y=this.timers.setTimeout(()=>{G.close(),Z(Error("relay websocket ready timed out"))},15000);G.addEventListener("message",(z)=>{try{if(typeof z.data!=="string"){this.handleBinaryChunk(z.data);return}let K=xW(z.data);if(K.type==="ready"){this.timers.clearTimeout(Y),this.serverState=K.state,$();return}this.handleMessage(K)}catch(K){this.timers.clearTimeout(Y),Z(K),this.failPending(K),G.close()}}),G.addEventListener("error",()=>{this.timers.clearTimeout(Y);let z=new Y3("relay websocket error");Z(z),this.failPending(z)}),G.addEventListener("close",(z)=>{if(this.timers.clearTimeout(Y),this.socket===G)this.socket=void 0,this.serverState=void 0,this.connecting=void 0;if(this.pending){if(this.pending.retryingBeforeResponse)return;let K=this.pending.responseStartedAt!=null,W=K?"closed after response_start before stream bytes":"closed before response";if(this.retryPendingBeforeResponse(this.pending,W,z))return;let Q=K?new Y3("relay websocket closed during response stream",z):Error("relay websocket closed before response");l(`websocket ${K?"closed during response stream":"closed before response without retry"} session=${c(this.affinity)} request=${this.pending.payload.id} chunks=${this.pending.streamChunkCount} bytes=${this.pending.streamByteCount} ${R7(z)}`),this.failPending(Q)}})}).finally(()=>{this.connecting=void 0}),await this.connecting}sendPayload($,Z,J,X,G,Y){let z=this.socket;if(!z||z.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");let K=i(),W,Q,V=new Promise((B,q)=>{W=B,Q=q});return{response:new Promise((B,q)=>{let H={payload:$,bodyText:Z,resolve:B,reject:q,streamDone:!1,accepted:!1,responseStarted:!1,resolveDone:W,rejectDone:Q,sentAt:K,optimisticResponse:J,streamChunkCount:0,streamByteCount:0,retryAttempts:0,retryingBeforeResponse:!1,onResponseHeaders:X,authorizeAttempt:G,authorization:Y,stagedResponseHeaders:void 0,responseHeadersDelivered:!1};if(this.pending=H,this.resetPendingTimeout(H),z.send(JSON.stringify($)),J)this.resolvePendingResponse(H,200,"OK",{"content-type":"text/event-stream","x-cortexkit-relay-optimistic":"true"})}),done:V}}resetPendingTimeout($){this.timers.clearTimeout($.timeout),$.timeout=this.timers.setTimeout(()=>{if(this.pending!==$)return;if(this.retryPendingBeforeResponse($,"response timed out"))return;this.failPending(Error("relay websocket response timed out")),this.socket?.close()},45000)}retryPendingBeforeResponse($,Z,J){if($.responseStartedAt!=null&&$.streamByteCount>0)return!1;if($.streamDone)return!1;if($.retryAttempts>=1)return!1;$.retryAttempts+=1,$.retryingBeforeResponse=!0,this.timers.clearTimeout($.timeout);let X=$.retryAttempts,G=$.payload.id;return l(`websocket ${Z}; reconnecting and retrying full_sync session=${c(this.affinity)} request=${G} retry=${X} chunks=${$.streamChunkCount} bytes=${$.streamByteCount}${J?` ${R7(J)}`:""}`),this.socket?.close(),this.socket=void 0,this.serverState=void 0,this.connecting=void 0,(async()=>{try{if(await this.ensureConnected(),this.pending!==$)return;let Y=z3($.payload,$.bodyText);Y.protocol=2,Y.id=X3(),Y.revision=(this.serverState?.revision??0)+1;let z=$.authorizeAttempt?await p$(Y,$.authorizeAttempt):void 0;if(this.pending!==$||$.streamDone)return;$.authorization=z,$.payload=Y,$.accepted=!1,$.acceptedAt=void 0,$.responseStartedAt=void 0,$.stagedResponseHeaders=void 0,$.responseHeadersDelivered=!1,$.sentAt=i(),$.retryingBeforeResponse=!1;let K=this.socket;if(!K||K.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");this.resetPendingTimeout($),l(`perf websocket retry_send session=${c(this.affinity)} request=${Y.id} previous=${G} mode=full_sync retry=${X} bodyBytes=${$.bodyText.length} relayBytes=${JSON.stringify(Y).length}`),K.send(JSON.stringify(Y))}catch(Y){if($.retryingBeforeResponse=!1,this.pending===$)this.failPending(Y instanceof u$?Y.failure:Y)}})(),!0}enqueueStreamChunk($,Z){this.deliverResponseHeaders($),$.streamChunkCount+=1,$.streamByteCount+=Z.byteLength,$.streamController?.enqueue(Z)}deliverResponseHeaders($){if($.responseHeadersDelivered||$.stagedResponseHeaders==null)return;$.responseHeadersDelivered=!0;try{$.onResponseHeaders?.($.stagedResponseHeaders)}catch{}}handleBinaryChunk($){let Z=this.pending;if(!Z?.responseStarted)return;this.enqueueStreamChunk(Z,NW($))}resolvePendingResponse($,Z,J,X){if($.responseStarted)return;$.responseStarted=!0;let G=new ReadableStream({start:(Y)=>{$.streamController=Y},cancel:()=>{this.socket?.close()}});$.resolve(new Response(G,{status:Z,statusText:J,headers:X}))}handleMessage($){if($.type==="keepalive"){if(this.pending)this.resetPendingTimeout(this.pending);return}let Z=this.pending;if(!Z)return;if("id"in $&&$.id&&$.id!==Z.payload.id)return;if($.type==="accepted"){let J=i();Z.accepted=!0,Z.acceptedAt=J,l(`perf websocket accepted session=${c(this.affinity)} request=${Z.payload.id} sentMs=${O0(J-Z.sentAt)} mode=${Z.payload.mode}`),this.serverState={hash:$.hash,revision:$.revision},w7(this.affinity,Z.bodyText,$.hash,$.revision),this.resetPendingTimeout(Z);return}if($.type==="response_start"){if(Z.responseStartedAt!=null)return;let J=i();Z.responseStartedAt=J;try{Z.authorization?.onUpstreamStatus?.($.status)}catch{}if(l(`perf websocket response_start session=${c(this.affinity)} request=${Z.payload.id} sentMs=${O0(J-Z.sentAt)} upstreamMs=${Z.acceptedAt==null?"unknown":O0(J-Z.acceptedAt)} status=${$.status}`),this.timers.clearTimeout(Z.timeout),$.headers)Z.stagedResponseHeaders=new Headers($.headers);if(this.resolvePendingResponse(Z,$.status,$.statusText,$.headers),Z.optimisticResponse&&$.status>=400)this.deliverResponseHeaders(Z),Z.streamController?.enqueue(new TextEncoder().encode(`event: error
56
- data: ${JSON.stringify({type:"error",error:{type:"relay_upstream_error",message:`Relay upstream returned HTTP ${$.status}`}})}
57
-
58
- `)),this.finishPending();return}if($.type==="chunk"){this.enqueueStreamChunk(Z,LW($.base64));return}if($.type==="done"){this.finishPending($);return}if($.type==="error"){if(Z.optimisticResponse&&Z.responseStartedAt!=null){l(`websocket relay error during optimistic response session=${c(this.affinity)} request=${Z.payload.id} status=${$.status} message=${$.message||"unknown"} chunks=${Z.streamChunkCount} bytes=${Z.streamByteCount}`),this.deliverResponseHeaders(Z),Z.streamController?.enqueue(new TextEncoder().encode(`event: error
59
- data: ${JSON.stringify({type:"error",error:{type:"relay_error",message:$.message||"relay error"}})}
60
-
61
- `)),this.finishPending(),this.socket?.close();return}if($.status===409&&this.retryPendingBeforeResponse(Z,$.message||"state mismatch"))return;let J=$.status===409?new G3($.message||"state mismatch"):Error(OW($));this.failPending(J)}}finishPending($){let Z=this.pending;if(!Z)return;let J=i(),X=$&&"frames"in $?` upstreamChunks=${$.upstreamChunks??"unknown"} upstreamBytes=${$.upstreamBytes??"unknown"} frames=${$.frames} frameBytes=${$.frameBytes??"unknown"}`:"";if(l(`perf websocket done session=${c(this.affinity)} request=${Z.payload.id} sentMs=${O0(J-Z.sentAt)} streamMs=${Z.responseStartedAt==null?"unknown":O0(J-Z.responseStartedAt)} chunks=${Z.streamChunkCount} bytes=${Z.streamByteCount}${X}`),this.timers.clearTimeout(Z.timeout),!Z.streamDone)this.deliverResponseHeaders(Z),Z.streamDone=!0,Z.streamController?.close();Z.resolveDone(),this.pending=void 0}failPending($){let Z=this.pending;if(!Z)return;if(this.timers.clearTimeout(Z.timeout),this.pending=void 0,Z.responseStarted)Z.streamController?.error($);else Z.reject($);Z.rejectDone($)}}function K3($=Date.now()){for(let[Z,J]of r0)if($-J.updatedAt>YW)r0.delete(Z);while(r0.size>KW){let Z=r0.keys().next().value;if(Z===void 0)break;r0.delete(Z)}for(let[Z,J]of f1)if(J.canEvict($))J.dispose(),f1.delete(Z);while(f1.size>WW){let Z=!1;for(let[J,X]of f1){if(!X.canEvict($))continue;X.dispose(),f1.delete(J),Z=!0;break}if(!Z)break}}function DW($,Z,J){K3();let X=f1.get(Z);if(X)return X.touch(),X;let G=new T7($,Z,J);return f1.set(Z,G),K3(),G}async function GL($){let{config:Z,input:J,init:X,headers:G,body:Y,fallback:z,affinity:K,optimisticResponse:W,authorizeAttempt:Q,onResponseHeaders:V,dumpTag:j,onDumpCreated:B,setTimeoutImpl:q=globalThis.setTimeout,clearTimeoutImpl:H=globalThis.clearTimeout}=$;if(!Z||!HW(J,Y))return z();let U=K||G.get("x-session-affinity")||G.get("x-opencode-session");if(!U)return l("skipping relay: missing x-session-affinity header"),z();let x=Y,O=i(),L=VW(x);z$("hash_body",{session:c(U),ms:O0(i()-O),bodyBytes:x.length});let M=r0.get(U),F=i(),N=qW({input:J,init:X,headers:G,bodyText:x,affinity:U,previous:M,nextHash:L});z$("create_payload",{session:c(U),ms:O0(i()-F),mode:N.mode,bodyBytes:x.length,previousBytes:M?.body.length});try{let D,w=i();if(Z.transport==="websocket")try{D=await DW(Z,U,{setTimeout:q,clearTimeout:H}).send(N,x,W===!0,V,Q)}catch(u){if(u instanceof u$)throw u;l(`websocket relay failed session=${c(U)}; trying http relay: ${u instanceof Error?u.message:String(u)}`),D=await C7({config:Z,payload:N,bodyText:x,fallback:z,signal:X?.signal,authorizeAttempt:Q})}else D=await C7({config:Z,payload:N,bodyText:x,fallback:z,signal:X?.signal,authorizeAttempt:Q});if(z$("send",{session:c(U),ms:O0(i()-w),transport:D.transport,protocol:D.protocol,mode:D.payload.mode,status:D.response.status,usedRelay:D.usedRelay}),!D.usedRelay)return D.response;if(D.transport==="http")try{V?.(D.response.headers)}catch{}if(D.transport==="http")w7(U,x,D.payload.next_hash,D.payload.revision);let E=i(),v=JSON.stringify(D.payload).length;z$("payload_stringify",{session:c(U),ms:O0(i()-E),relayBytes:v}),l(`used relay transport=${D.transport} protocol=${D.protocol} mode=${D.payload.mode} status=${D.response.status} session=${c(U)} bodyBytes=${x.length} relayBytes=${v}`);let R0=i(),o=await O8({affinity:U,transport:D.transport,protocol:D.protocol,mode:D.payload.mode,status:D.response.status,bodyText:x,previousBodyText:M?.body,payload:D.payload,relayBytes:v,tag:j});try{if(o)B?.(o)}catch{}return z$("dump",{session:c(U),ms:O0(i()-R0),enabled:!0}),D.response}catch(D){if(D instanceof u$)throw D.failure;if(!Z.fallbackToDirect)throw l(`relay failed session=${c(U)} and fallbackToDirect=false: ${D instanceof Error?D.message:String(D)}`),D;return l(`relay failed; falling back direct session=${c(U)}: ${D instanceof Error?D.message:String(D)}`),z()}}var YL=`
62
- async function hashBody(body) {
63
- const bytes = new TextEncoder().encode(body)
64
- const digest = await crypto.subtle.digest('SHA-256', bytes)
65
- const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')
66
- return 'sha256:' + hex
67
- }
68
-
69
- function applyPatch(base, patch) {
70
- return base.slice(0, patch.start) + patch.insert + base.slice(patch.start + patch.deleteCount)
71
- }
72
-
73
- function applyPatchSet(base, patch) {
74
- if (!Array.isArray(patch)) return applyPatch(base, patch)
75
- if (patch.length === 0) return base
76
-
77
- let result = ''
78
- let cursor = 0
79
- for (const item of patch) {
80
- if (item.start < cursor) return { error: 'overlapping patch', status: 400 }
81
- result += base.slice(cursor, item.start)
82
- result += item.insert
83
- cursor = item.start + item.deleteCount
84
- }
85
- return result + base.slice(cursor)
86
- }
87
-
88
- async function readState(env, affinity) {
89
- const raw = await env.RELAY_STATE.get('session:' + affinity)
90
- return raw ? JSON.parse(raw) : null
91
- }
92
-
93
- async function writeState(env, affinity, state) {
94
- await env.RELAY_STATE.put('session:' + affinity, JSON.stringify(state), { expirationTtl: 86400 })
95
- }
96
-
97
- async function resolveBody(env, payload) {
98
- if (payload.mode === 'full_sync') return payload.body
99
- if (payload.mode === 'patch') {
100
- const state = await readState(env, payload.affinity)
101
- if (!state || state.hash !== payload.base_hash) {
102
- return { error: 'state mismatch', status: 409 }
103
- }
104
- return applyPatchSet(state.body, payload.patch)
105
- }
106
- return { error: 'unknown mode', status: 400 }
107
- }
108
-
109
- async function prepareUpstream(env, payload) {
110
- if ((payload.protocol !== 1 && payload.protocol !== 2) || payload.type !== 'request' || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {
111
- return { error: 'invalid payload', status: 400 }
112
- }
113
-
114
- const body = await resolveBody(env, payload)
115
- if (body && typeof body === 'object' && 'error' in body) return body
116
-
117
- if (typeof body !== 'string' || (await hashBody(body)) !== payload.next_hash) {
118
- return { error: 'hash mismatch', status: 409 }
119
- }
120
-
121
- const stateWrite = writeState(env, payload.affinity, { body, hash: payload.next_hash, revision: payload.revision }).catch(() => {})
122
- console.log(JSON.stringify({
123
- relay: 'opencode-anthropic-auth',
124
- transport: 'relay',
125
- mode: payload.mode,
126
- revision: payload.revision,
127
- affinity: String(payload.affinity).slice(0, 12),
128
- bodyBytes: body.length,
129
- }))
130
-
131
- return { body, stateWrite }
132
- }
133
-
134
- function resolveBodyFromState(state, payload) {
135
- if (payload.mode === 'full_sync') return payload.body
136
- if (payload.mode === 'patch') {
137
- if (!state || state.hash !== payload.base_hash) {
138
- return { error: 'state mismatch', status: 409 }
139
- }
140
- return applyPatchSet(state.body, payload.patch)
141
- }
142
- return { error: 'unknown mode', status: 400 }
143
- }
144
-
145
- function deferWorkerTask(task) {
146
- return new Promise((resolve) => setTimeout(resolve, 0)).then(task)
147
- }
148
-
149
- const WEBSOCKET_STREAM_FLUSH_BYTES = 1024
150
- const WEBSOCKET_STREAM_FLUSH_MS = 20
151
-
152
- function createWebSocketStreamCoalescer(socket, options = {}) {
153
- const flushBytes = options.flushBytes || WEBSOCKET_STREAM_FLUSH_BYTES
154
- const flushMs = options.flushMs ?? WEBSOCKET_STREAM_FLUSH_MS
155
- let chunks = []
156
- let byteLength = 0
157
- let flushTimer = null
158
- const stats = {
159
- upstreamChunks: 0,
160
- upstreamBytes: 0,
161
- frames: 0,
162
- frameBytes: 0,
163
- }
164
-
165
- const clearFlushTimer = () => {
166
- if (flushTimer === null) return
167
- clearTimeout(flushTimer)
168
- flushTimer = null
169
- }
170
-
171
- const mergeChunks = () => {
172
- if (chunks.length === 1) return chunks[0]
173
- const frame = new Uint8Array(byteLength)
174
- let offset = 0
175
- for (const chunk of chunks) {
176
- frame.set(chunk, offset)
177
- offset += chunk.byteLength
178
- }
179
- return frame
180
- }
181
-
182
- const flush = () => {
183
- clearFlushTimer()
184
- if (byteLength === 0) return
185
- const frame = mergeChunks()
186
- chunks = []
187
- byteLength = 0
188
- socket.send(frame)
189
- stats.frames += 1
190
- stats.frameBytes += frame.byteLength
191
- }
192
-
193
- const scheduleFlush = () => {
194
- if (flushTimer !== null) return
195
- flushTimer = setTimeout(flush, flushMs)
196
- }
197
-
198
- return {
199
- push(value) {
200
- const chunk = value instanceof Uint8Array ? value : new Uint8Array(value)
201
- if (chunk.byteLength === 0) return
202
- stats.upstreamChunks += 1
203
- stats.upstreamBytes += chunk.byteLength
204
- chunks.push(chunk)
205
- byteLength += chunk.byteLength
206
- if (byteLength >= flushBytes) flush()
207
- else scheduleFlush()
208
- },
209
- flush,
210
- stats() {
211
- return { ...stats, pendingBytes: byteLength }
212
- },
213
- }
214
- }
215
-
216
- function checkpointWebSocketState(env, payload, body, nextState) {
217
- return deferWorkerTask(async () => {
218
- try {
219
- if ((await hashBody(body)) !== payload.next_hash) {
220
- throw new Error('hash mismatch')
221
- }
222
- await writeState(env, payload.affinity, nextState)
223
- } catch (error) {
224
- console.log(JSON.stringify({
225
- relay: 'opencode-anthropic-auth',
226
- transport: 'websocket',
227
- event: 'checkpoint_write_failed',
228
- affinity: String(payload.affinity).slice(0, 12),
229
- message: error instanceof Error ? error.message : String(error),
230
- }))
231
- }
232
- })
233
- }
234
-
235
- async function prepareWebSocketUpstream(env, state, payload) {
236
- if (payload.protocol !== 2 || payload.type !== 'request' || !payload.id || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {
237
- return { error: 'invalid payload', status: 400 }
238
- }
239
-
240
- const body = resolveBodyFromState(state, payload)
241
- if (body && typeof body === 'object' && 'error' in body) return body
242
- if (typeof body !== 'string') return { error: 'invalid body', status: 400 }
243
- if ((await hashBody(body)) !== payload.next_hash) {
244
- return { error: 'hash mismatch', status: 409 }
245
- }
246
-
247
- const nextState = { body, hash: payload.next_hash, revision: payload.revision }
248
- const checkpoint = checkpointWebSocketState(env, payload, body, nextState)
249
- const logAccepted = () => console.log(JSON.stringify({
250
- relay: 'opencode-anthropic-auth',
251
- transport: 'websocket',
252
- mode: payload.mode,
253
- revision: payload.revision,
254
- affinity: String(payload.affinity).slice(0, 12),
255
- bodyBytes: body.length,
256
- }))
257
-
258
- return { body, state: nextState, checkpoint, logAccepted }
259
- }
260
-
261
- function headersToObject(headers) {
262
- const result = {}
263
- for (const [key, value] of headers.entries()) result[key] = value
264
- return result
265
- }
266
-
267
- async function handleRelayPayload(env, payload) {
268
- const prepared = await prepareUpstream(env, payload)
269
- if (prepared.error) return prepared
270
- const upstream = await fetch(payload.upstream.url, {
271
- method: payload.upstream.method || 'POST',
272
- headers: payload.upstream.headers,
273
- body: prepared.body,
274
- })
275
- return { upstream, stateWrite: prepared.stateWrite }
276
- }
277
-
278
- async function handleWebSocket(socket, env, ctx, payload, getState, setState) {
279
- const heartbeat = setInterval(() => {
280
- try {
281
- socket.send(JSON.stringify({ protocol: 2, type: 'keepalive' }))
282
- } catch {
283
- clearInterval(heartbeat)
284
- }
285
- }, 15000)
286
- let streamCoalescer = null
287
- try {
288
- const result = await prepareWebSocketUpstream(env, getState(), payload)
289
- if (result.error) {
290
- socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: result.status, message: result.error }))
291
- return
292
- }
293
-
294
- setState(result.state)
295
- socket.send(JSON.stringify({ protocol: 2, type: 'accepted', id: payload.id, hash: result.state.hash, revision: result.state.revision }))
296
- ctx?.waitUntil?.(deferWorkerTask(result.logAccepted))
297
-
298
- const upstreamPromise = fetch(payload.upstream.url, {
299
- method: payload.upstream.method || 'POST',
300
- headers: payload.upstream.headers,
301
- body: result.body,
302
- })
303
- ctx?.waitUntil?.(result.checkpoint)
304
- const upstream = await upstreamPromise
305
- socket.send(JSON.stringify({
306
- protocol: 2,
307
- type: 'response_start',
308
- id: payload.id,
309
- status: upstream.status,
310
- statusText: upstream.statusText,
311
- headers: headersToObject(upstream.headers),
312
- }))
313
-
314
- const reader = upstream.body?.getReader()
315
- if (reader) {
316
- streamCoalescer = createWebSocketStreamCoalescer(socket)
317
- while (true) {
318
- const { done, value } = await reader.read()
319
- if (done) break
320
- streamCoalescer.push(value)
321
- }
322
- streamCoalescer.flush()
323
- }
324
- const stats = streamCoalescer?.stats?.() || {}
325
- socket.send(JSON.stringify({ protocol: 2, type: 'done', id: payload.id, ...stats }))
326
- } catch (error) {
327
- try {
328
- streamCoalescer?.flush?.()
329
- } catch {}
330
- socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: 500, message: error instanceof Error ? error.message : String(error) }))
331
- } finally {
332
- clearInterval(heartbeat)
333
- }
334
- }
335
-
336
- export default {
337
- async fetch(request, env, ctx) {
338
- if (request.headers.get('Upgrade') === 'websocket') {
339
- const url = new URL(request.url)
340
- const token = url.searchParams.get('token')
341
- const affinity = url.searchParams.get('affinity')
342
- if (token !== env.RELAY_TOKEN) return new Response('unauthorized', { status: 401 })
343
- if (!affinity) return new Response('missing affinity', { status: 400 })
344
- const pair = new WebSocketPair()
345
- const client = pair[0]
346
- const server = pair[1]
347
- server.binaryType = 'arraybuffer'
348
- let state = null
349
- let ready = false
350
- server.accept()
351
- const loadState = readState(env, affinity).then((loadedState) => {
352
- state = loadedState
353
- ready = true
354
- server.send(JSON.stringify({
355
- protocol: 2,
356
- type: 'ready',
357
- state: state ? { hash: state.hash, revision: state.revision } : null,
358
- }))
359
- }).catch((error) => {
360
- server.send(JSON.stringify({ protocol: 2, type: 'error', status: 500, message: error instanceof Error ? error.message : String(error) }))
361
- server.close(1011, 'state load failed')
362
- })
363
- ctx?.waitUntil?.(loadState)
364
- if (!ctx?.waitUntil) void loadState
365
- let busy = false
366
- server.addEventListener('message', (event) => {
367
- if (!ready) {
368
- server.send(JSON.stringify({ protocol: 2, type: 'error', status: 425, message: 'relay state is not ready' }))
369
- return
370
- }
371
- if (busy) {
372
- server.send(JSON.stringify({ protocol: 2, type: 'error', status: 429, message: 'request already in flight' }))
373
- return
374
- }
375
- let payload
376
- try {
377
- payload = JSON.parse(event.data)
378
- } catch {
379
- server.send(JSON.stringify({ protocol: 2, type: 'error', status: 400, message: 'invalid JSON payload' }))
380
- return
381
- }
382
- payload.affinity = affinity
383
- busy = true
384
- const run = handleWebSocket(server, env, ctx, payload, () => state, (nextState) => { state = nextState }).finally(() => { busy = false })
385
- ctx?.waitUntil?.(run)
386
- if (!ctx?.waitUntil) void run
387
- })
388
- return new Response(null, { status: 101, webSocket: client })
389
- }
390
-
391
- if (request.method === 'GET') {
392
- return Response.json({ status: 'ok', transports: ['http', 'websocket'] })
393
- }
394
- if (request.method !== 'POST') return new Response('method not allowed', { status: 405 })
395
- if (request.headers.get('x-relay-token') !== env.RELAY_TOKEN) {
396
- return new Response('unauthorized', { status: 401 })
397
- }
398
-
399
- try {
400
- const payload = await request.json()
401
- const result = await handleRelayPayload(env, payload)
402
- if (result.error) return Response.json({ error: result.error }, { status: result.status })
403
-
404
- if (result.stateWrite) ctx.waitUntil(result.stateWrite)
405
-
406
- const upstream = result.upstream
407
- return new Response(upstream.body, {
408
- status: upstream.status,
409
- statusText: upstream.statusText,
410
- headers: upstream.headers,
411
- })
412
- } catch (error) {
413
- return Response.json(
414
- { error: error instanceof Error ? error.message : 'internal relay error' },
415
- { status: 502 },
416
- )
417
- }
418
- },
419
- }
420
- `;var WL="claude-routing",W3=["main-first","fallback-first","sticky-balanced"],V3="main-first",S7="Usage: `/claude-routing`, `/claude-routing main-first`, `/claude-routing fallback-first`, `/claude-routing sticky-balanced`, or `/claude-routing reset`.";function MW($){return typeof $==="string"&&W3.includes($)?$:V3}function VL($){return MW($?.routing?.mode)}async function QL($,Z=I()){let J=await f(Z)??a();return J.routing={...J.routing??{},mode:$},await L0(J,Z),J}function _W($){let Z=$.trim().toLowerCase().split(/\s+/).filter(Boolean);if(Z.length===0)return{type:"status"};if(Z.length===1&&Z[0]==="reset")return{type:"reset"};if(Z.length===1&&W3.includes(Z[0]))return{type:"mode",mode:Z[0]};if(Z.length===2&&Z[0]==="mode"&&W3.includes(Z[1]))return{type:"mode",mode:Z[1]};return{type:"usage"}}function CW($){if($==="fallback-first")return"Try usable fallback accounts before the main account. If no fallback succeeds, try the main account.";if($==="sticky-balanced")return"Assign each session to a quota-weighted OAuth account, keep it sticky across transient failures, and migrate only for confirmed long-lived exhaustion or permanent account failure.";return"Try the main account first. Use fallback accounts only when quota policy or fallback errors require it."}function V2($){let Z=$?.mode??V3;return["## Claude Routing Status","",`- Mode: \`${Z}\``,`- Behavior: ${CW(Z)}`,"",S7].join(`
421
- `)}function jL($){let Z=_W($.argumentsText),J=$.mode??V3;if(Z.type==="status")return V2({mode:J});if(Z.type==="mode")return["## Claude Routing Updated","",`Mode updated to \`${Z.mode}\`.`,"",...V2({mode:Z.mode}).split(`
422
- `).slice(2)].join(`
423
- `);if(Z.type==="reset")return["## Claude Routing Assignment Reset","","The current session will be assigned again on its next request.","",...V2({mode:J}).split(`
424
- `).slice(2)].join(`
425
- `);return["## Claude Routing Usage","",S7,"",...V2({mode:J}).split(`
426
- `).slice(2)].join(`
427
- `)}var BL="claude-start";function RW($){if($.trim().split(/\s+/).filter(Boolean).length===0)return{type:"fire"};return{type:"usage"}}function qL($){let Z=RW($.argumentsText);if(Z.type==="fire")return{action:Z,text:["## Claude Lane Start Queued","","- Queued an explicit lane-start request.","- This is a billed request: the one-token limit does not remove prompt-cache read or write charges."].join(`
428
- `)};return{action:Z,text:["## Claude Lane Start Usage","","Usage: `/claude-start`.","","## Claude Lane Start Status"].join(`
429
- `)}}import{createHash as g7,randomUUID as PW}from"node:crypto";import{mkdir as FW,readFile as AW,rename as wW,rm as TW,stat as SW,writeFile as IW}from"node:fs/promises";import{basename as fW,dirname as m7,join as bW}from"node:path";var kW="main",EW=900000,I7=604800000,vW=3600000,hW=1e4,yW=5000,gW=10,f7=4096,mW=0.000001;function ML($){let Z=$.modelId,J=Z?$.routeQuotas.map((B)=>_0(B,Z)).find(Boolean)?.modelName:void 0,X;if(c1($.mainRefreshError))X=J?`Main Claude OAuth account requires re-login, and no fallback OAuth account is currently routable for ${J}.`:"Main Claude OAuth account requires re-login, and no fallback OAuth account is currently routable.";else if($.fallbackReauthLabels?.length)X=`No OAuth account is currently routable${J?` for ${J}`:""}. Fallback Claude OAuth accounts require re-login: ${$.fallbackReauthLabels.join(", ")}.`;if(X)return new Response(JSON.stringify({type:"error",error:{type:"authentication_error",message:X}}),{status:401,headers:{"content-type":"application/json"}});let G=Boolean(Z&&$.routeQuotas.length>0&&$.routeQuotas.every((B)=>!N6(B,Z))),[Y,...z]=$.routeQuotas,K=p5(Y,z.map((B)=>({quota:B})),$.now??Date.now(),G?Z:void 0),W=Math.floor(K/60),Q=K%60,j=`${G&&J?`${J} weekly limit reached, no routable OAuth accounts.`:"No OAuth account currently satisfies sticky-balanced quota policy."} Retry in ${W}m ${Q}s.`;return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:j}}),{status:429,headers:{"content-type":"application/json","retry-after":String(K)}})}function Q3($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function l$($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function pW($){if(!Q3($))return;if(typeof $.accountId!=="string"||!["fable","opus","general"].includes(String($.family)))return;let Z=l$($.assignedAt),J=l$($.lastSeenAt),X=l$($.initialInputBytes),G=l$($.quotaCheckedAt);if(Z===void 0||J===void 0||X===void 0||G===void 0)return;if(Object.hasOwn($,"affinityModelId")&&typeof $.affinityModelId!=="string")return;return{accountId:$.accountId,family:$.family,affinityModelId:typeof $.affinityModelId==="string"?$.affinityModelId:void 0,assignedAt:Z,lastSeenAt:J,initialInputBytes:Math.max(0,X),quotaCheckedAt:G}}function uW($){if(!Q3($)||$.version!==1||!Q3($.assignments))return;let Z={};for(let[J,X]of Object.entries($.assignments)){let G=pW(X);if(G)Z[J]=G}return{version:1,updatedAt:l$($.updatedAt)??0,assignments:Z}}function b7($){return{version:1,updatedAt:$,assignments:{}}}function k7($){return g7("sha256").update($).digest("hex")}function p7($,Z,J=Date.now(),X){let G=g0(Z);if(!["five_hour","seven_day"].every((K)=>{let W=$?.[K];return Boolean(W&&J-W.checkedAt<G)}))return!1;let z=_0($,X);return!z||J-z.checkedAt<G}function E7($){return Math.max($.checkedAt??0,$.five_hour?.checkedAt??0,$.seven_day?.checkedAt??0,...($.scoped??[]).map((Z)=>Z.checkedAt??0))}function K$($){if(!$)return;if("kind"in $)return $.kind==="known"?$.quota:void 0;return $}function v7($,Z,J){let X=M6($),G=J==="five_hour"?X.five_hour:J==="seven_day"?X.seven_day:0;if(!C6($))return G;let Y=r2($,Z===kW?void 0:Z);return Math.max(G,Y[J])}function h7($,Z,J,X){let G=Math.max(0,$-Z);if(G<=0)return 0;if(!J)return G;let Y=Date.parse(J);if(!Number.isFinite(Y)||Y<=X)return G;let z=Math.max((Y-X)/3600000,0.016666666666666666);return G/z}function _L($){if(c9($))return"fable";return typeof $==="string"&&$.toLowerCase().includes("opus")?"opus":"general"}function y7($){let Z=$.now??Date.now(),{candidate:J,storage:X}=$,G=K$(J.quota);if(!G)return 0;if(!p7(G,X,Z,$.modelId))return 0;let Y=[];for(let z of["five_hour","seven_day"]){let K=G[z];if(!K||!Number.isFinite(K.remainingPercent))return 0;Y.push(h7(K.remainingPercent,v7(X,J.accountId,z),K.resetsAt,Z))}if($.family==="fable"){let z=_0(G,$.modelId);if(z&&Number.isFinite(z.remainingPercent))Y.push(h7(z.remainingPercent,v7(X,J.accountId,"scoped"),z.resetsAt,Z))}return Math.min(...Y)}function lW($,Z,J=Date.now()){let X=K$($.quota),G=_0(X,"claude-fable-5");return Boolean(G&&p7(X,Z,J,"claude-fable-5")&&Number.isFinite(G.remainingPercent)&&G.remainingPercent<=0)}function CL($){let Z=$.now??Date.now(),J=K$($.quota);if(!J)return{action:"retain",reason:"unknown"};let X=_0(J,$.modelId);if(X&&Number.isFinite(X.remainingPercent)&&X.remainingPercent<=0)return{action:"migrate",reason:"model-scoped"};let G=J.seven_day;if(G&&Number.isFinite(G.remainingPercent)&&G.remainingPercent<=0)return{action:"migrate",reason:"seven-day"};let Y=J.five_hour;if(Y&&Number.isFinite(Y.remainingPercent)&&Y.remainingPercent<=0){let z=Y.resetsAt?Date.parse(Y.resetsAt):NaN;if(Number.isFinite(z)&&z>Z&&z-Z<=EW)return{action:"hold",reason:"five-hour-short-reset",retryAfterSeconds:Math.max(1,Math.ceil((z-Z)/1000))};return{action:"migrate",reason:"five-hour"}}return{action:"retain",reason:"not-exhausted"}}function RL($){let Z=fW($),J=Z.endsWith(".json")?Z.slice(0,-5):Z;return bW(m7($),`${J}-routing-state.json`)}function PL($,Z){let J=g7("sha256").update($).digest().readUInt32BE(0);return Math.max(1,Math.ceil(Z))+J%21}class dW{options;loaded=!1;state;stateMtimeNs;touchChain=Promise.resolve();constructor($){this.options=$,this.state=b7(this.now())}now(){return this.options.now?.()??Date.now()}async readState(){try{let $=await AW(this.options.path,"utf8"),Z=uW(JSON.parse($));if(!Z)throw Error(`Invalid sticky routing state at ${this.options.path}`);return Z}catch($){if($.code==="ENOENT")return b7(this.now());throw $}}async readStateMtimeNs(){try{return(await SW(this.options.path,{bigint:!0})).mtimeNs}catch($){if($.code==="ENOENT")return 0n;throw $}}async refreshStateIfChanged(){for(let $=0;$<3;$++){let Z=await this.readStateMtimeNs();if(this.loaded&&Z===this.stateMtimeNs)return;let J=await this.readState(),X=await this.readStateMtimeNs();if(Z!==X)continue;this.state=J,this.stateMtimeNs=X,this.loaded=!0;return}this.state=await this.readState(),this.stateMtimeNs=await this.readStateMtimeNs(),this.loaded=!0}async acquireLock(){await FW(m7(this.options.path),{recursive:!0,mode:448});let $=this.now()+yW;while(!0){let Z=await Q0({name:"write",path:this.options.path,ttlMs:hW,renew:!0});if(Z)return Z;if(this.now()>=$)throw Error("Timed out acquiring sticky routing state lock");await new Promise((J)=>setTimeout(J,gW))}}assignmentIsActive($){return $.lastSeenAt>=this.now()-(this.options.assignmentTtlMs??I7)}prune($){let Z=this.now()-(this.options.assignmentTtlMs??I7);for(let[X,G]of Object.entries($.assignments))if(G.lastSeenAt<Z)delete $.assignments[X];let J=Object.entries($.assignments);if(J.length<=f7)return;J.sort((X,G)=>G[1].lastSeenAt-X[1].lastSeenAt).slice(f7).forEach(([X])=>{delete $.assignments[X]})}async writeState($){this.prune($),$.updatedAt=this.now();let Z=`${this.options.path}.${PW()}.tmp`;try{await IW(Z,`${JSON.stringify($)}
430
- `,{mode:384}),await wW(Z,this.options.path)}finally{await TW(Z,{force:!0}).catch(()=>{})}this.state=$,this.stateMtimeNs=await this.readStateMtimeNs(),this.loaded=!0}scheduleTouch($){this.touchChain=this.touchChain.catch(()=>{}).then(async()=>{let Z=await this.acquireLock();try{let J=await this.readState(),X=J.assignments[$];if(!X)return;X.lastSeenAt=this.now(),await this.writeState(J)}finally{await Z.release()}}).catch(()=>{})}selectCandidate($){let Z=[...$.candidates];if($.family==="opus"){let G=Z.filter((Y)=>lW(Y,$.storage,this.now()));if(G.length>0)Z=G}let J=Z.flatMap((G)=>{let Y=y7({candidate:G,family:$.family,modelId:$.modelId,storage:$.storage,now:this.now()});return Y>0?[{candidate:G,weight:Y}]:[]});if(J.length===0&&Z.every((G)=>!K$(G.quota)))return[...Z].sort((G,Y)=>G.order-Y.order||G.accountId.localeCompare(Y.accountId))[0];let X=new Map;for(let G of Object.values($.state.assignments)){let Y=J.find((K)=>K.candidate.accountId===G.accountId)?.candidate;if(!Y)continue;let z=K$(Y.quota);if(z&&G.quotaCheckedAt!==E7(z))continue;X.set(G.accountId,(X.get(G.accountId)??0)+G.initialInputBytes)}return J.map(({candidate:G,weight:Y})=>({candidate:G,score:((X.get(G.accountId)??0)+$.inputBytes)/Math.max(Y,mW)})).sort((G,Y)=>G.score-Y.score||G.candidate.order-Y.candidate.order||G.candidate.accountId.localeCompare(Y.candidate.accountId))[0]?.candidate}async resolve($){if(!$.sessionId)return null;await this.refreshStateIfChanged();let Z=k7($.sessionId),J=$.affinityModelId??$.modelId,X=(z)=>J!==void 0?z.affinityModelId===J:z.family===$.family,G=this.state.assignments[Z];if(G&&this.assignmentIsActive(G)&&X(G)&&$.retainAccountIds.has(G.accountId)&&!$.excludeAccountIds?.has(G.accountId)){if(this.now()-G.lastSeenAt>=vW)G.lastSeenAt=this.now(),this.scheduleTouch(Z);return{accountId:G.accountId,assignment:{...G},created:!1,migrated:!1}}let Y=await this.acquireLock();try{let z=await this.readState();this.prune(z);let K=z.assignments[Z];if(K&&X(K)&&$.retainAccountIds.has(K.accountId)&&!$.excludeAccountIds?.has(K.accountId))return K.lastSeenAt=this.now(),await this.writeState(z),{accountId:K.accountId,assignment:{...K},created:!1,migrated:!1};let W=Boolean(K&&!X(K));if(W)delete z.assignments[Z];let Q=$.candidates.filter((U)=>!$.excludeAccountIds?.has(U.accountId)),j=(!W&&$.preferredAccountId?Q.find((U)=>U.accountId===$.preferredAccountId&&y7({candidate:U,family:$.family,modelId:$.modelId,storage:$.storage,now:this.now()})>0):void 0)??this.selectCandidate({...$,candidates:Q,state:z});if(!j){if(K)delete z.assignments[Z],await this.writeState(z);return null}let B=this.now(),q=K$(j.quota),H={accountId:j.accountId,family:$.family,affinityModelId:J,assignedAt:B,lastSeenAt:B,initialInputBytes:Math.max(1,$.inputBytes),quotaCheckedAt:q?E7(q):0};return z.assignments[Z]=H,await this.writeState(z),{accountId:j.accountId,assignment:{...H},created:!K,migrated:Boolean(K&&K.accountId!==j.accountId)}}finally{await Y.release()}}async clear($){if(!$)return;let Z=k7($),J=await this.acquireLock();try{let X=await this.readState();if(!(Z in X.assignments))return;delete X.assignments[Z],await this.writeState(X)}finally{await J.release()}}}var wL="thinking-binding-controls-2026-08-01";function d$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function iW($){if(!d$($))return!1;if($.type==="thinking")return typeof $.signature==="string"&&$.signature.length>0;if($.type==="redacted_thinking")return typeof $.data==="string"&&$.data.length>0;return!1}function TL($){let Z=$?.thinkingBinding?.prefixMismatchBehavior;return Z==="error"||Z==="drop_block"?Z:"account-default"}function cW($){if(!Array.isArray($.messages))return!1;return $.messages.some((Z)=>{if(!d$(Z)||Z.role!=="assistant")return!1;return Array.isArray(Z.content)&&Z.content.some(iW)})}function SL($,Z="account-default"){if(Z==="account-default")return!1;if(!J2($.model))return!1;if(!cW($))return!1;if(!d$($.thinking)||$.thinking.type==="disabled")return!1;return $.thinking.block_binding={prefix_mismatch_behavior:Z},!0}function IL($){if(!d$($.thinking))return!1;if(!d$($.thinking.block_binding))return!1;let Z=$.thinking.block_binding.prefix_mismatch_behavior;return Z==="error"||Z==="drop_block"}export{q0 as C,k1 as D,EZ as E,vZ as F,W6 as G,hZ as H,iV as I,cV as J,V6 as K,x$ as L,sV as M,A2 as N,nV as O,O$ as P,gZ as Q,y1 as R,q1 as S,z6 as T,p3 as U,aV as V,tV as W,w2 as X,oV as Y,N$ as Z,dZ as _,iZ as $,cZ as aa,sZ as ba,nZ as ca,rV as da,eV as ea,D$ as fa,S2 as ga,I2 as ha,U1 as ia,rZ as ja,s3 as ka,$Q as la,ZQ as ma,$J as na,f2 as oa,ZJ as pa,u3 as qa,JJ as ra,l3 as sa,L$ as ta,a3 as ua,JQ as va,e3 as wa,h2 as xa,k2 as ya,X5 as za,QQ as Aa,jQ as Ba,A0 as Ca,D5 as Da,qJ as Ea,UJ as Fa,d1 as Ga,p2 as Ha,A as Ia,u2 as Ja,M5 as Ka,FQ as La,PJ as Ma,I as Na,P$ as Oa,a as Pa,M1 as Qa,fJ as Ra,f as Sa,T0 as Ta,n0 as Ua,A5 as Va,n as Wa,w5 as Xa,AQ as Ya,wQ as Za,L0 as _a,i1 as $a,TQ as ab,tJ as bb,SQ as cb,IQ as db,Q0 as eb,fQ as fb,eJ as gb,bQ as hb,kQ as ib,EQ as jb,vQ as kb,hQ as lb,yQ as mb,gQ as nb,mQ as ob,pQ as pb,uQ as qb,lQ as rb,dQ as sb,iQ as tb,cQ as ub,sQ as vb,nQ as wb,M6 as xb,aQ as yb,tQ as zb,oQ as Ab,GX as Bb,c1 as Cb,g1 as Db,YX as Eb,rQ as Fb,o2 as Gb,_6 as Hb,O1 as Ib,eQ as Jb,g0 as Kb,$j as Lb,Zj as Mb,v5 as Nb,h5 as Ob,_0 as Pb,KX as Qb,N6 as Rb,g5 as Sb,Jj as Tb,N1 as Ub,C$ as Vb,C6 as Wb,r2 as Xb,m5 as Yb,p5 as Zb,Xj as _b,Gj as $b,Yj as ac,zj as bc,Kj as cc,Wj as dc,_1 as ec,s1 as fc,qX as gc,Vj as hc,Qj as ic,UX as jc,LX as kc,NX as lc,xX as mc,qj as nc,Uj as oc,Lj as pc,Nj as qc,xj as rc,Oj as sc,Dj as tc,CX as uc,F$ as vc,Mj as wc,TX as xc,SX as yc,Aj as zc,o5 as Ac,kX as Bc,EX as Cc,wj as Dc,vX as Ec,r5 as Fc,e5 as Gc,hX as Hc,Tj as Ic,yX as Jc,$8 as Kc,I0 as Lc,F6 as Mc,bj as Nc,kj as Oc,Ej as Pc,iX as Qc,vj as Rc,cX as Sc,tX as Tc,hj as Uc,K8 as Vc,yj as Wc,sj as Xc,nj as Yc,aj as Zc,tj as _c,I$ as $c,T$ as ad,RG as bd,FG as cd,w6 as dd,oj as ed,x8 as fd,O8 as gd,D8 as hd,XH as id,j4 as jd,M8 as kd,hG as ld,GH as md,yG as nd,_8 as od,gG as pd,mG as qd,pG as rd,uG as sd,cG as td,k6 as ud,E6 as vd,T8 as wd,sG as xd,nG as yd,P8 as zd,F8 as Ad,t1 as Bd,YH as Cd,aG as Dd,tG as Ed,XY as Fd,jH as Gd,zY as Hd,C0 as Id,Iz as Jd,iB as Kd,cB as Ld,_9 as Md,kz as Nd,F9 as Od,g4 as Pd,Ez as Qd,oB as Rd,rB as Sd,u4 as Td,iz as Ud,E9 as Vd,sz as Wd,v9 as Xd,Vq as Yd,Qq as Zd,$$ as _d,xq as $d,nz as ae,Cq as be,az as ce,h9 as de,tz as ee,oz as fe,Rq as ge,rz as he,ZK as ie,wq as je,Sq as ke,Iq as le,fq as me,bq as ne,JK as oe,$2 as pe,kq as qe,Z$ as re,XK as se,hq as te,gq as ue,GK as ve,YK as we,i4 as xe,mq as ye,uq as ze,lq as Ae,dq as Be,iq as Ce,c4 as De,J$ as Ee,s4 as Fe,i9 as Ge,zK as He,n4 as Ie,cq as Je,sq as Ke,nq as Le,aq as Me,KK as Ne,WK as Oe,p9 as Pe,tq as Qe,c9 as Re,VK as Se,J2 as Te,oq as Ue,u9 as Ve,rq as We,eq as Xe,l9 as Ye,$U as Ze,QK as _e,d9 as $e,ZU as af,JU as bf,XU as cf,GU as df,YU as ef,s9 as ff,zU as gf,KU as hf,QU as if,n9 as jf,jK as kf,jU as lf,UK as mf,BU as nf,CU as of,_K as pf,G7 as qf,CK as rf,RK as sf,PK as tf,FK as uf,o4 as vf,wK as wf,G2 as xf,RU as yf,bK as zf,e9 as Af,kK as Bf,PU as Cf,EK as Df,Y7 as Ef,vK as Ff,Z7 as Gf,yK as Hf,G$ as If,e4 as Jf,$3 as Kf,kU as Lf,tK as Mf,hU as Nf,yU as Of,m$ as Pf,j1 as Qf,nU as Rf,L7 as Sf,aU as Tf,tU as Uf,JL as Vf,XL as Wf,VW as Xf,D7 as Yf,GL as Zf,YL as _f,WL as $f,W3 as ag,V3 as bg,VL as cg,QL as dg,_W as eg,V2 as fg,jL as gg,BL as hg,RW as ig,qL as jg,kW as kg,EW as lg,I7 as mg,ML as ng,p7 as og,_L as pg,y7 as qg,lW as rg,CL as sg,RL as tg,PL as ug,dW as vg,wL as wg,TL as xg,cW as yg,SL as zg,IL as Ag};