@cortexkit/opencode-openai-auth 1.0.4 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/bin.js +7 -7
  2. package/dist/{index-dryydk6b.js → index-116q849r.js} +2 -2
  3. package/dist/{index-5dg931q0.js → index-4fnghj9e.js} +1 -1
  4. package/dist/{index-bgq9d21h.js → index-66asrje2.js} +1 -1
  5. package/dist/{index-jye6vccc.js → index-826s1yxa.js} +2 -2
  6. package/dist/index-a69gr76b.js +2 -0
  7. package/dist/{index-egrty6tz.js → index-fsky1rsh.js} +2 -2
  8. package/dist/{index-envpbt0k.js → index-fsxbncpw.js} +1 -1
  9. package/dist/{index-99esnzg0.js → index-h263aftt.js} +8 -8
  10. package/dist/{index-yeyp8t0k.js → index-nx2qh047.js} +1 -1
  11. package/dist/{index-45qgkb0m.js → index-pg305s90.js} +1 -1
  12. package/dist/{index-2hch7e8n.js → index-ssj7m2rd.js} +2 -2
  13. package/dist/{index-k4eacw7x.js → index-y4gxyxqd.js} +2 -2
  14. package/dist/{index-9reyazwh.js → index-ydz3hbhc.js} +2 -2
  15. package/dist/index.d.ts +2 -2
  16. package/dist/index.js +1 -1
  17. package/dist/{map-CCbSZIhT.d.ts → map-m6f5a_IA.d.ts} +1 -1
  18. package/dist/{pool-lifecycle-DqKq8Eej.d.ts → pool-lifecycle-C_6YRmsh.d.ts} +21 -21
  19. package/dist/{port-file-CZ9MIdy2.d.ts → port-file-ZPlxXB4G.d.ts} +1 -1
  20. package/dist/{protocol-CSIDDBDf.d.ts → protocol-DctqemRI.d.ts} +1 -1
  21. package/dist/rpc/port-file.d.ts +1 -1
  22. package/dist/rpc/port-file.js +1 -1
  23. package/dist/rpc/protocol.d.ts +1 -1
  24. package/dist/rpc/protocol.js +1 -1
  25. package/dist/rpc/rpc-client.d.ts +3 -3
  26. package/dist/rpc/rpc-client.js +1 -1
  27. package/dist/rpc/rpc-dir.js +1 -1
  28. package/dist/{sidebar-state-BCxFpH68.d.ts → sidebar-state-z_M7Trnd.d.ts} +4 -4
  29. package/dist/sidebar-state.d.ts +1 -1
  30. package/dist/sidebar-state.js +1 -1
  31. package/dist/{token-vykm9bxh.js → token-bzhkgc29.js} +1 -1
  32. package/dist/token-util-4a2xxnpg.js +1 -0
  33. package/dist/tui-preferences.js +1 -1
  34. package/dist/tui.d.ts +2 -2
  35. package/dist/v2/server.d.ts +1 -1
  36. package/dist/v2/server.js +1 -1
  37. package/package.json +2 -2
  38. package/src/tui-compiled/raw/shared/0332701351b3eeec-format.js +65 -34
  39. package/src/tui-compiled/raw/shared/d5a8f1061ee2f114-index.js +1 -1
  40. package/src/tui-compiled/runtime/shared/0332701351b3eeec-format.js +65 -34
  41. package/src/tui-compiled/runtime/shared/d5a8f1061ee2f114-index.js +1 -1
  42. package/dist/index-yf6arn5w.js +0 -2
  43. package/dist/token-util-gmn5yaqc.js +0 -1
@@ -1,4 +1,4 @@
1
- import{Ed as u,Fd as P,yd as h}from"./index-2hch7e8n.js";import{be as M,ce as R,he as S}from"./index-dryydk6b.js";import"./index-bgq9d21h.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.
1
+ import{Dd as u,Ed as P,xd as h}from"./index-ssj7m2rd.js";import{ae as M,be as R,ge as S}from"./index-116q849r.js";import"./index-66asrje2.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/tui.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { t as ApplyRequest } from "./protocol-CSIDDBDf.js";
2
- import { S as SpendControlReading, b as SidebarState, l as QuotaPacing, r as AccountQuota, u as QuotaWindow } from "./sidebar-state-BCxFpH68.js";
1
+ import { t as ApplyRequest } from "./protocol-DctqemRI.js";
2
+ import { S as SpendControlReading, b as SidebarState, l as QuotaPacing, r as AccountQuota, u as QuotaWindow } from "./sidebar-state-z_M7Trnd.js";
3
3
  import { TuiPluginModule } from "@opencode-ai/plugin/tui";
4
4
  //#region src/tui.d.ts
5
5
  /** One drawer action as the RPC apply request carries it, with its session. */
@@ -1,4 +1,4 @@
1
- import { c as BeginAccountLoginOptions, h as AccountPaths, l as BeginAccountLoginResult, n as HostSlotAdapter, s as OpenAiVaultOptions, t as PoolLifecycleDeps } from "../pool-lifecycle-DqKq8Eej.js";
1
+ import { c as BeginAccountLoginOptions, h as AccountPaths, l as BeginAccountLoginResult, n as HostSlotAdapter, s as OpenAiVaultOptions, t as PoolLifecycleDeps } from "../pool-lifecycle-C_6YRmsh.js";
2
2
  import { Plugin } from "@opencode/plugin";
3
3
  import "@opencode/plugin/promise/session";
4
4
  import "@opencode/plugin/promise/integration";
package/dist/v2/server.js CHANGED
@@ -1,3 +1,3 @@
1
- import{c as H$}from"../index-envpbt0k.js";import{C as b1,D as y1,F as n2,G as a2,H as s2,S as W$,Y as o2,Z as r2,aa as U$,d as e1,e as k2,f as G2,g as C2,h as z$,i as J$,j as X$,k as j$,l as w2,m as G$,n as Q$,o as R2,p as U1,q as C1,r as N1,s as F1,t as P1,u as T1,v as M1,w as B$,x as V$,y as W2,z as L1}from"../index-5dg931q0.js";import{$a as V1,$b as r1,Ba as l1,Ca as z1,Da as J1,Ea as X1,Ia as q1,Ib as E1,Ka as x1,Ma as c1,Na as d1,Oa as j1,Pb as w1,Ta as i1,Xa as G1,Ya as Q1,Zb as s1,_a as B1,_b as o1,ac as t1,cc as $$,dc as S1,eb as N2,kb as n1,lb as V2,mc as Y$,nc as K$,ob as a1,oc as Z$,pb as W1,pc as R1,qb as H1,sa as H2,ta as U2,ua as p1}from"../index-99esnzg0.js";import"../index-9reyazwh.js";import{nd as Z1}from"../index-yf6arn5w.js";import"../index-2hch7e8n.js";import"../index-jye6vccc.js";import"../index-egrty6tz.js";import{Vd as j2}from"../index-k4eacw7x.js";import"../index-dryydk6b.js";import"../index-45qgkb0m.js";import{te as g1,ue as u1}from"../index-bgq9d21h.js";class c 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 s($){return`common-auth-placeholder.${$}`}function c2($){let K=s($.integrationID);return{type:"oauth",methodID:$.methodID,access:K,refresh:K,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function J2($,K){if($?.type!=="oauth")return!1;let J=K===void 0?void 0:s(K),X=(j)=>J===void 0?j.startsWith("common-auth-placeholder."):j===J;return X($.access)&&X($.refresh)}var d2="No browser sign-in: this connects the plugin to the accounts in its vault.";async function M2($,K){let J=K.now??Date.now,{integrationID:X}=K,j=(T)=>c2({integrationID:X,methodID:T,now:J()}),B=async(T,O)=>{return await K.onLogin(T,{integrationID:X,methodID:O}),j(O)},R=(T)=>async(O)=>{let H=T.method.id,W=await T.authorize(O),y={url:W.url,instructions:W.instructions,...W.expiresAt===void 0?{}:{expiresAt:W.expiresAt}};if(W.mode==="auto")return{...y,mode:"auto",callback:W.callback.then((E)=>B(E,H))};let b=W.callback;return{...y,mode:"code",callback:async(E)=>B(await b(E),H)}};return $.integration.transform((T)=>{let O=K.label===void 0?{}:{label:()=>K.label};for(let y of K.methods)T.method.update({integrationID:X,method:y.method,authorize:R(y),refresh:async(b)=>{if(!J2(b,X))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return j(b.methodID)},...O});let H=K.vault;if(H===void 0)return;let W=H.method.id;T.method.update({integrationID:X,method:H.method,authorize:async()=>({url:"",instructions:H.instructions??d2,mode:"auto",callback:Promise.resolve().then(()=>H.activate({integrationID:X,methodID:W})).then(()=>j(W))}),refresh:async(y)=>{if(!J2(y,X)||y.methodID!==W)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return j(W)},...O})})}function P$($){let K=[],J;for(let X of $.split(/\r?\n/))if(X.startsWith("data:"))K.push(X.slice(5).replace(/^ /,""));else if(X.startsWith("event:"))J=X.slice(6).trim();if(K.length===0)return;return J===void 0?{data:K.join(`
1
+ import{c as H$}from"../index-fsxbncpw.js";import{C as b1,D as y1,F as n2,G as a2,H as s2,S as W$,Y as o2,Z as r2,aa as U$,d as e1,e as k2,f as G2,g as C2,h as z$,i as J$,j as X$,k as j$,l as w2,m as G$,n as Q$,o as R2,p as U1,q as C1,r as N1,s as F1,t as P1,u as T1,v as M1,w as B$,x as V$,y as W2,z as L1}from"../index-4fnghj9e.js";import{$a as V1,$b as t1,Ba as l1,Ca as z1,Da as J1,Ea as X1,Hb as E1,Ia as q1,Ka as x1,Ma as c1,Na as d1,Oa as j1,Ob as w1,Ta as i1,Xa as G1,Ya as Q1,Yb as s1,Zb as o1,_a as B1,_b as r1,bc as $$,cc as S1,eb as N2,kb as n1,lb as V2,lc as Y$,mc as K$,nc as Z$,ob as a1,oc as R1,pb as W1,qb as H1,sa as H2,ta as U2,ua as p1}from"../index-h263aftt.js";import"../index-ydz3hbhc.js";import{md as Z1}from"../index-a69gr76b.js";import"../index-ssj7m2rd.js";import"../index-826s1yxa.js";import"../index-fsky1rsh.js";import{Ud as j2}from"../index-y4gxyxqd.js";import"../index-116q849r.js";import"../index-pg305s90.js";import{se as g1,te as u1}from"../index-66asrje2.js";class c 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 s($){return`common-auth-placeholder.${$}`}function c2($){let K=s($.integrationID);return{type:"oauth",methodID:$.methodID,access:K,refresh:K,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function J2($,K){if($?.type!=="oauth")return!1;let J=K===void 0?void 0:s(K),X=(j)=>J===void 0?j.startsWith("common-auth-placeholder."):j===J;return X($.access)&&X($.refresh)}var d2="No browser sign-in: this connects the plugin to the accounts in its vault.";async function M2($,K){let J=K.now??Date.now,{integrationID:X}=K,j=(T)=>c2({integrationID:X,methodID:T,now:J()}),B=async(T,O)=>{return await K.onLogin(T,{integrationID:X,methodID:O}),j(O)},R=(T)=>async(O)=>{let H=T.method.id,W=await T.authorize(O),y={url:W.url,instructions:W.instructions,...W.expiresAt===void 0?{}:{expiresAt:W.expiresAt}};if(W.mode==="auto")return{...y,mode:"auto",callback:W.callback.then((E)=>B(E,H))};let b=W.callback;return{...y,mode:"code",callback:async(E)=>B(await b(E),H)}};return $.integration.transform((T)=>{let O=K.label===void 0?{}:{label:()=>K.label};for(let y of K.methods)T.method.update({integrationID:X,method:y.method,authorize:R(y),refresh:async(b)=>{if(!J2(b,X))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return j(b.methodID)},...O});let H=K.vault;if(H===void 0)return;let W=H.method.id;T.method.update({integrationID:X,method:H.method,authorize:async()=>({url:"",instructions:H.instructions??d2,mode:"auto",callback:Promise.resolve().then(()=>H.activate({integrationID:X,methodID:W})).then(()=>j(W))}),refresh:async(y)=>{if(!J2(y,X)||y.methodID!==W)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return j(W)},...O})})}function P$($){let K=[],J;for(let X of $.split(/\r?\n/))if(X.startsWith("data:"))K.push(X.slice(5).replace(/^ /,""));else if(X.startsWith("event:"))J=X.slice(6).trim();if(K.length===0)return;return J===void 0?{data:K.join(`
2
2
  `)}:{event:J,data:K.join(`
3
3
  `)}}function L2($,K){let J=new TextDecoder,X="",j=(R)=>{let T=P$(R);if(!T)return;try{$(T)}catch(O){K(O)}},B=()=>{for(;;){let R=/\r?\n\r?\n/.exec(X);if(!R)return;let T=X.slice(0,R.index);X=X.slice(R.index+R[0].length),j(T)}};return new TransformStream({transform(R,T){T.enqueue(R),X+=J.decode(R,{stream:!0}),B()},flush(){if(X+=J.decode(),B(),X.trim()!=="")j(X);X=""}})}var i2=512,Y2="x-common-auth-attempt",e=($,K)=>JSON.stringify([$,K]),o=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function T$($){let K=$.headers;return typeof K==="object"&&K!==null}function M$($,K){let J=$.getReader();return new ReadableStream({async pull(X){let j;try{j=await J.read()}catch(B){K({reason:"failed",message:B instanceof Error?B.message:String(B)}),X.error(B);return}if(j.done)K(),X.close();else X.enqueue(j.value)},async cancel(X){K({reason:"cancelled",...X===void 0?{}:{message:String(X)}}),await J.cancel(X)}})}function _2($,K){for(let[J,X]of Object.entries(K)){let j=J.toLowerCase();for(let B of Object.keys($))if(B.toLowerCase()===j)delete $[B];if(X!==null)$[J]=X}}function L$($,K){for(let[J,X]of Object.entries(K))if(X===null)$.delete(J);else $.set(J,X)}async function q2($,K,J={}){let{providerID:X}=K,j=J.gateOnPlaceholder,B=(Y)=>j===void 0||j.credential(Y)===s(X),R=J.logger,T=Math.max(1,J.maxRecords??i2),O=[...J.hostCredentials??[s(X)],...j?[s(X)]:[]].filter((Y)=>Y!==""),H=new Map,W=new WeakMap,y=new Map,b=new Set,E=new Map,v=!1,f=!1,d=new Map,I=0,u=!1,g=new Map,h=(Y,Z)=>{try{R?.warn(Y,Z)}catch{}},z=(Y)=>Y instanceof Error?Y.message:String(Y),V=async(Y,Z)=>{let G=d.get(Y);if(!G||G.size===0)return;await Promise.all([...G].map(async(Q)=>{try{await Q(Z)}catch(M){h("opencode2 auth listener threw; the request is unaffected",{event:Y,error:z(M)})}}))},F=async(Y,Z)=>{try{await K.onAttemptEnd?.(Y,Z)}catch(G){h("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:Y.attemptId,error:z(G)})}},C=(Y,Z)=>{if(Y.ended||!Y.attempt)return;let G={...Y.status===void 0?{}:{status:Y.status},outputStarted:Y.outputStarted,...Y.limit?{limit:Y.limit.signal}:{},...Z?{error:Z}:{}};if(Z)Y.endError=Z;Y.ended=F(Y.attempt,G)},A=(Y,Z)=>C(Y,{reason:"abandoned",message:Z}),P=(Y)=>[...H.values()].filter((Z)=>Z.key===Y),D=(Y)=>P(Y).at(-1),k=(Y)=>{if(H.delete(Y.id),!P(Y.key).length)y.delete(Y.key)},q=(Y)=>{H.set(Y.id,Y);while(H.size>T){let Z=H.values().next().value;if(Z===void 0)break;A(Z,"dropped to keep the record bound"),k(Z)}},m=(Y)=>Y.accountId===void 0?void 0:{...Y.scope,accountId:Y.accountId},i=(Y,Z)=>new c({kind:"no-account",providerID:X,sessionID:Y.sessionID,requestKind:Y.kind,...Z===void 0?{}:{message:Z}}),l=(Y)=>{g.get(Y)?.clear(),g.delete(Y)},p=async(Y,Z)=>{let G=()=>i(Y,`${X} ${Y.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(u)throw G();let Q=g.get(Y.sessionID);if(!Q)Q=new Set,g.set(Y.sessionID,Q);let M={};Q.add(M);let x=()=>{if(!Q.has(M))throw G()};try{return await Z(x)}finally{if(Q.delete(M),Q.size===0&&g.get(Y.sessionID)===Q)g.delete(Y.sessionID)}},U=(Y,Z)=>{for(let[G,Q]of Z)if(O.some((M)=>Q.includes(M)))throw new c({kind:"host-credential-on-wire",providerID:X,sessionID:Y.sessionID,requestKind:Y.kind,message:`${X} ${Y.kind} request still carries the host's placeholder credential in ${G}; the adapter's account headers must replace it`})},L=(Y)=>{for(let Z of P(Y))if(Z.ended||!Z.attempt)k(Z);else if(Z.transport==="ws"||Z.judged)A(Z,"a newer attempt of its session and kind began"),k(Z)},S=async(Y,Z,G,Q)=>{let M=e(Y.sessionID,Y.kind),x=y.get(M);y.delete(M);let N=x?.accountId??D(M)?.accountId;L(M);let _={...Y,...N===void 0?{}:{previousAccountId:N},...x?.rerouteFrom===void 0?{}:{rerouteFrom:x.rerouteFrom}},w=await K.chooseAccount(_);G();let a={},p2;if(w!==void 0){let Q2=await K.accountHeaders({...Y,accountId:w});if(G(),T$(Q2))a=Q2.headers,p2=Q2.attempt;else a=Q2}let l2=`attempt-${++I}`,z2={id:l2,key:M,scope:Y,accountId:w,headers:a,attempt:w===void 0?void 0:{...Y,accountId:w,attemptId:l2,transport:Q,data:p2},...Q===void 0?{}:{transport:Q},outputStarted:!1};if(q(z2),z2.attempt)V("select",{...Y,accountId:z2.attempt.accountId,hook:Z,..._.previousAccountId===void 0?{}:{previousAccountId:_.previousAccountId},..._.rerouteFrom===void 0?{}:{rerouteFrom:_.rerouteFrom},handle:z2.attempt});return z2},Z2=async(Y,Z,G,Q,M)=>{let x=e(Y.sessionID,Y.kind),N=Q===void 0?void 0:H.get(Q);if(N?.key!==x)N=void 0;if(!N){if(N=D(x),P(x).filter((w)=>w.transport===void 0&&!w.ended).length>1&&!f)f=!0,h("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:Y.sessionID,kind:Y.kind})}if(!N||N.transport!==void 0||N.ended)N=await S(Y,Z,M,G);else if(N.transport=G,N.attempt)N.attempt.transport=G;if(G==="ws"){for(let _ of P(x))if(_!==N&&_.transport==="ws")A(_,"a newer attempt of its session and kind went out over WebSocket")}return N},$2=async(Y,Z)=>{try{return await Z()}catch(G){throw C(Y,{reason:"failed",message:z(G)}),G}},h2=(Y,Z)=>{let G=P(e(Y,Z)).filter((Q)=>Q.transport==="ws").at(-1);return G?.attempt!==void 0&&!G.ended?G:void 0},P2=(Y,Z,G)=>{let Q=m(Y);if(!Q||!Y.attempt||Y.limit)return;Y.limit={signal:Z,delivered:V("limit",{...Q,via:G,limit:Z,outputStarted:Y.outputStarted,handle:Y.attempt})}},v2=(Y,Z,G,Q)=>{let M=m(Y);if(!M||!Y.attempt)return;V("quota",{...M,transport:Z,...Q===void 0?{}:{status:Q},quota:G,handle:Y.attempt})},m2=(Y,Z,G,Q)=>{let M=Y.attempt;if(!M)return;let x=K.inspectEvent?.(Q===void 0?{transport:Z,data:G,attempt:M}:{transport:Z,data:G,event:Q,attempt:M});if(!x)return;if(x.quota!==void 0)v2(Y,Z,x.quota);if(x.outputStarted)Y.outputStarted=!0;if(x.limit)P2(Y,x.limit,Z);if(x.error!==void 0)C(Y,{reason:"failed",message:x.error});else if(x.done)C(Y)},C$=(Y,Z)=>{let G=Y.attempt;if(!G||Z.accountId===Y.accountId)return;if(G.reboundFrom??=G.accountId,G.accountId=Z.accountId,"data"in Z)G.data=Z.data;Y.accountId=Z.accountId},N$=(Y)=>!Y.attempt||Y.endError!==void 0||Y.status!==void 0&&Y.status>=400,F$=(Y)=>{let Z=[...H.values()].filter((_)=>_.scope.sessionID===Y),G=Z.filter((_)=>_.limit&&!_.rerouted).at(-1);if(G)return G;let Q=Z.filter((_)=>_.scope.kind==="primary"),M=Q.length>0?Q:Z;if(M.length<=1)return M[0];let x=M.filter((_)=>!_.judged&&N$(_)).at(-1);if(x)return x;let N=M.filter((_)=>_.attempt&&!_.ended);if(N.length>1)return"ambiguous";return N[0]??M.at(-1)},t={providerID:X},r=[];r.push(await $.session.hook("model.request",(Y)=>{if(j)return;return p(o(Y),async(Z)=>{let G=await S(o(Y),"model.request",Z);if(Z(),G.accountId===void 0)throw i(G.scope);_2(Y.headers,{...G.headers,[Y2]:G.id})})},t)),r.push(await $.session.hook("http.request",(Y)=>{if(j){let Z=B(Y.request.headers);if(E.set(Y.sessionID,Z),!Z)return}return p(o(Y),async(Z)=>{let G=Y.request.headers.get(Y2)??void 0,Q=j?await S(o(Y),"http.request",Z,"http"):await Z2(o(Y),"http.request","http",G,Z);Z();let M=m(Q),x=Q.attempt;if(!M||!x)throw i(Q.scope);await $2(Q,async()=>{let N=Y.request;if(K.rewriteRequest){if(G!==void 0){let a=new Headers(N.headers);a.delete(Y2),N=new Request(N,{headers:a})}N=await K.rewriteRequest({...M,request:N,attempt:x})??N,Z()}let _=new Headers(N.headers);_.delete(Y2),L$(_,Q.headers),U(Q.scope,_.entries());let w=new Request(N,{headers:_});W.set(w,Q),Y.request=w})})},t)),r.push(await $.session.hook("http.response",async(Y)=>{let Z=W.get(Y.request);if(!Z){if(j)return;if(!v)v=!0,h("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:Y.sessionID,kind:Y.kind});return}let G=Y.response;if(K.answeredBy&&Z.attempt){let _=Z.attempt,w=await $2(Z,async()=>K.answeredBy?.({request:Y.request,response:G,attempt:_}));if(w)C$(Z,w)}let Q=m(Z),M=Z.attempt;if(!Q||!M)return;Z.status=G.status;let x=K.quotaFromHeaders?.(G.headers,G.status,M);if(x!==void 0)v2(Z,"http",x,G.status);if(!G.ok&&K.limitFromResponse){let _=await K.limitFromResponse({status:G.status,headers:G.headers,body:()=>G.clone().text(),attempt:M});if(_)P2(Z,_,"http")}if(!G.ok||!G.body)C(Z);let N=G;if(G.body&&(K.inspectEvent||K.onAttemptEnd)){let _=G.body;if(K.inspectEvent)_=_.pipeThrough(L2((w)=>m2(Z,"http",w.data,w.event),(w)=>h("opencode2 auth event inspection threw",{error:z(w)})));N=new Response(M$(_,(w)=>C(Z,w)),{status:G.status,statusText:G.statusText,headers:G.headers})}if(K.rewriteResponse)N=await K.rewriteResponse({...Q,request:Y.request,response:N,attempt:M})??N;if(N!==G)Y.response=N},t)),r.push(await $.session.hook("experimental.ws.handshake",(Y)=>{if(j){let Z=B(new Headers(Y.headers)),G=e(Y.sessionID,Y.kind);if(E.set(Y.sessionID,Z),b.delete(G),!Z)return}return p(o(Y),async(Z)=>{let G;for(let N of Object.keys(Y.headers)){if(N.toLowerCase()!==Y2)continue;G??=Y.headers[N],delete Y.headers[N]}let Q=j?await S(o(Y),"experimental.ws.handshake",Z,"ws"):await Z2(o(Y),"experimental.ws.handshake","ws",G,Z);Z();let M=m(Q),x=Q.attempt;if(!M||!x)throw i(Q.scope);await $2(Q,async()=>{_2(Y.headers,Q.headers);let N=K.rewriteHandshakeURL?.({...M,url:Y.url,attempt:x});if(N!==void 0)Y.url=N;if(U(Q.scope,Object.entries(Y.headers)),j)b.add(Q.key)})})},t));let f2=K.rewriteWebSocketFrame?.bind(K);if(f2)r.push(await $.session.hook("experimental.ws.send",async(Y)=>{let Z=o(Y);if(j&&!b.has(e(Z.sessionID,Z.kind)))return;let G=h2(Z.sessionID,Z.kind),Q=await f2({...Z,attempt:G?.attempt,frame:Y.frame});if(Q!==void 0)Y.frame=Q},t));r.push(await $.session.hook("experimental.ws.receive",(Y)=>{if(j&&!b.has(e(Y.sessionID,Y.kind)))return;let Z=h2(Y.sessionID,Y.kind);if(!Z)return;try{m2(Z,"ws",Y.frame)}catch(G){h("opencode2 auth frame inspection threw",{error:z(G)})}},t)),r.push(await $.session.hook("retry",async(Y)=>{if(j&&E.get(Y.sessionID)!==!0)return;let Z=F$(Y.sessionID);if(!Z)return;let G=Y.decision;if(Z==="ambiguous"){await V("retry",{sessionID:Y.sessionID,attempt:Y.attempt,reason:"host-decides",hostDecision:G,decision:G});return}let Q=Z;await p(Q.scope,async(M)=>{Q.judged=!0;let x=G,N,_,w=Q.attempt;if(Q.accountId===void 0||!w)x={retry:!1},N="no-account";else if(Q.outputStarted)x={retry:!1},N="output-started";else{if(!Q.limit){let a=K.limitFromError?.(Y.error,w);if(a)P2(Q,a,"error")}if(Q.ended)await Q.ended,M();if(Q.limit)await Q.limit.delivered,M(),Q.rerouted=!0,_={accountId:Q.accountId,limit:Q.limit.signal},x={retry:!0,delay:0},N="reroute";else N="host-decides"}if(Y.decision=x,x.retry&&Q.accountId!==void 0)y.set(Q.key,{sessionID:Q.scope.sessionID,accountId:Q.accountId,..._===void 0?{}:{rerouteFrom:_}});await V("retry",{sessionID:Y.sessionID,...Q.accountId===void 0?{}:{accountId:Q.accountId},kind:Q.scope.kind,attempt:Y.attempt,reason:N,hostDecision:G,decision:x,...w===void 0?{}:{handle:w}})})},t));let g2=(Y)=>{l(Y),E.delete(Y);for(let Z of b)if(JSON.parse(Z)[0]===Y)b.delete(Z);for(let Z of[...H.values()]){if(Z.scope.sessionID!==Y)continue;A(Z,"its session was forgotten"),H.delete(Z.id)}for(let[Z,G]of y)if(G.sessionID===Y)y.delete(Z)},T2=new AbortController,u2=$.event;if(u2)(async()=>{try{for await(let Y of u2.subscribe({signal:T2.signal}))if(Y.type==="session.deleted")g2(Y.data.sessionID)}catch(Y){if(!T2.signal.aborted)h("opencode2 auth stopped listening for session deletion",{error:z(Y)})}})();return{on(Y,Z){let G=d.get(Y);if(!G)G=new Set,d.set(Y,G);let Q=Z;return G.add(Q),()=>{G.delete(Q)}},accountFor(Y,Z){return D(e(Y,Z))?.accountId},forgetSession:g2,get size(){return H.size},async dispose(){if(u)return;u=!0;for(let Y of g.keys())l(Y);T2.abort();for(let Y of H.values())A(Y,"the installation was disposed");H.clear(),y.clear(),b.clear(),E.clear(),d.clear(),await Promise.all(r.map(async(Y)=>{try{await Y.dispose()}catch(Z){h("opencode2 auth hook did not dispose cleanly",{error:z(Z)})}}))}}}var x2={version:a2,"user-agent":s2,originator:"codex_exec"},_$="x-openai-internal-codex-responses-lite",q$=1024,x$=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,B2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),E$=($)=>B2($)&&($.type==="message"||("role"in $))&&$.role==="user",S$=($)=>B2($)&&$.type==="configuration_update";class E2{#$=new Map;apply($,K,J){if(K.kind!=="primary")return!1;let X=typeof $.model==="string"?$.model:"";if(!o2.has(X))return!1;if(x$.test(X))return!1;let j=B2($.reasoning)?$.reasoning:void 0,B=typeof j?.effort==="string"?j.effort:void 0;if(!B)return!1;let R=this.#$.get(K.sessionID);if(R===void 0)return this.#Y(K.sessionID,B),!1;if(B===R)return!1;let T=Array.isArray($.input)?$.input:void 0;if(!T||T.length===0)return!1;let O=T.findLastIndex(E$);if(O<0){if(J==="http")return!1;return $.reasoning={...j,effort:R},!0}if($.reasoning={...j,effort:R},!S$(T[O-1]))T.splice(O,0,{type:"configuration_update",reasoning:{effort:B}});return!0}forget($){this.#$.delete($)}#Y($,K){this.#$.set($,K);while(this.#$.size>q$){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function R$($){if(typeof $.model!=="string"||!n2.has($.model))return!1;return r2($),!0}function t2($){try{let K=JSON.parse($);return B2(K)?K:void 0}catch{return}}async function e2($,K,J,X){if($.method.toUpperCase()!=="POST"||$.body===null)return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let j=t2(await $.clone().text());if(!j)return;let B="max_output_tokens"in j;delete j.max_output_tokens;let R=J.apply(j,K,"http"),T=X&&R$(j);if(!B&&!R&&!T)return;let O=new Headers($.headers);if(O.delete("content-length"),T)O.set(_$,"true");return new Request($,{headers:O,body:JSON.stringify(j)})}function $1($,K,J){let X=t2($);if(X?.type!=="response.create")return;let j="max_output_tokens"in X;delete X.max_output_tokens;let B=J.apply(X,K,"ws");return j||B?JSON.stringify(X):void 0}function A$($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function S2($,K){let J=new URL($);if(J.origin!=="https://api.openai.com"&&J.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(J.pathname))return $;let X=new URL(`${A$(K)}/responses`);if(X.search=J.search,J.protocol==="ws:"||J.protocol==="wss:")X.protocol=X.protocol==="https:"?"wss:":"ws:";return X.href}var n="openai",D$=60000,Y1=1,O$="request refused: no account with a usable credential",b$=1024,K2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function A2($){try{return JSON.parse($)}catch{return}}function K1($){let K=H2($);return K?U2(K):void 0}var y$=new Set(["usage_limit_reached","rate_limit_exceeded"]);function D2($,K,J){return{reason:$.window,...J!==void 0?{status:J}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-K)}:{}}}function k$($,K){let J=W2($);if(J){let B=typeof $.status==="number"?$.status:void 0;return D2(J,K,B)}if($.type!=="response.failed"||!K2($.response))return;let X=$.response.failed;if(K2(X)&&typeof X.rate_limit_reached_type==="string")return{reason:X.rate_limit_reached_type};let j=$.response.error;if(K2(j)){let B=typeof j.code==="string"?j.code:typeof j.type==="string"?j.type:void 0;if(B&&y$.has(B))return{reason:B}}return}function w$($,K){let J=A2($);if(!K2(J))return;let X=typeof J.type==="string"?J.type:void 0;if(X==="codex.rate_limits")return{quota:{snapshot:X1(J),complete:!0}};let j=k$(J,K);if(j)return{limit:j};if(X===void 0||X==="error")return;return L1(X)?void 0:{outputStarted:!0}}function I$($){let K=!1;for(let J of $.keys())if(J.toLowerCase().startsWith("x-codex-")){K=!0;break}if(!K)return;return{snapshot:z1($),complete:J1($)}}function h$($){let K=$.get("retry-after");if(K===null)return;let J=Number(K);return Number.isFinite(J)&&J>=0?J*1000:void 0}function _1($){let{source:K,pins:J}=$,X=$.now??Date.now,j=$.log,B=$.vault,R=new E2,T=new Map,O=(z)=>`${z.sessionID}\x00${z.kind}\x00${z.accountId}`,H=new Map,W=new Map,y=(z,V)=>{W.delete(z),W.set(z,V);while(W.size>b$){let F=W.keys().next().value;if(F===void 0)break;W.delete(F)}},b=(z,V,F)=>{let C=F?[]:M1(K.peek().rows,z,V,B?.identities()??new Set),A=(B?.routes()??[]).filter((P)=>P.kind==="oauth"&&G1(V2(P.quota),z,V));return[...C.map((P)=>({id:P.id,...P.identity!==void 0?{identity:P.identity}:{},quota:P.quota,row:P})),...A.map((P)=>({id:P.id,...P.identity!==void 0?{identity:P.identity}:{},quota:P.quota}))]},E=(z,V,F)=>{let C=new Map;if(Q1(V))for(let q of z)C.set(q.id,V1(V2(q.quota),V,q.id===R2?void 0:q.id,F));let A=z.map((q)=>({id:q.id,kind:"oauth",...Z1(q.quota)?{quota:q.quota}:{}})),P=z.flatMap((q)=>q.row?[q.row]:[]),D=new Set(z.filter((q)=>!q.row).map((q)=>q.id)),k=K.rateLimitMarks(P);for(let q of D){let m=H.get(q);if(m===void 0)continue;if(m<=F)H.delete(q);else k.set(q,m)}return{rows:A,now:F,rateLimitMarks:k,refreshBackoff:K.refreshBackoffFor(P),killswitch:C,requestPull:(q)=>D.has(q)?B?.requestReading(q):K.requestReading(q)}},v=(z,V,F,C)=>{let A=N1({...z,placement:U1(V)});if(A.kind==="block"){j?.debug("pool admission refused the request",{reason:A.block.reason});return}let P=A.order.filter((D)=>!F.has(D));if(C!==void 0&&P.includes(C))return C;return P[0]},f=(z,V,F,C,A,P)=>{let D={requestBytes:Y1,reservePercent:(U)=>B1(F,U===R2?void 0:U),resetCredits:()=>{return}},k=F1(z),q=(U,L)=>J.place({sessionId:C,requestBytes:Y1,validPinnedAccountIds:z.rows.map((S)=>S.id).filter((S)=>!k.excluded.has(S)),excludeAccountIds:U,quotaCheckedAtByAccount:Object.fromEntries(z.rows.map((S)=>[S.id,k.projections.get(S.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(V.map((S)=>[S.id,S.identity])),select:(S)=>P1(z,D,new Set(U),S),persist:L}),m=[...A],i=q(m,P);if(!i)return;let l=i.accountId,p=T1(z,D,l);if(p.kind==="none")return;if(p.kind==="move"){let U=q([...m,l],P);if(U)return U.accountId;return p.reason==="killswitch"?void 0:l}if(p.kind==="detour")return q([...m,l],!1)?.accountId;return l},u={providerID:n,chooseAccount:async(z)=>{let V=await B?.authority(),F=await $.storage(),C=V!==void 0&&V!=="local",A=()=>{throw new c({kind:"no-account",providerID:n,sessionID:z.sessionID,requestKind:z.kind,message:C2})};if(C)await $.awaitVaultRoster?.();else{if(!(await K.current()).active){if(await $.slotPlaceholderWithoutMain?.())A();j?.warn("the account pool does not serve requests yet; refusing the request",{kind:z.kind});return}await K.prepareTokens(K.peek().rows,F)}let P=X(),D=b(F,P,C),k=C1(E(D.filter((S)=>S.id!==z.rerouteFrom?.accountId),F,P));if(k)await k,P=X(),D=b(F,P,C);let q=new Map(D.map((S)=>[S.id,S])),m=E(D,F,P),i=new Set(z.rerouteFrom?[z.rerouteFrom.accountId]:[]),l=F?.routing?.mode??"main-first",p=z.kind==="primary",U=new Set,L;for(;;){let S=new Set([...i,...U]);if(L=void 0,l==="sticky-balanced")L=f(m,D,F,z.sessionID,S,p&&U.size===0);if(L??=v(m,l,S,p?void 0:W.get(z.sessionID)),L===void 0||U.has(L)){L=void 0;break}let Z2=q.get(L)?.row;if(Z2){if(K.usableToken(Z2)!==void 0)break;j?.debug("pool row holds no usable token; choosing again",{accountId:L})}else{if(!B)break;let $2=await B.authorize(L);if($2){T.set(O({...z,accountId:L}),$2);break}j?.debug("the vault refused to serve an account; choosing again",{accountId:L})}U.add(L)}if(L===void 0&&!C&&D.length===0&&await $.slotPlaceholderWithoutMain?.())A();if(L===void 0&&C&&B&&(D.length===0||U.size>0)){let S=U.size>0?"vault-refused":H1(B);throw j?.warn("vault mode: no vault account can serve; refusing the request",{cause:S}),new c({kind:"no-account",providerID:n,sessionID:z.sessionID,requestKind:z.kind,message:W1[S]})}if(L!==void 0&&p)y(z.sessionID,L);return j?.debug("pool account chosen",{kind:z.kind,accountId:L,mode:l,...z.rerouteFrom?{rerouteFrom:z.rerouteFrom.accountId}:{}}),L},accountHeaders:async(z)=>{let{accountId:V}=z,F=()=>new c({kind:"no-account",providerID:n,sessionID:z.sessionID,requestKind:z.kind,message:O$}),C=B&&await B.authority()!=="local"?void 0:K.peek().rows.find((D)=>D.id===V);if(!C&&B){let D=O(z),k=T.get(D)??await B.authorize(V);if(T.delete(D),!k)throw j?.warn("the vault refused to serve an account; refusing the request",{accountId:V}),F();return{headers:{...x2,"session-id":z.sessionID,authorization:`Bearer ${k.accessToken}`,"chatgpt-account-id":k.accountIdentity??K1(k.accessToken)??null},attempt:{kind:"vault",routeId:V,receipt:k}}}let A=C?K.usableToken(C):void 0;if(!C||!A)throw j?.warn("pool row holds no usable token; refusing the request",{accountId:V}),F();let P=C.identity??K1(A);return{headers:{...x2,"session-id":z.sessionID,authorization:`Bearer ${A}`,"chatgpt-account-id":P??null},attempt:{kind:"pool",token:A,credentialEpoch:C.credentialEpoch}}},async rewriteRequest({request:z,sessionID:V,kind:F}){let C=$.codexEndpoint?S2(z.url,$.codexEndpoint()):z.url,A=C===z.url?z:new Request(C,z);return await e2(A,{sessionID:V,kind:F},R,$.responsesLite?.()??!1)??A},rewriteHandshakeURL:({url:z})=>$.codexEndpoint?S2(z,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:z,sessionID:V,kind:F})=>$1(z,{sessionID:V,kind:F},R),quotaFromHeaders:(z)=>I$(z),async limitFromResponse({status:z,headers:V,body:F}){if(z<400)return;let C=A2(await F().catch(()=>"")),A=W2({...K2(C)?C:{},status:z});if(!A)return;let P=X(),D=D2(A,P,z);if(D.retryAfterMs!==void 0)return D;let k=h$(V);return k===void 0?D:{...D,retryAfterMs:k}},inspectEvent:({data:z})=>w$(z,X()),limitFromError(z){let V=A2(z.message),F=W2({...K2(V)?V:{},...z.status!==void 0?{status:z.status}:{}})??(z.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return F?D2(F,X(),z.status):void 0},async onAttemptEnd(z,V){let F=z.data;if(F?.kind!=="vault"||V.status!==401)return;j?.warn("a vault account answered 401; reporting it to the vault",{accountId:z.accountId}),await B?.reportFailure(F.receipt,401)}},g=(z,V,F)=>{let C=F.data;if(C?.kind==="vault"){B?.recordSnapshot(z,V.snapshot,V.complete,C.receipt);return}if(C?.kind!=="pool")return;if(K.peek().rows.find((P)=>P.id===z)?.credentialEpoch!==C.credentialEpoch){j?.debug("quota reading dropped: the row holds another credential",{accountId:z});return}K.recordSnapshot(z,V.snapshot,C.token,V.complete)},h=(z,V,F)=>{let C=X(),A=F.data?.kind==="vault",P=A?B?.routes().find((q)=>q.id===z)?.quota:K.peek().rows.find((q)=>q.id===z)?.quota,D=j1(V2(P),V.reason,C,D$,V.retryAfterMs!==void 0?C+V.retryAfterMs:void 0);if(!A){K.markRateLimited(z,D);return}let k=H.get(z);if(k===void 0||k<D)H.set(z,D)};return{adapter:u,attach(z){z.on("quota",(V)=>g(V.accountId,V.quota,V.handle)),z.on("limit",(V)=>{h(V.accountId,V.limit,V.handle),j?.debug("pool row refused the request",{accountId:V.accountId,via:V.via,reason:V.limit.reason,outputStarted:V.outputStarted})})},forgetSession(z){J.forget(z),W.delete(z),R.forget(z)}}}var v$="openai-auth-pool-browser",m$="openai-auth-pool-headless",f$="openai-auth-vault",g$="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Connect to the vault or disconnect this host before trying again.";async function X2($){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 A1($){return{method:{id:f$,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await q1($.paths,$.name)!=="vault")throw Error(g$)}}}function D1($){let K=(J,X,j)=>({method:{id:J,type:"oauth",label:X},async authorize(){if($.vault)await X2($.vault);let B=await $.beginLogin({version:$.version,headless:j});return{url:B.url,instructions:B.instructions,mode:"auto",callback:B.completion}}});return[K(v$,"ChatGPT (openai-auth pool, browser)",!1),K(m$,"ChatGPT (openai-auth pool, headless)",!0)]}function O2($){let K=(J)=>typeof J==="string"?J:"";return J2({type:"oauth",access:K($.access),refresh:K($.refresh)})||$.refresh===S1||x1($)}function u$($){if($.accountId)return $.accountId;let K=$.access?H2($.access):void 0;return K?U2(K):void 0}async function O1($,K,J,X={}){if(X.vault)await X2(X.vault);if(O2(J))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let j=E1($,{rowLocks:(E)=>R1(K,E)}),B=await j.read();if(B.status!=="ready")throw Error(`the account pool cannot be read (${B.status}); the login was not stored`);let R={type:"oauth",refresh:J.refresh,...J.access!==void 0?{access:J.access}:{},...J.expires!==void 0?{expires:J.expires}:{}},T=u$(J);if(X.vault)await X2(X.vault);let O=T!==void 0?{identity:T}:{};if(X.origin==="import"){let E=B.rows.find((v)=>T!==void 0&&v.identity===T||v.credential?.type==="oauth"&&v.credential.refresh===J.refresh);if(E)return{id:E.id,operation:"kept"}}let H=B.rows.filter((E)=>E.type==="oauth"&&!E.invalid),W=T?H.find((E)=>E.identity===T):void 0,y=B.rows.find((E)=>E.id===N2);if(W)return{id:(await j.replace(W.id,R,O)).id,operation:"replaced"};if(!y){let E=await j.add({id:N2,credential:R,...O,...J.label!==void 0?{label:J.label}:{}});return{id:E.id,operation:E.outcome==="added-disabled"?"added-disabled":"added"}}if(!y.invalid&&!y.credential)return{id:(await j.replace(N2,R,O)).id,operation:"replaced"};let b=await j.add({id:J.id,credential:R,...O,...J.label!==void 0?{label:J.label}:{}});return{id:b.id,operation:b.outcome==="added-disabled"?"added-disabled":b.outcome==="rotated"?"replaced":"added"}}function p$($){if(!b1($.modelID??$.id)){$.enabled=!1;return}let K=y1($.id);if(K)$.limit={...K}}function k1($){return $.model.transform((K)=>{for(let J of K.list(n))K.update(n,String(J.id),(X)=>p$(X))})}import{resolve as I1}from"node:path";var l$=1024;class b2{pins=new Map;limit;constructor($=l$){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.pins.delete($)}get size(){return this.pins.size}set($,K){this.pins.delete($),this.pins.set($,K);while(this.pins.size>this.limit){let J=this.pins.keys().next().value;if(J===void 0)break;this.pins.delete(J)}}place($){return w1(this.pins,$,(K,J)=>this.set(K,J))}}var h1=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),v1=globalThis,y2=v1[h1]??new Map;v1[h1]=y2;function m1($){let K=JSON.stringify([I1($.configPath),I1($.statePath)]),J=y2.get(K);if(!J)J=new b2,y2.set(K,J);return J}var F2="cortexkit-openai-auth",c$=5000;async function f1($,K,J){let X=new Map,j=new Map,B=(H)=>{j.delete(H);for(let W of X.keys())if(W.startsWith(`${H}:`))X.delete(W)},T=await q2({session:{hook:(H,W,y)=>$.session.hook(H,async(b)=>{let E=H==="http.request"?b:void 0,v=H==="experimental.ws.handshake"?b:void 0,d=(E?E.request.headers:v?new Headers(v.headers):void 0)?.get("authorization")===`Bearer ${s(K.providerID)}`;try{await W(b)}catch(I){if(d&&!(I instanceof c))throw o1(I);throw I}if(E||v){let I=E??v;if(!I)return;let g=(E?E.request.headers:new Headers(I.headers)).get("authorization")?.replace(/^Bearer /,"");if(d&&g)j.set(I.sessionID,g);else j.delete(I.sessionID);if(v){let h=`${v.sessionID}:${v.kind}`;if(d&&g)X.set(h,g);else X.delete(h)}if(j.size>512){let h=j.keys().next().value;if(h)j.delete(h)}if(X.size>512){let h=X.keys().next().value;if(h)X.delete(h)}}else if(H==="experimental.ws.receive"){let I=b,u=X.get(`${I.sessionID}:${I.kind}`);if(u)I.frame=r1(I.frame,u)}else if(H==="retry"){let I=b,u=j.get(I.sessionID);if(u)Object.assign(I.error,{message:s1(I.error.message,u)})}},y)},event:{subscribe:(H)=>async function*(){for await(let W of $.event.subscribe(H)){if(W.type==="session.deleted")B(W.data.sessionID);yield W}}()}},{...K,rewriteResponse:async(H)=>{let W=await K.rewriteResponse?.(H)??H.response;return t1(W,H.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(H)=>{let W=H.get("authorization");return W?.startsWith("Bearer ")?W.slice(7):void 0}},logger:{warn:(H,W)=>J.warn(H,{data:W})}}),O=T.dispose;return{...T,dispose:async()=>{j.clear(),X.clear(),await O()}}}function I2($={}){return{id:F2,setup:(K)=>d$(K,$)}}async function d$($,K={}){let m=[];try{let J=j2("opencode2");let X=j2("quota");let j=K.paths??(()=>$$(e1()));let B=K.fetch??fetch;let R=K.version??J$;let T=K.poolMigration??W$;if(!T&&!G2(j().configPath)){J.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 U=(S)=>{throw new c({kind:"no-account",providerID:n,sessionID:S.sessionID,requestKind:S.kind,message:C2})},L=await f1($,{providerID:n,chooseAccount:U,accountHeaders:U},J);return()=>L.dispose()}let O=K.vault?.firstRosterWaitMs??j$;let H=V$({host:"opencode",stateDir:K.vault?.stateDir??a1(j().statePath),reservedRouteIds:()=>f.peek().rows.map((U)=>U.id),...K.vault?.connectionFile?{connectionFile:K.vault.connectionFile}:{},...K.vault?.connectScoped?{connectScoped:K.vault.connectScoped}:{},...K.vault?.connectEnrollment?{connectEnrollment:K.vault.connectEnrollment}:{},...K.vault?.pollIntervalMs!==void 0?{pollIntervalMs:K.vault.pollIntervalMs}:{},fetchImpl:()=>B},j());let W=H.vault;let y=!1;let b=!1;const E=g1(m,{[Symbol.dispose](){if(!y)H.release()}},0);await W.authority();let v=H.firstRoster;let f=new G$({paths:j,refreshProvider:async(U)=>{let L=await c1({refreshToken:U.refresh,fetchImpl:B,now:Date.now}),S=p1({id_token:"",access_token:L.access,refresh_token:L.refresh});return{...L,...S?{identity:S}:{}}},pullQuota:async(U)=>{let L=U.credential;if(L.type!=="oauth"||!L.access)throw Error("the row holds no access token to poll with");let S=await d1({accessToken:L.access,fetchImpl:B,now:Date.now,...U.identity?{accountId:U.identity}:{},accountKey:U.id,logger:X});return n1(S,Date.now(),!0)},vaultIdentities:()=>W.identities(),vaultMode:()=>W.enrolled(),vaultAuthority:()=>W.authority(),vaultFirstRoster:v,vaultFirstRosterBackgroundWaitMs:O,log:j2("pool")});await f.load();let d=K.heartbeat===!1?void 0:await B$({version:R,logger:j2("heartbeat")});let I=K.fence??(()=>z$({currentVersion:R}));let u=K.slot??H$();let g=async()=>Y$(j(),await u.get({path:{id:"openai"}}));let h=!1;let z=T?Q$({paths:j,slot:u,version:R,fence:I,runDeps:{vaultServes:()=>W.serves()},paused:async()=>await W.authority()!=="local",migrate:async(U)=>{let L=await K$(U);if(h=L.status==="refused",!b)await f.load();return L},adopt:async(U)=>{if(b)return{status:"retry",reason:"unsettled"};if(!await w2(v,O))return{status:"retry",reason:"vault-roster-pending"};if(b)return{status:"retry",reason:"unsettled"};let L=await Z$(U);if(!b)await f.load();return L}}):void 0;z?.start();H.start();let V=m1(j());let F=_1({source:f,slotPlaceholderWithoutMain:g,storage:()=>i1(j()),pins:V,vault:W,awaitVaultRoster:async()=>{await w2(W.awaitRequestRoster(),X$)},responsesLite:()=>k2().responsesLite,codexEndpoint:()=>k2().codexApiEndpoint,log:J});let C=await f1($,F.adapter,J);F.attach(C);let A=async(U)=>{if(await X2(W),G2(j().configPath))return;if(await z?.idle(),G2(j().configPath))return;if(h&&!O2(U)&&(await I()).open){await f.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 P=async(U)=>{await A(U);let L=await O1(f.poolStore(),j(),U,{vault:W});if(!G2(j().configPath))await z?.requestAdoption();await f.load(),J.info("ChatGPT login stored in the account pool",L)};let D=await M2($,{integrationID:n,methods:D1({beginLogin:K.beginLogin??l1,version:R,vault:W}),onLogin:(U)=>P(U),label:"ChatGPT (openai-auth account pool)",vault:A1(W)});let k=await k1($);let q=new AbortController;(async()=>{try{for await(let U of $.event.subscribe({signal:q.signal}))if(U.type==="session.deleted")F.forgetSession(U.data.sessionID)}catch(U){if(!q.signal.aborted)J.warn("stopped listening for session deletion",{error:U instanceof Error?U.message:String(U)})}})();y=!0;return async()=>{b=!0,q.abort(),z?.dispose(),f.dispose(),await Promise.allSettled([C.dispose(),D.dispose(),k.dispose()]);let U;try{await Promise.race([Promise.all([z?.idle(),f.settled()]),new Promise((L)=>{U=setTimeout(L,c$),U.unref?.()})])}finally{clearTimeout(U),H.release(),await d?.release()}}}catch(i){var l=i,p=1}finally{u1(m,l,p)}}var i$=I2(),jK={id:F2,setup:i$.setup,server:U$.server};export{jK as default,I2 as createOpenAIAuthPlugin,F2 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.0.4",
3
+ "version": "1.0.5",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "repository": {
@@ -66,7 +66,7 @@
66
66
  },
67
67
  "devDependencies": {
68
68
  "@ai-sdk/openai": "3.0.88",
69
- "@cortexkit/common-auth": "^0.17.0",
69
+ "@cortexkit/common-auth": "^0.17.1",
70
70
  "@cortexkit/openai-auth-core": "workspace:*",
71
71
  "@opencode/plugin": "2.0.27"
72
72
  },
@@ -1,7 +1,7 @@
1
1
  // The one quota wording every surface shows: the command menu's dialogs on
2
2
  // OpenCode and Pi, the terminal auth menu, and the plugins' sidebars. Each of
3
- // them calls `formatQuota` (or `quotaTextParts` for one line per window), so
4
- // the wording cannot drift between plugins or between a dialog and a sidebar.
3
+ // them calls `formatQuota`, `quotaTextParts`, or `quotaWindowParts`, so the
4
+ // wording cannot drift between plugins or between a dialog and a sidebar.
5
5
  //
6
6
  // The rules: a window is named by its length (`5h`, `7d`), or, for a window
7
7
  // that binds only one model family, by the label the plugin stored it under.
@@ -55,17 +55,20 @@ export function quotaWindowName(limit) {
55
55
  return limit.label;
56
56
  return lengthName(limit.windowMinutes);
57
57
  }
58
+ function clampPercent(remaining) {
59
+ return Math.min(100, Math.max(0, remaining));
60
+ }
58
61
  function percentLeft(remaining) {
59
- return `${Math.round(Math.min(100, Math.max(0, remaining)))}% left`;
62
+ return `${Math.round(clampPercent(remaining))}% left`;
60
63
  }
61
- function resetText(resetsAt, now) {
62
- if (resetsAt === undefined)
63
- return '';
64
- const at = Date.parse(resetsAt);
65
- // A reset already passed says nothing about the future; leave it out.
66
- if (!Number.isFinite(at) || at <= now)
67
- return '';
68
- return `, resets ${shortSpan(at - now)}`;
64
+ function resetDetails(resetsAt, checkedAt, now) {
65
+ const at = resetsAt === undefined ? Number.NaN : Date.parse(resetsAt);
66
+ return {
67
+ ...(Number.isFinite(at) && at > now
68
+ ? { resetIn: shortSpan(at - now) }
69
+ : {}),
70
+ resetSinceReading: Number.isFinite(at) && at > checkedAt && at <= now,
71
+ };
69
72
  }
70
73
  /** Shortest window first, so `5h` reads before `7d`; unknown lengths last. */
71
74
  function displayOrder(left, right) {
@@ -85,42 +88,70 @@ function displayOrder(left, right) {
85
88
  return left.label < right.label ? -1 : left.label > right.label ? 1 : 0;
86
89
  }
87
90
  /**
88
- * The pieces of a quota text, in order: one per reported window
89
- * (`5h 58% left, resets 2h`), then the credit budget when there is one, then
90
- * `checked 3h ago` when the oldest piece shown is stale. Empty when nothing
91
- * was reported; `formatQuota` turns that into a sentence. A caller printing
92
- * one line per window (the terminal auth menu) uses these directly.
91
+ * Structured quota wording for layouts that need one row per window. The
92
+ * windows use the same filtering and order as `quotaTextParts`; future resets
93
+ * and the optional age keep the shared formatter's wording.
93
94
  */
94
- export function quotaTextParts(quota, options) {
95
+ export function quotaWindowParts(quota, options) {
95
96
  if (!quota)
96
- return [];
97
+ return { windows: [] };
97
98
  const { now } = options;
98
- const full = (options.form ?? 'full') === 'full';
99
- const parts = [];
100
- const times = [];
101
99
  const readings = quota.limits
102
100
  .filter((limit) => limit.kind === 'reading' && limit.remainingPercent !== undefined)
103
101
  .sort(displayOrder);
104
- for (const limit of readings) {
105
- times.push(limit.checkedAt);
106
- parts.push(`${quotaWindowName(limit)} ${percentLeft(limit.remainingPercent ?? 0)}${full ? resetText(limit.resetsAt, now) : ''}`);
107
- }
102
+ const windows = readings.map((limit) => {
103
+ const remainingPercent = clampPercent(limit.remainingPercent ?? 0);
104
+ return {
105
+ kind: 'window',
106
+ name: quotaWindowName(limit),
107
+ figure: percentLeft(limit.remainingPercent ?? 0),
108
+ remainingPercent,
109
+ checkedAt: limit.checkedAt,
110
+ ...resetDetails(limit.resetsAt, limit.checkedAt, now),
111
+ };
112
+ });
108
113
  const budget = quota.budget;
109
114
  if (budget) {
110
- times.push(budget.checkedAt);
115
+ const remainingPercent = budget.remainingPercent;
111
116
  const figure = budget.reached
112
117
  ? 'credits spent'
113
- : budget.remainingPercent !== undefined
114
- ? `credits ${percentLeft(budget.remainingPercent)}`
118
+ : remainingPercent !== undefined
119
+ ? `credits ${percentLeft(remainingPercent)}`
115
120
  : 'credits available';
116
- parts.push(`${figure}${full ? resetText(budget.resetsAt, now) : ''}`);
121
+ windows.push({
122
+ kind: 'budget',
123
+ name: 'credits',
124
+ figure,
125
+ ...(remainingPercent === undefined
126
+ ? {}
127
+ : { remainingPercent: clampPercent(remainingPercent) }),
128
+ checkedAt: budget.checkedAt,
129
+ ...resetDetails(budget.resetsAt, budget.checkedAt, now),
130
+ });
117
131
  }
118
- if (times.length > 0) {
119
- const age = now - Math.min(...times);
120
- if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS))
121
- parts.push(`checked ${shortSpan(age)} ago`);
132
+ if (windows.length > 0) {
133
+ const age = now - Math.min(...windows.map((part) => part.checkedAt));
134
+ if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS)) {
135
+ return { windows, age: `checked ${shortSpan(age)} ago` };
136
+ }
122
137
  }
123
- return parts;
138
+ return { windows };
139
+ }
140
+ /**
141
+ * The pieces of a quota text, in order: one per reported window
142
+ * (`5h 58% left, resets 2h`), then the credit budget when there is one, then
143
+ * `checked 3h ago` when the oldest piece shown is stale. Empty when nothing
144
+ * was reported; `formatQuota` turns that into a sentence. A caller printing
145
+ * one line per window (the terminal auth menu) uses these directly.
146
+ */
147
+ export function quotaTextParts(quota, options) {
148
+ const parts = quotaWindowParts(quota, options);
149
+ const full = (options.form ?? 'full') === 'full';
150
+ const text = parts.windows.map((part) => {
151
+ const reset = full && part.resetIn ? `, resets ${part.resetIn}` : '';
152
+ return `${part.kind === 'budget' ? '' : `${part.name} `}${part.figure}${reset}`;
153
+ });
154
+ return parts.age === undefined ? text : [...text, parts.age];
124
155
  }
125
156
  /**
126
157
  * A row's quota as one line: `5h 58% left · 7d 90% left` in the compact
@@ -1,5 +1,5 @@
1
1
  export { quotaCodec } from "./053cc17b5419261e-codec.js";
2
- export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, } from "./0332701351b3eeec-format.js";
2
+ export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, quotaWindowParts, } from "./0332701351b3eeec-format.js";
3
3
  export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, decodeQuotaMap, emptyQuotaMap, isQuotaMap, } from "./905bffc0220f43d0-map.js";
4
4
  export { isQuotaObservation, mergeQuotaObservation, QuotaCodecError, } from "./4f36d333d081d040-merge.js";
5
5
  export { budgetExhaustedResetAt, futureResetAt, projectQuota, readsExhausted, } from "./39c3cb05738fcf6d-projection.js";
@@ -1,7 +1,7 @@
1
1
  // The one quota wording every surface shows: the command menu's dialogs on
2
2
  // OpenCode and Pi, the terminal auth menu, and the plugins' sidebars. Each of
3
- // them calls `formatQuota` (or `quotaTextParts` for one line per window), so
4
- // the wording cannot drift between plugins or between a dialog and a sidebar.
3
+ // them calls `formatQuota`, `quotaTextParts`, or `quotaWindowParts`, so the
4
+ // wording cannot drift between plugins or between a dialog and a sidebar.
5
5
  //
6
6
  // The rules: a window is named by its length (`5h`, `7d`), or, for a window
7
7
  // that binds only one model family, by the label the plugin stored it under.
@@ -55,17 +55,20 @@ export function quotaWindowName(limit) {
55
55
  return limit.label;
56
56
  return lengthName(limit.windowMinutes);
57
57
  }
58
+ function clampPercent(remaining) {
59
+ return Math.min(100, Math.max(0, remaining));
60
+ }
58
61
  function percentLeft(remaining) {
59
- return `${Math.round(Math.min(100, Math.max(0, remaining)))}% left`;
62
+ return `${Math.round(clampPercent(remaining))}% left`;
60
63
  }
61
- function resetText(resetsAt, now) {
62
- if (resetsAt === undefined)
63
- return '';
64
- const at = Date.parse(resetsAt);
65
- // A reset already passed says nothing about the future; leave it out.
66
- if (!Number.isFinite(at) || at <= now)
67
- return '';
68
- return `, resets ${shortSpan(at - now)}`;
64
+ function resetDetails(resetsAt, checkedAt, now) {
65
+ const at = resetsAt === undefined ? Number.NaN : Date.parse(resetsAt);
66
+ return {
67
+ ...(Number.isFinite(at) && at > now
68
+ ? { resetIn: shortSpan(at - now) }
69
+ : {}),
70
+ resetSinceReading: Number.isFinite(at) && at > checkedAt && at <= now,
71
+ };
69
72
  }
70
73
  /** Shortest window first, so `5h` reads before `7d`; unknown lengths last. */
71
74
  function displayOrder(left, right) {
@@ -85,42 +88,70 @@ function displayOrder(left, right) {
85
88
  return left.label < right.label ? -1 : left.label > right.label ? 1 : 0;
86
89
  }
87
90
  /**
88
- * The pieces of a quota text, in order: one per reported window
89
- * (`5h 58% left, resets 2h`), then the credit budget when there is one, then
90
- * `checked 3h ago` when the oldest piece shown is stale. Empty when nothing
91
- * was reported; `formatQuota` turns that into a sentence. A caller printing
92
- * one line per window (the terminal auth menu) uses these directly.
91
+ * Structured quota wording for layouts that need one row per window. The
92
+ * windows use the same filtering and order as `quotaTextParts`; future resets
93
+ * and the optional age keep the shared formatter's wording.
93
94
  */
94
- export function quotaTextParts(quota, options) {
95
+ export function quotaWindowParts(quota, options) {
95
96
  if (!quota)
96
- return [];
97
+ return { windows: [] };
97
98
  const { now } = options;
98
- const full = (options.form ?? 'full') === 'full';
99
- const parts = [];
100
- const times = [];
101
99
  const readings = quota.limits
102
100
  .filter((limit) => limit.kind === 'reading' && limit.remainingPercent !== undefined)
103
101
  .sort(displayOrder);
104
- for (const limit of readings) {
105
- times.push(limit.checkedAt);
106
- parts.push(`${quotaWindowName(limit)} ${percentLeft(limit.remainingPercent ?? 0)}${full ? resetText(limit.resetsAt, now) : ''}`);
107
- }
102
+ const windows = readings.map((limit) => {
103
+ const remainingPercent = clampPercent(limit.remainingPercent ?? 0);
104
+ return {
105
+ kind: 'window',
106
+ name: quotaWindowName(limit),
107
+ figure: percentLeft(limit.remainingPercent ?? 0),
108
+ remainingPercent,
109
+ checkedAt: limit.checkedAt,
110
+ ...resetDetails(limit.resetsAt, limit.checkedAt, now),
111
+ };
112
+ });
108
113
  const budget = quota.budget;
109
114
  if (budget) {
110
- times.push(budget.checkedAt);
115
+ const remainingPercent = budget.remainingPercent;
111
116
  const figure = budget.reached
112
117
  ? 'credits spent'
113
- : budget.remainingPercent !== undefined
114
- ? `credits ${percentLeft(budget.remainingPercent)}`
118
+ : remainingPercent !== undefined
119
+ ? `credits ${percentLeft(remainingPercent)}`
115
120
  : 'credits available';
116
- parts.push(`${figure}${full ? resetText(budget.resetsAt, now) : ''}`);
121
+ windows.push({
122
+ kind: 'budget',
123
+ name: 'credits',
124
+ figure,
125
+ ...(remainingPercent === undefined
126
+ ? {}
127
+ : { remainingPercent: clampPercent(remainingPercent) }),
128
+ checkedAt: budget.checkedAt,
129
+ ...resetDetails(budget.resetsAt, budget.checkedAt, now),
130
+ });
117
131
  }
118
- if (times.length > 0) {
119
- const age = now - Math.min(...times);
120
- if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS))
121
- parts.push(`checked ${shortSpan(age)} ago`);
132
+ if (windows.length > 0) {
133
+ const age = now - Math.min(...windows.map((part) => part.checkedAt));
134
+ if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS)) {
135
+ return { windows, age: `checked ${shortSpan(age)} ago` };
136
+ }
122
137
  }
123
- return parts;
138
+ return { windows };
139
+ }
140
+ /**
141
+ * The pieces of a quota text, in order: one per reported window
142
+ * (`5h 58% left, resets 2h`), then the credit budget when there is one, then
143
+ * `checked 3h ago` when the oldest piece shown is stale. Empty when nothing
144
+ * was reported; `formatQuota` turns that into a sentence. A caller printing
145
+ * one line per window (the terminal auth menu) uses these directly.
146
+ */
147
+ export function quotaTextParts(quota, options) {
148
+ const parts = quotaWindowParts(quota, options);
149
+ const full = (options.form ?? 'full') === 'full';
150
+ const text = parts.windows.map((part) => {
151
+ const reset = full && part.resetIn ? `, resets ${part.resetIn}` : '';
152
+ return `${part.kind === 'budget' ? '' : `${part.name} `}${part.figure}${reset}`;
153
+ });
154
+ return parts.age === undefined ? text : [...text, parts.age];
124
155
  }
125
156
  /**
126
157
  * A row's quota as one line: `5h 58% left · 7d 90% left` in the compact
@@ -1,5 +1,5 @@
1
1
  export { quotaCodec } from "./053cc17b5419261e-codec.js";
2
- export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, } from "./0332701351b3eeec-format.js";
2
+ export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, quotaWindowParts, } from "./0332701351b3eeec-format.js";
3
3
  export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, decodeQuotaMap, emptyQuotaMap, isQuotaMap, } from "./905bffc0220f43d0-map.js";
4
4
  export { isQuotaObservation, mergeQuotaObservation, QuotaCodecError, } from "./4f36d333d081d040-merge.js";
5
5
  export { budgetExhaustedResetAt, futureResetAt, projectQuota, readsExhausted, } from "./39c3cb05738fcf6d-projection.js";
@@ -1,2 +0,0 @@
1
- import{Ud as S,Xd as i}from"./index-k4eacw7x.js";var G="all",t=Object.freeze(["primary"]);function b(z){return z.kind==="retired"?z.retiredAt:z.checkedAt}function Q(z,D){return JSON.stringify([z,D])}function M(z){return typeof z==="object"&&z!==null&&!Array.isArray(z)}function V(z){return typeof z==="number"&&Number.isFinite(z)}function h(z){return typeof z==="string"&&z.length>0}function I(z,D,H){return z[D]===void 0||H(z[D])}function e(z){return V(z)&&z>0}function F(z){return typeof z==="string"}function zz(z){if(!M(z)||!h(z.scope)||!h(z.label))return!1;switch(z.kind){case"reading":return V(z.checkedAt)&&V(z.usedPercent)&&I(z,"resetsAt",F)&&I(z,"windowMinutes",e);case"retired":return V(z.retiredAt);case"absent":return V(z.checkedAt);default:return!1}}function Dz(z){if(!M(z)||!V(z.checkedAt))return!1;if(z.kind==="cleared")return!0;return z.kind==="reading"&&typeof z.reached==="boolean"&&I(z,"remainingPercent",V)&&I(z,"usedPercent",V)&&I(z,"resetsAt",F)&&I(z,"limit",V)&&I(z,"used",V)&&I(z,"remaining",V)&&I(z,"unit",F)}function p(z){return M(z)&&V(z.value)&&Number.isInteger(z.value)&&z.value>=0&&V(z.checkedAt)}function N(z){return M(z)&&Object.values(z).every(p)}function A(z){if(!M(z))return;let D=Object.entries(z).filter(([,H])=>p(H));return D.length===0?void 0:Object.fromEntries(D)}function _(z){if(R(z))return z;if(!M(z))return;let{counters:D,...H}=z;if(!R(H))return;let J=A(D);return{...H,...J===void 0?{}:{counters:J}}}function R(z){if(!M(z)||!Array.isArray(z.limits))return!1;let D=new Set;for(let H of z.limits){if(!zz(H))return!1;let J=Q(H.scope,H.label);if(D.has(J))return!1;D.add(J)}return I(z,"budget",Dz)&&I(z,"counters",N)}var g=900000,m="no quota reading yet",d="no limits reported";function v(z){let D=Math.max(1,Math.round(z/60000));if(D<60)return`${D}m`;let H=Math.round(D/60);if(H<24)return`${H}h`;return`${Math.max(1,Math.round(D/1440))}d`}function Hz(z){if(z%1440===0)return`${z/1440}d`;if(z%60===0)return`${z/60}h`;return`${z}m`}function s(z){if(z.scope!==G||z.windowMinutes===void 0)return z.label;return Hz(z.windowMinutes)}function c(z){return`${Math.round(Math.min(100,Math.max(0,z)))}% left`}function y(z,D){if(z===void 0)return"";let H=Date.parse(z);if(!Number.isFinite(H)||H<=D)return"";return`, resets ${v(H-D)}`}function Jz(z,D){let H=z.windowMinutes,J=D.windowMinutes;if(H!==void 0&&J!==void 0&&H!==J)return H-J;if(H===void 0!==(J===void 0))return H===void 0?1:-1;if(z.scope!==D.scope){if(z.scope===G)return-1;if(D.scope===G)return 1;return z.scope<D.scope?-1:1}return z.label<D.label?-1:z.label>D.label?1:0}function o(z,D){if(!z)return[];let{now:H}=D,J=(D.form??"full")==="full",U=[],X=[],T=z.limits.filter((Z)=>Z.kind==="reading"&&Z.remainingPercent!==void 0).sort(Jz);for(let Z of T)X.push(Z.checkedAt),U.push(`${s(Z)} ${c(Z.remainingPercent??0)}${J?y(Z.resetsAt,H):""}`);let W=z.budget;if(W){X.push(W.checkedAt);let Z=W.reached?"credits spent":W.remainingPercent!==void 0?`credits ${c(W.remainingPercent)}`:"credits available";U.push(`${Z}${J?y(W.resetsAt,H):""}`)}if(X.length>0){let Z=H-Math.min(...X);if(Z>(D.staleAfterMs??g))U.push(`checked ${v(Z)} ago`)}return U}function Uz(z,D){let H=o(z,D);if(H.length>0)return H.join(" · ");return z&&z.limits.length>0?d:m}function Xz(z){if(z.kind==="retired")return{scope:z.scope,label:z.label,kind:"retired",checkedAt:z.retiredAt};if(z.kind==="absent")return{scope:z.scope,label:z.label,kind:"absent",checkedAt:z.checkedAt};return{scope:z.scope,label:z.label,kind:"reading",checkedAt:z.checkedAt,usedPercent:z.usedPercent,remainingPercent:100-z.usedPercent,...z.windowMinutes===void 0?{}:{windowMinutes:z.windowMinutes},...z.resetsAt===void 0?{}:{resetsAt:z.resetsAt}}}function Yz(z,D){let H=z.windowMinutes!==void 0,J=D.windowMinutes!==void 0;if(H!==J)return H?-1:1;if(H&&J&&z.windowMinutes!==D.windowMinutes)return(D.windowMinutes??0)-(z.windowMinutes??0);if(z.label!==D.label)return z.label<D.label?-1:1;return 0}function Zz(z){return{checkedAt:z.checkedAt,reached:z.reached,...z.remainingPercent===void 0?{}:{remainingPercent:z.remainingPercent},...z.resetsAt===void 0?{}:{resetsAt:z.resetsAt}}}function $z(z,D=G){let H=new Map;for(let $ of z?.limits??[]){if($.scope!==D&&$.scope!==G)continue;let P=H.get($.label);if(P===void 0){H.set($.label,$);continue}let j=$.scope===G?P:$,E=$.scope===G?$:P;H.set($.label,j.kind==="reading"?j:E)}let J=[...H.values()].map(Xz).sort(Yz),U=J.filter(($)=>$.kind==="reading"),X=U.length>0?U:J,T=X.length>0?Math.min(...X.map(($)=>$.checkedAt)):void 0,W=z?.budget?.kind==="reading"?Zz(z.budget):void 0,Z=A(z?.counters);return{scope:D,limits:J,...T===void 0?{}:{checkedAt:T},...W===void 0?{}:{budget:W},...Z===void 0?{}:{counters:Z}}}function Gz(z,D){let H=z?.budget;if(H?.reached!==!0||typeof H.resetsAt!=="string")return;let J=Date.parse(H.resetsAt);if(!Number.isFinite(J)||J<=D)return;return{resetsAt:H.resetsAt,resetAtMs:J}}function Vz(z){return z.kind==="reading"&&typeof z.usedPercent==="number"&&Number.isFinite(z.usedPercent)&&z.usedPercent>=100}function Wz(z,D){if(typeof z.resetsAt!=="string")return;let H=Date.parse(z.resetsAt);return Number.isFinite(H)&&H>D?H:void 0}class q extends TypeError{constructor(z){super(z);this.name="QuotaCodecError"}}function C(z){return typeof z==="object"&&z!==null&&!Array.isArray(z)}function O(z){return typeof z==="number"&&Number.isFinite(z)}function n(z){return z===void 0||typeof z==="string"&&z!==""}function u(z){return typeof z==="string"&&z!==""}function K(z,D){return z[D]===void 0||O(z[D])}function L(z,D){return z[D]===void 0||typeof z[D]==="string"}function Iz(z){return C(z)&&n(z.scope)&&u(z.label)&&O(z.usedPercent)&&L(z,"resetsAt")&&(z.windowMinutes===void 0||O(z.windowMinutes)&&z.windowMinutes>0)}function xz(z){return C(z)&&n(z.scope)&&u(z.label)}function Bz(z){if(!C(z))return!1;if(z.kind==="cleared")return!0;return z.kind==="reading"&&typeof z.reached==="boolean"&&K(z,"remainingPercent")&&K(z,"usedPercent")&&L(z,"resetsAt")&&K(z,"limit")&&K(z,"used")&&K(z,"remaining")&&L(z,"unit")}function l(z){if(!C(z)||!O(z.checkedAt))return!1;let D=z.readings??[],H=z.coverage??[];if(!Array.isArray(D)||!Array.isArray(H))return!1;let J=new Set;for(let U of D){if(!Iz(U))return!1;let X=Q(U.scope??G,U.label);if(J.has(X))return!1;J.add(X)}if(!H.every(xz))return!1;return(z.budget===void 0||Bz(z.budget))&&(z.counters===void 0||N(z.counters))}function Tz(z,D){if(z.scope!==D.scope)return z.scope<D.scope?-1:1;if(z.label!==D.label)return z.label<D.label?-1:1;return 0}function Mz(z,D,H){if(D===void 0)return z;if(z!==void 0&&H<z.checkedAt)return z;return{...D,checkedAt:H}}function Qz(z,D){let H=new Map(Object.entries(z??{}));for(let[J,U]of Object.entries(D??{})){let X=H.get(J);if(X===void 0||U.checkedAt>=X.checkedAt)H.set(J,U)}return H.size===0?void 0:Object.fromEntries(H)}function w(z,D){let H=z===void 0?void 0:_(z);if(z!==void 0&&H===void 0)throw new q("stored quota map is malformed");if(!l(D))throw new q("quota observation is malformed");let J=H??{limits:[]},U=D.checkedAt,X=new Map;for(let Y of J.limits)X.set(Q(Y.scope,Y.label),Y);let T=(Y)=>{let x=X.get(Y);return x===void 0||U>=b(x)},W=new Set;for(let Y of D.readings??[]){let x=Y.scope??G,B=Q(x,Y.label);if(W.add(B),!T(B))continue;X.set(B,{scope:x,label:Y.label,kind:"reading",checkedAt:U,usedPercent:Y.usedPercent,...Y.resetsAt===void 0?{}:{resetsAt:Y.resetsAt},...Y.windowMinutes===void 0?{}:{windowMinutes:Y.windowMinutes}})}for(let Y of D.coverage??[]){let x=Y.scope??G,B=Q(x,Y.label);if(W.has(B)||!T(B))continue;let f=X.get(B);X.set(B,f===void 0||f.kind==="absent"?{scope:x,label:Y.label,kind:"absent",checkedAt:U}:{scope:x,label:Y.label,kind:"retired",retiredAt:U})}let{limits:Z,budget:$,counters:P,...j}=J,E=Mz(J.budget,D.budget,U),k=Qz(J.counters,D.counters);return{...j,limits:[...X.values()].sort(Tz),...E===void 0?{}:{budget:E},...k===void 0?{}:{counters:k}}}var Rz=Object.freeze({validate:R,decode:_,merge:w});import{tmpdir as r}from"node:os";import{join as a}from"node:path";var _z=["error","warn","info","debug","trace"];function Kz(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??(process.platform==="win32"?a(r(),"opencode-openai-auth","opencode-openai-auth.log"):a(r(),"opencode-openai-auth.log"))}function Pz(){let z=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;return z&&_z.includes(z)?z:void 0}i({file:Kz,level:Pz});if(process.once("beforeExit",async()=>{try{await S()}catch{process.emitWarning("OpenAI auth could not flush its log file at shutdown")}}),process.platform!=="win32")process.on("exit",()=>S());
2
- export{G as kd,t as ld,_ as md,R as nd,w as od,Rz as pd,s as qd,o as rd,Uz as sd,$z as td,Gz as ud,Vz as vd,Wz as wd};
@@ -1 +0,0 @@
1
- import{b as a}from"./index-yeyp8t0k.js";import"./index-bgq9d21h.js";export default a();