@cortexkit/opencode-openai-auth 0.3.4 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +1 -0
  2. package/dist/cli.js +1 -1
  3. package/dist/codex-http.d.ts +3 -0
  4. package/dist/config.d.ts +3 -0
  5. package/dist/core/accounts.d.ts +9 -3
  6. package/dist/core/oauth.d.ts +1 -1
  7. package/dist/core/quota-manager.d.ts +2 -2
  8. package/dist/{index-k5zwf3j1.js → index-1anzb8jh.js} +1 -1
  9. package/dist/index-1r02s323.js +6 -0
  10. package/dist/index-2ng03cby.js +2 -0
  11. package/dist/{index-e7m7qbne.js → index-6y6ss1kc.js} +1 -1
  12. package/dist/{index-1xmasv0x.js → index-b6kp9ydc.js} +1 -1
  13. package/dist/index-cz1bkmjz.js +2 -0
  14. package/dist/index-dzg88nw2.js +89 -0
  15. package/dist/index-y67qn95a.js +2 -0
  16. package/dist/index.d.ts +8 -1
  17. package/dist/index.js +65 -65
  18. package/dist/model-costs.d.ts +29 -0
  19. package/dist/prompt-context.d.ts +1 -1
  20. package/dist/quota-normalize-8yzxqy78.js +1 -0
  21. package/dist/quota-normalize.d.ts +13 -4
  22. package/dist/rpc/port-file.js +1 -1
  23. package/dist/rpc/rpc-client.js +1 -1
  24. package/dist/rpc/rpc-dir.js +1 -1
  25. package/dist/sidebar-state.d.ts +47 -2
  26. package/dist/sidebar-state.js +1 -1
  27. package/dist/token-util-h46jb3eg.js +1 -0
  28. package/dist/token-yzcb1p3e.js +1 -0
  29. package/dist/tui/command-dialogs.d.ts +8 -1
  30. package/dist/tui-preferences.js +1 -1
  31. package/dist/tui.d.ts +18 -1
  32. package/dist/version.d.ts +1 -1
  33. package/dist/ws-pool.d.ts +1 -0
  34. package/package.json +6 -5
  35. package/src/core/refresh-file-lock.ts +293 -0
  36. package/src/sidebar-state.ts +392 -13
  37. package/src/tui/command-dialogs.tsx +43 -25
  38. package/src/tui-compiled/sidebar-state.ts +392 -13
  39. package/src/tui-compiled/tui/command-dialogs.tsx +25 -20
  40. package/src/tui-compiled/tui.tsx +228 -171
  41. package/src/tui.tsx +142 -64
  42. package/dist/index-5s67238f.js +0 -2
  43. package/dist/index-d9hq0tmc.js +0 -2
  44. package/dist/index-mrg2fms9.js +0 -2
  45. package/dist/index-qdh7pt5a.js +0 -3
  46. package/dist/index-y8d01tgn.js +0 -92
  47. package/dist/quota-normalize-dfdpwwm3.js +0 -1
  48. package/dist/token-01dcf92a.js +0 -1
  49. package/dist/token-util-rkqd82q9.js +0 -1
@@ -0,0 +1,29 @@
1
+ type CacheCost = {
2
+ read: number;
3
+ write: number;
4
+ };
5
+ type TierCost = {
6
+ input: number;
7
+ output: number;
8
+ cache: CacheCost;
9
+ tier: {
10
+ type: 'context';
11
+ size: number;
12
+ };
13
+ };
14
+ export type ModelCost = {
15
+ input: number;
16
+ output: number;
17
+ cache: CacheCost;
18
+ tiers?: TierCost[];
19
+ experimentalOver200K?: {
20
+ input: number;
21
+ output: number;
22
+ cache: CacheCost;
23
+ };
24
+ };
25
+ export declare function toSdkCost(raw: unknown): ModelCost | null;
26
+ export declare function loadModelsDevCosts(): Promise<Record<string, ModelCost> | null>;
27
+ /** Test-only: drop the memoized catalog so a later load re-reads its source. */
28
+ export declare function resetModelCostsForTest(): void;
29
+ export {};
@@ -6,7 +6,7 @@
6
6
  * model/variant, OpenCode's next real prompt can inherit the synthetic message's
7
7
  * default model/variant and silently change the model, usage, or cache
8
8
  * attribution. Resolve the most recent assistant context and pass it through on
9
- * hidden command replies so the user's selected model (including -pro) is kept.
9
+ * hidden command replies so the user's selected model and reasoning variant are kept.
10
10
  */
11
11
  export interface ResolvedPromptContext {
12
12
  agent?: string;
@@ -0,0 +1 @@
1
+ import{c as a,d as b,e as c,f as d,g as e}from"./index-2ng03cby.js";import"./index-6y6ss1kc.js";export{a as toResetIso,d as normalizeWsFrame,e as normalizeWham,b as normalizeQuotaHeaders,c as isCompleteQuotaHeaderFrame};
@@ -1,14 +1,20 @@
1
1
  import type { OAuthQuotaSnapshot } from './core/accounts.ts';
2
2
  export declare function toResetIso(raw: string | number | undefined): string | undefined;
3
3
  export declare function normalizeQuotaHeaders(h: Headers): OAuthQuotaSnapshot;
4
+ /**
5
+ * A complete frame has at least one syntactically valid used-percent header
6
+ * and no malformed used-percent headers. Explicit retired-slot markers count
7
+ * as valid even though normalization omits them from the snapshot.
8
+ */
9
+ export declare function isCompleteQuotaHeaderFrame(h: Headers): boolean;
4
10
  interface WsRateLimitWindow {
5
11
  used_percent: number;
6
12
  window_minutes: number;
7
13
  reset_at?: string | number;
8
14
  }
9
15
  interface WsRateLimits {
10
- primary?: WsRateLimitWindow;
11
- secondary?: WsRateLimitWindow;
16
+ primary?: WsRateLimitWindow | null;
17
+ secondary?: WsRateLimitWindow | null;
12
18
  }
13
19
  interface WsRateLimitsFrame {
14
20
  type: string;
@@ -22,12 +28,15 @@ interface WhamRateLimitWindow {
22
28
  reset_at?: string | number;
23
29
  }
24
30
  interface WhamRateLimits {
25
- primary_window?: WhamRateLimitWindow;
26
- secondary_window?: WhamRateLimitWindow;
31
+ primary_window?: WhamRateLimitWindow | null;
32
+ secondary_window?: WhamRateLimitWindow | null;
27
33
  }
28
34
  interface WhamUsageResponse {
29
35
  plan_type?: string;
30
36
  rate_limit: WhamRateLimits;
37
+ rate_limit_reset_credits?: {
38
+ available_count?: number;
39
+ } | null;
31
40
  }
32
41
  export declare function normalizeWham(json: WhamUsageResponse): OAuthQuotaSnapshot;
33
42
  export {};
@@ -1 +1 @@
1
- import{da as a,ea as b}from"../index-k5zwf3j1.js";import"../index-e7m7qbne.js";export{a as writePortFile,b as discoverPortFile};
1
+ import{ma as a,na as b}from"../index-1anzb8jh.js";import"../index-6y6ss1kc.js";export{a as writePortFile,b as discoverPortFile};
@@ -1 +1 @@
1
- import{ea as c}from"../index-k5zwf3j1.js";import"../index-e7m7qbne.js";async function p(n,r,l,o,i){let t=await c(n,r);if(l?.(t),!t)return null;let e=new AbortController,s=setTimeout(()=>e.abort(),2000);try{let a=await fetch(`http://127.0.0.1:${t.port}/rpc/${o}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.token}`},body:JSON.stringify(i),signal:e.signal});if(!a.ok)return null;return await a.json()}catch{return null}finally{clearTimeout(s)}}function y(n,r,l){let o=!1,i=(t)=>{if(o)return;o=!0,l?.(t)};return{async pending(t,e){return(await p(n,r,i,"pending-notifications",{lastReceivedId:t,sessionId:e}))?.messages??[]},async apply(t){return await p(n,r,i,"apply",{...t})??{text:"apply failed",knobs:{}}}}}export{y as createRpcClient};
1
+ import{na as c}from"../index-1anzb8jh.js";import"../index-6y6ss1kc.js";async function p(n,r,l,o,i){let t=await c(n,r);if(l?.(t),!t)return null;let e=new AbortController,s=setTimeout(()=>e.abort(),2000);try{let a=await fetch(`http://127.0.0.1:${t.port}/rpc/${o}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.token}`},body:JSON.stringify(i),signal:e.signal});if(!a.ok)return null;return await a.json()}catch{return null}finally{clearTimeout(s)}}function y(n,r,l){let o=!1,i=(t)=>{if(o)return;o=!0,l?.(t)};return{async pending(t,e){return(await p(n,r,i,"pending-notifications",{lastReceivedId:t,sessionId:e}))?.messages??[]},async apply(t){return await p(n,r,i,"apply",{...t})??{text:"apply failed",knobs:{}}}}}export{y as createRpcClient};
@@ -1 +1 @@
1
- import{fa as a,ga as b}from"../index-1xmasv0x.js";import"../index-e7m7qbne.js";export{a as tmpdir,b as getRpcDir};
1
+ import{oa as a,pa as b}from"../index-b6kp9ydc.js";import"../index-6y6ss1kc.js";export{a as tmpdir,b as getRpcDir};
@@ -2,18 +2,36 @@ export interface QuotaWindow {
2
2
  usedPercent: number;
3
3
  remainingPercent: number;
4
4
  resetsAt?: string;
5
+ windowMinutes?: number;
5
6
  }
6
7
  export interface AccountQuota {
7
8
  primary?: QuotaWindow;
8
9
  secondary?: QuotaWindow;
10
+ resetCreditsAvailable?: number;
9
11
  }
12
+ export type QuotaWindowKey = 'primary' | 'secondary';
13
+ export declare function formatWindowLabel(windowMinutes: number | undefined, fallbackKey: QuotaWindowKey): string;
14
+ export interface PresentQuotaWindow {
15
+ key: QuotaWindowKey;
16
+ label: string;
17
+ window: QuotaWindow;
18
+ windowMs: number | null;
19
+ }
20
+ export declare function getPresentQuotaWindows(quota: AccountQuota | null): PresentQuotaWindow[];
10
21
  export interface SidebarAccountState {
11
22
  id: string;
12
23
  label: string | undefined;
13
24
  quota: AccountQuota | null;
14
25
  killed: boolean;
15
26
  enabled: boolean;
27
+ resetCredits?: number;
28
+ }
29
+ export interface ActiveRoutingEntry {
30
+ activeId: string;
31
+ route: string;
32
+ updatedAt: number;
16
33
  }
34
+ export type ActiveRoutingMap = Record<string, ActiveRoutingEntry>;
17
35
  export interface SidebarState {
18
36
  main: {
19
37
  quota: AccountQuota | null;
@@ -22,10 +40,14 @@ export interface SidebarState {
22
40
  quotaBackoffUntil?: number;
23
41
  refreshBackedOff?: boolean;
24
42
  refreshBackoffUntil?: number;
43
+ resetCredits?: number;
25
44
  };
26
45
  fallbacks: SidebarAccountState[];
46
+ /** @deprecated Compatibility field for readers that do not consume activeRouting. */
27
47
  activeId: string | undefined;
48
+ /** Machine-global routing mode and compatibility value for older readers. */
28
49
  route: string;
50
+ activeRouting?: ActiveRoutingMap;
29
51
  planType?: string;
30
52
  credits?: number;
31
53
  lastUpdated: number;
@@ -43,6 +65,21 @@ export declare const DEFAULT_SIDEBAR_STATE: SidebarState;
43
65
  */
44
66
  export declare function normalizeSidebarState(raw: unknown): SidebarState;
45
67
  export declare function getSidebarState(): Promise<SidebarState>;
68
+ export declare const ACTIVE_ROUTING_MAX_AGE_MS: number;
69
+ export declare const ACTIVE_ROUTING_MAX_ENTRIES = 128;
70
+ export type SidebarRoutingAccount = {
71
+ id: string;
72
+ enabled?: boolean;
73
+ };
74
+ export declare function isUsableRoutingEntry(entry: ActiveRoutingEntry, accounts: readonly SidebarRoutingAccount[], now?: number): boolean;
75
+ export declare function resolveSessionSidebarRouting(state: SidebarState, sessionId?: string, now?: number): {
76
+ activeId: string;
77
+ route: string;
78
+ };
79
+ export declare function pruneActiveRouting(activeRouting: ActiveRoutingMap | undefined, accounts: readonly SidebarRoutingAccount[], now?: number, removedSessionId?: string): ActiveRoutingMap | undefined;
80
+ interface SidebarMergeHooks {
81
+ beforeRecheck?: () => void | Promise<void>;
82
+ }
46
83
  /**
47
84
  * Write sidebar state to disk, serialized through a promise chain so
48
85
  * concurrent callers never interleave or let a stale write land last.
@@ -55,6 +92,15 @@ export declare function getSidebarState(): Promise<SidebarState>;
55
92
  * Defaults to getSidebarStateFile() (per-call resolution).
56
93
  */
57
94
  export declare function setSidebarState(state: SidebarState, file?: string): Promise<void>;
95
+ export type SidebarMachineState = Pick<SidebarState, 'main' | 'fallbacks' | 'planType' | 'credits' | 'lastUpdated'> & {
96
+ route: string;
97
+ };
98
+ export declare function setSidebarMachineState(machineState: SidebarMachineState, file?: string, hooks?: SidebarMergeHooks): Promise<void>;
99
+ export declare function upsertSidebarActiveRouting(input: {
100
+ sessionId: string;
101
+ } & ActiveRoutingEntry, accounts: readonly SidebarRoutingAccount[], file?: string, hooks?: SidebarMergeHooks): Promise<void>;
102
+ export declare function setSidebarLegacyRouting(input: ActiveRoutingEntry, file?: string): Promise<void>;
103
+ export declare function removeSidebarActiveRouting(sessionId: string, accounts: readonly SidebarRoutingAccount[], file?: string, hooks?: SidebarMergeHooks): Promise<void>;
58
104
  /**
59
105
  * Await all pending sidebar writes. Tests call this before restoring env
60
106
  * vars in teardown so no in-flight write can re-resolve getSidebarStateFile()
@@ -72,8 +118,6 @@ export declare function getCollapsedQuotaSummary(quota: AccountQuota | null): {
72
118
  secondaryUsedPercent: number | null;
73
119
  text: string | null;
74
120
  };
75
- export declare const FIVE_HOUR_MS: number;
76
- export declare const SEVEN_DAY_MS: number;
77
121
  export interface QuotaPacing {
78
122
  pacePercent: number;
79
123
  deltaPercent: number;
@@ -81,3 +125,4 @@ export interface QuotaPacing {
81
125
  runsOutAt: string | null;
82
126
  }
83
127
  export declare function computeQuotaPacing(window: QuotaWindow, windowMs: number, now: number): QuotaPacing | null;
128
+ export {};
@@ -1 +1 @@
1
- import{$ as k,R as a,S as b,T as c,U as d,V as e,W as f,X as g,Y as h,Z as i,_ as j}from"./index-mrg2fms9.js";import"./index-qdh7pt5a.js";import"./index-e7m7qbne.js";export{e as setSidebarState,g as resolveActiveAccount,c as normalizeSidebarState,a as getSidebarStateFile,d as getSidebarState,h as getCollapsedQuotaSummary,f as drainSidebarWrites,k as computeQuotaPacing,j as SEVEN_DAY_MS,i as FIVE_HOUR_MS,b as DEFAULT_SIDEBAR_STATE};
1
+ import{$ as l,Q as a,R as b,S as c,T as d,U as e,V as f,W as g,X as h,Y as i,Z as j,_ as k,aa as m,ba as n,ca as o,da as p,ea as q,fa as r,ga as s,ha as t}from"./index-cz1bkmjz.js";import"./index-1r02s323.js";import"./index-6y6ss1kc.js";export{n as upsertSidebarActiveRouting,l as setSidebarState,m as setSidebarMachineState,o as setSidebarLegacyRouting,j as resolveSessionSidebarRouting,r as resolveActiveAccount,p as removeSidebarActiveRouting,k as pruneActiveRouting,e as normalizeSidebarState,i as isUsableRoutingEntry,c as getSidebarStateFile,f as getSidebarState,b as getPresentQuotaWindows,s as getCollapsedQuotaSummary,a as formatWindowLabel,q as drainSidebarWrites,t as computeQuotaPacing,d as DEFAULT_SIDEBAR_STATE,h as ACTIVE_ROUTING_MAX_ENTRIES,g as ACTIVE_ROUTING_MAX_AGE_MS};
@@ -0,0 +1 @@
1
+ import{b as a}from"./index-y67qn95a.js";import"./index-6y6ss1kc.js";export default a();
@@ -0,0 +1 @@
1
+ import{a as U,b as V}from"./index-y67qn95a.js";import{ra as R}from"./index-6y6ss1kc.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();
@@ -1,6 +1,7 @@
1
1
  /** @jsxImportSource @opentui/solid */
2
2
  import type { TuiPluginApi } from '@opencode-ai/plugin/tui';
3
3
  import type { OpenDialogPayload } from '../rpc/protocol.js';
4
+ import { type AccountQuota, type SidebarState } from '../sidebar-state.js';
4
5
  type ApplyFn = (command: OpenDialogPayload['command'], args: string) => Promise<{
5
6
  text: string;
6
7
  knobs: Record<string, unknown>;
@@ -10,5 +11,11 @@ export declare function buildCachekeepDialogOptions(payload: OpenDialogPayload):
10
11
  value: string;
11
12
  description: string;
12
13
  }[];
13
- export declare function openCommandDialog(api: TuiPluginApi, payload: OpenDialogPayload, apply: ApplyFn): void;
14
+ export declare function openCommandDialog(api: TuiPluginApi, payload: OpenDialogPayload, apply: ApplyFn, sessionId?: string): void;
15
+ export declare function formatQuotaWindows(quota: AccountQuota | null | undefined): string;
16
+ export declare function buildAccountDialogRows(state: SidebarState, sessionId?: string): {
17
+ title: string;
18
+ value: string;
19
+ description: string;
20
+ }[];
14
21
  export {};
@@ -1,4 +1,4 @@
1
- import{ha as P,ia as C,ka as _}from"./index-e7m7qbne.js";var g=C((T,L)=>{(function(Q){if(typeof L==="object"&&typeof L.exports==="object"){var J=Q(_,T);if(J!==void 0)L.exports=J}else if(typeof define==="function"&&define.amd)define(["require","exports","./impl/format","./impl/edit","./impl/scanner","./impl/parser"],Q)})(function(Q,J){Object.defineProperty(J,"__esModule",{value:!0}),J.applyEdits=J.modify=J.format=J.printParseErrorCode=J.ParseErrorCode=J.stripComments=J.visit=J.getNodeValue=J.getNodePath=J.findNodeAtOffset=J.findNodeAtLocation=J.parseTree=J.parse=J.getLocation=J.SyntaxKind=J.ScanError=J.createScanner=void 0;let X=Q("./impl/format"),Z=Q("./impl/edit"),G=Q("./impl/scanner"),$=Q("./impl/parser");J.createScanner=G.createScanner;var W;(function(z){z[z.None=0]="None",z[z.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",z[z.UnexpectedEndOfString=2]="UnexpectedEndOfString",z[z.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",z[z.InvalidUnicode=4]="InvalidUnicode",z[z.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",z[z.InvalidCharacter=6]="InvalidCharacter"})(W||(J.ScanError=W={}));var H;(function(z){z[z.OpenBraceToken=1]="OpenBraceToken",z[z.CloseBraceToken=2]="CloseBraceToken",z[z.OpenBracketToken=3]="OpenBracketToken",z[z.CloseBracketToken=4]="CloseBracketToken",z[z.CommaToken=5]="CommaToken",z[z.ColonToken=6]="ColonToken",z[z.NullKeyword=7]="NullKeyword",z[z.TrueKeyword=8]="TrueKeyword",z[z.FalseKeyword=9]="FalseKeyword",z[z.StringLiteral=10]="StringLiteral",z[z.NumericLiteral=11]="NumericLiteral",z[z.LineCommentTrivia=12]="LineCommentTrivia",z[z.BlockCommentTrivia=13]="BlockCommentTrivia",z[z.LineBreakTrivia=14]="LineBreakTrivia",z[z.Trivia=15]="Trivia",z[z.Unknown=16]="Unknown",z[z.EOF=17]="EOF"})(H||(J.SyntaxKind=H={})),J.getLocation=$.getLocation,J.parse=$.parse,J.parseTree=$.parseTree,J.findNodeAtLocation=$.findNodeAtLocation,J.findNodeAtOffset=$.findNodeAtOffset,J.getNodePath=$.getNodePath,J.getNodeValue=$.getNodeValue,J.visit=$.visit,J.stripComments=$.stripComments;var q;(function(z){z[z.InvalidSymbol=1]="InvalidSymbol",z[z.InvalidNumberFormat=2]="InvalidNumberFormat",z[z.PropertyNameExpected=3]="PropertyNameExpected",z[z.ValueExpected=4]="ValueExpected",z[z.ColonExpected=5]="ColonExpected",z[z.CommaExpected=6]="CommaExpected",z[z.CloseBraceExpected=7]="CloseBraceExpected",z[z.CloseBracketExpected=8]="CloseBracketExpected",z[z.EndOfFileExpected=9]="EndOfFileExpected",z[z.InvalidCommentToken=10]="InvalidCommentToken",z[z.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",z[z.UnexpectedEndOfString=12]="UnexpectedEndOfString",z[z.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",z[z.InvalidUnicode=14]="InvalidUnicode",z[z.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",z[z.InvalidCharacter=16]="InvalidCharacter"})(q||(J.ParseErrorCode=q={}));function D(z){switch(z){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}J.printParseErrorCode=D;function m(z,U,j){return X.format(z,U,j)}J.format=m;function f(z,U,j,A){return Z.setProperty(z,U,j,A)}J.modify=f;function u(z,U){let j=U.slice(0).sort((I,Y)=>{let F=I.offset-Y.offset;if(F===0)return I.length-Y.length;return F}),A=z.length;for(let I=j.length-1;I>=0;I--){let Y=j[I];if(Y.offset+Y.length<=A)z=Z.applyEdit(z,Y);else throw Error("Overlapping edit");A=Y.offset}return z}J.applyEdits=u})});var M=P(g(),1);import{watch as K}from"node:fs";import{mkdir as c,readFile as O,rename as y,writeFile as S}from"node:fs/promises";import{homedir as E}from"node:os";import{basename as l,dirname as v,join as k}from"node:path";var p="OPENCODE_TUI_PREFERENCES_FILE",x="tui-preferences.jsonc";function w(){let Q=process.env[p];if(Q)return Q;let J=process.env.OPENCODE_CONFIG_DIR||k(process.env.XDG_CONFIG_HOME||k(E(),".config"),"opencode");return k(J,x)}function N(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}async function Xz(){try{let Q=await O(w(),"utf8"),J=[],X=M.parse(Q,J,{allowTrailingComma:!0});if(J.length>0)return{};return N(X)?X:{}}catch{return{}}}var i="openai-auth",s=160,b={forceToTop:!1,order:s,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 V(Q,J){return typeof Q==="boolean"?Q:J}function B(Q,J,X,Z){if(typeof Q!=="number"||!Number.isFinite(Q))return J;return Math.min(Math.max(Math.round(Q),X),Z)}function d(Q,J,X){if(typeof Q!=="string"||Q.length===0)return J;return Q.slice(0,X)}function h(Q,J){if(typeof Q!=="string")return J;return[...Q][0]??J}function Zz(Q){let J=Q[i];if(!N(J))return structuredClone(b);let X=b,Z=N(J.header)?J.header:{},G=N(J.sections)?J.sections:{},$=N(J.appearance)?J.appearance:{},W=B($.warnThreshold,X.appearance.warnThreshold,0,99),H=Math.max(B($.errorThreshold,X.appearance.errorThreshold,0,100),Math.min(W+1,100));return{forceToTop:V(J.forceToTop,X.forceToTop),order:B(J.order,X.order,-1e4,1e4),startCollapsed:V(J.startCollapsed,X.startCollapsed),rememberCollapsed:V(J.rememberCollapsed,X.rememberCollapsed),collapsed:typeof J.collapsed==="boolean"?J.collapsed:null,pollMs:B(J.pollMs,X.pollMs,500,30000),refreshDebounceMs:B(J.refreshDebounceMs,X.refreshDebounceMs,50,5000),header:{label:d(Z.label,X.header.label,20),showVersion:V(Z.showVersion,X.header.showVersion)},sections:{quota:V(G.quota,X.sections.quota),fallbackAccounts:V(G.fallbackAccounts,X.sections.fallbackAccounts),routing:V(G.routing,X.sections.routing),health:V(G.health,X.sections.health),pacing:V(G.pacing,X.sections.pacing)},appearance:{barWidth:B($.barWidth,X.appearance.barWidth,4,40),barFilledChar:h($.barFilledChar,X.appearance.barFilledChar),barEmptyChar:h($.barEmptyChar,X.appearance.barEmptyChar),warnThreshold:W,errorThreshold:H}}}var n=-1e5;function $z(Q,J,X){let Z=Q[J];if(!N(Z))return X;if(Z.forceToTop===!0)return n+Object.keys(Q).indexOf(J);return B(Z.order,X,-1e4,1e4)}var t=`// Shared preferences for opencode TUI plugins.
1
+ import{qa as P,ra as C,ta as _}from"./index-6y6ss1kc.js";var g=C((T,L)=>{(function(Q){if(typeof L==="object"&&typeof L.exports==="object"){var J=Q(_,T);if(J!==void 0)L.exports=J}else if(typeof define==="function"&&define.amd)define(["require","exports","./impl/format","./impl/edit","./impl/scanner","./impl/parser"],Q)})(function(Q,J){Object.defineProperty(J,"__esModule",{value:!0}),J.applyEdits=J.modify=J.format=J.printParseErrorCode=J.ParseErrorCode=J.stripComments=J.visit=J.getNodeValue=J.getNodePath=J.findNodeAtOffset=J.findNodeAtLocation=J.parseTree=J.parse=J.getLocation=J.SyntaxKind=J.ScanError=J.createScanner=void 0;let X=Q("./impl/format"),Z=Q("./impl/edit"),G=Q("./impl/scanner"),$=Q("./impl/parser");J.createScanner=G.createScanner;var W;(function(z){z[z.None=0]="None",z[z.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",z[z.UnexpectedEndOfString=2]="UnexpectedEndOfString",z[z.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",z[z.InvalidUnicode=4]="InvalidUnicode",z[z.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",z[z.InvalidCharacter=6]="InvalidCharacter"})(W||(J.ScanError=W={}));var H;(function(z){z[z.OpenBraceToken=1]="OpenBraceToken",z[z.CloseBraceToken=2]="CloseBraceToken",z[z.OpenBracketToken=3]="OpenBracketToken",z[z.CloseBracketToken=4]="CloseBracketToken",z[z.CommaToken=5]="CommaToken",z[z.ColonToken=6]="ColonToken",z[z.NullKeyword=7]="NullKeyword",z[z.TrueKeyword=8]="TrueKeyword",z[z.FalseKeyword=9]="FalseKeyword",z[z.StringLiteral=10]="StringLiteral",z[z.NumericLiteral=11]="NumericLiteral",z[z.LineCommentTrivia=12]="LineCommentTrivia",z[z.BlockCommentTrivia=13]="BlockCommentTrivia",z[z.LineBreakTrivia=14]="LineBreakTrivia",z[z.Trivia=15]="Trivia",z[z.Unknown=16]="Unknown",z[z.EOF=17]="EOF"})(H||(J.SyntaxKind=H={})),J.getLocation=$.getLocation,J.parse=$.parse,J.parseTree=$.parseTree,J.findNodeAtLocation=$.findNodeAtLocation,J.findNodeAtOffset=$.findNodeAtOffset,J.getNodePath=$.getNodePath,J.getNodeValue=$.getNodeValue,J.visit=$.visit,J.stripComments=$.stripComments;var q;(function(z){z[z.InvalidSymbol=1]="InvalidSymbol",z[z.InvalidNumberFormat=2]="InvalidNumberFormat",z[z.PropertyNameExpected=3]="PropertyNameExpected",z[z.ValueExpected=4]="ValueExpected",z[z.ColonExpected=5]="ColonExpected",z[z.CommaExpected=6]="CommaExpected",z[z.CloseBraceExpected=7]="CloseBraceExpected",z[z.CloseBracketExpected=8]="CloseBracketExpected",z[z.EndOfFileExpected=9]="EndOfFileExpected",z[z.InvalidCommentToken=10]="InvalidCommentToken",z[z.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",z[z.UnexpectedEndOfString=12]="UnexpectedEndOfString",z[z.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",z[z.InvalidUnicode=14]="InvalidUnicode",z[z.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",z[z.InvalidCharacter=16]="InvalidCharacter"})(q||(J.ParseErrorCode=q={}));function D(z){switch(z){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}J.printParseErrorCode=D;function m(z,U,j){return X.format(z,U,j)}J.format=m;function f(z,U,j,A){return Z.setProperty(z,U,j,A)}J.modify=f;function u(z,U){let j=U.slice(0).sort((I,Y)=>{let F=I.offset-Y.offset;if(F===0)return I.length-Y.length;return F}),A=z.length;for(let I=j.length-1;I>=0;I--){let Y=j[I];if(Y.offset+Y.length<=A)z=Z.applyEdit(z,Y);else throw Error("Overlapping edit");A=Y.offset}return z}J.applyEdits=u})});var M=P(g(),1);import{watch as K}from"node:fs";import{mkdir as c,readFile as O,rename as y,writeFile as S}from"node:fs/promises";import{homedir as E}from"node:os";import{basename as l,dirname as v,join as k}from"node:path";var p="OPENCODE_TUI_PREFERENCES_FILE",x="tui-preferences.jsonc";function w(){let Q=process.env[p];if(Q)return Q;let J=process.env.OPENCODE_CONFIG_DIR||k(process.env.XDG_CONFIG_HOME||k(E(),".config"),"opencode");return k(J,x)}function N(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}async function Xz(){try{let Q=await O(w(),"utf8"),J=[],X=M.parse(Q,J,{allowTrailingComma:!0});if(J.length>0)return{};return N(X)?X:{}}catch{return{}}}var i="openai-auth",s=160,b={forceToTop:!1,order:s,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 V(Q,J){return typeof Q==="boolean"?Q:J}function B(Q,J,X,Z){if(typeof Q!=="number"||!Number.isFinite(Q))return J;return Math.min(Math.max(Math.round(Q),X),Z)}function d(Q,J,X){if(typeof Q!=="string"||Q.length===0)return J;return Q.slice(0,X)}function h(Q,J){if(typeof Q!=="string")return J;return[...Q][0]??J}function Zz(Q){let J=Q[i];if(!N(J))return structuredClone(b);let X=b,Z=N(J.header)?J.header:{},G=N(J.sections)?J.sections:{},$=N(J.appearance)?J.appearance:{},W=B($.warnThreshold,X.appearance.warnThreshold,0,99),H=Math.max(B($.errorThreshold,X.appearance.errorThreshold,0,100),Math.min(W+1,100));return{forceToTop:V(J.forceToTop,X.forceToTop),order:B(J.order,X.order,-1e4,1e4),startCollapsed:V(J.startCollapsed,X.startCollapsed),rememberCollapsed:V(J.rememberCollapsed,X.rememberCollapsed),collapsed:typeof J.collapsed==="boolean"?J.collapsed:null,pollMs:B(J.pollMs,X.pollMs,500,30000),refreshDebounceMs:B(J.refreshDebounceMs,X.refreshDebounceMs,50,5000),header:{label:d(Z.label,X.header.label,20),showVersion:V(Z.showVersion,X.header.showVersion)},sections:{quota:V(G.quota,X.sections.quota),fallbackAccounts:V(G.fallbackAccounts,X.sections.fallbackAccounts),routing:V(G.routing,X.sections.routing),health:V(G.health,X.sections.health),pacing:V(G.pacing,X.sections.pacing)},appearance:{barWidth:B($.barWidth,X.appearance.barWidth,4,40),barFilledChar:h($.barFilledChar,X.appearance.barFilledChar),barEmptyChar:h($.barEmptyChar,X.appearance.barEmptyChar),warnThreshold:W,errorThreshold:H}}}var n=-1e5;function $z(Q,J,X){let Z=Q[J];if(!N(Z))return X;if(Z.forceToTop===!0)return n+Object.keys(Q).indexOf(J);return B(Z.order,X,-1e4,1e4)}var t=`// Shared preferences for opencode TUI plugins.
2
2
  // One top-level key per plugin (short name). See each plugin's README for
3
3
  // its supported settings. This file is safe to hand-edit; plugins update
4
4
  // individual keys in place and preserve comments.
package/dist/tui.d.ts CHANGED
@@ -1,8 +1,25 @@
1
1
  /** @jsxImportSource @opentui/solid */
2
2
  import type { TuiPluginModule } from '@opencode-ai/plugin/tui';
3
- import { type SidebarState } from './sidebar-state.js';
3
+ import { type AccountQuota, type QuotaPacing, type QuotaWindow, type SidebarState } from './sidebar-state.js';
4
4
  export declare function formatResetIn(resetsAt: string | undefined): string;
5
+ export interface QuotaDisplayRow {
6
+ key: 'primary' | 'secondary';
7
+ label: string;
8
+ window: QuotaWindow;
9
+ pacing: QuotaPacing | null;
10
+ }
11
+ export declare function buildQuotaRowsForDisplay(quota: AccountQuota | null, now: number, pacingEnabled: boolean): QuotaDisplayRow[];
12
+ export declare function isQuotaLoaded(quota: AccountQuota | null): boolean;
13
+ export declare function getQuotaMetadataRows(state: SidebarState): Array<{
14
+ label: string;
15
+ value: string;
16
+ }>;
17
+ export declare function getAccountMetadataRows(resetCredits: number | undefined): Array<{
18
+ label: string;
19
+ value: string;
20
+ }>;
5
21
  export declare function readStateFromFile(): Promise<SidebarState>;
22
+ export declare function resolveQuotaDialogActiveId(state: SidebarState, sessionId: string | undefined, now?: number): string | undefined;
6
23
  declare const plugin: TuiPluginModule & {
7
24
  id: string;
8
25
  };
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const PackageVersion = "0.3.4";
1
+ export declare const PackageVersion = "0.4.0";
package/dist/ws-pool.d.ts CHANGED
@@ -58,6 +58,7 @@ export declare function createWebSocketFetch(options?: CreateWebSocketFetchOptio
58
58
  export declare const CODEX_BODY_KEY_ORDER: string[];
59
59
  export declare function orderCodexBody(body: Record<string, unknown>): Record<string, unknown>;
60
60
  export declare function applyTurnId(entry: PoolEntry, body: Record<string, unknown>, fullBody?: Record<string, unknown>): Record<string, unknown>;
61
+ export { hasWebSocketResponsesLiteMetadata, sanitizeHttpFallbackBody, } from './codex-http';
61
62
  export declare function withoutInternalHeaders<T extends {
62
63
  headers?: HeadersInit;
63
64
  }>(init: T | undefined): T | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-openai-auth",
3
- "version": "0.3.4",
3
+ "version": "0.4.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "repository": {
@@ -42,6 +42,7 @@
42
42
  "src/sidebar-state.ts",
43
43
  "src/tui-preferences.ts",
44
44
  "src/logger.ts",
45
+ "src/core/refresh-file-lock.ts",
45
46
  "src/util",
46
47
  "src/rpc",
47
48
  "README.md",
@@ -60,10 +61,10 @@
60
61
  "@opencode-ai/plugin": "*"
61
62
  },
62
63
  "dependencies": {
63
- "@opentui/core": ">=0.4.0",
64
- "@opentui/solid": ">=0.4.0",
65
- "ai": "^5.0.88",
64
+ "@opentui/core": ">=0.4.4",
65
+ "@opentui/solid": ">=0.4.4",
66
+ "ai": "^7.0.30",
66
67
  "jsonc-parser": "^3.3.1",
67
- "solid-js": "^1.9.10"
68
+ "solid-js": "1.9.12"
68
69
  }
69
70
  }
@@ -0,0 +1,293 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
3
+ import { homedir } from 'node:os'
4
+ import { dirname, join } from 'node:path'
5
+
6
+ const setRefreshLockRenewalTimeout = globalThis.setTimeout.bind(globalThis)
7
+ const clearRefreshLockRenewalTimeout = globalThis.clearTimeout.bind(globalThis)
8
+
9
+ export const ACCOUNT_FILE_NAME = 'openai-auth.json'
10
+ export const ACCOUNT_STATE_FILE_NAME = 'openai-auth-state.json'
11
+
12
+ function getConfigDir() {
13
+ if (process.env.OPENCODE_CONFIG_DIR?.trim()) {
14
+ return process.env.OPENCODE_CONFIG_DIR.trim()
15
+ }
16
+ return join(
17
+ process.env.XDG_CONFIG_HOME || join(homedir(), '.config'),
18
+ 'opencode',
19
+ )
20
+ }
21
+
22
+ // A concurrent contender renaming the freshly-created eviction-marker directory
23
+ // away surfaces the vanished parent differently per platform: ENOENT on Linux,
24
+ // EINVAL or ENOTDIR on macOS/APFS. All three mean the marker is no longer ours
25
+ // to hold — a lost race the caller should retry, not a fatal lock error.
26
+ export function isLostMarkerRaceError(error: unknown): boolean {
27
+ const code = (error as NodeJS.ErrnoException | null)?.code
28
+ return code === 'ENOENT' || code === 'EINVAL' || code === 'ENOTDIR'
29
+ }
30
+
31
+ export function getAccountStoragePath() {
32
+ return (
33
+ process.env.OPENCODE_OPENAI_AUTH_FILE?.trim() ||
34
+ join(getConfigDir(), ACCOUNT_FILE_NAME)
35
+ )
36
+ }
37
+
38
+ export function getAccountStatePath(configPath = getAccountStoragePath()) {
39
+ const explicit = process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim()
40
+ if (explicit) return explicit
41
+ return configPath.endsWith(ACCOUNT_FILE_NAME)
42
+ ? join(dirname(configPath), ACCOUNT_STATE_FILE_NAME)
43
+ : `${configPath}.state.json`
44
+ }
45
+
46
+ export async function acquireRefreshFileLock(options: {
47
+ name: string
48
+ ttlMs: number
49
+ path?: string
50
+ now?: () => number
51
+ renew?: boolean
52
+ renewIntervalMs?: number
53
+ onStep?: (
54
+ step:
55
+ | 'stale-marker-stat'
56
+ | 'stale-marker-claimed'
57
+ | 'stale-lock-confirmed'
58
+ | 'eviction-marker-acquired',
59
+ ) => void | Promise<void>
60
+ }): Promise<{ release: () => Promise<void> } | null> {
61
+ const accountPath = options.path ?? getAccountStoragePath()
62
+ const lockPath = `${accountPath}.${options.name}.lock`
63
+ const legacyOwnerPath = join(lockPath, 'owner.json')
64
+ const ownerId = randomUUID()
65
+ const now = options.now ?? Date.now
66
+ let renewTimer: ReturnType<typeof setTimeout> | null = null
67
+ let released = false
68
+
69
+ async function readOwner() {
70
+ try {
71
+ return JSON.parse(await readFile(lockPath, 'utf8'))
72
+ } catch (error) {
73
+ const code = (error as NodeJS.ErrnoException).code
74
+ if (code !== 'EISDIR') throw error
75
+ return JSON.parse(await readFile(legacyOwnerPath, 'utf8'))
76
+ }
77
+ }
78
+
79
+ async function writeOwner() {
80
+ await writeFile(
81
+ lockPath,
82
+ `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}\n`,
83
+ { encoding: 'utf8', mode: 0o600 },
84
+ )
85
+ }
86
+
87
+ async function tryAcquire() {
88
+ try {
89
+ await writeFile(
90
+ lockPath,
91
+ `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}\n`,
92
+ { encoding: 'utf8', mode: 0o600, flag: 'wx' },
93
+ )
94
+ return true
95
+ } catch (error) {
96
+ const code = (error as NodeJS.ErrnoException).code
97
+ if (code === 'EEXIST' || code === 'EISDIR') return false
98
+ throw error
99
+ }
100
+ }
101
+
102
+ function scheduleRenewal() {
103
+ if (!options.renew || released) return
104
+ const intervalMs =
105
+ options.renewIntervalMs ?? Math.max(1_000, Math.floor(options.ttlMs / 3))
106
+ renewTimer = setRefreshLockRenewalTimeout(() => {
107
+ void (async () => {
108
+ try {
109
+ const owner = await readOwner()
110
+ const currentNow = now()
111
+ if (
112
+ released ||
113
+ owner?.ownerId !== ownerId ||
114
+ Number(owner?.expiresAt) <= currentNow
115
+ ) {
116
+ return
117
+ }
118
+ await writeOwner()
119
+ scheduleRenewal()
120
+ } catch {
121
+ // If renewal fails, contenders will wait until the last written expiry.
122
+ }
123
+ })()
124
+ }, intervalMs)
125
+ if ('unref' in renewTimer) renewTimer.unref()
126
+ }
127
+
128
+ let acquired = await tryAcquire()
129
+ if (!acquired) {
130
+ // Fencing-token eviction: a directory-based marker (mkdir O_EXCL) serializes
131
+ // destructive removal to one contender at a time. The marker holds an owner
132
+ // file so ownership survives a stale-marker recovery rename: the recovering
133
+ // contender renames the stale directory, then must re-check ownership before
134
+ // acting — preventing the 3rd interleaving where a stale observer renames the
135
+ // FRESH marker the mkdir-winner created.
136
+ const evictPath = `${lockPath}.evicting`
137
+ const evictOwnerPath = join(evictPath, 'owner.json')
138
+ const evictOwnerId = randomUUID()
139
+ const EVICT_TTL = 5_000
140
+ const MAX_STEAL_ATTEMPTS = 8
141
+
142
+ async function backoff() {
143
+ await new Promise((resolve) =>
144
+ setTimeout(resolve, Math.floor(Math.random() * 4)),
145
+ )
146
+ }
147
+
148
+ async function lockIsLive() {
149
+ try {
150
+ const currentOwner = await readOwner()
151
+ return Number(currentOwner?.expiresAt) > now()
152
+ } catch {
153
+ try {
154
+ const current = await stat(lockPath)
155
+ return current.mtimeMs + options.ttlMs > now()
156
+ } catch {
157
+ // Lock doesn't exist — safe to acquire.
158
+ return false
159
+ }
160
+ }
161
+ }
162
+
163
+ // Fail-closed: any read error means we do NOT own the marker.
164
+ async function ownsEvictionMarker() {
165
+ try {
166
+ const owner = JSON.parse(await readFile(evictOwnerPath, 'utf8'))
167
+ return owner?.ownerId === evictOwnerId
168
+ } catch {
169
+ return false
170
+ }
171
+ }
172
+
173
+ async function tryAcquireEvictionMarker() {
174
+ await mkdir(evictPath)
175
+ try {
176
+ await writeFile(
177
+ evictOwnerPath,
178
+ `${JSON.stringify({ ownerId: evictOwnerId, createdAt: now() })}\n`,
179
+ { encoding: 'utf8', mode: 0o600, flag: 'wx' },
180
+ )
181
+ } catch (error) {
182
+ // A competing contender can rename our just-created marker directory
183
+ // away between the mkdir above and this write (the stale-marker steal
184
+ // path below does exactly that). That is a lost race, not a failure, so
185
+ // report it as such and let the caller back off and retry rather than
186
+ // failing the whole lock acquisition.
187
+ if (isLostMarkerRaceError(error)) return false
188
+ await releaseEvictionMarker()
189
+ throw error
190
+ }
191
+ await options.onStep?.('eviction-marker-acquired')
192
+ return true
193
+ }
194
+
195
+ async function releaseEvictionMarker() {
196
+ if (await ownsEvictionMarker()) {
197
+ await rm(evictPath, { recursive: true, force: true }).catch(() => {})
198
+ }
199
+ }
200
+
201
+ for (let attempt = 0; attempt < MAX_STEAL_ATTEMPTS; attempt++) {
202
+ acquired = await tryAcquire()
203
+ if (acquired) break
204
+ if (await lockIsLive()) return null
205
+
206
+ try {
207
+ if (!(await tryAcquireEvictionMarker())) {
208
+ await backoff()
209
+ continue
210
+ }
211
+ } catch (evictError) {
212
+ const code = (evictError as NodeJS.ErrnoException).code
213
+ if (code !== 'EEXIST') throw evictError
214
+
215
+ let evictStat: Awaited<ReturnType<typeof stat>>
216
+ try {
217
+ evictStat = await stat(evictPath)
218
+ } catch (statError) {
219
+ if ((statError as NodeJS.ErrnoException).code === 'ENOENT') {
220
+ await backoff()
221
+ continue
222
+ }
223
+ throw statError
224
+ }
225
+ if (evictStat.mtimeMs + EVICT_TTL > now()) return null
226
+
227
+ await options.onStep?.('stale-marker-stat')
228
+ const claimedPath = `${evictPath}.${randomUUID()}`
229
+ try {
230
+ await rename(evictPath, claimedPath)
231
+ } catch (renameError) {
232
+ if ((renameError as NodeJS.ErrnoException).code === 'ENOENT') {
233
+ await backoff()
234
+ continue
235
+ }
236
+ throw renameError
237
+ }
238
+ await options.onStep?.('stale-marker-claimed')
239
+ await rm(claimedPath, { recursive: true, force: true }).catch(() => {})
240
+ await backoff()
241
+ continue
242
+ }
243
+
244
+ try {
245
+ if (await lockIsLive()) return null
246
+ // Fence check 1: verify we still own the marker before acting on the
247
+ // stale-lock-confirmed decision.
248
+ if (!(await ownsEvictionMarker())) return null
249
+ await options.onStep?.('stale-lock-confirmed')
250
+ // Fence check 2: re-verify ownership after the seam (another contender
251
+ // may have renamed our fresh marker while we were paused here).
252
+ if (!(await ownsEvictionMarker())) return null
253
+ await rm(lockPath, { recursive: true, force: true }).catch(() => {})
254
+ // Fence check 3: re-verify ownership after removing the stale lock.
255
+ if (!(await ownsEvictionMarker())) return null
256
+ acquired = await tryAcquire()
257
+ if (!acquired) return null
258
+ // Fence check 4: re-verify ownership after acquiring the lock. If the
259
+ // marker was stolen between tryAcquire and this check, release the
260
+ // just-acquired lock and return null (fail-closed).
261
+ if (!(await ownsEvictionMarker())) {
262
+ await rm(lockPath, { recursive: true, force: true }).catch(() => {})
263
+ acquired = false
264
+ return null
265
+ }
266
+ break
267
+ } finally {
268
+ await releaseEvictionMarker()
269
+ }
270
+ }
271
+ }
272
+
273
+ if (!acquired) return null
274
+
275
+ scheduleRenewal()
276
+
277
+ return {
278
+ release: async () => {
279
+ released = true
280
+ if (renewTimer) {
281
+ clearRefreshLockRenewalTimeout(renewTimer)
282
+ renewTimer = null
283
+ }
284
+ try {
285
+ const owner = await readOwner()
286
+ if (owner?.ownerId !== ownerId) return
287
+ } catch {
288
+ return
289
+ }
290
+ await rm(lockPath, { recursive: true, force: true }).catch(() => {})
291
+ },
292
+ }
293
+ }