@cortexkit/opencode-openai-auth 0.11.1 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -26
- package/dist/index-766sfrh5.js +1 -0
- package/dist/index-8kj7sa1p.js +12 -0
- package/dist/index-b3q3j39x.js +2 -0
- package/dist/index-bmd7x5aq.js +2 -0
- package/dist/index-eqh53k8v.js +2 -0
- package/dist/{index-sdt2d2ra.js → index-hy9030jh.js} +1 -1
- package/dist/index-jyr8y8k4.js +7 -0
- package/dist/index-rv08jmd4.js +2 -0
- package/dist/index-ww91hyzr.js +221 -0
- package/dist/index.d.ts +578 -145
- package/dist/index.js +1 -110
- package/dist/pool-lifecycle-DbDmgabd.d.ts +2430 -0
- package/dist/port-file-Do3lQIEk.d.ts +29 -0
- package/dist/protocol-BOBdkqqm.d.ts +198 -0
- package/dist/rpc/port-file.d.ts +4 -17
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.d.ts +2 -2
- package/dist/rpc/protocol.js +1 -0
- package/dist/rpc/rpc-client.d.ts +5 -4
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.d.ts +2 -0
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state-D6cUKgkm.d.ts +385 -0
- package/dist/sidebar-state.d.ts +2 -2
- package/dist/sidebar-state.js +1 -1
- package/dist/token-util-wdza526f.js +1 -0
- package/dist/{token-9823y0pc.js → token-ypk61xj0.js} +1 -1
- package/dist/tui-preferences.js +5 -2
- package/dist/tui.d.ts +9 -4
- package/dist/v2/server.d.ts +54 -0
- package/dist/v2/server.js +4 -0
- package/package.json +21 -9
- package/src/tui/entry.mjs +26 -25
- package/src/tui-compiled/raw/logger.js +24 -0
- package/src/tui-compiled/raw/rpc/protocol.js +3 -0
- package/src/tui-compiled/raw/rpc/rpc-client.js +7 -0
- package/src/tui-compiled/raw/rpc/rpc-dir.js +27 -0
- package/src/tui-compiled/raw/selector.js +21 -0
- package/src/tui-compiled/raw/shared/0332701351b3eeec-format.js +138 -0
- package/src/tui-compiled/raw/shared/04a6357627de5ed0-errors.js +38 -0
- package/src/tui-compiled/raw/shared/053cc17b5419261e-codec.js +12 -0
- package/src/tui-compiled/raw/shared/0766d78c6f481f18-watcher.js +157 -0
- package/src/tui-compiled/raw/shared/08eef45626a94992-reserved.js +13 -0
- package/src/tui-compiled/raw/shared/39c3cb05738fcf6d-projection.js +134 -0
- package/src/tui-compiled/raw/shared/3c2d4169d00f907e-tui-support.js +5 -0
- package/src/tui-compiled/raw/shared/3e7d45a77c6ad4d5-index.js +4 -0
- package/src/tui-compiled/raw/shared/415792e85d80819e-capture-sink.js +13 -0
- package/src/tui-compiled/raw/shared/42ae93ab554fcec2-open-url.js +28 -0
- package/src/tui-compiled/raw/shared/43fc9e6b994519c7-refresh-lock.js +136 -0
- package/src/tui-compiled/raw/shared/458b934e92490331-mutate.js +500 -0
- package/src/tui-compiled/raw/shared/45bf5343bbbf9add-admission.js +142 -0
- package/src/tui-compiled/raw/shared/46f3dff1266160e8-client.js +2 -0
- package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +48 -0
- package/src/tui-compiled/raw/shared/4f36d333d081d040-merge.js +162 -0
- package/src/tui-compiled/raw/shared/54eba94fd64c8c3c-index.js +7 -0
- package/src/tui-compiled/raw/shared/7211cfec06a298bc-atomic-write.js +80 -0
- package/src/tui-compiled/raw/shared/754d6017f8e419cf-builtins.js +534 -0
- package/src/tui-compiled/raw/shared/75bd8c3bd63b315f-identity.js +79 -0
- package/src/tui-compiled/raw/shared/7a91bb630e6f4804-index.js +1 -0
- package/src/tui-compiled/raw/shared/826342a4b6a8b89b-model.js +16 -0
- package/src/tui-compiled/raw/shared/83068c0dbe8a6f13-publication.js +304 -0
- package/src/tui-compiled/raw/shared/836fc615de6afbd9-settings.js +120 -0
- package/src/tui-compiled/raw/shared/83bc3ba9d0fe2761-runtime.js +68 -0
- package/src/tui-compiled/raw/shared/8a18abe4fa2977c8-menu.js +300 -0
- package/src/tui-compiled/raw/shared/901e149c5a0dbbff-sticky.js +339 -0
- package/src/tui-compiled/raw/shared/9020c407ce64f672-ordered.js +58 -0
- package/src/tui-compiled/raw/shared/905bffc0220f43d0-map.js +105 -0
- package/src/tui-compiled/raw/shared/94820e324f2b4c09-seam.js +301 -0
- package/src/tui-compiled/raw/shared/97484d9bb98c705b-provider-state.js +226 -0
- package/src/tui-compiled/raw/shared/9968e3cade6969a1-index.js +2 -0
- package/src/tui-compiled/raw/shared/9b4da614c45f9cd0-lock-constants.js +14 -0
- package/src/tui-compiled/raw/shared/9d3fc9e37456504e-refresh.js +225 -0
- package/src/tui-compiled/raw/shared/9deae3c4da4fd63b-hooks.js +34 -0
- package/src/tui-compiled/raw/shared/a09b6a533c11858f-tui-preferences.js +77 -0
- package/src/tui-compiled/raw/shared/a62a27a204266acd-attribution.js +60 -0
- package/src/tui-compiled/raw/shared/a910277ac43a8626-pull.js +143 -0
- package/src/tui-compiled/raw/shared/b85c5301fddcb98a-paths.js +5 -0
- package/src/tui-compiled/raw/shared/c14988621dc60a75-port-file.js +217 -0
- package/src/tui-compiled/raw/shared/c64d7afbc14ca125-sidebar-file.js +157 -0
- package/src/tui-compiled/raw/shared/c6b176708c446d6d-pins.js +34 -0
- package/src/tui-compiled/raw/shared/c7d252bedee01600-pi.js +206 -0
- package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +120 -0
- package/src/tui-compiled/raw/shared/cc9e0702a752cea7-index.js +3 -0
- package/src/tui-compiled/raw/shared/cd94316a888b0a8e-schema.js +754 -0
- package/src/tui-compiled/raw/shared/d319517e3ea6ad70-redact.js +83 -0
- package/src/tui-compiled/raw/shared/d5a8f1061ee2f114-index.js +5 -0
- package/src/tui-compiled/raw/shared/d669d72c40e9e116-logger.js +19 -0
- package/src/tui-compiled/raw/shared/d7dcba96fea1685c-engine.js +246 -0
- package/src/tui-compiled/raw/shared/dbef697d1df1cd84-index.js +5 -0
- package/src/tui-compiled/raw/shared/e4acc4cb713f300c-protocol.js +3 -0
- package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +501 -0
- package/src/tui-compiled/raw/shared/ec971142548df90e-index.js +6 -0
- package/src/tui-compiled/raw/shared/f37fcefc7aedbf25-error.js +11 -0
- package/src/tui-compiled/raw/shared/fbcdcd0f925e74c0-rpc-client.js +253 -0
- package/src/tui-compiled/raw/shared/fd45e82f2f9c0a0d-torn.js +294 -0
- package/src/tui-compiled/raw/shared/fe02abeadc535f77-rows.js +1258 -0
- package/src/tui-compiled/raw/sidebar-state.js +960 -0
- package/src/tui-compiled/raw/tui/command-dialogs.tsx +424 -0
- package/src/tui-compiled/raw/tui-preferences.js +135 -0
- package/src/tui-compiled/raw/tui.tsx +135 -143
- package/src/tui-compiled/runtime/logger.js +24 -0
- package/src/tui-compiled/runtime/rpc/protocol.js +3 -0
- package/src/tui-compiled/runtime/rpc/rpc-client.js +7 -0
- package/src/tui-compiled/runtime/rpc/rpc-dir.js +27 -0
- package/src/tui-compiled/runtime/selector.js +21 -0
- package/src/tui-compiled/runtime/shared/0332701351b3eeec-format.js +138 -0
- package/src/tui-compiled/runtime/shared/04a6357627de5ed0-errors.js +38 -0
- package/src/tui-compiled/runtime/shared/053cc17b5419261e-codec.js +12 -0
- package/src/tui-compiled/runtime/shared/0766d78c6f481f18-watcher.js +157 -0
- package/src/tui-compiled/runtime/shared/08eef45626a94992-reserved.js +13 -0
- package/src/tui-compiled/runtime/shared/39c3cb05738fcf6d-projection.js +134 -0
- package/src/tui-compiled/runtime/shared/3c2d4169d00f907e-tui-support.js +5 -0
- package/src/tui-compiled/runtime/shared/3e7d45a77c6ad4d5-index.js +4 -0
- package/src/tui-compiled/runtime/shared/415792e85d80819e-capture-sink.js +13 -0
- package/src/tui-compiled/runtime/shared/42ae93ab554fcec2-open-url.js +28 -0
- package/src/tui-compiled/runtime/shared/43fc9e6b994519c7-refresh-lock.js +136 -0
- package/src/tui-compiled/runtime/shared/458b934e92490331-mutate.js +500 -0
- package/src/tui-compiled/runtime/shared/45bf5343bbbf9add-admission.js +142 -0
- package/src/tui-compiled/runtime/shared/46f3dff1266160e8-client.js +2 -0
- package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +48 -0
- package/src/tui-compiled/runtime/shared/4f36d333d081d040-merge.js +162 -0
- package/src/tui-compiled/runtime/shared/54eba94fd64c8c3c-index.js +7 -0
- package/src/tui-compiled/runtime/shared/7211cfec06a298bc-atomic-write.js +80 -0
- package/src/tui-compiled/runtime/shared/754d6017f8e419cf-builtins.js +534 -0
- package/src/tui-compiled/runtime/shared/75bd8c3bd63b315f-identity.js +79 -0
- package/src/tui-compiled/runtime/shared/7a91bb630e6f4804-index.js +1 -0
- package/src/tui-compiled/runtime/shared/826342a4b6a8b89b-model.js +16 -0
- package/src/tui-compiled/runtime/shared/83068c0dbe8a6f13-publication.js +304 -0
- package/src/tui-compiled/runtime/shared/836fc615de6afbd9-settings.js +120 -0
- package/src/tui-compiled/runtime/shared/83bc3ba9d0fe2761-runtime.js +68 -0
- package/src/tui-compiled/runtime/shared/8a18abe4fa2977c8-menu.js +300 -0
- package/src/tui-compiled/runtime/shared/901e149c5a0dbbff-sticky.js +339 -0
- package/src/tui-compiled/runtime/shared/9020c407ce64f672-ordered.js +58 -0
- package/src/tui-compiled/runtime/shared/905bffc0220f43d0-map.js +105 -0
- package/src/tui-compiled/runtime/shared/94820e324f2b4c09-seam.js +301 -0
- package/src/tui-compiled/runtime/shared/97484d9bb98c705b-provider-state.js +226 -0
- package/src/tui-compiled/runtime/shared/9968e3cade6969a1-index.js +2 -0
- package/src/tui-compiled/runtime/shared/9b4da614c45f9cd0-lock-constants.js +14 -0
- package/src/tui-compiled/runtime/shared/9d3fc9e37456504e-refresh.js +225 -0
- package/src/tui-compiled/runtime/shared/9deae3c4da4fd63b-hooks.js +34 -0
- package/src/tui-compiled/runtime/shared/a09b6a533c11858f-tui-preferences.js +77 -0
- package/src/tui-compiled/runtime/shared/a62a27a204266acd-attribution.js +60 -0
- package/src/tui-compiled/runtime/shared/a910277ac43a8626-pull.js +143 -0
- package/src/tui-compiled/runtime/shared/b85c5301fddcb98a-paths.js +5 -0
- package/src/tui-compiled/runtime/shared/c14988621dc60a75-port-file.js +217 -0
- package/src/tui-compiled/runtime/shared/c64d7afbc14ca125-sidebar-file.js +157 -0
- package/src/tui-compiled/runtime/shared/c6b176708c446d6d-pins.js +34 -0
- package/src/tui-compiled/runtime/shared/c7d252bedee01600-pi.js +206 -0
- package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +120 -0
- package/src/tui-compiled/runtime/shared/cc9e0702a752cea7-index.js +3 -0
- package/src/tui-compiled/runtime/shared/cd94316a888b0a8e-schema.js +754 -0
- package/src/tui-compiled/runtime/shared/d319517e3ea6ad70-redact.js +83 -0
- package/src/tui-compiled/runtime/shared/d5a8f1061ee2f114-index.js +5 -0
- package/src/tui-compiled/runtime/shared/d669d72c40e9e116-logger.js +19 -0
- package/src/tui-compiled/runtime/shared/d7dcba96fea1685c-engine.js +246 -0
- package/src/tui-compiled/runtime/shared/dbef697d1df1cd84-index.js +5 -0
- package/src/tui-compiled/runtime/shared/e4acc4cb713f300c-protocol.js +3 -0
- package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +501 -0
- package/src/tui-compiled/runtime/shared/ec971142548df90e-index.js +6 -0
- package/src/tui-compiled/runtime/shared/f37fcefc7aedbf25-error.js +11 -0
- package/src/tui-compiled/runtime/shared/fbcdcd0f925e74c0-rpc-client.js +253 -0
- package/src/tui-compiled/runtime/shared/fd45e82f2f9c0a0d-torn.js +294 -0
- package/src/tui-compiled/runtime/shared/fe02abeadc535f77-rows.js +1258 -0
- package/src/tui-compiled/runtime/sidebar-state.js +960 -0
- package/src/tui-compiled/runtime/tui/command-dialogs.js +378 -0
- package/src/tui-compiled/runtime/tui-preferences.js +135 -0
- package/src/tui-compiled/runtime/{tui.tsx → tui.js} +288 -316
- package/dist/index-4effjmr6.js +0 -2
- package/dist/index-9ehhb051.js +0 -2
- package/dist/index-g3hsdjh4.js +0 -2
- package/dist/index-hh52v8sb.js +0 -2
- package/dist/index-jwn4r3sw.js +0 -1
- package/dist/index-sq36b120.js +0 -211
- package/dist/internal-BTndPmW2.d.ts +0 -914
- package/dist/quota-normalize-08hpp51v.js +0 -1
- package/dist/sidebar-state-CoKYKcLn.d.ts +0 -220
- package/dist/token-util-ypgz7rge.js +0 -1
- package/src/tui-compiled/raw/core-account-paths.ts +0 -114
- package/src/tui-compiled/raw/core-custody-state.ts +0 -243
- package/src/tui-compiled/raw/logger.ts +0 -53
- package/src/tui-compiled/raw/rpc-port-file.ts +0 -177
- package/src/tui-compiled/raw/rpc-protocol.ts +0 -12
- package/src/tui-compiled/raw/rpc-rpc-client.ts +0 -82
- package/src/tui-compiled/raw/rpc-rpc-dir.ts +0 -46
- package/src/tui-compiled/raw/sidebar-state.ts +0 -1659
- package/src/tui-compiled/raw/tui-command-dialogs.tsx +0 -1096
- package/src/tui-compiled/raw/tui-preferences.ts +0 -328
- package/src/tui-compiled/runtime/core-account-paths.ts +0 -114
- package/src/tui-compiled/runtime/core-custody-state.ts +0 -243
- package/src/tui-compiled/runtime/logger.ts +0 -53
- package/src/tui-compiled/runtime/rpc-port-file.ts +0 -177
- package/src/tui-compiled/runtime/rpc-protocol.ts +0 -12
- package/src/tui-compiled/runtime/rpc-rpc-client.ts +0 -82
- package/src/tui-compiled/runtime/rpc-rpc-dir.ts +0 -46
- package/src/tui-compiled/runtime/sidebar-state.ts +0 -1659
- package/src/tui-compiled/runtime/tui-command-dialogs.tsx +0 -855
- package/src/tui-compiled/runtime/tui-preferences.ts +0 -328
- package/src/tui-compiled/shared/internal.ts +0 -6
- package/src/tui-compiled/shared/logger.ts +0 -264
- package/src/tui-compiled/shared/paths.ts +0 -33
- package/src/tui-compiled/shared/refresh-file-lock.ts +0 -384
- package/src/tui-compiled/shared/util/error.ts +0 -9
- package/src/tui-compiled/shared/util/open-url.ts +0 -30
package/dist/index-sq36b120.js
DELETED
|
@@ -1,211 +0,0 @@
|
|
|
1
|
-
import{tb as W9}from"./index-9ehhb051.js";import{createHash as J8}from"node:crypto";var G8=86400000,Q8=300000,Y8=3600000,W8=60000,B8=900000,j8=300000;function n$($){return $ instanceof Error?$.message:String($)}function V8($){let Z=$?.status;if(typeof Z==="number")return Z===429||Z>=500;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.name==="TimeoutError"||$.message.includes("fetch failed")||"code"in $&&($.code==="ECONNRESET"||$.code==="ECONNREFUSED"||$.code==="ETIMEDOUT"||$.code==="UND_ERR_CONNECT_TIMEOUT")}function a$($){let Z=n$($),z=$?.status;if(typeof z==="number")return z===429||z>=500;if(!($ instanceof Error))return!1;let X=$.code;return $.name==="AbortError"||$.name==="TimeoutError"||Z.includes("fetch failed")||X==="ECONNRESET"||X==="ECONNREFUSED"||X==="ETIMEDOUT"||X==="UND_ERR_CONNECT_TIMEOUT"}function G4($){return J8("sha256").update($).digest("hex")}function Q4($){let Z=G4($.refreshToken),X=($.previous?.tokenHash===Z?$.previous.retryCount??0:0)+1,J,G=$.error?.retryAfter;if(typeof G==="number"&&G>0)J=G*1000;else if(V8($.error))J=Math.min(Y8,Q8*2**Math.min(X-1,6));else J=G8;return{message:n$($.error),checkedAt:$.now,nextRetryAt:$.now+J,retryCount:X,tokenHash:Z}}function J2($,Z,z){if(!$?.nextRetryAt||$.nextRetryAt<=z)return!1;if(!Z)return!0;return $.tokenHash===G4(Z)}function f2($,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??Z)-Z)/1000))}s after: ${$.message}`}function l2($){let z=($.previous?.retryCount??0)+1,X,J=$.error?.retryAfter;if(typeof J==="number"&&J>0)X=J*1000;else if(a$($.error))X=Math.min(B8,W8*2**Math.min(z-1,6));else X=j8;return{message:n$($.error),checkedAt:$.now,nextRetryAt:$.now+X,retryCount:z}}function E2($,Z){if(!$?.nextRetryAt||$.nextRetryAt<=Z)return!1;return!0}function t$($){if(!$)return;let Z=Number($);if(Number.isFinite(Z)&&Z>0)return Math.ceil(Z);let z=Date.parse($);if(Number.isFinite(z)){let X=Math.ceil((z-Date.now())/1000);return X>0?X:void 0}return}import{createHash as H8}from"node:crypto";import{constants as Y4}from"node:fs";import{lstat as q8,open as K8,stat as L8,readFile as N8}from"node:fs/promises";import{userInfo as U8}from"node:os";import{dirname as D8}from"node:path";var o$=262144,P8=/^[a-z0-9][a-z0-9._-]{0,63}$/,O8=/^ckh_[A-Za-z0-9_-]{43}$/,M8=new Set(["__proto__","constructor","prototype"]);var d2="openai",r$="oauth",e$="openai-auth";function _8(){return process.getuid?.()??U8().uid}async function V7($,Z={}){let z=Z.lstat??q8,X=Z.stat??L8,J=Z.readFile??N8,G=Z.open??((Y)=>K8(Y,Y4.O_RDONLY|Y4.O_NOFOLLOW)),Q;try{let Y;try{if(Z.lstat||Z.readFile)Y=await z($);else Q=await G($),Y=await Q.stat()}catch(H){if(H.code==="ENOENT")return{ok:!1,reason:"absent"};if(H.code==="ELOOP")return{ok:!1,reason:"symlink",message:"symlink"};return{ok:!1,reason:"unreadable",message:`unreadable (${W4(H)})`}}if(Y.isSymbolicLink?.())return{ok:!1,reason:"symlink",message:"symlink"};if(!Y.isFile())return{ok:!1,reason:"notRegular",message:"not regular"};if((Y.size??0)>o$)return{ok:!1,reason:"tooLarge",message:"too large"};if((Y.mode&511)!==384)return{ok:!1,reason:"permissions",message:"mode"};let B=(Z.currentUid??_8)();if(B!==void 0&&Y.uid!==void 0&&Y.uid!==B)return{ok:!1,reason:"permissions",message:"uid"};let j;try{j=await X(D8($))}catch{return{ok:!1,reason:"unsafeParent",message:"parent"}}if(!j.isDirectory?.())return{ok:!1,reason:"unsafeParent",message:"parent not dir"};if(B!==void 0&&j.uid!==void 0&&j.uid!==B)return{ok:!1,reason:"unsafeParent",message:"parent uid"};if((j.mode&63)!==0)return{ok:!1,reason:"unsafeParent",message:"parent mode"};let V;try{if(Q){let H=o$,N=Buffer.alloc(H+1),{bytesRead:U}=await Q.read({buffer:N,offset:0,length:H+1,position:0});if(U>H)return{ok:!1,reason:"tooLarge",message:"too large"};V=N.subarray(0,U).toString("utf8")}else V=await J($,"utf8")}catch{return{ok:!1,reason:"unreadable",message:`unreadable (${W4(Q?"fd":"io")})`}}if(Buffer.byteLength(V,"utf8")>o$)return{ok:!1,reason:"tooLarge",message:"too large"};let q;try{q=JSON.parse(V)}catch{return{ok:!1,reason:"invalid",message:"invalid JSON"}}let K=x8(q);if(!K)return{ok:!1,reason:"invalid",message:"invalid manifest"};return{ok:!0,value:K,revision:$3(V)}}finally{await Q?.close()}}function $3($){return H8("sha256").update($,"utf8").digest("hex")}function W4($){if(typeof $==="string")return $;return $?.code??"EIO"}function x8($){if(!$||typeof $!=="object")return null;let Z=$;if(Z.version!==1||!Array.isArray(Z.providers))return null;if(!B4(d2))return null;let z=[];for(let X of Z.providers){if(!X||typeof X!=="object")return null;let J=X;if(J.provider!==d2)continue;if(J.shape!==r$)continue;if(J.serve!==e$)continue;if(!Array.isArray(J.accounts)||J.accounts.length===0)return null;let G=new Set,Q=[];for(let Y of J.accounts){if(!Y||typeof Y!=="object")return null;let W=Y,B=W.label,j=W.handle,V=W.credential_id;if(typeof B!=="string"||!B4(B))return null;if(G.has(B))return null;if(G.add(B),typeof j!=="string"||!O8.test(j))return null;if(typeof V!=="string"||V.split(":")[1]!==J.provider)return null;Q.push({label:B,handle:j,credential_id:V})}z.push({provider:d2,shape:r$,serve:e$,accounts:Q})}return{version:1,providers:z}}function B4($){return P8.test($)&&!M8.has($)}var G2=d2;function Z3($){if(!$.ok)return new Map;let Z=new Map;for(let z of $.value.providers){if(z.provider!==d2||z.shape!==r$||z.serve!==e$)continue;for(let X of z.accounts)Z.set(X.label,X.handle)}return Z}import{appendFileSync as F8,chmodSync as I8,existsSync as X3,renameSync as j4,statSync as R8}from"node:fs";var K$={error:0,warn:1,info:2,debug:3,trace:4},A8=5242880,y2,q$,J3;function V4($){y2=$.file,q$=$.level}function T8($){if($===void 0||$ in K$)J3=$}function b8(){if(y2===void 0)return;return(typeof y2==="function"?y2():y2)||void 0}function C8(){if(J3)return J3;let $=typeof q$==="function"?q$():q$;if($&&$ in K$)return $;return"info"}var S8=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;function w8($){if(S8.test($))return!0;let Z=$.toLowerCase().replace(/[-_]/g,"");if(Z==="chatgptaccountid")return!0;if(Z==="email"||Z==="orgname"||Z==="organizationname")return!0;if(Z.includes("apikey"))return!0;if(Z.endsWith("secret")||Z.endsWith("password"))return!0;if(Z.endsWith("token")&&!Z.endsWith("tokens"))return!0;return!1}var H4=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function q4($){return Q3($,new WeakSet)}function K4($){return G3($,new WeakSet)}function G3($,Z){if(typeof $==="string")return $.replace(H4,"***REDACTED***");if(Array.isArray($)){if(Z.has($))return"[Circular]";Z.add($);let z=$.map((X)=>G3(X,Z));return Z.delete($),z}if($&&typeof $==="object"){if(Z.has($))return"[Circular]";Z.add($);let z={};for(let[X,J]of Object.entries($))z[X]=G3(J,Z);return Z.delete($),z}return $}function Q3($,Z){if(typeof $==="string")return $.replace(H4,"***REDACTED***");if(Array.isArray($)){if(Z.has($))return"[Circular]";Z.add($);let z=$.map((X)=>Q3(X,Z));return Z.delete($),z}if($&&typeof $==="object"){if(Z.has($))return"[Circular]";Z.add($);let z={};for(let[X,J]of Object.entries($))z[X]=w8(X)?"***REDACTED***":Q3(J,Z);return Z.delete($),z}return $}var c2=[],z3,k8=3;function Y3($){try{I8($,384)}catch{}}function f8($){try{if(!(X3($)&&R8($).size>A8))return;for(let z=k8-1;z>=1;z--)if(X3(`${$}.${z}`)){let X=`${$}.${z+1}`;j4(`${$}.${z}`,X),Y3(X)}let Z=`${$}.1`;j4($,Z),Y3(Z)}catch{}}function s2(){if(!c2.length)return;let $=b8(),Z=c2.join("");if(c2=[],!$)return;try{if(f8($),X3($))Y3($);F8($,Z,{encoding:"utf8",mode:384})}catch{}}function E8(){if(!z3)z3=setTimeout(()=>{z3=void 0,s2()},500)}function y8($){try{return` ${JSON.stringify(q4($))}`}catch{return" [unserializable]"}}function i2($,Z,z,X){if(y2===void 0)return;if(K$[Z]>K$[C8()])return;let J=`[${new Date().toISOString()}] ${Z.toUpperCase()} [${$}] ${K4(z)}`+(X===void 0?"":y8(X))+`
|
|
2
|
-
`;if(c2.push(J),c2.length>=50)s2();else E8()}function n($){return{error:(Z,z)=>i2($,"error",Z,z),warn:(Z,z)=>i2($,"warn",Z,z),info:(Z,z)=>i2($,"info",Z,z),debug:(Z,z)=>i2($,"debug",Z,z),trace:(Z,z)=>i2($,"trace",Z,z)}}import{createServer as v8}from"node:http";import{setTimeout as h8}from"node:timers/promises";var U$="app_EMoamEEZ73f0CkXaXp7hrann",x2="https://auth.openai.com",n2=1455,m8=3000,g8="cortexkit-opencode-openai-auth";function L4($){return`${g8}/${$}`}var N4="main",p8=`"${N4}" is a reserved account id; choose a different label.`;function U4($){let Z=new Uint8Array($),z=String.fromCharCode(...Z);return btoa(z).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function u8(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((X)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[X%66]).join(""),z=U4(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:z}}function o2($){if($.length>16384)return;let Z=$.split(".");if(Z.length!==3)return;let z=Z[1];if(!z||z.length>8192)return;try{return JSON.parse(Buffer.from(z,"base64url").toString())}catch{return}}function r2($){let Z=$.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let z=$["https://api.openai.com/auth"];if(z&&typeof z==="object"&&!Array.isArray(z)&&typeof z.chatgpt_account_id==="string"&&z.chatgpt_account_id.length>0)return z.chatgpt_account_id;let X=$.organizations;if(Array.isArray(X)){let J=X[0];if(J&&typeof J==="object"&&!Array.isArray(J)&&typeof J.id==="string"&&J.id.length>0)return J.id}return}function N$($){if($.id_token){let Z=o2($.id_token),z=Z&&r2(Z);if(z)return z}if($.access_token){let Z=o2($.access_token);return Z?r2(Z):void 0}return}function l8($){return typeof $==="string"&&$.toLowerCase()===N4}function W3($){if(l8($))throw Error(p8);return $}function d8($,Z,z){let X=new URLSearchParams({response_type:"code",client_id:U$,redirect_uri:$,scope:"openid profile email offline_access",code_challenge:Z.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:z,originator:"opencode"});return`${x2}/oauth/authorize?${X.toString()}`}async function i8($,Z,z){let X=await fetch(`${x2}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:$,redirect_uri:Z,client_id:U$,code_verifier:z.verifier}).toString()});if(!X.ok)throw Error(`Token exchange failed: ${X.status}`);return await X.json()}function c8($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var s8=`<!doctype html>
|
|
3
|
-
<html>
|
|
4
|
-
<head>
|
|
5
|
-
<title>CortexKit OpenAI Auth - Authorization Successful</title>
|
|
6
|
-
<style>
|
|
7
|
-
body {
|
|
8
|
-
font-family:
|
|
9
|
-
system-ui,
|
|
10
|
-
-apple-system,
|
|
11
|
-
sans-serif;
|
|
12
|
-
display: flex;
|
|
13
|
-
justify-content: center;
|
|
14
|
-
align-items: center;
|
|
15
|
-
height: 100vh;
|
|
16
|
-
margin: 0;
|
|
17
|
-
background: #131010;
|
|
18
|
-
color: #f1ecec;
|
|
19
|
-
}
|
|
20
|
-
.container {
|
|
21
|
-
text-align: center;
|
|
22
|
-
padding: 2rem;
|
|
23
|
-
}
|
|
24
|
-
h1 {
|
|
25
|
-
color: #f1ecec;
|
|
26
|
-
margin-bottom: 1rem;
|
|
27
|
-
}
|
|
28
|
-
p {
|
|
29
|
-
color: #b7b1b1;
|
|
30
|
-
}
|
|
31
|
-
</style>
|
|
32
|
-
</head>
|
|
33
|
-
<body>
|
|
34
|
-
<div class="container">
|
|
35
|
-
<h1>Authorization Successful</h1>
|
|
36
|
-
<p>You can close this window and return to OpenCode.</p>
|
|
37
|
-
</div>
|
|
38
|
-
<script>
|
|
39
|
-
setTimeout(() => window.close(), 2000)
|
|
40
|
-
</script>
|
|
41
|
-
</body>
|
|
42
|
-
</html>`,L$=($)=>`<!doctype html>
|
|
43
|
-
<html>
|
|
44
|
-
<head>
|
|
45
|
-
<title>CortexKit OpenAI Auth - Authorization Failed</title>
|
|
46
|
-
<style>
|
|
47
|
-
body {
|
|
48
|
-
font-family:
|
|
49
|
-
system-ui,
|
|
50
|
-
-apple-system,
|
|
51
|
-
sans-serif;
|
|
52
|
-
display: flex;
|
|
53
|
-
justify-content: center;
|
|
54
|
-
align-items: center;
|
|
55
|
-
height: 100vh;
|
|
56
|
-
margin: 0;
|
|
57
|
-
background: #131010;
|
|
58
|
-
color: #f1ecec;
|
|
59
|
-
}
|
|
60
|
-
.container {
|
|
61
|
-
text-align: center;
|
|
62
|
-
padding: 2rem;
|
|
63
|
-
}
|
|
64
|
-
h1 {
|
|
65
|
-
color: #fc533a;
|
|
66
|
-
margin-bottom: 1rem;
|
|
67
|
-
}
|
|
68
|
-
p {
|
|
69
|
-
color: #b7b1b1;
|
|
70
|
-
}
|
|
71
|
-
.error {
|
|
72
|
-
color: #ff917b;
|
|
73
|
-
font-family: monospace;
|
|
74
|
-
margin-top: 1rem;
|
|
75
|
-
padding: 1rem;
|
|
76
|
-
background: #3c140d;
|
|
77
|
-
border-radius: 0.5rem;
|
|
78
|
-
}
|
|
79
|
-
</style>
|
|
80
|
-
</head>
|
|
81
|
-
<body>
|
|
82
|
-
<div class="container">
|
|
83
|
-
<h1>Authorization Failed</h1>
|
|
84
|
-
<p>An error occurred during authorization.</p>
|
|
85
|
-
<div class="error">${c8($)}</div>
|
|
86
|
-
</div>
|
|
87
|
-
</body>
|
|
88
|
-
</html>`,t2,a2,Q2=new Map;function M2(){return Q2.size}function F2($){if(Q2.delete($),M2()===0)_2()}async function n8(){let $=`http://localhost:${n2}/auth/callback`;if(t2)return{port:n2,redirectUri:$};if(a2)return a2;a2=(async()=>{let Z=v8((z,X)=>{let J=new URL(z.url||"/",`http://127.0.0.1:${n2}`);if(J.pathname==="/auth/callback"){let G=J.searchParams.get("code"),Q=J.searchParams.get("state"),Y=J.searchParams.get("error"),W=J.searchParams.get("error_description");if(Y){let j=W||Y;if(Q){let V=Q2.get(Q);if(V)V.reject(Error(j)),F2(Q);else if(M2()===0)_2()}else if(M2()===0)_2();X.writeHead(200,{"Content-Type":"text/html"}),X.end(L$(j));return}if(!Q){if(M2()===0)_2();X.writeHead(400,{"Content-Type":"text/html"}),X.end(L$("Missing state parameter"));return}if(!G){if(M2()===0)_2();X.writeHead(400,{"Content-Type":"text/html"}),X.end(L$("Missing authorization code"));return}let B=Q2.get(Q);if(!B){if(M2()===0)_2();X.writeHead(400,{"Content-Type":"text/html"}),X.end(L$("Unknown state — authorization may have expired"));return}F2(Q),i8(G,$,B.pkce).then((j)=>B.resolve(j)).catch((j)=>B.reject(j)),X.writeHead(200,{"Content-Type":"text/html"}),X.end(s8);return}if(J.pathname==="/cancel"){let G=J.searchParams.get("state"),Q=G?[G]:[...Q2.keys()];X.writeHead(200),X.end("Login cancelled");for(let Y of Q){let W=Q2.get(Y);if(!W)continue;W.reject(Error("Login cancelled")),F2(Y)}if(M2()===0)_2();return}X.writeHead(404),X.end("Not found")});return await new Promise((z,X)=>{Z.once("error",X),Z.listen(n2,"127.0.0.1",()=>{Z.off("error",X),z()})}),t2=Z,{port:n2,redirectUri:$}})();try{return await a2}finally{a2=void 0}}function _2(){if(t2){let $=t2;t2=void 0,$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}}function a8($,Z,z=300000,X){return new Promise((J,G)=>{if(X?.aborted){F2(Z),G(Error("Login cancelled"));return}let Q=setTimeout(()=>{if(Q2.get(Z))F2(Z),G(Error("OAuth callback timeout — authorization took too long"))},z),Y=()=>{if(clearTimeout(Q),Q2.get(Z))F2(Z),G(Error("Login cancelled"))};if(X)X.addEventListener("abort",Y);Q2.set(Z,{pkce:$,state:Z,resolve:(W)=>{if(clearTimeout(Q),X)X.removeEventListener("abort",Y);J(W)},reject:(W)=>{if(clearTimeout(Q),X)X.removeEventListener("abort",Y);G(W)}})})}async function t8($){let Z=await fetch(`${x2}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":L4($)},body:JSON.stringify({client_id:U$})});if(!Z.ok)throw Error("Failed to initiate device authorization");let z=await Z.json();return{deviceData:z,url:`${x2}/codex/device`,instructions:`Enter code: ${z.user_code}`}}async function o8($,Z,z){let X=Math.max(parseInt($.interval,10)||5,1)*1000,J=typeof $.expires_in==="number"?$.expires_in:parseInt($.expires_in||"",10),G=!Number.isNaN(J)&&J>0?J*1000:900000,Q=Date.now();while(!0){if(z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-Q>G)throw Error("Device authorization expired");let Y=await fetch(`${x2}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":L4(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(Y.ok){let j=await Y.json(),V=await fetch(`${x2}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:j.authorization_code,redirect_uri:`${x2}/deviceauth/callback`,client_id:U$,code_verifier:j.code_verifier}).toString()});if(!V.ok)throw Error(`Token exchange failed: ${V.status}`);return await V.json()}if(Y.status!==403&&Y.status!==404)throw Error(`Device authorization failed: ${Y.status}`);let W=G-(Date.now()-Q);if(W<=0)throw Error("Device authorization expired");let B=Math.min(X+m8,W);try{await h8(B,void 0,{signal:z})}catch(j){if(j instanceof Error&&j.name==="AbortError")throw Error("Device authorization cancelled");throw j}}}function D4($,Z){let z=-1;if(Z.accountId)z=$.findIndex((X)=>X.accountId&&X.accountId===Z.accountId);if(z<0)z=$.findIndex((X)=>X.id===Z.id);if(z<0&&Z.label&&!Z.accountId)z=$.findIndex((X)=>X.label===Z.label);if(z>=0)return $[z]={...$[z],...Z,addedAt:$[z]?.addedAt??Z.addedAt},z;return $.push(Z),$.length-1}async function P4($){let{label:Z,headless:z=!1,signal:X,version:J}=$;if(W3(Z),z){let{deviceData:j,url:V,instructions:q}=await t8(J),K=(async()=>{let H=await o8(j,J,X),N=Date.now(),U=N$(H);return{id:W3(Z||U||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:H.access_token,refresh:H.refresh_token,expires:N+(H.expires_in??3600)*1000,enabled:!0,addedAt:N,lastUsed:N,lastRefreshedAt:N,accountId:U}})();return{url:V,instructions:q,completion:K}}let{redirectUri:G}=await n8(),Q=await u8(),Y=U4(crypto.getRandomValues(new Uint8Array(32)).buffer),W=d8(G,Q,Y),B=(async()=>{try{if(X?.aborted)throw Error("Login cancelled");let j=await a8(Q,Y,void 0,X),V=Date.now(),q=N$(j);return{id:W3(Z||q||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:j.access_token,refresh:j.refresh_token,expires:V+(j.expires_in??3600)*1000,enabled:!0,addedAt:V,lastUsed:V,lastRefreshedAt:V,accountId:q}}finally{F2(Y)}})();return{url:W,instructions:"Complete authorization in your browser. This window will close automatically.",completion:B}}import{createHash as N5}from"node:crypto";import{setTimeout as U5}from"node:timers/promises";import{createHash as R9,randomUUID as A9}from"node:crypto";import{setTimeout as T9}from"node:timers/promises";import{randomUUID as r8}from"node:crypto";import{mkdir as e8,rename as $9,rm as Z9,writeFile as z9}from"node:fs/promises";import{dirname as X9}from"node:path";async function Y2($,Z){await e8(X9($),{recursive:!0});let z=`${$}.${r8()}.tmp`;await z9(z,`${JSON.stringify(Z,null,2)}
|
|
89
|
-
`,{encoding:"utf8",mode:384});try{await $9(z,$)}catch(X){throw await Z9(z,{force:!0}).catch(()=>{}),X}}import{basename as J9,dirname as G9,join as Q9}from"node:path";var O4="openai-auth.json",M4="openai-auth-state.json";function Y9($){return J9($)===O4?Q9(G9($),M4):`${$}.state.json`}function W2($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;try{return JSON.stringify($)}catch{return String($)}}var B9=n("quota"),B3="primary",j3="secondary",j9="app_EMoamEEZ73f0CkXaXp7hrann",V9="https://auth.openai.com";async function b7($){_4($.refreshToken);let Z=await $.fetchImpl(`${V9}/oauth/token`,{method:"POST",signal:AbortSignal.timeout(15000),headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refreshToken,client_id:j9}).toString()});if(!Z.ok){let J=t$(Z.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${Z.status}`),{status:Z.status,retryAfter:J,isRefreshError:!0})}let z=await Z.json();if(!z||typeof z.access_token!=="string"||!z.access_token||typeof z.expires_in!=="number")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});if(z.refresh_token!==void 0&&typeof z.refresh_token!=="string")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});let X=typeof z.refresh_token==="string"&&z.refresh_token?z.refresh_token:$.refreshToken;return{access:z.access_token,refresh:X,expires:$.now()+z.expires_in*1000,expiresIn:z.expires_in}}var H9="https://chatgpt.com/backend-api/wham/usage";async function V3($){let Z=$.logger??B9,z=$.accountKey??"unknown",X=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:z});try{let J=await $.fetchImpl(H9,{signal:AbortSignal.timeout(15000),headers:{authorization:`Bearer ${$.accessToken}`,"chatgpt-account-id":$.accountId??"","oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":"/backend-api/wham/usage"}});if(!J.ok){let Y=t$(J.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${J.status}`),{status:J.status,retryAfter:Y})}let{normalizeWham:G}=await import("./quota-normalize-08hpp51v.js"),Q=G(await J.json());return Z.debug("wham usage fetch succeeded",{pid:process.pid,accountId:z,status:J.status,elapsedMs:Date.now()-X}),Q}catch(J){throw Z.warn("wham usage fetch failed",{pid:process.pid,accountId:z,status:typeof J?.status==="number"?J.status:"error",elapsedMs:Date.now()-X,error:W2(J)}),J}}import{createHash as D9}from"node:crypto";import{randomUUID as H3}from"node:crypto";import{mkdir as x4,readFile as q3,rename as q9,rm as v2,stat as F4,writeFile as D$}from"node:fs/promises";import{dirname as K9,join as I4}from"node:path";var L9=globalThis.setTimeout.bind(globalThis),N9=globalThis.clearTimeout.bind(globalThis);function U9($){let Z=$?.code;return Z==="ENOENT"||Z==="EINVAL"||Z==="ENOTDIR"}async function h2($){let Z=`${$.path}.${$.name}.lock`,z=I4(Z,"owner.json"),X=H3(),J=$.now??Date.now,G=null,Q=!1,Y=null,W=`${Z}.evicting`,B=I4(W,"owner.json"),j=H3(),V=5000,q=8;async function K(){try{return JSON.parse(await q3(Z,"utf8"))}catch(_){if(_.code!=="EISDIR")throw _;return JSON.parse(await q3(z,"utf8"))}}async function H(){await D$(Z,`${JSON.stringify({ownerId:X,expiresAt:J()+$.ttlMs})}
|
|
90
|
-
`,{encoding:"utf8",mode:384})}async function N(){try{return await D$(Z,`${JSON.stringify({ownerId:X,expiresAt:J()+$.ttlMs})}
|
|
91
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(_){let C=_.code;if(C==="EEXIST"||C==="EISDIR")return!1;if(C==="ENOENT"){await x4(K9(Z),{recursive:!0});try{return await D$(Z,`${JSON.stringify({ownerId:X,expiresAt:J()+$.ttlMs})}
|
|
92
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(w){let H$=w.code;if(H$==="EEXIST"||H$==="EISDIR")return!1;throw w}}throw _}}async function U(){await new Promise((_)=>setTimeout(_,Math.floor(Math.random()*4)))}async function P(){try{let _=await K();return Number(_?.expiresAt)>J()}catch{try{return(await F4(Z)).mtimeMs+$.ttlMs>J()}catch{return!1}}}async function M(){try{return JSON.parse(await q3(B,"utf8"))?.ownerId===j}catch{return!1}}async function O(){if(await M())await v2(W,{recursive:!0,force:!0}).catch(()=>{})}async function P2(){await x4(W);try{await D$(B,`${JSON.stringify({ownerId:j,createdAt:J()})}
|
|
93
|
-
`,{encoding:"utf8",mode:384,flag:"wx"})}catch(_){if(U9(_))return!1;throw await O(),_}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function b(){let _;try{_=await F4(W)}catch(w){if(w.code==="ENOENT")return"missing";throw w}if(_.mtimeMs+V>J())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let C=`${W}.${H3()}`;try{await q9(W,C)}catch(w){if(w.code==="ENOENT")return"missing";throw w}if($.onStep)await $.onStep("stale-marker-claimed");return await v2(C,{recursive:!0,force:!0}).catch(()=>{}),"recovered"}async function R(_){try{if(!await P2())return!1}catch(C){if(C.code==="EEXIST")return!1;throw C}try{await _()}finally{await O()}return!0}async function s$(){for(let _=0;_<q;_++){if($.onStep)await $.onStep("relinquish-read");let C;try{C=await K()}catch{return}if(C?.ownerId!==X)return;try{await v2(Z,{recursive:!0,force:!0});return}catch{await U()}}}function X4(){if(!$.renew||Q)return;let _=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=L9(()=>{let C=(async()=>{let w=!Q;try{if(!await R(async()=>{let J4=await K(),X8=J();if(Q||J4?.ownerId!==X){w=!1;return}if(Number(J4?.expiresAt)<=X8){w=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(Q){w=!1;return}if(!await M())return;if($.onStep)await $.onStep("renewal-write-fenced");if(Q){w=!1;return}if(!await M())return;if($.onStep)await $.onStep("renewal-write-ready");if(await H(),!await M()){w=!1,await s$();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch{}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(w&&!Q)X4()}})();Y=C,C.finally(()=>{if(Y===C)Y=null})},_),"unref"in G)G.unref()}let O2=await N();if(!O2)for(let _=0;_<q;_++){if(O2=await N(),O2)break;if(await P())return null;try{if(!await P2()){await U();continue}}catch(C){if(C.code!=="EEXIST")throw C;if(await b()==="fresh")return null;await U();continue}try{if(await P())return null;if(!await M())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await M())return null;if(await v2(Z,{recursive:!0,force:!0}).catch(()=>{}),!await M())return null;if(O2=await N(),!O2)return null;if(!await M())return await v2(Z,{recursive:!0,force:!0}).catch(()=>{}),O2=!1,null;break}finally{await O()}}if(!O2)return null;return X4(),{release:async()=>{if(Q=!0,G)N9(G),G=null;await Y;for(let _=0;_<q;_++){try{if(await R(async()=>{if((await K())?.ownerId!==X)return;if($.onStep)await $.onStep("release-owner-confirmed");if(!await M())return;await v2(Z,{recursive:!0,force:!0}).catch(()=>{})}))return;await b()}catch{return}await U()}}}}var P9=globalThis.setTimeout,O9=5;function e2($){let Z=$?.quota?.checkIntervalMinutes??O9;return Math.max(1,Z)*60000}function M9($){return $?.quota?.enabled!==!1}function P$($,Z){if(!$?.resetsAt)return!1;let z=Date.parse($.resetsAt);return Number.isFinite(z)&&z<=Z}function g7($,Z,z,X,J){if(J!==void 0&&Number.isFinite(J)&&J>z)return J;let G=Z===B3?$?.primary:Z===j3?$?.secondary:void 0,Q=G?.resetsAt?Date.parse(G.resetsAt):NaN;if(Number.isFinite(Q)&&Q>z)return Q;return z+X}function _9($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function R4($,Z,z){if(!M9(Z))return z+e2(Z);let X=_9(Z),J=[];for(let G of["primary","secondary"]){let Q=$?.[G];if(!Q)continue;if(Q.remainingPercent>=X[G])continue;let Y=Q.resetsAt?Date.parse(Q.resetsAt):Number.NaN;if(!Number.isFinite(Y)||Y<=z)return z+e2(Z);J.push(Y)}if(!J.length)return z+e2(Z);return Math.min(...J)+60000}function x9($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function F9($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function a($){return D9("sha256").update($).digest("hex").slice(0,16)}class K2{main=null;mainTokenFp=null;mainQuotaAccountId=null;fallbacks=new Map;fallbackTokenFps=new Map;inflightMain=null;inflightMainFp=null;inflightFallbacks=new Map;mainLastApiError=void 0;fallbackApiErrors=new Map;fallbackErrorTokenFps=new Map;rateLimitedUntilMap=new Map;apiGate=Promise.resolve();lastApiCallAt=0;storage;fetchImpl;now;fetchQuotaFn;onMainQuotaFetched;onApiError;configPath;constructor($){this.storage=$.storage,this.fetchImpl=$.fetchImpl??fetch,this.configPath=$.configPath,this.now=$.now??Date.now,this.fetchQuotaFn=$.fetchQuotaFn,this.onMainQuotaFetched=$.onMainQuotaFetched,this.onApiError=$.onApiError,this.seedMainFromStorage($.storage),this.seedMainBackoffFromStorage($.storage)}getMain($){if($&&this.main&&this.mainTokenFp&&this.mainTokenFp!==a($))this.main=null,this.mainTokenFp=null;return this.main}getFallback($,Z){let z=this.fallbacks.get($)??null;if(!Z||!z)return z;if(this.fallbackTokenFps.get($)!==a(Z))return this.fallbacks.delete($),this.fallbackTokenFps.delete($),null;return z}getAllFallbacks(){return this.fallbacks}setMain($,Z,z,X=!1){if(!X&&!A4(Z.quota))return;if(this.mainTokenFp=a($),z&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==z)this.clearRateLimited("main");if(z)this.mainQuotaAccountId=z;if(this.main=Z,K3(Z.quota))this.clearRateLimited("main")}peekMainForPolicy($){if($&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==$)return null;return this.main}peekFallbackForPolicy($,Z){let z=this.fallbacks.get($)??null;if(Z&&z?.accountId&&z.accountId!==Z)return null;return z}setFallback($,Z,z,X=!1,J){if(!X&&!A4(Z.quota))return;let G=this.fallbacks.get($)?.accountId;if(J&&G&&J!==G)this.clearRateLimited($);let Q=J??G;if(this.fallbacks.set($,{...Z,accountId:Q}),z)this.fallbackTokenFps.set($,a(z));else this.fallbackTokenFps.delete($);if(K3(Z.quota))this.clearRateLimited($)}markRateLimited($,Z){let z=this.rateLimitedUntilMap.get($);if(z!==void 0&&z>Z)return;this.rateLimitedUntilMap.set($,Z)}isRateLimited($){let Z=this.rateLimitedUntilMap.get($);return Z!==void 0&&this.now()<Z}rateLimitedUntil($){return this.rateLimitedUntilMap.get($)}clearRateLimited($){this.rateLimitedUntilMap.delete($)}async refreshMain($){let Z=a($);if(this.mainTokenFp&&this.mainTokenFp!==Z)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===Z)return this.inflightMain;if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}return this.inflightMainFp=Z,this.inflightMain=this._fetchMain($),this.inflightMain}async refreshFallback($,Z){let z=K2.fallbackInflightKey($,Z),X=this.inflightFallbacks.get(z);if(X)return X;if(this.isFallbackBackedOff($,Z)){let G=this.getFallback($,Z);if(G)return G.quota;throw Error("Quota API rate-limited — try again later")}let J=this._fetchFallback($,Z);return this.inflightFallbacks.set(z,J),J}async refreshAllFallbacks($){let Z=this.now();for(let z of $){if(z.enabled===!1)continue;if($$(z,"openai"),!z.access)continue;let X=this.getFallback(z.id,z.access);if(X&&Z<X.refreshAfter)continue;try{await this.refreshFallback(z.id,z.access)}catch{}}}refreshMainInBackground($){let Z=a($);if(this.inflightMain&&this.inflightMainFp===Z)return;if(this.isBackedOff())return;this.refreshMain($).catch(()=>{})}isMainStale(){if(!this.main)return!0;return this.now()>=this.main.refreshAfter}isFallbackStale($,Z){let z=this.getFallback($,Z);if(!z)return!0;return this.now()>=z.refreshAfter}shouldRefreshOnRequestCount($){let Z=F9(this.storage);if(Z<=0)return!1;return $>0&&$%Z===0}needsRefresh($){return this.isMainStale()||this.shouldRefreshOnRequestCount($)}updateStorage($){this.storage=$,this.seedMainFromStorage($),this.seedMainBackoffFromStorage($)}seedMainFromStorage($,Z){let z=x9($);if(!z)return;let X=Z?a(Z):null;if(X&&z.tokenFingerprint&&z.tokenFingerprint!==X)return;let J={quota:z.quota,refreshAfter:R4(z.quota,$,z.checkedAt),checkedAt:z.checkedAt};if(this.main&&this.main.checkedAt>=J.checkedAt&&(!X||!this.mainTokenFp||this.mainTokenFp===X))return;if(this.main=J,this.mainTokenFp=z.tokenFingerprint??null,$?.mainAccountId){if(this.mainQuotaAccountId&&this.mainQuotaAccountId!==$.mainAccountId)this.clearRateLimited("main");this.mainQuotaAccountId=$.mainAccountId}}seedMainBackoffFromStorage($){let Z=$?.quota?.mainLastQuotaApiError;this.mainLastApiError=Z&&E2(Z,this.now())?Z:void 0}seedFallbacksFromAccounts($){let Z=e2(this.storage);for(let z of $){if(z.enabled===!1)continue;if(!z.quota)continue;let X=Math.max(z.quota.primary?.checkedAt??0,z.quota.secondary?.checkedAt??0);if(X<=0)continue;let J=this.getFallback(z.id,z.access);if(J&&J.checkedAt>=X)continue;this.setFallback(z.id,{quota:z.quota,refreshAfter:X+Z,checkedAt:X},z.access,!1,z.accountId)}}isBackedOff(){return E2(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==a(Z))return!1}return E2(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey($,Z){return JSON.stringify([$,a(Z)])}static quotaLockName($){return`opencode-fallback-quota-refresh-${$.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch($){let Z=async()=>{let X=this.now()-this.lastApiCallAt;if(X<K2.API_CALL_GAP_MS)await new Promise((J)=>{let G=P9(J,K2.API_CALL_GAP_MS-X);if(typeof G==="object"&&"unref"in G)G.unref()});return this.lastApiCallAt=this.now(),$()},z=this.apiGate.then(Z,Z);return this.apiGate=z.catch(()=>{}),z}async _fetchMain($){let Z=a($);return this._enqueueApiFetch(async()=>{try{if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}let z=await h2({name:"opencode-main-quota-refresh",ttlMs:30000,path:this.configPath});if(!z){let X=this.main;if(X&&this.now()<X.refreshAfter)return X.quota;throw Error("Quota refresh is already in progress")}try{let X=this.now(),J=await this._fetchQuota($),G=this.now();if(this.mainTokenFp=a($),this.main={quota:J,refreshAfter:R4(J,this.storage,G),checkedAt:G},K3(J))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(J,G,this.mainTokenFp,X),J}catch(X){throw this._handleMainFetchError(X),X}finally{await z.release()}}finally{if(this.inflightMainFp===Z)this.inflightMain=null,this.inflightMainFp=null}})}async _fetchFallback($,Z){return this._enqueueApiFetch(async()=>{try{if(this.isFallbackBackedOff($,Z)){let X=this.getFallback($,Z);if(X)return X.quota;throw Error("Quota API rate-limited — try again later")}let z=await h2({name:K2.quotaLockName($),ttlMs:30000,path:this.configPath});if(!z){let X=this.getFallback($,Z);if(X&&this.now()<X.refreshAfter)return X.quota;throw Error("Quota refresh is already in progress")}try{let X=await this._fetchQuota(Z),J=this.now();return this.setFallback($,{quota:X,refreshAfter:J+e2(this.storage),checkedAt:J},Z,!0),this.fallbackApiErrors.delete($),this.fallbackErrorTokenFps.delete($),X}finally{await z.release()}}catch(z){throw this._handleFallbackFetchError($,Z,z),z}finally{this.inflightFallbacks.delete(K2.fallbackInflightKey($,Z))}})}async _fetchQuota($){if(!this.fetchQuotaFn)throw Error("Quota fetch not available — no fetchQuotaFn injected (push-only mode)");return this.fetchQuotaFn({accessToken:$,fetchImpl:this.fetchImpl,now:this.now})}static isAuthError($){return $?.status===401}_handleMainFetchError($){if(K2.isAuthError($))return;this.mainLastApiError=l2({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,z){if(K2.isAuthError(z))return;let X=a(Z),J=this.fallbackErrorTokenFps.get($)===X?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,l2({error:z,now:this.now(),previous:J})),this.fallbackErrorTokenFps.set($,X)}}function A4($){return Boolean($.primary||$.secondary)}function K3($){let{primary:Z,secondary:z}=$;if(!Z&&!z)return!1;if(Z&&Z.usedPercent>=100)return!1;if(z&&z.usedPercent>=100)return!1;return!0}import{readFile as p9}from"node:fs/promises";var I2=n("refresh"),z$=n("accounts"),b9=1e4,C9=15000,L3=50;function h($){return $.type==="oauth"&&$.corrupt!==!0}function S9($){let Z=$?.trim();if(!Z)return!1;try{let z=new URL(Z);return(z.protocol==="http:"||z.protocol==="https:")&&!z.username&&!z.password}catch{return!1}}function $Z($){return $.costZeroing?.enabled!==!1}class M$ extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor($){super(`Fallback account ${$} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var w9=[401,403,429],T4={primary:0,secondary:0},k9=!1,U3={primary:5,secondary:10};function D($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var f9=new Set(["__proto__","constructor","prototype"]);function t($){return $.length>0&&!f9.has($)}function E9($){return $ instanceof M$||D($)&&$.name==="AccountRemovedDuringRefreshError"&&$.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function O$($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():A9(),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,accountId:typeof $.accountId==="string"?$.accountId:void 0}}function b4($){if(!D($))return;if(typeof $.message!=="string")return;let Z=Number($.checkedAt);if(!Number.isFinite(Z))return;let z=Number($.nextRetryAt),X=Number($.retryCount);return{message:$.message,checkedAt:Z,nextRetryAt:Number.isFinite(z)?z:void 0,retryCount:Number.isFinite(X)?X:void 0,tokenHash:typeof $.tokenHash==="string"?$.tokenHash:void 0}}function y9($){if(!D($))return;let Z={};for(let J of["primary","secondary"]){let G=$[J];if(!D(G))continue;let Q=Number(G.usedPercent),Y=Number(G.remainingPercent),W=Number(G.checkedAt);if(!Number.isFinite(Q)||!Number.isFinite(Y)||!Number.isFinite(W))continue;let B=typeof G.windowMinutes==="number"?G.windowMinutes:Number.NaN;Z[J]={usedPercent:Q,remainingPercent:Y,checkedAt:W,resetsAt:typeof G.resetsAt==="string"?G.resetsAt:void 0,...Number.isFinite(B)&&B>0?{windowMinutes:B}:{}}}for(let J of["resetCreditsAvailable","resetCreditsApplicable"]){let G=typeof $[J]==="number"?$[J]:Number.NaN;if(Number.isFinite(G)&&G>=0)Z[J]=G}let z=$.spendControl;if(D(z)){let J=Number(z.limit),G=Number(z.used),Q=Number(z.remaining),Y=Number(z.usedPercent),W=Number(z.remainingPercent);if(Number.isFinite(J)&&Number.isFinite(G)&&Number.isFinite(Q)&&Number.isFinite(Y)&&Number.isFinite(W)&&typeof z.reached==="boolean")Z.spendControl={limit:J,used:G,remaining:Q,usedPercent:Y,remainingPercent:W,resetsAt:typeof z.resetsAt==="string"?z.resetsAt:void 0,unit:typeof z.unit==="string"?z.unit:void 0,source:typeof z.source==="string"?z.source:void 0,reached:z.reached}}let X=$.credits;if(D(X)&&typeof X.hasCredits==="boolean"&&typeof X.unlimited==="boolean"&&typeof X.overageLimitReached==="boolean"){let J=Number(X.balance);Z.credits={hasCredits:X.hasCredits,unlimited:X.unlimited,overageLimitReached:X.overageLimitReached,...Number.isFinite(J)?{balance:J}:{}}}return Object.keys(Z).length?Z:void 0}function v9($){if(!D($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",z=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!S9(Z))return null;let X=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...O$($),type:"api",apiKey:z||void 0,baseURL:Z,authHeader:X}}if($.type!=="oauth")return null;if($.corrupt===!0){if(typeof $.id!=="string"||!$.id.trim())return null;return{...O$($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...O$($),type:"oauth",corrupt:!0}}return{...O$($),type:"oauth",access:typeof $.access==="string"?$.access:void 0,refresh:$.refresh,expires:typeof $.expires==="number"?$.expires:void 0,lastRefreshedAt:typeof $.lastRefreshedAt==="number"?$.lastRefreshedAt:void 0,lastRefreshError:b4($.lastRefreshError),lastQuotaRefreshError:b4($.lastQuotaRefreshError),quota:y9($.quota)}}function h9($){if(!D($))return;let Z=Object.create(null);for(let[z,X]of Object.entries($)){if(!t(z)||!D(X))continue;let J={};if(D(X.inFlight))J.inFlight={...X.inFlight};if(D(X.lastOutcome)&&typeof X.lastOutcome.code==="string"&&X.lastOutcome.code.length>0&&typeof X.lastOutcome.at==="number"&&Number.isFinite(X.lastOutcome.at))J.lastOutcome={code:X.lastOutcome.code,at:X.lastOutcome.at,...D(X.lastOutcome.previousOutcome)&&typeof X.lastOutcome.previousOutcome.code==="string"&&X.lastOutcome.previousOutcome.code.length>0&&typeof X.lastOutcome.previousOutcome.at==="number"&&Number.isFinite(X.lastOutcome.previousOutcome.at)?{previousOutcome:{code:X.lastOutcome.previousOutcome.code,at:X.lastOutcome.previousOutcome.at}}:{}};if(typeof X.cooldownUntil==="number"&&Number.isFinite(X.cooldownUntil))J.cooldownUntil=X.cooldownUntil;if(Object.keys(J).length>0)Z[z]=J}return Object.keys(Z).length>0?Z:void 0}var C4=new Set;function y4($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(C4.has(Z))return;C4.add(Z),z$.warn("account load-dropped, preserved on disk",{droppedIds:$})}function M3($){if(!D($)||!Array.isArray($.accounts))return null;let Z=$.accounts,z=Z.map(v9).filter((X)=>X!=null);if(z.length<Z.length){let X=new Set;for(let Q of Z)if(D(Q)&&typeof Q.id==="string"&&Q.id.trim())X.add(Q.id.trim());let J=new Set(z.map((Q)=>Q.id)),G=[];for(let Q of X)if(!J.has(Q))G.push(Q);y4(G)}return{version:1,main:{type:"opencode",provider:"openai"},routing:D($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((X)=>Number.isInteger(X)):void 0,refresh:D($.refresh)?$.refresh:void 0,quota:D($.quota)?$.quota:void 0,reset:h9($.reset),dump:D($.dump)?$.dump:void 0,costZeroing:D($.costZeroing)?$.costZeroing:void 0,killswitch:D($.killswitch)?$.killswitch:void 0,logging:D($.logging)?$.logging:void 0,cachekeep:D($.cachekeep)?$.cachekeep:void 0,mainAccountId:typeof $.mainAccountId==="string"?$.mainAccountId:void 0,claustrum:m9($.claustrum),accounts:z}}function m9($){if(!D($))return;let Z=$.mode==="claustrum"?"claustrum":"local",z=g9($.transition),X=Array.isArray($.rowHistory)?$.rowHistory.filter((J)=>typeof J==="string"):void 0;return{mode:Z,transition:z,rowHistory:X}}function g9($){if(!D($)||!D($.fingerprints))return;if(typeof $.manifestRevision!=="string"||typeof $.storeGeneration!=="string"||!D($.fingerprints.fallbacks))return;let Z=Object.fromEntries(Object.entries($.fingerprints.fallbacks).filter((z)=>typeof z[1]==="string"));return{manifestRevision:$.manifestRevision,storeGeneration:$.storeGeneration,fingerprints:{main:typeof $.fingerprints.main==="string"?$.fingerprints.main:void 0,fallbacks:Z}}}async function B2($){try{return{exists:!0,value:JSON.parse(await p9($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function N2($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function v4($){return(await h4($)).roster}async function h4($){let Z;try{Z=(await B2($)).value}catch{return{roster:null,mode:"claustrum"}}return{roster:I3(Z),mode:S(D(Z)?Z:void 0)}}function _3($,Z){if(!D($))return $;let z=D(Z)?Z:{},X=D(z.main)?z.main:void 0,J=D(z.accounts)?z.accounts:{},G=D($.quota)?$.quota:{},Q=D($.refresh)?$.refresh:{},Y=X??G,W=X??Q,j=Array.isArray($.accounts)?$.accounts.map((V)=>{if(!D(V))return V;let q=typeof V.id==="string"&&D(J[V.id])?J[V.id]:{};return{...V,...q}}):void 0;return m4({...$,refresh:N2({...Q,mainLastRefreshError:W.lastRefreshError,mainRefreshLeaseId:W.refreshLeaseId,mainRefreshLeaseUntil:W.refreshLeaseUntil,mainRefreshLeaseTokenHash:W.refreshLeaseTokenHash}),quota:N2({...G,mainQuota:Y.quota,mainQuotaCheckedAt:Y.quotaCheckedAt,mainQuotaToken:Y.quotaToken,mainLastQuotaApiError:Y.lastQuotaApiError}),accounts:j})}async function u9($){let Z=await B2($.configPath);if(!Z.exists)return null;let z=await B2($.statePath);return M3(_3(Z.value,z.value))}function m4($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function l9($){return N2({id:$.id,label:$.label,type:$.type,corrupt:$.type==="oauth"&&$.corrupt===!0?!0:void 0,enabled:$.enabled,addedAt:$.addedAt,accountId:$.accountId,baseURL:$.type==="api"?$.baseURL:void 0,authHeader:$.type==="api"?$.authHeader:void 0})}function g4($){if($.type==="api")return N2({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return N2({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function _$($){return Math.max($?.primary?.checkedAt??0,$?.secondary?.checkedAt??0)}function L2($,Z,z){if(z in Z)$[z]=Z[z];else delete $[z]}function d9($,Z){return $.access===Z.access&&$.refresh===Z.refresh&&$.expires===Z.expires&&$.lastRefreshedAt===Z.lastRefreshedAt}function i9($,Z){if(!d9($,Z))return Z;if(!("lastRefreshError"in Z))return $;if(!("lastRefreshError"in $))return Z;return(Z.lastRefreshError?.checkedAt??0)>($.lastRefreshError?.checkedAt??0)?Z:$}var c9=300000;function S4($,Z){if($===void 0)return 0;return $>Z+c9?0:$}function s9($,Z,z){let X=Date.now(),J=S4(Z.lastRefreshedAt,X),G=S4(z.lastRefreshedAt,X),Q=Z.expires??0,Y=z.expires??0,W=G>J?z:J>G?Z:Y>Q?z:Q>Y?Z:i9(Z,z);L2($,W,"access"),L2($,W,"refresh"),L2($,W,"expires"),L2($,W,"lastRefreshedAt"),L2($,W,"lastRefreshError")}function n9($,Z,z){if(!D($))return Z;let X=$,J=_$(X.quota),G=_$(Z.quota),Q=J>G,Y=Q?{...X,...Z,quota:X.quota,lastQuotaRefreshError:X.lastQuotaRefreshError}:{...X,...Z};if(!Q&&!("lastQuotaRefreshError"in Z))delete Y.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete Y.lastRefreshError;if(typeof X.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||X.lastUsed>Z.lastUsed))Y.lastUsed=X.lastUsed;if(s9(Y,X,Z),z==="claustrum"&&X.refresh===m2(G2)&&Z.refresh!==m2(G2))L2(Y,X,"access"),L2(Y,X,"refresh"),L2(Y,X,"expires"),z$.warn("discarded stale credential write over a custody tombstone");return Y}function x3($){let Z=$.refresh?N2({enabled:$.refresh.enabled,refreshBeforeExpiryMinutes:$.refresh.refreshBeforeExpiryMinutes}):void 0,z=$.quota?N2({enabled:$.quota.enabled,checkIntervalMinutes:$.quota.checkIntervalMinutes,refreshEveryNRequests:$.quota.refreshEveryNRequests,minimumRemaining:$.quota.minimumRemaining,failClosedOnUnknownQuota:$.quota.failClosedOnUnknownQuota}):void 0;return m4({version:1,main:$.main,routing:$.routing,fallbackOn:$.fallbackOn,refresh:Z,quota:z,reset:$.reset,dump:$.dump,costZeroing:$.costZeroing,killswitch:$.killswitch,logging:$.logging,cachekeep:$.cachekeep,mainAccountId:$.mainAccountId,...$.claustrum!==void 0?{claustrum:{mode:$.claustrum.mode??"local",...$.claustrum.transition?{transition:$.claustrum.transition}:{},...$.claustrum.rowHistory?{rowHistory:$.claustrum.rowHistory}:{}}}:{},accounts:$.accounts.map(l9)})}async function A2($,Z=!1){let z=Date.now(),X=z+C9,J=0;while(Date.now()<=X){J++;let Y=await h2({name:"save",ttlMs:b9,path:$,renew:Z});if(Y)return Y;let W=X-Date.now();if(W<=0)break;await T9(Math.min(L3+c4(L3),W))}let G=Date.now()-z,Q=Math.round(G/Math.max(1,J));throw Error(`Timed out after ${G}ms waiting for the account store lock on ${$} (${J} attempts, ~${Q}ms apart; retry interval is ${L3}ms). A gap near the retry interval means lock contention; a much larger one means this process's event loop was saturated and the wait expired without getting scheduled.`)}function S($){return $?.claustrum?.mode==="claustrum"?"claustrum":"local"}async function zZ($,Z){let{configPath:z,statePath:X}=Z,J=await A2(z,!0);try{let G=await A2(X,!0);try{let Q=await B2(z),Y=await B2(X),W=(Q.exists?M3(_3(Q.value,Y.value)):null)??u4(),B=new Set(W.accounts.map((q)=>q.id));return await $({read:async()=>structuredClone(W),write:async(q)=>{let K=x3(q),H=p4(Q.value,B,new Set),N=new Set((Array.isArray(K.accounts)?K.accounts:[]).map((O)=>D(O)&&typeof O.id==="string"?O.id.trim():"").filter(Boolean)),U=H.filter((O)=>D(O)&&typeof O.id==="string"&&!N.has(O.id.trim())),M={...D(Q.value)?Q.value:{},...K,accounts:[...Array.isArray(K.accounts)?K.accounts:[],...U]};await Y2(z,M),await Y2(X,F3(q)),Q.value=M,W=structuredClone(q)},writeMode:async(q,K)=>{let H=D(Q.value)?Q.value:{version:1,accounts:[]},N=D(H.claustrum)?H.claustrum:{},U=Array.isArray(N.rowHistory)?N.rowHistory.filter((O)=>typeof O==="string"):void 0,P={mode:q,...q==="claustrum"&&K?{transition:K}:{},...U?{rowHistory:U}:{}},M={...H,claustrum:P};await Y2(z,M),Q.value=M,W={...W,claustrum:{mode:q,...q==="claustrum"&&K?{transition:K}:{},...U?{rowHistory:U}:{}}}}})}finally{await G.release()}}finally{await J.release()}}function F3($){let Z=Object.fromEntries($.accounts.map((z)=>[z.id,g4(z)]));return{version:1,main:N2({quota:$.quota?.mainQuota,quotaCheckedAt:$.quota?.mainQuotaCheckedAt,quotaToken:$.quota?.mainQuotaToken,lastQuotaApiError:$.quota?.mainLastQuotaApiError,lastRefreshError:$.refresh?.mainLastRefreshError,refreshLeaseId:$.refresh?.mainRefreshLeaseId,refreshLeaseUntil:$.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:$.refresh?.mainRefreshLeaseTokenHash}),accounts:Z}}function I3($){if(!D($)||!Array.isArray($.accounts))return null;let Z=new Set;for(let z of $.accounts){if(!D(z))continue;if(typeof z.id!=="string")continue;let X=z.id.trim();if(!X)continue;Z.add(X)}return Z}function a9($,Z,z,X){if(!D($)||!Array.isArray($.accounts))return{preservedRawEntries:[],preservedIds:[]};let J=[],G=[];for(let Q of Z){if(z.has(Q))continue;if(X.has(Q))continue;let Y=$.accounts.find((W)=>D(W)&&typeof W.id==="string"&&W.id.trim()===Q);if(!Y)continue;J.push(Y),G.push(Q)}return{preservedRawEntries:J,preservedIds:G}}function t9($){if(!Array.isArray($))return[];let Z=[];for(let z of $){if(!D(z))continue;if(typeof z.id!=="string")continue;Z.push(z.id)}return Z}function p4($,Z,z){let X=I3($);if(X===null)return[];let{preservedRawEntries:J,preservedIds:G}=a9($,X,Z,z);return y4(G),J}async function U2($,Z,z={}){let{configPath:X,statePath:J}=Z,G=await A2(X);try{let Q=await A2(J);try{let Y=await B2(X),W=await B2(J),B=(Y.exists?M3(_3(Y.value,W.value)):null)??u4(),j=new Set(B.accounts.map((R)=>R.id)),V=I3(Y.value)??new Set,q=$(B,{rawRosterIds:[...V],loadedRosterIds:[...j]})??B,K=new Set(q.accounts.map((R)=>R.id)),H=[...j].filter((R)=>!K.has(R));if(H.length>0)q.claustrum={...q.claustrum,mode:q.claustrum?.mode??"local",rowHistory:[...new Set([...q.claustrum?.rowHistory??[],...H])]};let N=new Set(z.allowDrop??[]),U=p4(Y.value,j,N),P=x3(q),M=new Set((Array.isArray(P.accounts)?P.accounts:[]).map((R)=>D(R)&&typeof R.id==="string"?R.id.trim():"").filter(Boolean)),O=U.filter((R)=>{if(!D(R))return!1;if(typeof R.id!=="string")return!1;return!M.has(R.id.trim())}),b={...D(Y.value)?Y.value:{},...P,accounts:[...Array.isArray(P.accounts)?P.accounts:[],...O]};return await Y2(X,b),await Y2(J,F3(q)),z$.debug("account config written",{accountCount:b.accounts.length,accountIds:t9(b.accounts)}),q}finally{await Q.release()}}finally{await G.release()}}function u4(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function o9($,Z){$.main=$.main??{};let z=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:_$($.main.quota),X=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:_$(Z.quota?.mainQuota);if(z>X)return;$.main.quota=Z.quota?.mainQuota,$.main.quotaCheckedAt=Z.quota?.mainQuotaCheckedAt,$.main.quotaToken=Z.quota?.mainQuotaToken,$.main.lastQuotaApiError=Z.quota?.mainLastQuotaApiError}function r9($,Z){$.main=$.main??{},$.main.lastRefreshError=Z.refresh?.mainLastRefreshError,$.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function D3($){if(Array.isArray($))return $.map(D3);if(!D($))return $;return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0).map(([Z,z])=>[Z,D3(z)]))}async function e9($,Z,z={mainQuota:!0,mainRefresh:!0,accounts:!0}){let X=Z.statePath,J=await A2(X);try{let G=(await B2(X)).value,Q=D(G)?{...G,version:1}:{version:1};if(z.mainQuota)o9(Q,$);if(z.mainRefresh)r9(Q,$);if(z.accounts){let Y=z.accounts===!0?null:new Set(z.accounts),{roster:W,mode:B}=await h4(Z.configPath);Q.accounts={...D(Q.accounts)?Q.accounts:{}};for(let j of $.accounts){if(Y&&!Y.has(j.id))continue;if(W&&!W.has(j.id))continue;Q.accounts[j.id]=n9(Q.accounts[j.id],g4(j),B)}if(Y){for(let j of Y)if(!$.accounts.some((V)=>V.id===j))delete Q.accounts[j]}if(W){for(let j of Object.keys(Q.accounts))if(!W.has(j))delete Q.accounts[j]}}await Y2(X,D3(Q))}finally{await J.release()}}function $5($){return $?.fallbackOn?.length?$.fallbackOn:w9}function XZ($,Z){return $5(Z).includes($)}function Z5($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??T4.primary,secondary:Z.secondary??Z["1w"]??T4.secondary}}function P3($){return $?.quota?.enabled!==!1}function X$($){return $?.quota?.failClosedOnUnknownQuota??k9}function l4($,Z,z=Date.now()){if(!P3(Z))return!0;if(!$)return!X$(Z);let X=Z5(Z),J=X$(Z);for(let G of["primary","secondary"]){let Q=$[G];if(!Q)continue;if(P$(Q,z)){if(J)return!1;continue}if(Q.remainingPercent<X[G])return!1}return!0}function d4($){return $?.killswitch?.enabled===!0}function w4($){return{primary:$?.primary??$?.["5h"]??U3.primary,secondary:$?.secondary??$?.["1w"]??U3.secondary}}function i4($,Z){if(!$?.killswitch)return U3;if(Z&&$.killswitch.accounts?.[Z])return w4($.killswitch.accounts[Z]);return w4($.killswitch.main)}function JZ($,Z,z,X=Date.now()){if(!d4(Z))return!0;if(!$)return!X$(Z);let J=i4(Z,z),G=X$(Z);for(let Q of["primary","secondary"]){let Y=$[Q];if(!Y)continue;if(P$(Y,X)){if(G)return!1;continue}if(Y.remainingPercent<J[Q])return!1}return!0}function GZ($,Z,z,X){if(!d4(X))return 300;let J=[],G=[{accountId:void 0,quota:$},...Z];for(let{accountId:Y,quota:W}of G){if(!W)continue;let B=i4(X,Y),j=[],V=!1;for(let q of["primary","secondary"]){let K=W[q];if(!K||P$(K,z))continue;if(K.remainingPercent>=B[q])continue;let H=K.resetsAt?Date.parse(K.resetsAt):NaN;if(!Number.isFinite(H)||H<=z){V=!0;break}j.push(H)}if(V||j.length===0)continue;J.push(Math.max(...j))}if(J.length===0)return 300;let Q=Math.min(...J);return Math.max(1,Math.ceil((Q-z)/1000))}function z5($){return typeof $.version==="number"&&Array.isArray($.accounts)}async function QZ($,Z){let{configPath:z,statePath:X}=Z,J=await A2(z);try{let G=await A2(X);try{let Q=await B2(z);if(Q.exists&&D(Q.value)){if(z5(Q.value))return}if(!$)return;let Y={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if($.access){let j=N$({id_token:"",access_token:$.access,refresh_token:$.refresh});if(j)Y.mainAccountId=j}let B={...Q.exists&&D(Q.value)?Q.value:{},...x3(Y)};await Y2(z,B),await Y2(X,F3(Y))}finally{await G.release()}}finally{await J.release()}}function X5($){return $?.refresh?.enabled!==!1}function J5($){return($?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function c4($){return Math.floor(Math.random()*($+1))}function R2($,Z,z){return!$.access||!$.expires||$.expires-z<=J5(Z)}function G5($,Z){return Boolean($.access&&typeof $.expires==="number"&&$.expires>Z)}function Q5($,Z){return Boolean($.mainAccountId&&Z.accountId&&Z.accountId===$.mainAccountId)}function p($,Z){let z=$.accounts.findIndex((X)=>X.id===Z.id);if(z!==-1)$.accounts[z]=Z}function Z$($){return $ instanceof Error?$.message:String($)}function O3($,Z,z){if(Z instanceof T2)return;$.lastRefreshError=Q4({error:Z,now:z,refreshToken:$.refresh,previous:$.lastRefreshError})}function N3($,Z,z){if(Z instanceof T2)return;if($.lastQuotaRefreshError=l2({error:Z,now:z,previous:$.lastQuotaRefreshError}),Z?.isRefreshError===!0)O3($,Z,z)}function k4($,Z){if(!$)return!1;if(!$.resetsAt)return!0;let z=Date.parse($.resetsAt);return Number.isFinite(z)?z>Z:!0}function Y5($,Z){if(!$)return!1;return k4($.primary,Z)||k4($.secondary,Z)}function W5($,Z,z){if(!$)return!1;let X=Z?.quota?.checkIntervalMinutes??5,J=Math.max(1,X)*60000,G=Math.max($.primary?.checkedAt??0,$.secondary?.checkedAt??0);return z-G<J}function f4($,Z,z){return!W5($.quota,Z,z)}function B5($,Z,z,X){return a$(z)&&l4($.quota,Z,X)&&Y5($.quota,X)}function j5($){let Z=$?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var V5=60000,H5=60000,R3=600000;function A3($){return`fallback-oauth-refresh-${R9("sha256").update($).digest("base64url").slice(0,16)}`}var q5=1e4,K5=100,YZ=globalThis.setTimeout.bind(globalThis),WZ=globalThis.clearTimeout.bind(globalThis);class L5{now;fetchImpl;paths;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;quotaManager;onFallbackStorageChanged;options;custodyReadManifest;custodyProvider;constructor($){this.options=$,this.now=$.now??Date.now,this.fetchImpl=$.fetchImpl??fetch,this.paths=$.paths,this.quotaManager=$.quotaManager??null,this.onFallbackStorageChanged=$.onFallbackStorageChanged,this.custodyReadManifest=$.custody.readManifest,this.custodyProvider=$.custody.provider??"openai"}async assertNotCustodyInert($){if(!$)return;$$($,this.custodyProvider);let Z=await this.custodyReadManifest();if(E4($,Z,this.custodyProvider))throw new T2(this.custodyProvider)}async isCustodyRefreshInert($){return await this.custodyAccountState($)!==null}async custodyAccountState($){if(j2($,this.custodyProvider))return"tombstoned";let Z=await this.custodyReadManifest();return J$($,Z,this.custodyProvider)?"enrolling":null}seedFallbackQuota($,Z){if(!this.quotaManager)return;if(!$.quota)return;let z=Math.max($.quota.primary?.checkedAt??0,$.quota.secondary?.checkedAt??0);if(z<=0)return;let X=this.quotaManager.getFallback($.id,$.access);if(X&&X.checkedAt>=z)return;this.quotaManager.setFallback($.id,{quota:$.quota,refreshAfter:z+j5(Z),checkedAt:z},$.access,!1,$.accountId)}async load(){return u9(this.paths)}async save($,Z){await e9($,this.paths,{accounts:Z??!0})}startBackgroundRefresh(){let $=async()=>{if(await this.refreshDueAccounts(),this.options.fetchQuotaFn)await this.refreshQuotaForDueAccounts()};if($().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{$().catch(()=>{})},V5+c4(H5)),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)clearInterval(this.refreshTimer);if(this.quotaTimer)clearInterval(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts($){let Z=$!==void 0?$:await this.load();if(!Z)return[];let z=[],X=!1;for(let J of Z.accounts){if(J.enabled===!1||!h(J))continue;if(Q5(Z,J))continue;let G=await this.custodyAccountState(J),Q=G==="enrolling"||G==="tombstoned",Y=!1,W=J;try{if(R2(W,Z,this.now())){let B=W.lastRefreshError;if(B&&J2(B,W.refresh,this.now()))throw Y=!0,Error(f2(B,this.now()));if(!Q)try{W=await this.refreshAccount(W,Z),X=!0}catch(j){if(E9(j))continue;Y=!0;let V=Z.accounts.find((q)=>q.id===J.id&&h(q));if(V&&!J2(V.lastRefreshError,V.refresh,this.now()))O3(V,j,this.now()),p(Z,V),X=!0;throw j}}if(this.seedFallbackQuota(W,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(W),Z))z.push(W)}catch(B){let j=G5(W,this.now());if(Y){if(!j)continue}else if(!j)continue;if(B5(W,Z,B,this.now()))I2.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:W.id,error:Z$(B)}),z.push(W);else if(!X$(Z))z.push(W)}}if(X)try{await this.save(Z)}catch(J){z$.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:Z$(J)})}return z}async markUsed($){try{let Z=await this.load();if(!Z)return;let z=Z.accounts.find((X)=>X.id===$.id);if(!z)return;z.lastUsed=this.now(),await this.save(Z,[z.id])}catch(Z){z$.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:$.id,error:Z$(Z)})}}accountPassesQuotaPolicy($,Z){return l4($.quota,Z,this.now())}quotaPolicyAccount($){if(!this.quotaManager)return $;let Z=this.quotaManager.getFallback($.id,$.access)?.quota;return Z?{...$,quota:Z}:$}async refreshDueAccounts(){let $=await this.load();if(!$||!X5($))return;let Z=!1;for(let z of $.accounts){if(z.enabled===!1||!h(z))continue;if(await this.isCustodyRefreshInert(z))continue;if(!R2(z,$,this.now()))continue;if(J2(z.lastRefreshError,z.refresh,this.now()))continue;try{I2.debug("fallback oauth background due",{pid:process.pid,accountId:z.id,expiresInMs:z.expires?z.expires-this.now():void 0}),await this.refreshAccount(z,$),Z=!0}catch(X){I2.warn("fallback oauth background failed",{pid:process.pid,accountId:z.id,error:Z$(X)}),O3(z,X,this.now()),p($,z),Z=!0}}if(Z)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!P3($))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let z of $.accounts){if(z.enabled===!1||!h(z))continue;if(await this.isCustodyRefreshInert(z))continue;let X=z;try{if(R2(X,$,this.now())){if(J2(X.lastRefreshError,X.refresh,this.now()))continue;X=await this.refreshAccount(X,$),Z=!0}if(E2(X.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(X,$),!(this.quotaManager?this.quotaManager.isFallbackStale(X.id,X.access):f4(X,$,this.now())))continue;await this.refreshAccountQuota(X,$),Z=!0}catch(J){N3(z,J,this.now()),p($,z),Z=!0}}if(Z)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let Z=await this.load(),z=[];if(!Z||!P3(Z))return{storage:Z,errors:z};if(!this.options.fetchQuotaFn)return{storage:Z,errors:z};let X=$.force??!1,J=!1;for(let G of Z.accounts){if(G.enabled===!1||!h(G))continue;if(await this.isCustodyRefreshInert(G))continue;let Q=G;try{if(R2(Q,Z,this.now())){let Y=Q.lastRefreshError;if(Y&&J2(Y,Q.refresh,this.now()))throw Error(f2(Y,this.now()));Q=await this.refreshAccount(Q,Z),J=!0}if(!X&&!f4(Q,Z,this.now())){if(Q.lastQuotaRefreshError)Q.lastQuotaRefreshError=void 0,p(Z,Q),J=!0;continue}await this.refreshAccountQuota(Q,Z),J=!0}catch(Y){N3(G,Y,this.now()),p(Z,G),J=!0,z.push({accountId:G.id,message:Z$(Y)})}}if(J)await this.save(Z);return{storage:Z,errors:z}}async refreshAccount($,Z,z={}){let X=this.refreshPromises.get($.id);if(X){let Q=await X;return p(Z,Q),Q}let J=this.refreshAccountNow($,Z,z).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,J);let G=await J;return p(Z,G),G}async waitForConcurrentFallbackRefresh($,Z,z,X){let J=Date.now()+q5;while(Date.now()<J){await new Promise((B)=>setTimeout(B,K5));let G=await this.load(),Q=G?.accounts.find((B)=>B.id===$.id&&h(B));if(!Q)continue;if(await this.assertNotCustodyInert(Q),(Q.access!==z.access||Q.refresh!==z.refresh||(Q.expires??0)>(z.expires??0)+60000)&&(X.force||!R2(Q,G,this.now())))return p(Z,Q),I2.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:Q.id,expiresInMs:Q.expires?Q.expires-this.now():void 0}),Q;let W=Q.lastRefreshError;if(W&&J2(W,Q.refresh,this.now()))throw p(Z,Q),Error(f2(W,this.now()))}return null}async refreshAccountNow($,Z,z){let X=await this.load(),J=X?.accounts.find((Y)=>Y.id===$.id&&h(Y));if(await this.assertNotCustodyInert(J),J&&!z.force&&!R2(J,X,this.now()))return p(Z,J),J;let G=J??$,Q=await h2({name:A3(G.id),ttlMs:R3,path:this.paths.configPath,now:this.now,renew:!0});if(!Q){I2.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:G.id});let Y=await this.waitForConcurrentFallbackRefresh($,Z,G,z);if(Y)return Y;throw Error("Fallback OAuth refresh is already in progress")}try{if(X=await this.load(),J=X?.accounts.find((j)=>j.id===$.id&&h(j)),await this.assertNotCustodyInert(J),J&&!z.force&&!R2(J,X,this.now()))return p(Z,J),J;if(!J)throw new M$($.id);G=J;let Y=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});I2.debug("fallback oauth refresh request start",{pid:process.pid,accountId:G.id,force:z.force===!0,expiresInMs:G.expires?G.expires-this.now():void 0});let W=await Y({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});G.access=W.access,G.refresh=W.refresh,G.expires=W.expires,G.lastRefreshedAt=W.expires-W.expiresIn*1000,G.lastRefreshError=void 0,p(Z,G),await this.save(Z);let B=await this.load();if(await this.assertNotCustodyInert(B?.accounts.find((j)=>j.id===$.id&&h(j))),!B?.accounts.some((j)=>j.id===$.id))throw new M$($.id);return I2.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G}finally{await Q.release()}}async refreshAccountQuota($,Z){let z=$;if($$(z,"openai"),!z.access)throw Error(`Fallback account ${$.id} has no access token`);if(!this.options.fetchQuotaFn)throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled");let X=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),J=(G)=>this.quotaManager?this.quotaManager.refreshFallback(z.id,G):X({accessToken:G,fetchImpl:this.fetchImpl,now:this.now});try{if(!z.access)throw Error(`Fallback account ${$.id} has no access token`);let G=await J(z.access);z.quota=G,z.lastQuotaRefreshError=void 0,p(Z,z),await this.save(Z)}catch(G){throw N3($,G,this.now()),p(Z,$),G}}}var b3=n("custody");function I9($,Z){let z=Buffer.from($,"utf8"),X=Buffer.from(Z,"utf8"),J=Buffer.allocUnsafe(4),G=Buffer.allocUnsafe(4);return J.writeUInt32BE(z.length),G.writeUInt32BE(X.length),N5("sha256").update(J).update(z).update(G).update(X).digest("hex")}var a4="claustrum-tombstone:v1:",y=Symbol("custody-refuse"),G$=Symbol("custody-excluded");function UZ($,Z,z){if(Z&&Z!=="local")z.set($,Z);return $}function m2($){return`${a4}${$}`}function D5($){return{type:"oauth",access:"",refresh:m2($),expires:0}}function _4($){if($.startsWith(a4))throw new T2("unknown")}function P5($,Z){return Z3(Z).has($.id)}function x$($,Z){return P5($,Z)}function j2($,Z){if($.corrupt)return!1;return $.refresh===m2(Z)}function DZ($,Z,z,X=G2){if(S(z)!=="claustrum")return!1;if(!x$($,Z))return!1;return j2($,X)}function J$($,Z,z=G2){return x$($,Z)&&!j2($,z)}function E4($,Z,z){return x$($,Z)||j2($,z)}function t4($,Z){let z=o2($.payload.access);if(!z)return{reason:"nullClaim"};let X=r2(z);if(!X)return{reason:"nullClaim"};if(Z.accountId&&X!==Z.accountId)return{reason:"identityMismatch",detail:"claimDiffersFromLocal"};if($.servedAccountId&&(Z.accountId&&$.servedAccountId!==Z.accountId||$.servedAccountId!==X))return{reason:"identityMismatch",detail:"labelDisagreesWithClaim"};return{reason:"ok"}}async function s4($,Z,z,X={}){let J=z??{ok:!0,value:{version:1,providers:[]},revision:$3('{"version":1,"providers":[]}')};if(j2($,G2)){if(S(Z)!=="claustrum")return G$;if(!x$($,J))return y;if(!$.accountId&&X.completeEnrollmentDeps){let j=await n4($,X.completeEnrollmentDeps);if(j.kind==="failed"||j.kind==="skipped"&&j.reason==="lockBusy")return y;let V=await X.completeEnrollmentDeps.loadAccounts(X.completeEnrollmentDeps.paths),q=V?.accounts.find((K)=>K.id===$.id);if(!V||!q||!h(q)||!q.accountId)return y;return s4(q,V,J,{...X,completeEnrollmentDeps:void 0})}let{manifestHandle:G,cache:Q}=X;if(!G||!Q)return y;let Y=(X.now??Date.now)();if(Q.isBlocked(G)||Q.isReauth(G,Y))return y;let W=await Q.peek(G);if(!W&&!X.requestPath)try{W=await Q.get(G,30000)}catch{return y}if(!W||W.expiresAtMs<=Y)return y;let B=t4(W,$);if(B.reason==="identityMismatch")return b3.warn("custody identity check refused",{reason:B.reason}),y;if(B.reason==="nullClaim")b3.warn("custody identity unverifiable; serving",{credentialId:G});return{token:W.payload.access,provenance:{handle:G,recordVersion:W.recordVersion}}}if(J$($,J,G2)){let G=(X.now??Date.now)(),Q=X.refreshBeforeExpiryMs??0;if(S(Z)==="claustrum"){if(!X.completeEnrollmentDeps)return y;let Y=await n4($,X.completeEnrollmentDeps);if(Y.kind==="failed"||Y.kind==="skipped"&&Y.reason==="lockBusy")return y;let W=await X.completeEnrollmentDeps.loadAccounts(X.completeEnrollmentDeps.paths),B=W?.accounts.find((V)=>V.id===$.id);if(!W||!B||!h(B))return y;let j=await X.completeEnrollmentDeps.readCustodyManifest(X.completeEnrollmentDeps.manifestPath);return s4(B,W,j,X)}if($.access&&$.expires&&$.expires-G>Q)return{token:$.access,provenance:"local"};return y}if(!$.access)return y;return{token:$.access,provenance:"local"}}var T3=3600000;class O5{#z;#J=new Map;#B=new Map;#Y=new Map;#G=new Map;#$=new Set;#X=new Map;#Q=new Map;#W;#Z=!1;constructor($){this.#z=$.connector({connectionFile:"",handshakeTimeoutMs:5000}),this.#W=$.now??Date.now}async peek($){return this.#J.get($)}async peekMetadata($){let Z=this.#J.get($);if(!Z)return;return{recordVersion:Z.recordVersion,expiresAtMs:Z.expiresAtMs}}isBlocked($){return this.#$.has($)}isReauth($,Z=this.#W()){let z=this.#X.get($);if(z===void 0)return!1;return z>Z}markVaultSuccess($){this.#X.delete($),this.#Q.delete($),this.#Y.delete($)}async get($,Z,z={}){if(this.#Z)throw Error("Claustrum cache is closed");if(!z.force){let Y=this.#J.get($);if(Y)return Y}let X=!!z.force,J=this.#B.get($);if(J&&J.force===X)return J.promise;let G=this.#j($,Z),Q={force:X,promise:G.finally(()=>{this.#B.delete($)})};return this.#B.set($,Q),Q.promise}async#j($,Z){let z=await this.#z,X=8;for(let J=0;J<8;J++){let G=await z.getCredential($,Z),Q=G.expiresAtMs??Number.MAX_SAFE_INTEGER;if(!this.#G.get($)?.has(G.recordVersion)){let W={payload:{access:G.material},recordVersion:G.recordVersion,expiresAtMs:Q,servedAccountId:G.accountId};return this.#J.set($,W),this.#$.delete($),this.#G.delete($),W}await U5(5*(J+1))}throw Error("custody credential rejected version after retries")}async reportAuthFailure($){if(this.#Z)return;let{handle:Z,recordVersion:z,providerStatus:X}=$,J=this.#W(),G=this.#Y.get(Z);if(G!==void 0&&G>=z)return;let Q=this.#Q.get(Z);if(Q&&Q.count>=2)if(Q.reauthUntil!==void 0&&J>=Q.reauthUntil)this.#Q.delete(Z),this.#X.delete(Z),this.#Y.delete(Z),Q=void 0;else return;let Y=await this.#z;try{await Y.reportAuthFailure({handle:Z,providerStatus:X,recordVersion:z,reporterSource:"direct"}),this.#Y.set(Z,z),this.#$.add(Z);let W=this.#Q.get(Z);if(this.#Q.set(Z,{count:(W?.count??0)+1,firstReportedAt:W?.firstReportedAt??J,reauthUntil:(W?.count??0)+1>=2?J+T3:void 0}),(W?.count??0)+1>=2)this.#X.set(Z,J+T3),b3.warn("custody report bound reached; entering reauth",{reauthMs:T3})}finally{let W=this.#J.get(Z);if(W&&W.recordVersion===z)this.#J.delete(Z);let B=this.#G.get(Z);if(!B)B=new Set,this.#G.set(Z,B);B.add(z)}}close(){if(this.#Z)return;this.#Z=!0,this.#J.clear(),this.#B.clear(),this.#Y.clear(),this.#G.clear(),this.#$.clear(),this.#X.clear(),this.#Q.clear(),this.#z.then(($)=>$.close()).catch(()=>{})}}class T2 extends Error{code="CUSTODY_TOMBSTONED";status=503;isRefreshError=!0;constructor($){super(`custody tombstoned: ${m2($)}`);this.name="CustodyTombstoneRefreshError"}}function $$($,Z){if(j2($,Z))throw new T2(Z)}async function n4($,Z){let z=Z.provider??G2,X=await Z.readCustodyManifest(Z.manifestPath),J=await Z.loadAccounts(Z.paths);if(!J)return{kind:"skipped",reason:"notEnrolling"};let G=J.accounts.find((B)=>B.id===$.id);if(!G||!h(G))return{kind:"skipped",reason:"notEnrolling"};if(!J$(G,X,z)&&!(j2(G,z)&&!G.accountId))return{kind:"skipped",reason:"notEnrolling"};let Q=Z3(X).get(G.id);if(!Q)return{kind:"skipped",reason:"notEnrolling"};let Y=A3(G.id),W=await Z.acquireRefreshFileLock({name:Y,ttlMs:R3,path:Z.configPath});if(!W)return{kind:"skipped",reason:"lockBusy"};try{let B=await Z.readCustodyManifest(Z.manifestPath),j=await Z.loadAccounts(Z.paths),V=j?.accounts.find((U)=>U.id===$.id);if(!j||!V||!h(V)||!J$(V,B,z)&&!(j2(V,z)&&!V.accountId))return{kind:"skipped",reason:"notEnrolling"};let q;try{q=await Z.cache.get(Q,Z.minTtlMs,{force:!0})}catch(U){return{kind:"failed",reason:M5(U)}}let K=t4({payload:{access:q.payload.access},recordVersion:q.recordVersion,expiresAtMs:q.expiresAtMs,servedAccountId:q.servedAccountId},V);if(K.reason!=="ok")return K.reason==="nullClaim"?{kind:"failed",reason:"nullClaim",recordVersion:q.recordVersion}:{kind:"failed",reason:"identityMismatch",recordVersion:q.recordVersion};let H=o2(q.payload.access),N=H?r2(H):void 0;if(!N)throw Error("unreachable: the served identity check refuses a missing claim before this point");return await Z.mutateAccounts((U)=>{let P=U.accounts.find((O)=>O.id===$.id);if(!P||!h(P))return U;let M={...P,accountId:P.accountId??N,...D5(z)};return{...U,accounts:U.accounts.map((O)=>O.id===$.id?M:O)}},Z.paths),{kind:"succeeded",recordVersion:q.recordVersion}}finally{await W.release().catch(()=>{})}}function M5($){if($&&typeof $==="object"&&"action"in $&&$.action==="gone")return"gone";return"unavailable"}function o4($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var C3="/backend-api/wham/rate-limit-reset-credits",_5=`https://chatgpt.com${C3}`,z6=`${C3}/consume`,x5=`https://chatgpt.com${z6}`,F5=300000,I5=60000,R5=15000,A5=60000;function F$($){return{configPath:$.configPath,statePath:$.statePath}}class o extends Error{kind;cooldownUntil;constructor($,Z,z){super(Z);this.name="ResetRedemptionError",this.kind=$,this.cooldownUntil=z}}class b2 extends Error{kind;status;constructor($,Z,z){super(Z);this.name="ResetCreditError",this.kind=$,this.status=z}}function X6($,Z,z){return{authorization:`Bearer ${$}`,...z?{"chatgpt-account-id":z}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":Z}}function I$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function J6($){if(!$)return;return{...$.inFlight?{inFlight:{...$.inFlight}}:{},...$.lastOutcome?{lastOutcome:{...$.lastOutcome}}:{},...$.cooldownUntil!==void 0?{cooldownUntil:$.cooldownUntil}:{}}}function S3($){if(!I$($)||typeof $.redeemRequestId!=="string"||$.redeemRequestId.length===0||typeof $.creditId!=="string"||$.creditId.length===0||typeof $.startedAt!=="number"||!Number.isFinite($.startedAt))return;return{redeemRequestId:$.redeemRequestId,creditId:$.creditId,startedAt:$.startedAt}}function G6($){return Boolean($&&Object.hasOwn($,"inFlight"))}function Q6($,Z){return Z-$.startedAt<F5}function R$($,Z){if(!t(Z))return;return $.reset?.[Z]}function Y6($){if(!$.reset)$.reset=Object.create(null);return $.reset}function W6($,Z,z){if(!t(Z))return;let X=Y6($),J=X[Z]??{},G=J.lastOutcome;delete J.inFlight,J.lastOutcome={code:"ambiguous_local",at:z,...G?{previousOutcome:{code:G.code,at:G.at}}:{}},X[Z]=J}function B6($,Z){let z=J6($),X=S3($?.inFlight);if(G6($)&&!X)return{kind:"corrupt",beforeState:z};if($?.cooldownUntil!==void 0&&$.cooldownUntil>Z)return{kind:"cooldown",beforeState:z,cooldownUntil:$.cooldownUntil};if(X&&Q6(X,Z))return{kind:"claim",beforeState:z,claim:{inFlight:X,selectedCredit:{id:X.creditId}}};if(X)return{kind:"expired_unreconciled",beforeState:z,claim:{inFlight:X,selectedCredit:{id:X.creditId}}};return{kind:"fresh",beforeState:z}}async function T5($,Z){if(!t(Z))return{kind:"fresh",beforeState:void 0};let z=await $.loadAccountsFn(F$($));return B6(z?R$(z,Z):void 0,$.now())}async function b5($,Z){let z;if(await $.mutateAccountsFn((X)=>{let J=$.now(),G=R$(X,Z);if(z=B6(G,J),z.kind==="corrupt")W6(X,Z,J);return X},F$($)),!z)throw Error("corrupt reset state mutation did not run");return z}async function C5($,Z,z){if(!t(Z))return{kind:"fresh",beforeState:void 0};let X;if(await $.mutateAccountsFn((J)=>{let G=$.now(),Q=R$(J,Z),Y=J6(Q),W=S3(Q?.inFlight);if(G6(Q)&&!W)return W6(J,Z,G),X={kind:"corrupt",beforeState:Y},J;if(Q?.cooldownUntil!==void 0&&Q.cooldownUntil>G)return X={kind:"cooldown",beforeState:Y,cooldownUntil:Q.cooldownUntil},J;if(W&&Q6(W,G))return X={kind:"claim",beforeState:Y,claim:{inFlight:W,selectedCredit:{id:W.creditId}}},J;if(W)return X={kind:"expired_unreconciled",beforeState:Y,claim:{inFlight:W,selectedCredit:{id:W.creditId}}},J;let B=A$(z);if(!B)return X={kind:"fresh",beforeState:Y},J;let j={redeemRequestId:$.randomUUID(),creditId:B.id,startedAt:G},V=Y6(J);return V[Z]={...Q,inFlight:j},X={kind:"claim",beforeState:Y,claim:{inFlight:j,selectedCredit:B}},J},F$($)),!X)throw Error("reset claim mutation did not run");return X}async function S5($,Z,z,X){if(!t(Z))return;if(!f3(X.kind))return;await $.mutateAccountsFn((J)=>{let G=R$(J,Z),Q=S3(G?.inFlight);if(!G||!Q||Q.redeemRequestId!==z.redeemRequestId||Q.creditId!==z.creditId)return J;let Y=$.now();if(delete G.inFlight,G.lastOutcome={code:X.kind,at:Y},X.kind==="reset"||X.kind==="already_redeemed")G.cooldownUntil=Y+A5;else delete G.cooldownUntil;return J},F$($))}function Q$($,Z){if(!$||$.usedPercent<100)return!1;if(!$.resetsAt)return!0;let z=Date.parse($.resetsAt);return!Number.isFinite(z)||z>Z}function w3($,Z,z){if(!(Z||Q$($.primary,z)||Q$($.secondary,z)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function r4($,Z){let z=$[Z];if(z===void 0||z===null)return;return typeof z==="string"?z:null}function w5($){if(!I$($))return;let Z=r4($,"granted_at"),z=r4($,"reset_type");if(typeof $.id!=="string"||typeof $.status!=="string"||typeof $.expires_at!=="string"||Number.isNaN(Date.parse($.expires_at))||typeof $.is_supported_by_plan!=="boolean"||Z===null||z===null)return;return{id:$.id,status:$.status,...Z===void 0?{}:{grantedAt:Z},expiresAt:$.expires_at,...z===void 0?{}:{resetType:z},isSupportedByPlan:$.is_supported_by_plan}}async function k3($,Z,z){let X;try{X=await $(_5,{method:"GET",headers:X6(Z,C3,z),signal:AbortSignal.timeout(R5)})}catch{throw new b2("http_error","reset credit list request failed")}if(!X.ok)throw new b2("http_error",`reset credit list request failed: ${X.status}`,X.status);let J;try{J=await X.json()}catch{throw new b2("invalid_response","reset credit list response was not valid JSON",X.status)}if(!I$(J))throw new b2("invalid_response","reset credit list response was not an object",X.status);return{credits:(Array.isArray(J.credits)?J.credits:[]).flatMap((Q)=>{let Y=w5(Q);return Y===void 0?[]:[Y]}),availableCount:typeof J.available_count==="number"&&Number.isFinite(J.available_count)?J.available_count:void 0}}function A$($){return[...$].filter(j6).sort((Z,z)=>Date.parse(Z.expiresAt)-Date.parse(z.expiresAt))[0]}function j6($){return $.status==="available"&&$.isSupportedByPlan&&$.resetType==="codex_rate_limits"}function V6($){return $.filter(j6).length}function f3($){return $==="reset"||$==="already_redeemed"||$==="nothing_to_reset"||$==="no_credit"}async function k5($,Z,z,X,J){let G;try{G=await $(x5,{method:"POST",headers:{...X6(Z,z6,z),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:J,credit_id:X}),signal:AbortSignal.timeout(I5)})}catch(B){return{kind:"ambiguous",raw:B}}let Q;try{Q=await G.text()}catch(B){return G.ok?{kind:"ambiguous",raw:B}:{kind:"http_error",raw:B,status:G.status}}let Y=Q,W=!1;try{Y=JSON.parse(Q),W=!0}catch{}if(!G.ok)return{kind:"http_error",raw:Y,status:G.status};if(!W||!I$(Y)||!f3(Y.code))return{kind:"ambiguous",raw:Y};return{kind:Y.code,raw:Y}}function e4($){if($.kind==="cooldown")throw new o("cooldown_active","reset credit redemption is cooling down",$.cooldownUntil);throw Error(`unexpected reset state decision: ${$.kind}`)}function $6(){throw new o("expired_unreconciled","the previous reset attempt outcome is unknown")}function Z6($,Z){return{target:$,selectedCredit:void 0,beforeState:Z,outcome:{kind:"ambiguous_local",raw:{reason:"corrupt_in_flight"}},retrySafety:"No request was sent because the saved redemption identity was incomplete."}}function f5($){if($.kind==="reset"||$.kind==="already_redeemed")return"The server returned a terminal result; cooldown blocks an immediate new redemption.";if($.kind==="nothing_to_reset"||$.kind==="no_credit")return"The server returned a terminal no-op. No cooldown was set; a new attempt starts fresh and remains gated by fresh preconditions.";return"The outcome is uncertain. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing."}async function H6($,Z){if(!t(Z.accountKey))throw new o("invalid_account_key","the reset account key is reserved");let z=await $.resolveTarget(Z.accountKey);if(z.chatgptAccountId!==Z.expectedChatgptAccountId)throw new o("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let X=z.accountKey==="main"?void 0:z.chatgptAccountId,J=await T5($,Z.accountKey);if(J.kind==="corrupt"){if(J=await b5($,Z.accountKey),J.kind==="corrupt")return Z6(z,J.beforeState)}if(J.kind==="cooldown")e4(J);let G;if(J.kind==="claim")G=J.claim;else if(J.kind==="expired_unreconciled"){if(!Z.retry)$6();G=J.claim}else{if(Z.retry)throw new o("retry_without_inflight","there is no active reset credit redemption to retry");let[W,B]=await Promise.all([$.fetchUsage(z),k3($.fetchImpl,z.accessToken,X)]),j=w3(W,$.hasActiveRateLimitMark(Z.accountKey),$.now());if(!j.ok)throw new o("not_exhausted",j.reason);if(!A$(B.credits))throw new o("no_eligible_credit","no eligible reset credit was returned");let V=await C5($,Z.accountKey,B.credits);if(V.kind==="corrupt")return Z6(z,V.beforeState);if(V.kind==="cooldown")e4(V);if(V.kind==="expired_unreconciled")$6();if(V.kind!=="claim")throw new o("no_eligible_credit","no eligible reset credit was available while claiming");G=V.claim}let Q=await k5($.fetchImpl,z.accessToken,X,G.inFlight.creditId,G.inFlight.redeemRequestId),Y=!1;try{await S5($,Z.accountKey,G.inFlight,Q)}catch{Y=f3(Q.kind)}return{target:z,selectedCredit:G.selectedCredit,beforeState:J.beforeState,outcome:Q,retrySafety:Y?"The server returned a terminal result, but the state write failed. A retry within five minutes reuses the same request and credit identifiers.":f5(Q),...Y?{finalizeStateWriteFailed:!0}:{}}}var bZ="openai-quota",CZ="openai-account",SZ="openai-routing",wZ="openai-killswitch",kZ="openai-dump",fZ="openai-logging",EZ="openai-cachekeep",T$="openai-reset",yZ=["openai-quota","openai-account","openai-routing","openai-killswitch","openai-dump","openai-logging","openai-cachekeep","openai-reset"],F=n("commands");function i($){return{configPath:$.accountStoragePath,statePath:$.accountStatePath}}function q6($){if($==="fallback-first")return"Try usable fallback accounts before the main account.";if($==="sticky-balanced")return"Keep each session on its assigned account while balancing new sessions.";return"Try the main account first. Use fallback accounts only when required."}var E5=900000;function K6($,Z){if(typeof $!=="number"||!Number.isFinite($))return" (age unknown)";let z=Z-$;if(z<E5)return"";let X=Math.floor(z/3600000);if(X>=24)return` (${Math.floor(X/24)}d old)`;if(X>=1)return` (${X}h old)`;return` (${Math.floor(z/60000)}m old)`}function L6($,Z=""){let z=$.resetsAt?` · resets ${$.resetsAt}`:"",X=(Q)=>Math.round(Q).toLocaleString("en-US"),J=$.unit??"unit",G=$.limit===1||J.endsWith("s")?J:`${J}s`;return`${Z}- credits: ${Math.round($.usedPercent)}% used (${X($.used)} / ${X($.limit)} ${G}, ${X($.remaining)} remaining)${z}`}async function y5($){let Z=await $.refreshAllQuota?.(),z=$.quotaManager.getMain(),X=Date.now(),J=["## OpenAI Quota",""];if(z?.quota){let Y=z.quota;J.push("### Main account");for(let W of["primary","secondary"]){let B=Y[W];if(B){let j=Math.round(B.usedPercent),V="█".repeat(Math.max(0,Math.min(Math.round(j/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(j/10),10)));J.push(`- ${W}: ${V} ${j}% used (${Math.round(B.remainingPercent)}% remaining)${K6(B.checkedAt??z.checkedAt,X)}`)}}if(Y.resetCreditsAvailable!==void 0)J.push(`- resets: ${Y.resetCreditsAvailable}`);if(Y.spendControl)J.push(L6(Y.spendControl))}else J.push("No main quota snapshot available. Send a request first.");let Q=[...$.quotaManager.getAllFallbacks().entries()].filter(([,Y])=>Y);if(Q.length>0){J.push(""),J.push("### Fallback accounts");for(let[Y,W]of Q){if(!W?.quota)continue;J.push(`**${Y}**`);for(let B of["primary","secondary"]){let j=W.quota[B];if(j){let V=Math.round(j.usedPercent);J.push(` - ${B}: ${V}% used (${Math.round(j.remainingPercent)}% remaining)${K6(j.checkedAt??W.checkedAt,X)}`)}}if(W.quota.resetCreditsAvailable!==void 0)J.push(` - resets: ${W.quota.resetCreditsAvailable}`);if(W.quota.spendControl)J.push(L6(W.quota.spendControl," "))}}if(Z?.length){let Y=Z.filter((W)=>!W.ok);if(Y.length>0){J.push("");for(let W of Y)J.push(W.permanent?`- ${W.account}: sign-in no longer accepted — remove and add this account again`:`- ${W.account}: fetch failed — Refresh to retry`)}}return{command:"openai-quota",text:J.join(`
|
|
94
|
-
`),knobs:{}}}function d($){return{id:$.id,type:$.type??"oauth",enabled:$.enabled,label:$.label}}async function v5($,Z){let z=$.trim().split(/\s+/).filter(Boolean);F.info("account command parsed",{args:$,tokens:z});let X=await Z.loadAccounts(i(Z))??{version:1,accounts:[]},J=X.accounts??[];if(z[0]==="claustrum"){if(F.info("claustrum mode requested",{hasEnterFn:typeof Z.enterClaustrumMode==="function",accounts:J.length}),!Z.enterClaustrumMode)return F.warn("claustrum refused: transition fn absent from command context"),{command:"openai-account",text:`## Claustrum Unavailable
|
|
95
|
-
|
|
96
|
-
The custody runtime is not ready. Try again after OpenAI auth finishes initializing.`,knobs:{accounts:J.map(d),claustrumMode:S(X)}};F.info("claustrum transition starting",{});let G;try{G=await Z.enterClaustrumMode()}catch(W){throw F.error("claustrum transition threw",{error:W instanceof Error?W.message:String(W)}),W}F.info("claustrum transition finished",{status:G.status,reason:G.reason,outcomes:G.outcomes});let Q=await Z.loadAccounts(i(Z))??{version:1,accounts:[]},Y=Object.entries(G.outcomes).map(([W,B])=>`- \`${W}\`: ${B}`);return{command:"openai-account",text:[`## Claustrum ${G.status}`,"","do not run a login in another OpenCode window during this transition","",...Y.length>0?Y:["- No enabled OAuth accounts."],...G.reason?["",`Reason: ${G.reason}`]:[]].join(`
|
|
97
|
-
`),knobs:{accounts:Q.accounts.map(d),claustrumMode:S(Q)}}}if(z[0]==="local"){if(F.info("local mode requested",{hasLeaveFn:typeof Z.leaveClaustrumMode==="function"}),!Z.leaveClaustrumMode)return F.warn("local refused: transition fn absent from command context"),{command:"openai-account",text:`## Local Mode Unavailable
|
|
98
|
-
|
|
99
|
-
The custody runtime is not ready. Try again after OpenAI auth finishes initializing.`,knobs:{accounts:J.map(d),claustrumMode:S(X)}};await Z.leaveClaustrumMode();let G=await Z.loadAccounts(i(Z))??{version:1,accounts:[]};return{command:"openai-account",text:"## Local Mode\n\nClaustrum mode is now local. Run a fresh `/login openai` for each account, then remove its binding with `ck auth` before it can refresh locally.",knobs:{accounts:G.accounts.map(d),claustrumMode:S(G)}}}if((z[0]==="enable"||z[0]==="disable")&&z[1]){let G=z[1],Q=z[0]==="enable",Y,W=!1,V=await(Z.withFallbackAccountLock??(async(q,K)=>K()))(G,async()=>{let q=await Z.loadAccounts(i(Z)),K=q?.accounts.find((H)=>H.id===G&&H.type==="oauth");if(!K)return q??{version:1,accounts:[]};if(Q&&S(q)==="claustrum"){let H=Z.checkUsableCustodyBinding?await Z.checkUsableCustodyBinding(K):{ready:!1,reason:"unbound-under-claustrum"};if(!H.ready)return Y=H.reason,q;return U2((N)=>{let U=N.accounts.find((P)=>P.id===G&&P.type==="oauth");if(!U)return N;return W=!0,U.accountId=H.accountId,U.enabled=!0,N},i(Z))}return U2((H)=>{let N=H.accounts.find((U)=>U.id===G);if(!N)return H;return W=!0,N.enabled=Q,H},i(Z))})??{version:1,accounts:[]};if(Y)return{command:"openai-account",text:`## Cannot Enable Account
|
|
100
|
-
|
|
101
|
-
\`${G}\` remains disabled: ${Y}. Resolve the custody binding, then try again.`,knobs:{accounts:V.accounts.map(d),claustrumMode:S(V)}};if(!W)return{command:"openai-account",text:`## Account Not Found
|
|
102
|
-
|
|
103
|
-
No account with id \`${G}\` exists.`,knobs:{accounts:V.accounts.map(d),claustrumMode:S(V)}};return{command:"openai-account",text:`## Account ${Q?"Enabled":"Disabled"}
|
|
104
|
-
|
|
105
|
-
\`${G}\` is ${Q?"enabled":"disabled"}.`,knobs:{accounts:V.accounts.map(d),claustrumMode:S(V)}}}if(z.length===0||z.length===1&&z[0]==="list"){let G=["## OpenAI Accounts",""];if(J.length===0)G.push("No accounts configured. Use `/login openai` to add your main account, or `/openai-account add` to add a fallback account.");else{let Q=X.routing?.mode??"main-first";G.push(`Routing: \`${Q}\` (set with \`/openai-routing\`). Modes: main-first, fallback-first, or sticky-balanced. \`/openai-routing reset\` clears this session's pin.`),G.push("");for(let Y of J){let W=Y.type??"oauth";G.push(`- \`${Y.id}\` (${W})`)}}return G.push(""),G.push(`Claustrum mode: \`${S(X)}\`
|
|
106
|
-
|
|
107
|
-
Commands: \`/openai-account claustrum\` | \`/openai-account local\` | \`/openai-account add [label]\` | \`/openai-account enable <id>\` | \`/openai-account disable <id>\` | \`/openai-account remove <id>\``),{command:"openai-account",text:G.join(`
|
|
108
|
-
`),knobs:{accounts:J.map(d),claustrumMode:S(X)}}}if(z[0]==="remove"&&z[1]){let G=z[1],Q=await v4(Z.accountStoragePath),Y=Q?Q.has(G):!1,W=!1,B=await U2((V)=>{let q=V.accounts.findIndex((K)=>K.id===G);if(q===-1)return V;return V.accounts.splice(q,1),W=!0,V},i(Z),{allowDrop:[G]});if(!(W||Y))return{command:"openai-account",text:`## Account Not Found
|
|
109
|
-
|
|
110
|
-
No account with id \`${G}\` exists.`,knobs:{accounts:B.accounts.map(d)}};return F.info("account removed",{id:G}),Z.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Account Removed
|
|
111
|
-
|
|
112
|
-
Removed account \`${G}\`.`,knobs:{accounts:B.accounts.map(d)}}}if(z[0]==="order"&&z.length>=3){let G=!1,Q=await U2((Y)=>{let W=Y.accounts.findIndex((V)=>V.id===z[1]),B=Y.accounts.findIndex((V)=>V.id===z[2]);if(W===-1||B===-1)return Y;G=!0;let j=Y.accounts[W];return Y.accounts[W]=Y.accounts[B],Y.accounts[B]=j,Y},i(Z));if(!G)return{command:"openai-account",text:`## Invalid Order
|
|
113
|
-
|
|
114
|
-
Both account IDs must exist.`,knobs:{accounts:Q.accounts.map(d)}};return F.info("accounts reordered",{a:z[1],b:z[2]}),Z.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Accounts Reordered
|
|
115
|
-
|
|
116
|
-
Swapped positions of \`${z[1]}\` and \`${z[2]}\`.`,knobs:{accounts:Q.accounts.map(d)}}}if(z[0]==="add"){if(X.claustrum?.mode==="claustrum")return{command:"openai-account",text:"## Add Failed\n\nThat account cannot be added while Claustrum mode is active. Run `/openai-account local` first.",knobs:{}};let G=z.includes("--headless"),Q=z.filter((K)=>K!=="add"&&K!=="--headless"),Y=Q.length>0?Q.join(" "):void 0,{url:W,instructions:B,completion:j}=await(Z.beginAccountLogin??P4)({label:Y,headless:G,version:Z.packageVersion}),V=Z.notify,q=Z.sessionId;if(j.then(async(K)=>{let H;if(await(Z.withFallbackAccountLock??(async(U,P)=>P()))(K.id,async()=>{let U=await Z.loadAccounts(i(Z));if(S(U??{})==="claustrum"){H="claustrum mode";return}await U2((P)=>{if(K.accountId&&P.mainAccountId&&K.accountId===P.mainAccountId)return H="main identity",P;return D4(P.accounts,K),P},i(Z))}),H){let U=H==="claustrum mode"?"That account cannot be added while Claustrum mode is active. Run `/openai-account local` first.":"That account is already your main account — not added as a fallback.";F.warn(`account add rejected (${H})`,{id:K.id,sessionId:q}),V?.({command:"openai-account",text:`## Add Failed
|
|
117
|
-
|
|
118
|
-
${U}`,knobs:{}});return}F.info("account added",{id:K.id,label:K.label}),Z.refreshSidebar?.().catch(()=>{}),V?.({command:"openai-account",text:`## Account Added
|
|
119
|
-
|
|
120
|
-
Added account \`${K.id}\`${K.label?` ("${K.label}")`:""}.
|
|
121
|
-
|
|
122
|
-
Run \`/openai-account\` to confirm.`,knobs:{}})}).catch((K)=>{let H=K instanceof Error?K.message:String(K??"unknown error");F.warn("account add failed",{error:H,sessionId:q}),V?.({command:"openai-account",text:`## Add Failed
|
|
123
|
-
|
|
124
|
-
Account add failed: ${H}`,knobs:{}})}),G){let K=B.match(/Enter code: (.+)/)?.[1]??B;return{command:"openai-account",text:`## Device Code
|
|
125
|
-
|
|
126
|
-
1. Open this verification URL:
|
|
127
|
-
|
|
128
|
-
${W}
|
|
129
|
-
|
|
130
|
-
2. Enter the code: **${K}**
|
|
131
|
-
|
|
132
|
-
${B}
|
|
133
|
-
|
|
134
|
-
The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{verificationUrl:W,userCode:K,instructions:B}}}return{command:"openai-account",text:`## Add OpenAI Account
|
|
135
|
-
|
|
136
|
-
Open this URL and complete sign-in:
|
|
137
|
-
|
|
138
|
-
${W}
|
|
139
|
-
|
|
140
|
-
${B}
|
|
141
|
-
|
|
142
|
-
The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{url:W,instructions:B}}}return{command:"openai-account",text:"## Account Commands\n\n- `/openai-account claustrum` — enter Claustrum mode\n- `/openai-account local` — leave Claustrum mode\n- `/openai-account add [label]` — add a new account\n- `/openai-account enable <id>` — enable a fallback\n- `/openai-account disable <id>` — disable a fallback\n- `/openai-account remove <id>` — remove\n- `/openai-account order <a> <b>` — swap fallback positions\n\nRouting modes are `main-first`, `fallback-first`, and `sticky-balanced`. `/openai-routing reset` clears the current session pin.",knobs:{accounts:J.map(d),claustrumMode:S(X)}}}async function h5($,Z){let z=$.trim().toLowerCase().split(/\s+/).filter(Boolean),J=(await Z.loadAccounts(i(Z))??{version:1,accounts:[]}).routing?.mode??"main-first";if(z.length===1&&z[0]==="reset"){if(!Z.sessionId)return{command:"openai-routing",text:`## OpenAI Routing Reset
|
|
143
|
-
|
|
144
|
-
No current session is available, so no pin was changed.`,knobs:{mode:J}};if(!Z.clearStickyRouting)return{command:"openai-routing",text:`## OpenAI Routing Reset
|
|
145
|
-
|
|
146
|
-
This runtime cannot clear the current session pin.`,knobs:{mode:J}};return await Z.clearStickyRouting(Z.sessionId),F.info("routing session pin cleared"),{command:"openai-routing",text:`## OpenAI Routing Reset
|
|
147
|
-
|
|
148
|
-
This session's pin was cleared. The next request may choose the same account if it remains the best selection.`,knobs:{mode:J}}}if(z.length===1&&(z[0]==="main-first"||z[0]==="fallback-first"||z[0]==="sticky-balanced")){let Y=z[0];return await U2((W)=>{return W.routing={...W.routing??{},mode:Y},W},i(Z)),F.info("routing mode changed",{mode:Y}),{command:"openai-routing",text:`## OpenAI Routing Updated
|
|
149
|
-
|
|
150
|
-
Mode: \`${Y}\`
|
|
151
|
-
- ${q6(Y)}
|
|
152
|
-
|
|
153
|
-
Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:Y}}}let G=J==="sticky-balanced"&&Z.sessionId?await Z.getStickyRouting?.(Z.sessionId):void 0,Q=J==="sticky-balanced"?G?`
|
|
154
|
-
- Session pin: \`${G}\`. Use \`/openai-routing reset\` to clear it.`:`
|
|
155
|
-
- Session pin: none yet. A request will choose one when a usable account is available.`:"";return{command:"openai-routing",text:`## OpenAI Routing
|
|
156
|
-
|
|
157
|
-
- Mode: \`${J}\`
|
|
158
|
-
- ${q6(J)}${Q}
|
|
159
|
-
|
|
160
|
-
Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:J}}}function D6($){let Z=[$.primary?.usedPercent,$.secondary?.usedPercent].filter((z)=>z!==void 0);return Z.length>0?Math.max(...Z):void 0}function m5($,Z){let z=[$.primary,$.secondary].filter((J)=>J!==void 0),X=z.filter((J)=>Q$(J,Z));return(X.length>0?X:z).sort((J,G)=>G.usedPercent-J.usedPercent)[0]?.resetsAt}function g5($,Z){if(!$)return!1;let z=[$.primary,$.secondary].filter((X)=>X!==void 0);if(z.length===0)return!1;return z.every((X)=>!Q$(X,Z))}function E3($){if(!$)return;try{return decodeURIComponent($)}catch{return}}async function N6($,Z){let z;try{z=await Z.resolveResetTarget($);let X=z.accountKey==="main"?void 0:z.chatgptAccountId,[J,G]=await Promise.all([V3({accessToken:z.accessToken,fetchImpl:Z.fetchImpl,now:Z.now,accountId:z.chatgptAccountId}),k3(Z.fetchImpl,z.accessToken,X)]),Q=A$(G.credits),Y=V6(G.credits),W=G.availableCount??J.resetCreditsAvailable??(Y>0?Y:void 0),B=J.resetCreditsApplicable,j=w3(J,Z.quotaManager.isRateLimited($),Z.now()),V;if(!z.chatgptAccountId)V="stable ChatGPT account identity unavailable";else if(!j.ok)V=j.reason;else if(!Q)V="no eligible credit";return{accountKey:z.accountKey,label:z.label,chatgptAccountId:z.chatgptAccountId,usedPercent:D6(J),resetTime:m5(J,Z.now()),availableCount:W,applicableAvailableCount:B,eligible:V===void 0,reason:V,selectedCreditId:Q?.id,selectedCreditExpiresAt:Q?.expiresAt}}catch(X){if(X?.status===401)await z?.onAuthFailure?.(401);return F.warn("reset preview row failed",{accountKey:$,error:X?.message??String(X)}),{accountKey:$,label:$==="main"?"Main account":$,eligible:!1,reason:X?.message??String(X)}}}function p5($){let Z=["## Reset credits","","Select an account to fetch a fresh confirmation preview:",""];for(let z of $){let X=z.usedPercent===void 0?"quota unavailable":`${z.usedPercent}% used`,J=z.availableCount===void 0?"credits unavailable":`${z.applicableAvailableCount===void 0?"?":z.applicableAvailableCount}/${z.availableCount} applicable/available`,G=z.eligible?`eligible · credit ${z.selectedCreditId} expires ${z.selectedCreditExpiresAt}`:z.reason;Z.push(`- **${z.label}** (\`${z.accountKey}\`) — ${X}; ${J}; ${G}`)}return Z.push(""),Z.push("Command: `/openai-reset select <encodedAccountKey>`"),Z.join(`
|
|
161
|
-
`)}function U6($){let Z=["## Confirm reset credit","",`Account: **${$.label}** (\`${$.accountKey}\`)`,`Current quota: **${$.usedPercent??"unknown"}% used**`,`Credit: **Spend 1 of ${$.availableCount??"unknown"}**`,`Credit expires: **${$.selectedCreditExpiresAt??"unavailable"}**`,`Quota resets: **${$.resetTime??"unavailable"}**`,""];if(($.availableCount??0)>0&&$.applicableAvailableCount===0)Z.push("The server does not currently count this credit as applicable; redemption may return a no-op, and a no-op does not spend the credit."),Z.push("");if($.eligible&&$.chatgptAccountId)Z.push(`Confirm: \`/openai-reset confirm ${encodeURIComponent($.accountKey)} ${encodeURIComponent($.chatgptAccountId)}\``);else Z.push(`Cannot reset: **${$.reason??"not eligible"}**`);return Z.join(`
|
|
162
|
-
`)}function c($,Z,z,X={}){return{command:T$,text:z,knobs:{stage:"result",accountKey:$,code:Z,...X}}}function u5($,Z,z){if(Z instanceof o){let J={identity_mismatch:"The account identity changed before redemption. Reopen the reset account list.",invalid_account_key:"The selected account key is reserved. Reopen the reset account list.",cooldown_active:"This account just reset — re-checking quota. Wait for the cooldown before another redemption.",expired_unreconciled:"The previous attempt outcome is unknown — retry replays the same identifiers, or wait until quota reflects the earlier attempt.",retry_without_inflight:"There is no active reset redemption to retry. Reopen the account list.",not_exhausted:"No credit was spent: the fresh account state is not exhausted.",no_eligible_credit:"No credit was spent: no eligible credit was returned."};return c($,Z.kind,`## Reset credit
|
|
163
|
-
|
|
164
|
-
${J[Z.kind]}
|
|
165
|
-
|
|
166
|
-
Code: \`${Z.kind}\``,{cooldownUntil:Z.cooldownUntil,...Z.kind==="expired_unreconciled"?{chatgptAccountId:z,retryGuidance:"Retry replays the same request and credit identifiers from the previous attempt."}:{}})}let X=Z?.code;if(X==="unknown_account"||X==="disabled_account"||X==="non_oauth_account"||X==="token_unavailable")return c($,X,`## Reset credit
|
|
167
|
-
|
|
168
|
-
${{unknown_account:"Account unavailable: the selected account no longer exists. Reopen the reset account list.",disabled_account:"Account unavailable: the selected account is disabled. Reopen the reset account list.",non_oauth_account:"Account unavailable: the selected account is not authenticated with OAuth. Reopen the reset account list.",token_unavailable:"Authentication problem: the selected account token is unavailable. Reauthenticate the account before retrying."}[X]}
|
|
169
|
-
|
|
170
|
-
Code: \`${X}\``);if(Z instanceof b2)return c($,Z.kind,`## Reset credit
|
|
171
|
-
|
|
172
|
-
No redemption was attempted: reset credit availability could not be loaded.
|
|
173
|
-
|
|
174
|
-
Code: \`${Z.kind}\``);return F.warn("reset command failed before a known result",{accountKey:$,error:Z?.message??String(Z)}),c($,"error",`## Reset credit
|
|
175
|
-
|
|
176
|
-
The reset request failed before a known result: internal command failure — see plugin log.`)}async function P6($,Z,z){let{accountKey:X}=$.target,J=$.outcome.kind;if($.finalizeStateWriteFailed)return c(X,J,`## Reset credit result
|
|
177
|
-
|
|
178
|
-
Account: **${$.target.label}** (\`${X}\`)
|
|
179
|
-
|
|
180
|
-
The server outcome recorded as \`${J}\`, but the state write failed. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.`,{stateWriteFailed:!0,retryGuidance:$.retrySafety,chatgptAccountId:z});if(J==="reset"||J==="already_redeemed"){let Q={account:X,ok:!1,error:"targeted quota refresh did not complete"};try{Q=await Z.refreshResetTargetQuota(X)}catch(K){Q.error=K?.message??String(K)}let Y=!Q.ok&&Q.error!==void 0;if(Y)F.warn("reset quota re-check failed",{accountKey:X,error:Q.error});let W=X==="main"?Z.quotaManager.getMain():Z.quotaManager.getFallback(X),B=Q.ok&&g5(W?.quota,Z.now()),j=W?.quota.resetCreditsApplicable,V=B?"Post-verification: **window fresh**.":`Post-verification: **window not yet refreshed** (server code \`${J}\`).`,q=Y?`
|
|
181
|
-
|
|
182
|
-
quota re-check failed — see log.`:"";return c(X,J,`## Reset credit result
|
|
183
|
-
|
|
184
|
-
Account: **${$.target.label}** (\`${X}\`)
|
|
185
|
-
|
|
186
|
-
Code: \`${J}\`
|
|
187
|
-
|
|
188
|
-
${V}${q}${j===void 0?"":`
|
|
189
|
-
|
|
190
|
-
Remaining applicable credits: **${j}**`}`,{verifiedFresh:B,afterUsedPercent:D6(W?.quota??{}),remainingCredits:j})}if(J==="ambiguous_local")return c(X,J,`## Reset credit result
|
|
191
|
-
|
|
192
|
-
Account: **${$.target.label}** (\`${X}\`)
|
|
193
|
-
|
|
194
|
-
Code: \`${J}\`
|
|
195
|
-
|
|
196
|
-
${$.retrySafety}`,{retryGuidance:$.retrySafety});if(J==="ambiguous"||J==="http_error"){let Q=z?`/openai-reset retry ${encodeURIComponent(X)} ${encodeURIComponent(z)}`:"/openai-reset";return c(X,J,`## Reset credit result
|
|
197
|
-
|
|
198
|
-
Account: **${$.target.label}** (\`${X}\`)
|
|
199
|
-
|
|
200
|
-
The redemption outcome is unknown (\`${J}\`).
|
|
201
|
-
|
|
202
|
-
Retry with \`${Q}\`. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.`,{retryGuidance:$.retrySafety,chatgptAccountId:z})}let G={nothing_to_reset:"The server found no exhausted quota window to reset. No reset was confirmed. A new attempt starts fresh and must pass the current preconditions.",no_credit:"The server found no usable reset credit. No reset was confirmed. A new attempt starts fresh and must pass the current preconditions."};return c(X,J,`## Reset credit result
|
|
203
|
-
|
|
204
|
-
Account: **${$.target.label}** (\`${X}\`)
|
|
205
|
-
|
|
206
|
-
Code: \`${J}\`
|
|
207
|
-
|
|
208
|
-
${G[J]??"The server returned a no-op result. No reset was confirmed."}`)}async function l5($,Z){let z=[Z.resolveResetTarget?void 0:"resolveResetTarget",Z.fetchImpl?void 0:"fetchImpl",Z.now?void 0:"now",Z.randomUUID?void 0:"randomUUID",Z.refreshResetTargetQuota?void 0:"refreshResetTargetQuota"].filter((Q)=>Q!==void 0);if(z.length>0)return F.warn("reset command dependencies unwired",{missingDeps:z}),{command:T$,text:`## Reset credit
|
|
209
|
-
|
|
210
|
-
Unavailable: reset command runtime dependencies are not wired.`,knobs:{}};let X=Z,J=$.trim().split(/\s+/).filter(Boolean),G=J[0];if(!G||G==="refresh"){let Y=["main",...((await Z.loadAccounts(i(Z)))?.accounts??[]).filter((B)=>B.enabled!==!1&&B.type==="oauth").map((B)=>B.id)];F.debug("reset accounts stage requested",{accountKeys:Y});let W=await Promise.all(Y.map((B)=>N6(B,X)));return F.debug("reset accounts stage built",{rows:W.map((B)=>({accountKey:B.accountKey,eligible:B.eligible,reason:B.reason,usedPercent:B.usedPercent,availableCount:B.availableCount,applicableAvailableCount:B.applicableAvailableCount}))}),{command:T$,text:p5(W),knobs:{stage:"accounts",accounts:W}}}if(G==="select"){let Q=E3(J[1]);if(!Q||!t(Q)||J.length!==2)return c("","invalid_command","Usage: `/openai-reset select <encodedAccountKey>`");let Y=await N6(Q,X);if(!Y.eligible)return c(Q,"not_eligible",U6(Y));return{command:T$,text:U6(Y),knobs:{stage:"confirm",preview:Y}}}if(G==="confirm"||G==="retry"){let Q=E3(J[1]),Y=E3(J[2]);if(!Q||!t(Q)||!Y||J.length!==3)return c(Q??"","invalid_command",`Usage: \`/openai-reset ${G} <encodedAccountKey> <encodedChatgptAccountId>\``);F.info("reset redemption decision",{accountKey:Q,action:G}),F.debug("reset redemption identity binding",{accountKey:Q,expectedChatgptAccountId:Y});try{let W=await H6({configPath:Z.accountStoragePath,statePath:Z.accountStatePath,mutateAccountsFn:U2,loadAccountsFn:Z.loadAccounts,now:X.now,randomUUID:X.randomUUID,fetchImpl:X.fetchImpl,resolveTarget:X.resolveResetTarget,fetchUsage:(B)=>V3({accessToken:B.accessToken,fetchImpl:X.fetchImpl,now:X.now,accountId:B.chatgptAccountId}),hasActiveRateLimitMark:(B)=>Z.quotaManager.isRateLimited(B)},{accountKey:Q,expectedChatgptAccountId:Y,retry:G==="retry"});return F.info("reset redemption outcome",{accountKey:Q,code:W.outcome.kind}),P6(W,X,Y)}catch(W){let B=u5(Q,W,Y);return F.info("reset redemption outcome",{accountKey:Q,code:B.knobs.code}),B}}return c("","invalid_command","Usage: `/openai-reset` | `/openai-reset select <encodedAccountKey>` | `/openai-reset confirm <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset retry <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset refresh`")}var d5=new Set(["access","refresh","apikey","authheader","password","secret"]);function i5($){let Z=$.toLowerCase().replace(/[-_]/g,"");if(d5.has(Z))return!0;return Z.endsWith("token")}function y3($,Z,z){if(Array.isArray($))return $.map((J,G)=>y3(J,`${Z}[${G}]`,z));if(!o4($))return $;let X={};for(let[J,G]of Object.entries($)){if(i5(J)){z.push(`${Z}.${J}`);continue}X[J]=y3(G,`${Z}.${J}`,z)}return X}async function vZ($,Z,z,X={}){let J=await c5($,Z,z,X),G=[],Q=y3(J.knobs,"knobs",G);if(G.length>0)return F.warn("credential-shaped knob stripped before RPC",{command:$,fields:G}),{...J,knobs:Q};return J}async function c5($,Z,z,X){switch($){case"openai-quota":return y5(z);case"openai-account":return v5(Z,z);case"openai-routing":return h5(Z,z);case"openai-reset":return l5(Z,z);default:{let J=X[$];if(!J)throw Error(`unhandled command: ${$}`);return J(Z,z)}}}var v3=n("quota"),O6="custody-deps-incomplete";function M6($){return $?.status===401}async function lZ($,Z={}){let z=$.whamFn;if(!z)throw Error("whamFn is required for refreshAllQuota");let X=[],J=$.logger??v3,G=new Set,Q=(H)=>{X.push(H);let N={pid:process.pid,accountId:H.account,status:H.ok?"ok":"error",...H.error?{error:H.error}:{}};if(H.ok)J.debug("quota refresh succeeded",N);else J.warn("quota refresh failed",N)},Y=$.skipFresherThanMs,W=!1,B;if(Y!==void 0)try{B=await $.readSidebarState()}catch{}let j=new Map(B?.fallbacks.map((H)=>[H.id,H])??[]),V=(...H)=>Y!==void 0&&H.some((N)=>typeof N==="number"&&Number.isFinite(N)&&N<=$.now()&&$.now()-N<Y),q=await $.loadAccounts($.paths).catch(()=>{return}),K=q?.mainAccountId??$.storageMainAccountId;if(!Z.accountKey||Z.accountKey==="main")try{let H=await $.getAuth();if(H.type==="oauth"){let N=B&&K!==void 0&&B.main.mainAccountId===K?B.main.quota:void 0;if(V($.quotaManager.peekMainForPolicy(K)?.checkedAt,N?.primary?.checkedAt,N?.secondary?.checkedAt,N?.checkedAt))Q({account:"main",ok:!0});else{if(!H.access||(H.expires??0)<$.now()){let P=$.resolveMainAccess?await $.resolveMainAccess(q??{version:1,accounts:[]}):G$;if(P===y)Q({account:"main",ok:!1,error:"custody refused"}),H={...H,access:void 0};else if(P!==G$)H={...H,access:P.token};else{let M=await $.refreshMainWithLease();H={...H,access:M.access,expires:M.expires}}}if(H.access)if($.respectBackoff&&$.quotaManager.isBackedOff())Q({account:"main",ok:!0});else{let P=await z({accessToken:H.access,fetchImpl:$.fetchImpl,now:$.now,accountId:K,accountKey:"main"});$.quotaManager.setMain(H.access,{quota:P,refreshAfter:$.now()+300000,checkedAt:$.now()},K,!0),W=!0,Q({account:"main",ok:!0})}else if(!X.some((P)=>P.account==="main"))Q({account:"main",ok:!1,error:"no access token"})}}else Q({account:"main",ok:!1,error:"auth type is not oauth"})}catch(H){Q({account:"main",ok:!1,error:W2(H)})}if(q)for(let H of q.accounts){if(Z.accountKey&&(Z.accountKey==="main"||H.id!==Z.accountKey))continue;if(H.enabled===!1||!$.isOAuthAccountFn(H)){if(Z.accountKey)Q({account:H.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let N=j.get(H.id),U=H.accountId,P=N&&U!==void 0&&N.accountId===U?N.quota:void 0;if(V($.quotaManager.peekFallbackForPolicy(H.id,U)?.checkedAt,P?.primary?.checkedAt,P?.secondary?.checkedAt,P?.checkedAt)){Q({account:H.id,ok:!0});continue}if($.respectBackoff&&$.quotaManager.isFallbackBackedOff(H.id,H.access)){Q({account:H.id,ok:!0});continue}let M=H.lastRefreshError;if(J2(M,H.refresh,$.now())){Q({account:H.id,ok:!1,error:f2(M,$.now()),permanent:!0});continue}if($.isFallbackRefreshInert&&await $.isFallbackRefreshInert(H,q)){if(!$.resolveFallbackAccess){if(!G.has("resolver"))J.warn("custody deps incomplete: resolver absent",{pid:process.pid,accountId:H.id}),G.add("resolver");Q({account:H.id,ok:!1,error:O6});continue}let b;try{b=await $.resolveFallbackAccess(H,q)}catch(R){Q({account:H.id,ok:!1,error:W2(R)});continue}if(b===y||b===G$){Q({account:H.id,ok:!1,error:"custody: no vault credential"});continue}if(b.provenance!=="local"&&!$.reportCustodyAuthFailure){if(!G.has("reporter"))J.warn("custody deps incomplete: reporter absent; vault probe refused",{pid:process.pid,accountId:H.id}),G.add("reporter");Q({account:H.id,ok:!1,error:O6});continue}try{let R=await z({accessToken:b.token,fetchImpl:$.fetchImpl,now:$.now,accountId:H.accountId,accountKey:H.id});$.quotaManager.setFallback(H.id,{quota:R,refreshAfter:$.now()+300000,checkedAt:$.now()},b.token,!0,H.accountId),W=!0,Q({account:H.id,ok:!0})}catch(R){if(!M6(R))throw R;if(b.provenance!=="local")try{await $.reportCustodyAuthFailure({handle:b.provenance.handle,providerStatus:401,recordVersion:b.provenance.recordVersion})}catch(s$){J.warn("custody auth-failure report failed",{accountId:H.id,error:W2(s$)})}Q({account:H.id,ok:!1,error:W2(R)})}continue}let O;try{O=await $.fallbackManager.refreshAccount(H,q)}catch(b){v3.warn("fallback token refresh failed during quota poll",{pid:process.pid,accountId:H.id,error:W2(b)}),O=H}if(!O.access||(O.expires??0)<$.now()){Q({account:H.id,ok:!1,error:"no usable access token"});continue}let P2;try{P2=await z({accessToken:O.access,fetchImpl:$.fetchImpl,now:$.now,accountId:O.accountId,accountKey:H.id})}catch(b){if(!M6(b))throw b;if(v3.warn("quota endpoint rejected the token; forcing a refresh",{pid:process.pid,accountId:H.id}),O=await $.fallbackManager.refreshAccount(H,q,{force:!0}),!O.access){Q({account:H.id,ok:!1,error:"no usable access token after forced refresh"});continue}P2=await z({accessToken:O.access,fetchImpl:$.fetchImpl,now:$.now,accountId:O.accountId,accountKey:H.id})}$.quotaManager.setFallback(H.id,{quota:P2,refreshAfter:$.now()+300000,checkedAt:$.now()},O.access,!0,O.accountId),W=!0,Q({account:H.id,ok:!0})}catch(N){Q({account:H.id,ok:!1,error:W2(N)})}}if(Z.accountKey&&Z.accountKey!=="main"&&!X.some((H)=>H.account===Z.accountKey))X.push({account:Z.accountKey,ok:!1,error:"account not found"});if(Y===void 0||W){let H=await $.loadAccounts($.paths);await $.writeSidebarState($.quotaManager,H)}return X}import{readdirSync as S1,statSync as w1}from"node:fs";import{readFile as k1}from"node:fs/promises";import{tmpdir as f1,userInfo as E1}from"node:os";import{join as V$}from"node:path";import{debuglog as J1}from"node:util";import{createHmac as o5,randomBytes as r5,timingSafeEqual as e5}from"node:crypto";import t5 from"node:net";var u=2,b$=21,C$=5,h3=67108864,L;(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"})(L||(L={}));var _6=L.Goodbye;function x6($){return $===L.Cancel||$===L.Ping||$===L.Pong||$===L.Goodbye}var k;(function($){$[$.Passive=0]="Passive",$[$.Interactive=1]="Interactive",$[$.Background=2]="Background"})(k||(k={}));var v;(function($){$[$.Normal=0]="Normal",$[$.Expedite=1]="Expedite",$[$.Sheddable=2]="Sheddable"})(v||(v={}));var s5=1,F6=6,m3=1,n5=8,I6=48,g3=4,R6=192;function l($,Z,z,X=v.Normal){let J=0;if($)J|=s5;if(J|=Z<<m3,z)J|=n5;return J|=X<<g3,J}function A6($){let Z=new Uint8Array(21),z=new DataView(Z.buffer);return z.setUint32(0,$.len,!0),Z[4]=$.ver,Z[5]=$.ty,Z[6]=$.flags,z.setUint16(7,$.channel,!0),z.setUint32(9,$.epoch,!0),z.setBigUint64(13,$.corr,!0),Z}class I extends Error{code;constructor($,Z){super($);this.code=Z,this.name="DecodeError"}}function a5($){let Z=$.len>>>0,z=$.ver>>>0&255,X=$.ty>>>0&255,J=$.flags>>>0&255,G=$.channel>>>0&65535,Q=$.epoch>>>0;if(BigInt.asUintN(64,$.corr),z!==2)throw new I(`unsupported envelope version ${z}`,"unsupported_version");if(X>_6)throw new I(`unknown frame type byte ${X}`,"unknown_frame_type");let Y=X;if((J&R6)!==0)throw new I(`reserved flag bits set in flags 0b${J.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((J&F6)>>m3===3)throw new I(`reserved priority bits set in flags 0b${J.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let W=(J&I6)>>g3;if(W===3)throw new I(`reserved admission class set in flags 0b${J.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(W===v.Sheddable&&Y!==L.Push&&Y!==L.StreamData)throw new I(`SHEDDABLE admission class is illegal on ${L[Y]} in flags 0b${J.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");if(G===0&&Q!==0)throw new I(`control channel carried nonzero epoch ${Q}`,"nonzero_epoch_on_control_channel");if(x6(Y)&&Z!==0)throw new I(`pure-header frame ${L[Y]} declared non-zero body length ${Z}`,"pure_header_frame_with_body")}function p3($){if($.length<5)throw new I(`header shorter than frozen prefix: have ${$.length} bytes`,"too_short_for_prefix");let Z=$[4];if(Z!==2)throw new I(`unsupported envelope version ${Z}`,"unsupported_version");if($.length<21)throw new I(`header too short for version: have ${$.length} bytes, need 21`,"too_short_for_header");let z=new DataView($.buffer,$.byteOffset,$.byteLength),X=z.getUint32(0,!0),J=$[5];if(J>_6)throw new I(`unknown frame type byte ${J}`,"unknown_frame_type");let G=J,Q=$[6];if((Q&R6)!==0)throw new I(`reserved flag bits set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((Q&F6)>>m3===3)throw new I(`reserved priority bits set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let Y=(Q&I6)>>g3;if(Y===3)throw new I(`reserved admission class set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(Y===v.Sheddable&&G!==L.Push&&G!==L.StreamData)throw new I(`SHEDDABLE admission class is illegal on ${L[G]} in flags 0b${Q.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");let W=z.getUint16(7,!0),B=z.getUint32(9,!0);if(W===0&&B!==0)throw new I(`control channel carried nonzero epoch ${B}`,"nonzero_epoch_on_control_channel");if(x6(G)&&X!==0)throw new I(`pure-header frame ${L[G]} declared non-zero body length ${X}`,"pure_header_frame_with_body");return{len:X,ver:Z,ty:G,flags:Q,channel:W,epoch:B,corr:z.getBigUint64(13,!0)}}function m($,Z,z,X,J,G){return e(2,$,Z,z,X,J,G)}function e($,Z,z,X,J,G,Q){if(Q.length>67108864)throw new I(`frame body ${Q.length} exceeds max 67108864`,"frame_body_too_large");let Y={len:Q.length,ver:$,ty:Z,flags:z,channel:X,epoch:J,corr:G};return a5(Y),{header:Y,body:Q}}function $2($){if($.header.len!==$.body.length)throw new I(`frame header length ${$.header.len} does not match body length ${$.body.length}`,"frame_length_mismatch");let Z=A6($.header),z=new Uint8Array(Z.length+$.body.length);return z.set(Z,0),z.set($.body,Z.length),z}class V2 extends Error{}class r extends Error{}class Z2 extends Error{cause;constructor($,Z){super($);this.cause=Z}}class D2 extends Error{cause;constructor($,Z){super($);this.cause=Z}}function T6($){return Buffer.from($.buffer,$.byteOffset,$.byteLength)}var b6=Symbol("subc.socket.writeBorrowed"),C6=Symbol("subc.socket.writeTrackedBorrowed");function z2($,Z,z){let X=$[b6];return X?X.call($,Z,z):$.write(Z,z)}function u3($,Z,z){let X=$[C6];return X?X.call($,Z,z):$.writeTracked(Z,z)}class C2{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 Z=(z)=>{if(!this.closedErr)this.closedErr=z;this.tryServe()};$.on("error",(z)=>Z(z instanceof Error?z:Error(String(z)))),$.on("end",()=>Z(new V2("subc closed the connection"))),$.on("close",()=>Z(new V2("subc connection closed")))}localPort(){return this.sock.localPort??null}static connect($,Z,z){return new Promise((X,J)=>{let G=t5.connect({host:$,port:Z});G.setNoDelay(!0);let Q=setTimeout(()=>{G.destroy(),J(new r(`timed out connecting to ${$}:${Z}`))},Math.max(0,z-Date.now()));G.once("connect",()=>{clearTimeout(Q),X(new C2(G))}),G.once("error",(Y)=>{clearTimeout(Q),J(Y)})})}async readFrame($,Z,z){let X=await this.readExact(C$,$),J=X[4];if(J!==u)throw new I(`unsupported envelope version ${J}`,"unsupported_version");let G=await this.readExact(b$-C$,$),Q=new Uint8Array(b$);Q.set(X),Q.set(G,C$);let Y=p3(Q);if(Y.len>h3)throw new I(`frame body ${Y.len} exceeds max ${h3}`,"frame_body_too_large");z?.();let W=typeof Z==="number"?Z:Date.now()+Z.afterHeaderMs,B=Y.len===0?new Uint8Array(0):await this.readExact(Y.len,W);return{header:Y,body:B}}readExact($,Z){if(this.waiter)return Promise.reject(Error("concurrent readExact is not supported"));if($===0)return Promise.resolve(new Uint8Array(0));return new Promise((z,X)=>{let J=null;if(Number.isFinite(Z)){let G=Z-Date.now();if(G<=0){X(new r(`timed out waiting for ${$} bytes`));return}J=setTimeout(()=>{this.waiter=null,X(new r(`timed out waiting for ${$} bytes`))},G)}this.waiter={need:$,resolve:z,reject:X,timer:J},this.tryServe()})}async write($,Z){await this.writeBuffer(Buffer.from($),Z)}writeTracked($,Z){return this.writeTrackedBuffer(Buffer.from($),Z)}async[b6]($,Z){await this.writeBuffer(T6($),Z)}[C6]($,Z){return this.writeTrackedBuffer(T6($),Z)}async writeBuffer($,Z){try{await this.writeTrackedBuffer($,Z).completed}catch(z){if(z instanceof Z2||z instanceof D2)throw z.cause??z;throw z}}writeTrackedBuffer($,Z){if(this.closedErr)return{queued:!1,completed:Promise.reject(new Z2("subc socket was closed before bytes could be queued",this.closedErr))};let z=!1,X=!1,J=null,G=new Promise((Q,Y)=>{let W=(j)=>{if(X)return;if(X=!0,J)clearTimeout(J);j()},B=Z-Date.now();if(B<=0){W(()=>Y(new Z2("timed out before bytes could be queued to subc",new r("timed out writing to subc"))));return}J=setTimeout(()=>{let j=new r("timed out writing to subc");W(()=>Y(z?new D2("timed out after bytes were handed to the subc socket",j):new Z2("timed out before bytes could be queued to subc",j)))},B);try{this.sock.write($,(j)=>{W(()=>{if(j)Y(new D2("subc socket reported a write error after bytes were handed to the socket",j instanceof Error?j:Error(String(j))));else Q()})}),z=!0}catch(j){W(()=>Y(new Z2("subc socket write threw before bytes could be queued",j instanceof Error?j:Error(String(j)))))}});return{queued:z,completed:G}}close(){this.sock.destroy()}tryServe(){let $=this.waiter;if(!$)return;if(this.buffered>=$.need){let Z=this.take($.need);if(this.waiter=null,$.timer)clearTimeout($.timer);$.resolve(Z);return}if(this.closedErr){if(this.waiter=null,$.timer)clearTimeout($.timer);$.reject(this.closedErr)}}take($){let Z=Buffer.allocUnsafe($),z=0;while(z<$){let X=this.chunks[0],J=$-z;if(X.length<=J)X.copy(Z,z),z+=X.length,this.chunks.shift();else X.copy(Z,z,0,J),this.chunks[0]=X.subarray(J),z+=J}return this.buffered-=$,Z}}var k6=32;var S$=4096,f6="subc-server-v1",E6="subc-client-v1",$1="client";class g extends Error{}function d3($,Z,z,X,J){let G=o5("sha256",Buffer.from($));return G.update(Buffer.from(Z,"utf8")),G.update(Buffer.from(z)),G.update(Buffer.from(X)),G.update(Buffer.from(J)),new Uint8Array(G.digest())}function S6($,Z){if($.length!==Z.length)return!1;return e5(Buffer.from($),Buffer.from(Z))}async function w6($,Z,z){let X=Buffer.from(JSON.stringify(Z),"utf8");if(X.length>S$)throw new g(`auth message too large: ${X.length} > ${S$}`);let J=new Uint8Array(4);new DataView(J.buffer).setUint32(0,X.length,!0),await z2($,J,z),await z2($,X,z)}async function Z1($,Z){let z=await $.readExact(4,Z),X=new DataView(z.buffer,z.byteOffset,4).getUint32(0,!0);if(X>S$)throw new g(`auth message too large: ${X} > ${S$}`);let J=X===0?new Uint8Array(0):await $.readExact(X,Z);try{return JSON.parse(Buffer.from(J).toString("utf8"))}catch(G){throw new g(`auth message JSON decode failed: ${String(G)}`)}}function l3($,Z){if(!Array.isArray($))throw new g(`auth field '${Z}' must be a byte array`);for(let z of $)if(typeof z!=="number"||!Number.isInteger(z)||z<0||z>255)throw new g(`auth field '${Z}' has invalid byte ${String(z)}`);return Uint8Array.from($)}async function Y$($,Z,z){let X=new Uint8Array(r5(k6));await w6($,{client_nonce:Array.from(X),role:$1},z);let J=await Z1($,z),G=l3(J.server_nonce,"server_nonce"),Q=l3(J.daemon_id,"daemon_id"),Y=l3(J.server_proof,"server_proof"),W=d3(Z.key,f6,X,G,Q);if(!S6(W,Y))throw new g("server proof mismatch — wrong key or impostor daemon");if(!S6(Q,Z.daemonId))throw new g("daemon id mismatch — connection file points at a different daemon");let B=d3(Z.key,E6,X,G,Q);await w6($,{client_auth:Array.from(B)},z)}import{promises as i3}from"node:fs";var y6=1,v6=32,h6=16;class f extends Error{}function m6($,Z){if(!Array.isArray($))throw new f(`connection file field '${Z}' must be a JSON array of bytes`);for(let z of $)if(typeof z!=="number"||!Number.isInteger(z)||z<0||z>255)throw new f(`connection file field '${Z}' has invalid byte ${String(z)}`);return Uint8Array.from($)}function z1($){if($.schema!==y6)throw new f(`unsupported connection file schema ${$.schema}; expected ${y6}`);if($.endpoints.length===0)throw new f("connection file must include at least one endpoint");if($.key.length<v6)throw new f(`connection file key is too short: ${$.key.length} bytes, need at least ${v6}`);if($.daemonId.length!==h6)throw new f(`connection file daemon_id must be ${h6} bytes, got ${$.daemonId.length}`)}async function X1($){if(process.platform==="win32")return;let z=(await i3.stat($)).mode&511;if((z&63)!==0)throw new f(`connection file ${$} has insecure permissions 0o${z.toString(8)}; expected owner-only 0600`)}async function S2($){await X1($);let Z=await i3.readFile($,"utf8"),z;try{z=JSON.parse(Z)}catch(Y){throw new f(`connection file JSON read failed for ${$}: ${String(Y)}`)}let X=z.wire_version;if(X!==void 0&&X!==u)throw new f(`connection file wire_version ${String(X)} but this client speaks ${u}; the client library must be upgraded`);let J=z.endpoints;if(!Array.isArray(J))throw new f("connection file 'endpoints' must be an array");let G=J.map((Y)=>{let W=Y;if(typeof W.host!=="string"||typeof W.port!=="number")throw new f("connection file endpoint must be { host: string, port: number }");return{host:W.host,port:W.port}}),Q={schema:z.schema,endpoints:G,key:m6(z.key,"key"),daemonId:m6(z.daemon_id,"daemon_id"),pid:z.pid,daemonVer:z.daemon_ver??""};return z1(Q),Q}var g6=new WeakMap;class w${channel;epoch;constructor($,Z,z){if(!Number.isInteger($)||$<=0||$>65535)throw RangeError(`route channel must be an integer in 1..65535, got ${$}`);if(!Number.isInteger(Z)||Z<=0||Z>4294967295)throw RangeError(`route epoch must be an integer in 1..4294967295, got ${Z}`);this.channel=$,this.epoch=Z,g6.set(this,z),Object.freeze(this)}static create($,Z,z){return new w$($,Z,z)}}function k$($,Z,z){return w$.create($,Z,z)}class H2 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 g2(){return Object.freeze({})}function W$($,Z){return g6.get($)===Z}function f$($,Z){return $===Z}var G1=J1("subc-client"),Q1=1e4,B$=30000,Y1=50,W1=2000,p6="request_deadline",c3="deadline_exceeded_no_drop_observed",B1=30000,j1=30000,u6=new Uint8Array(0),V1="management_surface",d6="SUBC_MODULE_ID",i6="SUBC_LAUNCH_NONCE",m$={baseMs:100,capMs:2000,maxAttempts:6};class E extends Error{kind;code;cause;constructor($,Z,z,X){super(Z);this.kind=$,this.code=z,this.cause=X,this.name="SubcCallError"}}class A extends Error{code;constructor($,Z){super($);this.code=Z}}class w2{sock;currentConn;opts;nextCorr=1n;pending=new Map;lateResponses=new Map;routes=new Map;liveRoutes=new Map;connectionToken=g2();ingressEpochDropCount=0;closedErr=null;closeStarted=!1;reconnecting=null;generation=1;readerActive=!1;constructor($,Z,z){this.sock=$,this.currentConn=Z,this.opts=z,this.readLoop($,this.generation)}get conn(){return this.currentConn}static async connect($){let Z=q1($),z=await w2.openConnection(Z);return new w2(z.sock,z.conn,Z)}async catalogList($){let Z=this.encode($===void 0?{op:"catalog.list"}:{op:"catalog.list",module_id:$}),z=await this.controlRpc(Z);return this.parseJson(z).modules??[]}async routeOpen($,Z,z={}){let X=s3(z),J=z.consumerCapabilities,G=this.encode({op:"route.open",target:$,identity:Z,...X?{consumer_identity:X}:{},...J!==void 0?{consumer_capabilities:J}:{}}),Q=null,Y=(B)=>{if(B.header.ty!==L.Response)return!0;let j=this.parseJson(B);if(typeof j.route_channel!=="number"||typeof j.route_epoch!=="number")throw new A(`route.open returned no route handle: ${JSON.stringify(j)}`);return Q=this.installRoute(j.route_channel,j.route_epoch),!0},W=(B)=>{if(B.header.ty!==L.Response)return;try{let j=this.parseJson(B);if(typeof j.route_channel!=="number"||typeof j.route_epoch!=="number")return;let V=this.installRoute(j.route_channel,j.route_epoch);this.failHandle(V,new A("late route.open was closed","route_closed")),this.liveRoutes.delete(V.channel),this.sendRouteGoodbye(V,!0)}catch{this.closeConnectionAfterCleanupFailure()}};if(await this.controlRpc(G,Y,W),!Q)throw new A("route.open response was not installed");return Q}async request($,Z,z={}){this.assertLiveHandle($);let X=Z instanceof Uint8Array?Z:this.encode(Z),J=z.priority??k.Interactive,G=z.admissionClass??v.Normal,Q=await this.send($,X,J,G,z.timeoutMs,z.onProgress);return this.parseJson(Q)}async call($,Z,z,X={}){let J=z===void 0?{method:Z}:{method:Z,params:z},G=!1;for(;;){let Q=await this.cachedRouteHandle($,X);try{return await this.managedRequest(Q,J,X)}catch(Y){if(!(Y instanceof E))throw this.terminalCallError("managed call failed",Y);let W=Y.code==="unknown_channel"||Y.code==="stale_route_epoch";if(W&&!G&&!this.closeStarted){G=!0,this.evictRouteHandle(Q);continue}if(W&&G)this.evictRouteHandle(Q);if(Y.kind==="not_sent"){try{await this.reconnectAfterDrop(Y)}catch(B){throw this.notSentRecoveryError("managed call was not sent",B)}continue}if(Y.kind==="outcome_unknown"&&Y.code!==c3)this.scheduleReconnectAfterDrop(Y);else if(Y.kind==="outcome_unknown"&&Y.code===c3)this.probeLivenessAfterDeadline();throw Y}}}subscribe($,Z,z,X={}){this.assertLiveHandle($);let J=Z instanceof Uint8Array?Z:this.encode(Z),G=X.priority??k.Interactive,Q=X.admissionClass??v.Normal,Y=this.allocateCorr(),W=y$($,Y),B=null,j=null,V=new Promise((H,N)=>{if(this.closedErr){N(this.closedErr);return}j=H,B={handle:$,resolve:()=>H(),reject:N,onProgress:z,timer:null,subscription:!0},this.pending.set(W,B);let U=m(L.Request,l(!1,G,!1,Q),$.channel,$.epoch,Y,J);z2(this.sock,$2(U),Date.now()+B$).catch((P)=>{let M=this.pending.get(W);if(M)this.rejectPending(W,M,P instanceof Error?P:new A(String(P)))})}),q=!1;return{unsubscribe:()=>{if(q)return;if(q=!0,B&&j)this.settle(W,B,j);if(this.isLiveHandle($))this.cancel($,Y,G)},closed:V}}cancel($,Z,z=k.Interactive){this.assertLiveHandle($);let X=m(L.Cancel,l(!1,z,!1),$.channel,$.epoch,Z,u6);z2(this.sock,$2(X),Date.now()+B$).catch(()=>{return})}async routePoll($,Z){this.assertLiveHandle($);let z=this.encode({op:"route.poll",route_channel:$.channel,route_epoch:$.epoch,kind:Z}),X=await this.controlRpc(z,(J)=>{if(J.header.ty!==L.Response)return!0;let G=this.parseJson(J);return G.route_channel===$.channel&&G.route_epoch===$.epoch});return this.parseJson(X)}async closeRoute($,Z={}){this.assertLiveHandle($);for(let[z,X]of this.routes)if(X.handle&&f$(X.handle,$))X.closed=!0,X.handle=null,this.routes.delete(z);if(Z.drain)await this.drainUnaryOnHandle($);if(this.failHandle($,new A("route closed by closeRoute","route_closed")),this.liveRoutes.get($.channel)===$)this.liveRoutes.delete($.channel);this.sendRouteGoodbye($)}async closeManagedRoute($,Z,z={}){let X=l6($,Z,s3(z)),J=this.routes.get(X);if(!J)return;J.closed=!0,this.routes.delete(X);let G=J.handle;if(J.handle=null,G)await this.closeRoute(G,z)}async closeRouteChannel($,Z={}){await this.closeRoute($,Z)}close(){this.closeStarted=!0,this.fail(new A("client closed")),this.sock.close()}drainUnaryOnHandle($){let Z=[];for(let z of this.pending.values())if(z.handle===$&&!z.subscription)Z.push(new Promise((X)=>{let J=z.onSettle;z.onSettle=()=>{J?.(),X()}}));return Promise.all(Z).then(()=>{return})}sendRouteGoodbye($,Z=!1){if(this.assertLiveConnection($),this.closedErr){if(Z)this.closeConnectionAfterCleanupFailure();return}let z=m(L.Goodbye,l(!1,k.Interactive,!1),$.channel,$.epoch,0n,u6),X=u3(this.sock,$2(z),Date.now()+B$);if(!X.queued&&Z)this.closeConnectionAfterCleanupFailure();X.completed.catch(()=>{if(Z&&!X.queued)this.closeConnectionAfterCleanupFailure()})}static async openConnection($){let Z=await S2($.connectionFile),z=Date.now()+($.handshakeTimeoutMs??Q1),X=Z.endpoints[0],J=await C2.connect(X.host,X.port,z);try{await Y$(J,Z,z)}catch(G){throw J.close(),G}return{sock:J,conn:Z}}async controlRpc($,Z,z){return this.send(null,$,k.Interactive,v.Normal,void 0,void 0,Z,z)}send($,Z,z,X,J,G,Q,Y){if($)this.assertLiveHandle($);if(this.closedErr)return Promise.reject(this.closedErr);let W;try{W=this.allocateCorr()}catch(K){return Promise.reject(K)}let B=y$($,W),j=$?.channel??0,V=$?.epoch??0,q=m(L.Request,l(!1,z,!1,X),j,V,W,Z);return new Promise((K,H)=>{let N=J??B$,U={handle:$,resolve:K,reject:H,onProgress:G,timer:null,acceptFrame:Q,onLateResponse:Y};U.timer=setTimeout(()=>this.arbitrateTimeout(B,U,j,W,N),N),this.pending.set(B,U),z2(this.sock,$2(q),Date.now()+N).catch((P)=>{let M=this.pending.get(B);if(M)this.rejectPending(B,M,P instanceof Error?P:new A(String(P)))})})}arbitrateTimeout($,Z,z,X,J){let G=()=>{if(Z.onLateResponse)this.lateResponses.set($,Z.onLateResponse);this.rejectPending($,Z,new A(this.timeoutMessage(z,X,J),p6))},Q=Date.now()+this.opts.timeoutArbitrationGraceMs,Y=()=>{if(this.pending.get($)!==Z)return;if((this.readerActive||this.sock.bufferedBytes()>0)&&Date.now()<Q){setImmediate(Y);return}G()};setImmediate(Y)}async managedRequest($,Z,z){let X=Z instanceof Uint8Array?Z:this.encode(Z),J=z.priority??k.Interactive,G=z.admissionClass??v.Normal;try{let Q=await this.sendManaged($,X,J,G,z.timeoutMs,z.onProgress);return this.parseJson(Q)}catch(Q){if(Q instanceof E)throw Q;throw this.terminalCallError("managed call failed",Q)}}sendManaged($,Z,z,X,J,G){try{this.assertLiveHandle($)}catch(V){return Promise.reject(this.notSentCallError("request used a stale route handle",V))}if(this.closedErr)return Promise.reject(this.notSentCallError("request was not sent because the subc connection was already closed",this.closedErr));let Q;try{Q=this.allocateCorr()}catch(V){return Promise.reject(this.notSentCallError("request correlation allocator was exhausted",V))}let Y=y$($,Q),W=m(L.Request,l(!1,z,!1,X),$.channel,$.epoch,Q,Z),B=!1,j=(V)=>{if(!B)return this.notSentCallError("request bytes were not queued to the subc socket",V);if(V instanceof A&&V.code===p6)return new E("outcome_unknown",`managed call deadline exceeded after request bytes were queued to the local socket; no terminal response was observed; outcome unknown${E$(V)}`,c3,V);return this.outcomeUnknownCallError("connection dropped before the managed call returned a response",V)};return new Promise((V,q)=>{let K=J??B$,H={handle:$,resolve:V,reject:q,onProgress:G,timer:null,classifyFailure:j};H.timer=setTimeout(()=>this.arbitrateTimeout(Y,H,$.channel,Q,K),K),this.pending.set(Y,H);let N=u3(this.sock,$2(W),Date.now()+K);B=N.queued,N.completed.catch((U)=>{let P=this.pending.get(Y);if(P)this.rejectPending(Y,P,U instanceof Error?U:new A(String(U)))})})}async cachedRouteHandle($,Z){let z=Z.identity??this.opts.identity;if(!z)throw new E("terminal","managed call requires a BindIdentity in SubcClient.connect({ identity }) or call(..., { identity })","missing_identity");let X={kind:Z.targetKind??this.opts.targetKind,module_id:$},J=s3(Z),G=l6(X,z,J),Q=this.routes.get(G);if(!Q)Q={key:G,moduleId:$,target:X,identity:z,consumerIdentity:J,handle:null,opening:null},this.routes.set(G,Q);if(Q.handle&&this.isLiveHandle(Q.handle))return Q.handle;if(!Q.opening)Q.opening=this.openCachedRoute(Q).finally(()=>{Q.opening=null});return Q.opening}async openCachedRoute($){let Z=Date.now()+B1,z=this.opts.reconnectBackoff.baseMs,X=0;for(;;){if($.closed)throw this.routeClosedDuringOpen();try{await this.ensureConnectedForManaged()}catch(J){throw this.notSentRecoveryError("route.open could not run because reconnect failed",J)}if($.handle&&this.isLiveHandle($.handle))return $.handle;try{let J=await this.routeOpen($.target,$.identity,{consumerIdentity:$.consumerIdentity??null});if($.closed)throw this.liveRoutes.delete(J.channel),this.sendRouteGoodbye(J),this.routeClosedDuringOpen();return $.handle=J,J}catch(J){if(J instanceof E&&J.code==="route_closed")throw J;if(!this.closeStarted&&v$(J)){try{await this.reconnectAfterDrop(J)}catch(G){throw this.notSentRecoveryError("route.open was not sent and reconnect failed",G)}continue}if(!this.closeStarted&&J instanceof A&&H1(J.code)){if(X+=1,X<this.opts.reconnectBackoff.maxAttempts&&Date.now()<Z){await this.opts.sleep(z),z=Math.min(z*2,this.opts.reconnectBackoff.capMs);continue}throw this.notSentCallError(`route.open failed for module ${$.moduleId}: ${J.code} (retry budget exhausted)`,J)}throw this.terminalCallError(`route.open failed for module ${$.moduleId}`,J)}}}lastInboundAtMs=0;livenessProbe=null;hasControlPending(){for(let $ of this.pending.values())if($.handle===null)return!0;return!1}probeLivenessAfterDeadline(){if(this.livenessProbe||this.closeStarted||this.closedErr)return;if(this.hasControlPending())return;let $=this.sock,Z=this.generation,z;try{z=this.allocateCorr()}catch{return}let X=Date.now(),J=m(L.Ping,l(!1,k.Interactive,!1,v.Normal),0,0,z,new Uint8Array),G=(async()=>{if(await z2($,$2(J),X+this.opts.livenessProbeWindowMs).catch(()=>{}),await this.opts.sleep(this.opts.livenessProbeWindowMs),this.sock!==$||this.generation!==Z||this.closeStarted)return;if(this.lastInboundAtMs>=X)return;if(this.hasControlPending())return;this.fail(new V2(`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=G}async ensureConnectedForManaged(){if(this.closeStarted)throw new A("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 A("client closed"));if(this.reconnecting)return this.reconnecting;let Z=this.reconnectWithRetry($).finally(()=>{if(this.reconnecting===Z)this.reconnecting=null});return this.reconnecting=Z,Z}async reconnectWithRetry($){let Z=0,z=this.opts.reconnectBackoff.baseMs;for(;;){if(this.closeStarted)throw new A("client closed");Z+=1;try{let X=await w2.openConnection(this.opts);if(this.closeStarted)throw X.sock.close(),new A("client closed");this.replaceConnection(X),await this.reopenCachedRoutes();return}catch(X){if(!v$(X)||Z>=this.opts.reconnectBackoff.maxAttempts){if(X instanceof g&&Z>1)throw new g(`reconnect gave up after ${Z} attempts: ${X.message} — the connection file and the daemon's key disagree persistently `+"(daemon restarting in a loop, split connection-file paths, or a genuinely foreign daemon on this port); check the daemon, then restart this host app");throw X}await this.opts.sleep(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=g2(),this.liveRoutes.clear(),this.lateResponses.clear(),this.nextCorr=1n,this.readLoop($.sock,this.generation)}async reopenCachedRoutes(){for(let $ of this.routes.values())$.handle=null;for(let $ of this.routes.values()){if($.closed)continue;let Z=await this.routeOpen($.target,$.identity,{consumerIdentity:$.consumerIdentity??null});if($.closed){this.liveRoutes.delete(Z.channel),this.sendRouteGoodbye(Z);continue}$.handle=Z}}timeoutMessage($,Z,z){let X=this.sock.localPort();return`request on ${X===null?"channel":`local_port=${X} channel`} ${$} corr ${Z} timed out after ${z}ms`}routeClosedDuringOpen(){return new E("not_sent","route was closed before route.open completed","route_closed")}async readLoop($,Z){try{for(;;){this.readerActive=!1;let z=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:j1},()=>{this.readerActive=!0});try{if(this.sock===$&&this.generation===Z)this.dispatch(z)}finally{this.readerActive=!1}}}catch(z){if(this.sock===$&&this.generation===Z)this.fail(z instanceof Error?z:new A(String(z)))}}dispatch($){if(this.lastInboundAtMs=Date.now(),$.header.channel===0&&$.header.ty===L.Push){let G=this.opts.onControlPush;if(G){let Q=null;try{let Y=this.parseJson($);if(Y&&typeof Y.op==="string")Q={op:Y.op,body:Y}}catch{}if(Q)try{G(Q)}catch{}}return}let Z=null;if($.header.channel!==0){if(Z=this.liveRoutes.get($.header.channel)??null,!Z||Z.epoch!==$.header.epoch){this.ingressEpochDropCount+=1;return}}let z=y$(Z,$.header.corr),X=this.pending.get(z);if(X){if(X.acceptFrame&&!X.acceptFrame($))return;switch($.header.ty){case L.Push:case L.StreamData:try{X.onProgress?.($.body)}catch{}return;case L.Response:case L.StreamEnd:this.settle(z,X,()=>X.resolve($));return;case L.Error:this.settle(z,X,()=>X.reject(this.errorFromFrame($)));return;default:return}}let J=this.lateResponses.get(z);if(J&&($.header.ty===L.Response||$.header.ty===L.Error)){this.lateResponses.delete(z),J($);return}if($.header.ty===L.Goodbye&&Z){if(this.failHandle(Z,new A("route closed by subc (GOODBYE)","route_closed")),this.liveRoutes.get(Z.channel)===Z)this.liveRoutes.delete(Z.channel);this.evictRouteHandle(Z);return}if($.header.ty===L.Response||$.header.ty===L.Error||$.header.ty===L.StreamEnd)G1("dropped terminal frame with no waiter: type=%d channel=%d epoch=%d corr=%s port=%s",$.header.ty,$.header.channel,$.header.epoch,$.header.corr,this.sock.localPort()??"?")}settle($,Z,z){if(this.pending.get($)!==Z)return!1;if(this.pending.delete($),Z.timer)clearTimeout(Z.timer);return z(),Z.onSettle?.(),!0}rejectPending($,Z,z){this.settle($,Z,()=>Z.reject(Z.classifyFailure?.(z)??z))}errorFromFrame($){try{let Z=JSON.parse(Buffer.from($.body).toString("utf8"));return new A(Z.message??"subc error",Z.code)}catch{return new A(Buffer.from($.body).toString("utf8")||"subc error")}}evictRouteHandle($){for(let Z of this.routes.values())if(Z.handle&&f$(Z.handle,$))Z.handle=null}failHandle($,Z){for(let[z,X]of this.pending)if(X.handle&&f$(X.handle,$))this.rejectPending(z,X,Z)}fail($){if(!this.closedErr)this.closedErr=$;for(let[Z,z]of this.pending)this.rejectPending(Z,z,$)}notSentCallError($,Z){return new E("not_sent",`${$}${E$(Z)}`,h$(Z),Z)}outcomeUnknownCallError($,Z){return new E("outcome_unknown",`${$}${E$(Z)}`,h$(Z),Z)}terminalCallError($,Z){if(Z instanceof E)return Z;return new E("terminal",`${$}${E$(Z)}`,h$(Z),Z)}notSentRecoveryError($,Z){if(Z instanceof E)return Z;if(v$(Z))return this.notSentCallError($,Z);return this.terminalCallError($,Z)}get droppedIngressFrames(){return this.ingressEpochDropCount}installRoute($,Z){let z=k$($,Z,this.connectionToken);return this.liveRoutes.set($,z),z}isLiveHandle($){return W$($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveConnection($){if(!W$($,this.connectionToken))throw new H2($)}assertLiveHandle($){if(!this.isLiveHandle($))throw new H2($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let z=new A("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.fail(z),this.sock.close(),this.scheduleReconnectAfterDrop(z),z}let Z=this.nextCorr;return this.nextCorr+=1n,Z}closeConnectionAfterCleanupFailure(){let $=new A("late route cleanup could not be queued","late_route_cleanup_failed");this.fail($),this.sock.close(),this.scheduleReconnectAfterDrop($)}encode($){return Buffer.from(JSON.stringify($),"utf8")}parseJson($){let Z=$.body;return JSON.parse(Buffer.from(Z.buffer,Z.byteOffset,Z.byteLength).toString("utf8"))}}function v$($){if($ instanceof V2||$ instanceof r)return!0;if($ instanceof Z2||$ instanceof D2)return!0;if($ instanceof E)return $.kind==="not_sent"||$.kind==="outcome_unknown";if($ instanceof g)return!0;if($ instanceof A||$ instanceof f)return!1;let Z=h$($);return Z==="ECONNREFUSED"||Z==="ECONNRESET"||Z==="EPIPE"||Z==="ETIMEDOUT"||Z==="ENOENT"}function H1($){return $==="unknown_module"||$==="module_reloading"||$==="module_warming"||$==="target_unavailable"||$==="module_timeout"}function q1($){return{connectionFile:$.connectionFile,handshakeTimeoutMs:$.handshakeTimeoutMs,identity:$.identity,targetKind:$.targetKind??V1,reconnectBackoff:$.reconnectBackoff??m$,sleep:$.sleep??((Z)=>new Promise((z)=>setTimeout(z,Z))),timeoutArbitrationGraceMs:$.timeoutArbitrationGraceMs??Y1,livenessProbeWindowMs:$.livenessProbeWindowMs??W1,onControlPush:$.onControlPush}}function l6($,Z,z){let X=z?`${z.module_id}\x00${z.launch_nonce}`:"";return`${$.kind}\x00${$.module_id}\x00${Z.project_root}\x00${Z.harness}\x00${Z.session}\x00${X}`}function s3($={}){if($.consumerIdentity!==void 0)return $.consumerIdentity??void 0;let Z=process.env[d6],z=process.env[i6];if(!Z||!z)return;return{module_id:Z,launch_nonce:z}}function h$($){if(typeof $==="object"&&$!==null&&"code"in $){let Z=$.code;if(typeof Z==="string")return Z}return}function E$($){if($===void 0)return"";return`: ${$ instanceof Error?$.message:String($)}`}function y$($,Z){return $?`${$.channel}:${$.epoch}:${Z}`:`0:0:${Z}`}import{Buffer as o3}from"node:buffer";var K1=1e4,L1=30000,s6=30000,N1=250,n3=64,t3="health.check",n6=1n;class p${available;waiters=[];constructor($){if(!Number.isInteger($)||$<=0)throw new T("provider handler capacity must be a positive integer","invalid_handler_capacity");this.available=$}async acquire(){if(this.available>0)return this.available-=1,this.releaseOnce();return await new Promise(($)=>{this.waiters.push($)}),this.releaseOnce()}releaseOnce(){let $=!1;return()=>{if($)return;$=!0;let Z=this.waiters.shift();if(Z)Z();else this.available+=1}}}class T extends Error{code;kind;constructor($,Z,z="terminal"){super($);this.code=Z,this.kind=z}}class j${sock;currentConn;opts;closed;resolveClosed=()=>{return};closeStarted=!1;closedErr=null;inflight=new Map;pending=new Map;liveRoutes=new Map;connectionToken=g2();nextCorr=1n;ingressEpochDropCount=0;requestGate=new p$(n3);reconnecting=null;generation=1;connectionEpoch=1;stateQueue=[];drainingStateQueue=!1;restoredDebounceToken=0;storage;constructor($,Z,z,X){this.sock=$,this.currentConn=Z,this.opts=z,this.storage=X,this.closed=new Promise((J)=>{this.resolveClosed=J}),this.readLoop($,this.generation),this.enqueueConnectionState({state:"connected",epoch:this.connectionEpoch})}get droppedIngressFrames(){return this.ingressEpochDropCount}get conn(){return this.currentConn}currentEpoch(){return this.connectionEpoch}async request($,Z,z={}){this.assertLiveHandle($);let X=this.allocateCorr(),J=g$($,X),G=z.timeoutMs??s6,Q=m(L.Request,l(!1,z.priority??k.Interactive,!1,z.admissionClass??v.Normal),$.channel,$.epoch,X,Z);return await new Promise((Y,W)=>{let B=setTimeout(()=>{if(this.pending.delete(J))W(new T("reverse request timed out","request_timeout"))},G);this.pending.set(J,{resolve:(j)=>Y(j.body),reject:W,timer:B}),this.sendOn(this.sock,this.generation,Q).catch((j)=>{let V=this.pending.get(J);if(!V)return;this.pending.delete(J),clearTimeout(V.timer),W(j instanceof Error?j:new T(String(j)))})})}async push($,Z,z={}){this.assertLiveHandle($),await this.sendOn(this.sock,this.generation,m(L.Push,l(!1,z.priority??k.Interactive,!1,z.admissionClass??v.Normal),$.channel,$.epoch,0n,Z))}cancel($,Z){this.assertLiveHandle($),this.sendOn(this.sock,this.generation,m(L.Cancel,X2(),$.channel,$.epoch,Z,new Uint8Array(0))).catch(()=>{return})}closeRoute($){this.assertLiveHandle($),this.liveRoutes.delete($.channel),this.abortHandle($),this.sendOn(this.sock,this.generation,m(L.Goodbye,X2(),$.channel,$.epoch,0n,new Uint8Array(0))).catch(()=>{return})}static async connect($){if($.manifest.protocol_ver!==u)throw new T(`manifest protocol_ver ${$.manifest.protocol_ver} does not match client protocol ${u}`,"invalid_manifest");let Z=O1($),z=await j$.openConnection(Z);return new j$(z.sock,z.conn,Z,z.ack.storage)}async close(){if(!this.closeStarted){this.closeStarted=!0,this.cancelRestoredDebounce();let $=this.sock;try{await a3($,m(L.Goodbye,X2(),0,0,0n,new Uint8Array(0)))}catch{}finally{$.close(),this.finishClosed()}}await this.closed}static async openConnection($,Z){let z=await S2($.connectionFile),X=Date.now()+($.handshakeTimeoutMs??K1),J=z.endpoints[0],G=await C2.connect(J.host,J.port,X);try{Z?.(G),await Y$(G,z,X),await a3(G,_1($));let Q=await R1(G,X);return{sock:G,conn:z,ack:Q}}catch(Q){throw G.close(),Q}}async readLoop($,Z){try{for(;;){let z=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:L1});if(!await this.dispatch(z,$,Z)){if(this.sock===$&&this.generation===Z)this.closeStarted=!0;break}}}catch(z){if(this.sock===$&&this.generation===Z&&!this.closeStarted){this.handleUnexpectedDrop($,Z,z instanceof Error?z:new T(String(z)));return}}finally{if(this.sock===$&&this.generation===Z){if($.close(),this.closeStarted)this.finishClosed()}}}async dispatch($,Z,z){let X=null;if($.header.channel!==0){if(X=this.liveRoutes.get($.header.channel)??null,!X||X.epoch!==$.header.epoch)return this.ingressEpochDropCount+=1,!0}if(X){let J=g$(X,$.header.corr),G=this.pending.get(J);if(G){if($.header.ty===L.Push||$.header.ty===L.StreamData)return!0;if($.header.ty===L.Response||$.header.ty===L.StreamEnd)return this.pending.delete(J),clearTimeout(G.timer),G.resolve($),!0;if($.header.ty===L.Error)return this.pending.delete(J),clearTimeout(G.timer),G.reject(U1($)),!0}}switch($.header.ty){case L.Ping:if($.header.channel===0)await this.sendOn(Z,z,e($.header.ver,L.Pong,$.header.flags,0,0,$.header.corr,new Uint8Array(0)));return!0;case L.Goodbye:if(!X)return!1;return this.liveRoutes.delete(X.channel),this.abortHandle(X),await this.opts.onRouteGone?.(X),!0;case L.Cancel:if(X)this.inflight.get(g$(X,$.header.corr))?.abort();return!0;case L.Request:if($.header.channel===0)await this.handleControlRequest($,Z,z);else if(X)this.handleDataRequest($,X,Z,z).catch((J)=>{if(!this.closeStarted&&this.sock===Z&&this.generation===z)console.warn("SubcProvider handler failed after its request was dispatched",J)});return!0;default:return!0}}abortHandle($){let Z=`${$.channel}:${$.epoch}:`;for(let[z,X]of this.inflight)if(z.startsWith(Z))X.abort();for(let[z,X]of this.pending){if(!z.startsWith(Z))continue;this.pending.delete(z),clearTimeout(X.timer),X.reject(new H2($))}}abortGeneration($){this.abortAllInflight();for(let[Z,z]of this.pending)this.pending.delete(Z),clearTimeout(z.timer),z.reject(new T("provider connection dropped","connection_dropped"));this.liveRoutes.clear()}abortAllInflight(){for(let $ of this.inflight.values())$.abort()}async handleControlRequest($,Z,z){let X=l$($.body);if(X.op===t3){this.handleHealthRequest($,Z,z).catch((V)=>{if(!this.closeStarted&&this.sock===Z&&this.generation===z)console.warn("SubcProvider health handler failed after its request was dispatched",V)});return}if(X.op!=="route.bind")throw new T(`unsupported module control request ${X.op??"<missing op>"}`);let J=c6(X.route_channel,"route_channel"),G=c6(X.epoch,"epoch"),Q=this.liveRoutes.get(J);if(Q){if(G<=Q.epoch){await this.sendError($,"route_rejected",`route.bind epoch ${G} does not supersede installed epoch ${Q.epoch} on channel ${J}`,X2(),Z,z);return}this.liveRoutes.delete(Q.channel),this.abortHandle(Q),await this.opts.onRouteGone?.(Q)}let Y=k$(J,G,this.connectionToken),W={handle:Y,target:X.target,identity:X.identity,principal:X.principal,consumer_capabilities:X.consumer_capabilities},B;try{B=await this.opts.onBind?.(W)}catch(V){try{await this.sendError($,"route_rejected",V instanceof Error?V.message:String(V),X2(),Z,z)}finally{await this.opts.onRouteGone?.(Y)}return}let j=A1(B);if(j){try{await this.sendError($,j.code,j.message,X2(),Z,z)}finally{await this.opts.onRouteGone?.(Y)}return}try{await this.sendOn(Z,z,e($.header.ver,L.Response,X2(),0,0,$.header.corr,u$({op:"route.bind"})))}catch(V){throw await this.opts.onRouteGone?.(Y),V}if(this.sock!==Z||this.generation!==z||this.closeStarted||this.closedErr){await this.opts.onRouteGone?.(Y);return}this.liveRoutes.set(Y.channel,Y),await this.opts.onBound?.(Y)}async handleDataRequest($,Z,z,X){let{corr:J,ver:G}=$.header,Q=g$(Z,J),Y=new AbortController;this.inflight.set(Q,Y);let W={handle:Z,signal:Y.signal,currentEpoch:()=>this.connectionEpoch,emit:async(V,q={})=>{if(this.assertLiveHandle(Z),Y.signal.aborted)return;await this.sendOn(z,X,e(G,L.StreamData,l(!1,q.priority??k.Interactive,!1,q.admissionClass??v.Normal),Z.channel,Z.epoch,J,V))}},B=await(this.requestGate??new p$(n3)).acquire(),j=l(!1,k.Interactive,!1);try{if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",j,z,X);return}let V=await this.opts.handler(Z,$.body,W);if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",j,z,X);return}if(this.assertLiveHandle(Z),V===void 0)await this.sendOn(z,X,e(G,L.StreamEnd,j,Z.channel,Z.epoch,J,new Uint8Array(0)));else if(V instanceof Uint8Array)await this.sendOn(z,X,e(G,L.Response,j,Z.channel,Z.epoch,J,V));else throw new T("provider handler must return a Uint8Array or void","invalid_handler_response")}catch(V){if(V instanceof H2)return;if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",j,z,X);return}await this.sendError($,V instanceof T&&V.code?V.code:"handler_error",V instanceof Error?V.message:String(V),j,z,X)}finally{if(B(),this.inflight.get(Q)===Y)this.inflight.delete(Q)}}async handleHealthRequest($,Z,z){let{corr:X,ver:J}=$.header,G=`control:${z}:${X}`,Q=new AbortController;this.inflight.set(G,Q);let Y=await(this.requestGate??new p$(n3)).acquire();try{if(Q.signal.aborted)return;let W=await this.opts.health();await this.sendOn(Z,z,e(J,L.Response,X2(),0,0,X,u$({op:t3,status:W.status,...W.detail===void 0?{}:{detail:W.detail},...W.metrics===void 0?{}:{metrics:W.metrics}})))}catch(W){await this.sendError($,W instanceof T&&W.code?W.code:"health_error",W instanceof Error?W.message:String(W),X2(),Z,z)}finally{if(Y(),this.inflight.get(G)===Q)this.inflight.delete(G)}}async sendError($,Z,z,X,J,G){if($.header.channel!==0){let Q=this.liveRoutes.get($.header.channel);if(!Q||Q.epoch!==$.header.epoch||!this.isLiveHandle(Q))return}await this.sendOn(J,G,e($.header.ver,L.Error,X,$.header.channel,$.header.epoch,$.header.corr,u$({code:Z,message:z})))}async sendOn($,Z,z){if(this.sock!==$||this.generation!==Z||this.closeStarted||this.closedErr)return;await a3($,z)}handleUnexpectedDrop($,Z,z){if(this.closeStarted||this.sock!==$||this.generation!==Z)return;this.cancelRestoredDebounce(),this.abortGeneration(Z),this.generation+=1,$.close(),this.scheduleReconnectAfterDrop(z,this.generation,$)}scheduleReconnectAfterDrop($,Z,z){if(this.closeStarted)return;let X=this.reconnecting;if(X){if(!this.shouldSupersedeReconnect(X,Z,z))return;X.superseded=!0,X.socket?.close()}let J={generation:Z,socket:null,socketDied:!1,superseded:!1};this.reconnecting=J,this.enqueueConnectionState({state:"down",cause:$}),this.reconnectWithRetry(J).catch((G)=>{if(this.isCurrentReconnect(J)&&!this.closeStarted)this.failFatal(G instanceof Error?G:new T(String(G)))}).finally(()=>{if(this.isCurrentReconnect(J))this.reconnecting=null})}async reconnectWithRetry($){let Z=0,z=this.opts.reconnectBackoff.baseMs;for(;;){if(!this.isCurrentReconnect($))return;if(this.closeStarted)throw new T("provider closed");$.socket=null,$.socketDied=!1,Z+=1,this.enqueueReconnectState($,Z);try{let X=await j$.openConnection(this.opts,(G)=>{if(!this.isCurrentReconnect($)){G.close();return}$.socket=G});if(!this.isCurrentReconnect($)||this.closeStarted){if(X.sock.close(),this.closeStarted)throw new T("provider closed");return}let J=this.replaceConnection(X,$.generation);if(this.reconnecting=null,this.reconnecting!==null)throw new T("reconnect state must clear before restored","reconnect_state");this.scheduleRestored($.generation,J);return}catch(X){if(!this.isCurrentReconnect($))return;if($.socket)$.socketDied=!0;if(this.closeStarted)throw X;if(!x1(X))throw X;await this.opts.sleep(z),z=Math.min(z*2,this.opts.reconnectBackoff.capMs)}}}isCurrentReconnect($){return!$.superseded&&this.reconnecting===$&&this.generation===$.generation}shouldSupersedeReconnect($,Z,z){return $.generation<Z||$.socketDied||$.socket===z}enqueueReconnectState($,Z){if(!this.isCurrentReconnect($))return;this.enqueueConnectionState({state:"reconnecting",attempt:Z},$.generation,$)}replaceConnection($,Z){return this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.storage=$.ack.storage,this.closedErr=null,this.connectionEpoch+=1,this.connectionToken=g2(),this.liveRoutes.clear(),this.nextCorr=1n,this.readLoop($.sock,Z),this.connectionEpoch}scheduleRestored($,Z){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===Z)this.enqueueConnectionState({state:"restored",epoch:Z},$)}).catch((X)=>{if(z===this.restoredDebounceToken&&!this.closeStarted)console.warn("SubcProvider restored debounce timer failed",X)})}cancelRestoredDebounce(){this.restoredDebounceToken+=1}enqueueConnectionState($,Z,z){if(!this.opts.onConnectionState)return;if(this.stateQueue.push({event:$,generation:Z,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:Z}=$;try{await this.opts.onConnectionState?.(Z),this.stateQueue.shift()}catch(z){if(Z.state==="restored"){console.warn("SubcProvider restored callback failed; retrying delivery",z),await I1();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 W$($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveHandle($){if(!this.isLiveHandle($))throw new H2($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let z=new T("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.handleUnexpectedDrop(this.sock,this.generation,z),z}let Z=this.nextCorr;return this.nextCorr+=1n,Z}failFatal($){if(!this.closedErr)this.closedErr=$;this.closeStarted=!0,this.cancelRestoredDebounce(),this.abortAllInflight(),this.sock.close(),this.finishClosed()}finishClosed(){this.resolveClosed()}}function g$($,Z){return`${$.channel}:${$.epoch}:${Z}`}function U1($){try{let Z=l$($.body);return new T(Z.message??"subc error",Z.code,Z.code==="stale_route_epoch"||Z.code==="unknown_channel"?"not_sent":"terminal")}catch{return new T(o3.from($.body).toString("utf8")||"subc error")}}function D1($){let Z=$.launchNonce??process.env[P1];return Z&&Z.length>0?Z:void 0}var P1="SUBC_LAUNCH_NONCE";function O1($){return{connectionFile:$.connectionFile,manifest:$.manifest,handler:$.handler,health:$.health??(()=>({status:"ok"})),handshakeTimeoutMs:$.handshakeTimeoutMs,controlOps:$.controlOps,onBind:$.onBind,onBound:$.onBound,onRouteGone:$.onRouteGone,reconnectBackoff:$.reconnectBackoff??m$,sleep:$.sleep??((Z)=>new Promise((z)=>setTimeout(z,Z))),restoredDebounceMs:$.restoredDebounceMs??N1,onConnectionState:$.onConnectionState,launchNonce:$.launchNonce}}function M1($){if($===null)return null;let Z=new Set($??[]);return Z.add(t3),[...Z]}function _1($){let Z=D1($);return m(L.Hello,X2(),0,0,n6,u$({manifest:T1($.manifest),protocol_ver:u,control_ops:M1($.controlOps),...Z?{launch_nonce:Z}:{}}))}function x1($){if($ instanceof T)return $.code==="duplicate_module_id";if($ instanceof V2||$ instanceof r)return!0;if($ instanceof Z2||$ instanceof D2)return!0;if($ instanceof g)return!0;if($ instanceof f)return!1;let Z=F1($);return Z==="ECONNREFUSED"||Z==="ECONNRESET"||Z==="EPIPE"||Z==="ETIMEDOUT"||Z==="ENOENT"}function F1($){if(typeof $==="object"&&$!==null&&"code"in $){let Z=$.code;if(typeof Z==="string")return Z}return}async function I1(){await new Promise(($)=>setTimeout($,0))}function X2(){return l(!1,k.Passive,!1)}async function a3($,Z){await z2($,$2(Z),Date.now()+s6)}async function R1($,Z){let z=await $.readFrame(Z,Z);switch(z.header.ty){case L.HelloAck:{let X=l$(z.body);if(X.negotiated_ver!==u)throw new T(`subc negotiated protocol ${X.negotiated_ver}; expected exactly ${u}`,"unsupported_version");return X}case L.Error:{let X=l$(z.body);throw new T(`subc rejected HELLO: ${X.code??"unknown"} — ${X.message??"subc error"}`,X.code)}default:throw new T(`unexpected frame ${L[z.header.ty]} awaiting HELLO_ACK`)}}function u$($){return new Uint8Array(o3.from(JSON.stringify($),"utf8"))}function l$($){return JSON.parse(o3.from($).toString("utf8"))}function c6($,Z){if(typeof $!=="number"||!Number.isInteger($))throw new T(`route.bind ${Z} must be an integer`);return $}function A1($){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 T1($){return{module_id:$.module_id,module_version:$.module_version,protocol_ver:$.protocol_ver,trust_tier:$.trust_tier,provides:$.provides.map(b1),consumes:$.consumes.map(C1),bindings:{storage:{kind:$.bindings.storage.kind,scope:$.bindings.storage.scope,owns_schema:$.bindings.storage.owns_schema},vault_grants:$.bindings.vault_grants.map((Z)=>({secret:Z.secret,reason:Z.reason})),identity:{requires:[...$.bindings.identity.requires],optional:[...$.bindings.identity.optional]}}}}function b1($){switch($.role){case"tool_provider":return{role:"tool_provider",tools:$.tools.map((Z)=>({name:Z.name,...Z.description===void 0?{}:{description:Z.description},execution_mode:Z.execution_mode,schema:Z.schema})),identity_scope:[...$.identity_scope],concurrency:$.concurrency,emits_push:$.emits_push,sub_supervises:$.sub_supervises};case"pipeline_stage":return{role:"pipeline_stage",stage:$.stage,applies_to:{provider:$.applies_to.provider,model:$.applies_to.model},interface:$.interface,declares_frozen_floor:$.declares_frozen_floor,needs_signals:[...$.needs_signals],conformance_class:$.conformance_class};case"management_surface":return{role:"management_surface",operations:$.operations.map((Z)=>({name:Z.name,kind:Z.kind})),config_schema:$.config_schema,observability:$.observability.map((Z)=>({name:Z.name,kind:Z.kind})),identity_scope:[...$.identity_scope],concurrency:$.concurrency};case"internal_service":return{role:"internal_service",service_id:$.service_id,transport:$.transport,agent_facing:$.agent_facing,operations:[...$.operations]}}}function C1($){switch($.role){case"tool_client":return{role:"tool_client",of:[...$.of]};case"llm_client":return{role:"llm_client",via:$.via,auth:$.auth};case"service_client":return{role:"service_client",of:[...$.of]}}}var d$="subc-connection.json",y1="subc-",v1=".connection.json";function a6(){let $=process.env.HOME;return $?V$($,".local","share","cortexkit","run",d$):void 0}function h1(){let $=process.env.XDG_RUNTIME_DIR?.trim();if($)return V$($,d$);let Z=a6();if(Z)return Z;return V$(E1().homedir,".local","share","cortexkit","run",d$)}function m1(){let $=process.env.XDG_RUNTIME_DIR?.trim();if($){let X=V$($,d$);if(r3(X))return X}let Z=a6();if(Z&&r3(Z))return Z;let z=g1(f1());return z.length===1?z[0]:void 0}function e3(){return m1()??h1()}function i$($){return $?.trim()||process.env.CLAUSTRUM_SUBC_CONNECTION?.trim()||e3()}function r3($){try{return w1($).isFile()}catch{return!1}}function g1($){let Z;try{Z=S1($)}catch{return[]}let z=[];for(let X of Z){if(typeof X!=="string")continue;if(!X.startsWith(y1)||!X.endsWith(v1))continue;let J=V$($,X);if(r3(J))z.push(J)}return z.sort(),z}async function p1($){let Z;try{Z=await k1($,"utf8")}catch{return}try{let z=JSON.parse(Z);return typeof z.wire_version==="number"?z.wire_version:void 0}catch{return}}async function t6($){let Z=i$($),z;try{z=await S2(Z)}catch(J){if(J.code==="ENOENT")return{status:"absent",path:Z};return{status:"malformed",path:Z,reason:"connection file could not be read or validated"}}let X=await p1(Z);return{status:"available",schema:z.schema,wireVersion:X??u,endpoints:z.endpoints}}import{createHash as u1}from"node:crypto";import{existsSync as l1,realpathSync as o6}from"node:fs";import{dirname as d1,relative as i1,resolve as c1}from"node:path";function r6($){let Z=$,z;try{z=o6(Z)}catch(X){if(X.code!=="ENOENT")throw X;let J=Z;while(!l1(J)){let G=d1(J);if(G===J)break;J=G}z=c1(o6(J),i1(J,Z))}return u1("sha256").update(z).digest("hex")}function $4($,Z){return{project_root:$,harness:"opencode",session:`store-${r6(Z)}`}}var e6=["transient","permanent","auth_required","context_overflow"];class u2 extends Error{code;action;["class"];constructor($,Z,z){super(`Claustrum credential request failed: ${$}`);this.code=$,this.action=z,this.name="ClaustrumCredentialError",this.class=Z}}function p2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function $8($){switch($){case"permanent":return"gone";case"auth_required":return"reauth";case"context_overflow":return"reduce_and_retry";case"transient":return"retry"}}function x($,Z="invalid_response",z=(X)=>console.warn(X)){let X=p2($)&&p2($.result)?$.result:void 0,J=X&&p2(X.error)?X.error:void 0,G=J?.class,Q=J?.code,Y=typeof G==="string"&&e6.includes(G),W=typeof Q==="string",j=Y&&W?G:"transient";if(typeof G!=="string")z("unknown");else if(!Y)z(G);return new u2(W?Q:Z,j,$8(j))}function k2($){return p2($)&&p2($.result)&&p2($.result.error)}var Z8="claustrum",a1=60000;function s($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function z4($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0?$:void 0}function q2($){return $===void 0||typeof $==="string"}function z8($,Z){if(k2($))throw x($,"invalid_response",Z);let z=s($)&&s($.result)?$.result:void 0,X=z?.payload;if(!Array.isArray(X)||X.length===0||!X.every((q)=>typeof q==="number"&&Number.isInteger(q)&&q>=0&&q<=255))throw x($,"invalid_response",Z);let J=z4(z?.record_version);if(J===void 0)throw x($,"invalid_record_version",Z);let G=z?.expires_at_ms,Q=G===void 0||G===null?null:typeof G==="number"&&Number.isFinite(G)?G:void 0;if(Q===void 0)throw x($,"invalid_expiry",Z);let Y=z?.credential_id,W=z?.project_id,B=z?.account_id,j=z?.email,V=z?.org_name;if(!q2(Y)||!q2(W)||!q2(B)||!q2(j)||!q2(V))throw x($,"invalid_response",Z);return{material:new TextDecoder().decode(Uint8Array.from(X)),recordVersion:J,expiresAtMs:Q,credentialId:Y,projectId:W,accountId:B,email:j,orgName:V}}function t1($,Z){if(k2($))throw x($,"invalid_response",Z);let z=s($)&&s($.result)?$.result:void 0,X=z4(z?.record_version);if(typeof z?.ready!=="boolean"||z?.last_error_code!==void 0&&z?.last_error_code!==null&&typeof z?.last_error_code!=="string"||typeof z?.lease_held!=="boolean"||X===void 0||z?.stale_pending!==void 0&&typeof z.stale_pending!=="boolean")throw x($,"invalid_status",Z);return{ready:z.ready,lastErrorCode:z.last_error_code??null,leaseHeld:z.lease_held,recordVersion:X,...z.stale_pending===void 0?{}:{stalePending:z.stale_pending}}}class c${#z;#J;#B;#Y;#G;#$;#X=null;#Q=0;#W=!1;constructor($,Z,z,X,J,G){this.#z=$,this.#J=Z,this.#B=z,this.#Y=X,this.#G=J,this.#$=G}static async connect($={}){let Z=i$($.connectionFile),z=$.connector??((G)=>w2.connect(G)),X=$.identity??$4($.projectRoot??process.cwd(),$.storagePath??process.cwd()),J=await z({connectionFile:Z,handshakeTimeoutMs:$.handshakeTimeoutMs});return new c$(J,z,Z,$.handshakeTimeoutMs,X,$.logger??((G)=>console.warn(G)))}async getCredential($,Z){let z=await this.#Z("credential.get",{handle:$,min_ttl_ms:Z,force_refresh:!1});return z8(z,this.#$)}async statusCredential($){let Z=await this.#Z("credential.status",{handle:$});return t1(Z,this.#$)}async reportAuthFailure($){let Z=await this.#Z("credential.report_auth_failure",{handle:$.handle,provider_status:$.providerStatus,record_version:$.recordVersion,reporter_source:$.reporterSource});if(k2(Z))throw x(Z,"invalid_response",this.#$);if((s(Z)&&s(Z.result)?Z.result:void 0)?.accepted!==!0)throw x(Z,"invalid_response",this.#$)}async listScoped($){let Z=await this.#Z("credential.list_scoped",$===void 0?{}:{enrollment_token:$});return o1(Z,this.#$)}async getScoped($){let Z=await this.#Z("credential.get_scoped",{credential_id:$.credentialId,enrollment_token:$.enrollmentToken,min_ttl_ms:$.minTtlMs});return z8(Z,this.#$)}async reportAuthFailureScoped($){let Z=await this.#Z("credential.report_auth_failure",{credential_id:$.credentialId,enrollment_token:$.enrollmentToken,provider_status:$.providerStatus,record_version:$.recordVersion,reporter_source:$.reporterSource});if(k2(Z))throw x(Z,"invalid_response",this.#$);if((s(Z)&&s(Z.result)?Z.result:void 0)?.accepted!==!0)throw x(Z,"invalid_response",this.#$)}async enrollPropose($){let Z=await this.#Z("auth.enroll_propose",{proposed_name:$.name,request_secret_hash:$.requestSecretHash}),X=Z4(Z,this.#$).request_id;if(typeof X!=="string"||X.length===0)throw x(Z,"invalid_response",this.#$);return{requestId:X}}async enrollPoll($){let Z=await this.#Z("auth.enroll_poll",{request_id:$.requestId,request_secret:$.requestSecret});return r1(Z,this.#$)}async enrollRotate($){let Z=await this.#Z("auth.enroll_rotate",{token:$.token,expected_token_generation:$.expectedTokenGeneration}),z=Z4(Z,this.#$),X=z.token,J=z.token_generation;if(typeof X!=="string"||X.length===0||typeof J!=="number")throw x(Z,"invalid_response",this.#$);return{token:X,tokenGeneration:J}}close(){this.#W=!0,this.#z.close()}async#Z($,Z){try{return await this.#z.call(Z8,$,Z,{identity:this.#G,consumerIdentity:null})}catch(z){if(this.#V(z)){try{await this.#H()}catch(X){throw this.#j(X)}try{return await this.#z.call(Z8,$,Z,{identity:this.#G,consumerIdentity:null})}catch(X){throw this.#j(X)}}throw this.#j(z)}}#j($){if($ instanceof u2)return $;let Z=$ instanceof E&&$.code?$.code:"transport_error";return new u2(Z,"transient","retry")}#V($){return!this.#W&&$ instanceof E&&$.kind==="terminal"&&$.code!=="missing_identity"&&$.code!=="invalid_control_body"}async#H(){if(this.#W)throw Error("Claustrum client is closed");if(this.#X){await this.#X;return}let $=Date.now();if($<this.#Q)throw Error("Claustrum client reconnect is backed off");this.#Q=$+a1,this.#X=this.#J({connectionFile:this.#B,handshakeTimeoutMs:this.#Y}).then((Z)=>{if(this.#W)throw Z.close(),Error("Claustrum client is closed");let z=this.#z;this.#z=Z,z.close()}).finally(()=>{this.#X=null}),await this.#X}}function o1($,Z){if(k2($))throw x($,"invalid_response",Z);let z=s($)&&s($.result)?$.result:void 0,X=z?.credentials;if(!Array.isArray(X))throw x($,"invalid_response",Z);let J=z?.view;if(typeof J!=="string"||J.length===0)throw x($,"invalid_response",Z);return{rows:X.map((Q)=>{if(!s(Q))throw x($,"invalid_response",Z);let Y=z4(Q.record_version);if(Y===void 0)throw x($,"invalid_record_version",Z);let W=(j)=>{if(!Array.isArray(j)||!j.every((V)=>typeof V==="string"))throw x($,"invalid_response",Z);return j};if(typeof Q.id!=="string"||typeof Q.type!=="string"||typeof Q.state!=="string")throw x($,"invalid_response",Z);let B=Q.created_at_ms===void 0||Q.created_at_ms===null?null:typeof Q.created_at_ms==="number"&&Number.isFinite(Q.created_at_ms)?Q.created_at_ms:void 0;if(B===void 0)throw x($,"invalid_response",Z);if(!q2(Q.refresh_adapter))throw x($,"invalid_response",Z);if(!q2(Q.account_id)||!q2(Q.email)||!q2(Q.org_name))throw x($,"invalid_response",Z);return{id:Q.id,categories:W(Q.categories),credentialType:Q.type,serves:W(Q.serves),state:Q.state,refreshAdapter:Q.refresh_adapter,recordVersion:Y,operations:W(Q.operations),createdAtMs:B,accountId:Q.account_id,email:Q.email,orgName:Q.org_name}}),view:J}}function Z4($,Z){if(k2($))throw x($,"invalid_response",Z);let z=s($)&&s($.result)?$.result:void 0;if(z===void 0)throw x($,"invalid_response",Z);return z}function r1($,Z){let z=Z4($,Z),X=z.status;if(X==="pending")return{status:"pending"};if(X==="denied")return{status:"denied"};if(X!=="approved")throw x($,"invalid_response",Z);let{name:J,token:G,token_generation:Q}=z;if(typeof J!=="string"||typeof G!=="string"||G.length===0||typeof Q!=="number"||!Number.isInteger(Q))throw x($,"invalid_response",Z);return{status:"approved",name:J,token:G,tokenGeneration:Q}}import{tmpdir as e1}from"node:os";import{join as $7}from"node:path";var Z7=["error","warn","info","debug","trace"];function z7(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??$7(e1(),"opencode-openai-auth.log")}function X7(){let $=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;return $&&Z7.includes($)?$:void 0}V4({file:z7,level:X7});process.on("exit",s2);
|
|
211
|
-
export{e3 as L,t6 as M,c$ as N,G8 as O,G4 as P,Q4 as Q,J2 as R,f2 as S,V7 as T,G2 as U,Z3 as V,T8 as W,q4 as X,K4 as Y,n as Z,L4 as _,U4 as $,u8 as aa,o2 as ba,r2 as ca,N$ as da,d8 as ea,F2 as fa,n8 as ga,a8 as ha,t8 as ia,o8 as ja,D4 as ka,P4 as la,I9 as ma,y as na,G$ as oa,UZ as pa,D5 as qa,j2 as ra,DZ as sa,J$ as ta,E4 as ua,s4 as va,O5 as wa,T2 as xa,n4 as ya,O4 as za,Y9 as Aa,W2 as Ba,b7 as Ca,V3 as Da,h2 as Ea,g7 as Fa,K2 as Ga,h as Ha,$Z as Ia,U3 as Ja,v4 as Ka,u9 as La,S as Ma,zZ as Na,U2 as Oa,XZ as Pa,d4 as Qa,i4 as Ra,JZ as Sa,GZ as Ta,QZ as Ua,R3 as Va,A3 as Wa,L5 as Xa,o4 as Ya,bZ as Za,CZ as _a,SZ as $a,wZ as ab,kZ as bb,fZ as cb,EZ as db,T$ as eb,yZ as fb,vZ as gb,lZ as hb};
|