@cortexkit/opencode-openai-auth 0.3.3 → 0.3.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.
@@ -0,0 +1,328 @@
1
+ import { watch } from 'node:fs'
2
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
3
+ import { homedir } from 'node:os'
4
+ import { basename, dirname, join } from 'node:path'
5
+ import { applyEdits, modify, type ParseError, parse } from 'jsonc-parser'
6
+
7
+ export const TUI_PREFS_FILE_ENV = 'OPENCODE_TUI_PREFERENCES_FILE'
8
+ const FILE_NAME = 'tui-preferences.jsonc'
9
+
10
+ // Shared preferences file for opencode TUI plugins. One top-level key per
11
+ // plugin (short name, e.g. "openai-auth"). The file is optional: every
12
+ // reader must fall back to defaults when it is missing or malformed.
13
+ export function getTuiPreferencesFile(): string {
14
+ const override = process.env[TUI_PREFS_FILE_ENV]
15
+ if (override) return override
16
+ const configDir =
17
+ process.env.OPENCODE_CONFIG_DIR ||
18
+ join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'opencode')
19
+ return join(configDir, FILE_NAME)
20
+ }
21
+
22
+ function isRecord(value: unknown): value is Record<string, unknown> {
23
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
24
+ }
25
+
26
+ // Tolerant read: missing file, parse errors, or a non-object root all resolve
27
+ // to {} so the sidebar never crashes on user-edited content. jsonc-parser's
28
+ // fault-tolerant parse can still hand back a partial object for an
29
+ // unterminated/bracketed file or trailing garbage, so we collect errors and
30
+ // treat any reported fault as malformed.
31
+ export async function readTuiPreferencesFile(): Promise<
32
+ Record<string, unknown>
33
+ > {
34
+ try {
35
+ const raw = await readFile(getTuiPreferencesFile(), 'utf8')
36
+ const errors: ParseError[] = []
37
+ const root: unknown = parse(raw, errors, { allowTrailingComma: true })
38
+ if (errors.length > 0) return {}
39
+ return isRecord(root) ? root : {}
40
+ } catch {
41
+ return {}
42
+ }
43
+ }
44
+
45
+ export const PLUGIN_KEY = 'openai-auth'
46
+ export const DEFAULT_SLOT_ORDER = 160
47
+
48
+ export interface OpenaiAuthTuiPrefs {
49
+ forceToTop: boolean
50
+ order: number
51
+ startCollapsed: boolean
52
+ rememberCollapsed: boolean
53
+ // null = never persisted; seed the UI from startCollapsed instead.
54
+ collapsed: boolean | null
55
+ pollMs: number
56
+ refreshDebounceMs: number
57
+ header: {
58
+ label: string
59
+ showVersion: boolean
60
+ }
61
+ sections: {
62
+ quota: boolean
63
+ fallbackAccounts: boolean
64
+ routing: boolean
65
+ health: boolean
66
+ pacing: boolean
67
+ }
68
+ appearance: {
69
+ barWidth: number
70
+ barFilledChar: string
71
+ barEmptyChar: string
72
+ warnThreshold: number
73
+ errorThreshold: number
74
+ }
75
+ }
76
+
77
+ export type AppearancePrefs = OpenaiAuthTuiPrefs['appearance']
78
+
79
+ export const DEFAULT_PREFS: OpenaiAuthTuiPrefs = {
80
+ forceToTop: false,
81
+ order: DEFAULT_SLOT_ORDER,
82
+ startCollapsed: false,
83
+ rememberCollapsed: true,
84
+ collapsed: null,
85
+ pollMs: 1500,
86
+ refreshDebounceMs: 200,
87
+ header: { label: 'OPENAI', showVersion: true },
88
+ sections: {
89
+ quota: true,
90
+ fallbackAccounts: true,
91
+ routing: true,
92
+ health: true,
93
+ pacing: true,
94
+ },
95
+ appearance: {
96
+ barWidth: 10,
97
+ barFilledChar: '\u2588',
98
+ barEmptyChar: '\u2591',
99
+ warnThreshold: 50,
100
+ errorThreshold: 80,
101
+ },
102
+ }
103
+
104
+ function bool(value: unknown, fallback: boolean): boolean {
105
+ return typeof value === 'boolean' ? value : fallback
106
+ }
107
+
108
+ function int(
109
+ value: unknown,
110
+ fallback: number,
111
+ min: number,
112
+ max: number,
113
+ ): number {
114
+ if (typeof value !== 'number' || !Number.isFinite(value)) return fallback
115
+ return Math.min(Math.max(Math.round(value), min), max)
116
+ }
117
+
118
+ function label(value: unknown, fallback: string, maxLength: number): string {
119
+ if (typeof value !== 'string' || value.length === 0) return fallback
120
+ return value.slice(0, maxLength)
121
+ }
122
+
123
+ function char(value: unknown, fallback: string): string {
124
+ if (typeof value !== 'string') return fallback
125
+ const first = [...value][0]
126
+ return first ?? fallback
127
+ }
128
+
129
+ // Per-key validation: every value is independently clamped/defaulted so one
130
+ // bad entry never poisons the rest. Never throws.
131
+ export function resolveOpenaiAuthPrefs(
132
+ root: Record<string, unknown>,
133
+ ): OpenaiAuthTuiPrefs {
134
+ const entry = root[PLUGIN_KEY]
135
+ if (!isRecord(entry)) return structuredClone(DEFAULT_PREFS)
136
+
137
+ const d = DEFAULT_PREFS
138
+ const header = isRecord(entry.header) ? entry.header : {}
139
+ const sections = isRecord(entry.sections) ? entry.sections : {}
140
+ const appearance = isRecord(entry.appearance) ? entry.appearance : {}
141
+
142
+ const warnThreshold = int(
143
+ appearance.warnThreshold,
144
+ d.appearance.warnThreshold,
145
+ 0,
146
+ 99,
147
+ )
148
+ const errorThreshold = Math.max(
149
+ int(appearance.errorThreshold, d.appearance.errorThreshold, 0, 100),
150
+ Math.min(warnThreshold + 1, 100),
151
+ )
152
+
153
+ return {
154
+ forceToTop: bool(entry.forceToTop, d.forceToTop),
155
+ order: int(entry.order, d.order, -10000, 10000),
156
+ startCollapsed: bool(entry.startCollapsed, d.startCollapsed),
157
+ rememberCollapsed: bool(entry.rememberCollapsed, d.rememberCollapsed),
158
+ collapsed: typeof entry.collapsed === 'boolean' ? entry.collapsed : null,
159
+ pollMs: int(entry.pollMs, d.pollMs, 500, 30000),
160
+ refreshDebounceMs: int(
161
+ entry.refreshDebounceMs,
162
+ d.refreshDebounceMs,
163
+ 50,
164
+ 5000,
165
+ ),
166
+ header: {
167
+ label: label(header.label, d.header.label, 20),
168
+ showVersion: bool(header.showVersion, d.header.showVersion),
169
+ },
170
+ sections: {
171
+ quota: bool(sections.quota, d.sections.quota),
172
+ fallbackAccounts: bool(
173
+ sections.fallbackAccounts,
174
+ d.sections.fallbackAccounts,
175
+ ),
176
+ routing: bool(sections.routing, d.sections.routing),
177
+ health: bool(sections.health, d.sections.health),
178
+ pacing: bool(sections.pacing, d.sections.pacing),
179
+ },
180
+ appearance: {
181
+ barWidth: int(appearance.barWidth, d.appearance.barWidth, 4, 40),
182
+ barFilledChar: char(appearance.barFilledChar, d.appearance.barFilledChar),
183
+ barEmptyChar: char(appearance.barEmptyChar, d.appearance.barEmptyChar),
184
+ warnThreshold,
185
+ errorThreshold,
186
+ },
187
+ }
188
+ }
189
+
190
+ const FORCE_TOP_BASE = -100000
191
+
192
+ // Shared forceToTop convention: forced plugins sort below FORCE_TOP_BASE,
193
+ // ordered among themselves by their top-level key's position in the file, so
194
+ // users reprioritize by reordering keys. The user-facing `order` knob clamps
195
+ // to -10000..10000, strictly above the forced band, so a manual order can
196
+ // never beat forceToTop. Host slots render ascending by order; opencode's
197
+ // built-ins occupy 100-500.
198
+ //
199
+ // Key-naming requirement: plugin keys must be non-integer-like short names
200
+ // (e.g. "openai-auth"). JavaScript object key iteration order hoists
201
+ // integer-like keys ("0", "1", "42") ahead of any string keys, which would
202
+ // skew the indexOf-based ordering of forced plugins. The shared
203
+ // `tui-preferences.jsonc` convention requires non-numeric names, so this
204
+ // implementation does not paper over the JS quirk.
205
+ export function computeEffectiveOrder(
206
+ root: Record<string, unknown>,
207
+ pluginKey: string,
208
+ defaultOrder: number,
209
+ ): number {
210
+ const entry = root[pluginKey]
211
+ if (!isRecord(entry)) return defaultOrder
212
+ if (entry.forceToTop === true) {
213
+ return FORCE_TOP_BASE + Object.keys(root).indexOf(pluginKey)
214
+ }
215
+ return int(entry.order, defaultOrder, -10000, 10000)
216
+ }
217
+
218
+ const TEMPLATE = `// Shared preferences for opencode TUI plugins.
219
+ // One top-level key per plugin (short name). See each plugin's README for
220
+ // its supported settings. This file is safe to hand-edit; plugins update
221
+ // individual keys in place and preserve comments.
222
+ {}
223
+ `
224
+
225
+ type JsonValue = string | number | boolean | null
226
+
227
+ async function writePreference(
228
+ pluginKey: string,
229
+ path: string[],
230
+ value: JsonValue,
231
+ ): Promise<void> {
232
+ const file = getTuiPreferencesFile()
233
+ await mkdir(dirname(file), { recursive: true })
234
+ let text: string
235
+ try {
236
+ text = await readFile(file, 'utf8')
237
+ } catch {
238
+ text = ''
239
+ }
240
+ if (text.trim() === '') text = TEMPLATE
241
+ const edits = modify(text, [pluginKey, ...path], value, {
242
+ formattingOptions: { insertSpaces: true, tabSize: 2 },
243
+ })
244
+ const next = applyEdits(text, edits)
245
+ const tmp = `${file}.${process.pid}.tmp`
246
+ await writeFile(tmp, next, 'utf8')
247
+ await rename(tmp, file)
248
+ }
249
+
250
+ let writeChain: Promise<void> = Promise.resolve()
251
+
252
+ // Writes are serialized on a promise chain: each update re-reads the file,
253
+ // applies a minimal comment-preserving edit to one property, and replaces the
254
+ // file atomically (temp + rename in the same directory). Best-effort by
255
+ // design — preferences are never worth crashing the TUI over.
256
+ export function queueTuiPreferenceUpdate(
257
+ pluginKey: string,
258
+ path: string[],
259
+ value: JsonValue,
260
+ ): Promise<void> {
261
+ writeChain = writeChain
262
+ .then(() => writePreference(pluginKey, path, value))
263
+ .catch(() => {})
264
+ return writeChain
265
+ }
266
+
267
+ const WATCH_DEBOUNCE_MS = 150
268
+
269
+ // Watches the directory rather than the file: editors and our own atomic
270
+ // writes replace the file via rename, which kills file-level watchers.
271
+ //
272
+ // Filtering is two-stage:
273
+ // 1. Filename pre-filter: only debounce events for the preferences file
274
+ // name, or our atomic-write temp file. This is a cheap first pass that
275
+ // drops the common case (unrelated sibling files).
276
+ // 2. Content check inside the debounce: after the timer fires, re-read
277
+ // the file and compare it against the last seen content. Only fire
278
+ // `onChange` when the content actually changed. This is the authority.
279
+ // Some platforms (notably macOS FSEvents and a few inotify backends)
280
+ // can misattribute a rename of an unrelated sibling file to the
281
+ // real preferences filename in addition to emitting the sibling's
282
+ // own event, so a name-only filter still produces a stray callback.
283
+ // A content comparison is robust against that, against coalesced
284
+ // events, and against mtime granularity.
285
+ //
286
+ // Returns a disposer; never throws.
287
+ export function watchTuiPreferences(onChange: () => void): () => void {
288
+ const file = getTuiPreferencesFile()
289
+ const name = basename(file)
290
+ let timer: ReturnType<typeof setTimeout> | null = null
291
+ let lastSeen: string | null = null
292
+ // Seed asynchronously; a real change that fires before the seed resolves
293
+ // still wins because the debounce re-reads the file fresh and compares
294
+ // against `lastSeen` (which will be `null` → does not match → fires).
295
+ void readFile(file, 'utf8')
296
+ .then((text) => {
297
+ if (lastSeen === null) lastSeen = text
298
+ })
299
+ .catch(() => {})
300
+ try {
301
+ const watcher = watch(dirname(file), (_event, filename) => {
302
+ // Exact match against the preferences file name, plus the temp file
303
+ // we use for atomic writes (carrying our pid + `.tmp`).
304
+ const isOurs =
305
+ filename === name ||
306
+ (filename?.startsWith(`${name}.`) && filename.endsWith('.tmp'))
307
+ if (filename != null && !isOurs) return
308
+ if (timer) clearTimeout(timer)
309
+ timer = setTimeout(() => {
310
+ timer = null
311
+ void readFile(file, 'utf8')
312
+ .catch(() => null)
313
+ .then((text) => {
314
+ if (text === null) return
315
+ if (text === lastSeen) return
316
+ lastSeen = text
317
+ onChange()
318
+ })
319
+ }, WATCH_DEBOUNCE_MS)
320
+ })
321
+ return () => {
322
+ if (timer) clearTimeout(timer)
323
+ watcher.close()
324
+ }
325
+ } catch {
326
+ return () => {}
327
+ }
328
+ }