@cortexkit/opencode-openai-auth 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +12 -60
  2. package/dist/bin.js +13 -0
  3. package/dist/index-2hch7e8n.js +8 -0
  4. package/dist/{index-766sfrh5.js → index-45qgkb0m.js} +1 -1
  5. package/dist/index-5dg931q0.js +65 -0
  6. package/dist/index-99esnzg0.js +157 -0
  7. package/dist/index-9reyazwh.js +2 -0
  8. package/dist/index-bgq9d21h.js +2 -0
  9. package/dist/index-dryydk6b.js +2 -0
  10. package/dist/index-egrty6tz.js +12 -0
  11. package/dist/index-envpbt0k.js +3 -0
  12. package/dist/index-jye6vccc.js +2 -0
  13. package/dist/index-k4eacw7x.js +2 -0
  14. package/dist/{index-hy9030jh.js → index-yeyp8t0k.js} +1 -1
  15. package/dist/index-yf6arn5w.js +2 -0
  16. package/dist/index.d.ts +2 -56
  17. package/dist/index.js +1 -1
  18. package/dist/map-CCbSZIhT.d.ts +56 -0
  19. package/dist/{pool-lifecycle-DbDmgabd.d.ts → pool-lifecycle-DqKq8Eej.d.ts} +104 -790
  20. package/dist/{port-file-Do3lQIEk.d.ts → port-file-CZ9MIdy2.d.ts} +1 -1
  21. package/dist/{protocol-BOBdkqqm.d.ts → protocol-CSIDDBDf.d.ts} +1 -1
  22. package/dist/rpc/port-file.d.ts +1 -1
  23. package/dist/rpc/port-file.js +1 -1
  24. package/dist/rpc/protocol.d.ts +1 -1
  25. package/dist/rpc/protocol.js +1 -1
  26. package/dist/rpc/rpc-client.d.ts +3 -3
  27. package/dist/rpc/rpc-client.js +1 -1
  28. package/dist/rpc/rpc-dir.js +1 -1
  29. package/dist/{sidebar-state-D6cUKgkm.d.ts → sidebar-state-BCxFpH68.d.ts} +5 -3
  30. package/dist/sidebar-state.d.ts +1 -1
  31. package/dist/sidebar-state.js +1 -1
  32. package/dist/token-util-gmn5yaqc.js +1 -0
  33. package/dist/{token-ypk61xj0.js → token-vykm9bxh.js} +1 -1
  34. package/dist/tui-preferences.d.ts +2 -1
  35. package/dist/tui-preferences.js +3 -3
  36. package/dist/tui.d.ts +2 -2
  37. package/dist/v2/server.d.ts +1 -1
  38. package/dist/v2/server.js +3 -4
  39. package/package.json +13 -8
  40. package/src/tui-compiled/raw/logger.js +10 -2
  41. package/src/tui-compiled/raw/shared/053cc17b5419261e-codec.js +2 -1
  42. package/src/tui-compiled/raw/shared/0766d78c6f481f18-watcher.js +26 -10
  43. package/src/tui-compiled/raw/shared/375d9cca2def037d-private-files.js +302 -0
  44. package/src/tui-compiled/raw/shared/39c3cb05738fcf6d-projection.js +3 -1
  45. package/src/tui-compiled/raw/shared/43fc9e6b994519c7-refresh-lock.js +5 -0
  46. package/src/tui-compiled/raw/shared/458b934e92490331-mutate.js +2 -2
  47. package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +4 -0
  48. package/src/tui-compiled/raw/shared/4f36d333d081d040-merge.js +21 -5
  49. package/src/tui-compiled/raw/shared/7211cfec06a298bc-atomic-write.js +21 -0
  50. package/src/tui-compiled/raw/shared/905bffc0220f43d0-map.js +36 -1
  51. package/src/tui-compiled/raw/shared/a09b6a533c11858f-tui-preferences.js +6 -4
  52. package/src/tui-compiled/raw/shared/c14988621dc60a75-port-file.js +30 -8
  53. package/src/tui-compiled/raw/shared/c64d7afbc14ca125-sidebar-file.js +17 -8
  54. package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +3 -0
  55. package/src/tui-compiled/raw/shared/cd94316a888b0a8e-schema.js +3 -2
  56. package/src/tui-compiled/raw/shared/d5a8f1061ee2f114-index.js +1 -1
  57. package/src/tui-compiled/raw/shared/d7dcba96fea1685c-engine.js +126 -11
  58. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +254 -37
  59. package/src/tui-compiled/raw/shared/ec971142548df90e-index.js +1 -0
  60. package/src/tui-compiled/raw/shared/fbcdcd0f925e74c0-rpc-client.js +15 -1
  61. package/src/tui-compiled/raw/sidebar-state.js +3 -3
  62. package/src/tui-compiled/runtime/logger.js +10 -2
  63. package/src/tui-compiled/runtime/shared/053cc17b5419261e-codec.js +2 -1
  64. package/src/tui-compiled/runtime/shared/0766d78c6f481f18-watcher.js +26 -10
  65. package/src/tui-compiled/runtime/shared/375d9cca2def037d-private-files.js +302 -0
  66. package/src/tui-compiled/runtime/shared/39c3cb05738fcf6d-projection.js +3 -1
  67. package/src/tui-compiled/runtime/shared/43fc9e6b994519c7-refresh-lock.js +5 -0
  68. package/src/tui-compiled/runtime/shared/458b934e92490331-mutate.js +2 -2
  69. package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +4 -0
  70. package/src/tui-compiled/runtime/shared/4f36d333d081d040-merge.js +21 -5
  71. package/src/tui-compiled/runtime/shared/7211cfec06a298bc-atomic-write.js +21 -0
  72. package/src/tui-compiled/runtime/shared/905bffc0220f43d0-map.js +36 -1
  73. package/src/tui-compiled/runtime/shared/a09b6a533c11858f-tui-preferences.js +6 -4
  74. package/src/tui-compiled/runtime/shared/c14988621dc60a75-port-file.js +30 -8
  75. package/src/tui-compiled/runtime/shared/c64d7afbc14ca125-sidebar-file.js +17 -8
  76. package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +3 -0
  77. package/src/tui-compiled/runtime/shared/cd94316a888b0a8e-schema.js +3 -2
  78. package/src/tui-compiled/runtime/shared/d5a8f1061ee2f114-index.js +1 -1
  79. package/src/tui-compiled/runtime/shared/d7dcba96fea1685c-engine.js +126 -11
  80. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +254 -37
  81. package/src/tui-compiled/runtime/shared/ec971142548df90e-index.js +1 -0
  82. package/src/tui-compiled/runtime/shared/fbcdcd0f925e74c0-rpc-client.js +15 -1
  83. package/src/tui-compiled/runtime/sidebar-state.js +3 -3
  84. package/dist/index-8kj7sa1p.js +0 -12
  85. package/dist/index-b3q3j39x.js +0 -2
  86. package/dist/index-bmd7x5aq.js +0 -2
  87. package/dist/index-eqh53k8v.js +0 -2
  88. package/dist/index-jyr8y8k4.js +0 -7
  89. package/dist/index-m9d2bfkn.js +0 -222
  90. package/dist/index-rv08jmd4.js +0 -2
  91. package/dist/token-util-wdza526f.js +0 -1
@@ -1,4 +1,4 @@
1
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.14.2+49be191d46b46482/node_modules/@cortexkit/common-auth/dist/rpc/port-file.d.ts
1
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/rpc/port-file.d.ts
2
2
  interface PortFileEntry {
3
3
  port: number;
4
4
  token: string;
@@ -1,4 +1,4 @@
1
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.14.2+49be191d46b46482/node_modules/@cortexkit/common-auth/dist/commands/model.d.ts
1
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/commands/model.d.ts
2
2
  /** The section slots, in the one order every renderer shows them. */
3
3
  declare const SECTION_SLOTS: readonly ['accounts', 'quota', 'routing', 'limits', 'cache', 'diagnostics', 'extra'];
4
4
  type SectionSlot = (typeof SECTION_SLOTS)[number];
@@ -1,4 +1,4 @@
1
- import { n as discoverPortFile, r as writePortFile, t as PortFileEntry } from "../port-file-Do3lQIEk.js";
1
+ import { n as discoverPortFile, r as writePortFile, t as PortFileEntry } from "../port-file-CZ9MIdy2.js";
2
2
  //#region src/rpc/port-file.d.ts
3
3
  export declare const isOpenaiRpcStateDir: (name: string) => boolean;
4
4
  //#endregion
@@ -1 +1 @@
1
- import{Yb as c}from"../index-rv08jmd4.js";import{_b as a,ac as b}from"../index-8kj7sa1p.js";import"../index-766sfrh5.js";import"../index-b3q3j39x.js";export{a as writePortFile,c as isOpenaiRpcStateDir,b as discoverPortFile};
1
+ import{Ld as c}from"../index-jye6vccc.js";import{Nd as a,Pd as b}from"../index-egrty6tz.js";import"../index-dryydk6b.js";import"../index-45qgkb0m.js";import"../index-bgq9d21h.js";export{a as writePortFile,c as isOpenaiRpcStateDir,b as discoverPortFile};
@@ -1,2 +1,2 @@
1
- import { a as RpcNotification, i as OpenDialogPayload, n as ApplyResult, o as isNotifyPayload, r as NotifyPayload, t as ApplyRequest } from "../protocol-BOBdkqqm.js";
1
+ import { a as RpcNotification, i as OpenDialogPayload, n as ApplyResult, o as isNotifyPayload, r as NotifyPayload, t as ApplyRequest } from "../protocol-CSIDDBDf.js";
2
2
  export { type ApplyRequest, type ApplyResult, type NotifyPayload, type OpenDialogPayload, type RpcNotification, isNotifyPayload };
@@ -1 +1 @@
1
- import{mc as b}from"../index-bmd7x5aq.js";import"../index-b3q3j39x.js";export{b as isNotifyPayload};
1
+ import{$d as b}from"../index-k4eacw7x.js";import"../index-dryydk6b.js";import"../index-bgq9d21h.js";export{b as isNotifyPayload};
@@ -1,6 +1,6 @@
1
- import { a as RpcNotification, n as ApplyResult, t as ApplyRequest } from "../protocol-BOBdkqqm.js";
2
- import { t as PortFileEntry } from "../port-file-Do3lQIEk.js";
3
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.14.2+49be191d46b46482/node_modules/@cortexkit/common-auth/dist/rpc/rpc-client.d.ts
1
+ import { a as RpcNotification, n as ApplyResult, t as ApplyRequest } from "../protocol-CSIDDBDf.js";
2
+ import { t as PortFileEntry } from "../port-file-CZ9MIdy2.js";
3
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/rpc/rpc-client.d.ts
4
4
  export declare const DEFAULT_RPC_TIMEOUT_MS = 2000;
5
5
  //#endregion
6
6
  //#region src/rpc/rpc-client.d.ts
@@ -1 +1 @@
1
- import{bc as F,cc as f}from"../index-8kj7sa1p.js";import"../index-b3q3j39x.js";function y(r,s,v){return f(r,s,v)}export{y as createRpcClient,F as DEFAULT_RPC_TIMEOUT_MS};
1
+ import{Qd as F,Rd as f}from"../index-egrty6tz.js";import"../index-dryydk6b.js";import"../index-bgq9d21h.js";function y(r,s,v){return f(r,s,v)}export{y as createRpcClient,F as DEFAULT_RPC_TIMEOUT_MS};
@@ -1 +1 @@
1
- import{oc as a,pc as b,qc as c,rc as d}from"../index-766sfrh5.js";import"../index-b3q3j39x.js";export{a as tmpdir,d as resolveRpcDir,c as getRpcDir,b as RPC_DIRECTORY_PREFIX};
1
+ import{me as a,ne as b,oe as c,pe as d}from"../index-45qgkb0m.js";import"../index-bgq9d21h.js";export{a as tmpdir,d as resolveRpcDir,c as getRpcDir,b as RPC_DIRECTORY_PREFIX};
@@ -1,4 +1,5 @@
1
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.14.2+49be191d46b46482/node_modules/@cortexkit/common-auth/dist/logger/engine.d.ts
1
+ import { t as QuotaCounter } from "./map-CCbSZIhT.js";
2
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/logger/engine.d.ts
2
3
  interface ChannelLogger {
3
4
  error(message: string, data?: unknown): void;
4
5
  warn(message: string, data?: unknown): void;
@@ -8,7 +9,7 @@ interface ChannelLogger {
8
9
  }
9
10
  declare function createLogger(channel: string): ChannelLogger;
10
11
  //#endregion
11
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.14.2+49be191d46b46482/node_modules/@cortexkit/common-auth/dist/quota/projection.d.ts
12
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/quota/projection.d.ts
12
13
  interface ProjectedLimit {
13
14
  scope: string;
14
15
  label: string;
@@ -40,9 +41,10 @@ interface ProjectedQuota {
40
41
  checkedAt?: number;
41
42
  /** Present only when the stored budget is a reading, not cleared. */
42
43
  budget?: ProjectedBudget;
44
+ counters?: Record<string, QuotaCounter>;
43
45
  }
44
46
  //#endregion
45
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.14.2+49be191d46b46482/node_modules/@cortexkit/common-auth/dist/sidebar-file/sidebar-file.d.ts
47
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/sidebar-file/sidebar-file.d.ts
46
48
  interface SidebarFileHooks {
47
49
  /** Runs on the first merge attempt, before checking for older, unlocked writers. */
48
50
  beforeRecheck?: () => void | Promise<void>;
@@ -1,2 +1,2 @@
1
- import { $ as resolveSessionSidebarRouting, A as clearSidebarStickyAssignment, B as getSidebarStateFile, C as StickyAssignment, D as StickyPinOverlay, E as StickyAssignmentPlan, F as exhaustedQuotaResetAt, G as persistSidebarStickyAssignment, H as isQuotaExhausted, I as formatWindowLabel, J as pruneActiveRouting, K as planSidebarStickyAssignment, L as getCollapsedQuotaSummary, M as createSidebarBookkeepingQueue, N as createSidebarStateCache, O as StickyPinOverlayEntry, P as drainSidebarWrites, Q as resolveActiveAccount, R as getPresentQuotaWindows, S as SpendControlReading, T as StickyAssignmentMap, U as isUsableRoutingEntry, V as hashSidebarSessionId, W as normalizeSidebarState, X as rememberStickyPin, Y as pruneStickyAssignments, Z as removeSidebarActiveRouting, _ as SidebarMachineState, a as ActiveRoutingMap, at as setSidebarState, b as SidebarState, c as PresentQuotaWindow, ct as spendControlExhaustedResetAt, d as QuotaWindowKey, et as resolveSessionStickyAccount, f as ResolveStickyAssignmentInput, g as SidebarBookkeepingQueue, h as SidebarAccountState, i as ActiveRoutingEntry, it as setSidebarMachineState, j as computeQuotaPacing, k as applyStickyPinOverlay, l as QuotaPacing, lt as upsertSidebarActiveRouting, m as STICKY_ASSIGNMENT_MAX_ENTRIES, n as ACTIVE_ROUTING_MAX_ENTRIES, nt as setLegacySidebarStateFileForTest, o as DEFAULT_SIDEBAR_STATE, ot as settleWithinBudget, p as STICKY_ASSIGNMENT_MAX_AGE_MS, q as planSidebarStickyAssignmentFromSnapshot, r as AccountQuota, rt as setSidebarLegacyRouting, s as HOT_PATH_READ_BUDGET_MS, st as sidebarQuotaProjection, t as ACTIVE_ROUTING_MAX_AGE_MS, tt as resolveSidebarStickyAssignment, u as QuotaWindow, v as SidebarRoutingAccount, w as StickyAssignmentChoice, x as SidebarStateCache, y as SidebarSnapshot, z as getSidebarState } from "./sidebar-state-D6cUKgkm.js";
1
+ import { $ as resolveSessionSidebarRouting, A as clearSidebarStickyAssignment, B as getSidebarStateFile, C as StickyAssignment, D as StickyPinOverlay, E as StickyAssignmentPlan, F as exhaustedQuotaResetAt, G as persistSidebarStickyAssignment, H as isQuotaExhausted, I as formatWindowLabel, J as pruneActiveRouting, K as planSidebarStickyAssignment, L as getCollapsedQuotaSummary, M as createSidebarBookkeepingQueue, N as createSidebarStateCache, O as StickyPinOverlayEntry, P as drainSidebarWrites, Q as resolveActiveAccount, R as getPresentQuotaWindows, S as SpendControlReading, T as StickyAssignmentMap, U as isUsableRoutingEntry, V as hashSidebarSessionId, W as normalizeSidebarState, X as rememberStickyPin, Y as pruneStickyAssignments, Z as removeSidebarActiveRouting, _ as SidebarMachineState, a as ActiveRoutingMap, at as setSidebarState, b as SidebarState, c as PresentQuotaWindow, ct as spendControlExhaustedResetAt, d as QuotaWindowKey, et as resolveSessionStickyAccount, f as ResolveStickyAssignmentInput, g as SidebarBookkeepingQueue, h as SidebarAccountState, i as ActiveRoutingEntry, it as setSidebarMachineState, j as computeQuotaPacing, k as applyStickyPinOverlay, l as QuotaPacing, lt as upsertSidebarActiveRouting, m as STICKY_ASSIGNMENT_MAX_ENTRIES, n as ACTIVE_ROUTING_MAX_ENTRIES, nt as setLegacySidebarStateFileForTest, o as DEFAULT_SIDEBAR_STATE, ot as settleWithinBudget, p as STICKY_ASSIGNMENT_MAX_AGE_MS, q as planSidebarStickyAssignmentFromSnapshot, r as AccountQuota, rt as setSidebarLegacyRouting, s as HOT_PATH_READ_BUDGET_MS, st as sidebarQuotaProjection, t as ACTIVE_ROUTING_MAX_AGE_MS, tt as resolveSidebarStickyAssignment, u as QuotaWindow, v as SidebarRoutingAccount, w as StickyAssignmentChoice, x as SidebarStateCache, y as SidebarSnapshot, z as getSidebarState } from "./sidebar-state-BCxFpH68.js";
2
2
  export { ACTIVE_ROUTING_MAX_AGE_MS, ACTIVE_ROUTING_MAX_ENTRIES, AccountQuota, ActiveRoutingEntry, ActiveRoutingMap, DEFAULT_SIDEBAR_STATE, HOT_PATH_READ_BUDGET_MS, PresentQuotaWindow, QuotaPacing, QuotaWindow, QuotaWindowKey, ResolveStickyAssignmentInput, STICKY_ASSIGNMENT_MAX_AGE_MS, STICKY_ASSIGNMENT_MAX_ENTRIES, SidebarAccountState, SidebarBookkeepingQueue, SidebarMachineState, SidebarRoutingAccount, SidebarSnapshot, SidebarState, SidebarStateCache, SpendControlReading, StickyAssignment, StickyAssignmentChoice, StickyAssignmentMap, StickyAssignmentPlan, StickyPinOverlay, StickyPinOverlayEntry, applyStickyPinOverlay, clearSidebarStickyAssignment, computeQuotaPacing, createSidebarBookkeepingQueue, createSidebarStateCache, drainSidebarWrites, exhaustedQuotaResetAt, formatWindowLabel, getCollapsedQuotaSummary, getPresentQuotaWindows, getSidebarState, getSidebarStateFile, hashSidebarSessionId, isQuotaExhausted, isUsableRoutingEntry, normalizeSidebarState, persistSidebarStickyAssignment, planSidebarStickyAssignment, planSidebarStickyAssignmentFromSnapshot, pruneActiveRouting, pruneStickyAssignments, rememberStickyPin, removeSidebarActiveRouting, resolveActiveAccount, resolveSessionSidebarRouting, resolveSessionStickyAccount, resolveSidebarStickyAssignment, setLegacySidebarStateFileForTest, setSidebarLegacyRouting, setSidebarMachineState, setSidebarState, settleWithinBudget, sidebarQuotaProjection, spendControlExhaustedResetAt, upsertSidebarActiveRouting };
@@ -1 +1 @@
1
- import{$a as e,Ab as F,Bb as G,Cb as H,Db as I,Eb as J,Fb as K,Gb as L,Hb as M,Ib as N,Jb as O,Xa as a,Ya as b,Za as c,_a as d,ab as f,bb as g,cb as h,db as i,eb as j,fb as k,gb as l,hb as m,ib as n,jb as o,kb as p,lb as q,mb as r,nb as s,ob as t,pb as u,qb as v,rb as w,sb as x,tb as y,ub as z,vb as A,wb as B,xb as C,yb as D,zb as E}from"./index-eqh53k8v.js";import"./index-jyr8y8k4.js";import"./index-bmd7x5aq.js";import"./index-b3q3j39x.js";export{w as upsertSidebarActiveRouting,n as spendControlExhaustedResetAt,M as sidebarQuotaProjection,G as settleWithinBudget,u as setSidebarState,v as setSidebarMachineState,x as setSidebarLegacyRouting,c as setLegacySidebarStateFileForTest,A as resolveSidebarStickyAssignment,q as resolveSessionStickyAccount,r as resolveSessionSidebarRouting,L as resolveActiveAccount,y as removeSidebarActiveRouting,I as rememberStickyPin,t as pruneStickyAssignments,s as pruneActiveRouting,B as planSidebarStickyAssignmentFromSnapshot,z as planSidebarStickyAssignment,C as persistSidebarStickyAssignment,i as normalizeSidebarState,m as isUsableRoutingEntry,p as isQuotaExhausted,f as hashSidebarSessionId,g as getSidebarStateFile,j as getSidebarState,b as getPresentQuotaWindows,N as getCollapsedQuotaSummary,a as formatWindowLabel,o as exhaustedQuotaResetAt,E as drainSidebarWrites,H as createSidebarStateCache,K as createSidebarBookkeepingQueue,O as computeQuotaPacing,D as clearSidebarStickyAssignment,J as applyStickyPinOverlay,e as STICKY_ASSIGNMENT_MAX_ENTRIES,d as STICKY_ASSIGNMENT_MAX_AGE_MS,F as HOT_PATH_READ_BUDGET_MS,h as DEFAULT_SIDEBAR_STATE,l as ACTIVE_ROUTING_MAX_ENTRIES,k as ACTIVE_ROUTING_MAX_AGE_MS};
1
+ import{$c as E,Ac as d,Bc as e,Cc as f,Dc as g,Ec as h,Fc as i,Gc as j,Hc as k,Ic as l,Jc as m,Kc as n,Lc as o,Mc as p,Nc as q,Oc as r,Pc as s,Qc as t,Rc as u,Sc as v,Tc as w,Uc as x,Vc as y,Wc as z,Xc as A,Yc as B,Zc as C,_c as D,ad as F,bd as G,cd as H,dd as I,ed as J,fd as K,gd as L,hd as M,id as N,jd as O,xc as a,yc as b,zc as c}from"./index-9reyazwh.js";import"./index-yf6arn5w.js";import"./index-2hch7e8n.js";import"./index-k4eacw7x.js";import"./index-dryydk6b.js";import"./index-bgq9d21h.js";export{w as upsertSidebarActiveRouting,n as spendControlExhaustedResetAt,M as sidebarQuotaProjection,G as settleWithinBudget,u as setSidebarState,v as setSidebarMachineState,x as setSidebarLegacyRouting,c as setLegacySidebarStateFileForTest,A as resolveSidebarStickyAssignment,q as resolveSessionStickyAccount,r as resolveSessionSidebarRouting,L as resolveActiveAccount,y as removeSidebarActiveRouting,I as rememberStickyPin,t as pruneStickyAssignments,s as pruneActiveRouting,B as planSidebarStickyAssignmentFromSnapshot,z as planSidebarStickyAssignment,C as persistSidebarStickyAssignment,i as normalizeSidebarState,m as isUsableRoutingEntry,p as isQuotaExhausted,f as hashSidebarSessionId,g as getSidebarStateFile,j as getSidebarState,b as getPresentQuotaWindows,N as getCollapsedQuotaSummary,a as formatWindowLabel,o as exhaustedQuotaResetAt,E as drainSidebarWrites,H as createSidebarStateCache,K as createSidebarBookkeepingQueue,O as computeQuotaPacing,D as clearSidebarStickyAssignment,J as applyStickyPinOverlay,e as STICKY_ASSIGNMENT_MAX_ENTRIES,d as STICKY_ASSIGNMENT_MAX_AGE_MS,F as HOT_PATH_READ_BUDGET_MS,h as DEFAULT_SIDEBAR_STATE,l as ACTIVE_ROUTING_MAX_ENTRIES,k as ACTIVE_ROUTING_MAX_AGE_MS};
@@ -0,0 +1 @@
1
+ import{b as a}from"./index-yeyp8t0k.js";import"./index-bgq9d21h.js";export default a();
@@ -1 +1 @@
1
- import{a as U,b as V}from"./index-hy9030jh.js";import{tc as R}from"./index-b3q3j39x.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
+ import{a as U,b as V}from"./index-yeyp8t0k.js";import{qe as R}from"./index-bgq9d21h.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();
@@ -38,4 +38,5 @@ export declare function computeEffectiveOrder(root: Record<string, unknown>, plu
38
38
  type JsonValue = string | number | boolean | null;
39
39
  export declare function queueTuiPreferenceUpdate(pluginKey: string, path: string[], value: JsonValue): Promise<void>;
40
40
  export declare function watchTuiPreferences(onChange: () => void): () => void;
41
- //#endregion
41
+ //#endregion
42
+ export {};
@@ -1,9 +1,9 @@
1
- import{Lb as p,Rb as l,Sb as m}from"./index-jyr8y8k4.js";import{sc as Hz,tc as zz,vc as y}from"./index-b3q3j39x.js";var x=zz((c,b)=>{(function(Q){if(typeof b==="object"&&typeof b.exports==="object"){var H=Q(y,c);if(H!==void 0)b.exports=H}else if(typeof define==="function"&&define.amd)define(["require","exports","./impl/format","./impl/edit","./impl/scanner","./impl/parser"],Q)})(function(Q,H){Object.defineProperty(H,"__esModule",{value:!0}),H.applyEdits=H.modify=H.format=H.printParseErrorCode=H.ParseErrorCode=H.stripComments=H.visit=H.getNodeValue=H.getNodePath=H.findNodeAtOffset=H.findNodeAtLocation=H.parseTree=H.parse=H.getLocation=H.SyntaxKind=H.ScanError=H.createScanner=void 0;let X=Q("./impl/format"),Z=Q("./impl/edit"),G=Q("./impl/scanner"),$=Q("./impl/parser");H.createScanner=G.createScanner;var B;(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"})(B||(H.ScanError=B={}));var D;(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"})(D||(H.SyntaxKind=D={})),H.getLocation=$.getLocation,H.parse=$.parse,H.parseTree=$.parseTree,H.findNodeAtLocation=$.findNodeAtLocation,H.findNodeAtOffset=$.findNodeAtOffset,H.getNodePath=$.getNodePath,H.getNodeValue=$.getNodeValue,H.visit=$.visit,H.stripComments=$.stripComments;var M;(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"})(M||(H.ParseErrorCode=M={}));function R(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>"}H.printParseErrorCode=R;function W(z,N,V){return X.format(z,N,V)}H.format=W;function J(z,N,V,U){return Z.setProperty(z,N,V,U)}H.modify=J;function Y(z,N){let V=N.slice(0).sort((I,j)=>{let T=I.offset-j.offset;if(T===0)return I.length-j.length;return T}),U=z.length;for(let I=V.length-1;I>=0;I--){let j=V[I];if(j.offset+j.length<=U)z=Z.applyEdit(z,j);else throw Error("Overlapping edit");U=j.offset}return z}H.applyEdits=Y})});import{mkdir as Dz,writeFile as Uz}from"node:fs/promises";import{homedir as Iz}from"node:os";import{dirname as jz,join as h}from"node:path";var F=Hz(x(),1);import{readFile as d}from"node:fs/promises";function Qz(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}async function K(Q){try{let H=[],X=F.parse(await d(Q,"utf8"),H,{allowTrailingComma:!0});return H.length===0&&Qz(X)?X:{}}catch{return{}}}var Xz=`// Shared preferences for TUI plugins.
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.
2
2
  // Plugins update individual keys in place and preserve comments.
3
3
  {}
4
- `;function P(Q){let{file:H,pluginKey:X,beforeCommit:Z}=Q,G={...m.preferences,timeoutMs:Q.timeoutMs??m.preferences.timeoutMs},$=Promise.resolve();async function B(D,M){await l(H,G,async(R)=>{let W;try{W=await d(H,"utf8")}catch(Y){if(Y.code!=="ENOENT")throw Y;W=""}if(W.trim()==="")W=Xz;let J=F.applyEdits(W,F.modify(W,[X,...D],M,{formattingOptions:{insertSpaces:!0,tabSize:2}}));await p(H,J,{serialize:(Y)=>String(Y),beforeRename:async()=>{await Z?.(),await R.assertOwned()}})})}return{queueTuiPreferenceUpdate(D,M){let R=[...D],W=structuredClone(M),J=$.then(()=>B(R,W));return $=J.catch(()=>{}),J}}}import{readFileSync as Zz,realpathSync as $z,statSync as Bz,watch as Gz}from"node:fs";import{readFile as Jz,stat as Yz}from"node:fs/promises";import{basename as n,dirname as a,join as Vz,resolve as Wz}from"node:path";import{clearTimeout as f,setTimeout as s}from"node:timers";function t(Q){let H=Wz(Q);try{return $z(H)}catch{let X=a(H);return X===H?H:Vz(t(X),n(H))}}function i(Q){return Q&&`${Q.dev}:${Q.ino}:${Q.mtimeMs}:${Q.size}`}function C(Q,H,X={}){let Z=globalThis,G=Symbol.for("cortexkit.common-auth.tui-prefs.watchers.v1"),$=Z[G]??new Map;Z[G]=$;let B=t(Q),D=$.get(B);if(D)return D.subscribe(H);let M=n(B),R=X.fs?.readFile??((L)=>Jz(L,"utf8")),W=X.fs?.stat??Yz,J=null,Y=null,z=null,N=null;try{let L=i((X.fs?.statSync??Bz)(B));N=(X.fs?.readFileSync??((q)=>Zz(q,"utf8")))(B),z=L}catch{}let V=!1,U=new Set,I=Promise.resolve(),j=(L)=>{return I=I.then(async()=>{if(V)return;let q=i(await W(B).catch(()=>null));if(!L&&q===z)return;if(q===null){z=null;return}let O=await R(B).catch(()=>null);if(V)return;if(O===null)return;if(z=q,O===N)return;N=O;for(let g of[...U]){if(!U.has(g))continue;try{g.notify()}catch{}}}),I},T=()=>{if(V)return;if(J)f(J);J=s(()=>{J=null,j(!0)},150)},k=null;try{k=(X.watchDirectory??Gz)(a(B),(L,q)=>{let O=q?.toString(),g=O===M||O?.startsWith(`${M}.`)&&O.endsWith(".tmp");if(O!=null&&!g)return;T()}),k.on("error",()=>{k?.close(),k=null})}catch{}let E=()=>{if(V||Y)return;Y=s(()=>{if(Y=null,V)return;j(!1).finally(E)},1000),Y.unref()},v={subscribe:(L)=>{let q={notify:L};return U.add(q),()=>{if(!U.delete(q)||U.size>0)return;if(V=!0,J)f(J);if(Y)f(Y);if(k?.close(),$.get(B)===v)$.delete(B)}}};return $.set(B,v),E(),v.subscribe(H)}var qz="OPENCODE_TUI_PREFERENCES_FILE",Mz="tui-preferences.jsonc";function S(){let Q=process.env[qz];if(Q)return Q;let H=process.env.OPENCODE_CONFIG_DIR||h(process.env.XDG_CONFIG_HOME||h(Iz(),".config"),"opencode");return h(H,Mz)}function w(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function lz(){return K(S())}var Nz="openai-auth",Az=160,o={forceToTop:!1,order:Az,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 A(Q,H){return typeof Q==="boolean"?Q:H}function _(Q,H,X,Z){if(typeof Q!=="number"||!Number.isFinite(Q))return H;return Math.min(Math.max(Math.round(Q),X),Z)}function Lz(Q,H,X){if(typeof Q!=="string"||Q.length===0)return H;return Q.slice(0,X)}function e(Q,H){if(typeof Q!=="string")return H;return[...Q][0]??H}function dz(Q){let H=Q[Nz];if(!w(H))return structuredClone(o);let X=o,Z=w(H.header)?H.header:{},G=w(H.sections)?H.sections:{},$=w(H.appearance)?H.appearance:{},B=_($.warnThreshold,X.appearance.warnThreshold,0,99),D=Math.max(_($.errorThreshold,X.appearance.errorThreshold,0,100),Math.min(B+1,100));return{forceToTop:A(H.forceToTop,X.forceToTop),order:_(H.order,X.order,-1e4,1e4),startCollapsed:A(H.startCollapsed,X.startCollapsed),rememberCollapsed:A(H.rememberCollapsed,X.rememberCollapsed),collapsed:typeof H.collapsed==="boolean"?H.collapsed:null,pollMs:_(H.pollMs,X.pollMs,500,30000),refreshDebounceMs:_(H.refreshDebounceMs,X.refreshDebounceMs,50,5000),header:{label:Lz(Z.label,X.header.label,20),showVersion:A(Z.showVersion,X.header.showVersion)},sections:{quota:A(G.quota,X.sections.quota),fallbackAccounts:A(G.fallbackAccounts,X.sections.fallbackAccounts),routing:A(G.routing,X.sections.routing),health:A(G.health,X.sections.health),pacing:A(G.pacing,X.sections.pacing)},appearance:{barWidth:_($.barWidth,X.appearance.barWidth,4,40),barFilledChar:e($.barFilledChar,X.appearance.barFilledChar),barEmptyChar:e($.barEmptyChar,X.appearance.barEmptyChar),warnThreshold:B,errorThreshold:D}}}var Oz=-1e5;function sz(Q,H,X){let Z=Q[H];if(!w(Z))return X;if(Z.forceToTop===!0)return Oz+Object.keys(Q).indexOf(H);return _(Z.order,X,-1e4,1e4)}var Rz=`// Shared preferences for opencode TUI plugins.
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.
5
5
  // One top-level key per plugin (short name). See each plugin's README for
6
6
  // its supported settings. This file is safe to hand-edit; plugins update
7
7
  // individual keys in place and preserve comments.
8
8
  {}
9
- `,r=new Map;function _z(Q,H){let X=JSON.stringify([Q,H]),Z=r.get(X);if(!Z)Z=P({file:Q,pluginKey:H}),r.set(X,Z);return Z}async function Fz(Q){await Dz(jz(Q),{recursive:!0}),await Uz(Q,Rz,{encoding:"utf8",flag:"wx"}).catch(()=>{})}var u=Promise.resolve();function iz(Q,H,X){let Z=S(),G=_z(Z,Q);return u=u.then(()=>Fz(Z)).then(()=>G.queueTuiPreferenceUpdate(H,X)).catch(()=>{}),u}function nz(Q){return C(S(),Q)}export{nz as watchTuiPreferences,dz as resolveOpenaiAuthPrefs,lz as readTuiPreferencesFile,iz as queueTuiPreferenceUpdate,S as getTuiPreferencesFile,sz as computeEffectiveOrder,qz as TUI_PREFS_FILE_ENV,Nz as PLUGIN_KEY,Az as DEFAULT_SLOT_ORDER,o as DEFAULT_PREFS};
9
+ `,a=new Map;function Lq(z,q){let H=JSON.stringify([z,q]),Q=a.get(H);if(!Q)Q=g({file:z,pluginKey:q}),a.set(H,Q);return Q}async function Oq(z){await Yq(Dq(z),{recursive:!0}),await Vq(z,Kq,{encoding:"utf8",flag:"wx"}).catch(()=>{})}var y=Promise.resolve();function nq(z,q,H){let Q=m(),$=Lq(Q,z);return y=y.then(()=>Oq(Q)).then(()=>$.queueTuiPreferenceUpdate(q,H)).catch(()=>{}),y}function lq(z){return T(m(),z)}export{lq as watchTuiPreferences,pq as resolveOpenaiAuthPrefs,dq as readTuiPreferencesFile,nq as queueTuiPreferenceUpdate,m as getTuiPreferencesFile,sq as computeEffectiveOrder,Uq as TUI_PREFS_FILE_ENV,Mq as PLUGIN_KEY,Aq as DEFAULT_SLOT_ORDER,l as DEFAULT_PREFS};
package/dist/tui.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { t as ApplyRequest } from "./protocol-BOBdkqqm.js";
2
- import { S as SpendControlReading, b as SidebarState, l as QuotaPacing, r as AccountQuota, u as QuotaWindow } from "./sidebar-state-D6cUKgkm.js";
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";
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 { a as BeginAccountLoginOptions, f as AccountPaths, i as OpenAiVaultOptions, n as HostSlotAdapter, o as BeginAccountLoginResult, t as PoolLifecycleDeps } from "../pool-lifecycle-DbDmgabd.js";
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";
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,4 +1,3 @@
1
- import{$ as F1,A as N1,Aa as W$,B as D1,C as a1,D as o1,E as r1,F as t1,G as e1,Ga as t2,H as I2,Ha as e2,I as $$,J as A1,K as Y$,Ka as H$,L as Z$,M as K$,N as O1,O as x1,P as k2,Q as j2,R as U2,S as z$,T as X$,U as J$,V as j$,W as v2,X as Q$,Y as G$,Z as R2,_ as C1,aa as P1,ba as T1,c as h1,ca as M1,d as f1,da as L1,e as W2,ea as B$,f as H2,fa as V$,g as l1,ga as V2,h as p1,ha as _1,i as J1,j as j1,k as Q1,ka as w1,l as E1,la as I1,m as R1,n as c1,na as a2,o as d1,oa as o2,p as G1,pa as r2,q as i1,r as B1,s as V1,t as W1,u as H1,v as N2,w as n1,x as B2,y as s1,z as U1}from"../index-m9d2bfkn.js";import{Na as X1}from"../index-eqh53k8v.js";import"../index-jyr8y8k4.js";import"../index-rv08jmd4.js";import"../index-8kj7sa1p.js";import{gc as J2}from"../index-bmd7x5aq.js";import"../index-766sfrh5.js";import{wc as g1,xc as u1}from"../index-b3q3j39x.js";class d 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 i2($){let Z=s($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function z2($,Z){if($?.type!=="oauth")return!1;let X=Z===void 0?void 0:s(Z),z=(j)=>X===void 0?j.startsWith("common-auth-placeholder."):j===X;return z($.access)&&z($.refresh)}var n2="No browser sign-in: this connects the plugin to the accounts in its vault.";async function M2($,Z){let X=Z.now??Date.now,{integrationID:z}=Z,j=(P)=>i2({integrationID:z,methodID:P,now:X()}),B=async(P,A)=>{return await Z.onLogin(P,{integrationID:z,methodID:A}),j(A)},F=(P)=>async(A)=>{let H=P.method.id,W=await P.authorize(A),O={url:W.url,instructions:W.instructions,...W.expiresAt===void 0?{}:{expiresAt:W.expiresAt}};if(W.mode==="auto")return{...O,mode:"auto",callback:W.callback.then((x)=>B(x,H))};let w=W.callback;return{...O,mode:"code",callback:async(x)=>B(await w(x),H)}};return $.integration.transform((P)=>{let A=Z.label===void 0?{}:{label:()=>Z.label};for(let O of Z.methods)P.method.update({integrationID:z,method:O.method,authorize:F(O),refresh:async(w)=>{if(!z2(w,z))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return j(w.methodID)},...A});let H=Z.vault;if(H===void 0)return;let W=H.method.id;P.method.update({integrationID:z,method:H.method,authorize:async()=>({url:"",instructions:H.instructions??n2,mode:"auto",callback:Promise.resolve().then(()=>H.activate({integrationID:z,methodID:W})).then(()=>j(W))}),refresh:async(O)=>{if(!z2(O,z)||O.methodID!==W)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return j(W)},...A})})}function F$($){let Z=[],X;for(let z of $.split(/\r?\n/))if(z.startsWith("data:"))Z.push(z.slice(5).replace(/^ /,""));else if(z.startsWith("event:"))X=z.slice(6).trim();if(Z.length===0)return;return X===void 0?{data:Z.join(`
2
- `)}:{event:X,data:Z.join(`
3
- `)}}function L2($,Z){let X=new TextDecoder,z="",j=(F)=>{let P=F$(F);if(!P)return;try{$(P)}catch(A){Z(A)}},B=()=>{for(;;){let F=/\r?\n\r?\n/.exec(z);if(!F)return;let P=z.slice(0,F.index);z=z.slice(F.index+F[0].length),j(P)}};return new TransformStream({transform(F,P){P.enqueue(F),z+=X.decode(F,{stream:!0}),B()},flush(){if(z+=X.decode(),B(),z.trim()!=="")j(z);z=""}})}var s2=512,$2="x-common-auth-attempt",e=($,Z)=>JSON.stringify([$,Z]),a=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function P$($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function T$($,Z){let X=$.getReader();return new ReadableStream({async pull(z){let j;try{j=await X.read()}catch(B){Z({reason:"failed",message:B instanceof Error?B.message:String(B)}),z.error(B);return}if(j.done)Z(),z.close();else z.enqueue(j.value)},async cancel(z){Z({reason:"cancelled",...z===void 0?{}:{message:String(z)}}),await X.cancel(z)}})}function _2($,Z){for(let[X,z]of Object.entries(Z)){let j=X.toLowerCase();for(let B of Object.keys($))if(B.toLowerCase()===j)delete $[B];if(z!==null)$[X]=z}}function M$($,Z){for(let[X,z]of Object.entries(Z))if(z===null)$.delete(X);else $.set(X,z)}async function q2($,Z,X={}){let{providerID:z}=Z,j=X.gateOnPlaceholder,B=(Y)=>j===void 0||j.credential(Y)===s(z),F=X.logger,P=Math.max(1,X.maxRecords??s2),A=[...X.hostCredentials??[s(z)],...j?[s(z)]:[]].filter((Y)=>Y!==""),H=new Map,W=new WeakMap,O=new Map,w=new Set,x=new Map,b=!1,r=!1,c=new Map,v=0,u=!1,m=new Map,I=(Y,K)=>{try{F?.warn(Y,K)}catch{}},J=(Y)=>Y instanceof Error?Y.message:String(Y),V=async(Y,K)=>{let Q=c.get(Y);if(!Q||Q.size===0)return;await Promise.all([...Q].map(async(G)=>{try{await G(K)}catch(_){I("opencode2 auth listener threw; the request is unaffected",{event:Y,error:J(_)})}}))},M=async(Y,K)=>{try{await Z.onAttemptEnd?.(Y,K)}catch(Q){I("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:Y.attemptId,error:J(Q)})}},T=(Y,K)=>{if(Y.ended||!Y.attempt)return;let Q={...Y.status===void 0?{}:{status:Y.status},outputStarted:Y.outputStarted,...Y.limit?{limit:Y.limit.signal}:{},...K?{error:K}:{}};if(K)Y.endError=K;Y.ended=M(Y.attempt,Q)},R=(Y,K)=>T(Y,{reason:"abandoned",message:K}),L=(Y)=>[...H.values()].filter((K)=>K.key===Y),D=(Y)=>L(Y).at(-1),k=(Y)=>{if(H.delete(Y.id),!L(Y.key).length)O.delete(Y.key)},S=(Y)=>{H.set(Y.id,Y);while(H.size>P){let K=H.values().next().value;if(K===void 0)break;R(K,"dropped to keep the record bound"),k(K)}},g=(Y)=>Y.accountId===void 0?void 0:{...Y.scope,accountId:Y.accountId},p=(Y,K)=>new d({kind:"no-account",providerID:z,sessionID:Y.sessionID,requestKind:Y.kind,...K===void 0?{}:{message:K}}),l=(Y)=>{m.get(Y)?.clear(),m.delete(Y)},U=async(Y,K)=>{let Q=()=>p(Y,`${z} ${Y.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(u)throw Q();let G=m.get(Y.sessionID);if(!G)G=new Set,m.set(Y.sessionID,G);let _={};G.add(_);let E=()=>{if(!G.has(_))throw Q()};try{return await K(E)}finally{if(G.delete(_),G.size===0&&m.get(Y.sessionID)===G)m.delete(Y.sessionID)}},N=(Y,K)=>{for(let[Q,G]of K)if(A.some((_)=>G.includes(_)))throw new d({kind:"host-credential-on-wire",providerID:z,sessionID:Y.sessionID,requestKind:Y.kind,message:`${z} ${Y.kind} request still carries the host's placeholder credential in ${Q}; the adapter's account headers must replace it`})},h=(Y)=>{for(let K of L(Y))if(K.ended||!K.attempt)k(K);else if(K.transport==="ws"||K.judged)R(K,"a newer attempt of its session and kind began"),k(K)},f=async(Y,K,Q,G)=>{let _=e(Y.sessionID,Y.kind),E=O.get(_);O.delete(_);let C=E?.accountId??D(_)?.accountId;h(_);let q={...Y,...C===void 0?{}:{previousAccountId:C},...E?.rerouteFrom===void 0?{}:{rerouteFrom:E.rerouteFrom}},y=await Z.chooseAccount(q);Q();let n={},c2;if(y!==void 0){let Q2=await Z.accountHeaders({...Y,accountId:y});if(Q(),P$(Q2))n=Q2.headers,c2=Q2.attempt;else n=Q2}let d2=`attempt-${++v}`,K2={id:d2,key:_,scope:Y,accountId:y,headers:n,attempt:y===void 0?void 0:{...Y,accountId:y,attemptId:d2,transport:G,data:c2},...G===void 0?{}:{transport:G},outputStarted:!1};if(S(K2),K2.attempt)V("select",{...Y,accountId:K2.attempt.accountId,hook:K,...q.previousAccountId===void 0?{}:{previousAccountId:q.previousAccountId},...q.rerouteFrom===void 0?{}:{rerouteFrom:q.rerouteFrom},handle:K2.attempt});return K2},Z2=async(Y,K,Q,G,_)=>{let E=e(Y.sessionID,Y.kind),C=G===void 0?void 0:H.get(G);if(C?.key!==E)C=void 0;if(!C){if(C=D(E),L(E).filter((y)=>y.transport===void 0&&!y.ended).length>1&&!r)r=!0,I("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:Y.sessionID,kind:Y.kind})}if(!C||C.transport!==void 0||C.ended)C=await f(Y,K,_,Q);else if(C.transport=Q,C.attempt)C.attempt.transport=Q;if(Q==="ws"){for(let q of L(E))if(q!==C&&q.transport==="ws")R(q,"a newer attempt of its session and kind went out over WebSocket")}return C},F2=async(Y,K)=>{try{return await K()}catch(Q){throw T(Y,{reason:"failed",message:J(Q)}),Q}},f2=(Y,K)=>{let Q=L(e(Y,K)).filter((G)=>G.transport==="ws").at(-1);return Q?.attempt!==void 0&&!Q.ended?Q:void 0},P2=(Y,K,Q)=>{let G=g(Y);if(!G||!Y.attempt||Y.limit)return;Y.limit={signal:K,delivered:V("limit",{...G,via:Q,limit:K,outputStarted:Y.outputStarted,handle:Y.attempt})}},m2=(Y,K,Q,G)=>{let _=g(Y);if(!_||!Y.attempt)return;V("quota",{..._,transport:K,...G===void 0?{}:{status:G},quota:Q,handle:Y.attempt})},g2=(Y,K,Q,G)=>{let _=Y.attempt;if(!_)return;let E=Z.inspectEvent?.(G===void 0?{transport:K,data:Q,attempt:_}:{transport:K,data:Q,event:G,attempt:_});if(!E)return;if(E.quota!==void 0)m2(Y,K,E.quota);if(E.outputStarted)Y.outputStarted=!0;if(E.limit)P2(Y,E.limit,K);if(E.error!==void 0)T(Y,{reason:"failed",message:E.error});else if(E.done)T(Y)},U$=(Y,K)=>{let Q=Y.attempt;if(!Q||K.accountId===Y.accountId)return;if(Q.reboundFrom??=Q.accountId,Q.accountId=K.accountId,"data"in K)Q.data=K.data;Y.accountId=K.accountId},N$=(Y)=>!Y.attempt||Y.endError!==void 0||Y.status!==void 0&&Y.status>=400,C$=(Y)=>{let K=[...H.values()].filter((q)=>q.scope.sessionID===Y),Q=K.filter((q)=>q.limit&&!q.rerouted).at(-1);if(Q)return Q;let G=K.filter((q)=>q.scope.kind==="primary"),_=G.length>0?G:K;if(_.length<=1)return _[0];let E=_.filter((q)=>!q.judged&&N$(q)).at(-1);if(E)return E;let C=_.filter((q)=>q.attempt&&!q.ended);if(C.length>1)return"ambiguous";return C[0]??_.at(-1)},t={providerID:z},o=[];o.push(await $.session.hook("model.request",(Y)=>{if(j)return;return U(a(Y),async(K)=>{let Q=await f(a(Y),"model.request",K);if(K(),Q.accountId===void 0)throw p(Q.scope);_2(Y.headers,{...Q.headers,[$2]:Q.id})})},t)),o.push(await $.session.hook("http.request",(Y)=>{if(j){let K=B(Y.request.headers);if(x.set(Y.sessionID,K),!K)return}return U(a(Y),async(K)=>{let Q=Y.request.headers.get($2)??void 0,G=j?await f(a(Y),"http.request",K,"http"):await Z2(a(Y),"http.request","http",Q,K);K();let _=g(G),E=G.attempt;if(!_||!E)throw p(G.scope);await F2(G,async()=>{let C=Y.request;if(Z.rewriteRequest){if(Q!==void 0){let n=new Headers(C.headers);n.delete($2),C=new Request(C,{headers:n})}C=await Z.rewriteRequest({..._,request:C,attempt:E})??C,K()}let q=new Headers(C.headers);q.delete($2),M$(q,G.headers),N(G.scope,q.entries());let y=new Request(C,{headers:q});W.set(y,G),Y.request=y})})},t)),o.push(await $.session.hook("http.response",async(Y)=>{let K=W.get(Y.request);if(!K){if(j)return;if(!b)b=!0,I("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:Y.sessionID,kind:Y.kind});return}let Q=Y.response;if(Z.answeredBy&&K.attempt){let q=K.attempt,y=await F2(K,async()=>Z.answeredBy?.({request:Y.request,response:Q,attempt:q}));if(y)U$(K,y)}let G=g(K),_=K.attempt;if(!G||!_)return;K.status=Q.status;let E=Z.quotaFromHeaders?.(Q.headers,Q.status,_);if(E!==void 0)m2(K,"http",E,Q.status);if(!Q.ok&&Z.limitFromResponse){let q=await Z.limitFromResponse({status:Q.status,headers:Q.headers,body:()=>Q.clone().text(),attempt:_});if(q)P2(K,q,"http")}if(!Q.ok||!Q.body)T(K);let C=Q;if(Q.body&&(Z.inspectEvent||Z.onAttemptEnd)){let q=Q.body;if(Z.inspectEvent)q=q.pipeThrough(L2((y)=>g2(K,"http",y.data,y.event),(y)=>I("opencode2 auth event inspection threw",{error:J(y)})));C=new Response(T$(q,(y)=>T(K,y)),{status:Q.status,statusText:Q.statusText,headers:Q.headers})}if(Z.rewriteResponse)C=await Z.rewriteResponse({...G,request:Y.request,response:C,attempt:_})??C;if(C!==Q)Y.response=C},t)),o.push(await $.session.hook("experimental.ws.handshake",(Y)=>{if(j){let K=B(new Headers(Y.headers)),Q=e(Y.sessionID,Y.kind);if(x.set(Y.sessionID,K),w.delete(Q),!K)return}return U(a(Y),async(K)=>{let Q;for(let C of Object.keys(Y.headers)){if(C.toLowerCase()!==$2)continue;Q??=Y.headers[C],delete Y.headers[C]}let G=j?await f(a(Y),"experimental.ws.handshake",K,"ws"):await Z2(a(Y),"experimental.ws.handshake","ws",Q,K);K();let _=g(G),E=G.attempt;if(!_||!E)throw p(G.scope);await F2(G,async()=>{_2(Y.headers,G.headers);let C=Z.rewriteHandshakeURL?.({..._,url:Y.url,attempt:E});if(C!==void 0)Y.url=C;if(N(G.scope,Object.entries(Y.headers)),j)w.add(G.key)})})},t));let u2=Z.rewriteWebSocketFrame?.bind(Z);if(u2)o.push(await $.session.hook("experimental.ws.send",async(Y)=>{let K=a(Y);if(j&&!w.has(e(K.sessionID,K.kind)))return;let Q=f2(K.sessionID,K.kind),G=await u2({...K,attempt:Q?.attempt,frame:Y.frame});if(G!==void 0)Y.frame=G},t));o.push(await $.session.hook("experimental.ws.receive",(Y)=>{if(j&&!w.has(e(Y.sessionID,Y.kind)))return;let K=f2(Y.sessionID,Y.kind);if(!K)return;try{g2(K,"ws",Y.frame)}catch(Q){I("opencode2 auth frame inspection threw",{error:J(Q)})}},t)),o.push(await $.session.hook("retry",async(Y)=>{if(j&&x.get(Y.sessionID)!==!0)return;let K=C$(Y.sessionID);if(!K)return;let Q=Y.decision;if(K==="ambiguous"){await V("retry",{sessionID:Y.sessionID,attempt:Y.attempt,reason:"host-decides",hostDecision:Q,decision:Q});return}let G=K;await U(G.scope,async(_)=>{G.judged=!0;let E=Q,C,q,y=G.attempt;if(G.accountId===void 0||!y)E={retry:!1},C="no-account";else if(G.outputStarted)E={retry:!1},C="output-started";else{if(!G.limit){let n=Z.limitFromError?.(Y.error,y);if(n)P2(G,n,"error")}if(G.ended)await G.ended,_();if(G.limit)await G.limit.delivered,_(),G.rerouted=!0,q={accountId:G.accountId,limit:G.limit.signal},E={retry:!0,delay:0},C="reroute";else C="host-decides"}if(Y.decision=E,E.retry&&G.accountId!==void 0)O.set(G.key,{sessionID:G.scope.sessionID,accountId:G.accountId,...q===void 0?{}:{rerouteFrom:q}});await V("retry",{sessionID:Y.sessionID,...G.accountId===void 0?{}:{accountId:G.accountId},kind:G.scope.kind,attempt:Y.attempt,reason:C,hostDecision:Q,decision:E,...y===void 0?{}:{handle:y}})})},t));let l2=(Y)=>{l(Y),x.delete(Y);for(let K of w)if(JSON.parse(K)[0]===Y)w.delete(K);for(let K of[...H.values()]){if(K.scope.sessionID!==Y)continue;R(K,"its session was forgotten"),H.delete(K.id)}for(let[K,Q]of O)if(Q.sessionID===Y)O.delete(K)},T2=new AbortController,p2=$.event;if(p2)(async()=>{try{for await(let Y of p2.subscribe({signal:T2.signal}))if(Y.type==="session.deleted")l2(Y.data.sessionID)}catch(Y){if(!T2.signal.aborted)I("opencode2 auth stopped listening for session deletion",{error:J(Y)})}})();return{on(Y,K){let Q=c.get(Y);if(!Q)Q=new Set,c.set(Y,Q);let G=K;return Q.add(G),()=>{Q.delete(G)}},accountFor(Y,K){return D(e(Y,K))?.accountId},forgetSession:l2,get size(){return H.size},async dispose(){if(u)return;u=!0;for(let Y of m.keys())l(Y);T2.abort();for(let Y of H.values())R(Y,"the installation was disposed");H.clear(),O.clear(),w.clear(),x.clear(),c.clear(),await Promise.all(o.map(async(Y)=>{try{await Y.dispose()}catch(K){I("opencode2 auth hook did not dispose cleanly",{error:J(K)})}}))}}}var x2={version:o2,"user-agent":r2,originator:"codex_exec"},L$="x-openai-internal-codex-responses-lite",_$=1024,q$=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,G2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),x$=($)=>G2($)&&($.type==="message"||("role"in $))&&$.role==="user",S$=($)=>G2($)&&$.type==="configuration_update";class S2{#$=new Map;apply($,Z,X){if(Z.kind!=="primary")return!1;let z=typeof $.model==="string"?$.model:"";if(!t2.has(z))return!1;if(q$.test(z))return!1;let j=G2($.reasoning)?$.reasoning:void 0,B=typeof j?.effort==="string"?j.effort:void 0;if(!B)return!1;let F=this.#$.get(Z.sessionID);if(F===void 0)return this.#Y(Z.sessionID,B),!1;if(B===F)return!1;let P=Array.isArray($.input)?$.input:void 0;if(!P||P.length===0)return!1;let A=P.findLastIndex(x$);if(A<0){if(X==="http")return!1;return $.reasoning={...j,effort:F},!0}if($.reasoning={...j,effort:F},!S$(P[A-1]))P.splice(A,0,{type:"configuration_update",reasoning:{effort:B}});return!0}forget($){this.#$.delete($)}#Y($,Z){this.#$.set($,Z);while(this.#$.size>_$){let X=this.#$.keys().next().value;if(X===void 0)break;this.#$.delete(X)}}}function E$($){if(typeof $.model!=="string"||!a2.has($.model))return!1;return e2($),!0}function $1($){try{let Z=JSON.parse($);return G2(Z)?Z:void 0}catch{return}}async function Y1($,Z,X,z){if($.method.toUpperCase()!=="POST"||$.body===null)return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let j=$1(await $.clone().text());if(!j)return;let B="max_output_tokens"in j;delete j.max_output_tokens;let F=X.apply(j,Z,"http"),P=z&&E$(j);if(!B&&!F&&!P)return;let A=new Headers($.headers);if(A.delete("content-length"),P)A.set(L$,"true");return new Request($,{headers:A,body:JSON.stringify(j)})}function Z1($,Z,X){let z=$1($);if(z?.type!=="response.create")return;let j="max_output_tokens"in z;delete z.max_output_tokens;let B=X.apply(z,Z,"ws");return j||B?JSON.stringify(z):void 0}function R$($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function E2($,Z){let X=new URL($);if(X.origin!=="https://api.openai.com"&&X.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(X.pathname))return $;let z=new URL(`${R$(Z)}/responses`);if(z.search=X.search,X.protocol==="ws:"||X.protocol==="wss:")z.protocol=z.protocol==="https:"?"wss:":"ws:";return z.href}var i="openai",D$=60000,K1=1,A$="request refused: no account with a usable credential",O$=1024,Y2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function D2($){try{return JSON.parse($)}catch{return}}function z1($){let Z=W2($);return Z?H2(Z):void 0}var b$=new Set(["usage_limit_reached","rate_limit_exceeded"]);function A2($,Z,X){return{reason:$.window,...X!==void 0?{status:X}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function k$($,Z){let X=V2($);if(X){let B=typeof $.status==="number"?$.status:void 0;return A2(X,Z,B)}if($.type!=="response.failed"||!Y2($.response))return;let z=$.response.failed;if(Y2(z)&&typeof z.rate_limit_reached_type==="string")return{reason:z.rate_limit_reached_type};let j=$.response.error;if(Y2(j)){let B=typeof j.code==="string"?j.code:typeof j.type==="string"?j.type:void 0;if(B&&b$.has(B))return{reason:B}}return}function y$($,Z){let X=D2($);if(!Y2(X))return;let z=typeof X.type==="string"?X.type:void 0;if(z==="codex.rate_limits")return{quota:{snapshot:Q1(X),complete:!0}};let j=k$(X,Z);if(j)return{limit:j};if(z===void 0||z==="error")return;return _1(z)?void 0:{outputStarted:!0}}function w$($){let Z=!1;for(let X of $.keys())if(X.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:J1($),complete:j1($)}}function I$($){let Z=$.get("retry-after");if(Z===null)return;let X=Number(Z);return Number.isFinite(X)&&X>=0?X*1000:void 0}function q1($){let{source:Z,pins:X}=$,z=$.now??Date.now,j=$.log,B=$.vault,F=new S2,P=new Map,A=(J)=>`${J.sessionID}\x00${J.kind}\x00${J.accountId}`,H=new Map,W=new Map,O=(J,V)=>{W.delete(J),W.set(J,V);while(W.size>O$){let M=W.keys().next().value;if(M===void 0)break;W.delete(M)}},w=(J,V,M)=>{let T=M?[]:L1(Z.peek().rows,J,V,B?.identities()??new Set),R=(B?.routes()??[]).filter((L)=>L.kind==="oauth"&&B1(B2(L.quota),J,V));return[...T.map((L)=>({id:L.id,...L.identity!==void 0?{identity:L.identity}:{},quota:L.quota,row:L})),...R.map((L)=>({id:L.id,...L.identity!==void 0?{identity:L.identity}:{},quota:L.quota}))]},x=(J,V,M)=>{let T=new Map;if(V1(V))for(let S of J)T.set(S.id,H1(B2(S.quota),V,S.id===R2?void 0:S.id,M));let R=J.map((S)=>({id:S.id,kind:"oauth",...X1(S.quota)?{quota:S.quota}:{}})),L=J.flatMap((S)=>S.row?[S.row]:[]),D=new Set(J.filter((S)=>!S.row).map((S)=>S.id)),k=Z.rateLimitMarks(L);for(let S of D){let g=H.get(S);if(g===void 0)continue;if(g<=M)H.delete(S);else k.set(S,g)}return{rows:R,now:M,rateLimitMarks:k,refreshBackoff:Z.refreshBackoffFor(L),killswitch:T,requestPull:(S)=>D.has(S)?B?.requestReading(S):Z.requestReading(S)}},b=(J,V,M,T)=>{let R=F1({...J,placement:C1(V)});if(R.kind==="block"){j?.debug("pool admission refused the request",{reason:R.block.reason});return}let L=R.order.filter((D)=>!M.has(D));if(T!==void 0&&L.includes(T))return T;return L[0]},r=(J,V,M,T,R,L)=>{let D={requestBytes:K1,reservePercent:(N)=>W1(M,N===R2?void 0:N),resetCredits:()=>{return}},k=P1(J),S=(N,h)=>X.place({sessionId:T,requestBytes:K1,validPinnedAccountIds:J.rows.map((f)=>f.id).filter((f)=>!k.excluded.has(f)),excludeAccountIds:N,quotaCheckedAtByAccount:Object.fromEntries(J.rows.map((f)=>[f.id,k.projections.get(f.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(V.map((f)=>[f.id,f.identity])),select:(f)=>T1(J,D,new Set(N),f),persist:h}),g=[...R],p=S(g,L);if(!p)return;let l=p.accountId,U=M1(J,D,l);if(U.kind==="none")return;if(U.kind==="move"){let N=S([...g,l],L);if(N)return N.accountId;return U.reason==="killswitch"?void 0:l}if(U.kind==="detour")return S([...g,l],!1)?.accountId;return l},u={providerID:i,chooseAccount:async(J)=>{let V=await B?.authority(),M=await $.storage(),T=V!==void 0&&V!=="local",R=()=>{throw new d({kind:"no-account",providerID:i,sessionID:J.sessionID,requestKind:J.kind,message:U2})};if(T)await $.awaitVaultRoster?.();else{if(!(await Z.current()).active){if(await $.slotPlaceholderWithoutMain?.())R();j?.warn("the account pool does not serve requests yet; refusing the request",{kind:J.kind});return}await Z.prepareTokens(Z.peek().rows,M)}let L=z(),D=w(M,L,T),k=new Map(D.map((h)=>[h.id,h])),S=x(D,M,L),g=new Set(J.rerouteFrom?[J.rerouteFrom.accountId]:[]),p=M?.routing?.mode??"main-first",l=J.kind==="primary",U=new Set,N;for(;;){let h=new Set([...g,...U]);if(N=void 0,p==="sticky-balanced")N=r(S,D,M,J.sessionID,h,l&&U.size===0);if(N??=b(S,p,h,l?void 0:W.get(J.sessionID)),N===void 0||U.has(N)){N=void 0;break}let f=k.get(N)?.row;if(f){if(Z.usableToken(f)!==void 0)break;j?.debug("pool row holds no usable token; choosing again",{accountId:N})}else{if(!B)break;let Z2=await B.authorize(N);if(Z2){P.set(A({...J,accountId:N}),Z2);break}j?.debug("the vault refused to serve an account; choosing again",{accountId:N})}U.add(N)}if(N===void 0&&!T&&D.length===0&&await $.slotPlaceholderWithoutMain?.())R();if(N===void 0&&T&&B&&(D.length===0||U.size>0)){let h=U.size>0?"vault-refused":N1(B);throw j?.warn("vault mode: no vault account can serve; refusing the request",{cause:h}),new d({kind:"no-account",providerID:i,sessionID:J.sessionID,requestKind:J.kind,message:U1[h]})}if(N!==void 0&&l)O(J.sessionID,N);return j?.debug("pool account chosen",{kind:J.kind,accountId:N,mode:p,...J.rerouteFrom?{rerouteFrom:J.rerouteFrom.accountId}:{}}),N},accountHeaders:async(J)=>{let{accountId:V}=J,M=()=>new d({kind:"no-account",providerID:i,sessionID:J.sessionID,requestKind:J.kind,message:A$}),T=B&&await B.authority()!=="local"?void 0:Z.peek().rows.find((D)=>D.id===V);if(!T&&B){let D=A(J),k=P.get(D)??await B.authorize(V);if(P.delete(D),!k)throw j?.warn("the vault refused to serve an account; refusing the request",{accountId:V}),M();return{headers:{...x2,"session-id":J.sessionID,authorization:`Bearer ${k.accessToken}`,"chatgpt-account-id":k.accountIdentity??z1(k.accessToken)??null},attempt:{kind:"vault",routeId:V,receipt:k}}}let R=T?Z.usableToken(T):void 0;if(!T||!R)throw j?.warn("pool row holds no usable token; refusing the request",{accountId:V}),M();let L=T.identity??z1(R);return{headers:{...x2,"session-id":J.sessionID,authorization:`Bearer ${R}`,"chatgpt-account-id":L??null},attempt:{kind:"pool",token:R,credentialEpoch:T.credentialEpoch}}},async rewriteRequest({request:J,sessionID:V,kind:M}){let T=$.codexEndpoint?E2(J.url,$.codexEndpoint()):J.url,R=T===J.url?J:new Request(T,J);return await Y1(R,{sessionID:V,kind:M},F,$.responsesLite?.()??!1)??R},rewriteHandshakeURL:({url:J})=>$.codexEndpoint?E2(J,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:J,sessionID:V,kind:M})=>Z1(J,{sessionID:V,kind:M},F),quotaFromHeaders:(J)=>w$(J),async limitFromResponse({status:J,headers:V,body:M}){if(J<400)return;let T=D2(await M().catch(()=>"")),R=V2({...Y2(T)?T:{},status:J});if(!R)return;let L=z(),D=A2(R,L,J);if(D.retryAfterMs!==void 0)return D;let k=I$(V);return k===void 0?D:{...D,retryAfterMs:k}},inspectEvent:({data:J})=>y$(J,z()),limitFromError(J){let V=D2(J.message),M=V2({...Y2(V)?V:{},...J.status!==void 0?{status:J.status}:{}})??(J.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return M?A2(M,z(),J.status):void 0},async onAttemptEnd(J,V){let M=J.data;if(M?.kind!=="vault"||V.status!==401)return;j?.warn("a vault account answered 401; reporting it to the vault",{accountId:J.accountId}),await B?.reportFailure(M.receipt,401)}},m=(J,V,M)=>{let T=M.data;if(T?.kind==="vault"){B?.recordSnapshot(J,V.snapshot,V.complete,T.receipt);return}if(T?.kind!=="pool")return;if(Z.peek().rows.find((L)=>L.id===J)?.credentialEpoch!==T.credentialEpoch){j?.debug("quota reading dropped: the row holds another credential",{accountId:J});return}Z.recordSnapshot(J,V.snapshot,T.token,V.complete)},I=(J,V,M)=>{let T=z(),R=M.data?.kind==="vault",L=R?B?.routes().find((S)=>S.id===J)?.quota:Z.peek().rows.find((S)=>S.id===J)?.quota,D=G1(B2(L),V.reason,T,D$,V.retryAfterMs!==void 0?T+V.retryAfterMs:void 0);if(!R){Z.markRateLimited(J,D);return}let k=H.get(J);if(k===void 0||k<D)H.set(J,D)};return{adapter:u,attach(J){J.on("quota",(V)=>m(V.accountId,V.quota,V.handle)),J.on("limit",(V)=>{I(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(J){X.forget(J),W.delete(J),F.forget(J)}}}import{randomUUID as v$}from"node:crypto";import{chmod as h$,mkdir as f$,readFile as m$,rename as g$,rm as u$,stat as l$,writeFile as p$}from"node:fs/promises";import{dirname as c$,resolve as d$}from"node:path";var i$="(no OpenCode 1 logins on this machine)";function n$($=process.env){return x1($)}async function O2($){let Z;try{Z=await m$($,"utf8")}catch(z){if(z.code==="ENOENT")return;throw z}let X=JSON.parse(Z);if(!X||typeof X!=="object"||Array.isArray(X))throw Error(`${$} does not hold a JSON object`);return X}function b2($){return $===void 0?void 0:JSON.stringify($)}async function s$($){try{return(await l$($)).mode&511}catch(Z){if(Z.code==="ENOENT")return;throw Z}}function S1($=n$()){let Z=new Map;return{path:d$($),async get(X){let z=(await O2($))?.[X.path.id];return Z.set(X.path.id,b2(z)),z},async set(X){let z=X.path.id,j=await s$($),B=await O2($)??{};if(!Z.has(z)||Z.get(z)!==b2(B[z]))throw new k2;B[z]=X.body,await f$(c$($),{recursive:!0});let F=`${$}.${v$()}.tmp`;try{await p$(F,`${JSON.stringify(B,null,2)}
4
- `,{mode:j??384}),await h$(F,j??384),await g$(F,$)}catch(P){throw await u$(F,{force:!0}).catch(()=>{}),P}return Z.set(z,b2(X.body)),!0},async all(){let X=await O2($);if(!X||Object.keys(X).length===0)return{[i$]:!0};return X}}}var a$="openai-auth-pool-browser",o$="openai-auth-pool-headless",r$="openai-auth-vault",t$="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 b1($){return{method:{id:r$,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await E1($.paths,$.name)!=="vault")throw Error(t$)}}}function k1($){let Z=(X,z,j)=>({method:{id:X,type:"oauth",label:z},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[Z(a$,"ChatGPT (openai-auth pool, browser)",!1),Z(o$,"ChatGPT (openai-auth pool, headless)",!0)]}function y2($){let Z=(X)=>typeof X==="string"?X:"";return z2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===A1||R1($)}function e$($){if($.accountId)return $.accountId;let Z=$.access?W2($.access):void 0;return Z?H2(Z):void 0}async function y1($,Z,X,z={}){if(z.vault)await X2(z.vault);if(y2(X))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let j=D1($,{rowLocks:(x)=>O1(Z,x)}),B=await j.read();if(B.status!=="ready")throw Error(`the account pool cannot be read (${B.status}); the login was not stored`);let F={type:"oauth",refresh:X.refresh,...X.access!==void 0?{access:X.access}:{},...X.expires!==void 0?{expires:X.expires}:{}},P=e$(X);if(z.vault)await X2(z.vault);let A=P!==void 0?{identity:P}:{};if(z.origin==="import"){let x=B.rows.find((b)=>P!==void 0&&b.identity===P||b.credential?.type==="oauth"&&b.credential.refresh===X.refresh);if(x)return{id:x.id,operation:"kept"}}let H=B.rows.filter((x)=>x.type==="oauth"&&!x.invalid),W=P?H.find((x)=>x.identity===P):void 0,O=B.rows.find((x)=>x.id===N2);if(W)return{id:(await j.replace(W.id,F,A)).id,operation:"replaced"};if(!O){let x=await j.add({id:N2,credential:F,...A,...X.label!==void 0?{label:X.label}:{}});return{id:x.id,operation:x.outcome==="added-disabled"?"added-disabled":"added"}}if(!O.invalid&&!O.credential)return{id:(await j.replace(N2,F,A)).id,operation:"replaced"};let w=await j.add({id:X.id,credential:F,...A,...X.label!==void 0?{label:X.label}:{}});return{id:w.id,operation:w.outcome==="added-disabled"?"added-disabled":w.outcome==="rotated"?"replaced":"added"}}function $Y($){if(!w1($.modelID??$.id)){$.enabled=!1;return}let Z=I1($.id);if(Z)$.limit={...Z}}function v1($){return $.model.transform((Z)=>{for(let X of Z.list(i))Z.update(i,String(X.id),(z)=>$Y(z))})}var YY=1024;class w2{pins=new Map;limit;constructor($=YY){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.pins.delete($)}get size(){return this.pins.size}set($,Z){this.pins.delete($),this.pins.set($,Z);while(this.pins.size>this.limit){let X=this.pins.keys().next().value;if(X===void 0)break;this.pins.delete(X)}}place($){let Z=this.pins.get($.sessionId),X=new Set($.validPinnedAccountIds);if(Z&&!$.excludeAccountIds.includes(Z.accountId)&&h1(Z,X,$.wireAccountIdByAccount[Z.accountId])){if($.persist){let F=$.quotaCheckedAtByAccount[Z.accountId];this.set($.sessionId,{accountId:Z.accountId,inputBytes:$.requestBytes,...Z.wireIdentity!==void 0?{wireIdentity:Z.wireIdentity}:{},...F!==void 0?{quotaCheckedAt:F}:{}})}return{accountId:Z.accountId}}let z=new Map(Object.entries($.quotaCheckedAtByAccount)),j=f1(this.pins,z,$.sessionId),B=$.select(j);if(!B)return;if($.persist){let F=$.wireAccountIdByAccount[B.accountId];this.set($.sessionId,{accountId:B.accountId,inputBytes:$.requestBytes,...F!==void 0?{wireIdentity:F}:{},...B.quotaCheckedAt!==void 0?{quotaCheckedAt:B.quotaCheckedAt}:{}})}return{accountId:B.accountId}}}var C2="cortexkit-openai-auth",ZY=5000;async function m1($,Z,X){let z=new Map,j=new Map,B=(H)=>{j.delete(H);for(let W of z.keys())if(W.startsWith(`${H}:`))z.delete(W)},P=await q2({session:{hook:(H,W,O)=>$.session.hook(H,async(w)=>{let x=H==="http.request"?w:void 0,b=H==="experimental.ws.handshake"?w:void 0,c=(x?x.request.headers:b?new Headers(b.headers):void 0)?.get("authorization")===`Bearer ${s(Z.providerID)}`;try{await W(w)}catch(v){if(c&&!(v instanceof d))throw o1(v);throw v}if(x||b){let v=x??b;if(!v)return;let m=(x?x.request.headers:new Headers(v.headers)).get("authorization")?.replace(/^Bearer /,"");if(c&&m)j.set(v.sessionID,m);else j.delete(v.sessionID);if(b){let I=`${b.sessionID}:${b.kind}`;if(c&&m)z.set(I,m);else z.delete(I)}if(j.size>512){let I=j.keys().next().value;if(I)j.delete(I)}if(z.size>512){let I=z.keys().next().value;if(I)z.delete(I)}}else if(H==="experimental.ws.receive"){let v=w,u=z.get(`${v.sessionID}:${v.kind}`);if(u)v.frame=r1(v.frame,u)}else if(H==="retry"){let v=w,u=j.get(v.sessionID);if(u)Object.assign(v.error,{message:a1(v.error.message,u)})}},O)},event:{subscribe:(H)=>async function*(){for await(let W of $.event.subscribe(H)){if(W.type==="session.deleted")B(W.data.sessionID);yield W}}()}},{...Z,rewriteResponse:async(H)=>{let W=await Z.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)=>X.warn(H,{data:W})}}),A=P.dispose;return{...P,dispose:async()=>{j.clear(),z.clear(),await A()}}}function h2($={}){return{id:C2,setup:(Z)=>KY(Z,$)}}async function KY($,Z={}){let S=[];try{let X=J2("opencode2");let z=J2("quota");let j=Z.paths??(()=>$$(e1()));let B=Z.fetch??fetch;let F=Z.version??X$;let P=Z.poolMigration??W$;if(!P&&!j2(j().configPath)){X.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=(h)=>{throw new d({kind:"no-account",providerID:i,sessionID:h.sessionID,requestKind:h.kind,message:U2})},N=await m1($,{providerID:i,chooseAccount:U,accountHeaders:U},X);return()=>N.dispose()}let A=Z.vault?.firstRosterWaitMs??j$;let H=V$({host:"opencode",stateDir:Z.vault?.stateDir??s1(j().statePath),reservedRouteIds:()=>b.peek().rows.map((U)=>U.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>B},j());let W=H.vault;let O=!1;const w=g1(S,{[Symbol.dispose](){if(!O)H.release()}},0);await W.authority();let x=H.firstRoster;let b=new Q$({paths:j,refreshProvider:async(U)=>{let N=await c1({refreshToken:U.refresh,fetchImpl:B,now:Date.now}),h=l1({id_token:"",access_token:N.access,refresh_token:N.refresh});return{...N,...h?{identity:h}:{}}},pullQuota:async(U)=>{let N=U.credential;if(N.type!=="oauth"||!N.access)throw Error("the row holds no access token to poll with");let h=await d1({accessToken:N.access,fetchImpl:B,now:Date.now,...U.identity?{accountId:U.identity}:{},accountKey:U.id,logger:z});return n1(h,Date.now(),!0)},vaultIdentities:()=>W.identities(),vaultMode:()=>W.enrolled(),vaultAuthority:()=>W.authority(),vaultFirstRoster:x,vaultFirstRosterBackgroundWaitMs:A,log:J2("pool")});await b.load();let r=Z.heartbeat===!1?void 0:await B$({version:F,logger:J2("heartbeat")});let c=Z.fence??(()=>z$({currentVersion:F}));let v=Z.slot??S1();let u=async()=>Y$(j(),await v.get({path:{id:"openai"}}));let m=!1;let I=P?G$({paths:j,slot:v,version:F,fence:c,runDeps:{vaultServes:()=>W.serves()},paused:async()=>await W.authority()!=="local",migrate:async(U)=>{let N=await Z$(U);return m=N.status==="refused",b.load(),N},adopt:async(U)=>{if(!await v2(x,A))return{status:"retry",reason:"vault-roster-pending"};let N=await K$(U);return b.load(),N}}):void 0;I?.start();H.start();let J=new w2;let V=q1({source:b,slotPlaceholderWithoutMain:u,storage:()=>i1(j()),pins:J,vault:W,awaitVaultRoster:async()=>{await v2(x,J$)},responsesLite:()=>I2().responsesLite,codexEndpoint:()=>I2().codexApiEndpoint,log:X});let M=await m1($,V.adapter,X);V.attach(M);let T=async(U)=>{if(await X2(W),j2(j().configPath))return;if(await I?.idle(),j2(j().configPath))return;if(m&&!y2(U)&&(await c()).open){await b.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let R=async(U)=>{await T(U);let N=await y1(b.poolStore(),j(),U,{vault:W});if(!j2(j().configPath))await I?.requestAdoption();await b.load(),X.info("ChatGPT login stored in the account pool",N)};let L=await M2($,{integrationID:i,methods:k1({beginLogin:Z.beginLogin??p1,version:F,vault:W}),onLogin:(U)=>R(U),label:"ChatGPT (openai-auth account pool)",vault:b1(W)});let D=await v1($);let k=new AbortController;(async()=>{try{for await(let U of $.event.subscribe({signal:k.signal}))if(U.type==="session.deleted")V.forgetSession(U.data.sessionID)}catch(U){if(!k.signal.aborted)X.warn("stopped listening for session deletion",{error:U instanceof Error?U.message:String(U)})}})();O=!0;return async()=>{k.abort(),I?.dispose(),await Promise.allSettled([M.dispose(),L.dispose(),D.dispose()]),await Promise.race([b.settled(),new Promise((U)=>setTimeout(U,ZY).unref?.())]),H.release(),b.dispose(),await r?.release()}}catch(g){var p=g,l=1}finally{u1(S,p,l)}}var zY=h2(),_Z={id:C2,setup:zY.setup,server:H$.server};export{_Z as default,h2 as createOpenAIAuthPlugin,C2 as OPENAI_AUTH_PLUGIN_ID};
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(`
2
+ `)}:{event:J,data:K.join(`
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.2",
3
+ "version": "1.0.4",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "repository": {
@@ -10,6 +10,9 @@
10
10
  },
11
11
  "main": "./dist/index.js",
12
12
  "types": "./dist/index.d.ts",
13
+ "bin": {
14
+ "opencode-openai-auth": "./dist/bin.js"
15
+ },
13
16
  "exports": {
14
17
  ".": {
15
18
  "import": "./dist/index.js",
@@ -43,7 +46,7 @@
43
46
  "LICENSE"
44
47
  ],
45
48
  "scripts": {
46
- "build": "rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --minify && bun run build:types && bun run build:tui",
49
+ "build": "rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts src/bin.ts --root src --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && bun run build:tui",
47
50
  "build:tui": "bun scripts/build-tui.ts",
48
51
  "build:types": "cd ../core && bun run build && cd ../opencode && tsdown --config tsdown.config.ts --config-loader native",
49
52
  "build:dev": "rm -rf dist && tsc -p tsconfig.build.json",
@@ -63,15 +66,17 @@
63
66
  },
64
67
  "devDependencies": {
65
68
  "@ai-sdk/openai": "3.0.88",
66
- "@cortexkit/claustrum-client": "^0.6.2",
67
- "@cortexkit/common-auth": "^0.14.2",
69
+ "@cortexkit/common-auth": "^0.17.0",
68
70
  "@cortexkit/openai-auth-core": "workspace:*",
69
- "@opencode/plugin": "2.0.22"
71
+ "@opencode/plugin": "2.0.27"
70
72
  },
71
73
  "dependencies": {
72
- "@opentui/core": ">=0.5.14",
73
- "@opentui/solid": ">=0.5.14",
74
- "ai": "^7.0.127",
74
+ "@cortexkit/claustrum-client": "^0.9.0",
75
+ "@cortexkit/private-files": "^0.2.1",
76
+ "@cortexkit/subc-client": "^0.16.0",
77
+ "@opentui/core": ">=0.6.1",
78
+ "@opentui/solid": ">=0.6.1",
79
+ "ai": "^7.0.137",
75
80
  "jsonc-parser": "^3.3.1",
76
81
  "solid-js": "1.9.12"
77
82
  }
@@ -14,11 +14,19 @@ export {
14
14
  } from "./shared/3c2d4169d00f907e-tui-support.js";
15
15
  const LEVELS = ["error", "warn", "info", "debug", "trace"];
16
16
  export function getLogFile() {
17
- return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE ?? join(tmpdir(), "opencode-openai-auth.log");
17
+ return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE ?? (process.platform === "win32" ? join(tmpdir(), "opencode-openai-auth", "opencode-openai-auth.log") : join(tmpdir(), "opencode-openai-auth.log"));
18
18
  }
19
19
  export function getEnvLogLevel() {
20
20
  const env = process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;
21
21
  return env && LEVELS.includes(env) ? env : void 0;
22
22
  }
23
23
  initLogger({ file: getLogFile, level: getEnvLogLevel });
24
- process.on("exit", flushLogs);
24
+ process.once("beforeExit", async () => {
25
+ try {
26
+ await flushLogs();
27
+ } catch {
28
+ process.emitWarning("OpenAI auth could not flush its log file at shutdown");
29
+ }
30
+ });
31
+ if (process.platform !== "win32")
32
+ process.on("exit", () => flushLogs());
@@ -1,4 +1,4 @@
1
- import { isQuotaMap } from "./905bffc0220f43d0-map.js";
1
+ import { decodeQuotaMap, isQuotaMap } from "./905bffc0220f43d0-map.js";
2
2
  import { mergeQuotaObservation } from "./4f36d333d081d040-merge.js";
3
3
  /**
4
4
  * The quota codec the account-pool store (the `/store` subpath) takes when it
@@ -8,5 +8,6 @@ import { mergeQuotaObservation } from "./4f36d333d081d040-merge.js";
8
8
  */
9
9
  export const quotaCodec = Object.freeze({
10
10
  validate: isQuotaMap,
11
+ decode: decodeQuotaMap,
11
12
  merge: mergeQuotaObservation,
12
13
  });
@@ -2,8 +2,13 @@ import { readFileSync, realpathSync, statSync, watch, } from "node:fs";
2
2
  import { readFile, stat } from "node:fs/promises";
3
3
  import { basename, dirname, join, resolve } from "node:path";
4
4
  import { clearTimeout, setTimeout } from "node:timers";
5
+ import { PrivateFileError, readPrivateText, windowsPrivateFiles, } from "./375d9cca2def037d-private-files.js";
5
6
  function canonicalPath(file) {
6
7
  const path = resolve(file);
8
+ // Leave reparse points in the path for private-files' ancestor walk to reject;
9
+ // realpath would follow them before the security backend saw the original path.
10
+ if (windowsPrivateFiles)
11
+ return path;
7
12
  try {
8
13
  return realpathSync(path);
9
14
  }
@@ -34,7 +39,9 @@ export function watchTuiPreferences(file, onChange, options = {}) {
34
39
  if (shared)
35
40
  return shared.subscribe(onChange);
36
41
  const name = basename(path);
37
- const read = options.fs?.readFile ?? ((file) => readFile(file, 'utf8'));
42
+ const read = windowsPrivateFiles
43
+ ? (file) => readPrivateText(file)
44
+ : (options.fs?.readFile ?? ((file) => readFile(file, 'utf8')));
38
45
  const probe = options.fs?.stat ?? stat;
39
46
  let timer = null;
40
47
  let pollTimer = null;
@@ -43,14 +50,15 @@ export function watchTuiPreferences(file, onChange, options = {}) {
43
50
  // Seed synchronously so an immediate write cannot be absorbed as the baseline.
44
51
  // The metadata is recorded only together with contents that were read, as in
45
52
  // the probe below: if the first read fails, the probe keeps trying.
46
- try {
47
- const metadata = identity((options.fs?.statSync ?? statSync)(path));
48
- lastSeen = (options.fs?.readFileSync ?? ((file) => readFileSync(file, 'utf8')))(path);
49
- lastMetadata = metadata;
50
- }
51
- catch {
52
- // Missing or unreadable files are picked up by the probe later.
53
- }
53
+ if (!windowsPrivateFiles)
54
+ try {
55
+ const metadata = identity((options.fs?.statSync ?? statSync)(path));
56
+ lastSeen = (options.fs?.readFileSync ?? ((file) => readFileSync(file, 'utf8')))(path);
57
+ lastMetadata = metadata;
58
+ }
59
+ catch {
60
+ // Missing or unreadable files are picked up by the probe later.
61
+ }
54
62
  let disposed = false;
55
63
  const subscribers = new Set();
56
64
  let checking = Promise.resolve();
@@ -68,7 +76,15 @@ export function watchTuiPreferences(file, onChange, options = {}) {
68
76
  lastMetadata = null;
69
77
  return;
70
78
  }
71
- const text = await read(path).catch(() => null);
79
+ const text = await read(path).catch((error) => {
80
+ if (error instanceof PrivateFileError && error.code !== 'ENOENT') {
81
+ if (options.onError)
82
+ options.onError(error);
83
+ else
84
+ process.emitWarning(error.message, error.name);
85
+ }
86
+ return null;
87
+ });
72
88
  if (disposed)
73
89
  return;
74
90
  // Record the metadata only once its contents were read. A failed read