@cortexkit/opencode-anthropic-auth 1.9.2 → 1.9.3

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