@cortexkit/opencode-anthropic-auth 1.22.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 (91) hide show
  1. package/README.md +259 -198
  2. package/dist/billing-lineage.d.ts +51 -0
  3. package/dist/cli-failure.d.ts +69 -0
  4. package/dist/cli.d.ts +16 -10
  5. package/dist/cli.js +111 -6
  6. package/dist/custody-dimensions.d.ts +19 -0
  7. package/dist/custody-mode.d.ts +46 -0
  8. package/dist/effort-history.d.ts +11 -2
  9. package/dist/fable-fallback.d.ts +1 -1
  10. package/dist/index-1jkyhgyr.js +2 -0
  11. package/dist/{index-bx5hsgf8.js → index-2arfb1y3.js} +2 -2
  12. package/dist/{index-926t2bzc.js → index-4ya27n12.js} +1 -1
  13. package/dist/{index-cgez4m0h.js → index-aaajxwzd.js} +1 -1
  14. package/dist/index-ae3fq4n6.js +42 -0
  15. package/dist/index-fds0s2j4.js +2 -0
  16. package/dist/index-nngmvczq.js +450 -0
  17. package/dist/index-pn597b6f.js +2 -0
  18. package/dist/{index-7f57ewkp.js → index-rqync0pc.js} +1 -1
  19. package/dist/index.js +1 -33
  20. package/dist/native-command.d.ts +19 -0
  21. package/dist/prime-manager-registry.d.ts +5 -1
  22. package/dist/rpc/notifications.d.ts +4 -3
  23. package/dist/rpc/port-file.js +1 -1
  24. package/dist/rpc/protocol.d.ts +15 -4
  25. package/dist/rpc/protocol.js +1 -1
  26. package/dist/rpc/rpc-client.d.ts +3 -1
  27. package/dist/rpc/rpc-client.js +1 -1
  28. package/dist/rpc/rpc-dir.js +1 -1
  29. package/dist/rpc/rpc-server.d.ts +5 -1
  30. package/dist/rpc/server-registry.d.ts +10 -0
  31. package/dist/setup/activation.d.ts +7 -0
  32. package/dist/setup/claustrum.d.ts +26 -0
  33. package/dist/setup/command-runner.d.ts +2 -0
  34. package/dist/setup/command.d.ts +20 -0
  35. package/dist/setup/command.test.d.ts +1 -0
  36. package/dist/setup/detect.d.ts +5 -0
  37. package/dist/setup/jsonc.d.ts +9 -0
  38. package/dist/setup/native-activation.d.ts +29 -0
  39. package/dist/setup/native-enrollment.d.ts +26 -0
  40. package/dist/setup/native-enrollment.test.d.ts +1 -0
  41. package/dist/setup/native-local.d.ts +20 -0
  42. package/dist/setup/native-login.d.ts +3 -0
  43. package/dist/setup/native-paths.d.ts +15 -0
  44. package/dist/setup/native-paths.test.d.ts +1 -0
  45. package/dist/setup/opencode-config.d.ts +18 -0
  46. package/dist/setup/paths.d.ts +15 -0
  47. package/dist/setup/pi.d.ts +18 -0
  48. package/dist/setup/process-fence.d.ts +20 -0
  49. package/dist/setup/process-fence.test.d.ts +1 -0
  50. package/dist/setup/types.d.ts +37 -0
  51. package/dist/sidebar-state.d.ts +3 -1
  52. package/dist/sidebar-state.js +1 -1
  53. package/dist/transform.d.ts +5 -1
  54. package/dist/tui/command-dialogs.d.ts +32 -2
  55. package/dist/tui-preferences.js +2 -2
  56. package/dist/v2/activation.d.ts +7 -0
  57. package/dist/v2/adapter.d.ts +276 -0
  58. package/dist/v2/install.d.ts +13 -0
  59. package/dist/v2/lifecycle.d.ts +8 -0
  60. package/dist/v2/menu-contract.d.ts +8 -0
  61. package/dist/v2/menu.d.ts +10 -0
  62. package/dist/v2/models.d.ts +6 -0
  63. package/dist/v2/ownership.d.ts +11 -0
  64. package/dist/v2/prime.d.ts +12 -0
  65. package/dist/v2/rpc.d.ts +50 -0
  66. package/dist/v2/server.d.ts +8 -0
  67. package/dist/v2/server.js +4 -0
  68. package/dist/v2/setup.d.ts +58 -0
  69. package/dist/v2/source.d.ts +41 -0
  70. package/dist/v2/tui.d.ts +13 -0
  71. package/dist/v2/tui.js +2 -0
  72. package/dist/v2/wire.d.ts +36 -0
  73. package/package.json +26 -6
  74. package/src/rpc/notifications.ts +37 -26
  75. package/src/rpc/protocol.ts +24 -7
  76. package/src/rpc/rpc-client.ts +18 -1
  77. package/src/rpc/rpc-server.ts +38 -8
  78. package/src/rpc/server-registry.ts +61 -0
  79. package/src/sidebar-state.ts +26 -2
  80. package/src/tui/command-dialogs.tsx +537 -68
  81. package/src/tui/entry.mjs +44 -18
  82. package/src/tui-compiled/rpc/protocol.ts +24 -7
  83. package/src/tui-compiled/rpc/rpc-client.ts +18 -1
  84. package/src/tui-compiled/sidebar-state.ts +26 -2
  85. package/src/tui-compiled/tui/command-dialogs.tsx +488 -95
  86. package/src/tui-compiled/tui.tsx +25 -7
  87. package/src/tui.tsx +38 -9
  88. package/dist/index-8aga2zwv.js +0 -4
  89. package/dist/index-d3f8g6ve.js +0 -428
  90. package/dist/index-sh51yqxs.js +0 -2
  91. package/dist/logger-jrkranbz.js +0 -1
@@ -1,428 +0,0 @@
1
- import{gd as f4,kd as M,ld as H0,md as S}from"./index-8aga2zwv.js";import{ud as s8}from"./index-cgez4m0h.js";import{readFile as A8}from"node:fs/promises";import{userInfo as b8}from"node:os";import{debuglog as G8}from"node:util";import{createHmac as t3,randomBytes as r3,timingSafeEqual as e3}from"node:crypto";import o3 from"node:net";var t=2,R1=21,f1=5,x$=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 b6=C.Goodbye;function E6($){return $===C.Cancel||$===C.Ping||$===C.Pong||$===C.Goodbye}var y;(function($){$[$.Passive=0]="Passive",$[$.Interactive=1]="Interactive",$[$.Background=2]="Background"})(y||(y={}));var l;(function($){$[$.Normal=0]="Normal",$[$.Expedite=1]="Expedite",$[$.Sheddable=2]="Sheddable"})(l||(l={}));var c3=1,I6=6,R$=1,n3=8,k6=48,f$=4,v6=192;function i($,J,Z,z=l.Normal){let G=0;if($)G|=c3;if(G|=J<<R$,Z)G|=n3;return G|=z<<f$,G}function h6($){let J=new Uint8Array(21),Z=new DataView(J.buffer);return Z.setUint32(0,$.len,!0),J[4]=$.ver,J[5]=$.ty,J[6]=$.flags,Z.setUint16(7,$.channel,!0),Z.setUint32(9,$.epoch,!0),Z.setBigUint64(13,$.corr,!0),J}class f extends Error{code;constructor($,J){super($);this.code=J,this.name="DecodeError"}}function a3($){let J=$.len>>>0,Z=$.ver>>>0&255,z=$.ty>>>0&255,G=$.flags>>>0&255,X=$.channel>>>0&65535,Y=$.epoch>>>0;if(BigInt.asUintN(64,$.corr),Z!==2)throw new f(`unsupported envelope version ${Z}`,"unsupported_version");if(z>b6)throw new f(`unknown frame type byte ${z}`,"unknown_frame_type");let K=z;if((G&v6)!==0)throw new f(`reserved flag bits set in flags 0b${G.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((G&I6)>>R$===3)throw new f(`reserved priority bits set in flags 0b${G.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let V=(G&k6)>>f$;if(V===3)throw new f(`reserved admission class set in flags 0b${G.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(V===l.Sheddable&&K!==C.Push&&K!==C.StreamData)throw new f(`SHEDDABLE admission class is illegal on ${C[K]} in flags 0b${G.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");if(X===0&&Y!==0)throw new f(`control channel carried nonzero epoch ${Y}`,"nonzero_epoch_on_control_channel");if(E6(K)&&J!==0)throw new f(`pure-header frame ${C[K]} declared non-zero body length ${J}`,"pure_header_frame_with_body")}function w$($){if($.length<5)throw new f(`header shorter than frozen prefix: have ${$.length} bytes`,"too_short_for_prefix");let J=$[4];if(J!==2)throw new f(`unsupported envelope version ${J}`,"unsupported_version");if($.length<21)throw new f(`header too short for version: have ${$.length} bytes, need 21`,"too_short_for_header");let Z=new DataView($.buffer,$.byteOffset,$.byteLength),z=Z.getUint32(0,!0),G=$[5];if(G>b6)throw new f(`unknown frame type byte ${G}`,"unknown_frame_type");let X=G,Y=$[6];if((Y&v6)!==0)throw new f(`reserved flag bits set in flags 0b${Y.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((Y&I6)>>R$===3)throw new f(`reserved priority bits set in flags 0b${Y.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let K=(Y&k6)>>f$;if(K===3)throw new f(`reserved admission class set in flags 0b${Y.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(K===l.Sheddable&&X!==C.Push&&X!==C.StreamData)throw new f(`SHEDDABLE admission class is illegal on ${C[X]} in flags 0b${Y.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");let V=Z.getUint16(7,!0),W=Z.getUint32(9,!0);if(V===0&&W!==0)throw new f(`control channel carried nonzero epoch ${W}`,"nonzero_epoch_on_control_channel");if(E6(X)&&z!==0)throw new f(`pure-header frame ${C[X]} declared non-zero body length ${z}`,"pure_header_frame_with_body");return{len:z,ver:J,ty:X,flags:Y,channel:V,epoch:W,corr:Z.getBigUint64(13,!0)}}function u($,J,Z,z,G,X){return z0(2,$,J,Z,z,G,X)}function z0($,J,Z,z,G,X,Y){if(Y.length>67108864)throw new f(`frame body ${Y.length} exceeds max 67108864`,"frame_body_too_large");let K={len:Y.length,ver:$,ty:J,flags:Z,channel:z,epoch:G,corr:X};return a3(K),{header:K,body:Y}}function G0($){if($.header.len!==$.body.length)throw new f(`frame header length ${$.header.len} does not match body length ${$.body.length}`,"frame_length_mismatch");let J=h6($.header),Z=new Uint8Array(J.length+$.body.length);return Z.set(J,0),Z.set($.body,J.length),Z}class W0 extends Error{}class $0 extends Error{}class X0 extends Error{cause;constructor($,J){super($);this.cause=J}}class B0 extends Error{cause;constructor($,J){super($);this.cause=J}}function y6($){return Buffer.from($.buffer,$.byteOffset,$.byteLength)}var m6=Symbol("subc.socket.writeBorrowed"),g6=Symbol("subc.socket.writeTrackedBorrowed");function Y0($,J,Z){let z=$[m6];return z?z.call($,J,Z):$.write(J,Z)}function P$($,J,Z){let z=$[g6];return z?z.call($,J,Z):$.writeTracked(J,Z)}class q0{sock;chunks=[];buffered=0;waiter=null;closedErr=null;bufferedBytes(){return this.buffered}constructor($){this.sock=$,$.on("data",(Z)=>{this.chunks.push(Z),this.buffered+=Z.length,this.tryServe()});let J=(Z)=>{if(!this.closedErr)this.closedErr=Z;this.tryServe()};$.on("error",(Z)=>J(Z instanceof Error?Z:Error(String(Z)))),$.on("end",()=>J(new W0("subc closed the connection"))),$.on("close",()=>J(new W0("subc connection closed")))}localPort(){return this.sock.localPort??null}static connect($,J,Z){return new Promise((z,G)=>{let X=o3.connect({host:$,port:J});X.setNoDelay(!0);let Y=setTimeout(()=>{X.destroy(),G(new $0(`timed out connecting to ${$}:${J}`))},Math.max(0,Z-Date.now()));X.once("connect",()=>{clearTimeout(Y),z(new q0(X))}),X.once("error",(K)=>{clearTimeout(Y),G(K)})})}async readFrame($,J,Z){let z=await this.readExact(f1,$),G=z[4];if(G!==t)throw new f(`unsupported envelope version ${G}`,"unsupported_version");let X=await this.readExact(R1-f1,$),Y=new Uint8Array(R1);Y.set(z),Y.set(X,f1);let K=w$(Y);if(K.len>x$)throw new f(`frame body ${K.len} exceeds max ${x$}`,"frame_body_too_large");Z?.();let V=typeof J==="number"?J:Date.now()+J.afterHeaderMs,W=K.len===0?new Uint8Array(0):await this.readExact(K.len,V);return{header:K,body:W}}readExact($,J){if(this.waiter)return Promise.reject(Error("concurrent readExact is not supported"));if($===0)return Promise.resolve(new Uint8Array(0));return new Promise((Z,z)=>{let G=null;if(Number.isFinite(J)){let X=J-Date.now();if(X<=0){z(new $0(`timed out waiting for ${$} bytes`));return}G=setTimeout(()=>{this.waiter=null,z(new $0(`timed out waiting for ${$} bytes`))},X)}this.waiter={need:$,resolve:Z,reject:z,timer:G},this.tryServe()})}async write($,J){await this.writeBuffer(Buffer.from($),J)}writeTracked($,J){return this.writeTrackedBuffer(Buffer.from($),J)}async[m6]($,J){await this.writeBuffer(y6($),J)}[g6]($,J){return this.writeTrackedBuffer(y6($),J)}async writeBuffer($,J){try{await this.writeTrackedBuffer($,J).completed}catch(Z){if(Z instanceof X0||Z instanceof B0)throw Z.cause??Z;throw Z}}writeTrackedBuffer($,J){if(this.closedErr)return{queued:!1,completed:Promise.reject(new X0("subc socket was closed before bytes could be queued",this.closedErr))};let Z=!1,z=!1,G=null,X=new Promise((Y,K)=>{let V=(j)=>{if(z)return;if(z=!0,G)clearTimeout(G);j()},W=J-Date.now();if(W<=0){V(()=>K(new X0("timed out before bytes could be queued to subc",new $0("timed out writing to subc"))));return}G=setTimeout(()=>{let j=new $0("timed out writing to subc");V(()=>K(Z?new B0("timed out after bytes were handed to the subc socket",j):new X0("timed out before bytes could be queued to subc",j)))},W);try{this.sock.write($,(j)=>{V(()=>{if(j)K(new B0("subc socket reported a write error after bytes were handed to the socket",j instanceof Error?j:Error(String(j))));else Y()})}),Z=!0}catch(j){V(()=>K(new X0("subc socket write threw before bytes could be queued",j instanceof Error?j:Error(String(j)))))}});return{queued:Z,completed:X}}close(){this.sock.destroy()}tryServe(){let $=this.waiter;if(!$)return;if(this.buffered>=$.need){let J=this.take($.need);if(this.waiter=null,$.timer)clearTimeout($.timer);$.resolve(J);return}if(this.closedErr){if(this.waiter=null,$.timer)clearTimeout($.timer);$.reject(this.closedErr)}}take($){let J=Buffer.allocUnsafe($),Z=0;while(Z<$){let z=this.chunks[0],G=$-Z;if(z.length<=G)z.copy(J,Z),Z+=z.length,this.chunks.shift();else z.copy(J,Z,0,G),this.chunks[0]=z.subarray(G),Z+=G}return this.buffered-=$,J}}var u6=32;var w1=4096,s6="subc-server-v1",d6="subc-client-v1",$8="client";class s extends Error{}function S$($,J,Z,z,G){let X=t3("sha256",Buffer.from($));return X.update(Buffer.from(J,"utf8")),X.update(Buffer.from(Z)),X.update(Buffer.from(z)),X.update(Buffer.from(G)),new Uint8Array(X.digest())}function p6($,J){if($.length!==J.length)return!1;return e3(Buffer.from($),Buffer.from(J))}async function l6($,J,Z){let z=Buffer.from(JSON.stringify(J),"utf8");if(z.length>w1)throw new s(`auth message too large: ${z.length} > ${w1}`);let G=new Uint8Array(4);new DataView(G.buffer).setUint32(0,z.length,!0),await Y0($,G,Z),await Y0($,z,Z)}async function J8($,J){let Z=await $.readExact(4,J),z=new DataView(Z.buffer,Z.byteOffset,4).getUint32(0,!0);if(z>w1)throw new s(`auth message too large: ${z} > ${w1}`);let G=z===0?new Uint8Array(0):await $.readExact(z,J);try{return JSON.parse(Buffer.from(G).toString("utf8"))}catch(X){throw new s(`auth message JSON decode failed: ${String(X)}`)}}function F$($,J){if(!Array.isArray($))throw new s(`auth field '${J}' must be a byte array`);for(let Z of $)if(typeof Z!=="number"||!Number.isInteger(Z)||Z<0||Z>255)throw new s(`auth field '${J}' has invalid byte ${String(Z)}`);return Uint8Array.from($)}async function z1($,J,Z){let z=new Uint8Array(r3(u6));await l6($,{client_nonce:Array.from(z),role:$8},Z);let G=await J8($,Z),X=F$(G.server_nonce,"server_nonce"),Y=F$(G.daemon_id,"daemon_id"),K=F$(G.server_proof,"server_proof"),V=S$(J.key,s6,z,X,Y);if(!p6(V,K))throw new s("server proof mismatch — wrong key or impostor daemon");if(!p6(Y,J.daemonId))throw new s("daemon id mismatch — connection file points at a different daemon");let W=S$(J.key,d6,z,X,Y);await l6($,{client_auth:Array.from(W)},Z)}import{promises as T$}from"node:fs";var i6=1,c6=32,n6=16;class m extends Error{}function a6($,J){if(!Array.isArray($))throw new m(`connection file field '${J}' must be a JSON array of bytes`);for(let Z of $)if(typeof Z!=="number"||!Number.isInteger(Z)||Z<0||Z>255)throw new m(`connection file field '${J}' has invalid byte ${String(Z)}`);return Uint8Array.from($)}function Z8($){if($.schema!==i6)throw new m(`unsupported connection file schema ${$.schema}; expected ${i6}`);if($.endpoints.length===0)throw new m("connection file must include at least one endpoint");if($.key.length<c6)throw new m(`connection file key is too short: ${$.key.length} bytes, need at least ${c6}`);if($.daemonId.length!==n6)throw new m(`connection file daemon_id must be ${n6} bytes, got ${$.daemonId.length}`)}async function z8($){if(process.platform==="win32")return;let Z=(await T$.stat($)).mode&511;if((Z&63)!==0)throw new m(`connection file ${$} has insecure permissions 0o${Z.toString(8)}; expected owner-only 0600`)}async function G1($){await z8($);let J=await T$.readFile($,"utf8"),Z;try{Z=JSON.parse(J)}catch(K){throw new m(`connection file JSON read failed for ${$}: ${String(K)}`)}let z=Z.wire_version;if(z!==void 0&&z!==t)throw new m(`connection file wire_version ${String(z)} but this client speaks ${t}; the client library must be upgraded`);let G=Z.endpoints;if(!Array.isArray(G))throw new m("connection file 'endpoints' must be an array");let X=G.map((K)=>{let V=K;if(typeof V.host!=="string"||typeof V.port!=="number")throw new m("connection file endpoint must be { host: string, port: number }");return{host:V.host,port:V.port}}),Y={schema:Z.schema,endpoints:X,key:a6(Z.key,"key"),daemonId:a6(Z.daemon_id,"daemon_id"),pid:Z.pid,daemonVer:Z.daemon_ver??""};return Z8(Y),Y}var o6=new WeakMap;class P1{channel;epoch;constructor($,J,Z){if(!Number.isInteger($)||$<=0||$>65535)throw RangeError(`route channel must be an integer in 1..65535, got ${$}`);if(!Number.isInteger(J)||J<=0||J>4294967295)throw RangeError(`route epoch must be an integer in 1..4294967295, got ${J}`);this.channel=$,this.epoch=J,o6.set(this,Z),Object.freeze(this)}static create($,J,Z){return new P1($,J,Z)}}function F1($,J,Z){return P1.create($,J,Z)}class j0 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 v0(){return Object.freeze({})}function X1($,J){return o6.get($)===J}function S1($,J){return $===J}var X8=G8("subc-client"),Y8=1e4,Y1=30000,K8=50,V8=2000,t6="request_deadline",A$="deadline_exceeded_no_drop_observed",W8=30000,j8=30000,r6=new Uint8Array(0),H8="management_surface",$2="SUBC_MODULE_ID",J2="SUBC_LAUNCH_NONCE",I1={baseMs:100,capMs:2000,maxAttempts:6};class g extends Error{kind;code;cause;constructor($,J,Z,z){super(J);this.kind=$,this.code=Z,this.cause=z,this.name="SubcCallError"}}class w extends Error{code;constructor($,J){super($);this.code=J}}class D0{sock;currentConn;opts;nextCorr=1n;pending=new Map;lateResponses=new Map;routes=new Map;liveRoutes=new Map;connectionToken=v0();ingressEpochDropCount=0;closedErr=null;closeStarted=!1;reconnecting=null;generation=1;readerActive=!1;constructor($,J,Z){this.sock=$,this.currentConn=J,this.opts=Z,this.readLoop($,this.generation)}get conn(){return this.currentConn}static async connect($){let J=U8($),Z=await D0.openConnection(J);return new D0(Z.sock,Z.conn,J)}async catalogList($){let J=this.encode($===void 0?{op:"catalog.list"}:{op:"catalog.list",module_id:$}),Z=await this.controlRpc(J);return this.parseJson(Z).modules??[]}async routeOpen($,J,Z={}){let z=b$(Z),G=Z.consumerCapabilities,X=this.encode({op:"route.open",target:$,identity:J,...z?{consumer_identity:z}:{},...G!==void 0?{consumer_capabilities:G}:{}}),Y=null,K=(W)=>{if(W.header.ty!==C.Response)return!0;let j=this.parseJson(W);if(typeof j.route_channel!=="number"||typeof j.route_epoch!=="number")throw new w(`route.open returned no route handle: ${JSON.stringify(j)}`);return Y=this.installRoute(j.route_channel,j.route_epoch),!0},V=(W)=>{if(W.header.ty!==C.Response)return;try{let j=this.parseJson(W);if(typeof j.route_channel!=="number"||typeof j.route_epoch!=="number")return;let H=this.installRoute(j.route_channel,j.route_epoch);this.failHandle(H,new w("late route.open was closed","route_closed")),this.liveRoutes.delete(H.channel),this.sendRouteGoodbye(H,!0)}catch{this.closeConnectionAfterCleanupFailure()}};if(await this.controlRpc(X,K,V),!Y)throw new w("route.open response was not installed");return Y}async request($,J,Z={}){this.assertLiveHandle($);let z=J instanceof Uint8Array?J:this.encode(J),G=Z.priority??y.Interactive,X=Z.admissionClass??l.Normal,Y=await this.send($,z,G,X,Z.timeoutMs,Z.onProgress);return this.parseJson(Y)}async call($,J,Z,z={}){let G=Z===void 0?{method:J}:{method:J,params:Z},X=!1;for(;;){let Y=await this.cachedRouteHandle($,z);try{return await this.managedRequest(Y,G,z)}catch(K){if(!(K instanceof g))throw this.terminalCallError("managed call failed",K);let V=K.code==="unknown_channel"||K.code==="stale_route_epoch";if(V&&!X&&!this.closeStarted){X=!0,this.evictRouteHandle(Y);continue}if(V&&X)this.evictRouteHandle(Y);if(K.kind==="not_sent"){try{await this.reconnectAfterDrop(K)}catch(W){throw this.notSentRecoveryError("managed call was not sent",W)}continue}if(K.kind==="outcome_unknown"&&K.code!==A$)this.scheduleReconnectAfterDrop(K);else if(K.kind==="outcome_unknown"&&K.code===A$)this.probeLivenessAfterDeadline();throw K}}}subscribe($,J,Z,z={}){this.assertLiveHandle($);let G=J instanceof Uint8Array?J:this.encode(J),X=z.priority??y.Interactive,Y=z.admissionClass??l.Normal,K=this.allocateCorr(),V=A1($,K),W=null,j=null,H=new Promise((B,O)=>{if(this.closedErr){O(this.closedErr);return}j=B,W={handle:$,resolve:()=>B(),reject:O,onProgress:Z,timer:null,subscription:!0},this.pending.set(V,W);let q=u(C.Request,i(!1,X,!1,Y),$.channel,$.epoch,K,G);Y0(this.sock,G0(q),Date.now()+Y1).catch((D)=>{let L=this.pending.get(V);if(L)this.rejectPending(V,L,D instanceof Error?D:new w(String(D)))})}),Q=!1;return{unsubscribe:()=>{if(Q)return;if(Q=!0,W&&j)this.settle(V,W,j);if(this.isLiveHandle($))this.cancel($,K,X)},closed:H}}cancel($,J,Z=y.Interactive){this.assertLiveHandle($);let z=u(C.Cancel,i(!1,Z,!1),$.channel,$.epoch,J,r6);Y0(this.sock,G0(z),Date.now()+Y1).catch(()=>{return})}async routePoll($,J){this.assertLiveHandle($);let Z=this.encode({op:"route.poll",route_channel:$.channel,route_epoch:$.epoch,kind:J}),z=await this.controlRpc(Z,(G)=>{if(G.header.ty!==C.Response)return!0;let X=this.parseJson(G);return X.route_channel===$.channel&&X.route_epoch===$.epoch});return this.parseJson(z)}async closeRoute($,J={}){this.assertLiveHandle($);for(let[Z,z]of this.routes)if(z.handle&&S1(z.handle,$))z.closed=!0,z.handle=null,this.routes.delete(Z);if(J.drain)await this.drainUnaryOnHandle($);if(this.failHandle($,new w("route closed by closeRoute","route_closed")),this.liveRoutes.get($.channel)===$)this.liveRoutes.delete($.channel);this.sendRouteGoodbye($)}async closeManagedRoute($,J,Z={}){let z=e6($,J,b$(Z)),G=this.routes.get(z);if(!G)return;G.closed=!0,this.routes.delete(z);let X=G.handle;if(G.handle=null,X)await this.closeRoute(X,Z)}async closeRouteChannel($,J={}){await this.closeRoute($,J)}close(){this.closeStarted=!0,this.fail(new w("client closed")),this.sock.close()}drainUnaryOnHandle($){let J=[];for(let Z of this.pending.values())if(Z.handle===$&&!Z.subscription)J.push(new Promise((z)=>{let G=Z.onSettle;Z.onSettle=()=>{G?.(),z()}}));return Promise.all(J).then(()=>{return})}sendRouteGoodbye($,J=!1){if(this.assertLiveConnection($),this.closedErr){if(J)this.closeConnectionAfterCleanupFailure();return}let Z=u(C.Goodbye,i(!1,y.Interactive,!1),$.channel,$.epoch,0n,r6),z=P$(this.sock,G0(Z),Date.now()+Y1);if(!z.queued&&J)this.closeConnectionAfterCleanupFailure();z.completed.catch(()=>{if(J&&!z.queued)this.closeConnectionAfterCleanupFailure()})}static async openConnection($){let J=await G1($.connectionFile),Z=Date.now()+($.handshakeTimeoutMs??Y8),z=J.endpoints[0],G=await q0.connect(z.host,z.port,Z);try{await z1(G,J,Z)}catch(X){throw G.close(),X}return{sock:G,conn:J}}async controlRpc($,J,Z){return this.send(null,$,y.Interactive,l.Normal,void 0,void 0,J,Z)}send($,J,Z,z,G,X,Y,K){if($)this.assertLiveHandle($);if(this.closedErr)return Promise.reject(this.closedErr);let V;try{V=this.allocateCorr()}catch(U){return Promise.reject(U)}let W=A1($,V),j=$?.channel??0,H=$?.epoch??0,Q=u(C.Request,i(!1,Z,!1,z),j,H,V,J);return new Promise((U,B)=>{let O=G??Y1,q={handle:$,resolve:U,reject:B,onProgress:X,timer:null,acceptFrame:Y,onLateResponse:K};q.timer=setTimeout(()=>this.arbitrateTimeout(W,q,j,V,O),O),this.pending.set(W,q),Y0(this.sock,G0(Q),Date.now()+O).catch((D)=>{let L=this.pending.get(W);if(L)this.rejectPending(W,L,D instanceof Error?D:new w(String(D)))})})}arbitrateTimeout($,J,Z,z,G){let X=()=>{if(J.onLateResponse)this.lateResponses.set($,J.onLateResponse);this.rejectPending($,J,new w(this.timeoutMessage(Z,z,G),t6))},Y=Date.now()+this.opts.timeoutArbitrationGraceMs,K=()=>{if(this.pending.get($)!==J)return;if((this.readerActive||this.sock.bufferedBytes()>0)&&Date.now()<Y){setImmediate(K);return}X()};setImmediate(K)}async managedRequest($,J,Z){let z=J instanceof Uint8Array?J:this.encode(J),G=Z.priority??y.Interactive,X=Z.admissionClass??l.Normal;try{let Y=await this.sendManaged($,z,G,X,Z.timeoutMs,Z.onProgress);return this.parseJson(Y)}catch(Y){if(Y instanceof g)throw Y;throw this.terminalCallError("managed call failed",Y)}}sendManaged($,J,Z,z,G,X){try{this.assertLiveHandle($)}catch(H){return Promise.reject(this.notSentCallError("request used a stale route handle",H))}if(this.closedErr)return Promise.reject(this.notSentCallError("request was not sent because the subc connection was already closed",this.closedErr));let Y;try{Y=this.allocateCorr()}catch(H){return Promise.reject(this.notSentCallError("request correlation allocator was exhausted",H))}let K=A1($,Y),V=u(C.Request,i(!1,Z,!1,z),$.channel,$.epoch,Y,J),W=!1,j=(H)=>{if(!W)return this.notSentCallError("request bytes were not queued to the subc socket",H);if(H instanceof w&&H.code===t6)return new g("outcome_unknown",`managed call deadline exceeded after request bytes were queued to the local socket; no terminal response was observed; outcome unknown${T1(H)}`,A$,H);return this.outcomeUnknownCallError("connection dropped before the managed call returned a response",H)};return new Promise((H,Q)=>{let U=G??Y1,B={handle:$,resolve:H,reject:Q,onProgress:X,timer:null,classifyFailure:j};B.timer=setTimeout(()=>this.arbitrateTimeout(K,B,$.channel,Y,U),U),this.pending.set(K,B);let O=P$(this.sock,G0(V),Date.now()+U);W=O.queued,O.completed.catch((q)=>{let D=this.pending.get(K);if(D)this.rejectPending(K,D,q instanceof Error?q:new w(String(q)))})})}async cachedRouteHandle($,J){let Z=J.identity??this.opts.identity;if(!Z)throw new g("terminal","managed call requires a BindIdentity in SubcClient.connect({ identity }) or call(..., { identity })","missing_identity");let z={kind:J.targetKind??this.opts.targetKind,module_id:$},G=b$(J),X=e6(z,Z,G),Y=this.routes.get(X);if(!Y)Y={key:X,moduleId:$,target:z,identity:Z,consumerIdentity:G,handle:null,opening:null},this.routes.set(X,Y);if(Y.handle&&this.isLiveHandle(Y.handle))return Y.handle;if(!Y.opening)Y.opening=this.openCachedRoute(Y).finally(()=>{Y.opening=null});return Y.opening}async openCachedRoute($){let J=Date.now()+W8,Z=this.opts.reconnectBackoff.baseMs,z=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 g&&G.code==="route_closed")throw G;if(!this.closeStarted&&b1(G)){try{await this.reconnectAfterDrop(G)}catch(X){throw this.notSentRecoveryError("route.open was not sent and reconnect failed",X)}continue}if(!this.closeStarted&&G instanceof w&&Q8(G.code)){if(z+=1,z<this.opts.reconnectBackoff.maxAttempts&&Date.now()<J){await this.opts.sleep(Z),Z=Math.min(Z*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,J=this.generation,Z;try{Z=this.allocateCorr()}catch{return}let z=Date.now(),G=u(C.Ping,i(!1,y.Interactive,!1,l.Normal),0,0,Z,new Uint8Array),X=(async()=>{if(await Y0($,G0(G),z+this.opts.livenessProbeWindowMs).catch(()=>{}),await this.opts.sleep(this.opts.livenessProbeWindowMs),this.sock!==$||this.generation!==J||this.closeStarted)return;if(this.lastInboundAtMs>=z)return;if(this.hasControlPending())return;this.fail(new W0(`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=X}async ensureConnectedForManaged(){if(this.closeStarted)throw new w("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 w("client closed"));if(this.reconnecting)return this.reconnecting;let J=this.reconnectWithRetry($).finally(()=>{if(this.reconnecting===J)this.reconnecting=null});return this.reconnecting=J,J}async reconnectWithRetry($){let J=0,Z=this.opts.reconnectBackoff.baseMs;for(;;){if(this.closeStarted)throw new w("client closed");J+=1;try{let z=await D0.openConnection(this.opts);if(this.closeStarted)throw z.sock.close(),new w("client closed");this.replaceConnection(z),await this.reopenCachedRoutes();return}catch(z){if(!b1(z)||J>=this.opts.reconnectBackoff.maxAttempts){if(z instanceof s&&J>1)throw new s(`reconnect gave up after ${J} attempts: ${z.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 z}await this.opts.sleep(Z),Z=Math.min(Z*2,this.opts.reconnectBackoff.capMs)}}}replaceConnection($){this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.closedErr=null,this.generation+=1,this.connectionToken=v0(),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 J=await this.routeOpen($.target,$.identity,{consumerIdentity:$.consumerIdentity??null});if($.closed){this.liveRoutes.delete(J.channel),this.sendRouteGoodbye(J);continue}$.handle=J}}timeoutMessage($,J,Z){let z=this.sock.localPort();return`request on ${z===null?"channel":`local_port=${z} channel`} ${$} corr ${J} timed out after ${Z}ms`}routeClosedDuringOpen(){return new g("not_sent","route was closed before route.open completed","route_closed")}async readLoop($,J){try{for(;;){this.readerActive=!1;let Z=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:j8},()=>{this.readerActive=!0});try{if(this.sock===$&&this.generation===J)this.dispatch(Z)}finally{this.readerActive=!1}}}catch(Z){if(this.sock===$&&this.generation===J)this.fail(Z instanceof Error?Z:new w(String(Z)))}}dispatch($){if(this.lastInboundAtMs=Date.now(),$.header.channel===0&&$.header.ty===C.Push){let X=this.opts.onControlPush;if(X){let Y=null;try{let K=this.parseJson($);if(K&&typeof K.op==="string")Y={op:K.op,body:K}}catch{}if(Y)try{X(Y)}catch{}}return}let J=null;if($.header.channel!==0){if(J=this.liveRoutes.get($.header.channel)??null,!J||J.epoch!==$.header.epoch){this.ingressEpochDropCount+=1;return}}let Z=A1(J,$.header.corr),z=this.pending.get(Z);if(z){if(z.acceptFrame&&!z.acceptFrame($))return;switch($.header.ty){case C.Push:case C.StreamData:try{z.onProgress?.($.body)}catch{}return;case C.Response:case C.StreamEnd:this.settle(Z,z,()=>z.resolve($));return;case C.Error:this.settle(Z,z,()=>z.reject(this.errorFromFrame($)));return;default:return}}let G=this.lateResponses.get(Z);if(G&&($.header.ty===C.Response||$.header.ty===C.Error)){this.lateResponses.delete(Z),G($);return}if($.header.ty===C.Goodbye&&J){if(this.failHandle(J,new w("route closed by subc (GOODBYE)","route_closed")),this.liveRoutes.get(J.channel)===J)this.liveRoutes.delete(J.channel);this.evictRouteHandle(J);return}if($.header.ty===C.Response||$.header.ty===C.Error||$.header.ty===C.StreamEnd)X8("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($,J,Z){if(this.pending.get($)!==J)return!1;if(this.pending.delete($),J.timer)clearTimeout(J.timer);return Z(),J.onSettle?.(),!0}rejectPending($,J,Z){this.settle($,J,()=>J.reject(J.classifyFailure?.(Z)??Z))}errorFromFrame($){try{let J=JSON.parse(Buffer.from($.body).toString("utf8"));return new w(J.message??"subc error",J.code)}catch{return new w(Buffer.from($.body).toString("utf8")||"subc error")}}evictRouteHandle($){for(let J of this.routes.values())if(J.handle&&S1(J.handle,$))J.handle=null}failHandle($,J){for(let[Z,z]of this.pending)if(z.handle&&S1(z.handle,$))this.rejectPending(Z,z,J)}fail($){if(!this.closedErr)this.closedErr=$;for(let[J,Z]of this.pending)this.rejectPending(J,Z,$)}notSentCallError($,J){return new g("not_sent",`${$}${T1(J)}`,E1(J),J)}outcomeUnknownCallError($,J){return new g("outcome_unknown",`${$}${T1(J)}`,E1(J),J)}terminalCallError($,J){if(J instanceof g)return J;return new g("terminal",`${$}${T1(J)}`,E1(J),J)}notSentRecoveryError($,J){if(J instanceof g)return J;if(b1(J))return this.notSentCallError($,J);return this.terminalCallError($,J)}get droppedIngressFrames(){return this.ingressEpochDropCount}installRoute($,J){let Z=F1($,J,this.connectionToken);return this.liveRoutes.set($,Z),Z}isLiveHandle($){return X1($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveConnection($){if(!X1($,this.connectionToken))throw new j0($)}assertLiveHandle($){if(!this.isLiveHandle($))throw new j0($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let Z=new w("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.fail(Z),this.sock.close(),this.scheduleReconnectAfterDrop(Z),Z}let J=this.nextCorr;return this.nextCorr+=1n,J}closeConnectionAfterCleanupFailure(){let $=new w("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 J=$.body;return JSON.parse(Buffer.from(J.buffer,J.byteOffset,J.byteLength).toString("utf8"))}}function b1($){if($ instanceof W0||$ instanceof $0)return!0;if($ instanceof X0||$ instanceof B0)return!0;if($ instanceof g)return $.kind==="not_sent"||$.kind==="outcome_unknown";if($ instanceof s)return!0;if($ instanceof w||$ instanceof m)return!1;let J=E1($);return J==="ECONNREFUSED"||J==="ECONNRESET"||J==="EPIPE"||J==="ETIMEDOUT"||J==="ENOENT"}function Q8($){return $==="unknown_module"||$==="module_reloading"||$==="module_warming"||$==="target_unavailable"||$==="module_timeout"}function U8($){return{connectionFile:$.connectionFile,handshakeTimeoutMs:$.handshakeTimeoutMs,identity:$.identity,targetKind:$.targetKind??H8,reconnectBackoff:$.reconnectBackoff??I1,sleep:$.sleep??((J)=>new Promise((Z)=>setTimeout(Z,J))),timeoutArbitrationGraceMs:$.timeoutArbitrationGraceMs??K8,livenessProbeWindowMs:$.livenessProbeWindowMs??V8,onControlPush:$.onControlPush}}function e6($,J,Z){let z=Z?`${Z.module_id}\x00${Z.launch_nonce}`:"";return`${$.kind}\x00${$.module_id}\x00${J.project_root}\x00${J.harness}\x00${J.session}\x00${z}`}function b$($={}){if($.consumerIdentity!==void 0)return $.consumerIdentity??void 0;let J=process.env[$2],Z=process.env[J2];if(!J||!Z)return;return{module_id:J,launch_nonce:Z}}function E1($){if(typeof $==="object"&&$!==null&&"code"in $){let J=$.code;if(typeof J==="string")return J}return}function T1($){if($===void 0)return"";return`: ${$ instanceof Error?$.message:String($)}`}function A1($,J){return $?`${$.channel}:${$.epoch}:${J}`:`0:0:${J}`}import{Buffer as v$}from"node:buffer";var N8=1e4,B8=30000,z2=30000,L8=250,E$=64,k$="health.check",G2=1n;class v1{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 J=this.waiters.shift();if(J)J();else this.available+=1}}}class P extends Error{code;kind;constructor($,J,Z="terminal"){super($);this.code=J,this.kind=Z}}class K1{sock;currentConn;opts;closed;resolveClosed=()=>{return};closeStarted=!1;closedErr=null;inflight=new Map;pending=new Map;liveRoutes=new Map;connectionToken=v0();nextCorr=1n;ingressEpochDropCount=0;requestGate=new v1(E$);reconnecting=null;generation=1;connectionEpoch=1;stateQueue=[];drainingStateQueue=!1;restoredDebounceToken=0;storage;constructor($,J,Z,z){this.sock=$,this.currentConn=J,this.opts=Z,this.storage=z,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($,J,Z={}){this.assertLiveHandle($);let z=this.allocateCorr(),G=k1($,z),X=Z.timeoutMs??z2,Y=u(C.Request,i(!1,Z.priority??y.Interactive,!1,Z.admissionClass??l.Normal),$.channel,$.epoch,z,J);return await new Promise((K,V)=>{let W=setTimeout(()=>{if(this.pending.delete(G))V(new P("reverse request timed out","request_timeout"))},X);this.pending.set(G,{resolve:(j)=>K(j.body),reject:V,timer:W}),this.sendOn(this.sock,this.generation,Y).catch((j)=>{let H=this.pending.get(G);if(!H)return;this.pending.delete(G),clearTimeout(H.timer),V(j instanceof Error?j:new P(String(j)))})})}async push($,J,Z={}){this.assertLiveHandle($),await this.sendOn(this.sock,this.generation,u(C.Push,i(!1,Z.priority??y.Interactive,!1,Z.admissionClass??l.Normal),$.channel,$.epoch,0n,J))}cancel($,J){this.assertLiveHandle($),this.sendOn(this.sock,this.generation,u(C.Cancel,K0(),$.channel,$.epoch,J,new Uint8Array(0))).catch(()=>{return})}closeRoute($){this.assertLiveHandle($),this.liveRoutes.delete($.channel),this.abortHandle($),this.sendOn(this.sock,this.generation,u(C.Goodbye,K0(),$.channel,$.epoch,0n,new Uint8Array(0))).catch(()=>{return})}static async connect($){if($.manifest.protocol_ver!==t)throw new P(`manifest protocol_ver ${$.manifest.protocol_ver} does not match client protocol ${t}`,"invalid_manifest");let J=M8($),Z=await K1.openConnection(J);return new K1(Z.sock,Z.conn,J,Z.ack.storage)}async close(){if(!this.closeStarted){this.closeStarted=!0,this.cancelRestoredDebounce();let $=this.sock;try{await I$($,u(C.Goodbye,K0(),0,0,0n,new Uint8Array(0)))}catch{}finally{$.close(),this.finishClosed()}}await this.closed}static async openConnection($,J){let Z=await G1($.connectionFile),z=Date.now()+($.handshakeTimeoutMs??N8),G=Z.endpoints[0],X=await q0.connect(G.host,G.port,z);try{J?.(X),await z1(X,Z,z),await I$(X,D8($));let Y=await w8(X,z);return{sock:X,conn:Z,ack:Y}}catch(Y){throw X.close(),Y}}async readLoop($,J){try{for(;;){let Z=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:B8});if(!await this.dispatch(Z,$,J)){if(this.sock===$&&this.generation===J)this.closeStarted=!0;break}}}catch(Z){if(this.sock===$&&this.generation===J&&!this.closeStarted){this.handleUnexpectedDrop($,J,Z instanceof Error?Z:new P(String(Z)));return}}finally{if(this.sock===$&&this.generation===J){if($.close(),this.closeStarted)this.finishClosed()}}}async dispatch($,J,Z){let z=null;if($.header.channel!==0){if(z=this.liveRoutes.get($.header.channel)??null,!z||z.epoch!==$.header.epoch)return this.ingressEpochDropCount+=1,!0}if(z){let G=k1(z,$.header.corr),X=this.pending.get(G);if(X){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(X.timer),X.resolve($),!0;if($.header.ty===C.Error)return this.pending.delete(G),clearTimeout(X.timer),X.reject(C8($)),!0}}switch($.header.ty){case C.Ping:if($.header.channel===0)await this.sendOn(J,Z,z0($.header.ver,C.Pong,$.header.flags,0,0,$.header.corr,new Uint8Array(0)));return!0;case C.Goodbye:if(!z)return!1;return this.liveRoutes.delete(z.channel),this.abortHandle(z),await this.opts.onRouteGone?.(z),!0;case C.Cancel:if(z)this.inflight.get(k1(z,$.header.corr))?.abort();return!0;case C.Request:if($.header.channel===0)await this.handleControlRequest($,J,Z);else if(z)this.handleDataRequest($,z,J,Z).catch((G)=>{if(!this.closeStarted&&this.sock===J&&this.generation===Z)console.warn("SubcProvider handler failed after its request was dispatched",G)});return!0;default:return!0}}abortHandle($){let J=`${$.channel}:${$.epoch}:`;for(let[Z,z]of this.inflight)if(Z.startsWith(J))z.abort();for(let[Z,z]of this.pending){if(!Z.startsWith(J))continue;this.pending.delete(Z),clearTimeout(z.timer),z.reject(new j0($))}}abortGeneration($){this.abortAllInflight();for(let[J,Z]of this.pending)this.pending.delete(J),clearTimeout(Z.timer),Z.reject(new P("provider connection dropped","connection_dropped"));this.liveRoutes.clear()}abortAllInflight(){for(let $ of this.inflight.values())$.abort()}async handleControlRequest($,J,Z){let z=y1($.body);if(z.op===k$){this.handleHealthRequest($,J,Z).catch((H)=>{if(!this.closeStarted&&this.sock===J&&this.generation===Z)console.warn("SubcProvider health handler failed after its request was dispatched",H)});return}if(z.op!=="route.bind")throw new P(`unsupported module control request ${z.op??"<missing op>"}`);let G=Z2(z.route_channel,"route_channel"),X=Z2(z.epoch,"epoch"),Y=this.liveRoutes.get(G);if(Y){if(X<=Y.epoch){await this.sendError($,"route_rejected",`route.bind epoch ${X} does not supersede installed epoch ${Y.epoch} on channel ${G}`,K0(),J,Z);return}this.liveRoutes.delete(Y.channel),this.abortHandle(Y),await this.opts.onRouteGone?.(Y)}let K=F1(G,X,this.connectionToken),V={handle:K,target:z.target,identity:z.identity,principal:z.principal,consumer_capabilities:z.consumer_capabilities},W;try{W=await this.opts.onBind?.(V)}catch(H){try{await this.sendError($,"route_rejected",H instanceof Error?H.message:String(H),K0(),J,Z)}finally{await this.opts.onRouteGone?.(K)}return}let j=P8(W);if(j){try{await this.sendError($,j.code,j.message,K0(),J,Z)}finally{await this.opts.onRouteGone?.(K)}return}try{await this.sendOn(J,Z,z0($.header.ver,C.Response,K0(),0,0,$.header.corr,h1({op:"route.bind"})))}catch(H){throw await this.opts.onRouteGone?.(K),H}if(this.sock!==J||this.generation!==Z||this.closeStarted||this.closedErr){await this.opts.onRouteGone?.(K);return}this.liveRoutes.set(K.channel,K),await this.opts.onBound?.(K)}async handleDataRequest($,J,Z,z){let{corr:G,ver:X}=$.header,Y=k1(J,G),K=new AbortController;this.inflight.set(Y,K);let V={handle:J,signal:K.signal,currentEpoch:()=>this.connectionEpoch,emit:async(H,Q={})=>{if(this.assertLiveHandle(J),K.signal.aborted)return;await this.sendOn(Z,z,z0(X,C.StreamData,i(!1,Q.priority??y.Interactive,!1,Q.admissionClass??l.Normal),J.channel,J.epoch,G,H))}},W=await(this.requestGate??new v1(E$)).acquire(),j=i(!1,y.Interactive,!1);try{if(K.signal.aborted){await this.sendError($,"cancelled","request cancelled",j,Z,z);return}let H=await this.opts.handler(J,$.body,V);if(K.signal.aborted){await this.sendError($,"cancelled","request cancelled",j,Z,z);return}if(this.assertLiveHandle(J),H===void 0)await this.sendOn(Z,z,z0(X,C.StreamEnd,j,J.channel,J.epoch,G,new Uint8Array(0)));else if(H instanceof Uint8Array)await this.sendOn(Z,z,z0(X,C.Response,j,J.channel,J.epoch,G,H));else throw new P("provider handler must return a Uint8Array or void","invalid_handler_response")}catch(H){if(H instanceof j0)return;if(K.signal.aborted){await this.sendError($,"cancelled","request cancelled",j,Z,z);return}await this.sendError($,H instanceof P&&H.code?H.code:"handler_error",H instanceof Error?H.message:String(H),j,Z,z)}finally{if(W(),this.inflight.get(Y)===K)this.inflight.delete(Y)}}async handleHealthRequest($,J,Z){let{corr:z,ver:G}=$.header,X=`control:${Z}:${z}`,Y=new AbortController;this.inflight.set(X,Y);let K=await(this.requestGate??new v1(E$)).acquire();try{if(Y.signal.aborted)return;let V=await this.opts.health();await this.sendOn(J,Z,z0(G,C.Response,K0(),0,0,z,h1({op:k$,status:V.status,...V.detail===void 0?{}:{detail:V.detail},...V.metrics===void 0?{}:{metrics:V.metrics}})))}catch(V){await this.sendError($,V instanceof P&&V.code?V.code:"health_error",V instanceof Error?V.message:String(V),K0(),J,Z)}finally{if(K(),this.inflight.get(X)===Y)this.inflight.delete(X)}}async sendError($,J,Z,z,G,X){if($.header.channel!==0){let Y=this.liveRoutes.get($.header.channel);if(!Y||Y.epoch!==$.header.epoch||!this.isLiveHandle(Y))return}await this.sendOn(G,X,z0($.header.ver,C.Error,z,$.header.channel,$.header.epoch,$.header.corr,h1({code:J,message:Z})))}async sendOn($,J,Z){if(this.sock!==$||this.generation!==J||this.closeStarted||this.closedErr)return;await I$($,Z)}handleUnexpectedDrop($,J,Z){if(this.closeStarted||this.sock!==$||this.generation!==J)return;this.cancelRestoredDebounce(),this.abortGeneration(J),this.generation+=1,$.close(),this.scheduleReconnectAfterDrop(Z,this.generation,$)}scheduleReconnectAfterDrop($,J,Z){if(this.closeStarted)return;let z=this.reconnecting;if(z){if(!this.shouldSupersedeReconnect(z,J,Z))return;z.superseded=!0,z.socket?.close()}let G={generation:J,socket:null,socketDied:!1,superseded:!1};this.reconnecting=G,this.enqueueConnectionState({state:"down",cause:$}),this.reconnectWithRetry(G).catch((X)=>{if(this.isCurrentReconnect(G)&&!this.closeStarted)this.failFatal(X instanceof Error?X:new P(String(X)))}).finally(()=>{if(this.isCurrentReconnect(G))this.reconnecting=null})}async reconnectWithRetry($){let J=0,Z=this.opts.reconnectBackoff.baseMs;for(;;){if(!this.isCurrentReconnect($))return;if(this.closeStarted)throw new P("provider closed");$.socket=null,$.socketDied=!1,J+=1,this.enqueueReconnectState($,J);try{let z=await K1.openConnection(this.opts,(X)=>{if(!this.isCurrentReconnect($)){X.close();return}$.socket=X});if(!this.isCurrentReconnect($)||this.closeStarted){if(z.sock.close(),this.closeStarted)throw new P("provider closed");return}let G=this.replaceConnection(z,$.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(z){if(!this.isCurrentReconnect($))return;if($.socket)$.socketDied=!0;if(this.closeStarted)throw z;if(!x8(z))throw z;await this.opts.sleep(Z),Z=Math.min(Z*2,this.opts.reconnectBackoff.capMs)}}}isCurrentReconnect($){return!$.superseded&&this.reconnecting===$&&this.generation===$.generation}shouldSupersedeReconnect($,J,Z){return $.generation<J||$.socketDied||$.socket===Z}enqueueReconnectState($,J){if(!this.isCurrentReconnect($))return;this.enqueueConnectionState({state:"reconnecting",attempt:J},$.generation,$)}replaceConnection($,J){return this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.storage=$.ack.storage,this.closedErr=null,this.connectionEpoch+=1,this.connectionToken=v0(),this.liveRoutes.clear(),this.nextCorr=1n,this.readLoop($.sock,J),this.connectionEpoch}scheduleRestored($,J){if(!this.opts.onConnectionState)return;let Z=++this.restoredDebounceToken;this.opts.sleep(this.opts.restoredDebounceMs).then(()=>{if(Z===this.restoredDebounceToken&&!this.closeStarted&&this.sock&&this.generation===$&&this.connectionEpoch===J)this.enqueueConnectionState({state:"restored",epoch:J},$)}).catch((z)=>{if(Z===this.restoredDebounceToken&&!this.closeStarted)console.warn("SubcProvider restored debounce timer failed",z)})}cancelRestoredDebounce(){this.restoredDebounceToken+=1}enqueueConnectionState($,J,Z){if(!this.opts.onConnectionState)return;if(this.stateQueue.push({event:$,generation:J,reconnect:Z}),!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:J}=$;try{await this.opts.onConnectionState?.(J),this.stateQueue.shift()}catch(Z){if(J.state==="restored"){console.warn("SubcProvider restored callback failed; retrying delivery",Z),await f8();continue}console.warn("SubcProvider connection-state callback failed",Z),this.stateQueue.shift()}}}finally{if(this.drainingStateQueue=!1,this.stateQueue.length>0)this.drainConnectionStateQueue()}}isLiveHandle($){return X1($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveHandle($){if(!this.isLiveHandle($))throw new j0($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let Z=new P("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.handleUnexpectedDrop(this.sock,this.generation,Z),Z}let J=this.nextCorr;return this.nextCorr+=1n,J}failFatal($){if(!this.closedErr)this.closedErr=$;this.closeStarted=!0,this.cancelRestoredDebounce(),this.abortAllInflight(),this.sock.close(),this.finishClosed()}finishClosed(){this.resolveClosed()}}function k1($,J){return`${$.channel}:${$.epoch}:${J}`}function C8($){try{let J=y1($.body);return new P(J.message??"subc error",J.code,J.code==="stale_route_epoch"||J.code==="unknown_channel"?"not_sent":"terminal")}catch{return new P(v$.from($.body).toString("utf8")||"subc error")}}function _8($){let J=$.launchNonce??process.env[O8];return J&&J.length>0?J:void 0}var O8="SUBC_LAUNCH_NONCE";function M8($){return{connectionFile:$.connectionFile,manifest:$.manifest,handler:$.handler,health:$.health??(()=>({status:"ok"})),handshakeTimeoutMs:$.handshakeTimeoutMs,controlOps:$.controlOps,onBind:$.onBind,onBound:$.onBound,onRouteGone:$.onRouteGone,reconnectBackoff:$.reconnectBackoff??I1,sleep:$.sleep??((J)=>new Promise((Z)=>setTimeout(Z,J))),restoredDebounceMs:$.restoredDebounceMs??L8,onConnectionState:$.onConnectionState,launchNonce:$.launchNonce}}function q8($){if($===null)return null;let J=new Set($??[]);return J.add(k$),[...J]}function D8($){let J=_8($);return u(C.Hello,K0(),0,0,G2,h1({manifest:F8($.manifest),protocol_ver:t,control_ops:q8($.controlOps),...J?{launch_nonce:J}:{}}))}function x8($){if($ instanceof P)return $.code==="duplicate_module_id";if($ instanceof W0||$ instanceof $0)return!0;if($ instanceof X0||$ instanceof B0)return!0;if($ instanceof s)return!0;if($ instanceof m)return!1;let J=R8($);return J==="ECONNREFUSED"||J==="ECONNRESET"||J==="EPIPE"||J==="ETIMEDOUT"||J==="ENOENT"}function R8($){if(typeof $==="object"&&$!==null&&"code"in $){let J=$.code;if(typeof J==="string")return J}return}async function f8(){await new Promise(($)=>setTimeout($,0))}function K0(){return i(!1,y.Passive,!1)}async function I$($,J){await Y0($,G0(J),Date.now()+z2)}async function w8($,J){let Z=await $.readFrame(J,J);switch(Z.header.ty){case C.HelloAck:{let z=y1(Z.body);if(z.negotiated_ver!==t)throw new P(`subc negotiated protocol ${z.negotiated_ver}; expected exactly ${t}`,"unsupported_version");return z}case C.Error:{let z=y1(Z.body);throw new P(`subc rejected HELLO: ${z.code??"unknown"} — ${z.message??"subc error"}`,z.code)}default:throw new P(`unexpected frame ${C[Z.header.ty]} awaiting HELLO_ACK`)}}function h1($){return new Uint8Array(v$.from(JSON.stringify($),"utf8"))}function y1($){return JSON.parse(v$.from($).toString("utf8"))}function Z2($,J){if(typeof $!=="number"||!Number.isInteger($))throw new P(`route.bind ${J} must be an integer`);return $}function P8($){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 F8($){return{module_id:$.module_id,module_version:$.module_version,protocol_ver:$.protocol_ver,trust_tier:$.trust_tier,provides:$.provides.map(S8),consumes:$.consumes.map(T8),bindings:{storage:{kind:$.bindings.storage.kind,scope:$.bindings.storage.scope,owns_schema:$.bindings.storage.owns_schema},vault_grants:$.bindings.vault_grants.map((J)=>({secret:J.secret,reason:J.reason})),identity:{requires:[...$.bindings.identity.requires],optional:[...$.bindings.identity.optional]}}}}function S8($){switch($.role){case"tool_provider":return{role:"tool_provider",tools:$.tools.map((J)=>({name:J.name,...J.description===void 0?{}:{description:J.description},execution_mode:J.execution_mode,schema:J.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((J)=>({name:J.name,kind:J.kind})),config_schema:$.config_schema,observability:$.observability.map((J)=>({name:J.name,kind:J.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 T8($){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 V2(){return`/run/user/${process.getuid?.()??b8().uid}/subc-connection.json`}function n($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function E8($){return n($)&&typeof $.host==="string"&&$.host.trim().length>0&&typeof $.port==="number"&&Number.isInteger($.port)&&$.port>0&&$.port<=65535}async function Hz($=V2()){let J;try{J=await A8($,"utf8")}catch(z){let G=z.code;if(G==="ENOENT")return{status:"absent",path:$};return{status:"malformed",path:$,reason:`unreadable (${G??"unknown"})`}}let Z;try{Z=JSON.parse(J)}catch{return{status:"malformed",path:$,reason:"invalid JSON"}}if(!n(Z)||typeof Z.schema!=="number"||!Number.isFinite(Z.schema)||typeof Z.wire_version!=="number"||!Number.isFinite(Z.wire_version)||!Array.isArray(Z.endpoints)||Z.endpoints.length===0||!Z.endpoints.every(E8))return{status:"malformed",path:$,reason:"connection file has an invalid schema, wire_version, or endpoints"};return{status:"available",schema:Z.schema,wireVersion:Z.wire_version,endpoints:Z.endpoints.map((z)=>({host:z.host,port:z.port}))}}var W2="claustrum-tombstone:v1:";function I8($){return`${W2}${$}`}function k8($){return typeof $==="string"&&$.startsWith(W2)}function Qz($,J){if(!n($)||$.type!=="oauth")return!1;let Z=I8(J);return $.refresh===Z&&$.access===Z}class j1 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"}}function j2($,J){if(k8($))throw new j1(J)}class h${#$;#Z;#G;#X;#z=null;#Y=0;#J=!1;constructor($,J,Z,z){this.#$=$,this.#Z=J,this.#G=Z,this.#X=z}static async connect($={}){let J=$.connectionFile??V2(),Z=$.connector??((G)=>D0.connect(G)),z=await Z({connectionFile:J,handshakeTimeoutMs:$.handshakeTimeoutMs});return new h$(z,Z,J,$.handshakeTimeoutMs)}async catalogList($){return this.#$.catalogList($)}async routeOpen($,J,Z={}){return this.#$.routeOpen($,J,{...Z,consumerIdentity:null})}async request($,J,Z={}){return this.#$.request($,J,Z)}async call($,J,Z,z={}){try{return await this.#$.call($,J,Z,{...z,consumerIdentity:null})}catch(G){if(!this.#V(G))throw G;return await this.#K(),this.#$.call($,J,Z,{...z,consumerIdentity:null})}}subscribe($,J,Z,z={}){return this.#$.subscribe($,J,Z,z)}async closeRoute($,J={}){return this.#$.closeRoute($,J)}async closeManagedRoute($,J,Z={}){return this.#$.closeManagedRoute($,J,{...Z,consumerIdentity:null})}close(){this.#J=!0,this.#$.close()}#V($){return!this.#J&&$ instanceof g&&$.kind==="terminal"&&$.code!=="missing_identity"&&$.code!=="invalid_control_body"}async#K(){if(this.#J)throw Error("Claustrum client is closed");if(this.#z){await this.#z;return}let $=Date.now();if($<this.#Y)throw Error("Claustrum client reconnect is backed off");this.#Y=$+H2,this.#z=this.#Z({connectionFile:this.#G,handshakeTimeoutMs:this.#X}).then((J)=>{if(this.#J)throw J.close(),Error("Claustrum client is closed");let Z=this.#$;this.#$=J,Z.close()}).finally(()=>{this.#z=null}),await this.#z}}function v8($={}){return h$.connect($)}var X2="claustrum",h8=120000,H2=60000,Y2=["transient","permanent","auth_required","context_overflow"];class W1 extends Error{code;action;errorClass;constructor($,J,Z,z){super($);this.code=J,this.action=z,this.name="ClaustrumCredentialError",this.errorClass=Z}}function y8($){switch($){case"permanent":return"gone";case"auth_required":return"reauth";case"context_overflow":return"reduce_and_retry";case"transient":return"retry"}}function V1($,J="invalid_response"){let Z=n($)&&n($.result)?$.result:void 0,z=Z&&n(Z.error)?Z.error:void 0,G=z?.class,X=typeof G==="string"&&Y2.includes(G)?G:"transient";if(typeof G!=="string"||!Y2.includes(G))M.warn("claustrum","unrecognised credential error class",{errorClass:G??null});let Y=z&&typeof z.code==="string"?z.code:J;return new W1(`Claustrum credential request failed: ${Y}`,Y,X,y8(X))}function K2($){if($ instanceof W1)return $;if($ instanceof g&&$.kind==="terminal")return M.warn("claustrum","terminal credential call failed",{code:$.code??null,message:$.message}),new W1(`Claustrum credential request failed: ${$.message}`,$.code??"terminal_error","transient","retry");let J=$ instanceof Error?$.message:String($),Z=n($)&&typeof $.code==="string"?$.code:"transport_error";return new W1(`Claustrum credential request failed: ${J}`,Z,"transient","retry")}function m8($){let J=n($)&&n($.result)?$.result:void 0;if(J&&n(J.error))throw V1($);let Z=J?.payload;if(!Array.isArray(Z)||Z.length===0||!Z.every((K)=>typeof K==="number"&&Number.isInteger(K)&&K>=0&&K<=255))throw V1($);let z=J?.record_version;if(typeof z!=="number"||!Number.isSafeInteger(z)||z<0)throw V1($,"invalid_record_version");let G=J?.expires_at_ms,X=G===null||G===void 0?null:typeof G==="number"&&Number.isFinite(G)?G:void 0;if(X===void 0)throw V1($,"invalid_expiry");return{payload:new TextDecoder().decode(Uint8Array.from(Z)),expiresAtMs:X,recordVersion:z,...typeof J?.project_id==="string"&&{projectId:J.project_id},...typeof J?.account_id==="string"&&{accountId:J.account_id}}}class Q2{#$=new Map;#Z=new Map;#G;#X;#z;#Y=new Map;#J;constructor($,J={}){if(this.#G=$,this.#X=J.identity,this.#z=J.now??Date.now,this.#J=J.minTtlMs??h8,!Number.isSafeInteger(this.#J)||this.#J<0)throw RangeError("minTtlMs must be a non-negative safe integer")}async get($,J=this.#J){if(!Number.isSafeInteger(J)||J<0)throw RangeError("minTtlMs must be a non-negative safe integer");let Z=this.#z(),z=this.#$.get($);if(z&&z.expiresAtMs!==null&&z.expiresAtMs>Z){if(z.expiresAtMs-Z<=J)this.#V($,Z,J);return z}if(z)this.#$.delete($),this.#Y.delete($);let G=this.#Z.get($);if(G)return G;let X=this.#K($,J);this.#Z.set($,X);try{return await X}finally{if(this.#Z.get($)===X)this.#Z.delete($)}}peek($){return this.#$.get($)}seedForTest($,J){this.#$.set($,J)}reduceMinTtlMs(){return this.#J=Math.floor(this.#J/2),this.#J}async reportAuthFailure($,J,Z,z){let G=typeof J==="number"?J:typeof Z==="number"?Z:401,Y=(typeof J==="number"?typeof Z==="object"&&Z!==null?Z:void 0:J)?.recordVersion;if(typeof Y!=="number"||!Number.isSafeInteger(Y)||Y<0)throw TypeError("record_version is required from the credential served to the provider");try{let K;try{K=await this.#G.call(X2,"credential.report_auth_failure",{handle:$,provider_status:G,record_version:Y,...z?{reporter_source:z}:{}},{identity:this.#X})}catch(W){throw K2(W)}let V=n(K)&&n(K.result)?K.result:void 0;if(V&&n(V.error))throw V1(K)}finally{this.invalidate($,Y)}}invalidate($,J){let Z=this.#$.get($);if(Z&&(J===void 0||Z.recordVersion===J))this.#$.delete($)}close(){this.#G.close()}#V($,J,Z){if(this.#Z.has($))return;let z=this.#Y.get($);if(z!==void 0&&z>J)return;this.#Y.set($,J+H2);let G=this.#K($,Z);this.#Z.set($,G),G.catch(()=>{}).finally(()=>{if(this.#Z.get($)===G)this.#Z.delete($)})}async#K($,J){let Z;try{Z=await this.#G.call(X2,"credential.get",{handle:$,force_refresh:!1,min_ttl_ms:J},{identity:this.#X})}catch(X){throw K2(X)}let z=m8(Z),G={payload:z.payload,expiresAtMs:z.expiresAtMs,recordVersion:z.recordVersion,...z.projectId!==void 0&&{projectId:z.projectId},...z.accountId!==void 0&&{accountId:z.accountId}};if(G.expiresAtMs!==null&&G.expiresAtMs>this.#z())this.#$.set($,G);return G}}async function Uz($={}){if($.enabled!==!0)return null;let{enabled:J,identity:Z,now:z,minTtlMs:G,...X}=$,Y=await v8(X);return new Q2(Y,{identity:Z,now:z,minTtlMs:G})}var m1="9d1c250a-e61b-44d9-88ed-5944d1962f5e",U2={console:"https://platform.claude.com/oauth/authorize",max:"https://claude.com/cai/oauth/authorize"},y$="https://platform.claude.com/oauth/code/callback",m$="https://platform.claude.com/v1/oauth/token",g$="axios/1.15.2",N2=["org:create_api_key","user:profile","user:inference","user:sessions:claude_code","user:mcp_servers","user:file_upload"],B2="user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload",Bz="mcp_";var L2="fast-mode-2026-02-01";function Lz($,J){let Z=($??"").split(",").map((z)=>z.trim()).filter(Boolean);return[...new Set([...Z,...J])].join(",")}function Cz($){return typeof $==="string"&&($.startsWith("claude-opus-4-6")||$.startsWith("claude-opus-4-7")||$.startsWith("claude-opus-4-8")||$.startsWith("claude-opus-5"))}var _z="You are OpenCode",Oz="You are Claude Code, Anthropic's official CLI for Claude.",Mz=["<use_parallel_tool_calls>","For maximum efficiency, whenever you perform multiple independent operations, invoke all relevant tools simultaneously rather than sequentially. Prioritize calling independent tools in parallel whenever possible. For example, when reading 3 known files, run 3 tool calls in parallel to read all 3 files into context at the same time. When running multiple independent read-only commands like `ls` or `list_dir`, run all of those commands in parallel. Err on the side of maximizing parallel tool calls for independent work rather than running too many tools sequentially.","","Do not parallelize tool calls when one call depends on the output of another call. If a tool call needs an ID, filename, search result, or any other value returned by a previous tool call, run the first call, wait for its result, then run the dependent call using the real returned value. Never invent placeholder IDs, guessed task IDs, or other guessed values for dependent tool calls just to place them in the same parallel block.","</use_parallel_tool_calls>"].join(`
2
- `),C2="59cf53e54c78",_2=[4,7,20],x0="2.1.258",O2="cli",M2="0.112.1",q2="v26.3.0",D2="claude-cli/2.1.258 (external, cli)",x2=["explicit","automatic","hybrid"],g1="explicit",qz=["github.com/anomalyco/opencode","opencode.ai/docs"],Dz=[{match:"if OpenCode honestly",replacement:"if the assistant honestly"},{match:"Here is some useful information about the environment you are running in:",replacement:"Environment context you are running in:"}];var R2=new Set(["EAI_AGAIN","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETUNREACH","ENOTFOUND","ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT"]);function f2($,J){if(!$||typeof $!=="object")return;let Z=$[J];return typeof Z==="string"?Z:void 0}function L0($){let J=f2($,"code");if(J&&R2.has(J))return!0;let Z=$ instanceof Error?$.message:f2($,"message")??String($);if(Z.includes("fetch failed"))return!0;return[...R2].some((z)=>Z.includes(z))}function w2($){let J="";for(let Z of $)J+=String.fromCharCode(Z);return btoa(J).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function P2(){let $=new Uint8Array(64);crypto.getRandomValues($);let J=w2($),Z=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(J));return{verifier:J,challenge:w2(new Uint8Array(Z)),method:"S256"}}function l$($){if(!$)return;let J=Number($);if(Number.isFinite(J)&&J>0)return Math.ceil(J);let Z=Date.parse($);if(Number.isFinite(Z)){let z=Math.ceil((Z-Date.now())/1000);return z>0?z:void 0}return}class p$ extends Error{status;body;retryAfter;isRefreshError=!0;constructor($,J,Z){super(`Claude OAuth refresh failed: ${$} — ${J}`);this.status=$,this.body=J,this.name="ClaudeOAuthRefreshError",this.retryAfter=l$(Z??void 0)}}async function F2($){j2($.refreshToken,"anthropic");let J=$.fetchImpl??fetch,Z=$.maxRetries??2,z=$.baseDelayMs??500,G=$.setTimeoutImpl??globalThis.setTimeout;for(let X=0;X<=Z;X++)try{if(X>0){let W=z*2**(X-1);await new Promise((j)=>G(j,W))}let Y=await J(m$,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":g$},body:JSON.stringify({grant_type:"refresh_token",refresh_token:$.refreshToken,client_id:m1,scope:B2})});if(!Y.ok){if(Y.status>=500&&X<Z){await Y.body?.cancel().catch(()=>{});continue}let W=await Y.text().catch(()=>"");throw new p$(Y.status,W,Y.headers.get("retry-after"))}let K=await Y.json(),V=$.now?.()??Date.now();return{access:K.access_token,refresh:K.refresh_token??$.refreshToken,expires:V+K.expires_in*1000,expiresIn:K.expires_in,authLineageId:$.authLineageId}}catch(Y){if(Y instanceof p$)throw Y;if(X<Z&&L0(Y))continue;throw Y}throw Error("Token refresh exhausted all retries")}function g8(){return crypto.randomUUID().replace(/-/g,"")}function p8($){let J=$.trim();try{let Y=new URL(J),K=Y.searchParams.get("code"),V=Y.searchParams.get("state");if(K&&V)return{code:K,state:V}}catch{}let Z=J.split("#");if(Z.length===2&&Z[0]&&Z[1])return{code:Z[0],state:Z[1]};let z=new URLSearchParams(J),G=z.get("code"),X=z.get("state");if(G&&X)return{code:G,state:X};return null}async function l8($,J,Z){let z=await fetch(m$,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":g$},body:JSON.stringify({code:$.code,state:$.state,grant_type:"authorization_code",client_id:m1,redirect_uri:Z,code_verifier:J})});if(!z.ok)return{type:"failed"};let G=await z.json();return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+G.expires_in*1000}}async function Tz($){let J=await P2(),Z=g8(),z=new URL(U2[$],import.meta.url);return z.searchParams.set("code","true"),z.searchParams.set("client_id",m1),z.searchParams.set("response_type","code"),z.searchParams.set("redirect_uri",y$),z.searchParams.set("scope",N2.join(" ")),z.searchParams.set("code_challenge",J.challenge),z.searchParams.set("code_challenge_method","S256"),z.searchParams.set("state",Z),{url:z.toString(),redirectUri:y$,state:Z,verifier:J.verifier}}async function Az($,J,Z,z){let G=p8($);if(!G)return{type:"failed"};if(z&&G.state!==z)return{type:"failed"};return l8(G,J,Z)}import{createHash as u8}from"node:crypto";function J0($){return u8("sha256").update($).digest("hex").slice(0,16)}import{createHash as p2,randomUUID as C0}from"node:crypto";import{mkdir as n$,readFile as l1,rename as l2,rm as y0,stat as S2,writeFile as u1}from"node:fs/promises";import{homedir as d8}from"node:os";import{dirname as a$,join as m0}from"node:path";function p1($){try{return JSON.parse($)}catch(J){if(J instanceof SyntaxError)throw SyntaxError("invalid JSON");throw J}}var i8=globalThis.setTimeout.bind(globalThis),c8=globalThis.clearTimeout.bind(globalThis),u2="anthropic-auth.json",n8="anthropic-auth-state.json",a8="https://api.anthropic.com/api/oauth/usage",u0=["five_hour","seven_day","scoped","extraUsage","bindingWindow","fallbackAdvised"];function E($){return $.type==="oauth"}function cz($){return $.type==="api"}function s2($){let J=$?.trim();if(!J)return!1;try{let Z=new URL(J);return(Z.protocol==="http:"||Z.protocol==="https:")&&!Z.username&&!Z.password}catch{return!1}}function nz($){return $.costZeroing?.enabled!==!1}var o8=[401,403,429],d2=240,t8=d2;var d$=300000,r8=3600000,i2=86400000,e8=60000,$5=900000,J5=300000,Z5=5,T2={five_hour:0,seven_day:0},z5=!0,G5=60000,X5=60000,Y5=600000,K5=1e4,V5=100;function W5(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return m0(process.env.XDG_CONFIG_HOME||m0(d8(),".config"),"opencode")}function R(){return process.env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim()||m0(W5(),u2)}function n1($=R()){let J=process.env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim();if(J)return J;return $.endsWith(u2)?m0(a$($),n8):`${$}.state.json`}function _($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function A2($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():C0(),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 c2($){if(!_($))return null;if($.type==="api"){let J=typeof $.baseURL==="string"?$.baseURL.trim():"",Z=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!s2(J))return null;let z=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...A2($),type:"api",apiKey:Z||void 0,baseURL:J,authHeader:z}}if($.type!=="oauth")return null;if(typeof $.refresh!=="string"||!$.refresh.trim())return null;return{...A2($),type:"oauth",authLineageId:typeof $.authLineageId==="string"&&$.authLineageId.trim()?$.authLineageId:void 0,claustrumHandle:typeof $.claustrumHandle==="string"&&$.claustrumHandle.trim()?$.claustrumHandle.trim():void 0,access:typeof $.access==="string"?$.access:void 0,refresh:$.refresh,expires:typeof $.expires==="number"?$.expires:void 0,lastRefreshedAt:typeof $.lastRefreshedAt==="number"?$.lastRefreshedAt:void 0,lastRefreshError:b2($.lastRefreshError),lastQuotaRefreshError:b2($.lastQuotaRefreshError),quota:j5($.quota),profile:H1($.profile),prime:o$($.prime)}}function H1($){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 $.tokenFingerprint==="string"&&$.tokenFingerprint.trim()&&{tokenFingerprint:$.tokenFingerprint.trim()}}}function b2($){if(!_($))return;if(typeof $.message!=="string")return;let J=Number($.checkedAt);if(!Number.isFinite(J))return;let Z=Number($.nextRetryAt),z=Number($.retryCount),G=Number($.status);return{message:$.message,checkedAt:J,nextRetryAt:Number.isFinite(Z)?Z:void 0,retryCount:Number.isFinite(z)?z: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 E2($){if(!_($))return;let J=Number($.usedPercent),Z=Number($.remainingPercent),z=Number($.checkedAt);if(!Number.isFinite(J)||!Number.isFinite(Z)||!Number.isFinite(z))return;return{usedPercent:J,remainingPercent:Z,checkedAt:z,resetsAt:typeof $.resetsAt==="string"?$.resetsAt:void 0}}function o$($){if(!_($))return;let J=Number($.count),Z=Number($.inputTokens),z=Number($.outputTokens),G=Number($.since);if(![J,Z,z,G].every(Number.isFinite)||J<0||Z<0||z<0||G<0)return;return{count:Math.floor(J),inputTokens:Math.floor(Z),outputTokens:Math.floor(z),since:Math.floor(G)}}function j5($){if(!_($))return;let J={};for(let Z of["five_hour","seven_day"]){let z=E2($[Z]);if(z)J[Z]=z}if(typeof $.checkedAt==="number"&&Number.isFinite($.checkedAt))J.checkedAt=$.checkedAt;if(typeof $.accountIdentity==="string"&&$.accountIdentity.trim())J.accountIdentity=$.accountIdentity.trim();if(Array.isArray($.scoped)){let Z=$.scoped.map((z)=>{if(!_(z))return;let G=E2(z);if(!G)return;if(typeof z.id!=="string"||!z.id.trim())return;if(typeof z.title!=="string"||!z.title.trim())return;if(typeof z.modelName!=="string"||!z.modelName.trim())return;let X=typeof z.modelId==="string"&&z.modelId.trim()?z.modelId.trim():void 0;return{...G,id:z.id.trim(),title:z.title.trim(),...X&&{modelId:X},modelName:z.modelName.trim()}}).filter((z)=>z!=null);J.scoped=Z}if(_($.extraUsage)){let Z=I2($.extraUsage.used),z=I2($.extraUsage.limit);if(Z&&z&&typeof $.extraUsage.exhausted==="boolean")J.extraUsage={used:Z,limit:z,...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())J.bindingWindow=$.bindingWindow.trim();if($.bindingWindowSource==="poll"||$.bindingWindowSource==="headers")J.bindingWindowSource=$.bindingWindowSource;if(typeof $.fallbackAdvised==="boolean")J.fallbackAdvised=$.fallbackAdvised;if($.source==="poll"||$.source==="headers")J.source=$.source;if(_($.fieldSources)){let Z={};for(let z of u0){if(J[z]===void 0)continue;let G=$.fieldSources[z];if(G==="poll"||G==="headers")Z[z]=G}if(Object.keys(Z).length>0)J.fieldSources=Z}return Object.keys(J).length?J:void 0}function I2($){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 v(){return{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]}}function H5($){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:H1(_($.main)?$.main.profile:void 0)},routing:_($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((J)=>Number.isInteger(J)):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:Q5($.claustrum),logging:_($.logging)?$.logging:void 0,killswitch:_($.killswitch)?$.killswitch:void 0,prime:(()=>{if(!_($.prime))return;let J=typeof $.prime.enabled==="boolean"?$.prime.enabled:void 0,Z=o$($.prime.main),z=typeof $.prime.mainAuthLineageId==="string"&&$.prime.mainAuthLineageId.trim()?$.prime.mainAuthLineageId:void 0,G=typeof $.prime.mainAuthLineageRefreshTokenFingerprint==="string"&&$.prime.mainAuthLineageRefreshTokenFingerprint.trim()?$.prime.mainAuthLineageRefreshTokenFingerprint:void 0;if(J===void 0&&!Z&&!z&&!G)return;return{...J!==void 0&&{enabled:J},...Z&&{main:Z},...z&&{mainAuthLineageId:z},...G&&{mainAuthLineageRefreshTokenFingerprint:G}}})(),accounts:$.accounts.map(c2).filter((J)=>J!=null)}}function Q5($){if(!_($)||!_($.accounts))return;let J=Object.fromEntries(Object.entries($.accounts).flatMap(([Z,z])=>{if(!_(z))return[];return[[Z,{...typeof z.enabled==="boolean"&&{enabled:z.enabled}}]]}));return Object.keys(J).length>0?{accounts:J}:void 0}async function w0($){try{return{exists:!0,value:p1(await l1($,"utf8"))}}catch(J){if(J.code==="ENOENT")return{exists:!1,value:null};let Z=J instanceof Error?J.message:String(J);throw Error(`account store at ${$} is corrupt or unreadable (${Z}) — fix or remove it`)}}function P0($){return Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))}function s1($){return typeof $==="number"&&Number.isFinite($)?$:0}function s0($,J){if(J===void 0||!Number.isFinite(J))return $;if($===void 0||!Number.isFinite($))return J;return Math.max($,J)}function U5($,J){if(J===void 0||!Number.isFinite(J))return $;if($===void 0||!Number.isFinite($))return J;return Math.max($,J)}function i$($){return Math.max(s1($.lastRefreshedAt),s1($.lastUsed),s1($.addedAt))}function N5($,J){if($.type!=="oauth")return!1;if(typeof $.refresh!=="string"||!$.refresh.trim())return!1;if(!Boolean(typeof $.access==="string"&&typeof J.access==="string"&&$.access!==J.access||typeof $.refresh==="string"&&typeof J.refresh==="string"&&$.refresh!==J.refresh))return!1;return i$($)>i$(J)}function n2($,J){if(N5($,J)){let Z={...J,...$},z=i$($);if(z>s1(Z.lastRefreshedAt))Z.lastRefreshedAt=z;return delete Z.quota,delete Z.lastRefreshError,delete Z.lastQuotaRefreshError,Z}return{...$,...J}}function B5($){if($.type!=="api"&&$.type!=="oauth")return!0;if($.type==="api"&&"baseURL"in $&&(typeof $.baseURL!=="string"||!s2($.baseURL)))return!0;if($.type==="oauth"&&"refresh"in $&&(typeof $.refresh!=="string"||!$.refresh.trim()))return!0;return!1}function L5($,J){if(!_($))return $;let Z=_(J)?J:{},z=_(Z.main)?Z.main:void 0,G=_(Z.accounts)?Z.accounts:{},X=_($.quota)?$.quota:{},Y=_($.refresh)?$.refresh:{},K=z??X,V=z??Y,W=typeof z?.quotaErrorClearedAt==="number"&&Number.isFinite(z.quotaErrorClearedAt)&&z.quotaErrorClearedAt>=0?z.quotaErrorClearedAt:void 0,j=typeof z?.refreshErrorClearedAt==="number"&&Number.isFinite(z.refreshErrorClearedAt)&&z.refreshErrorClearedAt>=0?z.refreshErrorClearedAt:void 0,H=X.mainLastQuotaApiError,Q=z?.lastQuotaApiError??(W!==void 0&&_(H)&&typeof H.checkedAt==="number"&&H.checkedAt<=W?void 0:H),U=Y.mainLastRefreshError,B=z?.lastRefreshError??(j!==void 0&&_(U)&&typeof U.checkedAt==="number"&&U.checkedAt<=j?void 0:U),O=Array.isArray($.accounts)?$.accounts.map((q)=>{if(!_(q))return q;let D=typeof q.id==="string"?q.id:void 0,L=D?G[D]??G[D.trim()]:void 0,x=_(L)?L:{};return n2(q,x)}):[];return{...$,main:{type:"opencode",provider:"anthropic",profile:H1(z?.profile)},refresh:P0({...Y,mainLastRefreshError:B,mainRefreshErrorClearedAt:V.refreshErrorClearedAt,mainRefreshLeaseId:V.refreshLeaseId,mainRefreshLeaseUntil:V.refreshLeaseUntil,mainRefreshLeaseTokenHash:V.refreshLeaseTokenHash}),quota:P0({...X,mainQuota:K.quota,mainQuotaCheckedAt:K.quotaCheckedAt,mainQuotaToken:K.quotaToken,mainLastQuotaApiError:Q,mainQuotaErrorGeneration:K.quotaErrorGeneration,mainQuotaErrorClearedAt:K.quotaErrorClearedAt}),prime:(()=>{let q=_($.prime)?$.prime:void 0,D=o$(z?.prime),L=typeof z?.primeAuthLineageId==="string"&&z.primeAuthLineageId.trim()?z.primeAuthLineageId:void 0,x=typeof z?.primeAuthLineageRefreshTokenFingerprint==="string"&&z.primeAuthLineageRefreshTokenFingerprint.trim()?z.primeAuthLineageRefreshTokenFingerprint:void 0;if(!q&&!D&&!L&&!x)return;return{...q&&typeof q.enabled==="boolean"&&{enabled:q.enabled},...D&&{main:D},...L&&{mainAuthLineageId:L},...x&&{mainAuthLineageRefreshTokenFingerprint:x}}})(),accounts:O}}async function F($=R()){let J=await w0($),Z=await w0(n1($));if(!J.exists&&!Z.exists)return null;let z=J.exists?J.value:v();return H5(L5(z,Z.value))}async function t$($){let J=await w0($);return _(J.value)?J.value:{}}function C5($){return Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))}function _5($){return P0({id:$.id,label:$.label,type:$.type,enabled:$.enabled,addedAt:$.addedAt,baseURL:$.type==="api"?$.baseURL:void 0,authHeader:$.type==="api"?$.authHeader:void 0})}function k2($){if($.type==="api")return P0({apiKey:$.apiKey,lastUsed:$.lastUsed});return P0({authLineageId:$.authLineageId,claustrumHandle:$.claustrumHandle,access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota,profile:$.profile,prime:$.prime})}function U0($){return Math.max($?.five_hour?.checkedAt??0,$?.seven_day?.checkedAt??0,...$?.scoped?.map((J)=>J.checkedAt)??[],$?.checkedAt??0)}function g0($){if($?.source==="poll")return 2;if($?.source==="headers")return 1;return 0}function O5($,J){if(!("scoped"in $))return J.scoped;if(!Array.isArray($.scoped)||$.scoped.length===0)return $.scoped;if(!Array.isArray(J.scoped)||J.scoped.length===0)return $.scoped;let Z=new Map(J.scoped.map((z)=>[z.id,z]));for(let z of $.scoped){let G=Z.get(z.id);if(!G||z.checkedAt>=G.checkedAt)Z.set(z.id,z)}return[...Z.values()]}function v2($,J,Z){let z=$[Z],G=J[Z];if(!G)return z;if(!z)return G;if(G.checkedAt>z.checkedAt)return G;if(G.checkedAt<z.checkedAt)return z;return g0($)>g0(J)?z:G}function Q0($,J){if(!$||$[J]===void 0)return;return $.fieldSources?.[J]??($.source==="poll"||$.source==="headers"?$.source:void 0)}function M5($,J,Z){let z={};for(let G of u0){if(Z[G]===void 0)continue;if(G==="scoped"||G==="extraUsage"){z[G]="poll";continue}if(G==="bindingWindow"&&$.bindingWindowSource==="poll"&&$.bindingWindow===Z.bindingWindow){z[G]="poll";continue}if(G==="fallbackAdvised"&&J.fieldSources?.fallbackAdvised===void 0){let Y=Q0($,G);if(Y)z[G]=Y;continue}let X=J[G]===Z[G]?Q0(J,G):$[G]===Z[G]?Q0($,G):Q0($,G)??Q0(J,G);if(X)z[G]=X}return Object.keys(z).length>0?z:void 0}function a2($,J){if(!$||J.source!=="headers")return J;let Z=$.bindingWindowSource==="poll",z={...$,...J,five_hour:v2($,J,"five_hour"),seven_day:v2($,J,"seven_day"),scoped:O5($,J),extraUsage:$.extraUsage??J.extraUsage,fallbackAdvised:J.fieldSources?.fallbackAdvised!==void 0?J.fallbackAdvised:$.fallbackAdvised??J.fallbackAdvised,bindingWindow:Z?$.bindingWindow:J.bindingWindow??$.bindingWindow,bindingWindowSource:Z?"poll":J.bindingWindowSource??$.bindingWindowSource},G=M5($,J,z);return{...z,...G&&{fieldSources:G}}}function q5($,J){if(!_($))return J;let Z=$,z=Boolean(Z.access&&J.access&&Z.access!==J.access||Z.refresh&&J.refresh&&Z.refresh!==J.refresh),G=Boolean(!z&&J.quota?.source==="headers"),X=G&&J.quota?{...J,quota:a2(Z.quota,J.quota)}:J,Y=(()=>{let H=Z.lastRefreshError,Q=X.lastRefreshError;if(!H)return Q;if(Q)return Q.checkedAt>=H.checkedAt?Q:H;return(X.lastRefreshedAt??0)>(Z.lastRefreshedAt??0)?void 0:H})(),K=U0(Z.quota),V=U0(X.quota),W=Boolean(K===V&&g0(Z.quota)>g0(X.quota));if(!G&&(K>V||W)){let H=Z.lastRefreshedAt??0,Q=X.lastRefreshedAt??0;if(z&&Q<=H){let B={...Z};if(typeof X.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||X.lastUsed>Z.lastUsed))B.lastUsed=X.lastUsed;return B}let U={...Z,...X};if(z){if(!("profile"in X))delete U.profile;if(X.quota?.source)U.quota=X.quota;else delete U.quota;if(!("lastQuotaRefreshError"in X))delete U.lastQuotaRefreshError;return U.lastRefreshError=Y,U}return{...U,quota:Z.quota,lastQuotaRefreshError:Z.lastQuotaRefreshError,lastRefreshError:Y}}let j={...Z,...X};if(z){if(!("profile"in X))delete j.profile;if(!X.quota?.source)delete j.quota}if(!("lastQuotaRefreshError"in X))delete j.lastQuotaRefreshError;return j.lastRefreshError=Y,j}function r$($){let J=$.refresh?P0({enabled:$.refresh.enabled,intervalMinutes:$.refresh.intervalMinutes,refreshBeforeExpiryMinutes:$.refresh.refreshBeforeExpiryMinutes}):void 0,Z=$.quota?P0({enabled:$.quota.enabled,checkIntervalMinutes:$.quota.checkIntervalMinutes,refreshEveryNRequests:$.quota.refreshEveryNRequests,minimumRemaining:$.quota.minimumRemaining,failClosedOnUnknownQuota:$.quota.failClosedOnUnknownQuota,showToasts:$.quota.showToasts}):void 0;return C5({version:1,mainAccountId:$.mainAccountId,main:{type:"opencode",provider:"anthropic"},routing:$.routing,fallbackOn:$.fallbackOn,refresh:J,quota:Z,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(_5)})}function e$($,J){return $.claustrum?.accounts?.[J]?.enabled===!0}var h2=Promise.resolve();function A0($){return new Promise((J,Z)=>{h2=h2.then(()=>$().then(J,Z),()=>$().then(J,Z))})}async function F0($,J){await n$(a$($),{recursive:!0});let Z=`${$}.${C0()}.tmp`;await u1(Z,`${JSON.stringify(J,null,2)}
3
- `,{encoding:"utf8",mode:384});try{await l2(Z,$)}catch(z){throw await y0(Z,{force:!0}).catch(()=>{}),z}}function y2($,J){return $.id===J.id||Boolean($.label&&J.label&&$.label===J.label)}function D5($,J,Z){let z=new Set(Z.removedAccountIds??[]),G=$.filter((W)=>!z.has(W.id)),X=J.filter((W)=>!z.has(W.id)),Y=G.filter((W)=>!X.some((j)=>y2(j,W)));if(!Y.length)return[...X];if(Z.preserveExistingAccountOrder===!1)return[...X,...Y];let K=new Set,V=G.map((W)=>{let j=X.findIndex((Q,U)=>!K.has(U)&&y2(Q,W)),H=X[j];if(!H)return W;return K.add(j),H});for(let W=0;W<X.length;W++){let j=X[W];if(!K.has(W)&&j)V.push(j)}return V}var x5=1e4,R5=12000,f5=1e4,w5=12000;async function o2($){let{path:J,name:Z,ttlMs:z,waitMs:G,description:X}=$;await n$(a$(J),{recursive:!0});let Y=Date.now()+G;while(!0){let K=await b0({name:Z,ttlMs:z,path:J,renew:!0});if(K)return K;if(Date.now()>=Y)throw Error(`Timed out waiting for the account ${X} lock`);await new Promise((V)=>setTimeout(V,25))}}function d0($){return o2({path:$,name:"config-write",ttlMs:x5,waitMs:R5,description:"configuration write"})}function i0($){return o2({path:$,name:"state-write",ttlMs:f5,waitMs:w5,description:"state write"})}function p($,J=R(),Z={}){let z=J;return A0(()=>P5($,z,Z))}async function az($=R(),J=C0){return A0(async()=>{let Z=await d0($);try{let z=await F($)??v();if(z.mainAccountId)return z.mainAccountId;let G=J(),X={...z,mainAccountId:G},Y=await t$($);return await F0($,{...Y,...r$(X)}),G}finally{await Z.release()}})}async function P5($,J,Z){let z=await d0(J);try{let G=await F(J),X={...$,accounts:D5(G?.accounts??[],$.accounts,Z)},K={...await t$(J),...r$(X)};await F0(J,K);let V=await i0(J);try{await S0(X,J,{mainQuota:!0,mainRefresh:!0,accounts:!0})}finally{await V.release()}}finally{await z.release()}}function F5($,J){$.main=$.main??{},$.main.profile=J.main?.profile}function S5($,J){$.main=$.main??{};let Z=J.quota?.mainLastQuotaApiError,z=typeof J.quota?.mainQuotaErrorGeneration==="number"&&Number.isSafeInteger(J.quota.mainQuotaErrorGeneration)&&J.quota.mainQuotaErrorGeneration>=0?J.quota.mainQuotaErrorGeneration:void 0,G=typeof J.quota?.mainQuotaErrorClearedAt==="number"&&Number.isFinite(J.quota.mainQuotaErrorClearedAt)&&J.quota.mainQuotaErrorClearedAt>=0?J.quota.mainQuotaErrorClearedAt:void 0,X=typeof $.main.quotaErrorGeneration==="number"&&Number.isSafeInteger($.main.quotaErrorGeneration)&&$.main.quotaErrorGeneration>=0?$.main.quotaErrorGeneration:0,Y=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,V=Math.max(Y??0,K??0),W=typeof Z?.checkedAt==="number"&&Number.isFinite(Z.checkedAt)&&Z.checkedAt>=0?Z.checkedAt:void 0;if(Z===void 0&&G!==void 0&&G>=V){if($.main.lastQuotaApiError=void 0,$.main.quotaErrorClearedAt=s0(K,G),z!==void 0&&z>=X)$.main.quotaErrorGeneration=z}else if(Z&&typeof Z.checkedAt==="number"&&Number.isFinite(Z.checkedAt)&&Z.checkedAt>V){let q=W!==void 0&&W>V,D=W!==void 0&&W===V&&Y!==void 0&&K===void 0&&z!==void 0&&z>=X,L=W===void 0&&G===void 0&&z!==void 0&&z>=X&&K===void 0;if(q||D||L){if($.main.lastQuotaApiError=Z,z!==void 0)$.main.quotaErrorGeneration=Math.max(X,z)}}let j=J.quota?.mainQuota,H=Boolean($.main.quotaToken&&J.quota?.mainQuotaToken&&$.main.quotaToken===J.quota.mainQuotaToken),Q=H&&j?.source==="headers"?a2($.main.quota,j):j,U=Boolean(H&&j?.source==="headers"),B=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:U0($.main.quota),O=typeof J.quota?.mainQuotaCheckedAt==="number"?J.quota.mainQuotaCheckedAt:U0(Q);if(!U&&(B>O||B===O&&g0($.main.quota)>g0(Q)))return;$.main.quota=Q,$.main.quotaCheckedAt=U?Math.max(B,O):J.quota?.mainQuotaCheckedAt,$.main.quotaToken=J.quota?.mainQuotaToken}function T5($,J){$.main=$.main??{};let Z=J.refresh?.mainLastRefreshError,z=J.refresh?.mainRefreshErrorClearedAt,G=$.main.lastRefreshError?.checkedAt,X=$.main.refreshErrorClearedAt,Y=Math.max(G??0,X??0);if(Z===void 0&&z!==void 0&&z>=Y)$.main.lastRefreshError=void 0,$.main.refreshErrorClearedAt=U5(X,z);else if(Z&&typeof Z.checkedAt==="number"&&Number.isFinite(Z.checkedAt)&&Z.checkedAt>Y)$.main.lastRefreshError=Z;$.main.refreshLeaseId=J.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=J.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=J.refresh?.mainRefreshLeaseTokenHash}function A5($,J){let Z=J.prime?.main,z=J.prime?.mainAuthLineageId,G=J.prime?.mainAuthLineageRefreshTokenFingerprint;if(!Z&&!z&&!G)return;if($.main=$.main??{},Z)$.main.prime=Z;if(z)$.main.primeAuthLineageId=z;if(G)$.main.primeAuthLineageRefreshTokenFingerprint=G}function p0($){if(Array.isArray($))return $.map(p0);if(!_($))return $;return Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0).map(([J,Z])=>[J,p0(Z)]))}function b5($,J=R(),Z={mainProfile:!0,mainQuota:!0,mainRefresh:!0,accounts:!0}){let z=J;return A0(async()=>{let G=await i0(z);try{await S0($,z,Z)}finally{await G.release()}})}function oz($,J=R()){let Z=J;return A0(async()=>{let z=await d0(Z);try{let G=await i0(Z);try{let X=await F(Z),Y=n1(Z),K=(await w0(Y)).value,V=_(K)?{...K,version:1}:{version:1},{accountId:W,accountIdentity:j,profile:H}=$;if(W==="main"){V.main={...V.main??{}};let Q=H1(V.main.profile);if(!H){if(Q&&(j===void 0||Q.accountIdentity===void 0||Q.accountIdentity===j))return!1;return V.main.profile=void 0,await F0(Y,p0(V)).then(()=>!0)}if(H.accountIdentity!==void 0&&H.accountIdentity!==j)return!1;let U=j===void 0||H.accountIdentity===j?H:{...H,accountIdentity:j};if(Q&&(j===void 0||Q.accountIdentity===void 0||Q.accountIdentity===j)&&Q.checkedAt>U.checkedAt)return!1;V.main.profile=U}else{if(!X?.accounts.find((O)=>O.id===W&&E(O)))return!1;V.accounts={..._(V.accounts)?V.accounts:{}};let U=_(V.accounts[W])?{...V.accounts[W]}:{},B=H1(U.profile);if(!H){if(B&&(j===void 0||B.accountIdentity===void 0||B.accountIdentity===j))return!1;U.profile=void 0}else{if(H.accountIdentity!==void 0&&H.accountIdentity!==j)return!1;let O=j===void 0||H.accountIdentity===j?H:{...H,accountIdentity:j};if(B&&(j===void 0||B.accountIdentity===void 0||B.accountIdentity===j)&&B.checkedAt>O.checkedAt)return!1;U.profile=O}V.accounts[W]=U}return await F0(Y,p0(V)),!0}finally{await G.release()}}finally{await z.release()}})}function tz($,J,Z=R()){return A0(async()=>{let z=await d0(Z);try{let G=await i0(Z);try{let X=await F(Z),Y=X?.accounts.find((W)=>W.id===$&&E(W));if(!X||!Y||Y.claustrumHandle!==J||!e$(X,$)||!Y.lastRefreshError)return!1;Y.lastRefreshError=void 0,await S0(X,Z,{accounts:[$]});let K=n1(Z),V=(await w0(K)).value;if(_(V)&&_(V.accounts)){let W=V.accounts[$];if(_(W))delete W.lastRefreshError,await F0(K,p0(V))}return!0}finally{await G.release()}}finally{await z.release()}})}async function S0($,J,Z){let z=n1(J),G=(await w0(z)).value,X=_(G)?{...G,version:1}:{version:1};if(Z.mainProfile)F5(X,$);if(Z.mainQuota)S5(X,$);if(Z.mainRefresh)T5(X,$);if(Z.mainPrime)A5(X,$);if(Z.accounts){let Y=Z.accounts===!0?null:new Set(Z.accounts),K=(await w0(J)).value,V=(()=>{if(!_(K)||!Array.isArray(K.accounts))return null;if(K.accounts.length===0)return new Set;let W=_(X.accounts)?X.accounts:{},j=Object.fromEntries($.accounts.map((Q)=>[Q.id.trim(),k2(Q)])),H=K.accounts.map((Q)=>{if(!_(Q)||typeof Q.id!=="string")return null;let U=Q.id.trim();if(!U)return null;if(B5(Q))return null;let B=W[Q.id]??W[U],O=_(B)?B:{},q=j[U];return c2(n2(Q,q??O))?[Q.id,U]:null});return H.every((Q)=>Q!==null)?new Set(H.flatMap((Q)=>Q??[])):null})();X.accounts={..._(X.accounts)?X.accounts:{}};for(let W of $.accounts){let j=W.id.trim();if(Y&&!Y.has(W.id)&&!Y.has(j))continue;if(V&&!V.has(W.id)&&!V.has(j))continue;let H=Object.keys(X.accounts).filter((B)=>B!==j&&B.trim()===j),Q=H[0],U=X.accounts[j]??(Q?X.accounts[Q]:void 0);for(let B of H)delete X.accounts[B];X.accounts[j]=q5(U,k2(W))}if(V){for(let W of Object.keys(X.accounts))if(!V.has(W))delete X.accounts[W]}if(Y){for(let W of Y)if(!$.accounts.some((j)=>j.id===W))delete X.accounts[W]}}await F0(z,p0(X))}async function b0($){let Z=`${$.path??R()}.${$.name}.lock`,z=m0(Z,"owner.json"),G=C0(),X=$.now??Date.now,Y=null,K=!1;async function V(){try{return JSON.parse(await l1(Z,"utf8"))}catch(U){if(U.code!=="EISDIR")throw U;return JSON.parse(await l1(z,"utf8"))}}async function W(){await u1(Z,`${JSON.stringify({ownerId:G,expiresAt:X()+$.ttlMs})}
4
- `,{encoding:"utf8",mode:384})}async function j(){try{return await u1(Z,`${JSON.stringify({ownerId:G,expiresAt:X()+$.ttlMs})}
5
- `,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(U){let B=U.code;if(B==="EEXIST"||B==="EISDIR")return!1;throw U}}function H(){if(!$.renew||K)return;let U=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(Y=i8(()=>{(async()=>{try{let B=await V(),O=X();if(K||B?.ownerId!==G||Number(B?.expiresAt)<=O)return;await W(),H()}catch{}})()},U),"unref"in Y)Y.unref()}let Q=await j();if(!Q){let U=`${Z}.evicting`,B=m0(U,"owner.json"),O=C0(),q=5000,D=8;async function L(){await new Promise((h)=>setTimeout(h,Math.floor(Math.random()*4)))}async function x(){try{let h=await V();return Number(h?.expiresAt)>X()}catch{try{return(await S2(Z)).mtimeMs+$.ttlMs>X()}catch{return!1}}}async function k(){try{return JSON.parse(await l1(B,"utf8"))?.ownerId===O}catch{return!1}}async function N(){await n$(U);try{await u1(B,`${JSON.stringify({ownerId:O,createdAt:X()})}
6
- `,{encoding:"utf8",mode:384,flag:"wx"})}catch(h){let e=h.code;if(e==="ENOENT"||e==="EINVAL")return!1;throw await T(),h}return await $.onStep?.("eviction-marker-acquired"),!0}async function T(){if(await k())await y0(U,{recursive:!0,force:!0}).catch(()=>{})}for(let h=0;h<8;h++){if(Q=await j(),Q)break;if(await x())return null;try{if(!await N()){await L();continue}}catch(e){if(e.code!=="EEXIST")throw e;let M0;try{M0=await S2(U)}catch(o){if(o.code==="ENOENT"){await L();continue}throw o}if(M0.mtimeMs+5000>X())return null;await $.onStep?.("stale-marker-stat");let c=`${U}.${C0()}`;try{await l2(U,c)}catch(o){if(o.code==="ENOENT"){await L();continue}throw o}await $.onStep?.("stale-marker-claimed"),await y0(c,{recursive:!0,force:!0}).catch(()=>{}),await L();continue}try{if(await x())return null;if(!await k())return null;if(await $.onStep?.("stale-lock-confirmed"),!await k())return null;if(await y0(Z,{recursive:!0,force:!0}).catch(()=>{}),!await k())return null;if(Q=await j(),!Q)return null;if(!await k())return await y0(Z,{recursive:!0,force:!0}).catch(()=>{}),Q=!1,null;break}finally{await T()}}}if(!Q)return null;return H(),{release:async()=>{if(K=!0,Y)c8(Y),Y=null;try{if((await V())?.ownerId!==G)return}catch{return}await y0(Z,{recursive:!0,force:!0}).catch(()=>{})}}}function rz($){return $?.claudeCache?.enabled===!0}function E5($){return typeof $==="string"&&x2.includes($)?$:g1}function I5($){return E5($?.claudeCache?.mode)}async function ez($,J,Z=R()){let z=await F(Z)??v();return z.claudeCache={...z.claudeCache??{},enabled:$,mode:J??I5(z)},await p(z,Z),z}async function $G($,J=R()){let Z=await F(J)??v();return Z.claudeCache={...Z.claudeCache??{},enabled:Z.claudeCache?.enabled===!0,mode:$},await p(Z,J),Z}function JG($){return $?.dump?.enabled===!0}async function ZG($,J=R()){let Z=await F(J)??v();return Z.dump={...Z.dump??{},enabled:$},await p(Z,J),Z}function zG($){return $?.claudeFast?.enabled===!0}async function GG($,J=R()){let Z=await F(J)??v();return Z.claudeFast={...Z.claudeFast??{},enabled:$},await p(Z,J),Z}async function XG($,J,Z=R()){let z=await F(Z)??v();return z.cacheKeep={...z.cacheKeep??{},enabled:!0,always:!1,startHour:$,endHour:J},await p(z,Z),z}async function YG($=R()){let J=await F($)??v();return J.cacheKeep={...J.cacheKeep??{},enabled:!0,always:!0},delete J.cacheKeep.startHour,delete J.cacheKeep.endHour,await p(J,$),J}async function KG($,J=R()){let Z=await F(J)??v();return Z.cacheKeep={...Z.cacheKeep??{},enabled:$},await p(Z,J),Z}function VG($){return $?.cacheKeep?.subagents===!0}async function WG($,J=R()){let Z=await F(J)??v();return Z.cacheKeep={...Z.cacheKeep??{},subagents:$},await p(Z,J),Z}function jG($){return $?.prime?.enabled===!0}async function HG($,J=R()){let Z=await F(J)??v();return Z.prime={...Z.prime??{},enabled:$},await p(Z,J),Z}async function QG($,J=R()){return A0(async()=>{let Z=await d0(J);try{let z=await i0(J);try{let G=await F(J)??v();if($==="main"){let K=G.prime?.mainAuthLineageId;if(K)return K;let V=G.mainAccountId??C0();if(!G.mainAccountId){let W=await t$(J);await F0(J,{...W,...r$({...G,mainAccountId:V})}),G.mainAccountId=V}return G.prime={...G.prime??{},mainAuthLineageId:V},await S0(G,J,{mainPrime:!0}),V}let X=G.accounts.find((K)=>K.id===$&&E(K));if(!X)throw Error(`getOrCreatePrimeAuthLineageId: OAuth account "${$}" not found`);if(X.authLineageId)return X.authLineageId;let Y=C0();return X.authLineageId=Y,await S0(G,J,{accounts:[$]}),Y}finally{await z.release()}}finally{await Z.release()}})}async function UG($,J,Z=R(),z=Date.now()){let G=Number.isFinite(J?.inputTokens)?Math.max(0,Math.floor(J.inputTokens)):0,X=Number.isFinite(J?.outputTokens)?Math.max(0,Math.floor(J.outputTokens)):0;return A0(async()=>{let Y=await d0(Z);try{let K=await i0(Z);try{let V=await F(Z)??v();if($==="main"){let U=V.prime?.main,B={count:(U?.count??0)+1,inputTokens:(U?.inputTokens??0)+G,outputTokens:(U?.outputTokens??0)+X,since:U?.since??Math.floor(z)};return V.prime={...V.prime??{},main:B},await S0(V,Z,{mainPrime:!0}),B}let W=V.accounts.findIndex((U)=>U.id===$);if(W<0)throw Error(`incrementPrimeUsagePersistent: account "${$}" not found`);let j=V.accounts[W],H=j.prime,Q={count:(H?.count??0)+1,inputTokens:(H?.inputTokens??0)+G,outputTokens:(H?.outputTokens??0)+X,since:H?.since??Math.floor(z)};return V.accounts[W]={...j,prime:Q},await S0(V,Z,{accounts:[$]}),Q}finally{await K.release()}}finally{await Y.release()}})}function k5($){return $?.fallbackOn?.length?$.fallbackOn:o8}function NG($,J){return k5(J).includes($)}function a1($){let J=$?.quota?.minimumRemaining||{};return{five_hour:J.five_hour??J["5h"]??T2.five_hour,seven_day:J.seven_day??J["1w"]??T2.seven_day}}function Q1($){return $?.quota?.enabled!==!1}function v5($){return $?.refresh?.enabled!==!1}function h5($){return Math.floor(Math.random()*Math.max(0,$))}function t2($){let J=$?.refresh?.refreshBeforeExpiryMinutes??t8;return Math.max(d2,J)*60000}function BG($){return t2($)}function LG($){return p2("sha256").update($).digest("hex")}function y5($){let J=$.status;if(typeof J==="number"&&Number.isFinite(J))return J===429||J>=500;return L0($)}function m5($){let Z=($.previous?.accountIdentity===$.accountIdentity&&$.previous?.refreshTokenFingerprint===$.refreshTokenFingerprint?$.previous?.retryCount??0:0)+1,z=$.error.retryAfter,G;if(typeof z==="number"&&z>0)G=z*1000;else if(L0($.error))G=d$;else if(y5($.error))G=Math.min(r8,d$*2**Math.min(Z-1,6));else G=i2;let X=$.error.status,Y=typeof X==="number"&&Number.isFinite(X)?X:void 0,K=l0($.error),W=(typeof $.error.body==="string"?$.error.body:"").includes("invalid_grant")||K.includes("invalid_grant");return{message:K,checkedAt:$.now,nextRetryAt:$.now+G,retryCount:Z,accountIdentity:$.accountIdentity,refreshTokenFingerprint:$.refreshTokenFingerprint,status:Y,permanent:Y===400&&W}}function c0($){if(!$)return!1;if(typeof $.permanent==="boolean")return $.permanent;if(typeof $.status==="number")return $.status===400;if(L0($))return!1;if(typeof $.nextRetryAt==="number")return $.nextRetryAt-$.checkedAt>=i2;return!1}function r2($){let J=$.nextRetryAt;if(!J||!L0($))return J;return Math.min(J,$.checkedAt+d$)}function h0($,J,Z,z){if(!$)return!1;let G=r2($);if(!G||G<=Z)return!1;if($.refreshTokenFingerprint&&z&&$.refreshTokenFingerprint!==z)return!1;if(!$.accountIdentity)return!0;if(!J)return!0;return $.accountIdentity===J}function g5($,J){return`Claude OAuth refresh is backed off for ${Math.max(1,Math.ceil(((r2($)??J)-J)/1000))}s after: ${$.message}`}function u$($,J){return Object.assign(Error(g5($,J)),{refreshBackoffError:$})}function e2($){if(!$||typeof $!=="object")return;let J=$.refreshBackoffError;return J&&typeof J.message==="string"?J:void 0}function CG($){if(!$)return[];return $.accounts.filter((J)=>J.enabled!==!1&&E(J)&&c0(J.lastRefreshError)).map((J)=>J.label?.trim()||J.id)}function $6($){if($.status===403)return!0;return/Claude quota check failed: 403\b/.test(l0($))}function o1($){let Z=($.previous?.accountIdentity===$.accountIdentity?$.previous?.retryCount??0:0)+1,z=K4($.error)?Math.min($5,e8*2**Math.min(Z-1,6)):J5;return{message:l0($.error),checkedAt:$.now,nextRetryAt:$.now+z,retryCount:Z,...$.accountIdentity!==void 0&&{accountIdentity:$.accountIdentity}}}function T0($,J){if(!$?.nextRetryAt||$.nextRetryAt<=J)return!1;return!0}function _G($,J){return`Quota API backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??J)-J)/1000))}s after: ${$.message}`}function V0($){let J=$?.quota?.checkIntervalMinutes??Z5;return Math.max(1,J)*60000}function OG($){return $?.logging?.level}async function MG($,J=R()){let{setLogLevel:Z}=await import("./logger-jrkranbz.js"),z=await F(J)??v();z.logging={...z.logging??{},level:$},await p(z,J),Z($)}function $4($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken,accountIdentity:$.quota.mainQuota.accountIdentity}}function J4($){let J=$?.quota?.refreshEveryNRequests;return typeof J==="number"&&Number.isFinite(J)&&J>0?Math.floor(J):0}function d1($){return $?.quota?.failClosedOnUnknownQuota??z5}function Z4($){return $.toLowerCase().replace(/[^a-z0-9]/g,"")}function p5($){if(typeof $!=="string")return null;let J=Z4($);if(J.includes("fable"))return"fable";if(J.includes("mythos"))return"mythos";return J}function r($,J){let Z=p5(J);if(!Z)return;return $?.scoped?.find((z)=>{return[z.modelId,z.modelName,z.title].filter((X)=>typeof X==="string").map(Z4).join(" ").includes(Z)})}function l5($,J){let Z=r($,J);return Boolean(Z&&Number.isFinite(Z.remainingPercent)&&Z.remainingPercent<=0)}function i1($,J){return!l5($,J)}function z4($,J){if(!Q1(J))return!0;let Z=a1(J);for(let z of["five_hour","seven_day"]){let G=$?.[z];if(!G)return!d1(J);if(!Number.isFinite(G.remainingPercent))return!d1(J);if(G.remainingPercent<Z[z])return!1}return!0}function qG($){return Boolean($?.five_hour&&$.seven_day)}var f0={five_hour:5,seven_day:10,scoped:0};function U1($){let J=$?.five_hour??$?.["5h"],Z=$?.seven_day??$?.["1w"],z=$?.scoped;return{five_hour:typeof J==="number"&&Number.isFinite(J)?J:f0.five_hour,seven_day:typeof Z==="number"&&Number.isFinite(Z)?Z:f0.seven_day,scoped:typeof z==="number"&&Number.isFinite(z)?z:f0.scoped}}function J6($){return $?.killswitch?.enabled===!0}function Z6($,J){if(!$?.killswitch)return f0;if(J&&$.killswitch.accounts?.[J])return U1($.killswitch.accounts[J]);return U1($.killswitch.main)}function G4($,J,Z,z){if(!J6(J))return!0;let G=Z6(J,Z),X=!1;for(let Y of["five_hour","seven_day"]){let K=$?.[Y];if(!K){X=!0;continue}if(!Number.isFinite(K.remainingPercent)){X=!0;continue}if(K.remainingPercent<G[Y])return!1}if(z){let Y=r($,z);if(Y&&Number.isFinite(Y.remainingPercent)&&Y.remainingPercent<=G.scoped)return!1}if(X)return!d1(J);return!0}function X4($,J,Z,z){let G=[],X=[$,...J.map((Y)=>Y.quota)];for(let Y of X)if(z){let V=r(Y,z)?.resetsAt;if(!V)continue;let W=Date.parse(V);if(Number.isFinite(W)&&W>Z)G.push(W)}else for(let K of["five_hour","seven_day"]){let V=Y?.[K]?.resetsAt;if(!V)continue;let W=Date.parse(V);if(Number.isFinite(W)&&W>Z)G.push(W)}if(!G.length)return 300;return Math.max(1,Math.ceil((Math.min(...G)-Z)/1000))+60}function DG($){return $?.killswitch??{enabled:!1}}async function xG($,J=R()){let Z=await F(J)??v();return Z.killswitch=$,await p(Z,J),Z}async function RG($,J=R()){let Z=await F(J);if(!Z)return!1;let z=o5(Z,$);if(z)await p(Z,J,{removedAccountIds:[$]});return z}async function fG($,J=R()){let Z=await F(J);if(!Z)return;t5(Z,$),await p(Z,J,{preserveExistingAccountOrder:!1})}async function wG($,J,Z=R()){let z=await F(Z);if(!z)return!1;let G=r5(z,$,J);if(G)await p(z,Z);return G}async function PG($,J=R()){let Z=await F(J)??v();a5(Z,$),await p(Z,J)}function E0($,J,Z){let z=V0(J);if(!Q1(J))return Z+z;let G=Math.min(...[...["five_hour","seven_day"].map((V)=>$?.[V]?.checkedAt),...($?.scoped??[]).map((V)=>V.checkedAt)].filter((V)=>Number.isFinite(V)).map((V)=>V+z)),X=(V)=>Number.isFinite(G)?Math.min(V,G):V,Y=a1(J),K=[];for(let V of["five_hour","seven_day"]){let W=$?.[V];if(!W)return X(Z+z);if(W.remainingPercent>=Y[V])continue;let j=W.resetsAt?Date.parse(W.resetsAt):Number.NaN;if(!Number.isFinite(j)||j<=Z)return X(Z+z);K.push(j)}if(!K.length)return X(Z+z);return X(Math.min(...K)+60000)}function R0($,J,Z){return!$.access||!$.expires||$.expires-Z<=t2(J)}function Y4($,J,Z){if(!Q1(J))return!0;let z=V0(J);return["five_hour","seven_day"].every((G)=>{let X=$?.[G];return Boolean(X&&Z-X.checkedAt<z)})}function s$($,J,Z,z){if(!Y4($.quota,J,Z))return!0;let G=r($.quota,z);return Boolean(G&&Z-G.checkedAt>=V0(J))}function u5($,J){if(!$)return!1;if(!$.resetsAt)return!0;let Z=Date.parse($.resetsAt);return!Number.isFinite(Z)||Z>J}function s5($,J){return["five_hour","seven_day"].every((Z)=>u5($?.[Z],J))}function K4($){let J=$.status;if(typeof J==="number"&&Number.isFinite(J)){if(J===429||J>=500)return!0}let Z=l0($);if(/Claude quota check failed: (429|5\d\d)\b/.test(Z))return!0;if(Z.includes("Quota refresh is already in progress"))return!0;return L0($)}function d5($,J,Z,z){return Boolean($.access&&$.expires&&$.expires>z)&&K4(Z)&&z4($.quota,J)&&s5($.quota,z)}function c1($){if(!Number.isFinite($))return 0;if($<0)return 0;if($>100)return 100;return $}function _0($){return typeof $==="string"&&$.trim()?$.trim():void 0}function V4($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function i5($,J){if(!Array.isArray($))return[];let Z=new Set,z=[];for(let G of $){if(G?.kind!=="weekly_scoped"||G.group!=="weekly")continue;if(typeof G.percent!=="number"||!Number.isFinite(G.percent))continue;let X=_0(G.scope?.model?.display_name);if(!X)continue;let Y=_0(G.scope?.model?.id)??X,K=V4(Y);if(!K)continue;let V=`claude-weekly-scoped-${K}`;if(Z.has(V))continue;Z.add(V);let W=c1(G.percent),j=_0(G.scope?.model?.id);z.push({id:V,title:`${X} only`,...j&&{modelId:j},modelName:X,usedPercent:W,remainingPercent:c1(100-W),resetsAt:G.resets_at,checkedAt:J})}return z}function c5($){if($.extra_usage?.is_enabled!==!0)return;let J=$.extra_usage.used_credits,Z=$.extra_usage.monthly_limit;if(typeof J!=="number"||!Number.isFinite(J)||typeof Z!=="number"||!Number.isFinite(Z))return;let z=$.spend?.limit?.currency,G=z==null?"USD":_0(z),X=$.spend?.limit?.exponent,Y=X==null?2:X;if(!G||!/^[A-Za-z]{3}$/.test(G)||!Number.isInteger(Y)||Y<0||Y>20)return;return{used:{amountMinor:J,currency:G,exponent:Y},limit:{amountMinor:Z,currency:G,exponent:Y},...typeof $.extra_usage.utilization==="number"&&Number.isFinite($.extra_usage.utilization)&&{utilizationPercent:$.extra_usage.utilization},..._0($.spend?.severity)&&{severity:_0($.spend?.severity)},exhausted:J>=Z}}function n5($){if(!Array.isArray($))return;let J=$.find((X)=>X?.is_active===!0);if(!J)return;if(J.kind==="session")return"five_hour";if(J.kind==="weekly_all")return"seven_day";if(J.kind!=="weekly_scoped"||J.group!=="weekly")return;let Z=_0(J.scope?.model?.display_name);if(!Z)return;let z=_0(J.scope?.model?.id)??Z,G=V4(z);return G?`claude-weekly-scoped-${G}`:void 0}function m2($,J){if(typeof $?.utilization!=="number")return;if(!Number.isFinite($.utilization))return;let Z=c1($.utilization);return{usedPercent:Z,remainingPercent:c1(100-Z),resetsAt:$.resets_at,checkedAt:J}}async function t1($){let Z=await($.fetchImpl??fetch)(a8,{method:"GET",headers:{Authorization:`Bearer ${$.accessToken}`,Accept:"application/json","Content-Type":"application/json","anthropic-beta":"oauth-2025-04-20","User-Agent":`claude-code/${x0}`}});if(!Z.ok){let V=await Z.text().catch(()=>"");throw Object.assign(Error(`Claude quota check failed: ${Z.status} — ${V}`),{status:Z.status,retryAfter:l$(Z.headers.get("Retry-After"))})}let z=$.now?.()??Date.now(),G=await Z.json(),X=n5(G.limits),Y={five_hour:m2(G.five_hour,z),seven_day:m2(G.seven_day,z),scoped:i5(G.limits,z),extraUsage:c5(G),...X&&{bindingWindow:X,bindingWindowSource:"poll"},source:"poll",checkedAt:z},K={...Y.five_hour&&{five_hour:"poll"},...Y.seven_day&&{seven_day:"poll"},...Y.scoped&&{scoped:"poll"},...Y.extraUsage&&{extraUsage:"poll"},...Y.bindingWindow&&{bindingWindow:"poll"}};return{...Y,...Object.keys(K).length>0&&{fieldSources:K}}}function d($,J){let Z=$.accounts.findIndex((z)=>z.id===J.id);if(Z>=0)$.accounts[Z]=J}function a5($,J){let Z=$.accounts.findIndex((z)=>z.id===J.id||J.label&&z.label===J.label);if(Z>=0){$.accounts[Z]={...$.accounts[Z],...J,addedAt:$.accounts[Z]?.addedAt??J.addedAt,...J.type==="oauth"&&{quota:J.quota,profile:J.profile,lastRefreshedAt:J.lastRefreshedAt,lastRefreshError:J.lastRefreshError,lastQuotaRefreshError:J.lastQuotaRefreshError}};return}$.accounts.push(J)}function o5($,J){let Z=$.accounts.findIndex((z)=>z.id===J);if(Z<0)return!1;return $.accounts.splice(Z,1),!0}function t5($,J){let Z=new Map(J.map((X,Y)=>[X,Y])),z=$.accounts.filter((X)=>Z.has(X.id)),G=$.accounts.filter((X)=>!Z.has(X.id));z.sort((X,Y)=>(Z.get(X.id)??0)-(Z.get(Y.id)??0)),$.accounts=[...z,...G]}function r5($,J,Z){let z=$.accounts.find((G)=>G.id===J);if(!z)return!1;return z.enabled=Z,!0}function l0($){return $ instanceof Error?$.message:String($)}function c$($,J,Z){if(J instanceof j1)return;let z=e2(J);if(z){$.lastRefreshError=z;return}$.lastRefreshError=m5({error:J,now:Z,accountIdentity:$.id,refreshTokenFingerprint:J0($.refresh),previous:$.lastRefreshError})}function g2($,J,Z){if(J instanceof j1)return;if($6(J)||e2(J))return;if($.lastQuotaRefreshError=o1({error:J,now:Z,previous:$.lastQuotaRefreshError}),J.isRefreshError)c$($,J,Z)}function e5($){return`fallback-oauth-refresh-${p2("sha256").update($).digest("hex").slice(0,16)}`}class $9{now;fetchImpl;configPath;refreshPromises=new Map;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??R(),this.quotaManager=$.quotaManager??null,this.isFallbackAccountVaultServed=$.isFallbackAccountVaultServed??(()=>!1),this.isFallbackAccountVaultEnabled=$.isFallbackAccountVaultEnabled??(()=>!1),this.resolveFallbackAccessToken=$.resolveFallbackAccessToken??((J)=>{if(!J.access||J.expires===void 0||J.expires<=this.now())return;return{token:J.access,source:"sidecar"}}),this.onBackgroundRefresh=$.onBackgroundRefresh,this.onFallbackStorageChanged=$.onFallbackStorageChanged,this.setIntervalImpl=$.setIntervalImpl??globalThis.setInterval,this.clearIntervalImpl=$.clearIntervalImpl??globalThis.clearInterval}seedFallbackQuota($,J){if(!this.quotaManager)return;if(!$.quota)return;let Z=U0($.quota);if(Z<=0)return;let z=this.quotaManager.getFallback($.id,$);if(z&&z.checkedAt>=Z)return;let G=V0(J);this.quotaManager.setFallback($.id,{quota:$.quota,refreshAfter:Z+G,checkedAt:Z},$)}async load(){return F(this.configPath)}async save($,J){await b5($,this.configPath,{accounts:J??!0})}startBackgroundRefresh(){let $=async(Z=!1)=>{await this.onBackgroundRefresh?.(Z),await this.refreshDueAccounts(),await this.refreshQuotaForDueAccounts()},J=$(!0).catch(()=>{});if(!this.refreshTimer){if(this.refreshTimer=this.setIntervalImpl(()=>$().catch(()=>{}),G5+h5(X5)),"unref"in this.refreshTimer)this.refreshTimer.unref()}return J}stopBackgroundRefresh(){if(this.refreshTimer)this.clearIntervalImpl(this.refreshTimer);if(this.quotaTimer)this.clearIntervalImpl(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts($,J={}){let Z=$!==void 0?$:await this.load();if(!Z)return[];let z=[],G=!1;for(let X of Z.accounts){if(X.enabled===!1||!E(X))continue;let Y=X;try{if(R0(Y,Z,this.now())&&(!this.isFallbackAccountVaultEnabled(Y.id,Z)||Y.expires===void 0||Y.expires<=this.now())&&!this.isFallbackAccountVaultServed(Y.id,Z)){if(this.isFallbackAccountVaultEnabled(Y.id,Z))M.warn("refresh","custody override: local fallback refresh",{accountId:Y.id,reason:"vault credential unavailable"});let V=Y.lastRefreshError;if(V&&h0(V,Y.id,this.now(),J0(Y.refresh)))throw u$(V,this.now());Y=await this.refreshAccount(Y,Z),G=!0}if(this.seedFallbackQuota(Y,Z),(this.quotaManager?this.quotaManager.isFallbackStale(Y.id,Y.access,J.modelId,Y):s$(Y,Z,this.now(),J.modelId))&&!T0(Y.lastQuotaRefreshError,this.now())){let V=await this.refreshAccountQuota(Y,Z);Y=V.account,G||=V.changed}if(this.accountPassesQuotaPolicy(this.quotaPolicyAccount(Y),Z,{modelId:J.modelId}))z.push(Y)}catch(K){if(d5(Y,Z,K,this.now())){if(H0("[refresh] fallback quota using cached quota after refresh error",{accountId:Y.id,error:l0(K)}),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(Y),Z,{modelId:J.modelId}))z.push(Y)}else if(!d1(Z)&&!h0(Y.lastRefreshError,Y.id,this.now(),J0(Y.refresh))&&i1(Y.quota,J.modelId))z.push(Y)}}if(G)await this.save(Z);return z}async markUsed($){let J=await this.load();if(!J)return;let Z=J.accounts.find((z)=>z.id===$.id);if(!Z)return;Z.lastUsed=this.now(),await this.save(J)}accountPassesQuotaPolicy($,J,Z={}){return z4($.quota,J)&&i1($.quota,Z.modelId)}quotaPolicyAccount($){if(!this.quotaManager)return $;let J=this.quotaManager.getFallback($.id,$)?.quota;return J?{...$,quota:J}:$}async refreshDueAccounts(){let $=await this.load();if(!$||!v5($))return;let J=!1;for(let Z of $.accounts){if(Z.enabled===!1||!E(Z))continue;if(!R0(Z,$,this.now())||this.isFallbackAccountVaultEnabled(Z.id,$)||this.isFallbackAccountVaultServed(Z.id,$))continue;if(h0(Z.lastRefreshError,Z.id,this.now(),J0(Z.refresh)))continue;try{H0("[refresh] fallback oauth background due",{accountId:Z.id,expiresInMs:Z.expires?Z.expires-this.now():void 0}),await this.refreshAccount(Z,$),J=!0}catch(z){M.warn("refresh","fallback oauth background failed",{accountId:Z.id,error:z instanceof Error?z.message:String(z)}),c$(Z,z,this.now()),d($,Z),J=!0}}if(J)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!Q1($))return;let J=!1;for(let Z of $.accounts){if(Z.enabled===!1||!E(Z))continue;let z=Z;try{if(R0(z,$,this.now())&&!this.isFallbackAccountVaultEnabled(z.id,$)&&!this.isFallbackAccountVaultServed(z.id,$)){if(h0(z.lastRefreshError,z.id,this.now(),J0(z.refresh)))continue;z=await this.refreshAccount(z,$),J=!0}if(T0(z.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(z,$),!(this.quotaManager?this.quotaManager.isFallbackStale(z.id,z.access):s$(z,$,this.now())))continue;let X=await this.refreshAccountQuota(z,$);J||=X.changed}catch(G){g2(Z,G,this.now()),d($,Z),J=!0}}if(J)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let J=await this.load(),Z=[];if(!J||!Q1(J))return{storage:J,errors:Z};let z=$.force??!1,G=!1;for(let X of J.accounts){if(X.enabled===!1||!E(X))continue;let Y=X;try{if(R0(Y,J,this.now())&&!this.isFallbackAccountVaultServed(Y.id,J)&&!this.isFallbackAccountVaultEnabled(Y.id,J)){let V=Y.lastRefreshError;if(V&&h0(V,Y.id,this.now(),J0(Y.refresh)))throw u$(V,this.now());Y=await this.refreshAccount(Y,J),G=!0}if(!z&&!s$(Y,J,this.now())){if(Y.lastQuotaRefreshError)Y.lastQuotaRefreshError=void 0,d(J,Y),G=!0;continue}let K=await this.refreshAccountQuota(Y,J);G||=K.changed}catch(K){g2(X,K,this.now()),d(J,X),G=!0,Z.push({accountId:X.id,message:l0(K)})}}if(G)await this.save(J);return{storage:J,errors:Z}}async refreshAccount($,J,Z={}){if(this.isFallbackAccountVaultServed($.id,J))return $;let z=this.refreshPromises.get($.id);if(z){let X=await z;return d(J,X),X}let G=this.refreshAccountNow($,J,Z).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,G);try{let X=await G;return d(J,X),X}catch(X){if(Z.persistError)c$($,X,this.now()),d(J,$),await this.save(J);throw X}}async waitForConcurrentFallbackRefresh($,J,Z,z){let G=Date.now()+K5;while(Date.now()<G){await new Promise((W)=>setTimeout(W,V5));let X=await this.load(),Y=X?.accounts.find((W)=>W.id===$.id&&E(W));if(!Y)continue;if((Y.access!==Z.access||Y.refresh!==Z.refresh||(Y.expires??0)>(Z.expires??0)+60000)&&(z.force||!R0(Y,X,this.now())))return d(J,Y),H0("[refresh] fallback oauth joined concurrent refresh",{accountId:Y.id,expiresInMs:Y.expires?Y.expires-this.now():void 0}),Y;let V=Y.lastRefreshError;if(V&&h0(V,Y.id,this.now(),J0(Y.refresh)))throw d(J,Y),u$(V,this.now())}return null}async refreshAccountNow($,J,Z){let z=await this.load(),G=z?.accounts.find((K)=>K.id===$.id&&E(K));if(G&&!Z.force&&!R0(G,z,this.now()))return d(J,G),G;let X=G??$,Y=await b0({name:e5(X.id),ttlMs:Y5,path:this.configPath,now:this.now,renew:!0});if(!Y){H0("[refresh] fallback oauth refresh skipped file lock",{accountId:X.id});let K=await this.waitForConcurrentFallbackRefresh($,J,X,Z);if(K)return K;throw Error("Fallback OAuth refresh is already in progress")}try{if(z=await this.load(),G=z?.accounts.find((W)=>W.id===$.id&&E(W)),G&&!Z.force&&!R0(G,z,this.now()))return d(J,G),G;X=G??X;let K=X.refresh;H0("[refresh] fallback oauth refresh request start",{accountId:X.id,force:Z.force===!0,expiresInMs:X.expires?X.expires-this.now():void 0});let V=await F2({refreshToken:K,authLineageId:X.authLineageId,fetchImpl:this.fetchImpl,now:this.now});return X.access=V.access,X.refresh=V.refresh,X.authLineageId=V.authLineageId??X.authLineageId,X.expires=V.expires,X.lastRefreshedAt=V.expires-V.expiresIn*1000,X.lastRefreshError=void 0,d(J,X),await this.save(J),H0("[refresh] fallback oauth refresh succeeded",{accountId:X.id,expiresInMs:X.expires?X.expires-this.now():void 0}),X}finally{await Y.release()}}async refreshAccountQuota($,J){let Z=JSON.stringify([$.quota,$.lastQuotaRefreshError]),z=!1,G=$,X=this.isFallbackAccountVaultEnabled(G.id,J),Y=this.resolveFallbackAccessToken(G,J);if(!Y&&!X)G=await this.refreshAccount($,J,{force:!0}),z=!0,Y=this.resolveFallbackAccessToken(G,J);if(!Y)return H0("[quota] fallback quota poll skipped: no usable credential",{accountId:G.id}),{account:G,fetched:!1,changed:z};let K=(Q)=>this.quotaManager?this.quotaManager.refreshFallbackWithMetadata(G.id,Q,G):t1({accessToken:Q,fetchImpl:this.fetchImpl,now:this.now}).then((U)=>({quota:U,fetched:!0})),V=this.now(),W=!1;try{let Q=await K(Y.token);G.quota=Q.quota,W=Q.fetched}catch(Q){if(!(Q instanceof Error?Q.message:String(Q)).includes("Claude quota check failed: 401")||X||Y.source!=="sidecar")throw Q;if(G=await this.refreshAccount($,J,{force:!0}),z=!0,Y=this.resolveFallbackAccessToken(G,J),!Y)return H0("[quota] fallback quota poll skipped after refresh: no usable credential",{accountId:G.id}),{account:G,fetched:!1,changed:z};let B=await K(Y.token);G.quota=B.quota,W=B.fetched}let j=await this.load(),H=j?.accounts.find((Q)=>Q.id===G.id&&E(Q));if(j&&H&&H.access!==G.access)return this.seedFallbackQuota(H,j),d(J,H),{account:H,fetched:!1,changed:!1};if(j&&H&&H.access===G.access&&H.quota&&U0(H.quota)>=V&&Y4(H.quota,j,this.now()))return this.seedFallbackQuota(H,j),d(J,H),{account:H,fetched:W,changed:!1};if(G.lastQuotaRefreshError=void 0,d(J,G),this.quotaManager&&G.quota){let Q=this.now();this.quotaManager.setFallback(G.id,{quota:G.quota,refreshAfter:Q+V0(J),checkedAt:Q},G)}return{account:G,fetched:W,changed:z||JSON.stringify([G.quota,G.lastQuotaRefreshError])!==Z}}}var TG="claude-cache",W4="## Claude Cache Status",J9="## Claude Cache Enabled",Z9="## Claude Cache Disabled",z9="## Claude Cache Usage",G9="Usage: `/claude-cache`, `/claude-cache on`, `/claude-cache off`, or `/claude-cache mode explicit|automatic|hybrid`.",r1=!1,e1=g1;function AG(){return r1}function bG(){return e1}function EG($){r1=$.enabled,e1=$.mode}function X9($){let J=$.trim().split(/\s+/).filter(Boolean);if(J.length===0)return{type:"status"};if(J.length===1&&J[0]==="on")return{type:"enable"};if(J.length===1&&J[0]==="off")return{type:"disable"};if(J.length===2&&J[0]==="mode"&&(J[1]==="explicit"||J[1]==="automatic"||J[1]==="hybrid"))return{type:"mode",mode:J[1]};return{type:"usage"}}function N1($){let J=$?.enabled??r1,Z=$?.mode??e1;return[W4,"",`- Enabled: ${J?"enabled":"disabled"}`,`- Mode: ${Z}`,"- 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 IG($){let J=X9($.argumentsText),Z=$.enabled??r1,z=$.mode??e1;if(J.type==="status")return N1({enabled:Z,mode:z});if(J.type==="enable")return[J9,"",N1({enabled:!0,mode:z})].join(`
8
- `);if(J.type==="disable")return[Z9,"",N1({enabled:!1,mode:z})].join(`
9
- `);if(J.type==="mode")return[W4,"",`Mode updated to \`${J.mode}\`.`,"",N1({enabled:Z,mode:J.mode})].join(`
10
- `);return[z9,"",G9,"",N1({enabled:Z,mode:z})].join(`
11
- `)}import{createHash as K9}from"node:crypto";var Y9=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 j4(){return function($){let{exports:{mem:J,xxh32:Z,xxh64:z,init32:G,update32:X,digest32:Y,init64:K,update64:V,digest64:W}}=$,j=new Uint8Array(J.buffer);function H(N,T){if(J.buffer.byteLength<N+T){let h=Math.ceil((N+T-J.buffer.byteLength)/65536);J.grow(h),j=new Uint8Array(J.buffer)}}function Q(N,T,h,e,x1,M0){H(N);let c=new Uint8Array(N);return j.set(c),h(0,T),c.set(j.subarray(0,N)),{update(o){let D$;return j.set(c),typeof o=="string"?(H(3*o.length,N),D$=q.encodeInto(o,j.subarray(N)).written):(H(o.byteLength,N),j.set(o,N),D$=o.byteLength),e(0,N,D$),c.set(j.subarray(0,N)),this},digest:()=>(j.set(c),M0(x1(0)))}}function U(N){return N>>>0}let B=2n**64n-1n;function O(N){return N&B}let q=new TextEncoder,D=0,L=0n;function x(N,T=D){return H(3*N.length,0),U(Z(0,q.encodeInto(N,j).written,T))}function k(N,T=L){return H(3*N.length,0),O(z(0,q.encodeInto(N,j).written,T))}return{h32:x,h32ToString:(N,T=D)=>x(N,T).toString(16).padStart(8,"0"),h32Raw:(N,T=D)=>(H(N.byteLength,0),j.set(N),U(Z(0,N.byteLength,T))),create32:(N=D)=>Q(48,N,G,X,Y,U),h64:k,h64ToString:(N,T=L)=>k(N,T).toString(16).padStart(16,"0"),h64Raw:(N,T=L)=>(H(N.byteLength,0),j.set(N),O(z(0,N.byteLength,T))),create64:(N=L)=>Q(88,N,K,V,W,O)}}((await WebAssembly.instantiate(Y9)).instance)}var V9=0x4d659218e32a3268n,W9="cch=00000;";var z6=/("system":\[\{"type":"text","text":"x-anthropic-billing-header: cc_version=[^;"]+; cc_entrypoint=[^;"]+; )cch=([0-9a-f]{5});/,j9=/("system":\[\{"type":"text","text":"x-anthropic-billing-header: cc_version=[^;"]+; cc_entrypoint=[^;"]+; )cch=00000;/,H4=null,$$=null;async function Q4(){if($$)return;H4??=(async()=>{$$=(await j4()).h64Raw})(),await H4}function U4($){let J=$.find((z)=>z.role==="user");if(!J)return"";let{content:Z}=J;if(typeof Z==="string")return Z;if(Array.isArray(Z)){let z=Z.filter((Y)=>Y.type==="text"),G=z.find((Y)=>Y.text?.includes("<command-name>"));if(G?.text)return G.text.slice(G.text.indexOf("<command-name>"));let X=z.findLast((Y)=>typeof Y.text==="string"&&Y.text.length>0);if(X?.text)return X.text}return""}class H9{limit;#$=new Map;constructor($=1000){this.limit=$}resolve($,J,Z=!0){let z=this.#$.get($);if(z!==void 0)return this.#$.delete($),this.#$.set($,z),z;let G=U4(J);if(Z){if(!this.#$.has($)&&this.#$.size>=this.limit){let X=this.#$.keys().next().value;if(X!==void 0)this.#$.delete(X)}this.#$.set($,G)}return G}has($){return this.#$.has($)}clear(){this.#$.clear()}}async function Q9($){return await Q4(),(($$?.($,V9)??0n)&0xfffffn).toString(16).padStart(5,"0")}async function gG($){return await Q4(),($$?.(new TextEncoder().encode($),0n)??0n).toString(16).padStart(16,"0").slice(0,16)}function U9($){return $.replace(z6,`$1${W9}`)}function N4($){return z6.exec($)?.[2]??null}async function B4($){if(!z6.test($))return $;let J=U9($),Z=JSON.parse(J);if("model"in Z)Z.model="";delete Z.max_tokens;let z=await Q9(new TextEncoder().encode(JSON.stringify(Z)));return J.replace(j9,`$1cch=${z};`)}function N9($,J=x0){let Z=_2.map((z)=>$[z]??"0").join("");return K9("sha256").update(`${C2}${Z}${J}`).digest("hex").slice(0,3)}function pG($,J=x0,Z,z){let G=N9(z??U4($),J);return`x-anthropic-billing-header: cc_version=${J}.${G}; cc_entrypoint=${Z}; cch=00000;`}import{randomBytes as B9,randomUUID as O4}from"node:crypto";var L9=1000,I=new Map;function Z0($,J,Z,z=L9){if(!$.has(J)&&$.size>=z){let G=$.keys().next().value;if(G!==void 0)$.delete(G)}$.set(J,Z)}function L4($,J){if(!J.accountUuid)return J;if(I.get($)!==J)return{...J,accountUuid:void 0};let Z={...J,accountUuid:void 0};return Z0(I,$,Z),Z}function G6($){let J=$||"anonymous",Z=I.get(J);if(Z)return Z;let z={deviceId:B9(32).toString("hex"),sessionId:O4()};return Z0(I,J,z),z}var C9=86400000,_9=300000,J$=new Map,C4=new Map;function O9($){return`compat:${$||"anonymous"}`}function M4($){return`identity:${$}`}function X6($,J){return`account:${$}:${J}`}function Z$($,J,Z){if(!$)return;if($.accountIdentity!==void 0&&$.accountIdentity!==J)return;if(Z!==void 0&&$.accountUuid!==void 0&&$.accountUuid!==Z)return;if($.accountIdentity===J&&(Z===void 0||$.accountUuid===Z))return $;return{...$,accountIdentity:J,...Z!==void 0&&{accountUuid:Z}}}function z$($,J,Z){Z0(I,M4(J),$),Z0(I,X6(Z,J),$)}async function M9($,J){if(!$.startsWith("sk-ant-oat"))return null;let Z=new AbortController,z=setTimeout(()=>Z.abort(),5000);try{let G=new URL("https://api.anthropic.com/api/claude_cli/bootstrap");if(G.searchParams.set("entrypoint",O2),J)G.searchParams.set("model",J);let X=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/${x0}`},signal:Z.signal});if(!X.ok)return null;let K=(await X.json().catch(()=>null))?.oauth_account?.account_uuid;return typeof K==="string"&&K?K:null}catch{return null}finally{clearTimeout(z)}}async function dG($,J,Z){let z=Z?.trim()||void 0,G=z?M4(z):O9($),X;if(z)X=Z$(I.get(G)??I.get($),z)??G6(G),X=Z$(X,z)??X,Z0(I,G,X);else X=I.get(G)??I.get($)??G6(G),Z0(I,G,X),Z0(I,$,X);if(!$.startsWith("sk-ant-oat"))return X;let Y=Date.now(),K=`${G}:${$}`,V=C4.get(K);if(V&&V.expiresAt>Y){if(!V.accountUuid)return X=L4(G,X),X;if(!z){if(X.accountUuid===V.accountUuid)return X;return X={...X,accountUuid:V.accountUuid},Z0(I,K,X),X}let Q=Z$(I.get(X6(V.accountUuid,z))??I.get(`account:${V.accountUuid}`),z,V.accountUuid);if(Q)return X=Q,z$(X,z,V.accountUuid),X;if(X.accountUuid===V.accountUuid)return X;return X={...X,accountIdentity:z,accountUuid:V.accountUuid},z$(X,z,V.accountUuid),X}let W=J$.get(K);if(!W)W=M9($,J),Z0(J$,K,W);let j=await W.finally(()=>{if(J$.get(K)===W)J$.delete(K)});if(Z0(C4,K,{accountUuid:j,expiresAt:Y+(j?C9:_9)}),!j)return X=L4(G,X),X;if(!z)return X={...X,accountUuid:j},Z0(I,K,X),X;let H=Z$(I.get(X6(j,z))??I.get(`account:${j}`),z,j);if(H)return X=H,z$(X,z,j),X;return X={...X,accountIdentity:z,accountUuid:j},z$(X,z,j),X}function I0($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function q9($){if(!$.accountUuid)return null;return JSON.stringify({device_id:$.deviceId,account_uuid:$.accountUuid,session_id:$.sessionId})}function iG($,J){let Z=q9(J);if(!Z){if(I0($.metadata))delete $.metadata.user_id;return!1}if(!I0($.metadata))$.metadata={};let z=$.metadata;if(I0(z))z.user_id=Z;return!0}var D9=["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"],x9=["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"],_4=["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 R9($){return $.output_config?.format?.type==="json_schema"}function f9($){return Array.isArray($.tools)&&$.tools.length>0&&Array.isArray($.system)&&I0($.thinking)&&I0($.context_management)&&I0($.output_config)&&I0($.diagnostics)}function w9($,J=[]){let Z=$?f9($)?[...D9]:R9($)?[...x9]:[..._4]:[..._4];if($?.speed==="fast")Z.push(L2);for(let z of J){let G=z.trim();if(G)Z.push(G)}return[...new Set(Z)].join(",")}function P9(){switch(process.platform){case"darwin":return"MacOS";case"win32":return"Windows";case"linux":return"Linux";case"freebsd":return"FreeBSD";default:return"Unknown"}}function F9(){switch(process.arch){case"arm64":return"arm64";case"x64":return"x64";case"ia32":return"x32";default:return process.arch}}function cG($,J,Z={}){let z=Z.identity??G6(J),X=[...($.get("anthropic-beta")??"").split(",").map((Y)=>Y.trim()).filter(Boolean),...Z.extraBetas??[]];return $.set("accept","application/json"),$.set("authorization",`Bearer ${J}`),$.set("content-type","application/json"),$.set("user-agent",D2),$.set("anthropic-beta",w9(Z.body,X)),$.set("anthropic-dangerous-direct-browser-access","true"),$.set("anthropic-version","2023-06-01"),$.set("x-app","cli"),$.set("x-client-request-id",O4()),$.set("x-claude-code-session-id",z.sessionId),$.set("x-stainless-arch",F9()),$.set("x-stainless-lang","js"),$.set("x-stainless-os",P9()),$.set("x-stainless-package-version",M2),$.set("x-stainless-retry-count","0"),$.set("x-stainless-runtime","node"),$.set("x-stainless-runtime-version",q2),$.set("x-stainless-timeout","600"),$.delete("x-api-key"),$}var S9=["model","messages","system","tools","tool_choice","metadata","max_tokens","temperature","thinking","context_management","output_config","diagnostics","stream","speed"];function q4($){let J={};for(let Z of S9)if(Object.hasOwn($,Z))J[Z]=$[Z];for(let[Z,z]of Object.entries($))if(!Object.hasOwn(J,Z))J[Z]=z;return J}import{createHash as T9,randomBytes as A9}from"node:crypto";import{lstat as K6,mkdir as b9,readdir as w4,readFile as D4,rename as E9,unlink as P4,writeFile as I9}from"node:fs/promises";import{tmpdir as k9}from"node:os";import{join as V$,resolve as L1}from"node:path";var ZX="claude-dump",v9="## Claude Dump Status",h9="## Claude Dump Enabled",y9="## Claude Dump Disabled",m9="## Claude Dump Usage",g9="Usage: `/claude-dump`, `/claude-dump on`, or `/claude-dump off`.",p9="OPENCODE_ANTHROPIC_AUTH_DUMP_DIR",l9="OPENCODE_ANTHROPIC_AUTH_DUMP_MAX_BYTES",u9=V$(k9(),"opencode-anthropic-auth-dumps"),s9=536870912,d9=300000,i9=60000,c9=600000,j6=/\.(body|meta|relay|request|response)\.json$/,F4=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d{5,}-(.+)$/,X$="[a-zA-Z0-9._-]",S4=new RegExp(`^${X$}{1,80}-direct(?:-${X$}{1,80})?$`),T4=new RegExp(`^${X$}{1,80}-(?:http|websocket)-p[12]-(?:full_sync|patch)$`),n9=new RegExp(`^-direct(?:-${X$}{1,80})?$`),a9=/^-(?:http|websocket)-p[12]-(?:full_sync|patch)$/,C1=!1,x4=0,R4=0,o9=100,n0=new Map;function zX($){C1=$}function _1(){return process.env[p9]||u9}function t9(){let $=Number(process.env[l9]);return Number.isFinite($)&&$>=0?Math.floor($):s9}function r9($){return L1($)===L1(_1())}function V6($){let J=$.replace(j6,"");if(J===$)return!1;let z=F4.exec(J)?.[1];if(!z)return!1;return S4.test(z)||T4.test(z)}function e9($){if(!$.endsWith(".partial"))return!1;let J=$.slice(0,-8);if(V6(J))return!0;let Z=J.lastIndexOf(".");if(Z<0)return!1;let z=J.slice(Z+1);return/^[a-f0-9]{24}$/.test(z)&&V6(J.slice(0,Z))}async function B1($,J){for(let Z=0;Z<2;Z+=1){let z=A9(12).toString("hex"),G=`${$}.${z}.partial`,X=!1;try{return await I9(G,J,{encoding:"utf8",flag:"wx"}),X=!0,await E9(G,$),!0}catch(Y){if(Y.code==="EEXIST")continue;if(X)await P4(G).catch(()=>{});throw Y}}return!1}async function $7($){let J=$.dumpDir??_1(),Z=$.maxBytes??t9(),z=$.now??Date.now(),G=$.minAgeMs??i9,X=$.partialStaleMs??c9,Y={removed:0,freedBytes:0};if(!r9(J)||Z<=0)return Y;try{if((await K6(J)).isSymbolicLink())return Y;let V=new Set(($.protectedPaths??[]).map((L)=>L1(L))),W=await w4(J,{withFileTypes:!0}),j=[];await Promise.all(W.map(async(L)=>{if(!L.isFile())return;let x=e9(L.name);if(!x&&!V6(L.name))return;let k=V$(J,L.name);try{let N=await K6(k);if(!N.isFile()||N.isSymbolicLink())return;j.push({path:k,size:N.size,mtimeMs:N.mtimeMs,partial:x,...!x&&{artifactGroup:L.name.replace(j6,"")}})}catch{}}));let H=j.reduce((L,x)=>L+x.size,0),Q=0,U=0,B=async(L)=>{try{await P4(L.path),H-=L.size,U+=L.size,Q+=1}catch{}},O=j.filter((L)=>L.partial).sort((L,x)=>L.mtimeMs-x.mtimeMs||L.path.localeCompare(x.path));for(let L of O){if(V.has(L1(L.path)))continue;if(z-L.mtimeMs<X)continue;await B(L)}let q=new Map;for(let L of j){if(L.partial||!L.artifactGroup)continue;let x=q.get(L.artifactGroup)??{files:[],newestMtimeMs:0};x.files.push(L),x.newestMtimeMs=Math.max(x.newestMtimeMs,L.mtimeMs),q.set(L.artifactGroup,x)}let D=[...q.entries()].sort(([L,x],[k,N])=>x.newestMtimeMs-N.newestMtimeMs||L.localeCompare(k));for(let[,L]of D){if(H<=Z)break;if(z-L.newestMtimeMs<G)continue;if(L.files.some((x)=>V.has(L1(x.path))))continue;for(let x of L.files)await B(x)}if(Q>0)M.debug("dump","removed old dump files",{removed:Q,freedBytes:U});return{removed:Q,freedBytes:U}}catch{return Y}}function J7($,J){let Z=Date.now();if(Z-R4<d9)return;R4=Z,$7({dumpDir:$,protectedPaths:J}).catch(()=>{})}function Z7($){let J=$.trim().split(/\s+/).filter(Boolean);if(J.length===0)return{type:"status"};if(J.length===1&&J[0]==="on")return{type:"enable"};if(J.length===1&&J[0]==="off")return{type:"disable"};return{type:"usage"}}function G$($){let J=$?.enabled??C1;return[v9,"",`- Enabled: ${J?"enabled":"disabled"}`,`- Directory: ${_1()}`,"- 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 GX($){let J=Z7($.argumentsText),Z=$.enabled??C1;if(J.type==="status")return G$({enabled:Z});if(J.type==="enable")return[h9,"",G$({enabled:!0})].join(`
13
- `);if(J.type==="disable")return[y9,"",G$({enabled:!1})].join(`
14
- `);return[m9,"",g9,"",G$({enabled:Z})].join(`
15
- `)}function W6($){return $.length<=16?$:`${$.slice(0,12)}…`}function Y$($,J=80){let Z=$.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!Z)return"session-unknown";return Z.length<=J?Z:Z.slice(0,J)}function z7($){if($.transport!=="direct")return`${$.transport}-p${$.protocol}-${$.mode}`;return`direct${$.route?`-${Y$($.route)}`:""}`}function A4($){if($==="cachekeep")return"-prewarm-cachekeep";if($==="start")return"-start";return""}function G7($){let J=$.affinity?.trim();if(J)return`session:${J}`;return`request:${$.route??"direct"}:${$.url??""}`}function X7($,J){if(!$.endsWith(".body.json"))return;let Z=$.replace(j6,""),z=F4.exec(Z)?.[1];if(!z||!S4.test(z)&&!T4.test(z))return;let G=A4("cachekeep"),X=[{prefix:Y$(J),tag:null},{prefix:`${Y$(J,80-G.length)}${G}`,tag:"cachekeep"}];for(let Y of X){if(!z.startsWith(`${Y.prefix}-`))continue;let K=z.slice(Y.prefix.length);if(n9.test(K)||a9.test(K))return Y.tag}return}async function Y7($){let J=$.affinity?.trim();if(!J)return;let Z=_1(),z;try{z=await w4(Z)}catch{return}let G=z.map((X)=>({name:X,tag:X7(X,J)})).filter((X)=>X.tag!==void 0).sort((X,Y)=>Y.name.localeCompare(X.name));for(let X of G)try{let Y=V$(Z,X.name),K=Y.replace(/\.body\.json$/,".meta.json");if(!(await K6(Y)).isFile())continue;let V=JSON.parse(await D4(K,"utf8"));if(V.session!==W6(J)||(X.tag===null?V.tag!=null:V.tag!==X.tag))continue;return await D4(Y,"utf8")}catch{}return}function K7($,J){if(!n0.has($))while(n0.size>=o9){let Z=n0.keys().next().value;if(Z===void 0)break;n0.delete(Z)}n0.set($,J)}function V7($){if($==null)return;return Object.fromEntries(new Headers($).entries())}function b4($){return T9("sha256").update($).digest("hex")}function W7($){return N4($)}function j7($,J){if($==null)return null;if($===J)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:$.length,currentBytes:J.length};let Z=0;while(Z<$.length&&Z<J.length&&$[Z]===J[Z])Z+=1;let z=$.length-1,G=J.length-1;while(z>=Z&&G>=Z&&$[z]===J[G])z-=1,G-=1;return{changed:!0,firstByte:Z,lastPreviousByte:z,lastCurrentByte:G,changedPreviousBytes:z-Z+1,changedCurrentBytes:G-Z+1,previousBytes:$.length,currentBytes:J.length}}function H7($){try{let J=p1($);return J!=null&&typeof J==="object"&&!Array.isArray(J)?J:null}catch(J){return S(`dump body parse failed: ${J instanceof Error?J.message:String(J)}`),null}}function Y6($){return b4(JSON.stringify($))}function Q7($){let J=H7($);if(!J)return{parseable:!1};let Z=Array.isArray(J.messages)?J.messages:[],z=Array.isArray(J.system)?J.system:[],G=Z[0],X=Z.slice(1);return{parseable:!0,model:typeof J.model==="string"?J.model:void 0,stream:J.stream,systemCount:z.length,messagesCount:Z.length,systemHash:Y6(z),message0Hash:G===void 0?null:Y6(G),message0Bytes:G===void 0?0:JSON.stringify(G).length,messagesAfter0Hash:Y6(X),messagesAfter0Bytes:JSON.stringify(X).length,cch:W7($)}}function K$($){if(Array.isArray($))return $.map(K$);if($==null||typeof $!=="object")return $;let J={};for(let[Z,z]of Object.entries($)){let G=Z.toLowerCase();if(G==="authorization"||G==="x-api-key"||G==="cookie"||G==="set-cookie"||f4(Z)){J[Z]="[redacted]";continue}J[Z]=K$(z)}return J}async function E4($){if(!C1)return null;x4+=1;let J=$.affinity?.trim()||"session-unknown",Z=A4($.tag),z=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(x4).padStart(6,"0")}-${Y$(J,80-Z.length)}${Z}-${z7($)}`,G=_1(),X=V$(G,z),Y={body:`${X}.body.json`,metadata:`${X}.meta.json`,response:`${X}.response.json`};if($.payload!==void 0)Y.relay=`${X}.relay.json`;if($.request!==void 0)Y.request=`${X}.request.json`;try{await b9(G,{recursive:!0});let K=$.previousBodyText??await Y7($),V={id:z,createdAt:new Date().toISOString(),session:W6(J),transport:$.transport,protocol:$.protocol,mode:$.mode,route:$.route,status:$.status,error:$.error,tag:$.tag,bodyBytes:$.bodyText.length,relayBytes:$.relayBytes,bodyHash:b4($.bodyText),diff:j7(K,$.bodyText),body:Q7($.bodyText),files:Y},W=[B1(Y.body,$.bodyText),B1(Y.metadata,`${JSON.stringify(V,null,2)}
16
- `)];if($.payload!==void 0&&Y.relay)W.push(B1(Y.relay,`${JSON.stringify(K$($.payload),null,2)}
17
- `));if($.request!==void 0&&Y.request)W.push(B1(Y.request,`${JSON.stringify(K$({...$.request,headers:V7($.request.headers)}),null,2)}
18
- `));await Promise.all(W),J7(G,Object.values(Y)),S(`dumped request id=${z} session=${W6(J)} body=${Y.body} meta=${Y.metadata}`)}catch(K){return S(`dump failed: ${K instanceof Error?K.message:String(K)}`),null}return{responsePath:Y.response,...$.tag?{tag:$.tag}:{}}}async function I4($){if(!C1)return null;let J=G7($),Z=n0.get(J),z=await E4({affinity:$.affinity,transport:"direct",route:$.route,status:$.status,error:$.error,bodyText:$.bodyText,previousBodyText:Z,request:{url:$.url,method:$.method,headers:$.headers},tag:$.tag});return K7(J,$.bodyText),z}async function k4($){return E4({affinity:$.affinity,transport:$.transport,protocol:$.protocol,mode:$.mode,status:$.status,bodyText:$.bodyText,previousBodyText:$.previousBodyText,payload:$.payload,relayBytes:$.relayBytes,tag:$.tag})}async function v4($,J){if(!$)return;let Z=J.message!=null&&typeof J.message==="object"&&!Array.isArray(J.message)?J.message:{},z={status:J.status,stream_complete:J.complete??!0};if(typeof Z.id==="string"&&Z.id.length>0)z.message_id=Z.id;if(typeof Z.model==="string"&&Z.model.length>0)z.model=Z.model;if(Object.hasOwn(Z,"usage"))z.usage=Z.usage;if(Object.hasOwn(Z,"diagnostics"))z.diagnostics=Z.diagnostics;if(typeof Z.stop_reason==="string"&&Z.stop_reason.length>0)z.stop_reason=Z.stop_reason;try{await B1($.responsePath,`${JSON.stringify(z,null,2)}
19
- `)}catch(G){S(`dump response failed: ${G instanceof Error?G.message:String(G)}`)}}var jX="claude-cachekeep",H6=3600000,h4=300000,U7=60000,HX="extended-cache-ttl-2025-04-11",N7=32,y4=16777216,B7=30000,L7=60000,C7=900000,_7=30000,m4="## Claude Cache Keep Status",g4="## Claude Cache Keep Enabled",O7="## Claude Cache Keep Disabled",M7="## Claude Cache Keep Usage",q7="Usage: `/claude-cachekeep`, `/claude-cachekeep always`, `/claude-cachekeep off`, or `/claude-cachekeep HH-HH`.";function W$($){return String($).padStart(2,"0")}function D7($){let J=$.trim();if(!J)return{type:"status"};if(J==="off")return{type:"disable"};if(J==="always")return{type:"always"};if(J==="subagents on")return{type:"subagents",enabled:!0};if(J==="subagents off")return{type:"subagents",enabled:!1};let Z=/^(\d{1,2})-(\d{1,2})$/.exec(J);if(!Z)return{type:"usage"};let z=Number(Z[1]),G=Number(Z[2]);if(!Number.isInteger(z)||!Number.isInteger(G)||z<0||z>23||G<0||G>23||z===G)return{type:"usage"};return{type:"window",startHour:z,endHour:G}}function j$($){let J=Number($?.cacheKeep?.startHour),Z=Number($?.cacheKeep?.endHour);if(!Number.isInteger(J)||!Number.isInteger(Z)||J<0||J>23||Z<0||Z>23||J===Z)return;return{startHour:J,endHour:Z}}function H$($){return $?.cacheKeep?.enabled===!0&&$.cacheKeep.always===!0}function d4($){return $?.cacheKeep?.enabled===!0&&(H$($)||!!j$($))}function x7($){return d4($)&&$?.claudeCache?.enabled===!0&&$.claudeCache.mode==="hybrid"}function R7($,J=new Date){if(!$)return!1;let Z=J.getHours();if($.startHour<$.endHour)return Z>=$.startHour&&Z<$.endHour;return Z>=$.startHour||Z<$.endHour}function p4($,J=new Date){if($?.cacheKeep?.enabled!==!0)return!1;return H$($)||R7(j$($),J)}function l4($=new Date){return`${$.getFullYear()}-${W$($.getMonth()+1)}-${W$($.getDate())}`}function i4($,J=new Date){if($&&$.startHour>$.endHour&&J.getHours()<$.endHour){let Z=new Date(J);return Z.setDate(Z.getDate()-1),l4(Z)}return l4(J)}function u4($,J,Z=new Date){return H$($)?"always":i4(J,Z)}function a0($){let J=$.always?"always (while this process is running)":$.window?`${W$($.window.startHour)}-${W$($.window.endHour)}`:"not configured",Z=[`Cache keep: ${$.enabled?"enabled":"disabled"}`,`Schedule: ${J}`,"Mode requirement: `/claude-cache mode hybrid` must be active."];if(typeof $.hybridActive==="boolean")Z.push(`Hybrid active: ${$.hybridActive?"yes":"no"}`);if(typeof $.trackedSessions==="number")Z.push(`Tracked sessions: ${$.trackedSessions}`);if($.trackedSessionDetails?.length){Z.push("Sessions:");for(let z of $.trackedSessionDetails)Z.push(`- ${z.id}`)}if($.nextPrewarmAt)Z.push(`Next prewarm: ${new Date($.nextPrewarmAt).toLocaleString()}`);return Z.join(`
20
- `)}function QX($){let J=D7($.argumentsText),Z={enabled:$.enabled??!1,always:$.always,window:$.window,trackedSessions:$.trackedSessions,trackedSessionDetails:$.trackedSessionDetails,nextPrewarmAt:$.nextPrewarmAt,hybridActive:$.hybridActive};if(J.type==="status")return[m4,"",a0(Z)].join(`
21
- `);if(J.type==="disable")return[O7,"",a0({...Z,enabled:!1})].join(`
22
- `);if(J.type==="always")return[g4,"",a0({...Z,enabled:!0,always:!0,window:void 0})].join(`
23
- `);if(J.type==="window")return[g4,"",a0({...Z,enabled:!0,always:!1,window:{startHour:J.startHour,endHour:J.endHour}})].join(`
24
- `);if(J.type==="subagents")return[m4,"",a0(Z),"",`Subagent tracking: ${J.enabled?"enabled":"disabled"}`].join(`
25
- `);return[M7,"",q7,"",a0(Z)].join(`
26
- `)}function Q6($){if(!$||typeof $!=="object")return!1;if(Array.isArray($))return $.some(Q6);let J=$,Z=J.cache_control;if(Z&&typeof Z==="object"&&Z.type==="ephemeral")return!0;return Object.values(J).some(Q6)}async function f7($){let J;try{J=JSON.parse($)}catch{return{ok:!1,reason:"body is not valid JSON"}}if(!Q6(J))return{ok:!1,reason:"body has no explicit cache breakpoints"};let Z=structuredClone(J);if(Z.max_tokens=0,delete Z.stream,Z.thinking?.type==="enabled")delete Z.thinking;if(Z.output_config?.format)delete Z.output_config;let X=Z.tool_choice;if(X?.type==="tool"||X?.type==="any")delete Z.tool_choice;return{ok:!0,bodyText:await B4(JSON.stringify(q4(Z)))}}function s4($,J){let Z=Math.min(C7,L7*2**Math.min(Math.max(J-1,0),8)),z=2166136261;for(let X of`${$}:${J}`)z^=X.charCodeAt(0),z=Math.imul(z,16777619);let G=(z>>>0)%(Math.min(_7,Z/4)+1);return Z+G}class w7{options;targets=new Map;timer=null;tickPromise=null;constructor($){this.options=$}start(){if(this.timer)return;if(M.debug("cachekeep","started"),this.timer=(this.options.setIntervalImpl??globalThis.setInterval)(()=>{this.tick().catch(($)=>{M.warn("cachekeep","tick failed",{error:$ instanceof Error?$.message:String($)})})},U7),"unref"in this.timer)this.timer.unref()}stop(){if(!this.timer)return;M.debug("cachekeep","stopped"),(this.options.clearIntervalImpl??globalThis.clearInterval)(this.timer),this.timer=null}stats($,J=this.options.now?.()??Date.now(),Z=!1){let z=Z?"always":i4($,new Date(J)),G=[...this.targets.values()].filter((Y)=>Y.dayKey===z),X=G.length?Math.min(...G.map((Y)=>Y.nextPrewarmAt)):void 0;return{trackedSessions:G.length,nextPrewarmAt:X}}trackedSessions(){return[...this.targets.values()].map(($)=>({id:$.id,cacheExpiresAt:$.cacheExpiresAt,nextPrewarmAt:$.nextPrewarmAt})).sort(($,J)=>$.id.localeCompare(J.id))}trackedOAuthRoute($){let J=this.targets.get($);return J?{oauthAccountId:J.oauthAccountId}:void 0}trackedCount(){return this.targets.size}publishTrackedSessions(){let $=this.options.onTrackedSessionsChanged;if(!$)return;try{Promise.resolve($(this.trackedSessions())).catch((J)=>{M.warn("cachekeep","failed to publish tracked sessions",{error:J instanceof Error?J.message:String(J)})})}catch(J){M.warn("cachekeep","failed to publish tracked sessions",{error:J instanceof Error?J.message:String(J)})}}totalBodyBytes(){return[...this.targets.values()].reduce(($,J)=>$+J.bodyText.length,0)}evictOldestTarget(){let $=this.targets.keys().next().value;if($!==void 0)this.targets.delete($)}pruneTargets($,J){for(let[Z,z]of this.targets){if(J&&z.dayKey!==J){this.targets.delete(Z);continue}if($>=z.cacheExpiresAt)this.targets.delete(Z)}while(this.targets.size>N7)this.evictOldestTarget();while(this.totalBodyBytes()>y4){let Z=this.targets.size;if(this.evictOldestTarget(),this.targets.size===Z)break}}track($){if(!$.sessionId)return{tracked:!1,reason:"missing session id"};if(!d4($.storage))return{tracked:!1,reason:"cachekeep disabled"};if($.cacheMode!=="hybrid")return{tracked:!1,reason:"cache mode is not hybrid"};if($.bodyText.length>y4)return{tracked:!1,reason:"body exceeds cachekeep memory budget"};let J=this.options.now?.()??Date.now(),Z=j$($.storage);if(!p4($.storage,new Date(J)))return{tracked:!1,reason:"outside configured schedule"};let z=u4($.storage,Z,new Date(J));if(this.pruneTargets(J,z),this.targets.has($.sessionId))this.targets.delete($.sessionId);let G={};return $.headers.forEach((X,Y)=>{G[Y]=X}),this.targets.set($.sessionId,{id:$.sessionId,url:$.url,headers:G,bodyText:$.bodyText,cacheExpiresAt:J+H6,nextPrewarmAt:J+H6-h4,consecutiveFailures:0,dayKey:z,oauthAccountId:$.oauthAccountId,isSubagent:$.isSubagent??!1}),this.pruneTargets(J,z),this.publishTrackedSessions(),this.start(),{tracked:!0}}async prewarmNow($){let J={};$.headers.forEach((z,G)=>{J[G]=z});let Z={id:$.sessionId,url:$.url,headers:J,bodyText:$.bodyText,cacheExpiresAt:this.options.now?.()??Date.now(),nextPrewarmAt:this.options.now?.()??Date.now(),consecutiveFailures:0,dayKey:"",oauthAccountId:$.oauthAccountId,isSubagent:$.isSubagent??!1};return this.sendPrewarm(Z)}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(),J=j$($),Z=this.options.now?.()??Date.now(),z=u4($,J,new Date(Z));if(H$($))for(let G of this.targets.values())G.dayKey="always";if(this.pruneTargets(Z,z),!this.targets.size){this.publishTrackedSessions(),this.stop();return}if(!x7($)){this.publishTrackedSessions();return}if(!p4($,new Date(Z))){this.publishTrackedSessions();return}M.debug("cachekeep","fired",{targets:this.targets.size});for(let G of this.targets.values()){if(G.nextPrewarmAt>Z)continue;try{await this.prewarm(G,Z)}catch(X){M.warn("cachekeep","prewarm failed",{session:G.id,reason:X instanceof Error?X.message:String(X)}),G.consecutiveFailures+=1,G.nextPrewarmAt=Z+s4(G.id,G.consecutiveFailures)}}this.publishTrackedSessions()}async sendPrewarm($){let J=$.bodyText;if(this.options.prepareBody)try{J=await this.options.prepareBody(J,$)}catch(U){M.warn("cachekeep","prepare body failed",{session:$.id,error:U instanceof Error?U.message:String(U)})}let Z={...$,bodyText:J},z=await f7(J);if(!z.ok)return z;let G=this.options.fetchImpl??fetch,X={...Z,bodyText:z.bodyText},Y=this.options.prepareHeaders?await this.options.prepareHeaders(new Headers($.headers),X):new Headers($.headers);Y.delete("content-length"),Y.delete("transfer-encoding");let K;try{K=await G($.url,{method:"POST",headers:Y,body:z.bodyText,signal:AbortSignal.timeout(this.options.prewarmTimeoutMs??B7)})}catch(U){return{ok:!1,reason:U instanceof Error?U.message:String(U),transient:!0}}let V=this.options.now?.()??Date.now(),W=await K.text().catch(()=>""),j=null;try{j=W?JSON.parse(W):null}catch{}try{await this.options.onResponse?.({target:$,bodyText:z.bodyText,status:K.status,data:j,receivedAt:V})}catch{}try{let U=await I4({affinity:$.id,route:"cachekeep",status:K.status,bodyText:z.bodyText,url:$.url,method:"POST",headers:Y,tag:"cachekeep"});await v4(U,{status:K.status,message:j})}catch(U){M.debug("cachekeep","dump failed",{session:$.id,error:U instanceof Error?U.message:String(U)})}if(!K.ok)return{ok:!1,reason:W||`HTTP ${K.status}`,status:K.status};let Q=(j&&typeof j==="object"&&!Array.isArray(j)?j:null)?.usage;return{ok:!0,...Q&&{usage:Q}}}async prewarm($,J){let Z=await this.sendPrewarm($);if(!Z.ok){if(Z.status==null&&!Z.transient)M.debug("cachekeep","prewarm skipped",{session:$.id,reason:Z.reason}),this.targets.delete($.id);else M.warn("cachekeep","prewarm failed",{session:$.id,status:Z.status,reason:Z.reason}),$.consecutiveFailures+=1,$.nextPrewarmAt=J+s4($.id,$.consecutiveFailures);return}$.cacheExpiresAt=J+H6,$.nextPrewarmAt=$.cacheExpiresAt-h4,$.consecutiveFailures=0,M.debug("cachekeep","prewarm succeeded",{session:$.id,...Z.usage&&{usage:Z.usage}})}}import{randomUUID as c4}from"node:crypto";import{mkdir as P7,readdir as F7,readFile as S7,rename as T7,rm as n4,writeFile as A7}from"node:fs/promises";import{tmpdir as b7}from"node:os";import{join as U6}from"node:path";var E7=180000;function I7($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(typeof J.id!=="string"||J.id.length===0||typeof J.cacheExpiresAt!=="number"||!Number.isFinite(J.cacheExpiresAt)||typeof J.nextPrewarmAt!=="number"||!Number.isFinite(J.nextPrewarmAt))return;return{id:J.id,cacheExpiresAt:J.cacheExpiresAt,nextPrewarmAt:J.nextPrewarmAt}}function k7($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(J.version!==1||typeof J.updatedAt!=="number"||!Number.isFinite(J.updatedAt)||!Array.isArray(J.sessions))return;return{version:1,updatedAt:J.updatedAt,sessions:J.sessions.flatMap((Z)=>{let z=I7(Z);return z?[z]:[]})}}function _X($){return U6(b7(),"opencode-anthropic-auth","cachekeep-sessions",$)}class v7{options;filePath;writeChain=Promise.resolve();constructor($){this.options=$;let J=$.instanceId??`${process.pid}-${c4()}`;this.filePath=U6($.directory,`${J}.json`)}publish($){let J=$.map((Z)=>({...Z}));return this.writeChain=this.writeChain.catch(()=>{}).then(async()=>{if(J.length===0){await n4(this.filePath,{force:!0});return}await P7(this.options.directory,{recursive:!0,mode:448});let Z=`${this.filePath}.${c4()}.tmp`,z={version:1,updatedAt:this.options.now?.()??Date.now(),sessions:J};await A7(Z,`${JSON.stringify(z)}
27
- `,{mode:384}),await T7(Z,this.filePath)}),this.writeChain}async list($=[]){await this.writeChain.catch(()=>{});let J=this.options.now?.()??Date.now(),Z=this.options.leaseMs??E7,z;try{z=(await F7(this.options.directory)).filter((Y)=>Y.endsWith(".json"))}catch{z=[]}let G=await Promise.all(z.map(async(Y)=>{try{let K=await S7(U6(this.options.directory,Y),"utf8");return k7(JSON.parse(K))}catch{return}})),X=new Map;for(let Y of G){if(!Y||J-Y.updatedAt>Z||Y.updatedAt>J)continue;for(let K of Y.sessions){let V=X.get(K.id);if(!V||K.cacheExpiresAt>V.cacheExpiresAt)X.set(K.id,K)}}for(let Y of $){let K=X.get(Y.id);if(!K||Y.cacheExpiresAt>K.cacheExpiresAt)X.set(Y.id,{...Y})}return[...X.values()].sort((Y,K)=>Y.id.localeCompare(K.id))}async dispose(){await this.writeChain.catch(()=>{}),await n4(this.filePath,{force:!0})}}async function MX($){let J=await($.fetchImpl??fetch)("https://api.anthropic.com/api/oauth/profile",{method:"GET",signal:$.signal,headers:{Authorization:`Bearer ${$.accessToken}`,Accept:"application/json","anthropic-beta":"oauth-2025-04-20"}});if(!J.ok)throw Error(`Claude profile check failed: ${J.status}`);let Z=await J.json(),z=Z.organization?.rate_limit_tier,G=Z.organization?.organization_type;if(typeof z!=="string"||z.trim()===""||typeof G!=="string"||G.trim()==="")throw Error("Claude profile response is missing account metadata");return{tier:z,orgType:G,checkedAt:$.now?.()??Date.now(),...$.accountIdentity!==void 0&&{accountIdentity:$.accountIdentity}}}function qX($,J){if(!$)return!1;if(J===void 0)return!0;return $.accountIdentity===void 0||$.accountIdentity===J}function DX($,J=Date.now()){return Boolean($&&Number.isFinite($.checkedAt)&&J>=$.checkedAt&&J-$.checkedAt<604800000)}function o0($){let J=$?.tier.match(/^default_claude_max_(\d+)x$/);if(!J)return;let Z=`Max ${J[1]}x`;return $?.orgType==="claude_team"?`Team · ${Z}`:Z}var wX="claude-account";function h7($){let J=$.trim().split(/\s+/).filter(Boolean);if(J.length===0)return{type:"status"};let Z=J[0],z=J.slice(1).join(" ");if(Z==="enable"&&z)return{type:"enable",id:z};if(Z==="disable"&&z)return{type:"disable",id:z};if(Z==="remove"&&z)return{type:"remove",id:z};if(Z==="move-up"&&z)return{type:"move-up",id:z};if(Z==="move-down"&&z)return{type:"move-down",id:z};if(Z==="reset-backoff"&&!z)return{type:"reset-backoff"};if(Z==="add-apikey"&&z){let G=z,X,Y,K=G.match(/--base-url\s+(\S+)/);if(K)X=K[1],G=G.replace(K[0],"").trim();let V=G.match(/--auth-header\s+(authorization-bearer|x-api-key)/);if(V)Y=V[1],G=G.replace(V[0],"").trim();let W,j=G.match(/--label\s+(.+)/);if(j)W=j[1]?.trim()||void 0,G=G.replace(j[0],"").trim();let H=G.indexOf(" ");if(H===-1){if(!G)return{type:"usage"};return{type:"add-apikey",apiKey:G,baseURL:X,authHeader:Y,label:W}}let Q=G.slice(0,H),U=G.slice(H+1).trim();return{type:"add-apikey",apiKey:Q,label:W??(U||void 0),baseURL:X,authHeader:Y}}if(Z==="add-oauth-start")return{type:"add-oauth-start"};if(Z==="add-oauth-finish"&&z){let G=z,X,Y=G.match(/--label\s+(.+)/);if(Y)X=Y[1]?.trim()||void 0,G=G.replace(Y[0],"").trim();if(!G)return{type:"usage"};return{type:"add-oauth-finish",code:G,label:X}}return{type:"usage"}}function y7($){let J=[],Z=$.quota?.mainQuota?.five_hour;J.push({id:"main",label:$.main?.provider==="anthropic"?"OpenCode anthropic":"Main",role:"main",enabled:!0,quotaPercent:Z?.usedPercent??null,tierLabel:o0($.main?.profile)});for(let z of $.accounts){let G=z.quota?.five_hour;J.push({id:z.id,label:z.label??z.id,role:"fallback",enabled:z.enabled!==!1,quotaPercent:G?.usedPercent??null,tierLabel:z.type==="oauth"?o0(z.profile):void 0})}return J}var N6=["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 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 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(`
28
- `);function PX($){let J=h7($.argumentsText),Z=$.storage.accounts,z="main";if(J.type==="status"){let X=y7($.storage),K=["## Claude Accounts","",`- Claustrum: ${$.claustrum?.status??"unknown"}`,""];for(let V of X){let W=V.quotaPercent!=null?` ${Math.round(V.quotaPercent)}%`:"",j=!V.enabled?" (disabled)":"",H=V.tierLabel?` · ${V.tierLabel}`:"",Q=V.id==="main"?" · gate n/a (OpenCode managed)":` · gate ${e$($.storage,V.id)?"on":"off"}`;K.push(`- **${V.label}** [${V.role}]${H}${j}${W}${Q}`)}return K.push("",N6),{text:K.join(`
29
- `)}}if(J.type==="usage")return{text:N6};if(J.type==="add-apikey")return{text:"add-apikey"};if(J.type==="add-oauth-start")return{text:"add-oauth-start"};if(J.type==="add-oauth-finish")return{text:"add-oauth-finish"};if(J.type==="reset-backoff")return{text:"Main OAuth refresh and quota backoff cleared.",updated:{id:"main",action:"reset-backoff"}};let G=J.id;if(G==="main")return{text:`Cannot ${J.type} the main account (OpenCode managed).`};if(J.type==="enable"||J.type==="disable"){let X=Z.find((Y)=>Y.id===G);if(!X)return{text:`Account "${G}" not found.`};return{text:`Account "${X.label??G}" ${J.type}d.`,updated:{id:G,action:J.type,enabled:J.type==="enable"}}}if(J.type==="remove"){let X=Z.find((Y)=>Y.id===G);if(!X)return{text:`Account "${G}" not found.`};return{text:`Account "${X.label??G}" removed.`,updated:{id:G,action:"remove"}}}if(J.type==="move-up"){let X=Z.findIndex((W)=>W.id===G);if(X<0)return{text:`Account "${G}" not found.`};if(X===0)return{text:`Account "${Z[X]?.label??G}" is already first.`};let Y=Z.map((W)=>W.id),K=[...Z];[K[X-1],K[X]]=[K[X],K[X-1]];let V=K.map((W)=>W.id);return{text:`Account "${Z[X]?.label??G}" moved up.`,updated:{id:G,action:"reorder",previousOrder:Y,newOrder:V}}}if(J.type==="move-down"){let X=Z.findIndex((W)=>W.id===G);if(X<0)return{text:`Account "${G}" not found.`};if(X===Z.length-1)return{text:`Account "${Z[X]?.label??G}" is already last.`};let Y=Z.map((W)=>W.id),K=[...Z];[K[X],K[X+1]]=[K[X+1],K[X]];let V=K.map((W)=>W.id);return{text:`Account "${Z[X]?.label??G}" moved down.`,updated:{id:G,action:"reorder",previousOrder:Y,newOrder:V}}}return{text:N6}}var SX="claude-fast";var U$=!1;function TX(){return U$}function AX($){U$=$}function m7($){let J=$.trim().split(/\s+/).filter(Boolean);if(J.length===0)return{type:"status"};if(J.length===1&&J[0]==="on")return{type:"enable"};if(J.length===1&&J[0]==="off")return{type:"disable"};return{type:"usage"}}function Q$($){return["## Claude Fast Mode Status","",`- Enabled: ${$?.enabled??U$?"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, and claude-opus-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(`
30
- `)}function bX($){let J=m7($.argumentsText),Z=$.enabled??U$;if(J.type==="status")return Q$({enabled:Z});if(J.type==="enable")return["## Claude Fast Mode Enabled","",Q$({enabled:!0})].join(`
31
- `);if(J.type==="disable")return["## Claude Fast Mode Disabled","",Q$({enabled:!1})].join(`
32
- `);return["## Claude Fast Mode Usage","","Usage: `/claude-fast`, `/claude-fast on`, or `/claude-fast off`.","",Q$({enabled:Z})].join(`
33
- `)}var t0="claude-killswitch";function g7($){let J=$.trim().split(/\s+/).filter(Boolean);if(J.length===0)return{type:"status"};if(J.length===1&&J[0]==="on")return{type:"on"};if(J.length===1&&J[0]==="off")return{type:"off"};if(J[0]==="set"){let Z=[];for(let z=1;z<J.length;z++){let G=J[z]?.match(/^([^:]+):(\d+),(\d+)(?:,(\d+))?$/);if(!G)return{type:"usage"};let[,X,Y,K,V]=G,W=typeof V==="string"&&V.length>0?Number.parseInt(V,10):void 0,j={account:X,fh:Number.parseInt(Y,10),sd:Number.parseInt(K,10)};if(W!==void 0)j.scoped=W;Z.push(j)}if(Z.length===0)return{type:"usage"};return{type:"set",entries:Z}}return{type:"usage"}}function N$($,J){let Z=$.enabled===!0,z=["## Killswitch","",`Status: **${Z?"ON":"OFF"}**`];if(Z){z.push(""),z.push("| Account | 5h threshold | 1w threshold | Scoped |"),z.push("| ------- | ------------ | ------------ | ------ |");let G=U1($.main);z.push(`| main | ≥ ${G.five_hour}% | ≥ ${G.seven_day}% | ≤ ${G.scoped}% |`);for(let X of J){let Y=U1($.accounts?.[X]??$.main);z.push(`| ${X} | ≥ ${Y.five_hour}% | ≥ ${Y.seven_day}% | ≤ ${Y.scoped}% |`)}}return z.join(`
34
- `)}var a4=["## Killswitch Commands","","```",`/${t0} — show status`,`/${t0} on — enable with current or default thresholds`,`/${t0} off — disable`,`/${t0} set all:5,10 — set all accounts to 5h≥5%, 1w≥10%`,`/${t0} set main:3,8,0 — set 5h≥3%, 1w≥8%, scoped≤0%`,`/${t0} set main:3,8 work-alt:5,10 — per-account`,"```"].join(`
35
- `);function kX($){let J=g7($.argumentsText);if(J.type==="status")return{text:`${N$($.config,$.accountIds)}
36
-
37
- ${a4}`};if(J.type==="on"){let z={...$.config,enabled:!0,main:$.config.main??{five_hour:f0.five_hour,seven_day:f0.seven_day}};return{text:`## Killswitch Enabled
38
-
39
- ${N$(z,$.accountIds)}`,updatedConfig:z}}if(J.type==="off")return{text:"## Killswitch Disabled",updatedConfig:{...$.config,enabled:!1}};if(J.type==="set"){let z={...$.config.accounts??{}},G={...$.config,enabled:!0,accounts:z};for(let Y of J.entries){let K={five_hour:Y.fh,seven_day:Y.sd};if(Y.scoped!==void 0)K.scoped=Y.scoped;if(Y.account==="main")G.main=K;else if(Y.account==="all"){G.main=K;for(let V of $.accountIds)z[V]=K}else z[Y.account]=K}return{text:`## Killswitch Updated
40
-
41
- ${N$(G,$.accountIds)}`,updatedConfig:G}}return{text:`${N$($.config,$.accountIds)}
42
-
43
- ${a4}`}}var hX="claude-logging",p7=["error","warn","info","debug","trace"];function l7($){let J=$.trim().toLowerCase().split(/\s+/).filter(Boolean);if(J.length===0)return{type:"status"};if(J.length===1&&p7.includes(J[0]))return{type:"level",level:J[0]};return{type:"usage"}}function B6($){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(`
44
- `)}function yX($){let J=l7($.argumentsText),Z=$.level??"info";if(J.type==="status")return B6({level:Z});if(J.type==="level")return["## Claude Log Level Updated","",`Level set to \`${J.level}\`.`,"",...B6({level:J.level}).split(`
45
- `).slice(2)].join(`
46
- `);return["## Claude Log Level Usage","","Usage: `/claude-logging`, `/claude-logging error|warn|info|debug|trace`.","",...B6({level:Z}).split(`
47
- `).slice(2)].join(`
48
- `)}var gX="claude-fable-5";var pX="claude-fable-5-1";var L6="claude-haiku-4-5",C6={input:1,output:5},e4=["claude-fable-5-1","claude-mythos-5-1"],u7=["claude-fable-5","claude-mythos-5",...e4],$3={type:"adaptive",display:"summarized"},lX={input:10,output:50,cacheRead:1,cacheWrite5m:12.5,cacheWrite1h:20},uX={input:10,output:50,cacheRead:0.25,cacheWrite5m:12.5,cacheWrite1h:20},sX=1e6,dX=128000;var o4={["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}},iX={["claude-fable-5-1"]:o4["claude-fable-5-1"],["claude-mythos-5-1"]:o4["claude-mythos-5-1"]};function J3($){return typeof $==="string"&&u7.some((J)=>$===J||$.startsWith(`${J}-`))}function s7($){return typeof $==="string"&&e4.some((J)=>$===J||$.startsWith(`${J}-`))}function B$($){if(typeof $!=="string")return!1;return $==="claude-fable-5-1"||$.startsWith("claude-fable-5-1-")}function cX($){return s7($)?"2026-09-01":"2026-06-09"}var t4="claude-sonnet-5",nX=$3;function aX($){return typeof $==="string"&&($===t4||$.startsWith(`${t4}-`))}var r4="claude-opus-5",oX=$3;function tX($){return typeof $==="string"&&($===r4||$.startsWith(`${r4}-`))}function rX($){if(typeof $!=="string")return!1;if($.startsWith("gAAAA"))return!0;if(!$.startsWith("{"))return!1;try{let J=JSON.parse($);return J.type==="reasoning"&&typeof J.id==="string"&&J.id.startsWith("rs_")&&typeof J.encrypted_content==="string"&&J.encrypted_content.startsWith("gAAAA")}catch{return!1}}import{createHash as d7}from"node:crypto";import{realpathSync as i7}from"node:fs";import{mkdir as c7,readdir as Z3,rm as L$,stat as z3,writeFile as n7}from"node:fs/promises";import{tmpdir as a7}from"node:os";import{join as r0,resolve as o7}from"node:path";var VY="claude-prime",t7=60000,j3=60000,r7=21600000,e7=90000,$J=300000;function JJ($){let J=$.trim().split(/\s+/).filter(Boolean);if(J.length===0)return{type:"status"};if(J.length===1&&J[0]==="on")return{type:"enable"};if(J.length===1&&J[0]==="off")return{type:"disable"};return{type:"usage"}}function O6($){if(!$)return 0;return($.inputTokens*C6.input+$.outputTokens*C6.output)/1e6}function ZJ($,J,Z){if(Z?.label?.trim())return Z.label;if($==="main")return"main";let z=J?.accounts?.find((G)=>G.id===$);if(z?.label?.trim())return z.label;return $}function zJ($,J){let Z=J?.transient,z=$?.quota?.mainQuota,G=$?.prime?.main,X={id:"main",label:"main",nextDueAt:G3(z?.five_hour),lastPrimedAt:Z?.get("main")?.lastPrimedAt??null,lastResult:Z?.get("main")?.lastResult,usage:G,estimatedCostUsd:O6(G)},Y=($?.accounts??[]).filter(E).filter((K)=>K.id!=="main").filter((K)=>K.enabled!==!1).map((K)=>({id:K.id,label:ZJ(K.id,$,K),nextDueAt:G3(K.quota?.five_hour),lastPrimedAt:Z?.get(K.id)?.lastPrimedAt??null,lastResult:Z?.get(K.id)?.lastResult,usage:K.prime,estimatedCostUsd:O6(K.prime)}));return[X,...Y]}function G3($){if(!$?.resetsAt)return;let J=Date.parse($.resetsAt);if(!Number.isFinite(J))return;return J+j3}function C$($){let Z=[$.enabled?"## Claude Prime Status":"## Claude Prime Disabled",""];Z.push(`Status: ${$.enabled?"enabled":"disabled"}`),Z.push(""),Z.push("Accounts:");for(let z of $.accounts){let X=z.usage?.count??0,Y=GJ(z.nextDueAt),K=XJ(z.lastPrimedAt,z.lastResult),V=[`${z.label}`];if(Y)V.push(`next prime ${Y}`);if(K)V.push(K);if(X>0)V.push(`${X} ${X===1?"prime":"primes"} ≈ $${YJ(z.estimatedCostUsd??0)}`);Z.push(`- ${V.join(" · ")}`)}return Z.push(""),Z.push("Usage: `/claude-prime on`, `/claude-prime off`, or status."),Z.join(`
49
- `)}function GJ($){if(typeof $!=="number")return"";return new Date($).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function XJ($,J){if(typeof $!=="number")return"";let Z=new Date($).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});if(J==="error")return`primed ${Z} err`;return`primed ${Z} ✓`}function YJ($){if($===0)return"0";if($<0.0001)return $.toExponential(2);return $.toFixed(Math.min(6,Math.max(0,4)))}function WY($){let J=JJ($.argumentsText);if(J.type==="status")return{text:C$({enabled:$.enabled,accounts:$.accounts})};if(J.type==="enable")return{text:C$({enabled:!0,accounts:$.accounts}),updated:{enabled:!0}};if(J.type==="disable")return{text:C$({enabled:!1,accounts:$.accounts}),updated:{enabled:!1}};return{text:["## Claude Prime Usage","","Usage: `/claude-prime`, `/claude-prime on`, or `/claude-prime off`.","",C$({enabled:$.enabled,accounts:$.accounts})].join(`
50
- `)}}var KJ={"not-oauth":"API-key account",disabled:"disabled","needs-reauth":"needs re-login",killswitch:"killswitch"};function VJ($){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 X3($){return KJ[$]}var WJ={model:L6,max_tokens:1,system:"Reply with 1 when you receive 0.",messages:[{role:"user",content:"0"}]};function jY(){return JSON.parse(JSON.stringify(WJ))}function Y3(){return r0(a7(),"opencode-anthropic-auth","prime")}function jJ($){let J=o7($),Z;try{Z=i7(J)}catch(z){if(z.code!=="ENOENT")throw z;Z=J}return d7("sha256").update(Z).digest("hex").slice(0,12)}function H3($,J){return r0($,jJ(J))}function HJ($,J,Z){if(!/^[a-f0-9]{12,}$/i.test(Z))throw Error("Prime account fingerprint must be a hexadecimal digest");return r0(H3($,J),Z.toLowerCase().slice(0,12))}function K3($,J,Z){return r0($,`${encodeURIComponent(J)}-${Z}`)}function V3($,J){return r0($,`${encodeURIComponent(J)}-bootstrap`)}function _6($,J){if($==="main")return"main";if(J&&"label"in J&&J.label?.trim())return J.label;return $}function QJ($){let J=[],Z=$.refresh?.mainLastRefreshError;J.push({id:"main",label:"main",isOAuth:!0,isEnabled:!0,hasPermanentRefreshError:c0(Z),storedQuota:$.quota?.mainQuota,storedFiveHour:$.quota?.mainQuota?.five_hour});for(let z of $.accounts??[]){if(z.id==="main"){M.debug("prime","ineligible",{account:_6(z.id,z),reason:"reserved-id"});continue}if(!E(z)){J.push({id:z.id,label:_6(z.id,z),isOAuth:!1,isEnabled:z.enabled!==!1,hasPermanentRefreshError:!1});continue}J.push({id:z.id,label:_6(z.id,z),isOAuth:!0,isEnabled:z.enabled!==!1,hasPermanentRefreshError:c0(z.lastRefreshError),storedQuota:z.quota,storedFiveHour:z.quota?.five_hour})}return J}function W3($){if(!$?.resetsAt)return;let J=Date.parse($.resetsAt);return Number.isFinite(J)?J:void 0}class UJ{timer=null;postFireRefreshTimers=new Set;lastForcedCheck=new Map;stopped=!1;options;transient=new Map;counters=new Map;windowActive=new Map;constructor($){this.options=$}updateOptions($){this.options=$}start(){if(this.timer)return;if(this.stopped=!1,M.trace("prime","manager started"),this.timer=setInterval(()=>{this.tick().catch(($)=>{M.warn("prime","tick failed",{error:$ instanceof Error?$.message:String($)})})},t7),typeof this.timer==="object"&&"unref"in this.timer)this.timer.unref?.()}stop(){let $=this.timer!==null,J=this.postFireRefreshTimers.size>0;if(this.stopped=!0,this.timer)clearInterval(this.timer),this.timer=null;for(let Z of this.postFireRefreshTimers)clearTimeout(Z);if(this.postFireRefreshTimers.clear(),this.lastForcedCheck.clear(),!$&&!J)return;M.trace("prime","manager stopped")}isStopped(){return this.stopped}async tick(){let $=this.options.now?.()??Date.now();if(M.trace("prime","tick start",{now:$}),await this.sweepMarkers($),this.stopped){M.trace("prime","tick: stopped, aborting");return}let J=await this.options.loadStorage();if(!J){M.trace("prime","tick: no storage, skipping");return}if(J.prime?.enabled!==!0){M.trace("prime","tick: feature disabled, skipping");return}let Z=QJ(J);await Promise.all(Z.map((z)=>this.runForAccount(z,J,$))),M.trace("prime","tick end")}stats($,J){let Z=zJ($??null,{now:J,transient:this.transient});if(this.counters.size===0)return Z;return Z.map((z)=>{let G=this.counters.get(z.id);if(!G)return z;return{...z,usage:G,estimatedCostUsd:O6(G)}})}isWindowActive($){return this.windowActive.has($)}async runForAccount($,J,Z){try{if(this.stopped)return;let z=VJ({storage:J,accountId:$.id,isOAuth:$.isOAuth,isEnabled:$.isEnabled,hasPermanentRefreshError:$.hasPermanentRefreshError,quota:$.storedQuota});if(!z.eligible){M.debug("prime","ineligible",{account:$.label,reason:X3(z.reason)});return}let G=W3($.storedFiveHour);if(G!==void 0&&Z<G+j3){M.trace("prime","not due",{account:$.label});return}let X=await this.options.getAccountFingerprint($.id);if(!X){M.debug("prime","credential identity unavailable",{account:$.label});return}let Y=`${$.id}:${X.toLowerCase().slice(0,12)}`,K=this.markerDir(X),V=V3(K,$.id),W=G===void 0?V:K3(K,$.id,G);try{await z3(W);return}catch(L){if(L.code!=="ENOENT")throw L}if(G===void 0&&await this.hasAnyClaimMarker($.id,X))return;if(this.stopped)return;let j=this.lastForcedCheck.get(Y);if(j!==void 0&&j.resetEpoch===G&&Z<j.at+$J)return;this.lastForcedCheck.set(Y,{at:Z,resetEpoch:G});let H;try{H=await this.options.refreshQuota($.id)}catch(L){M.warn("prime","refresh failed",{account:$.label,error:L instanceof Error?L.message:String(L)});return}if(this.stopped)return;let Q=await this.options.loadStorage();if(Q?.prime?.enabled!==!0)return;let U=H.quota;if(!H.fresh){M.debug("prime","stale fresh-check",{account:$.label});return}if(!G4(U,Q,$.id,L6)){M.debug("prime","ineligible",{account:$.label,reason:X3("killswitch")});return}let B=W3(U?.five_hour);if(B!==void 0&&B>Z){M.debug("prime","window active",{account:$.label,resetsAt:U.five_hour?.resetsAt}),this.windowActive.set($.id,Z);return}this.windowActive.delete($.id);let O=B??G,q=O===void 0?await this.tryClaimBootstrap($.id,X):await this.tryClaim($.id,X,O);if(!q){M.debug("prime","claim lost",{account:$.label,marker:`${$.id}-${O??"bootstrap"}`});return}let D=await this.options.loadStorage();if(this.stopped||D?.prime?.enabled!==!0){await L$(q,{force:!0});return}if(O!==void 0){if(await L$(V,{force:!0}),this.stopped){await L$(q,{force:!0});return}}await this.fire($,Z,D)}catch(z){M.warn("prime","account evaluation failed",{account:$.label,error:z instanceof Error?z.message:String(z)})}}async tryClaim($,J,Z){let z=this.markerDir(J),G=K3(z,$,Z);return this.tryClaimPath(z,G)}async tryClaimBootstrap($,J){let Z=this.markerDir(J),z=V3(Z,$);return this.tryClaimPath(Z,z)}async tryClaimPath($,J){try{await c7($,{recursive:!0})}catch{}try{return await n7(J,"",{encoding:"utf8",flag:"wx"}),J}catch(Z){if(Z.code==="EEXIST")return null;throw Z}}async hasAnyClaimMarker($,J){let Z=this.markerDir(J),z=`${encodeURIComponent($)}-`;try{return(await Z3(Z)).some((G)=>G.startsWith(z))}catch(G){if(G.code==="ENOENT")return!1;throw G}}async fire($,J,Z){let z;try{z=await this.options.sendPrime($.id)}catch(X){let Y=X instanceof Error?X.message:String(X);M.warn("prime","prime fire threw",{account:$.label,error:Y}),this.transient.set($.id,{lastPrimedAt:J,lastResult:"error"});return}if(this.stopped)return;if(!z.ok){if(z.reason==="token-refresh")M.warn("prime","prime token refresh failed",{account:$.label,error:z.error});else M.warn("prime","prime fire failed",{account:$.label,status:z.status,error:z.error});this.transient.set($.id,{lastPrimedAt:J,lastResult:"error"});return}let G={inputTokens:z.usage?.inputTokens,outputTokens:z.usage?.outputTokens};try{let X=await this.options.recordSuccess($.id,G);if(this.stopped){this.transient.delete($.id),this.counters.delete($.id);return}this.counters.set($.id,X),this.transient.set($.id,{lastPrimedAt:J,lastResult:"ok"}),M.info("prime","prime fired",{account:$.label,status:z.status,ms:z.ms,usage:{inputTokens:X.inputTokens,outputTokens:X.outputTokens}}),this.schedulePostFireRefresh($)}catch(X){M.warn("prime","recordSuccess failed",{account:$.label,error:X instanceof Error?X.message:String(X)}),this.transient.set($.id,{lastPrimedAt:J,lastResult:"error"})}}schedulePostFireRefresh($){let J=setTimeout(()=>{if(this.postFireRefreshTimers.delete(J),this.stopped)return;(async()=>{let Z=await this.options.loadStorage();if(this.stopped||Z?.prime?.enabled!==!0)return;await this.options.refreshQuota($.id)})().catch((Z)=>{M.debug("prime","post-fire refresh failed",{account:$.label,error:Z instanceof Error?Z.message:String(Z)})})},e7);if(this.postFireRefreshTimers.add(J),typeof J==="object"&&"unref"in J)J.unref?.()}async sweepMarkers($){let J=this.storageMarkerDir(),Z=await this.sweepMarkerDirectory(J,$);if(Z>0)M.trace("prime","swept stale markers",{swept:Z})}async sweepMarkerDirectory($,J){let Z;try{Z=await Z3($)}catch{return 0}let z=0;for(let G of Z)try{let X=r0($,G),Y=await z3(X);if(Y.isDirectory()){z+=await this.sweepMarkerDirectory(X,J);continue}if(J-Y.mtimeMs>r7)await L$(X,{force:!0}),z+=1}catch{}return z}storageMarkerDir(){return H3(this.options.markerDir??Y3(),this.options.storagePath)}markerDir($){return HJ(this.options.markerDir??Y3(),this.options.storagePath,$)}}import{randomUUID as Q3}from"node:crypto";import{chmod as U3,mkdir as NJ,readdir as BJ,readFile as N3,rename as LJ,rm as B3,writeFile as CJ}from"node:fs/promises";import{tmpdir as _J}from"node:os";import{join as q6}from"node:path";var e0=3,OJ=180000;function M6(){return process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR??q6(_J(),"opencode-anthropic-auth","quota-header-feed")}function CY($){return($.storage?.accounts.filter(E).length??0)+($.mainOAuthConfigured?1:0)}function C3($){if($.schema_version!==e0||$.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($.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 MJ($){if($.schema_version!==e0||$.provider!=="anthropic"||!C3($))throw Error("Invalid quota header feed entry")}function $1($){return typeof $==="number"&&Number.isFinite($)}function D6($){if(!$||typeof $!=="object")return;let J=$;if(!$1(J.usedPercent)||!$1(J.remainingPercent)||!$1(J.checkedAt))return;return{usedPercent:J.usedPercent,remainingPercent:J.remainingPercent,...typeof J.resetsAt==="string"&&{resetsAt:J.resetsAt},checkedAt:J.checkedAt}}function qJ($){if(!$||typeof $!=="object")return;let J=$,Z=D6(J);if(!Z||typeof J.id!=="string"||!J.id.trim()||typeof J.title!=="string"||!J.title.trim()||typeof J.modelName!=="string"||!J.modelName.trim())return;return{...Z,id:J.id,title:J.title,...typeof J.modelId==="string"&&J.modelId.trim()&&{modelId:J.modelId},modelName:J.modelName}}function L3($){if(!$||typeof $!=="object")return;let J=$;if(!$1(J.amountMinor)||typeof J.currency!=="string"||!J.currency.trim()||!$1(J.exponent))return;return{amountMinor:J.amountMinor,currency:J.currency,exponent:J.exponent}}function DJ($){if(!$||typeof $!=="object")return;let J=$,Z=L3(J.used),z=L3(J.limit);if(!Z||!z||typeof J.exhausted!=="boolean")return;return{used:Z,limit:z,...$1(J.utilizationPercent)&&{utilizationPercent:J.utilizationPercent},...typeof J.severity==="string"&&{severity:J.severity},exhausted:J.exhausted}}function xJ($,J){if(!$||typeof $!=="object")return;let Z=$,z={};for(let G of u0){if(!J.has(G))continue;let X=Z[G];if(X==="poll"||X==="headers")z[G]=X}return Object.keys(z).length>0?z:void 0}function RJ($){let J=D6($.five_hour),Z=D6($.seven_day),z=Array.isArray($.scoped)?$.scoped.map(qJ).filter((K)=>K!=null):void 0,G=DJ($.extraUsage),X=new Set;if(J)X.add("five_hour");if(Z)X.add("seven_day");if(typeof $.bindingWindow==="string")X.add("bindingWindow");if(typeof $.fallbackAdvised==="boolean")X.add("fallbackAdvised");if(z)X.add("scoped");if(G)X.add("extraUsage");let Y=xJ($.fieldSources,X);return{...J&&{five_hour:J},...Z&&{seven_day:Z},...typeof $.bindingWindow==="string"&&{bindingWindow:$.bindingWindow},...typeof $.fallbackAdvised==="boolean"&&{fallbackAdvised:$.fallbackAdvised},...z&&{scoped:z},...G&&{extraUsage:G},...Y&&{provenance:Y}}}class fJ{options;filePath;writeChain=Promise.resolve();constructor($={}){this.options=$;let J=$.instanceId??`${process.pid}-${Q3()}`;this.filePath=q6($.directory??M6(),`${J}.json`)}publish($){let{accountKey:J,quota:Z,...z}=$,G={...z,quota:RJ(Z)};try{MJ(G)}catch(X){return Promise.reject(X)}if(!J)return Promise.reject(Error("Invalid quota header feed account key"));return this.writeChain=this.writeChain.catch(()=>{}).then(async()=>{let X=this.options.directory??M6();await NJ(X,{recursive:!0,mode:448}),await U3(X,448);let Y={};try{let V=JSON.parse(await N3(this.filePath,"utf8"));if(V.version===e0&&V.entries&&typeof V.entries==="object")Y=V.entries}catch{}Y[J]=G;let K=`${this.filePath}.${Q3()}.tmp`;try{await CJ(K,`${JSON.stringify({version:e0,entries:Y})}
51
- `,{mode:384}),await U3(K,384),await LJ(K,this.filePath)}finally{await B3(K,{force:!0})}}),this.writeChain}async list(){await this.writeChain.catch(()=>{});let $=this.options.directory??M6(),J=this.options.now?.()??Date.now(),Z=this.options.leaseMs??OJ,z;try{z=(await BJ($)).filter((X)=>X.endsWith(".json"))}catch{return[]}let G=new Map;return await Promise.all(z.map(async(X)=>{try{let Y=JSON.parse(await N3(q6($,X),"utf8"));if(Y.version!==e0||!Y.entries||typeof Y.entries!=="object")return;for(let[K,V]of Object.entries(Y.entries)){if(!V||typeof V!=="object"||V.schema_version!==e0||V.provider!=="anthropic"||!C3(V))continue;let W=V.observed_at_ms;if(W>J||J-W>=Z)continue;let j=G.get(K);if(!j||W>j.observed_at_ms)G.set(K,V)}}catch{}})),[...G.values()].sort((X,Y)=>X.observed_at_ms-Y.observed_at_ms)}async dispose(){await this.writeChain.catch(()=>{}),await B3(this.filePath,{force:!0})}}var O1="anthropic-ratelimit-unified-",_3={"5h":"five_hour","7d":"seven_day"};function MY($){return Object.keys(_3).some((J)=>Number.isFinite(x6($,`${O1}${J}-utilization`)))}function x6($,J){let Z=$.get(J);if(Z==null||Z.trim()==="")return;let z=Number(Z);return Number.isFinite(z)?z:void 0}function wJ($,J,Z){let z=x6($,`${O1}${J}-utilization`);if(z==null)return;let G=Math.min(100,Math.max(0,Math.round(z*100))),X=x6($,`${O1}${J}-reset`),Y=X==null?void 0:new Date(X*1000),K=Y&&Number.isFinite(Y.getTime())?Y.toISOString():void 0;return{usedPercent:G,remainingPercent:100-G,...K&&{resetsAt:K},checkedAt:Z}}function qY($,J=Date.now()){let Z={},z=$.get(`${O1}fallback`),G={fallbackAdvised:z==="available",source:"headers",checkedAt:J};for(let[Y,K]of Object.entries(_3)){let V=wJ($,Y,J);if(V)G[K]=V,Z[K]="headers"}let X=$.get(`${O1}representative-claim`);if(X)G.bindingWindow=X,G.bindingWindowSource="headers",Z.bindingWindow="headers";if(z!==null)Z.fallbackAdvised="headers";return{...G,fieldSources:Z}}function M1($,J){let{scoped:Z,extraUsage:z,fieldSources:G,...X}=$??{},{scoped:Y,extraUsage:K,fieldSources:V,...W}=J,j={};for(let H of u0){let Q=H==="scoped"?Z:H==="extraUsage"?z:H==="fallbackAdvised"?V?.fallbackAdvised!==void 0?J.fallbackAdvised:$?.fallbackAdvised??J.fallbackAdvised:H==="bindingWindow"?$?.bindingWindowSource==="poll"?$?.bindingWindow:J.bindingWindow??$?.bindingWindow:J[H]??$?.[H];if(Q===void 0)continue;let U=H==="fallbackAdvised"?V?.fallbackAdvised??($?.fallbackAdvised!==void 0?G?G.fallbackAdvised:Q0($,H):void 0):(H==="scoped"||H==="extraUsage")&&Q!==void 0?"poll":H==="bindingWindow"&&$?.bindingWindowSource==="poll"&&$.bindingWindow!==void 0?"poll":J[H]!==void 0?V?.[H]??Q0(J,H):G?.[H]??Q0($,H);if(U)j[H]=U}return{...X,...W,...Array.isArray(Z)&&{scoped:Z},...z!=null&&{extraUsage:z},fallbackAdvised:V?.fallbackAdvised!==void 0?J.fallbackAdvised:$?.fallbackAdvised??J.fallbackAdvised,bindingWindow:$?.bindingWindowSource==="poll"?$.bindingWindow:J.bindingWindow??$?.bindingWindow,bindingWindowSource:$?.bindingWindowSource==="poll"?"poll":J.bindingWindowSource??$?.bindingWindowSource,...Object.keys(j).length>0&&{fieldSources:j},source:"headers"}}var PJ=globalThis.setTimeout;function O3($,J){if($?.source!=="headers")return J;let Z=Boolean($.five_hour&&$.five_hour.checkedAt>(J.five_hour?.checkedAt??0)),z=Boolean($.seven_day&&$.seven_day.checkedAt>(J.seven_day?.checkedAt??0));if(!Z&&!z)return J;return M1(J,{...Z&&{five_hour:$.five_hour},...z&&{seven_day:$.seven_day},fallbackAdvised:$.fallbackAdvised,...$.bindingWindowSource==="headers"&&{bindingWindow:$.bindingWindow,bindingWindowSource:$.bindingWindowSource},source:"headers",checkedAt:Math.max(Z?$.five_hour?.checkedAt??0:0,z?$.seven_day?.checkedAt??0:0)})}class O0{main=null;mainAccountId;mainQuotaIdentityKnown=!1;mainQuotaIdentityStrict=!1;mainGeneration=0;mainQuotaErrorGeneration=0;mainQuotaErrorClearedAt;fallbacks=new Map;fallbackAuthLineages=new Map;fallbackGenerations=new Map;inflightMain=null;inflightMainAccountId;inflightFallbacks=new Map;mainLastApiError=void 0;fallbackApiErrors=new Map;apiGate=Promise.resolve();lastApiCallAt=0;storage;fetchImpl;now;onMainQuotaFetched;onApiError;onFallbackQuotaFetched;onFallbackApiError;constructor($){this.storage=$.storage,this.fetchImpl=$.fetchImpl??fetch,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($,J){return this.bindFallbackLineage($,J),this.fallbacks.get($)??null}getAllFallbacks(){return this.fallbacks}setMain($,J){this.mainAccountId=$,this.main=J}setMainQuotaAccountIdentity($,J=!0){let Z=this.mainQuotaIdentityKnown,z=this.mainAccountId,G=!Z||this.mainAccountId!==$||this.mainQuotaIdentityStrict!==J;if(this.mainQuotaIdentityKnown=!0,this.mainQuotaIdentityStrict=J,!G)return;if(this.mainGeneration+=1,this.mainAccountId=$,$!==void 0&&this.main?.quota.accountIdentity!==$)this.main=null;if($!==void 0&&this.mainLastApiError&&(this.mainLastApiError.accountIdentity!==void 0?this.mainLastApiError.accountIdentity!==$:Z&&z!==void 0&&z!==$))return this.mainLastApiError=void 0,this.mainQuotaErrorGeneration+=1,this.mainQuotaErrorClearedAt=s0(this.mainQuotaErrorClearedAt,this.now()),this.mainQuotaErrorGeneration;return}setFallback($,J,Z){this.bindFallbackLineage($,Z),this.fallbacks.set($,J)}clearFallback($){this.fallbackGenerations.set($,(this.fallbackGenerations.get($)??0)+1),this.fallbacks.delete($),this.fallbackApiErrors.delete($),this.inflightFallbacks.delete(O0.fallbackInflightKey($))}pushMainFromHeaders($,J){let Z=J.checkedAt??this.now(),z=M1(this.mainAccountId===$&&(!this.mainQuotaIdentityKnown||!this.mainQuotaIdentityStrict||this.main?.quota.accountIdentity===$)?this.main?.quota:void 0,{...J,...$!==void 0&&{accountIdentity:$}}),G={quota:z,checkedAt:Z,refreshAfter:E0(z,this.storage,Z)};return this.setMain($,G),G}pushFallbackFromHeaders($,J,Z){if(!this.acceptFallbackQuotaObservation($,Z))return null;let z=J.checkedAt??this.now(),G=M1(this.fallbacks.get($)?.quota,{...J,accountIdentity:$}),X={quota:G,checkedAt:z,refreshAfter:E0(G,this.storage,z)};return this.fallbacks.set($,X),X}async refreshMain($,J,Z){let z=$,G=J??$;if(!G)throw Error("Main OAuth access token is unavailable");return(await this.refreshMainWithMetadata(z,G,Z)).quota}async refreshMainWithMetadata($,J,Z){let z=$,G=J??$;if(!G)throw Error("Main OAuth access token is unavailable");if(Z!==void 0&&(this.mainGeneration!==Z||this.mainAccountId!==z))throw Error("Main quota identity changed before refresh");if(this.mainAccountId!==z){if(this.main=null,this.mainAccountId=z,this.mainQuotaIdentityKnown)this.mainGeneration+=1}if(this.inflightMain&&this.inflightMainAccountId===z)return this.inflightMain;if(this.isBackedOff()){if(this.main&&this.mainAccountId===z)return{quota:this.main.quota,fetched:!1};throw Error("Quota API rate-limited — try again later")}this.inflightMainAccountId=z;let X=this.mainGeneration;return this.inflightMain=this._fetchMain(z,G,X),this.inflightMain}async refreshFallback($,J,Z){return(await this.refreshFallbackWithMetadata($,J,Z)).quota}async refreshFallbackWithMetadata($,J,Z){this.bindFallbackLineage($,Z);let z=O0.fallbackInflightKey($),G=this.inflightFallbacks.get(z);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 X=this.fallbackGenerations.get($)??0,Y=this._fetchFallback($,J,X,Z);return this.inflightFallbacks.set(z,Y),Y.then(()=>{if(this.inflightFallbacks.get(z)===Y)this.inflightFallbacks.delete(z)},()=>{if(this.inflightFallbacks.get(z)===Y)this.inflightFallbacks.delete(z)}),Y}async refreshAllFallbacks($,J){let Z=this.now();for(let z of $){if(z.enabled===!1)continue;let G=J?.(z)??(z.access&&z.expires!==void 0&&z.expires>Z?z.access:void 0);if(!G)continue;this.bindFallbackLineage(z.id,z);let X=this.getFallback(z.id);if(X&&Z<X.refreshAfter)continue;try{await this.refreshFallback(z.id,G,z)}catch{}}}refreshMainInBackground($){if(this.inflightMain)return;if(this.isBackedOff())return;this.refreshMain(this.mainAccountId,$).catch(()=>{})}scopedWindowIsStale($,J){let Z=r($.quota,J);return Boolean(Z&&this.now()-Z.checkedAt>=V0(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($,J,Z,z){let G=this.getFallback($,z);if(!G)return!0;return this.now()>=G.refreshAfter||this.scopedWindowIsStale(G,Z)}shouldRefreshOnRequestCount($){let J=J4(this.storage);if(J<=0)return!1;return $>0&&$%J===0}needsRefresh($,J){return this.isMainStale(J)||this.shouldRefreshOnRequestCount($)}updateStorage($){this.storage=$,this.seedMainFromStorage($,this.mainQuotaIdentityKnown?this.mainAccountId:$?.mainAccountId),this.seedMainBackoffFromStorage($)}seedMainFromStorage($,J){let Z=$4($);if(!Z)return;let z={quota:{...Z.quota,...(!this.mainQuotaIdentityKnown||!this.mainQuotaIdentityStrict)&&J!==void 0&&Z.accountIdentity===void 0&&{accountIdentity:J}},refreshAfter:E0(Z.quota,$,Z.checkedAt),checkedAt:Z.checkedAt},G=this.main&&this.mainAccountId===J&&(!this.mainQuotaIdentityKnown||!this.mainQuotaIdentityStrict||this.main.quota.accountIdentity===J)?this.main:void 0;if(G&&G.checkedAt>=z.checkedAt&&G.quota.source==="headers"&&z.quota.source==="poll"){let X=M1(z.quota,G.quota);this.main={quota:X,refreshAfter:E0(X,$,G.checkedAt),checkedAt:G.checkedAt};return}if(this.main&&this.mainAccountId===J&&this.main.checkedAt>=z.checkedAt)return;if(this.main=z,J!==void 0)this.mainAccountId=J}seedMainBackoffFromStorage($){let J=$?.quota?.mainLastQuotaApiError,Z=J?.accountIdentity,z=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=s0(this.mainQuotaErrorClearedAt,G),(!J||typeof J.checkedAt==="number"&&J.checkedAt<=G)&&(this.mainLastApiError?.checkedAt===void 0||this.mainLastApiError.checkedAt<=G))this.mainLastApiError=void 0}if(z!==void 0&&z>this.mainQuotaErrorGeneration){if(this.mainQuotaErrorGeneration=z,!J&&(this.mainLastApiError?.checkedAt===void 0||this.mainQuotaErrorClearedAt===void 0||this.mainLastApiError.checkedAt<=this.mainQuotaErrorClearedAt))this.mainLastApiError=void 0}if(J&&(!this.mainQuotaIdentityKnown||Z===void 0||Z===this.mainAccountId)&&(this.mainQuotaErrorClearedAt===void 0||typeof J.checkedAt!=="number"||J.checkedAt>this.mainQuotaErrorClearedAt)&&(this.mainLastApiError?.checkedAt===void 0||J.checkedAt>=this.mainLastApiError.checkedAt)&&T0(J,this.now())){if(this.mainLastApiError=J,z!==void 0)this.mainQuotaErrorGeneration=z;return}if(this.mainAccountId!==void 0&&this.mainLastApiError?.accountIdentity!==void 0&&this.mainLastApiError.accountIdentity!==this.mainAccountId)this.mainLastApiError=void 0}seedFallbacksFromAccounts($){let J=V0(this.storage),Z=new Set($.map((z)=>z.id));for(let z of this.fallbackAuthLineages.keys())if(!Z.has(z))this.clearFallback(z),this.fallbackAuthLineages.delete(z);for(let z of $){if(this.bindFallbackLineage(z.id,z))continue;if(z.enabled===!1)continue;let X=z.lastQuotaRefreshError,Y=U0(z.quota),K=this.fallbackApiErrors.get(z.id);if(X&&T0(X,this.now())&&Y<=(X.checkedAt??0)&&(!K||X.checkedAt>=K.checkedAt))this.fallbackApiErrors.set(z.id,X);else if(K&&Y>=K.checkedAt)this.fallbackApiErrors.delete(z.id);if(!z.quota)continue;let V=U0(z.quota);if(V<=0)continue;let W=this.getFallback(z.id);if(W&&W.checkedAt>=V)continue;this.setFallback(z.id,{quota:{...z.quota,accountIdentity:z.id},refreshAfter:V+J,checkedAt:V},z)}}isBackedOff(){return T0(this.mainLastApiError,this.now())}isFallbackBackedOff($){return T0(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=s0(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($,J){if(!J)return!1;let Z=this.fallbackAuthLineages.has($),z=this.fallbackAuthLineages.get($),G=Z&&J.authLineageId!==void 0&&z!==J.authLineageId;if(G)this.clearFallback($);return this.fallbackAuthLineages.set($,J.authLineageId),G}acceptFallbackQuotaObservation($,J){let Z=this.fallbackAuthLineages.has($),z=this.fallbackAuthLineages.get($),G=J?.authLineageId;if(Z&&z!==G)return M.trace("quota","skipped stale fallback quota observation after lineage change",{accountId:$,storedLineage:z,servedLineage:G}),!1;if(!Z)this.fallbackAuthLineages.set($,G);return!0}_enqueueApiFetch($){let J=async()=>{let z=this.now()-this.lastApiCallAt;if(z<O0.API_CALL_GAP_MS)await new Promise((G)=>{let X=PJ(G,O0.API_CALL_GAP_MS-z);if(typeof X==="object"&&"unref"in X)X.unref()});return this.lastApiCallAt=this.now(),$()},Z=this.apiGate.then(J,J);return this.apiGate=Z.catch(()=>{}),Z}async _fetchMain($,J,Z){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!==Z)return{quota:{accountIdentity:$},fetched:!1};let z=await b0({name:"opencode-main-quota-refresh",ttlMs:30000});if(!z){let G=this.main;if(G&&this.mainAccountId===$&&this.now()<G.refreshAfter)return{quota:G.quota,fetched:!1};throw Error("Quota refresh is already in progress")}try{let G=this.now(),X=await t1({accessToken:J,fetchImpl:this.fetchImpl,now:this.now}),Y=this.now();if(this.mainQuotaIdentityKnown&&this.mainQuotaIdentityStrict&&this.mainGeneration!==Z)return{quota:{...X,...$!==void 0&&{accountIdentity:$}},fetched:!0};let K=O3(this.mainAccountId===$&&(!this.mainQuotaIdentityKnown||!this.mainQuotaIdentityStrict||this.main?.quota.accountIdentity===$)?this.main?.quota:void 0,{...X,...$!==void 0&&{accountIdentity:$}});if(this.mainAccountId=$,this.main={quota:K,refreshAfter:E0(K,this.storage,Y),checkedAt:K.checkedAt??Y},this.mainLastApiError)this.mainLastApiError=void 0,this.mainQuotaErrorGeneration+=1,this.mainQuotaErrorClearedAt=s0(this.mainQuotaErrorClearedAt,Y);return this.onMainQuotaFetched?.(K,Y,J0(J),G,this.mainQuotaErrorGeneration,this.mainQuotaErrorClearedAt),{quota:K,fetched:!0}}catch(G){throw this._handleMainFetchError(G,Z),G}finally{await z.release()}}finally{if(this.inflightMainAccountId===$)this.inflightMain=null,this.inflightMainAccountId=void 0}})}async _fetchFallback($,J,Z,z){return this._enqueueApiFetch(async()=>{try{if((this.fallbackGenerations.get($)??0)!==Z)return{quota:{accountIdentity:$},fetched:!1};if(this.isFallbackBackedOff($)){let X=this.getFallback($,z);if(X)return{quota:X.quota,fetched:!1};throw Error("Quota API rate-limited — try again later")}let G=await b0({name:O0.quotaLockName($),ttlMs:30000});if(!G){let X=this.getFallback($,z);if(X&&this.now()<X.refreshAfter)return{quota:X.quota,fetched:!1};throw Error("Quota refresh is already in progress")}try{let X=this.now(),Y=await t1({accessToken:J,fetchImpl:this.fetchImpl,now:this.now}),K=this.now();if((this.fallbackGenerations.get($)??0)!==Z)return{quota:{...Y,accountIdentity:$},fetched:!0};let V=O3(this.getFallback($,z)?.quota,{...Y,accountIdentity:$});return this.setFallback($,{quota:V,refreshAfter:E0(V,this.storage,K),checkedAt:V.checkedAt??K},z),this.fallbackApiErrors.delete($),this.onFallbackQuotaFetched?.($,V,K,X),{quota:V,fetched:!0}}finally{await G.release()}}catch(G){throw this._handleFallbackFetchError($,G,Z),G}})}static isAuthError($){if($.status===401||$6($))return!0;let Z=$ instanceof Error?$.message:String($);return/quota check failed: 401\b/.test(Z)}_handleMainFetchError($,J){if(this.mainGeneration!==J)return;if(this.mainQuotaIdentityKnown&&this.mainQuotaIdentityStrict&&this.mainAccountId===void 0)return;if(O0.isAuthError($))return;this.mainLastApiError=o1({error:$,now:this.now(),accountIdentity:this.mainAccountId,previous:this.mainLastApiError}),this.mainQuotaErrorGeneration+=1,this.onApiError?.(this.mainLastApiError,this.mainQuotaErrorGeneration)}_handleFallbackFetchError($,J,Z){if((this.fallbackGenerations.get($)??0)!==Z)return;if(O0.isAuthError(J))return;let z=this.fallbackApiErrors.get($),G=o1({error:J,now:this.now(),previous:z,accountIdentity:$});this.fallbackApiErrors.set($,G),this.onFallbackApiError?.($,G)}}var AY="claude-quota",M3={five_hour:"5h",seven_day:"1w"};function _$($){return`${Math.round($*10)/10}%`}function O$($,J){let Z=Math.max(0,J-$),z=Math.floor(Z/60000);if(z<1)return"just now";if(z===1)return"1m ago";if(z<60)return`${z}m ago`;let G=Math.floor(z/60),X=z%60;if(X===0)return`${G}h ago`;return`${G}h ${X}m ago`}function FJ($,J){let Z=Date.parse($);if(!Number.isFinite(Z))return $;let z=Z-J;if(z<=0)return"now";let G=Math.max(1,Math.ceil(z/60000));if(G<60)return`in ${G}m`;let X=Math.floor(G/60),Y=G%60;if(Y===0)return`in ${X}h`;return`in ${X}h ${Y}m`}function x3($,J){if(!$)return"";return`, resets ${FJ($,J)}`}function q3($,J,Z,z){if(!J)return` - ${M3[$]}: unknown`;let G=[` - ${M3[$]}: ${_$(J.remainingPercent)} remaining`,` (${_$(J.usedPercent)} used`,`${x3(J.resetsAt,Z)}, checked ${O$(J.checkedAt,Z)})`].join("");return z===$?`${G} •`:G}function D3($){try{return new Intl.NumberFormat("en-US",{style:"currency",currency:$.currency,minimumFractionDigits:$.exponent,maximumFractionDigits:$.exponent}).format($.amountMinor/10**$.exponent)}catch{return`${$.amountMinor} ${$.currency}`}}function SJ($,J){return[` - ${$.title}: ${_$($.remainingPercent)} remaining`,` (${_$($.usedPercent)} used`,`${x3($.resetsAt,J)}, checked ${O$($.checkedAt,J)})`].join("")}function TJ($){return $.label?.trim()||$.id}function AJ($){return $.lastQuotaRefreshError?.message??$.lastRefreshError?.message}function bY($,J=new Map){if(!$?.accounts.length)return[];return $.accounts.filter(E).map((Z)=>{let z=J.get(Z.id)??AJ(Z);return{name:TJ(Z),role:"fallback",enabled:Z.enabled!==!1,quota:Z.quota,...o0(Z.profile)&&{tierLabel:o0(Z.profile)},lastRefreshedAt:Z.lastRefreshedAt,...z&&{error:z}}})}function EY($){let J=$.now??Date.now(),Z=["## Claude Quotas",""];if($.refreshedAt)Z.push(`Refreshed: ${O$($.refreshedAt,J)}`,"");if(!$.accounts.length)return Z.push("No Claude OAuth accounts found yet."),Z.join(`
52
- `);for(let z of $.accounts){let G=z.role==="main"?"main":"fallback",X=z.enabled===!1?" disabled":"";if(Z.push(`### ${z.name} (${G}${X})`),z.tierLabel)Z.push(` - Tier: ${z.tierLabel}`);if(z.lastRefreshedAt)Z.push(` - Last token refresh: ${O$(z.lastRefreshedAt,J)}`);if(z.error)Z.push(` - Error: ${z.error}`);Z.push(q3("five_hour",z.quota?.five_hour,J,z.quota?.bindingWindow)),Z.push(q3("seven_day",z.quota?.seven_day,J,z.quota?.bindingWindow));for(let K of z.quota?.scoped??[]){let V=SJ(K,J);Z.push(z.quota?.bindingWindow===K.id?`${V} •`:V)}let Y=z.quota?.extraUsage;if(Y){let K=D3(Y.used),V=D3(Y.limit);Z.push(` - credits ${K}/${V}${Y.exhausted?" · exhausted":""}`)}if(z.quota?.fallbackAdvised===!0)Z.push(" - → fallback advised");Z.push("")}return Z.join(`
53
- `).trimEnd()}import{Buffer as A3}from"node:buffer";import{createHash as bJ,randomBytes as EJ}from"node:crypto";class f6 extends Error{}class w6 extends Error{code="ECONNRESET";syscall="websocket";closeCode;closeReason;wasClean;constructor($,J){super($);this.name="RelayWebSocketConnectionResetError",this.closeCode=J?.code,this.closeReason=J?.reason,this.wasClean=J?.wasClean}}var N0=new Map,k0=new Map,R3=new Set,IJ=7200000,kJ=1800000,vJ=128,hJ=32,f3=0;function R6(){return f3+=1,`req_${Date.now().toString(36)}_${f3.toString(36)}`}function M$($){if(R3.has($))return;R3.add($),S($)}function mY($){let J=$?.relay;if(!J)return M$("disabled: no relay config found"),null;if(J.enabled!==!0)return M$("disabled: relay.enabled is not true"),null;if(!J.url?.trim()||!J.token?.trim())return M$("disabled: missing relay url or token"),null;let Z=J.transport==="http"?"http":"websocket";return M$(`configured transport=${Z} protocol=${Z==="websocket"?2:1} url=${J.url.trim()} fallbackToDirect=${J.fallbackToDirect!==!1}`),{enabled:!0,url:J.url.trim(),token:J.token.trim(),fallbackToDirect:J.fallbackToDirect!==!1,transport:Z}}function gY(){return EJ(32).toString("base64url")}function yJ($){return`sha256:${bJ("sha256").update($).digest("hex")}`}function w3($,J){let Z=0,z=Math.min($.length,J.length);while(Z<z&&$.charCodeAt(Z)===J.charCodeAt(Z))Z++;let G=$.length,X=J.length;while(G>Z&&X>Z&&$.charCodeAt(G-1)===J.charCodeAt(X-1))G--,X--;return{start:Z,deleteCount:G-Z,insert:J.slice(Z,X)}}function mJ($){return $.deleteCount===0&&$.insert.length===0}function P3($){let J=$.match(/\bcch=([0-9a-f]{5});/),Z=J?.[1];if(!Z||J.index==null)return null;let z=J.index+4;return{start:z,end:z+Z.length,token:Z}}function gJ($,J,Z,z){return`${$.slice(0,J)}${z}${$.slice(Z)}`}function b3($,J){let Z=P3($),z=P3(J);if(Z&&z&&Z.start===z.start&&Z.end-Z.start===z.end-z.start&&Z.token!==z.token){let G={start:Z.start,deleteCount:Z.end-Z.start,insert:z.token},X=gJ($,Z.start,Z.end,z.token),Y=w3(X,J);return mJ(Y)?G:[G,Y]}return w3($,J)}function pJ($,J){if(typeof J!=="string")return!1;try{let Z=$ instanceof Request?new URL($.url):new URL($.toString());return Z.pathname==="/v1/messages"||Z.pathname==="/messages"}catch{return!1}}function lJ($){let J={};for(let[Z,z]of $.entries()){if(Z==="x-session-affinity"||Z==="x-opencode-session")continue;J[Z]=z}return J}async function F3($,J,Z){let z=A(),G=JSON.stringify(J);return J1("http_payload_stringify",{session:b(J.affinity),ms:a(A()-z),relayBytes:G.length,mode:J.mode}),fetch($.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":$.token},body:G,signal:Z??void 0})}function b($){return $.length>12?`${$.slice(0,12)}…`:$}function A(){return performance.now()}function a($){return Math.round($*10)/10}function uJ(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function J1($,J){if(!uJ())return;S(`[perf] relay ${$} ${JSON.stringify(J)}`)}function sJ($){let{input:J,init:Z,headers:z,bodyText:G,affinity:X,previous:Y,nextHash:K}=$,V=J instanceof Request?J.url:J.toString(),W={protocol:1,type:"request",affinity:X,upstream:{url:V,method:Z?.method||(J instanceof Request?J.method:"POST"),headers:lJ(z)},next_hash:K};return Y?{...W,mode:"patch",base_hash:Y.hash,revision:Y.revision+1,patch:b3(Y.body,G)}:{...W,mode:"full_sync",revision:1,body:G}}function P6($,J){return{protocol:$.protocol,type:"request",affinity:$.affinity,upstream:$.upstream,next_hash:$.next_hash,mode:"full_sync",revision:1,body:J}}function E3($,J,Z,z){let G=Date.now();N0.delete($),N0.set($,{body:J,hash:Z,revision:z,updatedAt:G}),F6(G)}async function S3($){let{config:J,payload:Z,bodyText:z,fallback:G,signal:X}=$,Y=Z,K=await F3(J,Y,X);if(K.status===409&&Y.mode==="patch")S(`state mismatch from relay session=${b(Y.affinity)}; retrying full_sync`),await K.body?.cancel().catch(()=>{}),Y=P6(Y,z),K=await F3(J,Y,X);if(!K.ok&&K.status>=500&&J.fallbackToDirect)return S(`relay returned ${K.status}; falling back direct session=${b(Y.affinity)}`),await K.body?.cancel().catch(()=>{}),{response:await G(),payload:Y,transport:"http",protocol:Y.protocol,usedRelay:!1};return{response:K,payload:Y,transport:"http",protocol:Y.protocol,usedRelay:!0}}function dJ($,J){let Z=new URL($);return Z.protocol=Z.protocol==="http:"?"ws:":"wss:",Z.pathname="/ws",Z.searchParams.set("token",J),Z.toString()}function iJ($){return new Uint8Array(A3.from($,"base64"))}function cJ($){if($ instanceof Uint8Array)return $;if($ instanceof ArrayBuffer)return new Uint8Array($);if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);return new Uint8Array(A3.from(String($)))}function nJ($){return JSON.parse($)}function T3($){let J=$,Z=[`code=${J.code??"unknown"}`,`wasClean=${J.wasClean??"unknown"}`];if(J.reason)Z.push(`reason=${JSON.stringify(J.reason)}`);return Z.join(" ")}function aJ($){let J=$.message||"relay websocket error";return $.status?`relay websocket error ${$.status}: ${J}`:J}class I3{config;affinity;timers;socket;connecting;queue=Promise.resolve();pending;serverState;lastUsedAt=Date.now();constructor($,J,Z){this.config=$,this.affinity=J,this.timers=Z}touch($=Date.now()){this.lastUsedAt=$}canEvict($=Date.now()){return!this.pending&&!this.connecting&&$-this.lastUsedAt>kJ}dispose(){this.socket?.close(),this.socket=void 0,this.serverState=void 0,this.connecting=void 0}send($,J,Z=!1,z){this.touch();let G=A(),X=this.queue.catch(()=>{}).then(()=>this.startQueued($,J,G,Z,z)),Y=X.then(async({response:K,getPayload:V})=>({response:await K,payload:V(),transport:"websocket",protocol:2,usedRelay:!0}));return this.queue=X.then(({done:K})=>K.catch(()=>{}),()=>{}),Y}async startQueued($,J,Z,z,G){let X=A();await this.ensureConnected();let Y=A(),K=N0.get(this.affinity),V=this.serverState?.hash,W={...$,protocol:2,id:R6()};if(W.mode==="patch"&&(!V||V!==W.base_hash))W.mode="full_sync",W.revision=(this.serverState?.revision??0)+1,delete W.base_hash,delete W.patch,W.body=J;if(W.mode==="patch"&&K)W.patch=b3(K.body,J);S(`perf websocket send_start session=${b(this.affinity)} request=${W.id} mode=${W.mode} queueMs=${a(Y-Z)} connectMs=${a(Y-X)} bodyBytes=${J.length} relayBytes=${JSON.stringify(W).length}`);let j=W,H=this.sendPayload(W,J,z,G);H.done.catch(()=>{});let Q=H.done,U=H.response.catch((O)=>{if(!(O instanceof f6)||W.mode!=="patch")throw O;let q=P6(W,J);q.protocol=2,q.id=R6(),q.revision=(this.serverState?.revision??0)+1,j=q;let D=this.sendPayload(q,J,z,G);return D.done.catch(()=>{}),Q=D.done,D.response}),B=U.then(()=>Q,()=>Q.catch(()=>{}));return{response:U,done:B,getPayload:()=>j}}async ensureConnected(){if(this.socket?.readyState===WebSocket.OPEN&&this.serverState!==void 0)return;if(this.connecting)return await this.connecting;this.connecting=new Promise(($,J)=>{let Z=dJ(this.config.url,this.config.token),z=new URL(Z);z.searchParams.set("affinity",this.affinity);let G=new WebSocket(z.toString());this.socket=G,this.serverState=void 0;let X=this.timers.setTimeout(()=>{G.close(),J(Error("relay websocket ready timed out"))},15000);G.addEventListener("message",(Y)=>{try{if(typeof Y.data!=="string"){this.handleBinaryChunk(Y.data);return}let K=nJ(Y.data);if(K.type==="ready"){this.timers.clearTimeout(X),this.serverState=K.state,$();return}this.handleMessage(K)}catch(K){this.timers.clearTimeout(X),J(K),this.failPending(K),G.close()}}),G.addEventListener("error",()=>{this.timers.clearTimeout(X);let Y=new w6("relay websocket error");J(Y),this.failPending(Y)}),G.addEventListener("close",(Y)=>{if(this.timers.clearTimeout(X),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,V=K?"closed after response_start before stream bytes":"closed before response";if(this.retryPendingBeforeResponse(this.pending,V,Y))return;let W=K?new w6("relay websocket closed during response stream",Y):Error("relay websocket closed before response");S(`websocket ${K?"closed during response stream":"closed before response without retry"} session=${b(this.affinity)} request=${this.pending.payload.id} chunks=${this.pending.streamChunkCount} bytes=${this.pending.streamByteCount} ${T3(Y)}`),this.failPending(W)}})}).finally(()=>{this.connecting=void 0}),await this.connecting}sendPayload($,J,Z,z){let G=this.socket;if(!G||G.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");let X=A(),Y,K,V=new Promise((j,H)=>{Y=j,K=H});return{response:new Promise((j,H)=>{let Q={payload:$,bodyText:J,resolve:j,reject:H,streamDone:!1,accepted:!1,responseStarted:!1,resolveDone:Y,rejectDone:K,sentAt:X,optimisticResponse:Z,streamChunkCount:0,streamByteCount:0,retryAttempts:0,retryingBeforeResponse:!1,onResponseHeaders:z,stagedResponseHeaders:void 0,responseHeadersDelivered:!1};if(this.pending=Q,this.resetPendingTimeout(Q),G.send(JSON.stringify($)),Z)this.resolvePendingResponse(Q,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($,J,Z){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 z=$.retryAttempts,G=$.payload.id;return S(`websocket ${J}; reconnecting and retrying full_sync session=${b(this.affinity)} request=${G} retry=${z} chunks=${$.streamChunkCount} bytes=${$.streamByteCount}${Z?` ${T3(Z)}`:""}`),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 X=P6($.payload,$.bodyText);X.protocol=2,X.id=R6(),X.revision=(this.serverState?.revision??0)+1,$.payload=X,$.accepted=!1,$.acceptedAt=void 0,$.responseStartedAt=void 0,$.stagedResponseHeaders=void 0,$.responseHeadersDelivered=!1,$.sentAt=A(),$.retryingBeforeResponse=!1;let Y=this.socket;if(!Y||Y.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");this.resetPendingTimeout($),S(`perf websocket retry_send session=${b(this.affinity)} request=${X.id} previous=${G} mode=full_sync retry=${z} bodyBytes=${$.bodyText.length} relayBytes=${JSON.stringify(X).length}`),Y.send(JSON.stringify(X))}catch(X){if($.retryingBeforeResponse=!1,this.pending===$)this.failPending(X)}})(),!0}enqueueStreamChunk($,J){this.deliverResponseHeaders($),$.streamChunkCount+=1,$.streamByteCount+=J.byteLength,$.streamController?.enqueue(J)}deliverResponseHeaders($){if($.responseHeadersDelivered||$.stagedResponseHeaders==null)return;$.responseHeadersDelivered=!0;try{$.onResponseHeaders?.($.stagedResponseHeaders)}catch{}}handleBinaryChunk($){let J=this.pending;if(!J?.responseStarted)return;this.enqueueStreamChunk(J,cJ($))}resolvePendingResponse($,J,Z,z){if($.responseStarted)return;$.responseStarted=!0;let G=new ReadableStream({start:(X)=>{$.streamController=X},cancel:()=>{this.socket?.close()}});$.resolve(new Response(G,{status:J,statusText:Z,headers:z}))}handleMessage($){if($.type==="keepalive"){if(this.pending)this.resetPendingTimeout(this.pending);return}let J=this.pending;if(!J)return;if("id"in $&&$.id&&$.id!==J.payload.id)return;if($.type==="accepted"){let Z=A();J.accepted=!0,J.acceptedAt=Z,S(`perf websocket accepted session=${b(this.affinity)} request=${J.payload.id} sentMs=${a(Z-J.sentAt)} mode=${J.payload.mode}`),this.serverState={hash:$.hash,revision:$.revision},E3(this.affinity,J.bodyText,$.hash,$.revision),this.resetPendingTimeout(J);return}if($.type==="response_start"){if(J.responseStartedAt!=null)return;let Z=A();if(J.responseStartedAt=Z,S(`perf websocket response_start session=${b(this.affinity)} request=${J.payload.id} sentMs=${a(Z-J.sentAt)} upstreamMs=${J.acceptedAt==null?"unknown":a(Z-J.acceptedAt)} status=${$.status}`),clearTimeout(J.timeout),$.headers)J.stagedResponseHeaders=new Headers($.headers);if(this.resolvePendingResponse(J,$.status,$.statusText,$.headers),J.optimisticResponse&&$.status>=400)this.deliverResponseHeaders(J),J.streamController?.enqueue(new TextEncoder().encode(`event: error
54
- data: ${JSON.stringify({type:"error",error:{type:"relay_upstream_error",message:`Relay upstream returned HTTP ${$.status}`}})}
55
-
56
- `)),this.finishPending();return}if($.type==="chunk"){this.enqueueStreamChunk(J,iJ($.base64));return}if($.type==="done"){this.finishPending($);return}if($.type==="error"){if(J.optimisticResponse&&J.responseStartedAt!=null){S(`websocket relay error during optimistic response session=${b(this.affinity)} request=${J.payload.id} status=${$.status} message=${$.message||"unknown"} chunks=${J.streamChunkCount} bytes=${J.streamByteCount}`),this.deliverResponseHeaders(J),J.streamController?.enqueue(new TextEncoder().encode(`event: error
57
- data: ${JSON.stringify({type:"error",error:{type:"relay_error",message:$.message||"relay error"}})}
58
-
59
- `)),this.finishPending(),this.socket?.close();return}if($.status===409&&this.retryPendingBeforeResponse(J,$.message||"state mismatch"))return;let Z=$.status===409?new f6($.message||"state mismatch"):Error(aJ($));this.failPending(Z)}}finishPending($){let J=this.pending;if(!J)return;let Z=A(),z=$&&"frames"in $?` upstreamChunks=${$.upstreamChunks??"unknown"} upstreamBytes=${$.upstreamBytes??"unknown"} frames=${$.frames} frameBytes=${$.frameBytes??"unknown"}`:"";if(S(`perf websocket done session=${b(this.affinity)} request=${J.payload.id} sentMs=${a(Z-J.sentAt)} streamMs=${J.responseStartedAt==null?"unknown":a(Z-J.responseStartedAt)} chunks=${J.streamChunkCount} bytes=${J.streamByteCount}${z}`),this.timers.clearTimeout(J.timeout),!J.streamDone)this.deliverResponseHeaders(J),J.streamDone=!0,J.streamController?.close();J.resolveDone(),this.pending=void 0}failPending($){let J=this.pending;if(!J)return;if(this.timers.clearTimeout(J.timeout),this.pending=void 0,J.responseStarted)J.streamController?.error($);else J.reject($);J.rejectDone($)}}function F6($=Date.now()){for(let[J,Z]of N0)if($-Z.updatedAt>IJ)N0.delete(J);while(N0.size>vJ){let J=N0.keys().next().value;if(J===void 0)break;N0.delete(J)}for(let[J,Z]of k0)if(Z.canEvict($))Z.dispose(),k0.delete(J);while(k0.size>hJ){let J=!1;for(let[Z,z]of k0){if(!z.canEvict($))continue;z.dispose(),k0.delete(Z),J=!0;break}if(!J)break}}function oJ($,J,Z){F6();let z=k0.get(J);if(z)return z.touch(),z;let G=new I3($,J,Z);return k0.set(J,G),F6(),G}async function pY($){let{config:J,input:Z,init:z,headers:G,body:X,fallback:Y,affinity:K,optimisticResponse:V,onResponseHeaders:W,dumpTag:j,onDumpCreated:H,setTimeoutImpl:Q=globalThis.setTimeout,clearTimeoutImpl:U=globalThis.clearTimeout}=$;if(!J||!pJ(Z,X))return Y();let B=K||G.get("x-session-affinity")||G.get("x-opencode-session");if(!B)return S("skipping relay: missing x-session-affinity header"),Y();let O=X,q=A(),D=yJ(O);J1("hash_body",{session:b(B),ms:a(A()-q),bodyBytes:O.length});let L=N0.get(B),x=A(),k=sJ({input:Z,init:z,headers:G,bodyText:O,affinity:B,previous:L,nextHash:D});J1("create_payload",{session:b(B),ms:a(A()-x),mode:k.mode,bodyBytes:O.length,previousBytes:L?.body.length});try{let N,T=A();if(J.transport==="websocket")try{N=await oJ(J,B,{setTimeout:Q,clearTimeout:U}).send(k,O,V===!0,W)}catch(c){S(`websocket relay failed session=${b(B)}; trying http relay: ${c instanceof Error?c.message:String(c)}`),N=await S3({config:J,payload:k,bodyText:O,fallback:Y,signal:z?.signal})}else N=await S3({config:J,payload:k,bodyText:O,fallback:Y,signal:z?.signal});if(J1("send",{session:b(B),ms:a(A()-T),transport:N.transport,protocol:N.protocol,mode:N.payload.mode,status:N.response.status,usedRelay:N.usedRelay}),!N.usedRelay)return N.response;if(N.transport==="http")try{W?.(N.response.headers)}catch{}if(N.transport==="http")E3(B,O,N.payload.next_hash,N.payload.revision);let h=A(),e=JSON.stringify(N.payload).length;J1("payload_stringify",{session:b(B),ms:a(A()-h),relayBytes:e}),S(`used relay transport=${N.transport} protocol=${N.protocol} mode=${N.payload.mode} status=${N.response.status} session=${b(B)} bodyBytes=${O.length} relayBytes=${e}`);let x1=A(),M0=await k4({affinity:B,transport:N.transport,protocol:N.protocol,mode:N.payload.mode,status:N.response.status,bodyText:O,previousBodyText:L?.body,payload:N.payload,relayBytes:e,tag:j});try{if(M0)H?.(M0)}catch{}return J1("dump",{session:b(B),ms:a(A()-x1),enabled:!0}),N.response}catch(N){if(!J.fallbackToDirect)throw S(`relay failed session=${b(B)} and fallbackToDirect=false: ${N instanceof Error?N.message:String(N)}`),N;return S(`relay failed; falling back direct session=${b(B)}: ${N instanceof Error?N.message:String(N)}`),Y()}}var lY=`
60
- async function hashBody(body) {
61
- const bytes = new TextEncoder().encode(body)
62
- const digest = await crypto.subtle.digest('SHA-256', bytes)
63
- const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')
64
- return 'sha256:' + hex
65
- }
66
-
67
- function applyPatch(base, patch) {
68
- return base.slice(0, patch.start) + patch.insert + base.slice(patch.start + patch.deleteCount)
69
- }
70
-
71
- function applyPatchSet(base, patch) {
72
- if (!Array.isArray(patch)) return applyPatch(base, patch)
73
- if (patch.length === 0) return base
74
-
75
- let result = ''
76
- let cursor = 0
77
- for (const item of patch) {
78
- if (item.start < cursor) return { error: 'overlapping patch', status: 400 }
79
- result += base.slice(cursor, item.start)
80
- result += item.insert
81
- cursor = item.start + item.deleteCount
82
- }
83
- return result + base.slice(cursor)
84
- }
85
-
86
- async function readState(env, affinity) {
87
- const raw = await env.RELAY_STATE.get('session:' + affinity)
88
- return raw ? JSON.parse(raw) : null
89
- }
90
-
91
- async function writeState(env, affinity, state) {
92
- await env.RELAY_STATE.put('session:' + affinity, JSON.stringify(state), { expirationTtl: 86400 })
93
- }
94
-
95
- async function resolveBody(env, payload) {
96
- if (payload.mode === 'full_sync') return payload.body
97
- if (payload.mode === 'patch') {
98
- const state = await readState(env, payload.affinity)
99
- if (!state || state.hash !== payload.base_hash) {
100
- return { error: 'state mismatch', status: 409 }
101
- }
102
- return applyPatchSet(state.body, payload.patch)
103
- }
104
- return { error: 'unknown mode', status: 400 }
105
- }
106
-
107
- async function prepareUpstream(env, payload) {
108
- if ((payload.protocol !== 1 && payload.protocol !== 2) || payload.type !== 'request' || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {
109
- return { error: 'invalid payload', status: 400 }
110
- }
111
-
112
- const body = await resolveBody(env, payload)
113
- if (body && typeof body === 'object' && 'error' in body) return body
114
-
115
- if (typeof body !== 'string' || (await hashBody(body)) !== payload.next_hash) {
116
- return { error: 'hash mismatch', status: 409 }
117
- }
118
-
119
- const stateWrite = writeState(env, payload.affinity, { body, hash: payload.next_hash, revision: payload.revision }).catch(() => {})
120
- console.log(JSON.stringify({
121
- relay: 'opencode-anthropic-auth',
122
- transport: 'relay',
123
- mode: payload.mode,
124
- revision: payload.revision,
125
- affinity: String(payload.affinity).slice(0, 12),
126
- bodyBytes: body.length,
127
- }))
128
-
129
- return { body, stateWrite }
130
- }
131
-
132
- function resolveBodyFromState(state, payload) {
133
- if (payload.mode === 'full_sync') return payload.body
134
- if (payload.mode === 'patch') {
135
- if (!state || state.hash !== payload.base_hash) {
136
- return { error: 'state mismatch', status: 409 }
137
- }
138
- return applyPatchSet(state.body, payload.patch)
139
- }
140
- return { error: 'unknown mode', status: 400 }
141
- }
142
-
143
- function deferWorkerTask(task) {
144
- return new Promise((resolve) => setTimeout(resolve, 0)).then(task)
145
- }
146
-
147
- const WEBSOCKET_STREAM_FLUSH_BYTES = 1024
148
- const WEBSOCKET_STREAM_FLUSH_MS = 20
149
-
150
- function createWebSocketStreamCoalescer(socket, options = {}) {
151
- const flushBytes = options.flushBytes || WEBSOCKET_STREAM_FLUSH_BYTES
152
- const flushMs = options.flushMs ?? WEBSOCKET_STREAM_FLUSH_MS
153
- let chunks = []
154
- let byteLength = 0
155
- let flushTimer = null
156
- const stats = {
157
- upstreamChunks: 0,
158
- upstreamBytes: 0,
159
- frames: 0,
160
- frameBytes: 0,
161
- }
162
-
163
- const clearFlushTimer = () => {
164
- if (flushTimer === null) return
165
- clearTimeout(flushTimer)
166
- flushTimer = null
167
- }
168
-
169
- const mergeChunks = () => {
170
- if (chunks.length === 1) return chunks[0]
171
- const frame = new Uint8Array(byteLength)
172
- let offset = 0
173
- for (const chunk of chunks) {
174
- frame.set(chunk, offset)
175
- offset += chunk.byteLength
176
- }
177
- return frame
178
- }
179
-
180
- const flush = () => {
181
- clearFlushTimer()
182
- if (byteLength === 0) return
183
- const frame = mergeChunks()
184
- chunks = []
185
- byteLength = 0
186
- socket.send(frame)
187
- stats.frames += 1
188
- stats.frameBytes += frame.byteLength
189
- }
190
-
191
- const scheduleFlush = () => {
192
- if (flushTimer !== null) return
193
- flushTimer = setTimeout(flush, flushMs)
194
- }
195
-
196
- return {
197
- push(value) {
198
- const chunk = value instanceof Uint8Array ? value : new Uint8Array(value)
199
- if (chunk.byteLength === 0) return
200
- stats.upstreamChunks += 1
201
- stats.upstreamBytes += chunk.byteLength
202
- chunks.push(chunk)
203
- byteLength += chunk.byteLength
204
- if (byteLength >= flushBytes) flush()
205
- else scheduleFlush()
206
- },
207
- flush,
208
- stats() {
209
- return { ...stats, pendingBytes: byteLength }
210
- },
211
- }
212
- }
213
-
214
- function checkpointWebSocketState(env, payload, body, nextState) {
215
- return deferWorkerTask(async () => {
216
- try {
217
- if ((await hashBody(body)) !== payload.next_hash) {
218
- throw new Error('hash mismatch')
219
- }
220
- await writeState(env, payload.affinity, nextState)
221
- } catch (error) {
222
- console.log(JSON.stringify({
223
- relay: 'opencode-anthropic-auth',
224
- transport: 'websocket',
225
- event: 'checkpoint_write_failed',
226
- affinity: String(payload.affinity).slice(0, 12),
227
- message: error instanceof Error ? error.message : String(error),
228
- }))
229
- }
230
- })
231
- }
232
-
233
- async function prepareWebSocketUpstream(env, state, payload) {
234
- if (payload.protocol !== 2 || payload.type !== 'request' || !payload.id || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {
235
- return { error: 'invalid payload', status: 400 }
236
- }
237
-
238
- const body = resolveBodyFromState(state, payload)
239
- if (body && typeof body === 'object' && 'error' in body) return body
240
- if (typeof body !== 'string') return { error: 'invalid body', status: 400 }
241
- if ((await hashBody(body)) !== payload.next_hash) {
242
- return { error: 'hash mismatch', status: 409 }
243
- }
244
-
245
- const nextState = { body, hash: payload.next_hash, revision: payload.revision }
246
- const checkpoint = checkpointWebSocketState(env, payload, body, nextState)
247
- const logAccepted = () => console.log(JSON.stringify({
248
- relay: 'opencode-anthropic-auth',
249
- transport: 'websocket',
250
- mode: payload.mode,
251
- revision: payload.revision,
252
- affinity: String(payload.affinity).slice(0, 12),
253
- bodyBytes: body.length,
254
- }))
255
-
256
- return { body, state: nextState, checkpoint, logAccepted }
257
- }
258
-
259
- function headersToObject(headers) {
260
- const result = {}
261
- for (const [key, value] of headers.entries()) result[key] = value
262
- return result
263
- }
264
-
265
- async function handleRelayPayload(env, payload) {
266
- const prepared = await prepareUpstream(env, payload)
267
- if (prepared.error) return prepared
268
- const upstream = await fetch(payload.upstream.url, {
269
- method: payload.upstream.method || 'POST',
270
- headers: payload.upstream.headers,
271
- body: prepared.body,
272
- })
273
- return { upstream, stateWrite: prepared.stateWrite }
274
- }
275
-
276
- async function handleWebSocket(socket, env, ctx, payload, getState, setState) {
277
- const heartbeat = setInterval(() => {
278
- try {
279
- socket.send(JSON.stringify({ protocol: 2, type: 'keepalive' }))
280
- } catch {
281
- clearInterval(heartbeat)
282
- }
283
- }, 15000)
284
- let streamCoalescer = null
285
- try {
286
- const result = await prepareWebSocketUpstream(env, getState(), payload)
287
- if (result.error) {
288
- socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: result.status, message: result.error }))
289
- return
290
- }
291
-
292
- setState(result.state)
293
- socket.send(JSON.stringify({ protocol: 2, type: 'accepted', id: payload.id, hash: result.state.hash, revision: result.state.revision }))
294
- ctx?.waitUntil?.(deferWorkerTask(result.logAccepted))
295
-
296
- const upstreamPromise = fetch(payload.upstream.url, {
297
- method: payload.upstream.method || 'POST',
298
- headers: payload.upstream.headers,
299
- body: result.body,
300
- })
301
- ctx?.waitUntil?.(result.checkpoint)
302
- const upstream = await upstreamPromise
303
- socket.send(JSON.stringify({
304
- protocol: 2,
305
- type: 'response_start',
306
- id: payload.id,
307
- status: upstream.status,
308
- statusText: upstream.statusText,
309
- headers: headersToObject(upstream.headers),
310
- }))
311
-
312
- const reader = upstream.body?.getReader()
313
- if (reader) {
314
- streamCoalescer = createWebSocketStreamCoalescer(socket)
315
- while (true) {
316
- const { done, value } = await reader.read()
317
- if (done) break
318
- streamCoalescer.push(value)
319
- }
320
- streamCoalescer.flush()
321
- }
322
- const stats = streamCoalescer?.stats?.() || {}
323
- socket.send(JSON.stringify({ protocol: 2, type: 'done', id: payload.id, ...stats }))
324
- } catch (error) {
325
- try {
326
- streamCoalescer?.flush?.()
327
- } catch {}
328
- socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: 500, message: error instanceof Error ? error.message : String(error) }))
329
- } finally {
330
- clearInterval(heartbeat)
331
- }
332
- }
333
-
334
- export default {
335
- async fetch(request, env, ctx) {
336
- if (request.headers.get('Upgrade') === 'websocket') {
337
- const url = new URL(request.url)
338
- const token = url.searchParams.get('token')
339
- const affinity = url.searchParams.get('affinity')
340
- if (token !== env.RELAY_TOKEN) return new Response('unauthorized', { status: 401 })
341
- if (!affinity) return new Response('missing affinity', { status: 400 })
342
- const pair = new WebSocketPair()
343
- const client = pair[0]
344
- const server = pair[1]
345
- server.binaryType = 'arraybuffer'
346
- let state = null
347
- let ready = false
348
- server.accept()
349
- const loadState = readState(env, affinity).then((loadedState) => {
350
- state = loadedState
351
- ready = true
352
- server.send(JSON.stringify({
353
- protocol: 2,
354
- type: 'ready',
355
- state: state ? { hash: state.hash, revision: state.revision } : null,
356
- }))
357
- }).catch((error) => {
358
- server.send(JSON.stringify({ protocol: 2, type: 'error', status: 500, message: error instanceof Error ? error.message : String(error) }))
359
- server.close(1011, 'state load failed')
360
- })
361
- ctx?.waitUntil?.(loadState)
362
- if (!ctx?.waitUntil) void loadState
363
- let busy = false
364
- server.addEventListener('message', (event) => {
365
- if (!ready) {
366
- server.send(JSON.stringify({ protocol: 2, type: 'error', status: 425, message: 'relay state is not ready' }))
367
- return
368
- }
369
- if (busy) {
370
- server.send(JSON.stringify({ protocol: 2, type: 'error', status: 429, message: 'request already in flight' }))
371
- return
372
- }
373
- let payload
374
- try {
375
- payload = JSON.parse(event.data)
376
- } catch {
377
- server.send(JSON.stringify({ protocol: 2, type: 'error', status: 400, message: 'invalid JSON payload' }))
378
- return
379
- }
380
- payload.affinity = affinity
381
- busy = true
382
- const run = handleWebSocket(server, env, ctx, payload, () => state, (nextState) => { state = nextState }).finally(() => { busy = false })
383
- ctx?.waitUntil?.(run)
384
- if (!ctx?.waitUntil) void run
385
- })
386
- return new Response(null, { status: 101, webSocket: client })
387
- }
388
-
389
- if (request.method === 'GET') {
390
- return Response.json({ status: 'ok', transports: ['http', 'websocket'] })
391
- }
392
- if (request.method !== 'POST') return new Response('method not allowed', { status: 405 })
393
- if (request.headers.get('x-relay-token') !== env.RELAY_TOKEN) {
394
- return new Response('unauthorized', { status: 401 })
395
- }
396
-
397
- try {
398
- const payload = await request.json()
399
- const result = await handleRelayPayload(env, payload)
400
- if (result.error) return Response.json({ error: result.error }, { status: result.status })
401
-
402
- if (result.stateWrite) ctx.waitUntil(result.stateWrite)
403
-
404
- const upstream = result.upstream
405
- return new Response(upstream.body, {
406
- status: upstream.status,
407
- statusText: upstream.statusText,
408
- headers: upstream.headers,
409
- })
410
- } catch (error) {
411
- return Response.json(
412
- { error: error instanceof Error ? error.message : 'internal relay error' },
413
- { status: 502 },
414
- )
415
- }
416
- },
417
- }
418
- `;var dY="claude-routing",S6=["main-first","fallback-first","sticky-balanced"],T6="main-first",k3="Usage: `/claude-routing`, `/claude-routing main-first`, `/claude-routing fallback-first`, `/claude-routing sticky-balanced`, or `/claude-routing reset`.";function tJ($){return typeof $==="string"&&S6.includes($)?$:T6}function iY($){return tJ($?.routing?.mode)}async function cY($,J=R()){let Z=await F(J)??v();return Z.routing={...Z.routing??{},mode:$},await p(Z,J),Z}function rJ($){let J=$.trim().toLowerCase().split(/\s+/).filter(Boolean);if(J.length===0)return{type:"status"};if(J.length===1&&J[0]==="reset")return{type:"reset"};if(J.length===1&&S6.includes(J[0]))return{type:"mode",mode:J[0]};if(J.length===2&&J[0]==="mode"&&S6.includes(J[1]))return{type:"mode",mode:J[1]};return{type:"usage"}}function eJ($){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 q$($){let J=$?.mode??T6;return["## Claude Routing Status","",`- Mode: \`${J}\``,`- Behavior: ${eJ(J)}`,"",k3].join(`
419
- `)}function nY($){let J=rJ($.argumentsText),Z=$.mode??T6;if(J.type==="status")return q$({mode:Z});if(J.type==="mode")return["## Claude Routing Updated","",`Mode updated to \`${J.mode}\`.`,"",...q$({mode:J.mode}).split(`
420
- `).slice(2)].join(`
421
- `);if(J.type==="reset")return["## Claude Routing Assignment Reset","","The current session will be assigned again on its next request.","",...q$({mode:Z}).split(`
422
- `).slice(2)].join(`
423
- `);return["## Claude Routing Usage","",k3,"",...q$({mode:Z}).split(`
424
- `).slice(2)].join(`
425
- `)}var oY="claude-start";function $Z($){if($.trim().split(/\s+/).filter(Boolean).length===0)return{type:"fire"};return{type:"usage"}}function tY($){let J=$Z($.argumentsText);if(J.type==="fire")return{action:J,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(`
426
- `)};return{action:J,text:["## Claude Lane Start Usage","","Usage: `/claude-start`.","","## Claude Lane Start Status"].join(`
427
- `)}}import{createHash as s3,randomUUID as JZ}from"node:crypto";import{mkdir as ZZ,readFile as zZ,rename as GZ,rm as XZ,stat as YZ,writeFile as KZ}from"node:fs/promises";import{basename as VZ,dirname as d3,join as WZ}from"node:path";var jZ="main",HZ=900000,v3=604800000,QZ=3600000,UZ=1e4,NZ=5000,BZ=10,h3=4096,LZ=0.000001;function GK($){let J=$.modelId,Z=J?$.routeQuotas.map((Q)=>r(Q,J)).find(Boolean)?.modelName:void 0,z;if(c0($.mainRefreshError))z=Z?`Main Claude OAuth account requires re-login, and no fallback OAuth account is currently routable for ${Z}.`:"Main Claude OAuth account requires re-login, and no fallback OAuth account is currently routable.";else if($.fallbackReauthLabels?.length)z=`No OAuth account is currently routable${Z?` for ${Z}`:""}. Fallback Claude OAuth accounts require re-login: ${$.fallbackReauthLabels.join(", ")}.`;if(z)return new Response(JSON.stringify({type:"error",error:{type:"authentication_error",message:z}}),{status:401,headers:{"content-type":"application/json"}});let G=Boolean(J&&$.routeQuotas.length>0&&$.routeQuotas.every((Q)=>!i1(Q,J))),[X,...Y]=$.routeQuotas,K=X4(X,Y.map((Q)=>({quota:Q})),$.now??Date.now(),G?J:void 0),V=Math.floor(K/60),W=K%60,H=`${G&&Z?`${Z} weekly limit reached, no routable OAuth accounts.`:"No OAuth account currently satisfies sticky-balanced quota policy."} Retry in ${V}m ${W}s.`;return new Response(JSON.stringify({type:"error",error:{type:"rate_limit_error",message:H}}),{status:429,headers:{"content-type":"application/json","retry-after":String(K)}})}function A6($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function q1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function CZ($){if(!A6($))return;if(typeof $.accountId!=="string"||!["fable","opus","general"].includes(String($.family)))return;let J=q1($.assignedAt),Z=q1($.lastSeenAt),z=q1($.initialInputBytes),G=q1($.quotaCheckedAt);if(J===void 0||Z===void 0||z===void 0||G===void 0)return;return{accountId:$.accountId,family:$.family,assignedAt:J,lastSeenAt:Z,initialInputBytes:Math.max(0,z),quotaCheckedAt:G}}function _Z($){if(!A6($)||$.version!==1||!A6($.assignments))return;let J={};for(let[Z,z]of Object.entries($.assignments)){let G=CZ(z);if(G)J[Z]=G}return{version:1,updatedAt:q1($.updatedAt)??0,assignments:J}}function y3($){return{version:1,updatedAt:$,assignments:{}}}function m3($){return s3("sha256").update($).digest("hex")}function i3($,J,Z=Date.now(),z){let G=V0(J);if(!["five_hour","seven_day"].every((K)=>{let V=$?.[K];return Boolean(V&&Z-V.checkedAt<G)}))return!1;let Y=r($,z);return!Y||Z-Y.checkedAt<G}function g3($){return Math.max($.checkedAt??0,$.five_hour?.checkedAt??0,$.seven_day?.checkedAt??0,...($.scoped??[]).map((J)=>J.checkedAt??0))}function Z1($){if(!$)return;if("kind"in $)return $.kind==="known"?$.quota:void 0;return $}function p3($,J,Z){let z=a1($),G=Z==="five_hour"?z.five_hour:Z==="seven_day"?z.seven_day:0;if(!J6($))return G;let X=Z6($,J===jZ?void 0:J);return Math.max(G,X[Z])}function l3($,J,Z,z){let G=Math.max(0,$-J);if(G<=0)return 0;if(!Z)return G;let X=Date.parse(Z);if(!Number.isFinite(X)||X<=z)return G;let Y=Math.max((X-z)/3600000,0.016666666666666666);return G/Y}function XK($){if(J3($))return"fable";return typeof $==="string"&&$.toLowerCase().includes("opus")?"opus":"general"}function u3($){let J=$.now??Date.now(),{candidate:Z,storage:z}=$,G=Z1(Z.quota);if(!G)return 0;if(!i3(G,z,J,$.modelId))return 0;let X=[];for(let Y of["five_hour","seven_day"]){let K=G[Y];if(!K||!Number.isFinite(K.remainingPercent))return 0;X.push(l3(K.remainingPercent,p3(z,Z.accountId,Y),K.resetsAt,J))}if($.family==="fable"){let Y=r(G,$.modelId);if(Y&&Number.isFinite(Y.remainingPercent))X.push(l3(Y.remainingPercent,p3(z,Z.accountId,"scoped"),Y.resetsAt,J))}return Math.min(...X)}function OZ($,J,Z=Date.now()){let z=Z1($.quota),G=r(z,"claude-fable-5");return Boolean(G&&i3(z,J,Z,"claude-fable-5")&&Number.isFinite(G.remainingPercent)&&G.remainingPercent<=0)}function YK($){let J=$.now??Date.now(),Z=Z1($.quota);if(!Z)return{action:"retain",reason:"unknown"};let z=r(Z,$.modelId);if(z&&Number.isFinite(z.remainingPercent)&&z.remainingPercent<=0)return{action:"migrate",reason:"model-scoped"};let G=Z.seven_day;if(G&&Number.isFinite(G.remainingPercent)&&G.remainingPercent<=0)return{action:"migrate",reason:"seven-day"};let X=Z.five_hour;if(X&&Number.isFinite(X.remainingPercent)&&X.remainingPercent<=0){let Y=X.resetsAt?Date.parse(X.resetsAt):NaN;if(Number.isFinite(Y)&&Y>J&&Y-J<=HZ)return{action:"hold",reason:"five-hour-short-reset",retryAfterSeconds:Math.max(1,Math.ceil((Y-J)/1000))};return{action:"migrate",reason:"five-hour"}}return{action:"retain",reason:"not-exhausted"}}function KK($){let J=VZ($),Z=J.endsWith(".json")?J.slice(0,-5):J;return WZ(d3($),`${Z}-routing-state.json`)}function VK($,J){let Z=s3("sha256").update($).digest().readUInt32BE(0);return Math.max(1,Math.ceil(J))+Z%21}class MZ{options;loaded=!1;state;stateMtimeNs;touchChain=Promise.resolve();constructor($){this.options=$,this.state=y3(this.now())}now(){return this.options.now?.()??Date.now()}async readState(){try{let $=await zZ(this.options.path,"utf8"),J=_Z(JSON.parse($));if(!J)throw Error(`Invalid sticky routing state at ${this.options.path}`);return J}catch($){if($.code==="ENOENT")return y3(this.now());throw $}}async readStateMtimeNs(){try{return(await YZ(this.options.path,{bigint:!0})).mtimeNs}catch($){if($.code==="ENOENT")return 0n;throw $}}async refreshStateIfChanged(){for(let $=0;$<3;$++){let J=await this.readStateMtimeNs();if(this.loaded&&J===this.stateMtimeNs)return;let Z=await this.readState(),z=await this.readStateMtimeNs();if(J!==z)continue;this.state=Z,this.stateMtimeNs=z,this.loaded=!0;return}this.state=await this.readState(),this.stateMtimeNs=await this.readStateMtimeNs(),this.loaded=!0}async acquireLock(){await ZZ(d3(this.options.path),{recursive:!0,mode:448});let $=this.now()+NZ;while(!0){let J=await b0({name:"write",path:this.options.path,ttlMs:UZ,renew:!0});if(J)return J;if(this.now()>=$)throw Error("Timed out acquiring sticky routing state lock");await new Promise((Z)=>setTimeout(Z,BZ))}}assignmentIsActive($){return $.lastSeenAt>=this.now()-(this.options.assignmentTtlMs??v3)}prune($){let J=this.now()-(this.options.assignmentTtlMs??v3);for(let[z,G]of Object.entries($.assignments))if(G.lastSeenAt<J)delete $.assignments[z];let Z=Object.entries($.assignments);if(Z.length<=h3)return;Z.sort((z,G)=>G[1].lastSeenAt-z[1].lastSeenAt).slice(h3).forEach(([z])=>{delete $.assignments[z]})}async writeState($){this.prune($),$.updatedAt=this.now();let J=`${this.options.path}.${JZ()}.tmp`;try{await KZ(J,`${JSON.stringify($)}
428
- `,{mode:384}),await GZ(J,this.options.path)}finally{await XZ(J,{force:!0}).catch(()=>{})}this.state=$,this.stateMtimeNs=await this.readStateMtimeNs(),this.loaded=!0}scheduleTouch($){this.touchChain=this.touchChain.catch(()=>{}).then(async()=>{let J=await this.acquireLock();try{let Z=await this.readState(),z=Z.assignments[$];if(!z)return;z.lastSeenAt=this.now(),await this.writeState(Z)}finally{await J.release()}}).catch(()=>{})}selectCandidate($){let J=[...$.candidates];if($.family==="opus"){let G=J.filter((X)=>OZ(X,$.storage,this.now()));if(G.length>0)J=G}let Z=J.flatMap((G)=>{let X=u3({candidate:G,family:$.family,modelId:$.modelId,storage:$.storage,now:this.now()});return X>0?[{candidate:G,weight:X}]:[]});if(Z.length===0&&J.every((G)=>!Z1(G.quota)))return[...J].sort((G,X)=>G.order-X.order||G.accountId.localeCompare(X.accountId))[0];let z=new Map;for(let G of Object.values($.state.assignments)){let X=Z.find((K)=>K.candidate.accountId===G.accountId)?.candidate;if(!X)continue;let Y=Z1(X.quota);if(Y&&G.quotaCheckedAt!==g3(Y))continue;z.set(G.accountId,(z.get(G.accountId)??0)+G.initialInputBytes)}return Z.map(({candidate:G,weight:X})=>({candidate:G,score:((z.get(G.accountId)??0)+$.inputBytes)/Math.max(X,LZ)})).sort((G,X)=>G.score-X.score||G.candidate.order-X.candidate.order||G.candidate.accountId.localeCompare(X.candidate.accountId))[0]?.candidate}async resolve($){if(!$.sessionId)return null;await this.refreshStateIfChanged();let J=m3($.sessionId),Z=this.state.assignments[J];if(Z&&this.assignmentIsActive(Z)&&$.retainAccountIds.has(Z.accountId)&&!$.excludeAccountIds?.has(Z.accountId)){if(this.now()-Z.lastSeenAt>=QZ)Z.lastSeenAt=this.now(),this.scheduleTouch(J);return{accountId:Z.accountId,assignment:{...Z},created:!1,migrated:!1}}let z=await this.acquireLock();try{let G=await this.readState();this.prune(G);let X=G.assignments[J];if(X&&$.retainAccountIds.has(X.accountId)&&!$.excludeAccountIds?.has(X.accountId))return X.lastSeenAt=this.now(),await this.writeState(G),{accountId:X.accountId,assignment:{...X},created:!1,migrated:!1};let Y=$.candidates.filter((Q)=>!$.excludeAccountIds?.has(Q.accountId)),V=($.preferredAccountId?Y.find((Q)=>Q.accountId===$.preferredAccountId&&u3({candidate:Q,family:$.family,modelId:$.modelId,storage:$.storage,now:this.now()})>0):void 0)??this.selectCandidate({...$,candidates:Y,state:G});if(!V){if(X)delete G.assignments[J],await this.writeState(G);return null}let W=this.now(),j=Z1(V.quota),H={accountId:V.accountId,family:$.family,assignedAt:W,lastSeenAt:W,initialInputBytes:Math.max(1,$.inputBytes),quotaCheckedAt:j?g3(j):0};return G.assignments[J]=H,await this.writeState(G),{accountId:V.accountId,assignment:{...H},created:!X,migrated:Boolean(X&&X.accountId!==V.accountId)}}finally{await z.release()}}async clear($){if(!$)return;let J=m3($),Z=await this.acquireLock();try{let z=await this.readState();if(!(J in z.assignments))return;delete z.assignments[J],await this.writeState(z)}finally{await Z.release()}}}var HK="thinking-binding-controls-2026-08-01";function D1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function qZ($){if(!D1($))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 QK($){let J=$?.thinkingBinding?.prefixMismatchBehavior;return J==="error"||J==="drop_block"?J:"account-default"}function DZ($){if(!Array.isArray($.messages))return!1;return $.messages.some((J)=>{if(!D1(J)||J.role!=="assistant")return!1;return Array.isArray(J.content)&&J.content.some(qZ)})}function UK($,J="account-default"){if(J==="account-default")return!1;if(!B$($.model))return!1;if(!DZ($))return!1;if(!D1($.thinking)||$.thinking.type==="disabled")return!1;return $.thinking.block_binding={prefix_mismatch_behavior:J},!0}function NK($){if(!D1($.thinking))return!1;if(!D1($.thinking.block_binding))return!1;let J=$.thinking.block_binding.prefix_mismatch_behavior;return J==="error"||J==="drop_block"}var CK="mid-conversation-output-config-2026-07-01";function _K($){if($==="minimal")return"low";if($==="low"||$==="medium"||$==="high"||$==="xhigh"||$==="max")return $;return}function OK($){return B$($.model)}export{Hz as v,Qz as w,j1 as x,W1 as y,Uz as z,Bz as A,L2 as B,Lz as C,Cz as D,_z as E,Oz as F,Mz as G,O2 as H,qz as I,Dz as J,F2 as K,Tz as L,Az as M,J0 as N,E as O,cz as P,s2 as Q,nz as R,G5 as S,R as T,v as U,s0 as V,U5 as W,F as X,U0 as Y,a2 as Z,e$ as _,p as $,az as aa,b5 as ba,oz as ca,tz as da,b0 as ea,rz as fa,I5 as ga,ez as ha,$G as ia,JG as ja,ZG as ka,zG as la,GG as ma,XG as na,YG as oa,KG as pa,VG as qa,WG as ra,jG as sa,HG as ta,QG as ua,UG as va,NG as wa,BG as xa,LG as ya,m5 as za,c0 as Aa,h0 as Ba,g5 as Ca,CG as Da,_G as Ea,OG as Fa,MG as Ga,$4 as Ha,r as Ia,l5 as Ja,i1 as Ka,z4 as La,qG as Ma,J6 as Na,Z6 as Oa,G4 as Pa,X4 as Qa,DG as Ra,xG as Sa,RG as Ta,fG as Ua,wG as Va,PG as Wa,E0 as Xa,$9 as Ya,TG as Za,AG as _a,bG as $a,EG as ab,X9 as bb,IG as cb,H9 as db,gG as eb,B4 as fb,pG as gb,Z0 as hb,dG as ib,iG as jb,w9 as kb,cG as lb,q4 as mb,ZX as nb,zX as ob,Z7 as pb,GX as qb,I4 as rb,v4 as sb,jX as tb,HX as ub,D7 as vb,j$ as wb,H$ as xb,d4 as yb,x7 as zb,QX as Ab,w7 as Bb,_X as Cb,v7 as Db,MX as Eb,qX as Fb,DX as Gb,o0 as Hb,wX as Ib,h7 as Jb,y7 as Kb,PX as Lb,SX as Mb,TX as Nb,AX as Ob,m7 as Pb,bX as Qb,t0 as Rb,kX as Sb,hX as Tb,l7 as Ub,yX as Vb,gX as Wb,pX as Xb,L6 as Yb,$3 as Zb,lX as _b,uX as $b,sX as ac,dX as bc,o4 as cc,J3 as dc,s7 as ec,B$ as fc,cX as gc,nX as hc,aX as ic,oX as jc,tX as kc,rX as lc,CK as mc,_K as nc,OK as oc,VY as pc,JJ as qc,WY as rc,jY as sc,jJ as tc,UJ as uc,e0 as vc,CY as wc,fJ as xc,MY as yc,qY as zc,O0 as Ac,AY as Bc,bY as Cc,EY as Dc,mY as Ec,gY as Fc,pY as Gc,lY as Hc,dY as Ic,iY as Jc,cY as Kc,rJ as Lc,nY as Mc,oY as Nc,$Z as Oc,tY as Pc,jZ as Qc,GK as Rc,i3 as Sc,XK as Tc,YK as Uc,KK as Vc,VK as Wc,MZ as Xc,HK as Yc,QK as Zc,UK as _c,NK as $c};