@cortexkit/opencode-openai-auth 1.9.5 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +8 -8
- package/dist/{codex-request-CZ16goZ6.d.ts → codex-request-BLzSBegI.d.ts} +4 -0
- package/dist/{index-4gnwkw3a.js → index-17rh67pr.js} +1 -1
- package/dist/{index-npj40h62.js → index-29ztc0ay.js} +2 -2
- package/dist/{index-f1cqptqa.js → index-361xxyg2.js} +2 -2
- package/dist/index-3p1tc2e2.js +91 -0
- package/dist/index-3r9thx6n.js +76 -0
- package/dist/{index-mcy24ej8.js → index-95z5dpe1.js} +2 -2
- package/dist/index-dcyhv7eh.js +8 -0
- package/dist/{index-y4j7y8b8.js → index-dkhy2peg.js} +1 -1
- package/dist/{index-7qxa018z.js → index-fd3f8vw2.js} +2 -2
- package/dist/{index-s2vrkdj4.js → index-mf3dqvbn.js} +2 -2
- package/dist/{index-cf0mrvqj.js → index-mkda7acs.js} +1 -1
- package/dist/{index-s52j2h64.js → index-w37815v4.js} +1 -1
- package/dist/index-ya96m6wr.js +64 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-djwdynff.js → token-pd3t5f20.js} +1 -1
- package/dist/token-util-807rzwws.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.d.ts +1 -2
- package/dist/v2/server.js +3 -3
- package/package.json +6 -6
- package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +32 -8
- package/src/tui-compiled/raw/shared/5f8cc863449a6c85-limits-namespace.js +19 -7
- package/src/tui-compiled/raw/shared/92e38944b51b2405-file-read-cache.js +10 -5
- package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +1 -1
- package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +47 -3
- package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +32 -8
- package/src/tui-compiled/runtime/shared/5f8cc863449a6c85-limits-namespace.js +19 -7
- package/src/tui-compiled/runtime/shared/92e38944b51b2405-file-read-cache.js +10 -5
- package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +1 -1
- package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +47 -3
- package/dist/index-1nrre3d8.js +0 -91
- package/dist/index-41yn5c02.js +0 -8
- package/dist/index-8rj2xddq.js +0 -63
- package/dist/index-h3vtzckv.js +0 -76
- package/dist/token-util-0xt1ws82.js +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { _ as parseJwtClaims, a as RESPONSES_LITE_MODELS, g as extractAccountIdFromClaims, h as TokenResponse, l as ResetTargetIdentity, m as IdTokenClaims, n as CODEX_VERSION, o as RuntimeLayoutOptions, s as PoolLifecycleDeps, t as CODEX_USER_AGENT, u as OpenAiVault, v as AccountPaths } from "./codex-request-
|
|
1
|
+
import { _ as parseJwtClaims, a as RESPONSES_LITE_MODELS, g as extractAccountIdFromClaims, h as TokenResponse, l as ResetTargetIdentity, m as IdTokenClaims, n as CODEX_VERSION, o as RuntimeLayoutOptions, s as PoolLifecycleDeps, t as CODEX_USER_AGENT, u as OpenAiVault, v as AccountPaths } from "./codex-request-BLzSBegI.js";
|
|
2
2
|
import { S as SidebarState, y as SidebarMachineState } from "./sidebar-state-CrRiE9hw.js";
|
|
3
3
|
import { Hooks, Plugin, PluginInput } from "@opencode-ai/plugin";
|
|
4
4
|
type QuotaWindowName = string;
|
|
@@ -331,6 +331,7 @@ type AccountStorage = {
|
|
|
331
331
|
};
|
|
332
332
|
routing?: {
|
|
333
333
|
mode?: RoutingMode;
|
|
334
|
+
maxSameAccountWait?: 0 | 15 | 'max';
|
|
334
335
|
};
|
|
335
336
|
fallbackOn?: number[];
|
|
336
337
|
refresh?: {
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as
|
|
1
|
+
import{$ as w,K as f,L as g,M as h,N as i,O as j,P as k,Q as l,R as m,S as n,T as o,U as p,V as q,W as r,X as s,Y as t,Z as u,_ as v,aa as x,ba as y,ca as z,da as A,ea as B,fa as C,ga as D,ha as E,ia as F,j as c,ja as G,k as d,l as e}from"./index-ya96m6wr.js";import"./index-3r9thx6n.js";import"./index-fd3f8vw2.js";import{Jd as a,Kd as b}from"./index-3p1tc2e2.js";import"./index-dcyhv7eh.js";import"./index-361xxyg2.js";import"./index-29ztc0ay.js";import"./index-mf3dqvbn.js";import"./index-95z5dpe1.js";import"./index-dkhy2peg.js";import"./index-mkda7acs.js";export{D as rewriteResponsesLiteBody,B as resolveSidebarSessionId,s as poolResetTarget,a as parseJwtClaims,y as mergePushedQuotaMetadata,l as getMainRefreshLockName,x as findCachekeepFallbackAccount,b as extractAccountIdFromClaims,G as default,t as createResetTargetResolver,j as codexOAuthModelVariantSource,h as codexOAuthModelListed,i as codexOAuthModelLimit,A as buildSidebarState,z as buildSidebarMachineState,u as buildResetRedemptionDeps,p as __resetBootQuotaSeedForTest,v as __menuContextForTest,o as __bootQuotaSeedPromiseForTest,r as ResetTargetResolutionError,c as RESPONSES_LITE_MODELS,w as POOL_MIGRATION_ENABLED,F as OpenAIAuthPlugin,C as MID_CONVERSATION_EFFORT_MODELS,m as MAIN_REFRESH_LOCK_TTL_MS,n as MAIN_REFRESH_LEASE_TTL_MS,k as EMPTY_BEARER_MESSAGE,g as DISALLOWED_MODELS,E as CodexAuthPlugin,d as CODEX_VERSION,e as CODEX_USER_AGENT,q as AuthPersistError,f as ALLOWED_MODELS};
|
package/dist/rpc/port-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{uf as b,vf as c}from"../index-361xxyg2.js";import{zf as a}from"../index-29ztc0ay.js";import"../index-95z5dpe1.js";import"../index-dkhy2peg.js";import"../index-mkda7acs.js";export{b as writePortFile,c as isOpenaiRpcStateDir,a as discoverPortFile};
|
package/dist/rpc/protocol.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Nf as b}from"../index-mf3dqvbn.js";import"../index-95z5dpe1.js";import"../index-mkda7acs.js";export{b as isNotifyPayload};
|
package/dist/rpc/rpc-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Af as F,Bf as f}from"../index-29ztc0ay.js";import"../index-95z5dpe1.js";import"../index-mkda7acs.js";function y(r,s,v){return f(r,s,v)}export{y as createRpcClient,F as DEFAULT_RPC_TIMEOUT_MS};
|
package/dist/rpc/rpc-dir.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{$f as a,ag as b,bg as c,cg as d}from"../index-dkhy2peg.js";import"../index-mkda7acs.js";export{a as tmpdir,d as resolveRpcDir,c as getRpcDir,b as RPC_DIRECTORY_PREFIX};
|
package/dist/sidebar-state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$
|
|
1
|
+
import{$c as M,Ac as l,Bc as m,Cc as n,Dc as o,Ec as p,Fc as q,Gc as r,Hc as s,Ic as t,Jc as u,Kc as v,Lc as w,Mc as x,Nc as y,Oc as z,Pc as A,Qc as B,Rc as C,Sc as D,Tc as E,Uc as F,Vc as G,Wc as H,Xc as I,Yc as J,Zc as K,_c as L,ad as N,bd as O,cd as P,dd as Q,ed as R,fd as S,gd as T,pc as a,qc as b,rc as c,sc as d,tc as e,uc as f,vc as g,wc as h,xc as i,yc as j,zc as k}from"./index-fd3f8vw2.js";import"./index-3p1tc2e2.js";import"./index-dcyhv7eh.js";import"./index-mf3dqvbn.js";import"./index-95z5dpe1.js";import"./index-mkda7acs.js";export{y as upsertSidebarActiveRouting,p as spendControlExhaustedResetAt,O as sidebarQuotaProjection,I as settleWithinBudget,w as setSidebarState,x as setSidebarMachineState,z as setSidebarLegacyRouting,e as setLegacySidebarStateFileForTest,C as resolveSidebarStickyAssignment,s as resolveSessionStickyAccount,t as resolveSessionSidebarRouting,N as resolveActiveAccount,A as removeSidebarActiveRouting,K as rememberStickyPin,v as pruneStickyAssignments,u as pruneActiveRouting,D as planSidebarStickyAssignmentFromSnapshot,B as planSidebarStickyAssignment,E as persistSidebarStickyAssignment,k as normalizeSidebarState,o as isUsableRoutingEntry,r as isQuotaExhausted,h as hashSidebarSessionId,i as getSidebarStateFile,l as getSidebarState,d as getPresentQuotaWindows,P as getCollapsedQuotaSummary,Q as getCollapsedAccountLines,c as formatWindowLabel,S as fitCollapsedLabel,q as exhaustedQuotaResetAt,G as drainSidebarWrites,R as displayWidth,J as createSidebarStateCache,M as createSidebarBookkeepingQueue,T as computeQuotaPacing,F as clearSidebarStickyAssignment,L as applyStickyPinOverlay,b as accountServesOnCredits,a as accountCreditsText,g as STICKY_ASSIGNMENT_MAX_ENTRIES,f as STICKY_ASSIGNMENT_MAX_AGE_MS,H as HOT_PATH_READ_BUDGET_MS,j as DEFAULT_SIDEBAR_STATE,n as ACTIVE_ROUTING_MAX_ENTRIES,m as ACTIVE_ROUTING_MAX_AGE_MS};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as U,b as V}from"./index-
|
|
1
|
+
import{a as U,b as V}from"./index-w37815v4.js";import{dg as R}from"./index-mkda7acs.js";var E=R((M,Q)=>{var{defineProperty:H,getOwnPropertyDescriptor:W,getOwnPropertyNames:X}=Object,Y=Object.prototype.hasOwnProperty,Z=(z,q)=>{for(var B in q)H(z,B,{get:q[B],enumerable:!0})},$=(z,q,B,F)=>{if(q&&typeof q==="object"||typeof q==="function"){for(let v of X(q))if(!Y.call(z,v)&&v!==B)H(z,v,{get:()=>q[v],enumerable:!(F=W(q,v))||F.enumerable})}return z},A=(z)=>$(H({},"__esModule",{value:!0}),z),L={};Z(L,{refreshToken:()=>D});Q.exports=A(L);var K=U(),G=V();async function D(z){let q=z?.project,B=z?.team;if(!q&&!B){let v=(0,G.findProjectInfo)();q=v.projectId,B=v.teamId}else if(!q||!B){let v=(0,G.findProjectInfo)();q=q??v.projectId,B=B??v.teamId}if(!q)throw new K.VercelOidcTokenError("Failed to refresh OIDC token: No project specified. Try re-linking your project with `vc link`");let F=(0,G.loadToken)(q);if(!F||(0,G.isExpired)((0,G.getTokenPayload)(F.token),z?.expirationBufferMs)){let v=await(0,G.getVercelToken)({expirationBufferMs:z?.expirationBufferMs});if(F=await(0,G.getVercelOidcToken)(v,q,B),!F)throw new K.VercelOidcTokenError("Failed to refresh OIDC token");(0,G.saveToken)(F,q)}process.env.VERCEL_OIDC_TOKEN=F.token;return}});export default E();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as a}from"./index-w37815v4.js";import"./index-mkda7acs.js";export default a();
|
package/dist/tui-preferences.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ff as h,mf as u,nf as P}from"./index-dcyhv7eh.js";import{Pf as M,Qf as R,Wf as S}from"./index-95z5dpe1.js";import"./index-mkda7acs.js";import{mkdir as Yq,writeFile as Vq}from"node:fs/promises";import{homedir as Wq}from"node:os";import{dirname as Dq,join as b}from"node:path";import{applyEdits as t,modify as r,parse as e}from"jsonc-parser";function qq(z){return z!==null&&typeof z==="object"&&!Array.isArray(z)}async function k(z){try{let q=[],H=e(await S(z,M),q,{allowTrailingComma:!0});return q.length===0&&qq(H)?H:{}}catch(q){if(q instanceof R&&q.code!=="ENOENT")throw q;return{}}}var zq=`// Shared preferences for TUI plugins.
|
|
2
2
|
// Plugins update individual keys in place and preserve comments.
|
|
3
3
|
{}
|
|
4
4
|
`;function g(z){let{file:q,pluginKey:H,beforeCommit:Q}=z,$={...P.preferences,timeoutMs:z.timeoutMs??P.preferences.timeoutMs},Z=Promise.resolve();async function X(U,j){await u(q,$,async(K)=>{let J;try{J=await S(q,M)}catch(G){if(G.code!=="ENOENT")throw G;J=""}if(J.trim()==="")J=zq;let B=t(J,r(J,[H,...U],j,{formattingOptions:{insertSpaces:!0,tabSize:2}}));await h(q,B,{serialize:(G)=>String(G),beforeRename:async()=>{await Q?.(),await K.assertOwned()}})})}return{queueTuiPreferenceUpdate(U,j){let K=[...U],J=structuredClone(j),B=Z.then(()=>X(K,J));return Z=B.catch(()=>{}),B}}}import{readFileSync as Hq,realpathSync as Qq,statSync as Xq,watch as Zq}from"node:fs";import{readFile as $q,stat as Bq}from"node:fs/promises";import{basename as p,dirname as s,join as Gq,resolve as Jq}from"node:path";import{clearTimeout as w,setTimeout as c}from"node:timers";function n(z){let q=Jq(z);if(M)return q;try{return Qq(q)}catch{let H=s(q);return H===q?q:Gq(n(H),p(q))}}function d(z){return z&&`${z.dev}:${z.ino}:${z.mtimeMs}:${z.size}`}function T(z,q,H={}){let Q=globalThis,$=Symbol.for("cortexkit.common-auth.tui-prefs.watchers.v1"),Z=Q[$]??new Map;Q[$]=Z;let X=n(z),U=Z.get(X);if(U)return U.subscribe(q);let j=p(X),K=M?(Y)=>S(Y):H.fs?.readFile??((Y)=>$q(Y,"utf8")),J=H.fs?.stat??Bq,B=null,G=null,x=null,C=null;if(!M)try{let Y=d((H.fs?.statSync??Xq)(X));C=(H.fs?.readFileSync??((V)=>Hq(V,"utf8")))(X),x=Y}catch{}let N=!1,L=new Set,E=Promise.resolve(),v=(Y)=>{return E=E.then(async()=>{if(N)return;let V=d(await J(X).catch(()=>null));if(!Y&&V===x)return;if(V===null){x=null;return}let I=await K(X).catch((W)=>{if(W instanceof R&&W.code!=="ENOENT")if(H.onError)H.onError(W);else process.emitWarning(W.message,W.name);return null});if(N)return;if(I===null)return;if(x=V,I===C)return;C=I;for(let W of[...L]){if(!L.has(W))continue;try{W.notify()}catch{}}}),E},i=()=>{if(N)return;if(B)w(B);B=c(()=>{B=null,v(!0)},150)},O=null;try{O=(H.watchDirectory??Zq)(s(X),(Y,V)=>{let I=V?.toString(),W=I===j||I?.startsWith(`${j}.`)&&I.endsWith(".tmp");if(I!=null&&!W)return;i()}),O.on("error",()=>{O?.close(),O=null})}catch{}let f=()=>{if(N||G)return;G=c(()=>{if(G=null,N)return;v(!1).finally(f)},1000),G.unref()},F={subscribe:(Y)=>{let V={notify:Y};return L.add(V),()=>{if(!L.delete(V)||L.size>0)return;if(N=!0,B)w(B);if(G)w(G);if(O?.close(),Z.get(X)===F)Z.delete(X)}}};return Z.set(X,F),f(),F.subscribe(q)}var Uq="OPENCODE_TUI_PREFERENCES_FILE",Iq="tui-preferences.jsonc";function m(){let z=process.env[Uq];if(z)return z;let q=process.env.OPENCODE_CONFIG_DIR||b(process.env.XDG_CONFIG_HOME||b(Wq(),".config"),"opencode");return b(q,Iq)}function _(z){return typeof z==="object"&&z!==null&&!Array.isArray(z)}function dq(){return k(m())}var Mq="openai-auth",Aq=160,l={forceToTop:!1,order:Aq,startCollapsed:!1,rememberCollapsed:!0,collapsed:null,pollMs:1500,refreshDebounceMs:200,header:{label:"OPENAI",showVersion:!0},sections:{quota:!0,fallbackAccounts:!0,routing:!0,health:!0,pacing:!0},appearance:{barWidth:10,barFilledChar:"█",barEmptyChar:"░",warnThreshold:50,errorThreshold:80}};function D(z,q){return typeof z==="boolean"?z:q}function A(z,q,H,Q){if(typeof z!=="number"||!Number.isFinite(z))return q;return Math.min(Math.max(Math.round(z),H),Q)}function jq(z,q,H){if(typeof z!=="string"||z.length===0)return q;return z.slice(0,H)}function o(z,q){if(typeof z!=="string")return q;return[...z][0]??q}function pq(z){let q=z[Mq];if(!_(q))return structuredClone(l);let H=l,Q=_(q.header)?q.header:{},$=_(q.sections)?q.sections:{},Z=_(q.appearance)?q.appearance:{},X=A(Z.warnThreshold,H.appearance.warnThreshold,0,99),U=Math.max(A(Z.errorThreshold,H.appearance.errorThreshold,0,100),Math.min(X+1,100));return{forceToTop:D(q.forceToTop,H.forceToTop),order:A(q.order,H.order,-1e4,1e4),startCollapsed:D(q.startCollapsed,H.startCollapsed),rememberCollapsed:D(q.rememberCollapsed,H.rememberCollapsed),collapsed:typeof q.collapsed==="boolean"?q.collapsed:null,pollMs:A(q.pollMs,H.pollMs,500,30000),refreshDebounceMs:A(q.refreshDebounceMs,H.refreshDebounceMs,50,5000),header:{label:jq(Q.label,H.header.label,20),showVersion:D(Q.showVersion,H.header.showVersion)},sections:{quota:D($.quota,H.sections.quota),fallbackAccounts:D($.fallbackAccounts,H.sections.fallbackAccounts),routing:D($.routing,H.sections.routing),health:D($.health,H.sections.health),pacing:D($.pacing,H.sections.pacing)},appearance:{barWidth:A(Z.barWidth,H.appearance.barWidth,4,40),barFilledChar:o(Z.barFilledChar,H.appearance.barFilledChar),barEmptyChar:o(Z.barEmptyChar,H.appearance.barEmptyChar),warnThreshold:X,errorThreshold:U}}}var Nq=-1e5;function sq(z,q,H){let Q=z[q];if(!_(Q))return H;if(Q.forceToTop===!0)return Nq+Object.keys(z).indexOf(q);return A(Q.order,H,-1e4,1e4)}var Kq=`// Shared preferences for opencode TUI plugins.
|
package/dist/v2/server.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { c as HostSlotAdapter, d as OpenAiVaultOptions, f as BeginAccountLoginOptions, i as CodexSessionMetadata, o as RuntimeLayoutOptions, p as BeginAccountLoginResult, r as CodexRequestRuntime, s as PoolLifecycleDeps, v as AccountPaths } from "../codex-request-
|
|
1
|
+
import { c as HostSlotAdapter, d as OpenAiVaultOptions, f as BeginAccountLoginOptions, i as CodexSessionMetadata, o as RuntimeLayoutOptions, p as BeginAccountLoginResult, r as CodexRequestRuntime, s as PoolLifecycleDeps, v as AccountPaths } from "../codex-request-BLzSBegI.js";
|
|
2
2
|
import { i as OpenDialogPayload, n as ApplyResult } from "../protocol-BZZtDn5h.js";
|
|
3
3
|
import { Plugin } from "@opencode/plugin";
|
|
4
|
-
import "@opencode/plugin/promise/session";
|
|
5
4
|
import "@opencode/plugin/promise/integration";
|
|
6
5
|
import "@opencode/plugin/promise/registration";
|
|
7
6
|
/** The turn a frame is sent in. */
|
package/dist/v2/server.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{c as
|
|
2
|
-
`)}:{event:
|
|
3
|
-
`)}}function E1($,Z){let z=new TextDecoder,G="",Y=(K)=>{let U=c0(K);if(!U)return;try{$(U)}catch(H){Z(H)}},Q=()=>{for(;;){let K=/\r?\n\r?\n/.exec(G);if(!K)return;let U=G.slice(0,K.index);G=G.slice(K.index+K[0].length),Y(U)}};return new TransformStream({transform(K,U){U.enqueue(K),G+=z.decode(K,{stream:!0}),Q()},flush(){if(G+=z.decode(),Q(),G.trim()!=="")Y(G);G=""}})}var Y$=512,C1=3621000,k2="x-common-auth-attempt",b2=($,Z)=>JSON.stringify([$,Z]),N2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function d0($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function i0($,Z){let z=$.getReader();return new ReadableStream({async pull(G){let Y;try{Y=await z.read()}catch(Q){Z({reason:"failed",message:Q instanceof Error?Q.message:String(Q)}),G.error(Q);return}if(Y.done)Z(),G.close();else G.enqueue(Y.value)},async cancel(G){Z({reason:"cancelled",...G===void 0?{}:{message:String(G)}}),await z.cancel(G)}})}function o2($,Z){for(let[z,G]of Object.entries(Z)){let Y=z.toLowerCase();for(let Q of Object.keys($))if(Q.toLowerCase()===Y)delete $[Q];if(G!==null)$[z]=G}}function a0($,Z){for(let[z,G]of Object.entries(Z))if(G===null)$.delete(z);else $.set(z,G)}async function O1($,Z,z={}){let{providerID:G}=Z,Y=z.gateOnPlaceholder,Q=(J)=>Y===void 0||Y.credential(J)===P2(G),K=z.logger,U=Math.max(1,z.maxRecords??Y$),H=z.hostRetryLimit??10,N=[...z.hostCredentials??[P2(G)],...Y?[P2(G)]:[]].filter((J)=>J!==""),V=new Map,P=new WeakMap,C=new Map,E=0,w=new Set,n=new Map,O=new Map,D=(J)=>{let j=O.get(J);return j?.ownedSeen===!0&&j.foreignSeen},U2=(J,j)=>{n.set(J,j);let W=O.get(J)??{ownedSeen:!1,foreignSeen:!1};if(j)W.ownedSeen=!0;else W.foreignSeen=!0;O.set(J,W)},G2=(J,j)=>{let W=Y?.refuseMisplaced,M=W?[...j].filter(([,b])=>b.includes(P2(G))):[],B=Q(j)&&(!W||M.length>0);if(W){if(M.length>0&&(M.length!==1||!B))throw U2(J.sessionID,!1),new V2({kind:"placement-refused",providerID:G,sessionID:J.sessionID,requestKind:J.kind,message:W(M[0]?.[0]??"")})}return U2(J.sessionID,B),B},I=!1,i=!1,H2=new Map,X2=0,$2=!1,X=new Map,F=(J,j)=>{try{K?.warn(J,j)}catch{}},T=(J)=>J instanceof Error?J.message:String(J),L=(J)=>J.excluded.clear(),g=(J)=>J.excluded.size===0?{}:{excluded:[...J.excluded]},x=(J,j,W)=>{if(!z.enforceRequestExclusion||J===void 0||!W.excluded.has(J))return!1;return F("opencode2 auth ignored a chooser result for a request-excluded account",{sessionID:j.sessionID,kind:j.kind,phase:j.phase,accountId:J}),!0},k=new Map,f=(J,j)=>{let W=(k.get(J)??Promise.resolve()).then(j),M=W.then(()=>{},()=>{});return k.set(J,M),M.then(()=>{if(k.get(J)===M)k.delete(J)}),W},S=(J,j)=>{let W=k.get(J);return W?W.then(()=>S(J,j)):j()},y=async(J)=>{try{await Z.dropChoice?.({...J.input,accountId:J.accountId})}catch(j){F("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:J.input.sessionID,error:T(j)})}},u=async(J)=>{try{await Z.dropSameAccountRetry?.({...J.input,accountId:J.accountId})}catch(j){F("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:J.input.sessionID,error:T(j)})}},a=async(J)=>{if(J.next)await y(J.next);if(J.sameAccount)await u(J.sameAccount)},J2=(J)=>{let j=C.get(J);if(C.delete(J),j)f(j.sessionID,()=>a(j))},r=async(J,j)=>{let W=H2.get(J);if(!W||W.size===0)return;await Promise.all([...W].map(async(M)=>{try{await M(j)}catch(B){F("opencode2 auth listener threw; the request is unaffected",{event:J,error:T(B)})}}))},Q2=async(J,j)=>{try{await Z.onAttemptEnd?.(J,j)}catch(W){F("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:J.attemptId,error:T(W)})}},p=(J,j)=>{if(J.ended||!J.attempt)return;let W={...J.status===void 0?{}:{status:J.status},outputStarted:J.outputStarted,...J.limit?{limit:J.limit.signal}:{},...j?{error:j}:{}};if(j)J.endError=j;if(j?.reason==="cancelled"||!j&&!J.limit&&(J.status===void 0||J.status<400))L(J.request);J.ended=Q2(J.attempt,W)},A=(J,j)=>p(J,{reason:"abandoned",message:j}),z2=(J)=>[...V.values()].filter((j)=>j.key===J),c=(J)=>z2(J).at(-1),m=(J)=>{if(V.delete(J.id),C.get(J.key)?.attemptId===J.id||!z2(J.key).length)J2(J.key)},j2=(J)=>{V.set(J.id,J);while(V.size>U){let j=V.values().next().value;if(j===void 0)break;A(j,"dropped to keep the record bound"),m(j)}},Y2=(J)=>J.accountId===void 0?void 0:{...J.scope,accountId:J.accountId},_=(J,j)=>new V2({kind:"no-account",providerID:G,sessionID:J.sessionID,requestKind:J.kind,...j===void 0?{}:{message:j}}),v=(J)=>{X.get(J)?.clear(),X.delete(J)},B2=async(J,j)=>{let W=()=>_(J,`${G} ${J.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if($2)throw W();let M=X.get(J.sessionID);if(!M)M=new Set,X.set(J.sessionID,M);let B={};M.add(B);let b=()=>{if(!M.has(B))throw W()};try{return await j(b)}finally{if(M.delete(B),M.size===0&&X.get(J.sessionID)===M)X.delete(J.sessionID)}},i2=(J,j)=>{for(let[W,M]of j)if(N.some((B)=>M.includes(B)))throw new V2({kind:"host-credential-on-wire",providerID:G,sessionID:J.sessionID,requestKind:J.kind,message:`${G} ${J.kind} request still carries the host's placeholder credential in ${W}; the adapter's account headers must replace it`})},l0=(J)=>{for(let j of z2(J))if(j.ended||!j.attempt)m(j);else if(j.transport==="ws"||j.judged)A(j,"a newer attempt of its session and kind began"),m(j)},a2=async(J,j,W,M)=>{let B=b2(J.sessionID,J.kind),{input:b,accountId:R,sameAccountRetry:q,request:o}=await S(J.sessionID,async()=>{W();let d=C.get(B);C.delete(B);let s=z2(B);if(d&&s.some((_2)=>_2.id!==d.attemptId&&_2.attempt&&!_2.ended))F("opencode2 auth bound a pending retry to an ambiguous concurrent request; keeping its exclusions",{sessionID:J.sessionID,kind:J.kind});if(!d){let _2=new Set(s.filter((W2)=>W2.attempt&&!W2.ended).map((W2)=>W2.request));for(let W2 of s)if(!_2.has(W2.request))L(W2.request)}let t=d?.request??{excluded:new Set},C2=d?.accountId??c(B)?.accountId;l0(B);let h=d?.next,e=d?.sameAccount,T2=e!==void 0&&e.input.modelID===J.modelID&&e.input.agent===J.agent,l=h!==void 0&&h.input.modelID===J.modelID&&h.input.agent===J.agent,O2=d?.wake,x2={...J,phase:"request",...g(t),...C2===void 0?{}:{previousAccountId:C2},...d?.rerouteFrom?{rerouteFrom:d.rerouteFrom}:{},...O2===void 0?{}:{wake:O2,hostAttempt:h?.input.hostAttempt}};if(h&&(!l||O2!==void 0))await f(J.sessionID,()=>y(h)),W();if(e&&!T2)await f(J.sessionID,()=>u(e)),W();let Z2=T2?e.accountId:l&&O2===void 0?h.accountId:await Z.chooseAccount(x2),L2=typeof Z2==="string"?Z2:void 0;if(x(L2,x2,t)){let _2=L2;if(T2&&e)await f(J.sessionID,()=>u(e));else if(_2!==void 0)await f(J.sessionID,()=>y(l&&h?h:{accountId:_2,input:x2}));L2=void 0,W()}return{input:x2,accountId:L2,sameAccountRetry:T2,request:t}});W();let E2={},R2;if(R!==void 0){let d=await Z.accountHeaders({...J,accountId:R});if(W(),d0(d))E2=d.headers,R2=d.attempt;else E2=d}let n2=`attempt-${++X2}`,S2={id:n2,key:B,scope:J,request:o,accountId:R,headers:E2,attempt:R===void 0?void 0:{...J,accountId:R,attemptId:n2,transport:M,data:R2},...M===void 0?{}:{transport:M},outputStarted:!1,sameAccountRetry:q};if(j2(S2),S2.attempt)r("select",{...J,accountId:S2.attempt.accountId,hook:j,...b.previousAccountId===void 0?{}:{previousAccountId:b.previousAccountId},...b.rerouteFrom===void 0?{}:{rerouteFrom:b.rerouteFrom},handle:S2.attempt});return S2},s1=async(J,j,W,M,B)=>{let b=b2(J.sessionID,J.kind),R=M===void 0?void 0:V.get(M);if(R?.key!==b)R=void 0;if(!R){if(R=c(b),z2(b).filter((o)=>o.transport===void 0&&!o.ended).length>1&&!i)i=!0,F("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:J.sessionID,kind:J.kind})}if(!R||R.transport!==void 0||R.ended)R=await a2(J,j,B,W);else if(R.transport=W,R.attempt)R.attempt.transport=W;if(W==="ws"){for(let q of z2(b))if(q!==R&&q.transport==="ws")A(q,"a newer attempt of its session and kind went out over WebSocket")}return R},T1=async(J,j)=>{try{return await j()}catch(W){throw p(J,{reason:"failed",message:T(W)}),W}},r1=(J,j)=>{let W=z2(b2(J,j)).filter((M)=>M.transport==="ws").at(-1);return W?.attempt!==void 0&&!W.ended?W:void 0},L1=(J,j,W)=>{let M=Y2(J);if(!M||!J.attempt||J.limit)return;J.limit={signal:j,delivered:r("limit",{...M,via:W,limit:j,outputStarted:J.outputStarted,handle:J.attempt})}},t1=(J,j,W,M)=>{let B=Y2(J);if(!B||!J.attempt)return;r("quota",{...B,transport:j,...M===void 0?{}:{status:M},quota:W,handle:J.attempt})},e1=(J,j,W,M)=>{let B=J.attempt;if(!B)return;let b=Z.inspectEvent?.(M===void 0?{transport:j,data:W,attempt:B}:{transport:j,data:W,event:M,attempt:B});if(!b)return;if(b.quota!==void 0)t1(J,j,b.quota);if(b.outputStarted)J.outputStarted=!0;if(b.hostRetry==="veto")J.hostRetry="veto";if(b.limit)L1(J,b.limit,j);if(b.error!==void 0)p(J,{reason:"failed",message:b.error});else if(b.done)p(J)},u0=(J,j)=>{let W=J.attempt;if(!W||j.accountId===J.accountId)return;if(W.reboundFrom??=W.accountId,W.accountId=j.accountId,"data"in j)W.data=j.data;J.accountId=j.accountId},p0=(J)=>!J.attempt||J.endError!==void 0||J.status!==void 0&&J.status>=400,$$=(J)=>{let j=[...V.values()].filter((q)=>q.scope.sessionID===J),W=j.filter((q)=>q.limit&&!q.rerouted).at(-1);if(W)return W;let M=j.filter((q)=>q.scope.kind==="primary"),B=M.length>0?M:j;if(B.length<=1)return B[0];let b=B.filter((q)=>!q.judged&&p0(q)).at(-1);if(b)return b;let R=B.filter((q)=>q.attempt&&!q.ended);if(R.length>1)return"ambiguous";return R[0]??B.at(-1)},q2={providerID:G},A2=[];A2.push(await $.session.hook("model.request",(J)=>{if(Y)return;return B2(N2(J),async(j)=>{let W=await a2(N2(J),"model.request",j);if(j(),W.accountId===void 0)throw _(W.scope);o2(J.headers,{...W.headers,[k2]:W.id})})},q2)),A2.push(await $.session.hook("http.request",(J)=>{if(Y){if(!G2(N2(J),J.request.headers))return}return B2(N2(J),async(j)=>{let W=J.request.headers.get(k2)??void 0,M=Y?await a2(N2(J),"http.request",j,"http"):await s1(N2(J),"http.request","http",W,j);j();let B=Y2(M),b=M.attempt;if(!B||!b)throw _(M.scope);await T1(M,async()=>{let R=J.request;if(Z.rewriteRequest){if(W!==void 0){let E2=new Headers(R.headers);E2.delete(k2),R=new Request(R,{headers:E2})}R=await Z.rewriteRequest({...B,request:R,attempt:b})??R,j()}let q=new Headers(R.headers);q.delete(k2),a0(q,M.headers),i2(M.scope,q.entries());let o=new Request(R,{headers:q});P.set(o,M),J.request=o})})},q2)),A2.push(await $.session.hook("http.response",async(J)=>{let j=P.get(J.request);if(!j){if(Y)return;if(!I)I=!0,F("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:J.sessionID,kind:J.kind});return}let W=J.response;if(Z.answeredBy&&j.attempt){let q=j.attempt,o=await T1(j,async()=>Z.answeredBy?.({request:J.request,response:W,attempt:q}));if(o)u0(j,o)}let M=Y2(j),B=j.attempt;if(!M||!B)return;j.status=W.status;let b=Z.quotaFromHeaders?.(W.headers,W.status,B);if(b!==void 0)t1(j,"http",b,W.status);if(!W.ok&&Z.limitFromResponse){let q=await Z.limitFromResponse({status:W.status,headers:W.headers,body:()=>W.clone().text(),attempt:B});if(q)L1(j,q,"http")}if(!W.ok||!W.body)p(j);let R=W;if(W.body&&(Z.inspectEvent||Z.onAttemptEnd)){let q=W.body;if(Z.inspectEvent)q=q.pipeThrough(E1((o)=>e1(j,"http",o.data,o.event),(o)=>F("opencode2 auth event inspection threw",{error:T(o)})));R=new Response(i0(q,(o)=>p(j,o)),{status:W.status,statusText:W.statusText,headers:W.headers})}if(Z.rewriteResponse)R=await Z.rewriteResponse({...M,request:J.request,response:R,attempt:B})??R;if(Z.responseRetry){if(await Z.responseRetry({...M,request:J.request,response:R,attempt:B})==="veto")j.hostRetry="veto"}if(R!==W)J.response=R},q2)),A2.push(await $.session.hook("experimental.ws.handshake",(J)=>{if(Y){let j=b2(J.sessionID,J.kind);if(w.delete(j),!G2(N2(J),new Headers(J.headers)))return}return B2(N2(J),async(j)=>{let W;for(let R of Object.keys(J.headers)){if(R.toLowerCase()!==k2)continue;W??=J.headers[R],delete J.headers[R]}let M=Y?await a2(N2(J),"experimental.ws.handshake",j,"ws"):await s1(N2(J),"experimental.ws.handshake","ws",W,j);j();let B=Y2(M),b=M.attempt;if(!B||!b)throw _(M.scope);await T1(M,async()=>{if(!Y?.refuseMisplaced)o2(J.headers,M.headers);let R=Z.rewriteHandshakeURL?.({...B,url:J.url,attempt:b});if(R!==void 0)J.url=R;if(Y?.refuseMisplaced)o2(J.headers,M.headers);if(i2(M.scope,Object.entries(J.headers)),Y)w.add(M.key)})})},q2));let Z$=Z.rewriteWebSocketFrame?.bind(Z);if(Z$)A2.push(await $.session.hook("experimental.ws.send",async(J)=>{let j=N2(J);if(Y&&!w.has(b2(j.sessionID,j.kind)))return;let W=r1(j.sessionID,j.kind),M=await Z$({...j,attempt:W?.attempt,frame:J.frame});if(M!==void 0)J.frame=M},q2));A2.push(await $.session.hook("experimental.ws.receive",(J)=>{if(Y&&!w.has(b2(J.sessionID,J.kind)))return;let j=r1(J.sessionID,J.kind);if(!j)return;try{e1(j,"ws",J.frame)}catch(W){F("opencode2 auth frame inspection threw",{error:T(W)})}},q2)),A2.push(await $.session.hook("retry",async(J)=>{if(Y&&n.get(J.sessionID)!==!0)return;let j=J.decision,W=()=>r("retry",{sessionID:J.sessionID,attempt:J.attempt,reason:"host-decides",hostDecision:j,decision:j});if(D(J.sessionID)&&!Z.retrySameAccount){await W();return}let M=$$(J.sessionID);if(!M)return;if(M==="ambiguous"){await r("retry",{sessionID:J.sessionID,attempt:J.attempt,reason:"host-decides",hostDecision:j,decision:j});return}let B=M,b=()=>B.hostRetry==="veto";await B2(B.scope,async(R)=>{let q=R,o=Z.retrySameAccount?.bind(Z),E2=B.attempt;if(o&&E2&&!B.outputStarted&&(!b()||D(J.sessionID))&&!B.sameAccountRetry){if(B.ended)await B.ended;if(B.limit)await B.limit.delivered;let d=await f(B.scope.sessionID,async()=>{q();let s=E2.accountId,t=()=>V.has(B.id)&&B.accountId===s&&$$(J.sessionID)===B&&!B.outputStarted&&(!b()||D(J.sessionID))&&(!Y||n.get(J.sessionID)===!0);if(!t()||B.sameAccountRetry)return!1;B.sameAccountRetry=!0;let C2={...B.scope,accountId:s,error:J.error,attempt:J.attempt,...B.limit?{limit:B.limit.signal}:{}},h;try{h=await o(C2)}catch(l){F("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:J.sessionID,error:T(l)})}if(!h)return q(),!1;let e={accountId:h.accountId,input:C2};try{q()}catch(l){throw await u(e),l}if(!t()||h.accountId!==s)return await u(e),!1;let T2=C.get(B.key);if(C.delete(B.key),T2)await a(T2);try{q()}catch(l){throw await u(e),l}if(!t())return await u(e),!1;return C.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++E,accountId:s,sameAccount:e}),B.judged=!0,J.decision={retry:!0,delay:0},!0});if(q(),d){await r("retry",{sessionID:J.sessionID,accountId:B.accountId,kind:B.scope.kind,attempt:J.attempt,reason:"same-account",hostDecision:j,decision:J.decision,handle:B.attempt});return}}if(D(J.sessionID)){await W();return}B.judged=!0;let R2=B.attempt;if(R2&&!B.outputStarted){if(!B.limit){let d=Z.limitFromError?.(J.error,R2);if(d)L1(B,d,"error")}if(B.ended)await B.ended;if(B.limit)await B.limit.delivered}q();let{decision:n2,reason:S2}=await f(B.scope.sessionID,async()=>{if(q(),D(J.sessionID))return{decision:j,reason:"host-decides"};let d=C.get(B.key);if(C.delete(B.key),d)await a(d);if(q(),D(J.sessionID))return{decision:j,reason:"host-decides"};let s=j,t,C2,h,e;if(B.accountId===void 0||!R2)s={retry:!1},t="no-account";else if(B.outputStarted)s={retry:!1},t="output-started";else if(b())s={retry:!1},t="adapter-veto";else if(B.limit){let T2={accountId:B.accountId,limit:B.limit.signal},l,O2={...B.scope,phase:"retry",...g(B.request),hostAttempt:J.attempt,previousAccountId:B.accountId,rerouteFrom:T2};try{l=await Z.chooseAccount(O2)}catch(P1){F("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:B.scope.sessionID,error:T(P1)})}let x2=typeof l==="string"?l:typeof l==="object"&&("hold"in l)?B.accountId:void 0;if(x(x2,O2,B.request)){if(x2!==void 0)await y({accountId:x2,input:O2});l=void 0}let Z2=typeof l==="object"&&"hold"in l?l.hold:void 0,L2=typeof l==="object"&&"waitThenReselect"in l?l.waitThenReselect:void 0,_2=typeof l==="object"&&"hostRetry"in l?l.hostRetry:void 0,W2=typeof l==="string"?l:Z2?B.accountId:void 0;if(W2!==void 0)h={accountId:W2,input:O2};try{q()}catch(P1){if(h)await y(h);throw P1}if(D(J.sessionID)){if(h)await y(h);return{decision:j,reason:"host-decides"}}if(b()||_2==="veto"){if(h)await y(h);if(h=void 0,q(),D(J.sessionID))return{decision:j,reason:"host-decides"};B.hostRetry="veto",s={retry:!1},t="adapter-veto"}else if(!(H-J.attempt>=1)){if(h)await y(h);h=void 0,t="host-decides-last-account"}else if(L2&&Number.isFinite(L2.delayMs)&&L2.delayMs>=0&&L2.delayMs<=C1)s={retry:!0,delay:Math.ceil(L2.delayMs)},t="wait-then-reselect";else if(Z2&&Number.isFinite(Z2.delayMs)&&Z2.delayMs>=0&&Z2.delayMs<=C1){if(s={retry:!0,delay:Math.ceil(Z2.delayMs)},Z2.target!==void 0)e={target:Z2.target,...Z2.checkpoint===void 0?{}:{checkpoint:Z2.checkpoint},...Z2.kind===void 0?{}:{kind:Z2.kind}};t="hold"}else if(!Z2&&W2!==void 0&&W2!==B.accountId)B.rerouted=!0,B.request.excluded.add(B.accountId),C2=T2,s={retry:!0,delay:0},t="reroute";else{if(Z2&&h)await y(h),h=void 0;t="host-decides-last-account"}}else t="host-decides";if(J.decision=s,s.retry&&B.accountId!==void 0&&V.has(B.id))C.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++E,accountId:B.accountId,...C2===void 0?{}:{rerouteFrom:C2},...h===void 0?{}:{next:h},...e===void 0?{}:{wake:e}});else if(h)await y(h);if(!s.retry)L(B.request);return{decision:s,reason:t}});q(),await r("retry",{sessionID:J.sessionID,...B.accountId===void 0?{}:{accountId:B.accountId},kind:B.scope.kind,attempt:J.attempt,reason:S2,hostDecision:j,decision:n2,...R2===void 0?{}:{handle:R2}})})},q2));let J$=(J)=>{if(v(J),n.delete(J),!O.get(J)?.foreignSeen)O.delete(J);for(let j of w)if(JSON.parse(j)[0]===J)w.delete(j);for(let j of[...V.values()]){if(j.scope.sessionID!==J)continue;A(j,"its session was forgotten"),L(j.request),V.delete(j.id)}for(let[j,W]of C)if(W.sessionID===J)J2(j)},_1=new AbortController,z$=$.event;if(z$)(async()=>{try{for await(let J of z$.subscribe({signal:_1.signal}))if(J.type==="session.deleted")J$(J.data.sessionID);else if(J.type==="session.status"&&J.data.status.type==="idle"){let j=J.data.sessionID,W=++E;f(j,async()=>{for(let[M,B]of C)if(B.sessionID===j&&B.order<W)C.delete(M),L(B.request),await a(B)})}}catch(J){if(!_1.signal.aborted)F("opencode2 auth stopped listening for session deletion",{error:T(J)})}})();return{on(J,j){let W=H2.get(J);if(!W)W=new Set,H2.set(J,W);let M=j;return W.add(M),()=>{W.delete(M)}},accountFor(J,j){return c(b2(J,j))?.accountId},forgetSession:J$,get size(){return V.size},async dispose(){if($2)return;$2=!0;for(let J of X.keys())v(J);_1.abort();for(let J of V.values())A(J,"the installation was disposed");V.clear();for(let J of C.keys())J2(J);w.clear(),n.clear(),O.clear(),H2.clear(),await Promise.all(k.values()),await Promise.all(A2.map(async(J)=>{try{await J.dispose()}catch(j){F("opencode2 auth hook did not dispose cleanly",{error:T(j)})}}))}}}import{createHash as n0}from"node:crypto";var o0=1024,s0=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),X$=($)=>j$($,"user"),r0=($)=>s0($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function t0($){return n0("sha256").update(JSON.stringify($)).digest("hex")}class w2{runtime;maxSessions;#$=new Map;constructor($,Z=o0){this.runtime=$;this.maxSessions=Z}advance($,Z,z=this.runtime){let G=this.#$.get($),Y=Array.isArray(Z.input)?Z.input:[],Q=Y.filter(X$),K=Y.findLastIndex(X$),U=K<0?void 0:t0(Y[K]),H=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,N,V,P;if(H)N=Q.length>0,V=U??G?.fingerprint,P=G?.userCount===void 0?void 0:G.userCount+Q.length;else{V=U,P=Q.length;let E=K>=0&&K>Y.findLastIndex(r0),w=G!==void 0&&!G.completed&&G.fingerprint===V&&G.userCount===P;N=E&&!w}let C=N||!G?{turnID:(z?.uuid??D2)(),turnStartedAt:(z?.now??Date.now)()}:{turnID:G.turnID,turnStartedAt:G.turnStartedAt};return this.#Z($,{...C,completed:!1,fingerprint:V,userCount:P}),C}completed($){let Z=this.#$.get($);if(Z)this.#Z($,{...Z,completed:!0})}get($){return this.#$.get($)}forget($){this.#$.delete($)}#Z($,Z){this.#$.delete($),this.#$.set($,Z);while(this.#$.size>this.maxSessions){let z=this.#$.keys().next().value;if(z===void 0)break;this.#$.delete(z)}}}function A1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var B$=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function e0(){let $=globalThis;return $[B$]??=crypto.randomUUID(),$[B$]}class v2{runtime;store;sessions;frameTurns;installationID;constructor($,Z,z){this.runtime=$;this.store=z;this.installationID=Z??e0(),this.sessions=z?.sessions??new Map,this.frameTurns=z?.frameTurns??new w2}get($){let Z=this.runtime?.uuid??D2;if(this.store)return this.store.get($,Z);let z=this.sessions.get($);if(!z){let G=Z();z={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,z)}return z}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(s2(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var R1={version:V$,"user-agent":W$,originator:"codex_exec"};var $4=1024,Z4=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,t2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),N$=($)=>t2($)&&($.type==="message"||("role"in $))&&$.role==="user",F$=($)=>t2($)&&$.type==="configuration_update";class x1{http;#$=new Map;constructor($=new v2){this.http=$}apply($,Z,z){if(Z.kind!=="primary")return!1;let G=typeof $.model==="string"?$.model:"";if(!U$.has(G))return!1;if(Z4.test(G))return!1;let Y=t2($.reasoning)?$.reasoning:void 0,Q=typeof Y?.effort==="string"?Y.effort:void 0;if(!Q)return!1;let K=this.#$.get(Z.sessionID);if(K===void 0)return this.#Z(Z.sessionID,Q),!1;if(Q===K)return!1;let U=Array.isArray($.input)?$.input:void 0;if(!U||U.length===0)return!1;let H=U.findLastIndex(N$);if(H<0){if(z==="http")return!1;return $.reasoning={...Y,effort:K},!0}if($.reasoning={...Y,effort:K},!F$(U[H-1]))U.splice(H,0,{type:"configuration_update",reasoning:{effort:Q}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>$4){let z=this.#$.keys().next().value;if(z===void 0)break;this.#$.delete(z)}}}function s2($){try{let Z=JSON.parse($);return t2(Z)?Z:void 0}catch{return}}async function K$($,Z,z,G,Y=z.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let Q=await $.clone().text(),K=s2(Q);if(K)delete K.max_output_tokens;let U=new Headers($.headers),H=r2({rewriteLite:H$,init:{body:K?JSON.stringify(K):$.body===null?void 0:Q},headers:U,metadata:Y.get(Z.sessionID),installationID:Y.installationID,runtime:Y.runtime,websocket:!1,responsesLite:G,applyEffort:(N)=>{z.apply(N,Z,"http")}});return new Request($,{headers:U,body:H.init?.body})}function T$($,Z,z,G){let Y=G.sessions.get($.sessionID),Q=G.frameTurns.get($.sessionID);if(!Y||!Q)return;let K=A1(Y,Q),U=new Headers({"content-type":"application/json"});for(let N of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let V=z.get(N);if(V!==null)U.set(N,V)}r2({init:{body:$.bodyText},headers:U,metadata:K,installationID:G.installationID,runtime:G.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let H=new URL(Z);if(H.protocol==="wss:")H.protocol="https:";if(H.protocol==="ws:")H.protocol="http:";return new Request(H,{method:"POST",headers:U,body:$.bodyText})}function J4($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let z=Z.findIndex((G,Y)=>JSON.stringify(G)!==JSON.stringify($[Y]));return z>=0&&F$(Z[z])&&N$(Z[z+1])&&JSON.stringify(Z.slice(z+1))===JSON.stringify($.slice(z))}function L$($,Z,z){let G=s2($);if(G?.type!=="response.create")return;let Y=z.http.advanceFrame(Z.sessionID,G),Q=z.http.get(Z.sessionID);delete G.max_output_tokens;let K=r2({rewriteLite:()=>{},init:{body:JSON.stringify(G)},headers:new Headers,metadata:A1(Q,Y),installationID:z.http.installationID,runtime:z.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(H)=>{z.apply(H,Z,"ws")}}),U=s2(String(K.init?.body));if(!U)return;if(!J4(G.input,U.input)){if("input"in G)U.input=G.input;else delete U.input;return JSON.stringify(U)}return String(K.init?.body)}function z4($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function q1($,Z){let z=new URL($);if(z.origin!=="https://api.openai.com"&&z.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(z.pathname))return $;let G=new URL(`${z4(Z)}/responses`);if(G.search=z.search,z.protocol==="ws:"||z.protocol==="wss:")G.protocol=G.protocol==="https:"?"wss:":"ws:";return G.href}import{resolve as S1}from"node:path";var _$=Symbol.for("@cortexkit/openai-auth/opencode2-rate-limits/v1"),P$=globalThis,b1=P$[_$]??new Map;P$[_$]=b1;function M$($){let Z=b1.get($);if(!Z)Z=new Map,b1.set($,Z);return Z}function E$($){return M$(JSON.stringify(["pool",S1($.configPath),S1($.statePath)]))}function C$($){return M$(JSON.stringify(["vault",S1($)]))}import{resolve as O$}from"node:path";var G4=1024;class e2{accounts=new Map;limit;constructor($=G4){this.limit=Math.max(1,$)}record($,Z){this.accounts.delete($),this.accounts.set($,Z);while(this.accounts.size>this.limit){let z=this.accounts.keys().next().value;if(z===void 0)break;this.accounts.delete(z)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var A$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),R$=globalThis,D1=R$[A$]??new Map;R$[A$]=D1;function k1($){let Z=JSON.stringify([O$($.configPath),O$($.statePath)]),z=D1.get(Z);if(!z)z=new e2,D1.set(Z,z);return z}var F2="openai",Q4=60000,w1=1,Y4="request refused: no account with a usable credential",K2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function X4($){let Z=K2($)?$.counters:void 0,z=K2(Z)?Z.resetCredits:void 0,G=K2(z)?z.value:void 0;return typeof G==="number"&&Number.isFinite(G)?G:void 0}function g2($){try{return JSON.parse($)}catch{return}}function x$($){let Z=J1($);return Z?z1(Z):void 0}var j4=new Set(["usage_limit_reached","rate_limit_exceeded"]);function I1($,Z,z){return{reason:$.window,...z!==void 0?{status:z}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function B4($,Z){let z=Z1($);if(z){let Q=typeof $.status==="number"?$.status:void 0;return I1(z,Z,Q)}if($.type!=="response.failed"||!K2($.response))return;let G=$.response.failed;if(K2(G)&&typeof G.rate_limit_reached_type==="string")return{reason:G.rate_limit_reached_type};let Y=$.response.error;if(K2(Y)){let Q=typeof Y.code==="string"?Y.code:typeof Y.type==="string"?Y.type:void 0;if(Q&&j4.has(Q))return{reason:Q}}return}function V4($,Z){let z=g2($);if(!K2(z))return;let G=typeof z.type==="string"?z.type:void 0;if(G==="codex.rate_limits")return{quota:{snapshot:D$(z),complete:!0}};let Y=B4(z,Z);if(Y)return{limit:Y};if(G===void 0||G==="error")return;return o$(G)?void 0:{outputStarted:!0}}function W4($){let Z=!1;for(let z of $.keys())if(z.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:S$($),complete:b$($)}}function U4($){let Z=$.get("retry-after");if(Z===null)return;let z=Number(Z);return Number.isFinite(z)&&z>=0?z*1000:void 0}function r$($){let Z=new WeakMap,z=new WeakSet,{source:G,pins:Y}=$,Q=$.now??Date.now,K=$.log,U=$.vault,H=new x1($.codex),N=new Map,V=new Map,P=(X)=>`${X.sessionID}\x00${X.kind}\x00${X.accountId}`,C=U?.paths?.rosterPath,E=C?C$(C):new Map,w=$.sessionAccounts??new e2,n=new u$,O=(X,F,T)=>{let L=T?[]:s$(G.peek().rows,X,F,U?.identities()??new Set),g=(U?.routes()??[]).filter((x)=>x.kind==="oauth"&&w$(m2(x.quota),X,F));return[...L.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota,row:x})),...g.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota}))]},D=(X,F,T)=>{let L=g$(X,F,T),g=X.map((S)=>({id:S.id,kind:"oauth",...q$(S.quota)?{quota:S.quota}:{}})),x=X.flatMap((S)=>S.row?[S.row]:[]),k=new Set(X.filter((S)=>!S.row).map((S)=>S.id)),f=G.rateLimitMarks(x);for(let S of k){let y=E.get(S);if(y===void 0)continue;if(y<=T)E.delete(S);else f.set(S,y)}return{rows:g,now:T,rateLimitMarks:f,refreshBackoff:G.refreshBackoffFor(x),killswitch:L,requestPull:(S)=>k.has(S)?U?.requestReading(S):G.requestReading(S)}},U2=(X,F,T,L,g)=>{let x=p$({...X,placement:m$(F),mainId:g});if(x.kind==="block"){K?.debug("pool admission refused the request",{reason:x.block.reason});return}let k=x.order.filter((f)=>!T.has(f));if(L!==void 0&&k.includes(L))return L;return k[0]},G2=(X,F,T,L,g,x,k,f)=>{let S=new Map(F.map((A)=>[A.id,A.quota])),y={requestBytes:w1,reservePercent:(A)=>y$(T,A===v$?void 0:A),resetCredits:(A)=>X4(S.get(A))},u=y1(X),a=(A,z2)=>G1(k,{sessionId:L,requestBytes:w1,validPinnedAccountIds:X.rows.map((c)=>c.id).filter((c)=>!u.excluded.has(c)),excludeAccountIds:A,quotaCheckedAtByAccount:Object.fromEntries(X.rows.map((c)=>[c.id,u.projections.get(c.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(F.map((c)=>[c.id,c.identity])),select:(c)=>f?{accountId:f,source:"mode-fallback",quotaCheckedAt:u.projections.get(f)?.checkedAt}:c$(X,y,new Set(A),c),persist:z2},(c,m)=>k.set(c,m)),J2=[...g],r=a(J2,x);if(!r)return;let Q2=r.accountId,p=d$(X,y,Q2);if(p.kind==="none")return;if(p.kind==="move"){let A=a([...J2,Q2],x);if(A)return A.accountId;return p.reason==="killswitch"?void 0:Q2}if(p.kind==="detour")return a([...J2,Q2],!1)?.accountId;return Q2},H2={providerID:F2,dropChoice(X){let F=P(X);V.get(F)?.drop(),V.delete(F),N.delete(F)},chooseAccount:async(X)=>{let F=await U?.authority(),T=await $.storage(),L=F!==void 0&&F!=="local",g=()=>{throw new V2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:Q1})};if(L)await $.awaitVaultRoster?.();else{if(!(await G.current()).active){if(await $.slotPlaceholderWithoutMain?.())g();K?.warn("the account pool does not serve requests yet; refusing the request",{kind:X.kind});return}await G.prepareTokens(G.peek().rows,T)}let x=Q(),k=O(T,x,L),f=l$(D(k.filter((m)=>m.id!==X.rerouteFrom?.accountId),T,x));if(f)await f,x=Q(),k=O(T,x,L);let S=new Map(k.map((m)=>[m.id,m])),y=D(k,T,x),u=new Set(X.rerouteFrom?[X.rerouteFrom.accountId]:[]),a=T?.routing?.mode??"main-first",J2=X.kind==="primary",r=new Set,Q2,p,A,z2=!1,c=(m)=>{let j2=y1(y).projections.get(m)?.checkedAt,Y2=S.get(m)?.identity;return Y.reserve(X.sessionID,{accountId:m,inputBytes:w1,...j2!==void 0?{quotaCheckedAt:j2}:{},...Y2!==void 0?{wireIdentity:Y2}:{}})};try{for(;;){let m=new Set([...u,...r]);A=void 0,Q2=void 0;let j2=a!=="sticky-balanced";if(a==="sticky-balanced"){let _=new Map(Y.placementSnapshot(X.sessionID)),v=_.get(X.sessionID);if(j2=v===void 0,A=G2(y,k,T,X.sessionID,m,J2&&r.size===0,_),A!==void 0&&_.get(X.sessionID)!==v)Q2=_.get(X.sessionID)}if(A??=U2(y,a,m,J2?void 0:w.activeAccount(X.sessionID),L?a==="sticky-balanced"?null:h$(U?.routes()??[]):void 0),A===void 0||r.has(A)){if(u.size>0){let _=new Map(y.rateLimitMarks);for(let v of u)_.delete(v);y={...y,rateLimitMarks:_},u.clear();continue}if(y.rateLimitMarks.size>0){y={...y,rateLimitMarks:new Map};continue}A=void 0;break}if(J2&&a==="sticky-balanced")p=c(A);if(!z2){z2=!0;let _=await i$({vaultMode:L,fresh:j2,sessionId:X.sessionID,request:{modelId:X.modelID,kind:X.kind,retry:X.phase==="retry"||X.rerouteFrom!==void 0},routes:U?.routes()??[],routing:y,eligibleIds:k.filter((v)=>!m.has(v.id)).map((v)=>v.id)});if(_&&_!==A){if(p)Y.rollback(p);if(p=void 0,a==="sticky-balanced"){let v=new Map(Y.placementSnapshot(X.sessionID));A=G2(y,k,T,X.sessionID,m,J2,v,_)??A,Q2=v.get(X.sessionID)??Q2}else A=_;if(J2&&a==="sticky-balanced")p=c(A)}}let Y2=S.get(A)?.row;if(Y2){if(G.usableToken(Y2)!==void 0)break;K?.debug("pool row holds no usable token; choosing again",{accountId:A})}else{if(!U)break;let _=await U.authorize(A);if(_){N.set(P({...X,accountId:A}),_);break}K?.debug("the vault refused to serve an account; choosing again",{accountId:A})}if(p)Y.rollback(p);p=void 0,r.add(A)}if(A===void 0&&!L&&k.length===0&&await $.slotPlaceholderWithoutMain?.())g();if(A===void 0&&L&&U&&(k.length===0||r.size>0)){let m=r.size>0?"vault-refused":f$(U);throw K?.warn("vault mode: no vault account can serve; refusing the request",{cause:m}),new V2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:I$(m,U.name)})}if(A!==void 0){let m=A,j2=p,Y2=Q2,_=()=>{if(j2)Y.finish(j2,Y2);if(J2)w.record(X.sessionID,m),$.onRoute?.(X.sessionID,m,a)};if(X.phase==="retry")V.set(P({...X,accountId:A}),{commit:_,drop:()=>{if(j2)Y.rollback(j2)}}),p=void 0;else _();let v=K?.info;n.served(y,A,K&&v?{info:(B2,i2)=>v.call(K,B2,i2)}:void 0)}return K?.debug("pool account chosen",{kind:X.kind,accountId:A,mode:a,...X.rerouteFrom?{rerouteFrom:X.rerouteFrom.accountId}:{}}),A}finally{if(p)Y.rollback(p)}},accountHeaders:async(X)=>{let{accountId:F}=X,T=P(X),L=V.get(T);V.delete(T);let g=()=>{L?.commit()};try{let x=()=>new V2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:Y4}),k=U&&await U.authority()!=="local"?void 0:G.peek().rows.find((y)=>y.id===F);if(!k&&U){let y=P(X),u=N.get(y)??await U.authorize(F);if(N.delete(y),!u)throw K?.warn("the vault refused to serve an account; refusing the request",{accountId:F}),x();return g(),{headers:{...R1,"session-id":X.sessionID,authorization:`Bearer ${u.accessToken}`,"chatgpt-account-id":u.accountIdentity??x$(u.accessToken)??null},attempt:{kind:"vault",routeId:F,receipt:u}}}let f=k?G.usableToken(k):void 0;if(!k||!f)throw K?.warn("pool row holds no usable token; refusing the request",{accountId:F}),x();let S=k.identity??x$(f);return g(),{headers:{...R1,"session-id":X.sessionID,authorization:`Bearer ${f}`,"chatgpt-account-id":S??null},attempt:{kind:"pool",token:f,credentialEpoch:k.credentialEpoch}}}finally{L?.drop()}},async rewriteRequest({request:X,sessionID:F,kind:T}){let L=$.codexEndpoint?q1(X.url,$.codexEndpoint()):X.url,g=L===X.url?X:new Request(L,X);return await K$(g,{sessionID:F,kind:T},H,$.responsesLite?.()??!1)??g},rewriteHandshakeURL:({url:X})=>$.codexEndpoint?q1(X,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:X,sessionID:F,kind:T})=>L$(X,{sessionID:F,kind:T},H),quotaFromHeaders:(X,F,T)=>{if(T.data?.kind==="vault")U?.reportUsage(T.data.routeId,{headers:X},T.data.receipt);if(T.data?.kind==="vault"&&h2()&&F>=200&&F<300)Z.set(T,{status:F,headers:X});return W4(X)},async limitFromResponse({status:X,headers:F,body:T,attempt:L}){if(X<400)return;let g=g2(await T().catch(()=>"")),x=Z1({...K2(g)?g:{},status:X});if(L.data?.kind==="vault"&&h2())$1(L.sessionID,L.data.receipt,{status:X,headers:F,body:g,limit:x,quota:U?.routes().find((y)=>y.id===L.accountId)?.quota,now:Q()});if(!x)return;let k=Q(),f=I1(x,k,X);if(f.retryAfterMs!==void 0)return f;let S=U4(F);return S===void 0?f:{...f,retryAfterMs:S}},inspectEvent:({data:X,transport:F,attempt:T})=>{if(T.data?.kind==="vault"&&X.includes("codex.rate_limits")){let L=g2(X);if(K2(L)&&L.type==="codex.rate_limits")U?.reportUsage(T.data.routeId,{frame:L},T.data.receipt)}if(T.data?.kind==="vault"&&h2()&&(n$(X)||F==="ws"&&X.includes('"response.completed"'))){let L=g2(X);if(a$(L))z.add(T);if(F==="ws"&&K2(L)&&L.type==="response.completed")$1(T.sessionID,T.data.receipt,{status:200,headers:new Headers,failed:z.has(T)})}return V4(X,Q())},limitFromError(X){let F=g2(X.message),T=Z1({...K2(F)?F:{},...X.status!==void 0?{status:X.status}:{}})??(X.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return T?I1(T,Q(),X.status):void 0},async onAttemptEnd(X,F){let T=X.data,L=T?.kind==="vault"&&h2()?Z.get(X):void 0;if(Z.delete(X),T?.kind==="vault"&&L&&!F.error&&!F.limit)$1(X.sessionID,T.receipt,{...L,failed:z.has(X)});if(T?.kind!=="vault"||F.status!==401)return;K?.warn("a vault account answered 401; reporting it to the vault",{accountId:X.accountId}),await U?.reportFailure(T.receipt,401)}},X2=(X,F,T)=>{let L=T.data;if(L?.kind==="vault"){U?.recordSnapshot(X,F.snapshot,F.complete,L.receipt);return}if(L?.kind!=="pool")return;if(G.peek().rows.find((x)=>x.id===X)?.credentialEpoch!==L.credentialEpoch){K?.debug("quota reading dropped: the row holds another credential",{accountId:X});return}G.recordSnapshot(X,F.snapshot,L.token,F.complete)},$2=(X,F,T)=>{let L=Q(),g=T.data?.kind==="vault",x=g?U?.routes().find((S)=>S.id===X)?.quota:G.peek().rows.find((S)=>S.id===X)?.quota,k=k$(m2(x),F.reason,L,Q4,F.retryAfterMs!==void 0?L+F.retryAfterMs:void 0);if(!g){G.markRateLimited(X,k);return}let f=E.get(X);if(f===void 0||f<k)E.set(X,k)};return{adapter:H2,attach(X){X.on("quota",(F)=>X2(F.accountId,F.quota,F.handle)),X.on("limit",(F)=>{$2(F.accountId,F.limit,F.handle),K?.debug("pool row refused the request",{accountId:F.accountId,via:F.via,reason:F.limit.reason,outputStarted:F.outputStarted})})},forgetSession(X){Y.forget(X),w.forget(X),H.forget(X)},activeAccount:(X)=>w.activeAccount(X)}}import{resolve as zZ}from"node:path";import{Buffer as H4}from"node:buffer";import{resolve as t$}from"node:path";function l2($){return H4.byteLength(JSON.stringify($))}function N4($){return $.reduce((Z,z)=>Z+l2(z),0)}function f1($,Z){return 2+$+Math.max(0,Z-1)}function F4($){let{head:Z,pending:z}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+f1(Z.inputBytes,Z.input.length)+1:0)+(z?20+f1(z.inputBytes,z.input.length)+10+f1(z.outputBytes,z.output.length)+(z.responseID===void 0?0:14+z.responseIDBytes)+1:0)}function e$($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class $Z{enabled;caps=Y1;entries=new Map;bytes=0;constructor($=!1){this.enabled=$}setEnabled($){if(this.enabled=$,!$)this.entries.clear(),this.bytes=0}send($,Z){if(!this.enabled)return;let z=e$(Z);if(z?.type!=="response.create")return;if(!Array.isArray(z.input)){this.forget($);return}let G=z.previous_response_id,Y=this.entries.get($),Q=Y?.head;if(G&&G!==Q?.responseID){this.forget($);return}let{type:K,previous_response_id:U,input:H,...N}=z;this.keep($,{fields:G&&Y?Y.fields:N,fieldsBytes:G&&Y?Y.fieldsBytes:l2(N),...G&&Q?{head:Q}:{},pending:{input:H,inputBytes:N4(H),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,z){if(!this.enabled||!Z.includes("response.created")&&!Z.includes("response.output_item.done")&&!Z.includes("response.completed"))return;let G=this.entries.get($);if(!G?.pending)return;let Y=e$(Z);if(!Y)return;let Q=G.pending,K=Y.response;if(Y.type==="response.created"&&typeof K?.id==="string")Q.responseID=K.id,Q.responseIDBytes=l2(K.id),this.keep($,G);else if(Y.type==="response.output_item.done"&&Y.item){if(typeof Y.response_id==="string"&&Q.responseID!==void 0&&Y.response_id!==Q.responseID)return;Q.output.push(Y.item),Q.outputBytes+=l2(Y.item),this.keep($,G)}else if(Y.type==="response.completed"&&typeof K?.id==="string"){if(K.id===G.head?.responseID||Q.responseID!==void 0&&K.id!==Q.responseID)return;let U={responseID:K.id,responseIDBytes:Q.responseID===K.id?Q.responseIDBytes:l2(K.id),input:[...G.head?.input??[],...Q.input,...Q.output],inputBytes:(G.head?.inputBytes??0)+Q.inputBytes+Q.outputBytes},H={...G,head:U,pending:void 0};if(!this.keep($,H))return;z?.({sessionID:$,responseID:U.responseID,bodyText:this.body(G.fields,U)})}}replay($){let Z=this.entries.get($);if(!Z?.head)return;return this.entries.delete($),this.entries.set($,Z),this.body(Z.fields,Z.head)}forget($){let Z=this.entries.get($);if(Z)this.bytes-=Z.bytes;this.entries.delete($)}status(){return{bytes:this.bytes,sessions:[...this.entries].map(([$,Z])=>({sessionID:$,bytes:Z.bytes,responseID:Z.head?.responseID,pending:Z.pending!==void 0}))}}body($,Z){return JSON.stringify({...$,input:Z.input,stream:!0})}keep($,Z){let z=F4(Z);if(this.forget($),z>this.caps.maxBytes)return!1;Z.bytes=z,this.entries.set($,Z),this.bytes+=z;while(this.entries.size>this.caps.maxTargets||this.bytes>this.caps.maxBytes){let G=this.entries.keys().next().value;if(G===void 0)break;this.forget(G)}return this.entries.has($)}}var ZZ=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),JZ=globalThis,v1=JZ[ZZ]??new Map;JZ[ZZ]=v1;function X1($){let Z=JSON.stringify([t$($.configPath),t$($.statePath)]),z=v1.get(Z);if(!z)z=new $Z,v1.set(Z,z);return z}var K4=5000,T4=["accept","originator","session-id","thread-id","user-agent","version","x-client-request-id","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-openai-internal-codex-responses-lite","x-opencode-parent-session-id","x-parent-session-id"],L4=["x-opencode-parent-session-id","x-parent-session-id"];function XZ($){let Z=GZ($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:QZ($?{...$,cachekeep:Z}:$)}}var jZ=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),BZ=globalThis,u2=BZ[jZ]??new Map;BZ[jZ]=u2;function _4($,Z){let z=[],G=()=>z.at(-1)?.location,Y=()=>{let H=G();if(!H)throw Error("no location holds keep-warm");return H},Q=(H,N)=>{U.remove(H),G()?.log?.debug(`cachekeep dropped target (${N})`,{sessionKey:H})},K=async(H)=>{if(H.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let N=H.accountId??"main",V=Y(),P=await V.source.accessFor(N,await V.storage());if(!P)throw Error(`pool row ${N} has no usable token`);return{token:P.token,identity:P.row.identity}},U=YZ({...Y1,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(H,N)=>Y().fetch(H,N),logger:{debug:(H,N)=>G()?.log?.debug(H,N),warn:(H,N)=>G()?.log?.warn(H,N)},getWindow:()=>G()?.settings().window,getSustain:()=>G()?.settings().sustain===!0,resolveLocal:K,vault:{owns:(H)=>G()?.vault.owns(H)===!0,authority:()=>Y().vault.authority(),reportUsage:(...H)=>G()?.vault.reportUsage(...H),send:async(H,N,V)=>{let P=Y();if(await P.vault.authority()!=="vault")return;return P.vault.send(H,N,V)}},activeAccount:(H)=>{if(H===void 0)throw Error("target has no session");let N=G(),V=N?.settings();if(!N||!V?.enabled){Q(H,"keep-warm is off");return}if(!V.subagents&&U.status().targets.some((C)=>C.sessionKey===H&&C.isSubagent)){Q(H,"subagent warming is off");return}let P=N.accounts.activeAccount(H);if(P===void 0){Q(H,"no account recorded for the session");return}return P},verifyCredential:({target:H,mode:N,identity:V})=>{if(H.meta.credentialMode!==N)throw Error(`a target captured in ${H.meta.credentialMode??"an unknown"} mode is not warmed with a ${N} credential`);if(V!==H.meta.chatgptAccountId)throw Q(H.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:U,settings:Z,holders:z,joinTimeoutMs:$.joinTimeoutMs??K4}}function P4($){try{let Z=JSON.parse($),z=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(z?.role!=="user")return!1;return(typeof z.content==="string"?z.content:Array.isArray(z.content)?z.content.map((Y)=>typeof Y?.text==="string"?Y.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function M4($){let Z={};for(let z of T4){let G=$.get(z);if(G)Z[z]=G}return Z}function VZ($,Z,z){let G=JSON.stringify([zZ($.configPath),zZ($.statePath)]),Y=u2.get(G);if(!Y)Y=_4(z,Z.settings()),u2.set(G,Y);let Q=Y,K=X1($);K.setEnabled(Q.settings.enabled);let U={location:{...Z,settings:()=>Q.settings}};Q.holders.push(U);let H=!1,N=async(V)=>{try{let P=U.location.settings();if(H||!P.enabled)return;if(V.kind!=="primary"){if(V.kind==="generate"&&P4(await V.request.clone().text())){if(H)return;Q.manager.remove(V.sessionID)}return}let C=V.attempt.data,E=C?.kind==="pool"?"local":C?.kind==="vault"?"vault":void 0;if(!E)return;let w=V.request.headers,n=L4.some((U2)=>w.has(U2))||Z.parentOf!==void 0&&await Z.parentOf(V.sessionID)!==void 0;if(n&&!P.subagents)return;let O=await V.request.clone().text();if(H)return;let D=w.get("chatgpt-account-id")??void 0;Q.manager.track({sessionKey:V.sessionID,bodyText:O,accountId:V.attempt.accountId,isSubagent:n,meta:{replayHeaders:M4(w),...D?{chatgptAccountId:D}:{},routingSessionId:V.sessionID,url:V.request.url,credentialMode:E}})}catch(P){Z.log?.warn("cachekeep capture failed",{error:P instanceof Error?P.message:String(P)})}};return{manager:Q.manager,configure:(V)=>{Object.assign(Q.settings,V),K.setEnabled(Q.settings.enabled)},capture:N,forget:(V)=>Q.manager.remove(V),async release(){if(H)return;H=!0;let V=Q.holders.indexOf(U);if(V>=0)Q.holders.splice(V,1);if(Q.holders.length>0)return;if(u2.get(G)===Q)u2.delete(G);Q.manager.stop();let P;try{await Promise.race([Q.manager.tick().catch(()=>{}),new Promise((C)=>{P=setTimeout(C,Q.joinTimeoutMs),P.unref?.()})])}finally{clearTimeout(P)}}}}import{mkdirSync as E4}from"node:fs";import{dirname as C4,resolve as O4}from"node:path";function A4(){return WZ("opencode2")}var R4=2000;class KZ{path;options;sessions;frameTurns=new w2;#$=new Set;#Z=new Set;#z=new Set;#G=Promise.resolve();#Q=!1;#J;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=NZ($,Z.uuid??D2)}get($,Z=D2){let z=this.sessions.get($);if(!z){let G=Z();z={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,z),this.#Z.delete($),this.#z.delete($),this.#$.add($),this.#Y()}return z}delete($){let Z=this.sessions.delete($);if(this.frameTurns.forget($),this.#$.delete($),Z)this.#Z.add($);else if(!this.#Z.has($))this.#z.add($);this.#Y()}#Y(){if(this.#J)return;this.#J=setTimeout(()=>{this.#J=void 0,this.save()},this.options.saveDelayMs??R4),this.#J.unref?.()}save(){if(clearTimeout(this.#J),this.#J=void 0,!this.#Q)this.#Q=!0,this.#G=this.#G.then(()=>{return this.#Q=!1,this.#j()});return this.#G}settled(){return this.#J?this.save():this.#G}#X(){if(this.#z.size===0)return;let $;try{$=h1(this.path)}catch{$=new Map}for(let Z of this.#z)if($.has(Z)&&!this.sessions.has(Z))this.#Z.add(Z);this.#z.clear()}async#j(){if(this.#X(),this.#$.size===0&&this.#Z.size===0)return;let $=[...this.#$].flatMap((G)=>{let Y=this.sessions.get(G);return Y?[[G,Y]]:[]}),Z=[...this.#Z],z=null;try{if(E4(C4(this.path),{recursive:!0}),z=await this.#B(),!z)return;let G;try{G=h1(this.path)}catch{G=new Map}await this.options.afterRead?.();let Y=!1;for(let Q of Z)if(G.delete(Q))Y=!0;for(let[Q,K]of $){if(G.get(Q)===K.threadID)continue;G.set(Q,K.threadID),Y=!0}if(Y)FZ(this.path,G)}catch{return}finally{await z?.release().catch(()=>{})}for(let[G,Y]of $)if(this.sessions.get(G)===Y)this.#$.delete(G);for(let G of Z)if(!this.sessions.has(G))this.#Z.delete(G)}#B(){return HZ(this.path,this.options.lockWaitMs??UZ)}}var TZ=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),LZ=globalThis,j1=LZ[TZ]??new Map;LZ[TZ]=j1;function x4($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.sessions instanceof Map&&typeof Z.get==="function"&&typeof Z.delete==="function"&&typeof Z.save==="function"&&typeof Z.settled==="function"&&(Z.frameTurns===void 0||Z.frameTurns!==null&&typeof Z.frameTurns.advance==="function"&&typeof Z.frameTurns.get==="function"&&typeof Z.frameTurns.completed==="function"&&typeof Z.frameTurns.forget==="function")}function _Z($=A4()){let Z=O4($),z=j1,G=j1.get(Z),Y=j1;if(G!==void 0&&!x4(G))z.compatible??=new Map,Y=z.compatible;let Q=Y.get(Z);if(!Q)Q=new KZ(Z),Y.set(Z,Q);let K=Q;return K.frameTurns??=new w2,Q}var g1=Symbol.for("cortexkit.openai-auth.v2.commands"),q4=M2("v2-command");function B1($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.closed instanceof AbortController&&typeof Z.menu?.open==="function"&&typeof Z.menu?.apply==="function"&&typeof Z.session?.get==="function"&&(Z.registration===void 0||Z.registration!==null&&typeof Z.registration.dispose==="function")}function m1($){q4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function S4(){let $=globalThis;return $[g1]??={locations:new Map},$[g1].locations??=new Map,$[g1]}async function RZ($,Z){let z=S4(),G=$.location.directory,Y={menu:Z,session:$.session,closed:new AbortController},Q=await MZ(G),K=await PZ(OZ,Q.dir,()=>AZ({...Q,drain:CZ,apply:(P)=>{let C=z.locations.get(G);if(!B1(C))throw Error("The OpenAI menu location was closed");return C.menu.apply(P)}})),U=z.locations.get(G);if(z.locations.set(G,Y),B1(U))U.closed.abort(),await U.registration?.dispose();let H={name:"openai",description:"OpenAI account menu",async execute(P){let C=[...z.locations.values()].find(B1)?.session;if(!C)return m1("no live location");let E=await C.get({sessionID:P.sessionID}),w=z.locations.get(E.location.directory);if(!B1(w))return m1("location closed");let n=await EZ(P.sessionID,w.closed.signal);if(!n||z.locations.get(E.location.directory)!==w){if(!n&&!w.closed.signal.aborted)l1({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},P.sessionID);return m1(w.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let O=await w.menu.open(P.sessionID);l1(O,P.sessionID)}};z.command??=H,z.command.execute=H.execute;let N=z.command;try{Y.registration=await $.command.transform((P)=>{P.add(N)})}catch(P){if(Y.closed.abort(),z.locations.get(G)===Y)z.locations.delete(G);throw await K.release(),P}let V=!1;return async()=>{if(V)return;if(V=!0,Y.closed.abort(),z.locations.get(G)===Y)z.locations.delete(G);await K.release(),await Y.registration?.dispose()}}var b4="openai-auth-pool-browser",D4="openai-auth-pool-headless",k4="openai-auth-vault",w4="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Run /openai → Vault → Connect and approve the request before trying again.";async function p2($){if(await $.authority()!=="local")throw Error("This host is connected to the credential vault or its enrollment is unreadable; the login was not stored. Disconnect this host from the vault to add a local login.")}function kZ($){return{method:{id:k4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await xZ($.paths,$.name)!=="vault")throw Error(w4)}}}function wZ($){let Z=(z,G,Y)=>({method:{id:z,type:"oauth",label:G},async authorize(){if($.vault)await p2($.vault);let Q=await $.beginLogin({version:$.version,headless:Y});return{url:Q.url,instructions:Q.instructions,mode:"auto",callback:Q.completion}}});return[Z(b4,"ChatGPT (openai-auth pool, browser)",!1),Z(D4,"ChatGPT (openai-auth pool, headless)",!0)]}function u1($){let Z=(z)=>typeof z==="string"?z:"";return f2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===bZ||qZ($)}function y4($){if($.accountId)return $.accountId;let Z=$.access?J1($.access):void 0;return Z?z1(Z):void 0}async function yZ($,Z,z,G={}){if(G.vault)await p2(G.vault);if(u1(z))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Y=SZ($,{rowLocks:(E)=>DZ(Z,E)}),Q=await Y.read();if(Q.status!=="ready")throw Error(`the account pool cannot be read (${Q.status}); the login was not stored`);let K={type:"oauth",refresh:z.refresh,...z.access!==void 0?{access:z.access}:{},...z.expires!==void 0?{expires:z.expires}:{}},U=y4(z);if(G.vault)await p2(G.vault);let H=U!==void 0?{identity:U}:{};if(G.origin==="import"){let E=Q.rows.find((w)=>U!==void 0&&w.identity===U||w.credential?.type==="oauth"&&w.credential.refresh===z.refresh);if(E)return{id:E.id,operation:"kept"}}let N=Q.rows.filter((E)=>E.type==="oauth"&&!E.invalid),V=U?N.find((E)=>E.identity===U):void 0,P=Q.rows.find((E)=>E.id===V1);if(V)return{id:(await Y.replace(V.id,K,H)).id,operation:"replaced"};if(!P){let E=await Y.add({id:V1,credential:K,...H,...z.label!==void 0?{label:z.label}:{}});return{id:E.id,operation:E.outcome==="added-disabled"?"added-disabled":"added"}}if(!P.invalid&&!P.credential)return{id:(await Y.replace(V1,K,H)).id,operation:"replaced"};let C=await Y.add({id:z.id,credential:K,...H,...z.label!==void 0?{label:z.label}:{}});return{id:C.id,operation:C.outcome==="added-disabled"?"added-disabled":C.outcome==="rotated"?"replaced":"added"}}function I4($){let Z=$.itemId!==void 0;switch($.sectionId){case"accounts":return Z?["enable","disable","remove","move"].includes($.actionId):$.actionId==="add";case"routing":return!Z&&["order","mode"].includes($.actionId);case"quota":return $.actionId==="check";case"limits":return Z?$.actionId==="floors":$.actionId==="killswitch";case"session":return!Z&&$.actionId==="clear-pin";case"vault":return Z?["enable","disable"].includes($.actionId):["connect","disconnect"].includes($.actionId);case"diagnostics":return!Z&&["logging","dump"].includes($.actionId);case"cache":return!Z&&["enabled","subagents","sustain","window"].includes($.actionId);case"reset":return Z&&["preview","spend","retry"].includes($.actionId);default:return!1}}function vZ($){let Z={...$,allowAction:I4,unavailableSections:[]};return{open:(z)=>IZ(Z,z),apply:(z)=>{let G=z!==null&&typeof z==="object"?z:{},Y=G.values&&typeof G.values==="object"&&!Array.isArray(G.values)?Object.fromEntries(Object.entries(G.values).filter(([,Q])=>Q===null||["string","number","boolean"].includes(typeof Q))):void 0;return fZ(Z,{command:"openai",sectionId:typeof G.sectionId==="string"?G.sectionId:"",actionId:typeof G.actionId==="string"?G.actionId:"",...Y?{values:Y}:{},...G.confirmed===!0?{confirmed:!0}:{},...typeof G.itemId==="string"?{itemId:G.itemId}:{},...typeof G.sessionId==="string"?{sessionId:G.sessionId}:{}})}}}function f4($,Z){if(!hZ($.modelID??$.id)){$.enabled=!1;return}let z=gZ($.id);if(z)$.limit={...z};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((G)=>[G.id,G])).values()]}function lZ($){return $.model.transform((Z)=>{let z=Z.list(F2);for(let G of z){let Y=mZ(String(G.id)),Q=Y?z.find((K)=>String(K.id)===Y):void 0;Z.update(F2,String(G.id),(K)=>f4(K,Q?.variants?.map((U)=>({...U,id:String(U.id)}))))}})}class p1{log;pending=new Map;requests=new Map;writing=new Set;constructor($){this.log=$}async safely($){let Z=(async()=>{try{await $()}catch{this.log.warn("request dump failed")}})();this.writing.add(Z);try{await Z}finally{this.writing.delete(Z)}}async captureHttp($,Z){if(!uZ())return;await this.safely(async()=>{let z={sessionID:Z.sessionID,accountId:Z.accountId,transport:"http",phase:"http",url:$.url,method:$.method,headers:new Headers($.headers),bodyText:await $.clone().text()};if(this.pending.set($,{attemptId:Z.attemptId,input:z}),this.requests.set(Z.attemptId,$),this.pending.size>512){let G=this.pending.keys().next().value;if(G)this.take(G)}})}take($){let Z=this.pending.get($);if(Z)this.pending.delete($),this.requests.delete(Z.attemptId);return Z?.input}async response($,Z){let z=this.take($);if(z)await this.safely(()=>W1({...z,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let z=this.requests.get($.attemptId),G=z&&this.take(z);if(!G)return;let{reason:Y,message:Q}=Z.error,K=Q?`${Y}: ${Q}`:Y;await this.safely(()=>W1({...G,error:U1(K,z?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>W1({sessionID:Z.sessionID,accountId:Z.accountId,transport:"websocket",phase:"observed",bodyText:$}))}clear(){this.pending.clear(),this.requests.clear()}async settle(){await Promise.all(this.writing)}}class c1{counts=new Map;record($,Z){let z=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof z==="number"&&Number.isFinite(z)?z:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function aZ($){return async(Z)=>{let z=Z.credential;if(z.type!=="oauth"||!z.access)throw Error("the row holds no access token to poll with");let G=await pZ({accessToken:z.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,G),cZ(G,$.now(),!0)}}function nZ($){let{source:Z,counts:z,now:G}=$,Y=async(N)=>{let V=await Z.rowAccess(N,await $.storage());if(!V?.row)throw new dZ("unknown_account",`${N==="main"?"Main":"Fallback"} account ${N} was not found.`);return iZ(N,V)},Q=async(N)=>{if($.authority&&await $.authority()!=="local")return{account:N,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[V]=await Z.pollRows(await $.storage(),{ids:[N]});if(!V)return{account:N,ok:!1,error:"targeted quota refresh returned no result"};return{account:V.id,ok:V.ok,...V.error!==void 0?{error:V.error}:{}}},K=(N)=>Z.peek().rows.find((V)=>V.id===N),U=(N)=>{let V=K(N);if(!V)return null;let P=m2(V.quota)??{},C=z.applicable(V),E=Math.max(0,...[P.primary?.checkedAt,P.secondary?.checkedAt].filter((w)=>typeof w==="number"));return{quota:{...P,...C!==void 0?{resetCreditsApplicable:C}:{}},checkedAt:E,refreshAfter:E,...V.identity!==void 0?{accountId:V.identity}:{}}};return{resolveResetTarget:Y,refreshResetTargetQuota:Q,quotaManager:{isRateLimited:(N)=>{let V=K(N);if(!V)return!1;let P=Z.rateLimitMarks([V]).get(V.id);return P!==void 0&&P>G()},getMain:()=>U("main"),getFallback:(N)=>U(N)}}}import{resolve as oZ}from"node:path";var v4=1024;class d1{pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=v4){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.reservations.delete($),this.pins.delete($);for(let Z of this.listeners)Z($)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}snapshot(){return new Map(this.pins)}placementSnapshot($){let Z=new Map(this.pins);for(let z of this.reservations.values())if(z.sessionId!==$)Z.set(z.sessionId,z.pin);return Z}reserve($,Z){let z={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,z),z}rollback($){if(this.reservations.get($.sessionId)===$)this.reservations.delete($.sessionId)}finish($,Z){if(this.reservations.get($.sessionId)!==$)return;if(this.rollback($),Z&&this.pins.get($.sessionId)===$.previous)this.set($.sessionId,Z)}get size(){return this.pins.size}set($,Z){this.reservations.delete($),this.pins.delete($),this.pins.set($,Z);for(let z of this.listeners)z($,Z);while(this.pins.size>this.limit){let z=this.pins.keys().next().value;if(z===void 0)break;this.forget(z)}}place($){return G1(this.placementSnapshot($.sessionId),$,(Z,z)=>this.set(Z,z))}}var sZ=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),rZ=globalThis,H1=rZ[sZ]??new Map;rZ[sZ]=H1;function h4($){if(!$||typeof $!=="object")return!1;let Z=$;return typeof Z.get==="function"&&typeof Z.forget==="function"&&typeof Z.subscribe==="function"&&typeof Z.snapshot==="function"&&typeof Z.place==="function"&&typeof Z.placementSnapshot==="function"&&typeof Z.reserve==="function"&&typeof Z.rollback==="function"&&typeof Z.finish==="function"}function tZ($){let Z=JSON.stringify([oZ($.configPath),oZ($.statePath)]),z=H1,G=H1.get(Z);if(G!==void 0&&!h4(G)){let Q=H1;Q.compatibleV1??=new Map,z=Q.compatibleV1}let Y=z.get(Z);if(!Y)Y=new d1,z.set(Z,Y);return Y}import{statSync as g4}from"node:fs";import{resolve as m4}from"node:path";function X0($){return $.map((Z)=>{try{let z=g4(Z);return`${z.ino}:${z.size}:${z.mtimeMs}:${z.ctimeMs}`}catch{return"?"}}).join("|")}function i1($){return X0([$.vault.paths.tokenPath,$.vault.paths.statePath])}function eZ($){return X0([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+i1($)}class j0{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;protocol=V0;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:eZ($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),z=this.subscriptions.get($.pins);if(!z){let G=new Set;z={producers:G,stop:$.pins.subscribe((Y,Q)=>{let K=G.values().next().value;if(K)this.publish(K,{sessionId:Y,pin:Q,accountId:Q?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,z)}return z.producers.add($),this.timer??=setInterval(()=>{for(let G of this.producers){let Y={stamp:eZ(G),roster:G.vault.snapshot()},Q=this.observations.get(G);if(Y.stamp!==Q?.stamp||Y.roster!==Q?.roster)this.observations.set(G,Y),this.publish(G)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),z.producers.delete($),!z.producers.size)z.stop(),this.subscriptions.delete($.pins);if(!this.producers.size)clearInterval(this.timer),this.timer=void 0}}publish($,Z){return this.chain=this.chain.then(async()=>{if(!this.producers.has($))return;await($.write??B0)(this.file,$,Z,()=>this.producers.has($))}).catch(()=>{M2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var B0=async($,Z,z,G)=>{let Q=await Z.vault.authority()!=="local",K=i1(Z),U=()=>G()&&Z.vault.enrolled()===Q&&i1(Z)===K,H=await(Q?d2(Z.paths):y2(Z.paths)),N=Q?Q0(Z.vault.snapshot()?.rows,new Set(Z.vault.routes().map((C)=>C.id)),H,Date.now()):Y0((await Z.source.sidebarView()).rows,H,Date.now()),V={canWrite:U,vaultMode:Q};if(await Z0(N,$,V),!U()||!z)return;let P=N.vaultAccounts??N.fallbacks;if(z.accountId===void 0){await z0(z.sessionId,P,$,V);return}if(z.pin){let C=Date.now();await G0({sessionId:z.sessionId,assignment:{accountId:z.pin.accountId,wireAccountId:z.pin.wireIdentity,inputBytes:z.pin.inputBytes??0,quotaCheckedAt:z.pin.quotaCheckedAt,assignedAt:C,lastSeenAt:C},validPinnedAccountIds:[...Q?[]:["main"],...P.filter((E)=>E.enabled).map((E)=>E.id)]},$,V)}await J0({sessionId:z.sessionId,activeId:z.accountId,route:z.route??N.route,updatedAt:Date.now()},P,$,V)},V0=2,W0=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),U0=globalThis,c2=U0[W0]??new Map;U0[W0]=c2;function H0($,Z=$0(),z=2000){let G=m4(Z),Y=c2.get(G);if(Y?.protocol!==V0)Y=new j0(G,z),c2.set(G,Y);let Q=Y;$={...$,write:$.write??B0};let K=Q.add($),U=!1;for(let[H,N]of $.pins.snapshot())Q.publish($,{sessionId:H,pin:N,accountId:N.accountId,route:"sticky-balanced"});return{publish:()=>Q.publish($),route:(H,N,V)=>{Q.publish($,{sessionId:H,accountId:N,route:V})},async release(){if(U)return;if(U=!0,K(),await Q.settled(),Q.empty&&c2.get(G)===Q)c2.delete(G)}}}var K1="cortexkit-openai-auth",p4=5000;async function N0($,Z,z,G=new v2,Y,Q,K){let U=new p1(z),H=new l4,N=new Map,V=new Map,P=(O)=>{V.delete(O);for(let D of N.keys())if(D.startsWith(`${O}:`))N.delete(D)},C=(O)=>{K?.(O.sessionID),Q?.send(O.sessionID,O.frame)},w=await O1({session:{hook:(O,D,U2)=>$.session.hook(O,async(G2)=>{let I=O==="http.request"?G2:void 0,i=O==="experimental.ws.handshake"?G2:void 0,X2=(I?I.request.headers:i?new Headers(i.headers):void 0)?.get("authorization")===`Bearer ${P2(Z.providerID)}`,$2={};if(i)N.delete(`${i.sessionID}:${i.kind}`);try{await H.run($2,()=>D(G2))}catch(X){if(X2&&!(X instanceof V2))throw P0(X);throw X}if(I&&X2&&$2.attempt){let X=I.request.headers.get("thread-id");if(X)I.request.headers.set("session-id",X)}if(I&&X2&&$2.attempt)await U.captureHttp(I.request,$2.attempt);if(I&&X2&&$2.attempt)await Y?.({sessionID:I.sessionID,kind:I.kind,request:I.request,attempt:$2.attempt});if(i&&X2&&$2.attempt)i.headers["session-id"]=G.get(i.sessionID).threadID;if(O==="experimental.ws.send"){let X=G2,F=N.get(`${X.sessionID}:${X.kind}`);if(F)await U.frame(X.frame,F.attempt);if(F&&X.kind==="primary")C(X)}if(I||i){let X=I??i;if(!X)return;let T=(I?I.request.headers:new Headers(X.headers)).get("authorization")?.replace(/^Bearer /,"");if(X2&&T)V.set(X.sessionID,T);else V.delete(X.sessionID);if(i){let L=`${i.sessionID}:${i.kind}`;if(X2&&T&&$2.attempt)N.set(L,{bearer:T,attempt:$2.attempt,url:i.url,headers:new Headers(Object.entries(i.headers).filter(([g])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(g.toLowerCase())))});else N.delete(L)}if(V.size>512){let L=V.keys().next().value;if(L)V.delete(L)}if(N.size>512){let L=N.keys().next().value;if(L)N.delete(L)}}else if(O==="experimental.ws.receive"){let X=G2,F=N.get(`${X.sessionID}:${X.kind}`);if(F){if(G.frameReceived(X.sessionID,X.frame),X.kind==="primary"){let T;if(Q?.receive(X.sessionID,X.frame,(L)=>{T=L}),T)try{let L=T$(T,F.url,F.headers,G);if(L)await Y?.({sessionID:X.sessionID,kind:"primary",request:L,attempt:F.attempt})}catch(L){z.warn("cachekeep WebSocket capture failed",{error:L instanceof Error?L.message:String(L)})}}X.frame=M0(X.frame,F.bearer)}}else if(O==="retry"){let X=G2,F=V.get(X.sessionID);if(F)Object.assign(X.error,{message:U1(X.error.message,F)})}},U2)},event:{subscribe:(O)=>async function*(){for await(let D of $.event.subscribe(O)){if(D.type==="session.deleted")P(D.data.sessionID);yield D}}()}},{...Z,rewriteRequest:async(O)=>{let D=H.getStore();if(D)D.attempt=O.attempt;return Z.rewriteRequest?.(O)},rewriteHandshakeURL:(O)=>{let D=H.getStore();if(D)D.attempt=O.attempt;return Z.rewriteHandshakeURL?.(O)},onAttemptEnd:async(O,D)=>{await U.end(O,D),await Z.onAttemptEnd?.(O,D)},rewriteResponse:async(O)=>{await U.response(O.request,O.response.status);let D=await Z.rewriteResponse?.(O)??O.response;return E0(D,O.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(O)=>{let D=O.get("authorization");return D?.startsWith("Bearer ")?D.slice(7):void 0}},logger:{warn:(O,D)=>z.warn(O,{data:D})}}),n=w.dispose;return{...w,dispose:async()=>{V.clear(),N.clear(),await n(),await U.settle(),U.clear()}}}function o1($={}){return{id:K1,setup:(Z)=>c4(Z,$)}}async function c4($,Z={}){let c=[];try{let z=M2("opencode2");let G=M2("quota");let Y=Z.version??O0;await f0({version:Y,...Z.runtimeLayout});let Q=Z.paths??(()=>R0(C0()));let K=await d2(Q());let U=K?.logging?.level;if(U&&typeof U==="string")K0(U);let H=Z.fetch??fetch;let N=Z.now??Date.now;let V=Z.poolMigration??h0;if(!V&&!I2(Q().configPath)){z.info("openai-auth stands aside on OpenCode 2: this install has not moved into the account pool and the migration is switched off, so OpenCode 2 serves its own ChatGPT login");let _=(B2)=>{throw new V2({kind:"no-account",providerID:F2,sessionID:B2.sessionID,requestKind:B2.kind,message:Q1})},v=await N0($,{providerID:F2,chooseAccount:_,accountHeaders:_},z);return()=>v.dispose()}let P=Z.vault?.firstRosterWaitMs??D0;let C=v0({host:"opencode",stateDir:Z.vault?.stateDir??_0(Q().statePath),reservedRouteIds:()=>I.peek().rows.map((_)=>_.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>H},Q());let E=C.vault;let w=async()=>await E.authority()==="local"?y2(Q()):d2(Q());let n=!1;let O=!1;const D=N1(c,{[Symbol.dispose](){if(!n)C.release()}},0);await E.authority();let U2=C.firstRoster;let G2=new c1;let I=new k0({paths:Q,rateLimitMarks:E$(Q()),refreshProvider:async(_)=>{let v=await L0({refreshToken:_.refresh,fetchImpl:H,now:N}),B2=T0({id_token:"",access_token:v.access,refresh_token:v.refresh});return{...v,...B2?{identity:B2}:{}}},pullQuota:aZ({fetchImpl:H,now:N,counts:G2,logger:G}),now:N,vaultIdentities:()=>E.identities(),vaultMode:()=>E.enrolled(),vaultAuthority:()=>E.authority(),vaultFirstRoster:U2,vaultFirstRosterBackgroundWaitMs:P,log:M2("pool")});if(await E.authority()==="local")await I.load();let i=Z.heartbeat===!1?void 0:await y0({version:Y,logger:M2("heartbeat")});let H2=Z.fence??(()=>A0({currentVersion:Y}));let X2=Z.slot??g0();let $2=async()=>x0(Q(),await X2.get({path:{id:"openai"}}));let X=!1;let F=V?w0({paths:Q,slot:X2,version:Y,fence:H2,runDeps:{vaultServes:()=>E.serves()},paused:async()=>await E.authority()!=="local",migrate:async(_)=>{let v=await q0(_);if(X=v.status==="refused",!O)await I.load();return v},adopt:async(_)=>{if(O)return{status:"retry",reason:"unsettled"};if(!await n1(U2,P))return{status:"retry",reason:"vault-roster-pending"};if(O)return{status:"retry",reason:"unsettled"};let v=await S0(_);if(!O)await I.load();return v}}):void 0;F?.start();C.start();let T=tZ(Q());let L=H0({paths:Q(),source:I,pins:T,vault:E},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const g=N1(c,{[Symbol.dispose](){if(!n)L.release()}},0);L.publish();let x=Z.codex??new v2(void 0,void 0,_Z());let k=XZ(K);let f=X1(Q());let S=VZ(Q(),{source:I,storage:w,vault:E,accounts:k1(Q()),settings:()=>k,parentOf:async(_)=>(await $.session.get({sessionID:_}))?.parentID??void 0,fetch:H,log:M2("cachekeep")},{now:N,codexResponsesUrl:F1().codexApiEndpoint,...Z.cacheKeep});const y=N1(c,{[Symbol.dispose](){if(!n)S.release()}},0);let u=r$({codex:x,onRoute:L.route,source:I,slotPlaceholderWithoutMain:$2,storage:w,pins:T,sessionAccounts:k1(Q()),vault:E,awaitVaultRoster:async()=>{await n1(E.awaitRequestRoster(),b0)},responsesLite:()=>F1().responsesLite,codexEndpoint:()=>F1().codexApiEndpoint,now:N,log:z});let a=await N0($,u.adapter,z,x,(_)=>S.capture(_),f,(_)=>S.forget(_));u.attach(a);let J2=async(_)=>{if(await p2(E),I2(Q().configPath))return;if(await F?.idle(),I2(Q().configPath))return;if(X&&!u1(_)&&(await H2()).open){await I.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let r=async(_)=>{await J2(_);let v=await yZ(I.poolStore(),Q(),_,{vault:E});if(!I2(Q().configPath))await F?.requestAdoption();await I.load(),z.info("ChatGPT login stored in the account pool",v)};let Q2=await M1($,{integrationID:F2,methods:wZ({beginLogin:Z.beginLogin??a1,version:Y,vault:E}),onLogin:(_)=>r(_),label:"ChatGPT (openai-auth account pool)",vault:kZ(E)});let p=await lZ($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let A=$.command&&$.location?await RZ({session:$.session,command:$.command,location:$.location},Z.controlPlane??vZ({...nZ({source:I,storage:w,counts:G2,now:N,authority:()=>E.authority()}),fetchImpl:H,now:N,randomUUID:u4,accountStoragePath:Q().configPath,accountStatePath:Q().statePath,packageVersion:Y,layoutNotice:I0,loadAccounts:y2,store:()=>I.poolStore(),migration:async()=>{if(I2(Q().configPath))return{migrated:!0};let _=await H2();return{migrated:!1,blockers:_.open?[]:_.blockers}},beginAccountLogin:Z.beginLogin??a1,refreshAllQuota:async()=>(await I.pollRows(await y2(Q()))).map((_)=>({..._,account:_.id})),getStickyRouting:async(_)=>T.get(_),cacheKeepManager:S.manager,setCacheKeepEnabled:(_)=>S.configure({enabled:_}),setCacheKeepSubagents:(_)=>S.configure({subagents:_}),setCacheKeepSustain:(_)=>S.configure({sustain:_}),setCacheKeepWindow:(_)=>S.configure({window:_}),afterWrite:()=>I.load(),refreshSidebar:()=>L.publish(),clearStickyRouting:async(_)=>{let v=T.get(_)!==void 0;return T.forget(_),v},vault:E})):void 0;let z2=new AbortController;(async()=>{try{for await(let _ of $.event.subscribe({signal:z2.signal}))if(_.type==="session.deleted")u.forgetSession(_.data.sessionID),S.forget(_.data.sessionID),f.forget(_.data.sessionID)}catch(_){if(!z2.signal.aborted)z.warn("stopped listening for session deletion",{error:_ instanceof Error?_.message:String(_)})}})();n=!0;return async()=>{O=!0,z2.abort();let _=S.release();await A?.(),F?.dispose(),await I.dispose(),await L.release(),await Promise.allSettled([a.dispose(),Q2.dispose(),p.dispose()]);let v;try{await Promise.race([Promise.all([F?.idle(),I.settled(),x.store?.settled(),_]),new Promise((B2)=>{v=setTimeout(B2,p4),v.unref?.()})])}finally{clearTimeout(v),C.release(),await i?.release()}}}catch(m){var j2=m,Y2=1}finally{F0(c,j2,Y2)}}var d4=o1(),_7={id:K1,setup:d4.setup,server:m0.server};export{_7 as default,o1 as createOpenAIAuthPlugin,K1 as OPENAI_AUTH_PLUGIN_ID};
|
|
1
|
+
import{c as Z4}from"../index-17rh67pr.js";import{$ as $4,A as n0,B as o0,C as E1,D as WZ,E as VZ,F as T0,G as _0,H as e0,I as mZ,J as lZ,M as $0,N as Z0,O as z0,W as Y0,X as Q0,d as g0,e as J0,f as v1,fa as b$,g as e2,ga as R$,h as q1,i as y1,ja as z4,k as q$,l as S$,m as x$,n as M1,o as hZ,p as N$,q as gZ,r as rZ,s as tZ,t as b1,u as TZ,v as _Z,w as S1,x as i0,y as C$,z as a0}from"../index-ya96m6wr.js";import{Ab as Q1,Cb as YZ,Db as _1,Eb as QZ,Fb as BZ,Hb as l0,Ib as qZ,Kb as u0,Lb as iZ,Ra as dZ,Ub as p0,Vb as c0,Wb as d0,Xb as aZ,ab as $Z,cb as ZZ,db as X$,dc as d2,eb as j$,ec as SZ,fb as zZ,fc as bZ,gc as W$,hb as A1,hc as RZ,ic as DZ,lc as s0,mc as r0,na as s2,nc as t0,oa as u$,pb as GZ,qa as r1,qb as Y$,rb as JZ,ua as I0,ub as XZ,vb as jZ,wb as I1,xb as f0,ya as n$,yb as v0,za as o$,zb as h0}from"../index-3r9thx6n.js";import{Mc as L0,Nc as P0,Pc as M0,Tc as C0,xc as K0}from"../index-fd3f8vw2.js";import{$e as z$,Be as i$,Ce as a$,De as CZ,Ee as t1,Jd as O1,Kd as x1,Ke as w1,Ld as w0,Re as j0,Sd as M$,Se as i2,Td as p$,Te as e1,Ud as c$,Ue as $$,Vd as d$,Ve as s$,Xe as Z$,Ye as r$,_e as t$,af as G$,be as pZ,bf as e$,cf as J$,hd as s1,ie as cZ,ke as y0,le as X0,pd as m$,qd as l$,ve as t2,we as H1}from"../index-3p1tc2e2.js";import"../index-dcyhv7eh.js";import{sf as fZ,tf as m0}from"../index-361xxyg2.js";import"../index-29ztc0ay.js";import{Ef as k0,Gf as w2}from"../index-mf3dqvbn.js";import"../index-95z5dpe1.js";import{cg as vZ}from"../index-dkhy2peg.js";import{gg as F1,hg as D0}from"../index-mkda7acs.js";import{AsyncLocalStorage as e4}from"node:async_hooks";import{randomUUID as $5}from"node:crypto";class L2 extends Error{kind;providerID;sessionID;requestKind;constructor($){super($.message??`${$.providerID} ${$.requestKind} request refused (${$.kind})`);this.name="OpenCode2AuthError",this.kind=$.kind,this.providerID=$.providerID,this.sessionID=$.sessionID,this.requestKind=$.requestKind}}function k2($){return`common-auth-placeholder.${$}`}function _$($){let Z=k2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function J1($,Z){if($?.type!=="oauth")return!1;let G=Z===void 0?void 0:k2(Z),J=(Y)=>G===void 0?Y.startsWith("common-auth-placeholder."):Y===G;return J($.access)&&J($.refresh)}var E$="No browser sign-in: this connects the plugin to the accounts in its vault.";async function m1($,Z){let G=Z.now??Date.now,{integrationID:J}=Z,Y=(H)=>_$({integrationID:J,methodID:H,now:G()}),j=async(H,V)=>{return await Z.onLogin(H,{integrationID:J,methodID:V}),Y(V)},K=(H)=>async(V)=>{let L=H.method.id,U=await H.authorize(V),T={url:U.url,instructions:U.instructions,...U.expiresAt===void 0?{}:{expiresAt:U.expiresAt}};if(U.mode==="auto")return{...T,mode:"auto",callback:U.callback.then((A)=>j(A,L))};let S=U.callback;return{...T,mode:"code",callback:async(A)=>j(await S(A),L)}};return $.integration.transform((H)=>{let V=Z.label===void 0?{}:{label:()=>Z.label};for(let T of Z.methods)H.method.update({integrationID:J,method:T.method,authorize:K(T),refresh:async(S)=>{if(!J1(S,J))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return Y(S.methodID)},...V});let L=Z.vault;if(L===void 0)return;let U=L.method.id;H.method.update({integrationID:J,method:L.method,authorize:async()=>({url:"",instructions:L.instructions??E$,mode:"auto",callback:Promise.resolve().then(()=>L.activate({integrationID:J,methodID:U})).then(()=>Y(U))}),refresh:async(T)=>{if(!J1(T,J)||T.methodID!==U)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return Y(U)},...V})})}function J4($){let Z=[],G;for(let J of $.split(/\r?\n/))if(J.startsWith("data:"))Z.push(J.slice(5).replace(/^ /,""));else if(J.startsWith("event:"))G=J.slice(6).trim();if(Z.length===0)return;return G===void 0?{data:Z.join(`
|
|
2
|
+
`)}:{event:G,data:Z.join(`
|
|
3
|
+
`)}}function l1($,Z){let G=new TextDecoder,J="",Y=(K)=>{let H=J4(K);if(!H)return;try{$(H)}catch(V){Z(V)}},j=()=>{for(;;){let K=/\r?\n\r?\n/.exec(J);if(!K)return;let H=J.slice(0,K.index);J=J.slice(K.index+K[0].length),Y(H)}};return new TransformStream({transform(K,H){H.enqueue(K),J+=G.decode(K,{stream:!0}),j()},flush(){if(J+=G.decode(),j(),J.trim()!=="")Y(J);J=""}})}var n2=512,c2=3621000,a2="x-common-auth-attempt",p2=($,Z)=>JSON.stringify([$,Z]),b2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function X4($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function j4($,Z){let G=$.getReader();return new ReadableStream({async pull(J){let Y;try{Y=await G.read()}catch(j){Z({reason:"failed",message:j instanceof Error?j.message:String(j)}),J.error(j);return}if(Y.done)Z(),J.close();else J.enqueue(Y.value)},async cancel(J){Z({reason:"cancelled",...J===void 0?{}:{message:String(J)}}),await G.cancel(J)}})}function L1($,Z){for(let[G,J]of Object.entries(Z)){let Y=G.toLowerCase();for(let j of Object.keys($))if(j.toLowerCase()===Y)delete $[j];if(J!==null)$[G]=J}}function Y4($,Z){for(let[G,J]of Object.entries(Z))if(J===null)$.delete(G);else $.set(G,J)}async function u1($,Z,G={}){let{providerID:J}=Z,Y=G.gateOnPlaceholder,j=(z)=>Y===void 0||Y.credential(z)===k2(J),K=G.logger,H=Math.max(1,G.maxRecords??n2),V=G.hostRetryLimit??10,L=[...G.hostCredentials??[k2(J)],...Y?[k2(J)]:[]].filter((z)=>z!==""),U=new Map,T=new WeakMap,S=new Map,A=0,f=new Set,Z2=new Map,b=new Map,D=(z)=>{let Q=b.get(z);return Q?.ownedSeen===!0&&Q.foreignSeen},H2=(z,Q)=>{Z2.set(z,Q);let B=b.get(z)??{ownedSeen:!1,foreignSeen:!1};if(Q)B.ownedSeen=!0;else B.foreignSeen=!0;b.set(z,B)},X2=(z,Q)=>{let B=Y?.refuseMisplaced,F=B?[...Q].filter(([,E])=>E.includes(k2(J))):[],W=j(Q)&&(!B||F.length>0);if(B){if(F.length>0&&(F.length!==1||!W))throw H2(z.sessionID,!1),new L2({kind:"placement-refused",providerID:J,sessionID:z.sessionID,requestKind:z.kind,message:B(F[0]?.[0]??"")})}return H2(z.sessionID,W),W},I=!1,p=!1,I2=new Map,M2=0,t=!1,w=new Map,u=(z,Q)=>{try{K?.warn(z,Q)}catch{}},o=(z)=>z instanceof Error?z.message:String(z),m=(z)=>z.excluded.clear(),E2=(z)=>z.excluded.size===0?{}:{excluded:[...z.excluded]},A2=(z,Q,B)=>{if(!G.enforceRequestExclusion||z===void 0||!B.excluded.has(z))return!1;return u("opencode2 auth ignored a chooser result for a request-excluded account",{sessionID:Q.sessionID,kind:Q.kind,phase:Q.phase,accountId:z}),!0},R2=new Map,F2=(z,Q)=>{let B=(R2.get(z)??Promise.resolve()).then(Q),F=B.then(()=>{},()=>{});return R2.set(z,F),F.then(()=>{if(R2.get(z)===F)R2.delete(z)}),B},$1=(z,Q)=>{let B=R2.get(z);return B?B.then(()=>$1(z,Q)):Q()},V2=async(z)=>{try{await Z.dropChoice?.({...z.input,accountId:z.accountId})}catch(Q){u("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:z.input.sessionID,error:o(Q)})}},z2=async(z)=>{try{await Z.dropSameAccountRetry?.({...z.input,accountId:z.accountId})}catch(Q){u("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:z.input.sessionID,error:o(Q)})}},g2=async(z)=>{if(z.next)await V2(z.next);if(z.sameAccount)await z2(z.sameAccount)},X=(z)=>{let Q=S.get(z);if(S.delete(z),Q)F2(Q.sessionID,()=>g2(Q))},N=async(z,Q)=>{let B=I2.get(z);if(!B||B.size===0)return;await Promise.all([...B].map(async(F)=>{try{await F(Q)}catch(W){u("opencode2 auth listener threw; the request is unaffected",{event:z,error:o(W)})}}))},M=async(z,Q)=>{try{await Z.onAttemptEnd?.(z,Q)}catch(B){u("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:z.attemptId,error:o(B)})}},P=(z,Q)=>{if(z.ended||!z.attempt)return;let B={...z.status===void 0?{}:{status:z.status},outputStarted:z.outputStarted,...z.limit?{limit:z.limit.signal}:{},...Q?{error:Q}:{}};if(Q)z.endError=Q;if(Q?.reason==="cancelled"||!Q&&!z.limit&&(z.status===void 0||z.status<400))m(z.request);z.ended=M(z.attempt,B)},R=(z,Q)=>P(z,{reason:"abandoned",message:Q}),x=(z)=>[...U.values()].filter((Q)=>Q.key===z),q=(z)=>x(z).at(-1),y=(z)=>{if(U.delete(z.id),S.get(z.key)?.attemptId===z.id||!x(z.key).length)X(z.key)},v=(z)=>{U.set(z.id,z);while(U.size>H){let Q=U.values().next().value;if(Q===void 0)break;R(Q,"dropped to keep the record bound"),y(Q)}},h=(z)=>z.accountId===void 0?void 0:{...z.scope,accountId:z.accountId},k=(z,Q)=>new L2({kind:"no-account",providerID:J,sessionID:z.sessionID,requestKind:z.kind,...Q===void 0?{}:{message:Q}}),a=(z)=>{w.get(z)?.clear(),w.delete(z)},G2=async(z,Q)=>{let B=()=>k(z,`${J} ${z.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(t)throw B();let F=w.get(z.sessionID);if(!F)F=new Set,w.set(z.sessionID,F);let W={};F.add(W);let E=()=>{if(!F.has(W))throw B()};try{return await Q(E)}finally{if(F.delete(W),F.size===0&&w.get(z.sessionID)===F)w.delete(z.sessionID)}},_=(z,Q)=>{for(let[B,F]of Q)if(L.some((W)=>F.includes(W)))throw new L2({kind:"host-credential-on-wire",providerID:J,sessionID:z.sessionID,requestKind:z.kind,message:`${J} ${z.kind} request still carries the host's placeholder credential in ${B}; the adapter's account headers must replace it`})},g=(z)=>{for(let Q of x(z))if(Q.ended||!Q.attempt)y(Q);else if(Q.transport==="ws"||Q.judged)R(Q,"a newer attempt of its session and kind began"),y(Q)},s=async(z,Q,B,F)=>{let W=p2(z.sessionID,z.kind),{input:E,accountId:C,sameAccountRetry:O,request:i}=await $1(z.sessionID,async()=>{B();let Y2=S.get(W);S.delete(W);let G1=x(W);if(Y2&&G1.some(($2)=>$2.id!==Y2.attemptId&&$2.attempt&&!$2.ended))u("opencode2 auth bound a pending retry to an ambiguous concurrent request; keeping its exclusions",{sessionID:z.sessionID,kind:z.kind});if(!Y2){let $2=new Set(G1.filter((_2)=>_2.attempt&&!_2.ended).map((_2)=>_2.request));for(let _2 of G1)if(!$2.has(_2.request))m(_2.request)}let K2=Y2?.request??{excluded:new Set},J2=Y2?.accountId??q(W)?.accountId;g(W);let r=Y2?.next,Q2=Y2?.sameAccount,d=Q2!==void 0&&Q2.input.modelID===z.modelID&&Q2.input.agent===z.agent,T2=r!==void 0&&r.input.modelID===z.modelID&&r.input.agent===z.agent,D2=Y2?.wake,n={...z,phase:"request",...E2(K2),...J2===void 0?{}:{previousAccountId:J2},...Y2?.rerouteFrom?{rerouteFrom:Y2.rerouteFrom}:{},...D2===void 0?{}:{wake:D2,hostAttempt:r?.input.hostAttempt}};if(r&&(!T2||D2!==void 0))await F2(z.sessionID,()=>V2(r)),B();if(Q2&&!d)await F2(z.sessionID,()=>z2(Q2)),B();if(Q2?.continuation&&(!d||D(z.sessionID))){if(d)await F2(z.sessionID,()=>z2(Q2));throw k(z)}let u2=d?Q2.accountId:T2&&D2===void 0?r.accountId:await Z.chooseAccount(n),h2=typeof u2==="string"?u2:void 0;if(A2(h2,n,K2)){let $2=h2;if(d&&Q2)await F2(z.sessionID,()=>z2(Q2));else if($2!==void 0)await F2(z.sessionID,()=>V2(T2&&r?r:{accountId:$2,input:n}));h2=void 0,B()}return{input:n,accountId:h2,sameAccountRetry:d,request:K2}});B();let W2={},q2;if(C!==void 0){let Y2=await Z.accountHeaders({...z,accountId:C});if(B(),X4(Y2))W2=Y2.headers,q2=Y2.attempt;else W2=Y2}let z1=`attempt-${++M2}`,S2={id:z1,key:W,scope:z,request:i,accountId:C,headers:W2,attempt:C===void 0?void 0:{...z,accountId:C,attemptId:z1,transport:F,data:q2},...F===void 0?{}:{transport:F},outputStarted:!1,sameAccountRetry:O};if(v(S2),S2.attempt)N("select",{...z,accountId:S2.attempt.accountId,hook:Q,...E.previousAccountId===void 0?{}:{previousAccountId:E.previousAccountId},...E.rerouteFrom===void 0?{}:{rerouteFrom:E.rerouteFrom},handle:S2.attempt});return S2},O2=async(z,Q,B,F,W)=>{let E=p2(z.sessionID,z.kind),C=F===void 0?void 0:U.get(F);if(C?.key!==E)C=void 0;if(!C){if(C=q(E),x(E).filter((i)=>i.transport===void 0&&!i.ended).length>1&&!p)p=!0,u("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:z.sessionID,kind:z.kind})}if(!C||C.transport!==void 0||C.ended)C=await s(z,Q,W,B);else if(C.transport=B,C.attempt)C.attempt.transport=B;if(B==="ws"){for(let O of x(E))if(O!==C&&O.transport==="ws")R(O,"a newer attempt of its session and kind went out over WebSocket")}return C},c=async(z,Q)=>{try{return await Q()}catch(B){throw P(z,{reason:"failed",message:o(B)}),B}},e=(z,Q)=>{let B=x(p2(z,Q)).filter((F)=>F.transport==="ws").at(-1);return B?.attempt!==void 0&&!B.ended?B:void 0},U2=(z,Q,B)=>{let F=h(z);if(!F||!z.attempt||z.limit)return;z.limit={signal:Q,delivered:N("limit",{...F,via:B,limit:Q,outputStarted:z.outputStarted,handle:z.attempt})}},f2=(z,Q,B,F)=>{let W=h(z);if(!W||!z.attempt)return;N("quota",{...W,transport:Q,...F===void 0?{}:{status:F},quota:B,handle:z.attempt})},Z1=(z,Q,B,F)=>{let W=z.attempt;if(!W)return;let E=Z.inspectEvent?.(F===void 0?{transport:Q,data:B,attempt:W}:{transport:Q,data:B,event:F,attempt:W});if(!E)return;if(E.quota!==void 0)f2(z,Q,E.quota);if(E.outputStarted)z.outputStarted=!0;if(E.hostRetry==="veto")z.hostRetry="veto";if(E.limit)U2(z,E.limit,Q);if(E.error!==void 0)P(z,{reason:"failed",message:E.error});else if(E.done)P(z)},C2=(z,Q)=>{let B=z.attempt;if(!B||Q.accountId===z.accountId)return;if(B.reboundFrom??=B.accountId,B.accountId=Q.accountId,"data"in Q)B.data=Q.data;z.accountId=Q.accountId},m2=(z)=>!z.attempt||z.endError!==void 0||z.status!==void 0&&z.status>=400,l2=(z)=>{let Q=[...U.values()].filter((O)=>O.scope.sessionID===z),B=Q.filter((O)=>O.limit&&!O.rerouted).at(-1);if(B)return B;let F=Q.filter((O)=>O.scope.kind==="primary"),W=F.length>0?F:Q;if(W.length<=1)return W[0];let E=W.filter((O)=>!O.judged&&m2(O)).at(-1);if(E)return E;let C=W.filter((O)=>O.attempt&&!O.ended);if(C.length>1)return"ambiguous";return C[0]??W.at(-1)},j2={providerID:J},N2=[];N2.push(await $.session.hook("model.request",(z)=>{if(Y)return;return G2(b2(z),async(Q)=>{let B=await s(b2(z),"model.request",Q);if(Q(),B.accountId===void 0)throw k(B.scope);L1(z.headers,{...B.headers,[a2]:B.id})})},j2)),N2.push(await $.session.hook("http.request",(z)=>{if(Y){if(!X2(b2(z),z.request.headers))return}return G2(b2(z),async(Q)=>{let B=z.request.headers.get(a2)??void 0,F=Y?await s(b2(z),"http.request",Q,"http"):await O2(b2(z),"http.request","http",B,Q);Q();let W=h(F),E=F.attempt;if(!W||!E)throw k(F.scope);await c(F,async()=>{let C=z.request;if(Z.rewriteRequest){if(B!==void 0){let W2=new Headers(C.headers);W2.delete(a2),C=new Request(C,{headers:W2})}C=await Z.rewriteRequest({...W,request:C,attempt:E})??C,Q()}let O=new Headers(C.headers);O.delete(a2),Y4(O,F.headers),_(F.scope,O.entries());let i=new Request(C,{headers:O});T.set(i,F),z.request=i})})},j2)),N2.push(await $.session.hook("http.response",async(z)=>{let Q=T.get(z.request);if(!Q){if(Y)return;if(!I)I=!0,u("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:z.sessionID,kind:z.kind});return}let B=z.response;if(Z.answeredBy&&Q.attempt){let O=Q.attempt,i=await c(Q,async()=>Z.answeredBy?.({request:z.request,response:B,attempt:O}));if(i)C2(Q,i)}let F=h(Q),W=Q.attempt;if(!F||!W)return;Q.status=B.status;let E=Z.quotaFromHeaders?.(B.headers,B.status,W);if(E!==void 0)f2(Q,"http",E,B.status);if(!B.ok&&Z.limitFromResponse){let O=await Z.limitFromResponse({status:B.status,headers:B.headers,body:()=>B.clone().text(),attempt:W});if(O)U2(Q,O,"http")}if(!B.ok||!B.body)P(Q);let C=B;if(B.body&&(Z.inspectEvent||Z.onAttemptEnd)){let O=B.body;if(Z.inspectEvent)O=O.pipeThrough(l1((i)=>Z1(Q,"http",i.data,i.event),(i)=>u("opencode2 auth event inspection threw",{error:o(i)})));C=new Response(j4(O,(i)=>{if(i?.reason==="failed")Q.httpReadFailed=!0;P(Q,i)}),{status:B.status,statusText:B.statusText,headers:B.headers})}if(Z.rewriteResponse)C=await Z.rewriteResponse({...F,request:z.request,response:C,attempt:W})??C;if(Z.responseRetry){if(await Z.responseRetry({...F,request:z.request,response:C,attempt:W})==="veto")Q.hostRetry="veto"}if(C!==B)z.response=C},j2)),N2.push(await $.session.hook("experimental.ws.handshake",(z)=>{if(Y){let Q=p2(z.sessionID,z.kind);if(f.delete(Q),!X2(b2(z),new Headers(z.headers)))return}return G2(b2(z),async(Q)=>{let B;for(let C of Object.keys(z.headers)){if(C.toLowerCase()!==a2)continue;B??=z.headers[C],delete z.headers[C]}let F=Y?await s(b2(z),"experimental.ws.handshake",Q,"ws"):await O2(b2(z),"experimental.ws.handshake","ws",B,Q);Q();let W=h(F),E=F.attempt;if(!W||!E)throw k(F.scope);await c(F,async()=>{if(!Y?.refuseMisplaced)L1(z.headers,F.headers);let C=Z.rewriteHandshakeURL?.({...W,url:z.url,attempt:E});if(C!==void 0)z.url=C;if(Y?.refuseMisplaced)L1(z.headers,F.headers);if(_(F.scope,Object.entries(z.headers)),Y)f.add(F.key)})})},j2));let y2=Z.rewriteWebSocketFrame?.bind(Z);if(y2)N2.push(await $.session.hook("experimental.ws.send",async(z)=>{let Q=b2(z);if(Y&&!f.has(p2(Q.sessionID,Q.kind)))return;let B=e(Q.sessionID,Q.kind),F=await y2({...Q,attempt:B?.attempt,frame:z.frame});if(F!==void 0)z.frame=F},j2));N2.push(await $.session.hook("experimental.ws.receive",(z)=>{if(Y&&!f.has(p2(z.sessionID,z.kind)))return;let Q=e(z.sessionID,z.kind);if(!Q)return;try{Z1(Q,"ws",z.frame)}catch(B){u("opencode2 auth frame inspection threw",{error:o(B)})}},j2)),N2.push(await $.session.hook("retry",async(z)=>{if(Y&&Z2.get(z.sessionID)!==!0)return;let Q=z.decision,B=()=>N("retry",{sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:Q,decision:Q});if(D(z.sessionID)&&!Z.retrySameAccount){await B();return}let F=l2(z.sessionID);if(!F)return;if(F==="ambiguous"){await N("retry",{sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:Q,decision:Q});return}let W=F,E=()=>W.hostRetry==="veto";await G2(W.scope,async(C)=>{let O=C,i=Z.retrySameAccount?.bind(Z),W2=W.attempt,q2=W.outputStarted;if(q2&&W.httpReadFailed&&i&&W2&&!D(z.sessionID)){if(!W.limit){let K2=Z.limitFromError?.(z.error,W2);if(K2)U2(W,K2,"error")}if(W.ended)await W.ended;if(W.limit)await W.limit.delivered;O()}let z1=()=>W.httpReadFailed===!0&&z.error.type==="provider.transport"&&Q.retry&&V-z.attempt>=1&&!W.limit&&!(W.status!==void 0&&W.status>=400)&&!(z.error.status!==void 0&&z.error.status>=400)&&!W2?.reboundFrom&&!E()&&!D(z.sessionID);if(i&&W2&&(!q2||z1())&&(!E()||D(z.sessionID))&&!W.sameAccountRetry){if(W.ended)await W.ended;if(W.limit)await W.limit.delivered;let K2=await F2(W.scope.sessionID,async()=>{O();let J2=W2.accountId,r=()=>U.has(W.id)&&W.accountId===J2&&l2(z.sessionID)===W&&W.outputStarted===q2&&(!q2||z1())&&(!E()||D(z.sessionID))&&(!Y||Z2.get(z.sessionID)===!0);if(!r()||W.sameAccountRetry)return!1;W.sameAccountRetry=!0;let Q2={...W.scope,accountId:J2,error:z.error,attempt:z.attempt,...W.limit?{limit:W.limit.signal}:{},...q2?{continuation:"interrupted-read"}:{}},d;try{d=await i(Q2)}catch(n){u("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:z.sessionID,error:o(n)})}if(!d)return O(),!1;let T2={accountId:d.accountId,input:Q2,...q2?{continuation:!0}:{}};try{O()}catch(n){throw await z2(T2),n}if(!r()||d.accountId!==J2)return await z2(T2),!1;let D2=S.get(W.key);if(S.delete(W.key),D2)await g2(D2);try{O()}catch(n){throw await z2(T2),n}if(!r())return await z2(T2),!1;return S.set(W.key,{request:W.request,attemptId:W.id,sessionID:W.scope.sessionID,order:++A,accountId:J2,sameAccount:T2}),W.judged=!0,z.decision=q2?Q:{retry:!0,delay:0},!0});if(O(),K2){await N("retry",{sessionID:z.sessionID,accountId:W.accountId,kind:W.scope.kind,attempt:z.attempt,reason:q2?"continue-same-account":"same-account",hostDecision:Q,decision:z.decision,handle:W.attempt});return}}if(D(z.sessionID)){await B();return}W.judged=!0;let S2=W.attempt;if(S2&&!W.outputStarted){if(!W.limit){let K2=Z.limitFromError?.(z.error,S2);if(K2)U2(W,K2,"error")}if(W.ended)await W.ended;if(W.limit)await W.limit.delivered}O();let{decision:Y2,reason:G1}=await F2(W.scope.sessionID,async()=>{if(O(),D(z.sessionID))return{decision:Q,reason:"host-decides"};let K2=S.get(W.key);if(S.delete(W.key),K2)await g2(K2);if(O(),D(z.sessionID))return{decision:Q,reason:"host-decides"};let J2=Q,r,Q2,d,T2;if(W.accountId===void 0||!S2)J2={retry:!1},r="no-account";else if(W.outputStarted)J2={retry:!1},r="output-started";else if(E())J2={retry:!1},r="adapter-veto";else if(W.limit){let D2={accountId:W.accountId,limit:W.limit.signal},n,u2={...W.scope,phase:"retry",...E2(W.request),hostAttempt:z.attempt,previousAccountId:W.accountId,rerouteFrom:D2};try{n=await Z.chooseAccount(u2)}catch(g1){u("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:W.scope.sessionID,error:o(g1)})}let h2=typeof n==="string"?n:typeof n==="object"&&("hold"in n)?W.accountId:void 0;if(A2(h2,u2,W.request)){if(h2!==void 0)await V2({accountId:h2,input:u2});n=void 0}let $2=typeof n==="object"&&"hold"in n?n.hold:void 0,_2=typeof n==="object"&&"waitThenReselect"in n?n.waitThenReselect:void 0,G4=typeof n==="object"&&"hostRetry"in n?n.hostRetry:void 0,K1=typeof n==="string"?n:$2?W.accountId:void 0;if(K1!==void 0)d={accountId:K1,input:u2};try{O()}catch(g1){if(d)await V2(d);throw g1}if(D(z.sessionID)){if(d)await V2(d);return{decision:Q,reason:"host-decides"}}if(E()||G4==="veto"){if(d)await V2(d);if(d=void 0,O(),D(z.sessionID))return{decision:Q,reason:"host-decides"};W.hostRetry="veto",J2={retry:!1},r="adapter-veto"}else if(!(V-z.attempt>=1)){if(d)await V2(d);d=void 0,r="host-decides-last-account"}else if(_2&&Number.isFinite(_2.delayMs)&&_2.delayMs>=0&&_2.delayMs<=c2)J2={retry:!0,delay:Math.ceil(_2.delayMs)},r="wait-then-reselect";else if($2&&Number.isFinite($2.delayMs)&&$2.delayMs>=0&&$2.delayMs<=c2){if(J2={retry:!0,delay:Math.ceil($2.delayMs)},$2.target!==void 0)T2={target:$2.target,...$2.checkpoint===void 0?{}:{checkpoint:$2.checkpoint},...$2.kind===void 0?{}:{kind:$2.kind}};r="hold"}else if(!$2&&K1!==void 0&&K1!==W.accountId)W.rerouted=!0,W.request.excluded.add(W.accountId),Q2=D2,J2={retry:!0,delay:0},r="reroute";else{if($2&&d)await V2(d),d=void 0;r="host-decides-last-account"}}else r="host-decides";if(z.decision=J2,J2.retry&&W.accountId!==void 0&&U.has(W.id))S.set(W.key,{request:W.request,attemptId:W.id,sessionID:W.scope.sessionID,order:++A,accountId:W.accountId,...Q2===void 0?{}:{rerouteFrom:Q2},...d===void 0?{}:{next:d},...T2===void 0?{}:{wake:T2}});else if(d)await V2(d);if(!J2.retry)m(W.request);return{decision:J2,reason:r}});O(),await N("retry",{sessionID:z.sessionID,...W.accountId===void 0?{}:{accountId:W.accountId},kind:W.scope.kind,attempt:z.attempt,reason:G1,hostDecision:Q,decision:Y2,...S2===void 0?{}:{handle:S2}})})},j2));let v2=(z)=>{if(a(z),Z2.delete(z),!b.get(z)?.foreignSeen)b.delete(z);for(let Q of f)if(JSON.parse(Q)[0]===z)f.delete(Q);for(let Q of[...U.values()]){if(Q.scope.sessionID!==z)continue;R(Q,"its session was forgotten"),m(Q.request),U.delete(Q.id)}for(let[Q,B]of S)if(B.sessionID===z)X(Q)},B2=new AbortController,l=$.event;if(l)(async()=>{try{for await(let z of l.subscribe({signal:B2.signal}))if(z.type==="session.deleted")v2(z.data.sessionID);else if(z.type==="session.status"&&z.data.status.type==="idle"){let Q=z.data.sessionID,B=++A;F2(Q,async()=>{for(let[F,W]of S)if(W.sessionID===Q&&W.order<B)S.delete(F),m(W.request),await g2(W)})}}catch(z){if(!B2.signal.aborted)u("opencode2 auth stopped listening for session deletion",{error:o(z)})}})();return{on(z,Q){let B=I2.get(z);if(!B)B=new Set,I2.set(z,B);let F=Q;return B.add(F),()=>{B.delete(F)}},accountFor(z,Q){return q(p2(z,Q))?.accountId},forgetSession:v2,get size(){return U.size},async dispose(){if(t)return;t=!0;for(let z of w.keys())a(z);B2.abort();for(let z of U.values())R(z,"the installation was disposed");U.clear();for(let z of S.keys())X(z);f.clear(),Z2.clear(),b.clear(),I2.clear(),await Promise.all(R2.values()),await Promise.all(N2.map(async(z)=>{try{await z.dispose()}catch(Q){u("opencode2 auth hook did not dispose cleanly",{error:o(Q)})}}))}}}import{randomUUID as g$}from"node:crypto";import{createHash as Q4}from"node:crypto";var B4=1024,W4=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),O$=($)=>x$($,"user"),V4=($)=>W4($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function U4($){return Q4("sha256").update(JSON.stringify($)).digest("hex")}class o2{runtime;maxSessions;#$=new Map;constructor($,Z=B4){this.runtime=$;this.maxSessions=Z}advance($,Z,G=this.runtime){let J=this.#$.get($),Y=Array.isArray(Z.input)?Z.input:[],j=Y.filter(O$),K=Y.findLastIndex(O$),H=K<0?void 0:U4(Y[K]),V=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,L,U,T;if(V)L=j.length>0,U=H??J?.fingerprint,T=J?.userCount===void 0?void 0:J.userCount+j.length;else{U=H,T=j.length;let A=K>=0&&K>Y.findLastIndex(V4),f=J!==void 0&&!J.completed&&J.fingerprint===U&&J.userCount===T;L=A&&!f}let S=L||!J?{turnID:(G?.uuid??d2)(),turnStartedAt:(G?.now??Date.now)()}:{turnID:J.turnID,turnStartedAt:J.turnStartedAt};return this.#Z($,{...S,completed:!1,fingerprint:U,userCount:T}),S}completed($){let Z=this.#$.get($);if(Z)this.#Z($,{...Z,completed:!0})}get($){return this.#$.get($)}forget($){this.#$.delete($)}#Z($,Z){this.#$.delete($),this.#$.set($,Z);while(this.#$.size>this.maxSessions){let G=this.#$.keys().next().value;if(G===void 0)break;this.#$.delete(G)}}}function p1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var A$=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function N4(){let $=globalThis;return $[A$]??=crypto.randomUUID(),$[A$]}class X1{runtime;store;sessions;frameTurns;installationID;constructor($,Z,G){this.runtime=$;this.store=G;this.installationID=Z??N4(),this.sessions=G?.sessions??new Map,this.frameTurns=G?.frameTurns??new o2}get($){let Z=this.runtime?.uuid??d2;if(this.store)return this.store.get($,Z);let G=this.sessions.get($);if(!G){let J=Z();G={threadID:J,turnID:Z(),windowID:`${J}:0`},this.sessions.set($,G)}return G}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(P1(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var c1={version:q$,"user-agent":S$,originator:"codex_exec"};var H4=1024,F4=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,C1=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),D$=($)=>C1($)&&($.type==="message"||("role"in $))&&$.role==="user",k$=($)=>C1($)&&$.type==="configuration_update";class d1{http;#$=new Map;constructor($=new X1){this.http=$}apply($,Z,G){if(Z.kind!=="primary")return!1;let J=typeof $.model==="string"?$.model:"";if(!b$.has(J))return!1;if(F4.test(J))return!1;let Y=C1($.reasoning)?$.reasoning:void 0,j=typeof Y?.effort==="string"?Y.effort:void 0;if(!j)return!1;let K=this.#$.get(Z.sessionID);if(K===void 0)return this.#Z(Z.sessionID,j),!1;if(j===K)return!1;let H=Array.isArray($.input)?$.input:void 0;if(!H||H.length===0)return!1;let V=H.findLastIndex(D$);if(V<0){if(G==="http")return!1;return $.reasoning={...Y,effort:K},!0}if($.reasoning={...Y,effort:K},!k$(H[V-1]))H.splice(V,0,{type:"configuration_update",reasoning:{effort:j}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>H4){let G=this.#$.keys().next().value;if(G===void 0)break;this.#$.delete(G)}}}function P1($){try{let Z=JSON.parse($);return C1(Z)?Z:void 0}catch{return}}async function w$($,Z,G,J,Y=G.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let j=await $.clone().text(),K=P1(j);if(K)delete K.max_output_tokens;let H=new Headers($.headers),V=M1({rewriteLite:R$,init:{body:K?JSON.stringify(K):$.body===null?void 0:j},headers:H,metadata:Y.get(Z.sessionID),installationID:Y.installationID,runtime:Y.runtime,websocket:!1,responsesLite:J,applyEffort:(L)=>{G.apply(L,Z,"http")}});return new Request($,{headers:H,body:V.init?.body})}function y$($,Z,G,J){let Y=J.sessions.get($.sessionID),j=J.frameTurns.get($.sessionID);if(!Y||!j)return;let K=p1(Y,j),H=new Headers({"content-type":"application/json"});for(let L of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let U=G.get(L);if(U!==null)H.set(L,U)}M1({init:{body:$.bodyText},headers:H,metadata:K,installationID:J.installationID,runtime:J.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let V=new URL(Z);if(V.protocol==="wss:")V.protocol="https:";if(V.protocol==="ws:")V.protocol="http:";return new Request(V,{method:"POST",headers:H,body:$.bodyText})}function K4($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let G=Z.findIndex((J,Y)=>JSON.stringify(J)!==JSON.stringify($[Y]));return G>=0&&k$(Z[G])&&D$(Z[G+1])&&JSON.stringify(Z.slice(G+1))===JSON.stringify($.slice(G))}function I$($,Z,G){let J=P1($);if(J?.type!=="response.create")return;let Y=G.http.advanceFrame(Z.sessionID,J),j=G.http.get(Z.sessionID);delete J.max_output_tokens;let K=M1({rewriteLite:()=>{},init:{body:JSON.stringify(J)},headers:new Headers,metadata:p1(j,Y),installationID:G.http.installationID,runtime:G.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(V)=>{G.apply(V,Z,"ws")}}),H=P1(String(K.init?.body));if(!H)return;if(!K4(J.input,H.input)){if("input"in J)H.input=J.input;else delete H.input;return JSON.stringify(H)}return String(K.init?.body)}function L4($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function i1($,Z){let G=new URL($);if(G.origin!=="https://api.openai.com"&&G.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(G.pathname))return $;let J=new URL(`${L4(Z)}/responses`);if(J.search=G.search,G.protocol==="ws:"||G.protocol==="wss:")J.protocol=J.protocol==="https:"?"wss:":"ws:";return J.href}import{resolve as f$}from"node:path";var P4=1024;class T1{accounts=new Map;limit;constructor($=P4){this.limit=Math.max(1,$)}record($,Z){this.accounts.delete($),this.accounts.set($,Z);while(this.accounts.size>this.limit){let G=this.accounts.keys().next().value;if(G===void 0)break;this.accounts.delete(G)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var v$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),h$=globalThis,a1=h$[v$]??new Map;h$[v$]=a1;function n1($){let Z=JSON.stringify([f$($.configPath),f$($.statePath)]),G=a1.get(Z);if(!G)G=new T1,a1.set(Z,G);return G}var x2="openai",r2=10;var o1=1,M4="request refused: no account with a usable credential",P2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function C4($){let Z=P2($)?$.counters:void 0,G=P2(Z)?Z.resetCredits:void 0,J=P2(G)?G.value:void 0;return typeof J==="number"&&Number.isFinite(J)?J:void 0}function j1($){try{return JSON.parse($)}catch{return}}function Y1($){let Z=O1($);return Z?x1(Z):void 0}var T4=new Set(["usage_limit_reached","rate_limit_exceeded"]);function B1($,Z,G,J){return{reason:$.window,windows:$Z($,Z,J,Z),observedAt:Z,...$.resetAt!==void 0?{resetAt:$.resetAt,resetSource:"provider"}:{},...G!==void 0?{status:G}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function UZ($,Z,G){if($.type!=="response.failed"){let j=E1($,Z),K=typeof $.status==="number"?$.status:void 0;return j?B1(j,Z,K,G):void 0}if(!P2($.response))return;let J=$.response.failed;if(P2(J)&&typeof J.rate_limit_reached_type==="string")return B1({window:J.rate_limit_reached_type},Z,void 0,G);let Y=$.response.error;if(P2(Y)){let j=typeof Y.code==="string"?Y.code:typeof Y.type==="string"?Y.type:void 0;if(j&&T4.has(j)){let K=typeof $.status==="number"?$.status:void 0,H=E1({error:{...Y,type:j},status:K},Z);return B1(H??{window:j},Z,K,G)}}return}function _4($,Z,G){if(!P2($))return;let J=typeof $.type==="string"?$.type:void 0;if(J==="codex.rate_limits")return{quota:{snapshot:d$($),complete:!0}};let Y=UZ($,Z,G);if(Y)return{limit:Y};if(J===void 0||J==="error")return;return WZ(J)?void 0:{outputStarted:!0}}function E4($){let Z=!1;for(let G of $.keys())if(G.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:p$($),complete:c$($)}}function O4($){let Z=$.get("retry-after");if(Z===null)return;let G=Z.trim()?Number(Z):NaN;return Number.isFinite(G)&&G>=0?G*1000:void 0}function NZ($){let Z=new WeakMap,G=new WeakSet,{source:J,pins:Y}=$,j=$.now??Date.now,K=$.log,H=$.vault,V=$.limits,L=g$(),U=new WeakMap,T=new Map,S=(X,N)=>i2(N?H?.routes().find((M)=>M.id===X)?.quota:J.peek().rows.find((M)=>M.id===X)?.quota),A=new d1($.codex),f=new Map,Z2=(X)=>{for(let[N,M]of f)if(M===X)f.delete(N)},b=new Map,D=new Map,H2=(X)=>`${X.sessionID}\x00${X.kind}`,X2=new Map,I=new Map,p=(X)=>{let N=I.get(X);if(N)clearTimeout(N.timer);I.delete(X)},I2=(X,N,M)=>{let P=t({...X,accountId:N});p(P);let R={request:M,sessionID:X.sessionID,expiresAt:performance.now()+5000,timer:setTimeout(()=>{if(I.get(P)===R)p(P)},5000)};if(R.timer.unref(),I.set(P,R),I.size>n2){let x=I.keys().next().value;if(x!==void 0)p(x)}},M2=(X)=>{let N=I.get(X);return p(X),N&&performance.now()<N.expiresAt?N.request:void 0},t=(X)=>`${X.sessionID}\x00${X.kind}\x00${X.accountId}`,w=$.sessionAccounts??new T1,u=new t$,o=(X,N,M)=>{let P=M?[]:VZ(J.peek().rows,X,N,H?.identities()??new Set),R=(H?.routes()??[]).filter((x)=>x.kind==="oauth"&&i$(i2(x.quota),X,N));return[...P.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota,row:x})),...R.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota}))]},m=(X,N,M)=>{let P=s$(X,N,M),R=X.map((v)=>({id:v.id,kind:"oauth",...s1(v.quota)?{quota:v.quota}:{}})),x=X.flatMap((v)=>v.row?[v.row]:[]),q=new Set(X.filter((v)=>!v.row).map((v)=>v.id)),y=V?.marks()??new Map;return{rows:R,now:M,rateLimitMarks:y,refreshBackoff:J.refreshBackoffFor(x),killswitch:P,requestPull:(v)=>q.has(v)?H?.requestReading(v):J.requestReading(v)}},E2=(X,N,M,P,R)=>{let x=z$({...X,rows:X.rows.filter((y)=>!M.has(y.id)),placement:Z$(N),mainId:R});if(x.kind==="block"){K?.debug("pool admission refused the request",{reason:x.block.reason});return}let q=x.order.filter((y)=>!M.has(y));if(P!==void 0&&q.includes(P))return P;return q[0]},A2=(X,N)=>{let M=new Map(X.map((P)=>[P.id,P.quota]));return{requestBytes:o1,reservePercent:(P)=>t1(N,P===e1?void 0:P),resetCredits:(P)=>C4(M.get(P))}},R2=(X,N,M,P,R,x,q,y)=>{let v=A2(N,M),h=G$(X),k=(s,O2)=>A1(q,{sessionId:P,requestBytes:o1,validPinnedAccountIds:X.rows.map((c)=>c.id).filter((c)=>!h.excluded.has(c)),excludeAccountIds:s,quotaCheckedAtByAccount:Object.fromEntries(X.rows.map((c)=>[c.id,h.projections.get(c.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(N.map((c)=>[c.id,c.identity])),select:(c)=>y?{accountId:y,source:"mode-fallback",quotaCheckedAt:h.projections.get(y)?.checkedAt}:e$(X,v,new Set(s),c),persist:O2},(c,e)=>q.set(c,e)),a=[...R],G2=k(a,x);if(!G2)return;let _=G2.accountId,g=J$(X,v,_);if(g.kind==="none")return;if(g.kind==="move"){let s=k([...a,_],x);if(s)return s.accountId;return g.reason==="killswitch"?void 0:_}if(g.kind==="detour")return k([...a,_],!1)?.accountId;return _},V2={providerID:x2,async retrySameAccount(X){if(X.continuation!=="interrupted-read")return;let N=D.get(H2(X));if(D.delete(H2(X)),!N||N.accountId!==X.accountId||N.modelID!==X.modelID||N.agent!==X.agent||X.limit)return;let M=H!==void 0&&await H.authority()!=="local",P=await $.storage();if(!M&&!(await J.current()).active)return;let R=j(),x=o(P,R,M),q=x.find((k)=>k.id===X.accountId);if(!q)return;let y=m(x,P,R),v=P?.routing?.mode??"main-first";if(v==="sticky-balanced"){let k=J$(y,A2(x,P),X.accountId);if(k.kind!=="serve"&&k.kind!=="last-path")return}else{let k=z$({...y,placement:Z$(v),...M?{mainId:$$(H?.routes()??[])}:{}});if(k.kind==="block"||!k.order.includes(X.accountId))return}let h=N.data;if(q.row){if(h?.kind!=="pool")return;let k=J.usableToken(q.row),a=q.row.identity??(k&&Y1(k));if(!k||!h.identity||a!==h.identity)return}else{if(h?.kind!=="vault"||!H)return;let k=await H.authorize(X.accountId);if(!k||k.credentialId!==h.credentialId||k.accountIdentity!==h.accountIdentity||(k.accountIdentity??Y1(k.accessToken))!==h.wireIdentity||q.identity!==void 0&&q.identity!==h.wireIdentity)return}return{accountId:X.accountId}},dropSameAccountRetry(){},dropChoice(X){let N=t(X);p(N),X2.get(N)?.drop(),X2.delete(N),b.delete(N)},chooseAccount:async(X)=>{let N,M=await H?.authority(),P=await $.storage(),R=M!==void 0&&M!=="local",x=()=>{throw new L2({kind:"no-account",providerID:x2,sessionID:X.sessionID,requestKind:X.kind,message:q1})};if(R){let B=performance.now()+S1;await $.awaitVaultRoster?.(),N=await V?.forRequest(B)}else{if(N=await V?.forRequest(),!(await J.current()).active){if(await $.slotPlaceholderWithoutMain?.())x();K?.warn("the account pool does not serve requests yet; refusing the request",{kind:X.kind});return}await J.prepareTokens(J.peek().rows,P)}let q=j(),y=o(P,q,R),v=r$(m(y.filter((B)=>B.id!==X.rerouteFrom?.accountId),P,q));if(v)await v,q=j(),y=o(P,q,R);let h=new Map(y.map((B)=>[B.id,B])),k=m(y,P,q),a=P?.routing?.maxSameAccountWait,G2=JSON.stringify([X.sessionID,X.kind]),_=[...f.values()].includes(X.sessionID),g=V?.activity.get(X.sessionID),s=g&&V?.accountKey(g.accountKey.accountId),O2=X.previousAccountId??X.rerouteFrom?.accountId,c=O2&&V?.accountKey(O2),e=X.rerouteFrom?.limit,U2=y.flatMap((B)=>{let F=V?.accountKey(B.id);if(!F)return[];let W=i2(B.quota),E=ZZ(e&&B.id===O2?{account:F,kind:"rate-limit",reason:e.reason,scope:{kind:"pool"},windows:e.windows??[],observedAt:e.observedAt??q}:void 0,W,q),C=k.rateLimitMarks.get(B.id),O=k.refreshBackoff.get(B.id),i=[...C&&C>q?[{kind:"hard",until:C,cause:"rate-limit"}]:[],...O&&O>q?[{kind:"cooldown",until:O}]:[]],W2=k.killswitch.get(B.id)!==!1&&!!(W?.primary||W?.secondary)&&!l$(m$(s1(B.quota)?B.quota:void 0),q)&&!(O&&O>q)&&(!B.row||!!J.usableToken(B.row));return[{account:F,admitted:W2,placementEligible:W2,ready:W2&&!i.length&&!E.length,blockers:i,confirmedBlockers:E}]}),f2={phase:X.phase==="retry"?"after-limit":"pre-send",host:"opencode2",hostPhase:X.phase,now:q,clockNow:q,sessionId:X.sessionID,requestScope:{kind:"pool"},history:u$({requestId:X.sessionID,originalUrl:"https://api.openai.com/v1/responses",clockNow:q}),delivery:{owned:!0,attributable:!0,replayable:!0},candidates:U2,...X.phase==="retry"&&c?{attempted:c}:{},...X.phase==="retry"&&c&&e?{signal:{account:c,kind:"rate-limit",reason:e.reason,scope:{kind:"pool"},windows:e.windows??[],observedAt:e.observedAt??q},status:e.status}:{},remainingRetries:r2-(X.hostAttempt??r2)},Z1=()=>{let B=V?.owner();return GZ({accounts:U2.flatMap((F)=>{let W=h.get(F.account.accountId);if(!W)return[];return[{account:F.account,reading:i2(W.quota),usable:!W.row||!!J.usableToken(W.row),confirmedBlockers:F.confirmedBlockers,floors:a$(P)?t1(P,W.id===e1?void 0:W.id):void 0,marks:B?.snapshot()?.marks.filter((E)=>E.key.window==="account"&&E.key.scope.kind==="pool"&&s2(E.key.account,F.account)).flatMap((E)=>E.entries.map((C)=>({until:C.until,evidenceAt:C.evidenceAt})))}]}),now:q,effectiveModel:X.modelID,maxSameAccountWait:a,activity:g,currentAccountKey:s,provenance:B?.provenance})},C2=U2.find((B)=>c&&s2(B.account,c));if(X.phase==="retry"&&e&&C2){let B=X$({candidate:C2,activity:g,maxSameAccountWait:a,now:q,maxDelayMs:c2}),F=j$({...f2,hold:B},{mode:"sticky"});if(F?.action==="hold"&&!_)return f.set(G2,X.sessionID),{hold:{delayMs:F.delayMs,target:F.target,checkpoint:F.checkpoint,kind:"hold"}};let W=y.filter((C)=>C.id!==O2);if(C2.confirmedBlockers?.some((C)=>C.confirmed)&&W.length>0&&W.every((C)=>{let O=U2.find((i)=>i.account.accountId===C.id);return O&&(!O.admitted||(k.rateLimitMarks.get(C.id)??0)>q)})){if(_)return{hostRetry:"veto"};let C=Y$(f2,Z1());if(r1(a)===0)return{hostRetry:"veto"};let O="delayMs"in C?C.delayMs:("retryAfterMs"in C)?C.retryAfterMs:void 0;if((f2.remainingRetries??0)<1||O===void 0||O>c2)return{hostRetry:"leave"};if(C.action==="hold"&&s2(C.account,C2.account))return f.set(G2,X.sessionID),{hold:{delayMs:O,target:C.target,checkpoint:C.checkpoint,kind:"terminal"}};return f.set(G2,X.sessionID),{waitThenReselect:{delayMs:O}}}}let m2;if(X.phase==="request"&&X.wake?.checkpoint&&C2&&(X.hostAttempt??r2)<r2&&r1(a)!==0&&s2(C2.account,X.wake.checkpoint.accountKey)){let B=X.wake.checkpoint,F=new Map(B.blockers.map((O)=>[O.window,{...O,confirmed:!0,confirmedByReading:!1,observedAt:B.decidedAt,provenance:"provider"}]));for(let O of C2.confirmedBlockers??[])F.set(O.window,O);let W={...C2,confirmedBlockers:[...F.values()]},E=X$({candidate:W,activity:g,maxSameAccountWait:a,now:q,maxDelayMs:c2});if(j$({...f2,attempted:C2.account,candidates:U2.map((O)=>O===C2?W:O),hold:E,wake:{...X.wake,checkpoint:B}},{mode:"sticky"})?.action==="retain")m2=C2.account.accountId}let l2=new Set(X.rerouteFrom?[X.rerouteFrom.accountId]:[]),j2=P?.routing?.mode??"main-first",N2=X.kind==="primary",y2=new Set,v2,B2,l,z=!1,Q=(B)=>{let F=G$(k).projections.get(B)?.checkedAt,W=h.get(B)?.identity;return Y.reserve(X.sessionID,{accountId:B,inputBytes:o1,...F!==void 0?{quotaCheckedAt:F}:{},...W!==void 0?{wireIdentity:W}:{}})};try{for(;;){let B=new Set([...l2,...y2]);l=void 0,v2=void 0;let F=j2!=="sticky-balanced";if(m2&&!B.has(m2))l=m2,m2=void 0;else if(j2==="sticky-balanced"){let E=new Map(Y.placementSnapshot(X.sessionID)),C=E.get(X.sessionID);if(F=C===void 0,l=R2(k,y,P,X.sessionID,B,N2&&y2.size===0,E),l!==void 0&&E.get(X.sessionID)!==C)v2=E.get(X.sessionID)}if(l??=E2(k,j2,B,N2?void 0:w.activeAccount(X.sessionID),R?j2==="sticky-balanced"?null:$$(H?.routes()??[]):void 0),l===void 0||y2.has(l)){if(l2.size>0){let E=new Map(k.rateLimitMarks);for(let C of l2)E.delete(C);k={...k,rateLimitMarks:E},l2.clear();continue}if(k.rateLimitMarks.size>0){k={...k,rateLimitMarks:new Map};continue}l=void 0;break}if(N2&&j2==="sticky-balanced")B2=Q(l);if(!z){z=!0;let E=X.wake?void 0:await YZ({vaultMode:R,fresh:F,sessionId:X.sessionID,request:{modelId:X.modelID,kind:X.kind,retry:X.phase==="retry"||X.rerouteFrom!==void 0},routes:H?.routes()??[],routing:k,wait:{activity:g,accountKey:s,maxSameAccountWait:a},eligibleIds:y.filter((C)=>!B.has(C.id)).map((C)=>C.id)});if(E&&E!==l){if(B2)Y.rollback(B2);if(B2=void 0,j2==="sticky-balanced"){let C=new Map(Y.placementSnapshot(X.sessionID));l=R2(k,y,P,X.sessionID,B,N2,C,E)??l,v2=C.get(X.sessionID)??v2}else l=E;if(N2&&j2==="sticky-balanced")B2=Q(l)}}let W=h.get(l)?.row;if(W){if(J.usableToken(W)!==void 0)break;K?.debug("pool row holds no usable token; choosing again",{accountId:l})}else{if(!H)break;let E=await H.authorize(l);if(E){b.set(t({...X,accountId:l}),E);break}K?.debug("the vault refused to serve an account; choosing again",{accountId:l})}if(B2)Y.rollback(B2);B2=void 0,y2.add(l)}if(l===void 0&&!R&&y.length===0&&await $.slotPlaceholderWithoutMain?.())x();if(l===void 0&&R&&H&&(y.length===0||y2.size>0)){let B=y2.size>0?"vault-refused":o$(H);throw K?.warn("vault mode: no vault account can serve; refusing the request",{cause:B}),new L2({kind:"no-account",providerID:x2,sessionID:X.sessionID,requestKind:X.kind,message:n$(B,H.name)})}if(l!==void 0){if(N)I2(X,l,N);let B=l,F=B2,W=v2,E=()=>{if(F)Y.finish(F,W);if(N2)w.record(X.sessionID,B),$.onRoute?.(X.sessionID,B,j2)};if(X.phase==="retry")X2.set(t({...X,accountId:l}),{commit:E,drop:()=>{if(F)Y.rollback(F)}}),B2=void 0;else E();let C=K?.info;u.served(k,l,K&&C?{info:(O,i)=>C.call(K,O,i)}:void 0)}if(l===void 0&&X.phase==="request"&&U2.length>0&&U2.every((B)=>!B.admitted)&&U2.some((B)=>k.killswitch.get(B.account.accountId)===!1||B.confirmedBlockers?.length)){let B=Y$(f2,Z1()),F=JZ({decision:B,now:q,host:"opencode2",requestThrow:!0,maxSameAccountWait:a});if(F.kind==="http"){let W=JSON.parse(F.body);throw new L2({kind:"no-account",providerID:x2,sessionID:X.sessionID,requestKind:X.kind,message:W.error.message})}}return K?.debug("pool account chosen",{kind:X.kind,accountId:l,mode:j2,...X.rerouteFrom?{rerouteFrom:X.rerouteFrom.accountId}:{}}),l}finally{if(B2)Y.rollback(B2)}},accountHeaders:async(X)=>{let{accountId:N}=X;D.delete(H2(X));let M=t(X),P=X2.get(M);X2.delete(M);let R=()=>{P?.commit()};try{let x=()=>new L2({kind:"no-account",providerID:x2,sessionID:X.sessionID,requestKind:X.kind,message:M4}),q=async(a)=>{if(!V)return;let G2=M2(M)??await V.forRequest();if(a.kind==="pool"){let e=J.peek().rows.find((U2)=>U2.id===N);if(!e||e.credentialEpoch!==a.credentialEpoch||J.usableToken(e)!==a.token)throw x()}let _=V.bindings().find((e)=>e.account.accountId===N),g=await G2?.beforeDispatch(_,()=>V.ownershipBindings(),N),s=V.accountKey(N);if(g&&g.status!=="ready"||_&&(!s||!s2(_.account,s)))throw x();let O2=V.owner(),c=_?{sessionId:X.sessionID,accountKey:_.account,dispatchedAt:j(),ttlMs:XZ(JSON.stringify({model:X.modelID}))}:void 0;if(c){if(T.delete(c.sessionId),T.set(c.sessionId,c),T.size>n2){let e=T.keys().next().value;if(e!==void 0)T.delete(e)}}U.set(a,{owner:O2,probe:O2?.observe(_),dispatch:c,failed:!1,completed:!1})},y=H&&await H.authority()!=="local"?void 0:J.peek().rows.find((a)=>a.id===N);if(!y&&H){let a=t(X),G2=b.get(a)??await H.authorize(N);if(b.delete(a),!G2)throw K?.warn("the vault refused to serve an account; refusing the request",{accountId:N}),x();let _={kind:"vault",routeId:N,receipt:G2};return await q(_),R(),{headers:{...c1,"session-id":X.sessionID,authorization:`Bearer ${G2.accessToken}`,"chatgpt-account-id":G2.accountIdentity??Y1(G2.accessToken)??null},attempt:_}}let v=y?J.usableToken(y):void 0;if(!y||!v)throw K?.warn("pool row holds no usable token; refusing the request",{accountId:N}),x();let h=y.identity??Y1(v),k={kind:"pool",token:v,credentialEpoch:y.credentialEpoch,...h!==void 0?{identity:h}:{}};return await q(k),R(),{headers:{...c1,"session-id":X.sessionID,authorization:`Bearer ${v}`,"chatgpt-account-id":h??null},attempt:k}}finally{P?.drop()}},async rewriteRequest({request:X,sessionID:N,kind:M}){let P=$.codexEndpoint?i1(X.url,$.codexEndpoint()):X.url,R=P===X.url?X:new Request(P,X);return await w$(R,{sessionID:N,kind:M},A,$.responsesLite?.()??!1)??R},rewriteHandshakeURL:({url:X})=>$.codexEndpoint?i1(X,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:X,sessionID:N,kind:M})=>I$(X,{sessionID:N,kind:M},A),quotaFromHeaders:(X,N,M)=>{if(M.data?.kind==="vault")H?.reportUsage(M.data.routeId,{headers:X},M.data.receipt);if(M.data?.kind==="vault"&&Q1()&&N>=200&&N<300)Z.set(M,{status:N,headers:X});return E4(X)},async limitFromResponse({status:X,headers:N,body:M,attempt:P}){if(X<400)return;let R=j1(await M().catch(()=>"")),x=j(),q=E1({...P2(R)?R:{},status:X},x);if(P.data?.kind==="vault"&&Q1())_1(P.sessionID,P.data.receipt,{status:X,headers:N,body:R,limit:q,quota:H?.routes().find((h)=>h.id===P.accountId)?.quota,now:j()});if(!q)return;let y=B1(q,x,X,S(P.accountId,P.data?.kind==="vault"));if(y.retryAfterMs!==void 0)return y;let v=O4(N);return v===void 0?y:{...y,retryAfterMs:v,resetAt:x+v,resetSource:"retry-after"}},inspectEvent:({data:X,transport:N,attempt:M})=>{let P=j1(X),R=M.data&&U.get(M.data);if(R&&P2(P)&&(P.type==="response.failed"||P.type==="error"))R.failed=!0;if(R&&P2(P)&&P.type==="response.completed")R.completed=!0;if(M.data?.kind==="vault"&&X.includes("codex.rate_limits")){let q=j1(X);if(P2(q)&&q.type==="codex.rate_limits")H?.reportUsage(M.data.routeId,{frame:q},M.data.receipt)}if(M.data?.kind==="vault"&&Q1()&&(BZ(X)||N==="ws"&&X.includes('"response.completed"'))){let q=j1(X);if(QZ(q))G.add(M);if(N==="ws"&&P2(q)&&q.type==="response.completed")_1(M.sessionID,M.data.receipt,{status:200,headers:new Headers,failed:G.has(M)})}let x=_4(P,j(),S(M.accountId,M.data?.kind==="vault"));return N==="ws"&&P2(P)&&P.type==="response.completed"?{...x,done:!0}:x},limitFromError(X,N){let M=j1(X.message),P=j(),R=S(N.accountId,N.data?.kind==="vault");return UZ({...P2(M)?M:{},...X.status!==void 0?{status:X.status}:{}},P,R)??(X.message.includes("usage_limit_reached")?B1({window:"usage_limit_reached"},P,X.status,R):void 0)},async onAttemptEnd(X,N){let M=X.data,P=M&&U.get(M);if(P){let x=!N.error&&!N.limit&&!P.failed&&(X.transport==="ws"?P.completed:N.status!==void 0&&N.status>=200&&N.status<300);if(x&&P.dispatch&&V){let q=T.get(P.dispatch.sessionId);jZ(V.activity,P.dispatch,q===P.dispatch?V.accountKey(X.accountId):void 0,X.transport==="ws"?{kind:"ws",event:"response.completed",aborted:!1}:{kind:"http",completed:!0,failed:!1,aborted:!1})}P.owner?.afterProbe(P.probe,x,Boolean(N.limit))}if(M&&N.outputStarted&&N.error?.reason==="failed"){if(D.set(H2(X),{accountId:X.accountId,modelID:X.modelID,agent:X.agent,sessionID:X.sessionID,data:M.kind==="pool"?{kind:"pool",identity:M.identity}:{kind:"vault",credentialId:M.receipt.credentialId,accountIdentity:M.receipt.accountIdentity,wireIdentity:M.receipt.accountIdentity??Y1(M.receipt.accessToken)}}),D.size>n2){let x=D.keys().next().value;if(x!==void 0)D.delete(x)}}let R=M?.kind==="vault"&&Q1()?Z.get(X):void 0;if(Z.delete(X),M?.kind==="vault"&&R&&!N.error&&!N.limit)_1(X.sessionID,M.receipt,{...R,failed:G.has(X)});if(M?.kind!=="vault"||N.status!==401)return;K?.warn("a vault account answered 401; reporting it to the vault",{accountId:X.accountId}),await H?.reportFailure(M.receipt,401)}},z2=(X,N,M)=>{let P=M.data;if(P?.kind==="vault"){H?.recordSnapshot(X,N.snapshot,N.complete,P.receipt);return}if(P?.kind!=="pool")return;if(J.peek().rows.find((x)=>x.id===X)?.credentialEpoch!==P.credentialEpoch){K?.debug("quota reading dropped: the row holds another credential",{accountId:X});return}J.recordSnapshot(X,N.snapshot,P.token,N.complete)},g2=(X,N,M)=>{let P=j(),R=M.data?.kind==="vault";if(V){let x=M.data&&U.get(M.data),q=x?.owner??V.owner();if(!q)return;if(!x?.probe||q.registry!==x.probe.registry){q.dropSignal();return}let y=N,{command:v,provenance:h}=zZ({binding:x.probe.binding,baseRevision:x.probe.baseRevision,producerId:L,operationId:g$(),parsed:{window:N.reason,resetAt:y.resetAt??(N.retryAfterMs!==void 0?P+N.retryAfterMs:void 0)},reading:S(X,R),now:P,observedAt:y.observedAt??P,evidenceAt:P,resetSource:y.resetSource});q.enqueue(v,h);return}};return{adapter:V2,beginTurn:Z2,dispose:()=>f.clear(),attach(X){X.on("quota",(N)=>z2(N.accountId,N.quota,N.handle)),X.on("limit",(N)=>{g2(N.accountId,N.limit,N.handle),K?.debug("pool row refused the request",{accountId:N.accountId,via:N.via,reason:N.limit.reason,outputStarted:N.outputStarted})})},forgetSession(X){Z2(X);for(let[N,M]of I)if(M.sessionID===X)p(N);T.delete(X),V?.forget(X);for(let[N,M]of D)if(M.sessionID===X)D.delete(N);Y.forget(X),w.forget(X),A.forget(X)},activeAccount:(X)=>w.activeAccount(X)}}import{resolve as MZ}from"node:path";import{Buffer as x4}from"node:buffer";import{resolve as HZ}from"node:path";function W1($){return x4.byteLength(JSON.stringify($))}function A4($){return $.reduce((Z,G)=>Z+W1(G),0)}function Q$($,Z){return 2+$+Math.max(0,Z-1)}function q4($){let{head:Z,pending:G}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+Q$(Z.inputBytes,Z.input.length)+1:0)+(G?20+Q$(G.inputBytes,G.input.length)+10+Q$(G.outputBytes,G.output.length)+(G.responseID===void 0?0:14+G.responseIDBytes)+1:0)}function FZ($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class KZ{enabled;caps=b1;entries=new Map;bytes=0;constructor($=!1){this.enabled=$}setEnabled($){if(this.enabled=$,!$)this.entries.clear(),this.bytes=0}send($,Z){if(!this.enabled)return;let G=FZ(Z);if(G?.type!=="response.create")return;if(!Array.isArray(G.input)){this.forget($);return}let J=G.previous_response_id,Y=this.entries.get($),j=Y?.head;if(J&&J!==j?.responseID){this.forget($);return}let{type:K,previous_response_id:H,input:V,...L}=G;this.keep($,{fields:J&&Y?Y.fields:L,fieldsBytes:J&&Y?Y.fieldsBytes:W1(L),...J&&j?{head:j}:{},pending:{input:V,inputBytes:A4(V),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,G){if(!this.enabled||!Z.includes("response.created")&&!Z.includes("response.output_item.done")&&!Z.includes("response.completed"))return;let J=this.entries.get($);if(!J?.pending)return;let Y=FZ(Z);if(!Y)return;let j=J.pending,K=Y.response;if(Y.type==="response.created"&&typeof K?.id==="string")j.responseID=K.id,j.responseIDBytes=W1(K.id),this.keep($,J);else if(Y.type==="response.output_item.done"&&Y.item){if(typeof Y.response_id==="string"&&j.responseID!==void 0&&Y.response_id!==j.responseID)return;j.output.push(Y.item),j.outputBytes+=W1(Y.item),this.keep($,J)}else if(Y.type==="response.completed"&&typeof K?.id==="string"){if(K.id===J.head?.responseID||j.responseID!==void 0&&K.id!==j.responseID)return;let H={responseID:K.id,responseIDBytes:j.responseID===K.id?j.responseIDBytes:W1(K.id),input:[...J.head?.input??[],...j.input,...j.output],inputBytes:(J.head?.inputBytes??0)+j.inputBytes+j.outputBytes},V={...J,head:H,pending:void 0};if(!this.keep($,V))return;G?.({sessionID:$,responseID:H.responseID,bodyText:this.body(J.fields,H)})}}replay($){let Z=this.entries.get($);if(!Z?.head)return;return this.entries.delete($),this.entries.set($,Z),this.body(Z.fields,Z.head)}forget($){let Z=this.entries.get($);if(Z)this.bytes-=Z.bytes;this.entries.delete($)}status(){return{bytes:this.bytes,sessions:[...this.entries].map(([$,Z])=>({sessionID:$,bytes:Z.bytes,responseID:Z.head?.responseID,pending:Z.pending!==void 0}))}}body($,Z){return JSON.stringify({...$,input:Z.input,stream:!0})}keep($,Z){let G=q4(Z);if(this.forget($),G>this.caps.maxBytes)return!1;Z.bytes=G,this.entries.set($,Z),this.bytes+=G;while(this.entries.size>this.caps.maxTargets||this.bytes>this.caps.maxBytes){let J=this.entries.keys().next().value;if(J===void 0)break;this.forget(J)}return this.entries.has($)}}var LZ=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),PZ=globalThis,B$=PZ[LZ]??new Map;PZ[LZ]=B$;function R1($){let Z=JSON.stringify([HZ($.configPath),HZ($.statePath)]),G=B$.get(Z);if(!G)G=new KZ,B$.set(Z,G);return G}var S4=5000,b4=["accept","originator","session-id","thread-id","user-agent","version","x-client-request-id","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-openai-internal-codex-responses-lite","x-opencode-parent-session-id","x-parent-session-id"],R4=["x-opencode-parent-session-id","x-parent-session-id"];function EZ($){let Z=CZ($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:TZ($?{...$,cachekeep:Z}:$)}}var OZ=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),xZ=globalThis,V1=xZ[OZ]??new Map;xZ[OZ]=V1;function D4($,Z){let G=[],J=()=>G.at(-1)?.location,Y=()=>{let V=J();if(!V)throw Error("no location holds keep-warm");return V},j=(V,L)=>{H.remove(V),J()?.log?.debug(`cachekeep dropped target (${L})`,{sessionKey:V})},K=async(V)=>{if(V.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let L=V.accountId??"main",U=Y(),T=await U.source.accessFor(L,await U.storage());if(!T)throw Error(`pool row ${L} has no usable token`);return{token:T.token,identity:T.row.identity}},H=_Z({...b1,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(V,L)=>Y().fetch(V,L),logger:{debug:(V,L)=>J()?.log?.debug(V,L),warn:(V,L)=>J()?.log?.warn(V,L)},getWindow:()=>J()?.settings().window,getSustain:()=>J()?.settings().sustain===!0,resolveLocal:K,activity:{store:{get size(){return J()?.limits?.activity.size??0},get:(V)=>J()?.limits?.activity.get(V),forgetSession:(V)=>J()?.limits?.activity.forgetSession(V),recordAccepted:(V)=>J()?.limits?.activity.recordAccepted(V)??!1},accountKey:({target:V})=>{let L=J(),U=V.meta.routingSessionId??V.sessionKey,T=V.accountId??"main";return L?.accounts.activeAccount(U)===T?L.limits?.accountKey(T):void 0}},vault:{owns:(V)=>J()?.vault.owns(V)===!0,authority:()=>Y().vault.authority(),reportUsage:(...V)=>J()?.vault.reportUsage(...V),send:async(V,L,U)=>{let T=Y();if(await T.vault.authority()!=="vault")return;return T.vault.send(V,L,U)}},activeAccount:(V)=>{if(V===void 0)throw Error("target has no session");let L=J(),U=L?.settings();if(!L||!U?.enabled){j(V,"keep-warm is off");return}if(!U.subagents&&H.status().targets.some((S)=>S.sessionKey===V&&S.isSubagent)){j(V,"subagent warming is off");return}let T=L.accounts.activeAccount(V);if(T===void 0){j(V,"no account recorded for the session");return}return T},verifyCredential:({target:V,mode:L,identity:U})=>{if(V.meta.credentialMode!==L)throw Error(`a target captured in ${V.meta.credentialMode??"an unknown"} mode is not warmed with a ${L} credential`);if(U!==V.meta.chatgptAccountId)throw j(V.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:H,settings:Z,holders:G,joinTimeoutMs:$.joinTimeoutMs??S4}}function k4($){try{let Z=JSON.parse($),G=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(G?.role!=="user")return!1;return(typeof G.content==="string"?G.content:Array.isArray(G.content)?G.content.map((Y)=>typeof Y?.text==="string"?Y.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function w4($){let Z={};for(let G of b4){let J=$.get(G);if(J)Z[G]=J}return Z}function AZ($,Z,G){let J=JSON.stringify([MZ($.configPath),MZ($.statePath)]),Y=V1.get(J);if(!Y)Y=D4(G,Z.settings()),V1.set(J,Y);let j=Y,K=R1($);K.setEnabled(j.settings.enabled);let H={location:{...Z,settings:()=>j.settings}};j.holders.push(H);let V=!1,L=async(U)=>{try{let T=H.location.settings();if(V||!T.enabled)return;if(U.kind!=="primary"){if(U.kind==="generate"&&k4(await U.request.clone().text())){if(V)return;j.manager.remove(U.sessionID)}return}let S=U.attempt.data,A=S?.kind==="pool"?"local":S?.kind==="vault"?"vault":void 0;if(!A)return;let f=U.request.headers,Z2=R4.some((H2)=>f.has(H2))||Z.parentOf!==void 0&&await Z.parentOf(U.sessionID)!==void 0;if(Z2&&!T.subagents)return;let b=await U.request.clone().text();if(V)return;let D=f.get("chatgpt-account-id")??void 0;j.manager.track({sessionKey:U.sessionID,bodyText:b,accountId:U.attempt.accountId,isSubagent:Z2,meta:{replayHeaders:w4(f),...D?{chatgptAccountId:D}:{},routingSessionId:U.sessionID,url:U.request.url,credentialMode:A}})}catch(T){Z.log?.warn("cachekeep capture failed",{error:T instanceof Error?T.message:String(T)})}};return{manager:j.manager,configure:(U)=>{Object.assign(j.settings,U),K.setEnabled(j.settings.enabled)},capture:L,forget:(U)=>j.manager.remove(U),async release(){if(V)return;V=!0;let U=j.holders.indexOf(H);if(U>=0)j.holders.splice(U,1);if(j.holders.length>0)return;if(V1.get(J)===j)V1.delete(J);j.manager.stop();let T;try{await Promise.race([j.manager.tick().catch(()=>{}),new Promise((S)=>{T=setTimeout(S,j.joinTimeoutMs),T.unref?.()})])}finally{clearTimeout(T)}}}}import{mkdirSync as y4}from"node:fs";import{dirname as I4,resolve as f4}from"node:path";function v4(){return qZ("opencode2")}var h4=2000;class kZ{path;options;sessions;frameTurns=new o2;#$=new Set;#Z=new Set;#G=new Set;#J=Promise.resolve();#X=!1;#z;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=RZ($,Z.uuid??d2)}get($,Z=d2){let G=this.sessions.get($);if(!G){let J=Z();G={threadID:J,turnID:Z(),windowID:`${J}:0`},this.sessions.set($,G),this.#Z.delete($),this.#G.delete($),this.#$.add($),this.#j()}return G}delete($){let Z=this.sessions.delete($);if(this.frameTurns.forget($),this.#$.delete($),Z)this.#Z.add($);else if(!this.#Z.has($))this.#G.add($);this.#j()}#j(){if(this.#z)return;this.#z=setTimeout(()=>{this.#z=void 0,this.save()},this.options.saveDelayMs??h4),this.#z.unref?.()}save(){if(clearTimeout(this.#z),this.#z=void 0,!this.#X)this.#X=!0,this.#J=this.#J.then(()=>{return this.#X=!1,this.#Q()});return this.#J}settled(){return this.#z?this.save():this.#J}#Y(){if(this.#G.size===0)return;let $;try{$=W$(this.path)}catch{$=new Map}for(let Z of this.#G)if($.has(Z)&&!this.sessions.has(Z))this.#Z.add(Z);this.#G.clear()}async#Q(){if(this.#Y(),this.#$.size===0&&this.#Z.size===0)return;let $=[...this.#$].flatMap((J)=>{let Y=this.sessions.get(J);return Y?[[J,Y]]:[]}),Z=[...this.#Z],G=null;try{if(y4(I4(this.path),{recursive:!0}),G=await this.#B(),!G)return;let J;try{J=W$(this.path)}catch{J=new Map}await this.options.afterRead?.();let Y=!1;for(let j of Z)if(J.delete(j))Y=!0;for(let[j,K]of $){if(J.get(j)===K.threadID)continue;J.set(j,K.threadID),Y=!0}if(Y)DZ(this.path,J)}catch{return}finally{await G?.release().catch(()=>{})}for(let[J,Y]of $)if(this.sessions.get(J)===Y)this.#$.delete(J);for(let J of Z)if(!this.sessions.has(J))this.#Z.delete(J)}#B(){return bZ(this.path,this.options.lockWaitMs??SZ)}}var wZ=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),yZ=globalThis,D1=yZ[wZ]??new Map;yZ[wZ]=D1;function g4($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.sessions instanceof Map&&typeof Z.get==="function"&&typeof Z.delete==="function"&&typeof Z.save==="function"&&typeof Z.settled==="function"&&(Z.frameTurns===void 0||Z.frameTurns!==null&&typeof Z.frameTurns.advance==="function"&&typeof Z.frameTurns.get==="function"&&typeof Z.frameTurns.completed==="function"&&typeof Z.frameTurns.forget==="function")}function IZ($=v4()){let Z=f4($),G=D1,J=D1.get(Z),Y=D1;if(J!==void 0&&!g4(J))G.compatible??=new Map,Y=G.compatible;let j=Y.get(Z);if(!j)j=new kZ(Z),Y.set(Z,j);let K=j;return K.frameTurns??=new o2,j}var V$=Symbol.for("cortexkit.openai-auth.v2.commands"),m4=w2("v2-command");function k1($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.closed instanceof AbortController&&typeof Z.menu?.open==="function"&&typeof Z.menu?.apply==="function"&&typeof Z.session?.get==="function"&&(Z.registration===void 0||Z.registration!==null&&typeof Z.registration.dispose==="function")}function U$($){m4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function l4(){let $=globalThis;return $[V$]??={locations:new Map},$[V$].locations??=new Map,$[V$]}async function uZ($,Z){let G=l4(),J=$.location.directory,Y={menu:Z,session:$.session,closed:new AbortController},j=await vZ(J),K=await fZ(mZ,j.dir,()=>lZ({...j,drain:gZ,apply:(T)=>{let S=G.locations.get(J);if(!k1(S))throw Error("The OpenAI menu location was closed");return S.menu.apply(T)}})),H=G.locations.get(J);if(G.locations.set(J,Y),k1(H))H.closed.abort(),await H.registration?.dispose();let V={name:"openai",description:"OpenAI account menu",async execute(T){let S=[...G.locations.values()].find(k1)?.session;if(!S)return U$("no live location");let A=await S.get({sessionID:T.sessionID}),f=G.locations.get(A.location.directory);if(!k1(f))return U$("location closed");let Z2=await hZ(T.sessionID,f.closed.signal);if(!Z2||G.locations.get(A.location.directory)!==f){if(!Z2&&!f.closed.signal.aborted)N$({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},T.sessionID);return U$(f.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let b=await f.menu.open(T.sessionID);N$(b,T.sessionID)}};G.command??=V,G.command.execute=V.execute;let L=G.command;try{Y.registration=await $.command.transform((T)=>{T.add(L)})}catch(T){if(Y.closed.abort(),G.locations.get(J)===Y)G.locations.delete(J);throw await K.release(),T}let U=!1;return async()=>{if(U)return;if(U=!0,Y.closed.abort(),G.locations.get(J)===Y)G.locations.delete(J);await K.release(),await Y.registration?.dispose()}}var u4="openai-auth-pool-browser",p4="openai-auth-pool-headless",c4="openai-auth-vault",d4="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Run /openai → Vault → Connect and approve the request before trying again.";async function U1($){if(await $.authority()!=="local")throw Error("This host is connected to the credential vault or its enrollment is unreadable; the login was not stored. Disconnect this host from the vault to add a local login.")}function nZ($){return{method:{id:c4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await pZ($.paths,$.name)!=="vault")throw Error(d4)}}}function oZ($){let Z=(G,J,Y)=>({method:{id:G,type:"oauth",label:J},async authorize(){if($.vault)await U1($.vault);let j=await $.beginLogin({version:$.version,headless:Y});return{url:j.url,instructions:j.instructions,mode:"auto",callback:j.completion}}});return[Z(u4,"ChatGPT (openai-auth pool, browser)",!1),Z(p4,"ChatGPT (openai-auth pool, headless)",!0)]}function H$($){let Z=(G)=>typeof G==="string"?G:"";return J1({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===iZ||cZ($)}function i4($){if($.accountId)return $.accountId;let Z=$.access?O1($.access):void 0;return Z?x1(Z):void 0}async function sZ($,Z,G,J={}){if(J.vault)await U1(J.vault);if(H$(G))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Y=dZ($,{rowLocks:(A)=>aZ(Z,A)}),j=await Y.read();if(j.status!=="ready")throw Error(`the account pool cannot be read (${j.status}); the login was not stored`);let K={type:"oauth",refresh:G.refresh,...G.access!==void 0?{access:G.access}:{},...G.expires!==void 0?{expires:G.expires}:{}},H=i4(G);if(J.vault)await U1(J.vault);let V=H!==void 0?{identity:H}:{};if(J.origin==="import"){let A=j.rows.find((f)=>H!==void 0&&f.identity===H||f.credential?.type==="oauth"&&f.credential.refresh===G.refresh);if(A)return{id:A.id,operation:"kept"}}let L=j.rows.filter((A)=>A.type==="oauth"&&!A.invalid),U=H?L.find((A)=>A.identity===H):void 0,T=j.rows.find((A)=>A.id===w1);if(U)return{id:(await Y.replace(U.id,K,V)).id,operation:"replaced"};if(!T){let A=await Y.add({id:w1,credential:K,...V,...G.label!==void 0?{label:G.label}:{}});return{id:A.id,operation:A.outcome==="added-disabled"?"added-disabled":"added"}}if(!T.invalid&&!T.credential)return{id:(await Y.replace(w1,K,V)).id,operation:"replaced"};let S=await Y.add({id:G.id,credential:K,...V,...G.label!==void 0?{label:G.label}:{}});return{id:S.id,operation:S.outcome==="added-disabled"?"added-disabled":S.outcome==="rotated"?"replaced":"added"}}function a4($){let Z=$.itemId!==void 0;switch($.sectionId){case"accounts":return Z?["enable","disable","remove","move"].includes($.actionId):$.actionId==="add";case"routing":return!Z&&["order","mode","maxSameAccountWait"].includes($.actionId);case"quota":return $.actionId==="check";case"limits":return Z?$.actionId==="floors":$.actionId==="killswitch";case"session":return!Z&&$.actionId==="clear-pin";case"vault":return Z?["enable","disable"].includes($.actionId):["connect","disconnect"].includes($.actionId);case"diagnostics":return!Z&&["logging","dump"].includes($.actionId);case"cache":return!Z&&["enabled","subagents","sustain","window"].includes($.actionId);case"reset":return Z&&["preview","spend","retry"].includes($.actionId);default:return!1}}function eZ($){let Z={...$,allowAction:a4,unavailableSections:[]};return{open:(G)=>rZ(Z,G),apply:(G)=>{let J=G!==null&&typeof G==="object"?G:{},Y=J.values&&typeof J.values==="object"&&!Array.isArray(J.values)?Object.fromEntries(Object.entries(J.values).filter(([,j])=>j===null||["string","number","boolean"].includes(typeof j))):void 0;return tZ(Z,{command:"openai",sectionId:typeof J.sectionId==="string"?J.sectionId:"",actionId:typeof J.actionId==="string"?J.actionId:"",...Y?{values:Y}:{},...J.confirmed===!0?{confirmed:!0}:{},...typeof J.itemId==="string"?{itemId:J.itemId}:{},...typeof J.sessionId==="string"?{sessionId:J.sessionId}:{}})}}}function n4($,Z){if(!$0($.modelID??$.id)){$.enabled=!1;return}let G=Z0($.id);if(G)$.limit={...G};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((J)=>[J.id,J])).values()]}function G0($){return $.model.transform((Z)=>{let G=Z.list(x2);for(let J of G){let Y=z0(String(J.id)),j=Y?G.find((K)=>String(K.id)===Y):void 0;Z.update(x2,String(J.id),(K)=>n4(K,j?.variants?.map((H)=>({...H,id:String(H.id)}))))}})}class F${log;pending=new Map;requests=new Map;writing=new Set;constructor($){this.log=$}async safely($){let Z=(async()=>{try{await $()}catch{this.log.warn("request dump failed")}})();this.writing.add(Z);try{await Z}finally{this.writing.delete(Z)}}async captureHttp($,Z){if(!J0())return;await this.safely(async()=>{let G={sessionID:Z.sessionID,accountId:Z.accountId,transport:"http",phase:"http",url:$.url,method:$.method,headers:new Headers($.headers),bodyText:await $.clone().text()};if(this.pending.set($,{attemptId:Z.attemptId,input:G}),this.requests.set(Z.attemptId,$),this.pending.size>512){let J=this.pending.keys().next().value;if(J)this.take(J)}})}take($){let Z=this.pending.get($);if(Z)this.pending.delete($),this.requests.delete(Z.attemptId);return Z?.input}async response($,Z){let G=this.take($);if(G)await this.safely(()=>y1({...G,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let G=this.requests.get($.attemptId),J=G&&this.take(G);if(!J)return;let{reason:Y,message:j}=Z.error,K=j?`${Y}: ${j}`:Y;await this.safely(()=>y1({...J,error:I1(K,G?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>y1({sessionID:Z.sessionID,accountId:Z.accountId,transport:"websocket",phase:"observed",bodyText:$}))}clear(){this.pending.clear(),this.requests.clear()}async settle(){await Promise.all(this.writing)}}class K${counts=new Map;record($,Z){let G=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof G==="number"&&Number.isFinite(G)?G:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function B0($){return async(Z)=>{let G=Z.credential;if(G.type!=="oauth"||!G.access)throw Error("the row holds no access token to poll with");let J=await X0({accessToken:G.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,J),j0(J,$.now(),!0)}}function W0($){let{source:Z,counts:G,now:J}=$,Y=async(L)=>{let U=await Z.rowAccess(L,await $.storage());if(!U?.row)throw new Y0("unknown_account",`${L==="main"?"Main":"Fallback"} account ${L} was not found.`);return Q0(L,U)},j=async(L)=>{if($.authority&&await $.authority()!=="local")return{account:L,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[U]=await Z.pollRows(await $.storage(),{ids:[L]});if(!U)return{account:L,ok:!1,error:"targeted quota refresh returned no result"};return{account:U.id,ok:U.ok,...U.error!==void 0?{error:U.error}:{}}},K=(L)=>Z.peek().rows.find((U)=>U.id===L),H=(L)=>{let U=K(L);if(!U)return null;let T=i2(U.quota)??{},S=G.applicable(U),A=Math.max(0,...[T.primary?.checkedAt,T.secondary?.checkedAt].filter((f)=>typeof f==="number"));return{quota:{...T,...S!==void 0?{resetCreditsApplicable:S}:{}},checkedAt:A,refreshAfter:A,...U.identity!==void 0?{accountId:U.identity}:{}}};return{resolveResetTarget:Y,refreshResetTargetQuota:j,quotaManager:{isRateLimited:(L)=>{let U=K(L);if(!U)return!1;let T=$.rateLimitMarks().get(U.id);return T!==void 0&&T>J()},getMain:()=>H("main"),getFallback:(L)=>H(L)}}}import{resolve as V0}from"node:path";var o4=1024;class L${pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=o4){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.reservations.delete($),this.pins.delete($);for(let Z of this.listeners)Z($)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}snapshot(){return new Map(this.pins)}placementSnapshot($){let Z=new Map(this.pins);for(let G of this.reservations.values())if(G.sessionId!==$)Z.set(G.sessionId,G.pin);return Z}reserve($,Z){let G={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,G),G}rollback($){if(this.reservations.get($.sessionId)===$)this.reservations.delete($.sessionId)}finish($,Z){if(this.reservations.get($.sessionId)!==$)return;if(this.rollback($),Z&&this.pins.get($.sessionId)===$.previous)this.set($.sessionId,Z)}get size(){return this.pins.size}set($,Z){this.reservations.delete($),this.pins.delete($),this.pins.set($,Z);for(let G of this.listeners)G($,Z);while(this.pins.size>this.limit){let G=this.pins.keys().next().value;if(G===void 0)break;this.forget(G)}}place($){return A1(this.placementSnapshot($.sessionId),$,(Z,G)=>this.set(Z,G))}}var U0=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),N0=globalThis,f1=N0[U0]??new Map;N0[U0]=f1;function s4($){if(!$||typeof $!=="object")return!1;let Z=$;return typeof Z.get==="function"&&typeof Z.forget==="function"&&typeof Z.subscribe==="function"&&typeof Z.snapshot==="function"&&typeof Z.place==="function"&&typeof Z.placementSnapshot==="function"&&typeof Z.reserve==="function"&&typeof Z.rollback==="function"&&typeof Z.finish==="function"}function H0($){let Z=JSON.stringify([V0($.configPath),V0($.statePath)]),G=f1,J=f1.get(Z);if(J!==void 0&&!s4(J)){let j=f1;j.compatibleV1??=new Map,G=j.compatibleV1}let Y=G.get(Z);if(!Y)Y=new L$,G.set(Z,Y);return Y}import{statSync as r4}from"node:fs";import{resolve as t4}from"node:path";function E0($){return $.map((Z)=>{try{let G=r4(Z);return`${G.ino}:${G.size}:${G.mtimeMs}:${G.ctimeMs}`}catch{return"?"}}).join("|")}function P$($){return E0([$.vault.paths.tokenPath,$.vault.paths.statePath])}function F0($){return E0([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+P$($)}class O0{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;protocol=A0;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:F0($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),G=this.subscriptions.get($.pins);if(!G){let J=new Set;G={producers:J,stop:$.pins.subscribe((Y,j)=>{let K=J.values().next().value;if(K)this.publish(K,{sessionId:Y,pin:j,accountId:j?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,G)}return G.producers.add($),this.timer??=setInterval(()=>{for(let J of this.producers){let Y={stamp:F0(J),roster:J.vault.snapshot()},j=this.observations.get(J);if(Y.stamp!==j?.stamp||Y.roster!==j?.roster)this.observations.set(J,Y),this.publish(J)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),G.producers.delete($),!G.producers.size)G.stop(),this.subscriptions.delete($.pins);if(!this.producers.size)clearInterval(this.timer),this.timer=void 0}}publish($,Z){return this.chain=this.chain.then(async()=>{if(!this.producers.has($))return;await($.write??x0)(this.file,$,Z,()=>this.producers.has($))}).catch(()=>{w2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var x0=async($,Z,G,J)=>{let j=await Z.vault.authority()!=="local",K=P$(Z),H=()=>J()&&Z.vault.enrolled()===j&&P$(Z)===K,V=await(j?H1(Z.paths):t2(Z.paths)),L=j?T0(Z.vault.snapshot()?.rows,new Set(Z.vault.routes().map((S)=>S.id)),V,Date.now()):_0((await Z.source.sidebarView()).rows,V,Date.now()),U={canWrite:H,vaultMode:j};if(await L0(L,$,U),!H()||!G)return;let T=L.vaultAccounts??L.fallbacks;if(G.accountId===void 0){await M0(G.sessionId,T,$,U);return}if(G.pin){let S=Date.now();await C0({sessionId:G.sessionId,assignment:{accountId:G.pin.accountId,wireAccountId:G.pin.wireIdentity,inputBytes:G.pin.inputBytes??0,quotaCheckedAt:G.pin.quotaCheckedAt,assignedAt:S,lastSeenAt:S},validPinnedAccountIds:[...j?[]:["main"],...T.filter((A)=>A.enabled).map((A)=>A.id)]},$,U)}await P0({sessionId:G.sessionId,activeId:G.accountId,route:G.route??L.route,updatedAt:Date.now()},T,$,U)},A0=2,q0=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),S0=globalThis,N1=S0[q0]??new Map;S0[q0]=N1;function b0($,Z=K0(),G=2000){let J=t4(Z),Y=N1.get(J);if(Y?.protocol!==A0)Y=new O0(J,G),N1.set(J,Y);let j=Y;$={...$,write:$.write??x0};let K=j.add($),H=!1;for(let[V,L]of $.pins.snapshot())j.publish($,{sessionId:V,pin:L,accountId:L.accountId,route:"sticky-balanced"});return{publish:()=>j.publish($),route:(V,L,U)=>{j.publish($,{sessionId:V,accountId:L,route:U})},async release(){if(H)return;if(H=!0,K(),await j.settled(),j.empty&&N1.get(J)===j)N1.delete(J)}}}var h1="cortexkit-openai-auth",Z5=5000;async function R0($,Z,G,J=new X1,Y,j,K){let H=new F$(G),V=new e4,L=new Map,U=new Map,T=(b)=>{U.delete(b);for(let D of L.keys())if(D.startsWith(`${b}:`))L.delete(D)},S=(b)=>{K?.(b.sessionID),j?.send(b.sessionID,b.frame)},f=await u1({session:{hook:(b,D,H2)=>$.session.hook(b,async(X2)=>{let I=b==="http.request"?X2:void 0,p=b==="experimental.ws.handshake"?X2:void 0,M2=(I?I.request.headers:p?new Headers(p.headers):void 0)?.get("authorization")===`Bearer ${k2(Z.providerID)}`,t={};if(p)L.delete(`${p.sessionID}:${p.kind}`);try{await V.run(t,()=>D(X2))}catch(w){if(M2&&!(w instanceof L2))throw f0(w);throw w}if(I&&M2&&t.attempt){let w=I.request.headers.get("thread-id");if(w)I.request.headers.set("session-id",w)}if(I&&M2&&t.attempt)await H.captureHttp(I.request,t.attempt);if(I&&M2&&t.attempt)await Y?.({sessionID:I.sessionID,kind:I.kind,request:I.request,attempt:t.attempt});if(p&&M2&&t.attempt)p.headers["session-id"]=J.get(p.sessionID).threadID;if(b==="experimental.ws.send"){let w=X2,u=L.get(`${w.sessionID}:${w.kind}`);if(u)await H.frame(w.frame,u.attempt);if(u&&w.kind==="primary")S(w)}if(I||p){let w=I??p;if(!w)return;let o=(I?I.request.headers:new Headers(w.headers)).get("authorization")?.replace(/^Bearer /,"");if(M2&&o)U.set(w.sessionID,o);else U.delete(w.sessionID);if(p){let m=`${p.sessionID}:${p.kind}`;if(M2&&o&&t.attempt)L.set(m,{bearer:o,attempt:t.attempt,url:p.url,headers:new Headers(Object.entries(p.headers).filter(([E2])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(E2.toLowerCase())))});else L.delete(m)}if(U.size>512){let m=U.keys().next().value;if(m)U.delete(m)}if(L.size>512){let m=L.keys().next().value;if(m)L.delete(m)}}else if(b==="experimental.ws.receive"){let w=X2,u=L.get(`${w.sessionID}:${w.kind}`);if(u){if(J.frameReceived(w.sessionID,w.frame),w.kind==="primary"){let o;if(j?.receive(w.sessionID,w.frame,(m)=>{o=m}),o)try{let m=y$(o,u.url,u.headers,J);if(m)await Y?.({sessionID:w.sessionID,kind:"primary",request:m,attempt:u.attempt})}catch(m){G.warn("cachekeep WebSocket capture failed",{error:m instanceof Error?m.message:String(m)})}}w.frame=v0(w.frame,u.bearer)}}else if(b==="retry"){let w=X2,u=U.get(w.sessionID);if(u)Object.assign(w.error,{message:I1(w.error.message,u)})}},H2)},event:{subscribe:(b)=>async function*(){for await(let D of $.event.subscribe(b)){if(D.type==="session.deleted")T(D.data.sessionID);yield D}}()}},{...Z,rewriteRequest:async(b)=>{let D=V.getStore();if(D)D.attempt=b.attempt;return Z.rewriteRequest?.(b)},rewriteHandshakeURL:(b)=>{let D=V.getStore();if(D)D.attempt=b.attempt;return Z.rewriteHandshakeURL?.(b)},onAttemptEnd:async(b,D)=>{await H.end(b,D),await Z.onAttemptEnd?.(b,D)},rewriteResponse:async(b)=>{await H.response(b.request,b.response.status);let D=await Z.rewriteResponse?.(b)??b.response;return h0(D,b.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(b)=>{let D=b.get("authorization");return D?.startsWith("Bearer ")?D.slice(7):void 0}},hostRetryLimit:r2,logger:{warn:(b,D)=>G.warn(b,{data:D})}}),Z2=f.dispose;return{...f,dispose:async()=>{U.clear(),L.clear(),await Z2(),await H.settle(),H.clear()}}}function T$($={}){return{id:h1,setup:(Z)=>z5(Z,$)}}async function z5($,Z={}){let h=[];try{let G=w2("opencode2");let J=w2("quota");let Y=Z.version??m0;await t0({version:Y,...Z.runtimeLayout});let j=Z.paths??(()=>u0(g0()));let K=await H1(j());let H=K?.logging?.level;if(H&&typeof H==="string")k0(H);let V=Z.fetch??fetch;let L=Z.now??Date.now;let U=Z.poolMigration??$4;if(!U&&!e2(j().configPath)){G.info("openai-auth stands aside on OpenCode 2: this install has not moved into the account pool and the migration is switched off, so OpenCode 2 serves its own ChatGPT login");let _=(s)=>{throw new L2({kind:"no-account",providerID:x2,sessionID:s.sessionID,requestKind:s.kind,message:q1})},g=await R0($,{providerID:x2,chooseAccount:_,accountHeaders:_},G);return()=>g.dispose()}let T=Z.vault?.firstRosterWaitMs??i0;let S=e0({host:"opencode",stateDir:Z.vault?.stateDir??I0(j().statePath),reservedRouteIds:()=>I.peek().rows.map((_)=>_.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>V},j());let A=S.vault;let f=async()=>await A.authority()==="local"?t2(j()):H1(j());let Z2=!1;let b=!1;const D=F1(h,{[Symbol.dispose](){if(!Z2)S.release()}},0);await A.authority();let H2=S.firstRoster;let X2=new K$;let I=new a0({paths:j,refreshProvider:async(_)=>{let g=await y0({refreshToken:_.refresh,fetchImpl:V,now:L}),s=w0({id_token:"",access_token:g.access,refresh_token:g.refresh});return{...g,...s?{identity:s}:{}}},pullQuota:B0({fetchImpl:V,now:L,counts:X2,logger:J}),now:L,vaultIdentities:()=>A.identities(),vaultMode:()=>A.enrolled(),vaultAuthority:()=>A.authority(),vaultFirstRoster:H2,vaultFirstRosterBackgroundWaitMs:T,log:w2("pool")});if(await A.authority()==="local")await I.load();let p=new n0({pool:I,vault:A,log:(_)=>G.warn(_)});const I2=F1(h,{[Symbol.dispose](){if(!Z2)p.dispose()}},0);let M2=Z.heartbeat===!1?void 0:await s0({version:Y,logger:w2("heartbeat")});let t=Z.fence??(()=>l0({currentVersion:Y}));let w=Z.slot??Z4();let u=async()=>p0(j(),await w.get({path:{id:"openai"}}));let o=!1;let m=U?o0({paths:j,slot:w,version:Y,fence:t,runDeps:{vaultServes:()=>A.serves()},paused:async()=>await A.authority()!=="local",migrate:async(_)=>{let g=await c0(_);if(o=g.status==="refused",!b)await I.load();return g},adopt:async(_)=>{if(b)return{status:"retry",reason:"unsettled"};if(!await C$(H2,T))return{status:"retry",reason:"vault-roster-pending"};if(b)return{status:"retry",reason:"unsettled"};let g=await d0(_);if(!b)await I.load();return g}}):void 0;m?.start();S.start();let E2=H0(j());let A2=b0({paths:j(),source:I,pins:E2,vault:A},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const R2=F1(h,{[Symbol.dispose](){if(!Z2)A2.release()}},0);A2.publish();let F2=Z.codex??new X1(void 0,void 0,IZ());let $1=EZ(K);let V2=R1(j());let z2=AZ(j(),{source:I,limits:p,storage:f,vault:A,accounts:n1(j()),settings:()=>$1,parentOf:async(_)=>(await $.session.get({sessionID:_}))?.parentID??void 0,fetch:V,log:w2("cachekeep")},{now:L,codexResponsesUrl:v1().codexApiEndpoint,...Z.cacheKeep});const g2=F1(h,{[Symbol.dispose](){if(!Z2)z2.release()}},0);let X=NZ({limits:p,codex:F2,onRoute:A2.route,source:I,slotPlaceholderWithoutMain:u,storage:f,pins:E2,sessionAccounts:n1(j()),vault:A,awaitVaultRoster:async()=>{await C$(A.awaitRequestRoster(),S1)},responsesLite:()=>v1().responsesLite,codexEndpoint:()=>v1().codexApiEndpoint,now:L,log:G});let N=await R0($,X.adapter,G,F2,(_)=>z2.capture(_),V2,(_)=>z2.forget(_));X.attach(N);let M=await $.session.hook("prompt",(_)=>{X.beginTurn(_.sessionID)});let P=async(_)=>{if(await U1(A),e2(j().configPath))return;if(await m?.idle(),e2(j().configPath))return;if(o&&!H$(_)&&(await t()).open){await I.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let R=async(_)=>{await P(_);let g=await sZ(I.poolStore(),j(),_,{vault:A});if(!e2(j().configPath))await m?.requestAdoption();await I.load(),G.info("ChatGPT login stored in the account pool",g)};let x=await m1($,{integrationID:x2,methods:oZ({beginLogin:Z.beginLogin??M$,version:Y,vault:A}),onLogin:(_)=>R(_),label:"ChatGPT (openai-auth account pool)",vault:nZ(A)});let q=await G0($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let y=$.command&&$.location?await uZ({session:$.session,command:$.command,location:$.location},Z.controlPlane??eZ({...W0({rateLimitMarks:()=>p.marks(),source:I,storage:f,counts:X2,now:L,authority:()=>A.authority()}),fetchImpl:V,now:L,randomUUID:$5,accountStoragePath:j().configPath,accountStatePath:j().statePath,packageVersion:Y,layoutNotice:r0,loadAccounts:t2,store:()=>I.poolStore(),migration:async()=>{if(e2(j().configPath))return{migrated:!0};let _=await t();return{migrated:!1,blockers:_.open?[]:_.blockers}},beginAccountLogin:Z.beginLogin??M$,refreshAllQuota:async()=>(await I.pollRows(await t2(j()))).map((_)=>({..._,account:_.id})),getStickyRouting:async(_)=>E2.get(_),cacheKeepManager:z2.manager,setCacheKeepEnabled:(_)=>z2.configure({enabled:_}),setCacheKeepSubagents:(_)=>z2.configure({subagents:_}),setCacheKeepSustain:(_)=>z2.configure({sustain:_}),setCacheKeepWindow:(_)=>z2.configure({window:_}),afterWrite:()=>I.load(),refreshSidebar:()=>A2.publish(),clearStickyRouting:async(_)=>{let g=E2.get(_)!==void 0;return E2.forget(_),g},vault:A})):void 0;let v=new AbortController;(async()=>{try{for await(let _ of $.event.subscribe({signal:v.signal}))if(_.type==="session.deleted")X.forgetSession(_.data.sessionID),z2.forget(_.data.sessionID),V2.forget(_.data.sessionID)}catch(_){if(!v.signal.aborted)G.warn("stopped listening for session deletion",{error:_ instanceof Error?_.message:String(_)})}})();Z2=!0;return async()=>{b=!0,v.abort(),X.dispose();let _=z2.release();await y?.(),m?.dispose(),await p.dispose(),await A2.release(),await Promise.allSettled([N.dispose(),M.dispose(),x.dispose(),q.dispose()]);let g;try{await Promise.race([Promise.all([m?.idle(),I.settled(),F2.store?.settled(),_]),new Promise((s)=>{g=setTimeout(s,Z5),g.unref?.()})])}finally{clearTimeout(g),await S.release(),await M2?.release()}}}catch(k){var a=k,G2=1}finally{D0(h,a,G2)}}var G5=T$(),D7={id:h1,setup:G5.setup,server:z4.server};export{D7 as default,T$ as createOpenAIAuthPlugin,h1 as OPENAI_AUTH_PLUGIN_ID};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/opencode-openai-auth",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.10.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -66,18 +66,18 @@
|
|
|
66
66
|
},
|
|
67
67
|
"devDependencies": {
|
|
68
68
|
"@ai-sdk/openai": "3.0.88",
|
|
69
|
-
"@cortexkit/common-auth": "^0.
|
|
69
|
+
"@cortexkit/common-auth": "^0.39.1",
|
|
70
70
|
"@cortexkit/openai-auth-core": "workspace:*",
|
|
71
|
-
"@opencode/plugin": "2.2.
|
|
71
|
+
"@opencode/plugin": "2.2.5"
|
|
72
72
|
},
|
|
73
73
|
"dependencies": {
|
|
74
|
-
"@cortexkit/claustrum-client": "^0.
|
|
74
|
+
"@cortexkit/claustrum-client": "^0.15.0",
|
|
75
75
|
"@cortexkit/private-files": "^0.2.2",
|
|
76
76
|
"@cortexkit/subc-client": "^0.22.0",
|
|
77
77
|
"@opentui/core": ">=0.7.0",
|
|
78
78
|
"@opentui/solid": ">=0.7.0",
|
|
79
|
-
"ai": "^7.0.
|
|
79
|
+
"ai": "^7.0.159",
|
|
80
80
|
"jsonc-parser": "^3.3.1",
|
|
81
|
-
"solid-js": "1.9.
|
|
81
|
+
"solid-js": "1.9.18"
|
|
82
82
|
}
|
|
83
83
|
}
|