opencode-codebuddy-quota 0.0.0-stage → 0.1.2

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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +81 -2
  3. package/config.default.json +41 -0
  4. package/dist/gui-experimental.cjs +1 -0
  5. package/package.json +47 -4
  6. package/rpc.ts +92 -0
  7. package/server.ts +251 -0
  8. package/src/gui/battery.tsx +81 -0
  9. package/src/gui/dialog-helpers.ts +30 -0
  10. package/src/gui/dialog.css +83 -0
  11. package/src/gui/dialog.tsx +262 -0
  12. package/src/gui/pace.ts +76 -0
  13. package/src/gui/quota.ts +198 -0
  14. package/src/gui/store.ts +181 -0
  15. package/src/gui.tsx +111 -0
  16. package/src/server/catalog.ts +264 -0
  17. package/src/server/config-writer.ts +621 -0
  18. package/src/server/config.ts +215 -0
  19. package/src/server/embedding-local.ts +166 -0
  20. package/src/server/embedding-mode.ts +14 -0
  21. package/src/server/gateway-owner.ts +243 -0
  22. package/src/server/gateway-setup.ts +51 -0
  23. package/src/server/headers.ts +72 -0
  24. package/src/server/logger.ts +26 -0
  25. package/src/server/login-gate.ts +21 -0
  26. package/src/server/login.ts +206 -0
  27. package/src/server/model-cache.ts +136 -0
  28. package/src/server/model-info.ts +109 -0
  29. package/src/server/model-prewarm.ts +123 -0
  30. package/src/server/models-dev.ts +77 -0
  31. package/src/server/models-endpoint.ts +74 -0
  32. package/src/server/package-spec.ts +42 -0
  33. package/src/server/package-version.ts +51 -0
  34. package/src/server/pricing.ts +169 -0
  35. package/src/server/proxy.ts +564 -0
  36. package/src/server/quota-source.ts +129 -0
  37. package/src/server/rpc-handlers.ts +87 -0
  38. package/src/server/signal.ts +36 -0
  39. package/src/server/site-select.ts +24 -0
  40. package/src/server/site-state.ts +58 -0
  41. package/src/server/stream-collect.ts +166 -0
  42. package/src/server/token-store.ts +263 -0
  43. package/src/server/upstream.ts +150 -0
  44. package/src/server/wire.ts +67 -0
  45. package/src/shared.ts +20 -0
@@ -0,0 +1,621 @@
1
+ import { readFileSync, writeFileSync } from "node:fs"
2
+ import type { ImportedModel } from "./model-info"
3
+ import { withVersion } from "./package-version"
4
+ import { isVersion, packageSpec, PROVIDER_IDS } from "./package-spec"
5
+
6
+ /**
7
+ * Writes the imported model list into the user's `opencode.jsonc`.
8
+ *
9
+ * Why the config file and not `ctx.provider.transform`: in OpenCode 2.2.5 the
10
+ * provider records handed to a transform are already frozen — every write path
11
+ * (`add`, `models.set`, `update`) throws `Attempted to assign to readonly
12
+ * property`. The config file is read before providers are resolved, so it is
13
+ * the only place a plugin can add models that actually reach the model picker.
14
+ *
15
+ * The file is JSONC, so this edits text rather than re-serializing: comments and
16
+ * key order survive, and an unrelated field is never reformatted. Failure to
17
+ * parse means the file is left untouched.
18
+ */
19
+
20
+ export interface WriteModelsDeps {
21
+ jsoncPath: string
22
+ /** Which provider's `models` block to edit. Defaults to the legacy provider. */
23
+ providerId?: string
24
+ models: readonly ImportedModel[]
25
+ /** When set, the provider's `package` version is moved to this value. */
26
+ packageVersion?: string | null
27
+ readFile?: (path: string) => string
28
+ writeFile?: (path: string, content: string) => void
29
+ /** Reads the file from disk for the concurrent-write guard. Defaults to readFileSync. */
30
+ diskRead?: (path: string) => string
31
+ /** Called with the original text right before it is replaced. */
32
+ backup?: (path: string, content: string) => void
33
+ }
34
+
35
+ /**
36
+ * Refuse to write if another process changed the file since we read it. When
37
+ * `writeFile` is injected (tests / in-memory use) there is no real disk file to
38
+ * guard, so this is a no-op unless an explicit `diskRead` is supplied.
39
+ */
40
+ function fileChangedOnDisk(deps: WriteModelsDeps, original: string): boolean {
41
+ if (!deps.diskRead && deps.writeFile) return false
42
+ try {
43
+ const diskRead = deps.diskRead ?? ((p: string) => readFileSync(p, "utf8"))
44
+ return diskRead(deps.jsoncPath) !== original
45
+ } catch {
46
+ // A file that vanished/changed unreadably is unsafe to overwrite blindly.
47
+ return true
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Three outcomes, not two booleans: the file was rewritten, it already matched
53
+ * (so nothing was touched), or it was left alone because something about it
54
+ * could not be understood.
55
+ */
56
+ export type WriteModelsResult =
57
+ | {
58
+ status: "written"
59
+ /** The `package` version moved. False when it already matched or was not a version. */
60
+ packageUpdated: boolean
61
+ /**
62
+ * Set when a `package` key exists but updating it failed — the models still
63
+ * land, but the caller should say why the version did not move.
64
+ */
65
+ packageWarning?: string
66
+ }
67
+ | { status: "unchanged" }
68
+ | { status: "skipped"; reason: string }
69
+
70
+ /**
71
+ * Blanks `//` and leading-`*` comments plus trailing commas, so `JSON.parse`
72
+ * can read the text.
73
+ *
74
+ * Deleted characters are replaced by spaces rather than removed: every caller
75
+ * splices the original text using offsets taken from this result, and a changed
76
+ * length would silently cut a different span. Newlines survive so line offsets
77
+ * and error messages stay meaningful.
78
+ */
79
+ export function stripComments(text: string): string {
80
+ let out = ""
81
+ let inString = false
82
+ let inLine = false
83
+ let inBlock = false
84
+
85
+ for (let i = 0; i < text.length; i++) {
86
+ const ch = text[i]
87
+ const next = text[i + 1]
88
+
89
+ if (inLine) {
90
+ if (ch === "\n") {
91
+ inLine = false
92
+ out += "\n"
93
+ } else {
94
+ out += " "
95
+ }
96
+ continue
97
+ }
98
+ if (inBlock) {
99
+ if (ch === "*" && next === "/") {
100
+ inBlock = false
101
+ out += " "
102
+ i++
103
+ } else {
104
+ out += ch === "\n" ? "\n" : " "
105
+ }
106
+ continue
107
+ }
108
+ if (inString) {
109
+ out += ch
110
+ if (ch === "\\") {
111
+ out += next ?? ""
112
+ i++
113
+ } else if (ch === "\"") {
114
+ inString = false
115
+ }
116
+ continue
117
+ }
118
+ if (ch === "\"") {
119
+ inString = true
120
+ out += ch
121
+ continue
122
+ }
123
+ if (ch === "/" && next === "/") {
124
+ inLine = true
125
+ out += " "
126
+ i++
127
+ continue
128
+ }
129
+ if (ch === "/" && next === "*") {
130
+ inBlock = true
131
+ out += " "
132
+ i++
133
+ continue
134
+ }
135
+ out += ch
136
+ }
137
+
138
+ return blankTrailingCommas(out)
139
+ }
140
+
141
+ /** JSONC allows a comma before a closing brace/bracket; JSON does not. */
142
+ function blankTrailingCommas(text: string): string {
143
+ // Code units, not code points: the caller relies on a 1:1 index mapping back
144
+ // into `text`, which a `[...text]` spread would break for astral characters.
145
+ const chars = text.split("")
146
+ let inString = false
147
+ for (let i = 0; i < text.length; i++) {
148
+ const ch = text[i]
149
+ if (inString) {
150
+ if (ch === "\\") i++
151
+ else if (ch === "\"") inString = false
152
+ continue
153
+ }
154
+ if (ch === "\"") {
155
+ inString = true
156
+ continue
157
+ }
158
+ if (ch !== ",") continue
159
+ // Only a comma whose next non-space character closes a container is trailing.
160
+ let j = i + 1
161
+ while (j < text.length && /\s/.test(text[j])) j++
162
+ if (j < text.length && (text[j] === "}" || text[j] === "]")) chars[i] = " "
163
+ }
164
+ return chars.join("")
165
+ }
166
+
167
+ /** A model as it must appear in `opencode.jsonc`, matching the existing hand-written entries. */
168
+ export function toConfigModel(model: ImportedModel): Record<string, unknown> {
169
+ const cost = model.cost[0]
170
+ const entry: Record<string, unknown> = {
171
+ name: model.name,
172
+ capabilities: {
173
+ tools: true,
174
+ input: model.imageInput ? ["text", "image"] : ["text"],
175
+ output: ["text"],
176
+ },
177
+ limit: { context: model.limit.context, output: model.limit.output },
178
+ }
179
+
180
+ if (cost) {
181
+ entry.cost = {
182
+ input: cost.input,
183
+ output: cost.output,
184
+ cache: { read: cost.cache.read, write: cost.cache.write },
185
+ }
186
+ }
187
+
188
+ const variants = model.efforts.map((effort) => ({
189
+ id: effort,
190
+ settings: effort === "off" ? {} : { reasoningEffort: effort },
191
+ }))
192
+ if (variants.length > 0) {
193
+ entry.variants = variants
194
+ entry.settings = { reasoningEffort: model.defaultEffort ?? model.efforts[model.efforts.length - 1] }
195
+ }
196
+
197
+ return entry
198
+ }
199
+
200
+ /**
201
+ * Serializes one property value on a single line: `{ ... }` with spaces inside
202
+ * the braces and `[a, b]` for arrays, which is how these config files are
203
+ * normally hand-written. Keeping it compact matters — a fully expanded entry
204
+ * costs ~40 lines, so ten models would turn a 190-line file into 500.
205
+ */
206
+ function compactJson(value: unknown): string {
207
+ if (Array.isArray(value)) return `[${value.map(compactJson).join(", ")}]`
208
+ if (value && typeof value === "object") {
209
+ const entries = Object.entries(value as Record<string, unknown>)
210
+ if (entries.length === 0) return "{}"
211
+ return `{ ${entries.map(([k, v]) => `${JSON.stringify(k)}: ${compactJson(v)}`).join(", ")} }`
212
+ }
213
+ return JSON.stringify(value)
214
+ }
215
+
216
+ /** The line ending the file actually uses, so a rewritten block does not mix them. */
217
+ function newlineOf(text: string): string {
218
+ return text.includes("\r\n") ? "\r\n" : "\n"
219
+ }
220
+
221
+ function indentOf(text: string, at: number): string {
222
+ const lineStart = text.lastIndexOf("\n", at) + 1
223
+ const prefix = text.slice(lineStart, at)
224
+ const match = /^[ \t]*/.exec(prefix)
225
+ return match ? match[0] : " "
226
+ }
227
+
228
+ /**
229
+ * Brings `providers.codebuddy` in line with what the plugin computed: the
230
+ * `models` block is replaced, and the provider `package` version is moved
231
+ * forward when a newer one was found.
232
+ *
233
+ * The whole block is compared by content, not just by the set of model ids, so
234
+ * a price or reasoning-level change from models.dev also lands. Nothing is
235
+ * written when the rendered text already matches what is on disk.
236
+ *
237
+ * Any malformed input ends in `skipped` rather than risk corrupting the user's
238
+ * configuration.
239
+ */
240
+ export function writeModels(deps: WriteModelsDeps): WriteModelsResult {
241
+ // Default to the first NEW provider, never the legacy `codebuddy`: a future
242
+ // missed providerId must not rewrite the old provider block.
243
+ const providerId = deps.providerId ?? PROVIDER_IDS[0]
244
+ const read = deps.readFile ?? ((p: string) => readFileSync(p, "utf8"))
245
+ const write = deps.writeFile ?? ((p: string, c: string) => writeFileSync(p, c, "utf8"))
246
+
247
+ let original: string
248
+ try {
249
+ original = read(deps.jsoncPath)
250
+ } catch {
251
+ return { status: "skipped", reason: "config file could not be read" }
252
+ }
253
+
254
+ const bare = stripComments(original)
255
+ if (!isJsonObject(bare)) {
256
+ return { status: "skipped", reason: "config file is not valid JSON/JSONC" }
257
+ }
258
+
259
+ const provider = locateProvider(bare, providerId)
260
+ if (!provider) {
261
+ return { status: "skipped", reason: `could not locate providers.${providerId} in the config text` }
262
+ }
263
+ const modelsRange = locateModelsBlock(bare, provider)
264
+ if (!modelsRange) {
265
+ return { status: "skipped", reason: `could not locate providers.${providerId}.models in the config text` }
266
+ }
267
+
268
+ const modelsById: Record<string, unknown> = {}
269
+ for (const model of deps.models) modelsById[model.id] = toConfigModel(model)
270
+
271
+ const modelsIndent = indentOf(original, modelsRange.open)
272
+ const eol = newlineOf(original)
273
+ const members = Object.entries(modelsById)
274
+ .map(([id, value]) => `${modelsIndent} ${JSON.stringify(id)}: ${compactJson(value)}`)
275
+ .join(`,${eol}`)
276
+ const body = members ? `${eol}${members}${eol}${modelsIndent}` : ""
277
+ let next = `${original.slice(0, modelsRange.open + 1)}${body}${original.slice(modelsRange.close)}`
278
+
279
+ // A version that is not a version (a whole file, an empty string, a URL) is
280
+ // never written into the `package` spec; the models still land.
281
+ const packageVersion = isVersion(deps.packageVersion) ? deps.packageVersion : null
282
+ let packageUpdated = false
283
+ let packageWarning: string | undefined
284
+ if (packageVersion) {
285
+ const retargeted = retargetPackage({ text: next, provider, version: packageVersion })
286
+ next = retargeted.text
287
+ packageUpdated = retargeted.applied
288
+ packageWarning = retargeted.problem
289
+ }
290
+
291
+ if (next === original) return { status: "unchanged" }
292
+
293
+ // Last gate before touching the user's file: a splice that landed on the
294
+ // wrong offset produces text that no longer parses, and writing that would
295
+ // destroy the config. Refuse instead. Comments are still in `next`, so it is
296
+ // parsed the same way the input was.
297
+ const rendered = parseJsonc(next)
298
+ if (!rendered) {
299
+ return { status: "skipped", reason: "rendered config would not parse; refusing to write" }
300
+ }
301
+ const renderedProvider = (rendered as { providers?: Record<string, unknown> }).providers?.[providerId] as
302
+ | { models?: unknown; package?: unknown }
303
+ | undefined
304
+ const renderedIds = Object.keys((renderedProvider?.models as Record<string, unknown>) ?? {})
305
+ if (renderedIds.join("\u0000") !== Object.keys(modelsById).join("\u0000")) {
306
+ return { status: "skipped", reason: "model block did not land under the expected provider; refusing to write" }
307
+ }
308
+ if (packageVersion) {
309
+ const expected = packageSpec(packageVersion)
310
+ if (renderedProvider?.package !== undefined && renderedProvider.package !== expected && !packageWarning) {
311
+ return { status: "skipped", reason: `package is ${JSON.stringify(renderedProvider.package)} after the rewrite; refusing to write` }
312
+ }
313
+ }
314
+
315
+ if (fileChangedOnDisk(deps, original)) {
316
+ return { status: "skipped", reason: "config file changed on disk while editing; refusing to overwrite" }
317
+ }
318
+ deps.backup?.(deps.jsoncPath, original)
319
+ write(deps.jsoncPath, next)
320
+ return packageWarning
321
+ ? { status: "written", packageUpdated, packageWarning }
322
+ : { status: "written", packageUpdated }
323
+ }
324
+
325
+ function isJsonObject(text: string): boolean {
326
+ try {
327
+ const value: unknown = JSON.parse(text)
328
+ return typeof value === "object" && value !== null && !Array.isArray(value)
329
+ } catch {
330
+ return false
331
+ }
332
+ }
333
+
334
+ /** The config as a value, comments and trailing commas tolerated. Null if it is not parseable. */
335
+ function parseJsonc(text: string): unknown | null {
336
+ try {
337
+ return JSON.parse(stripComments(text))
338
+ } catch {
339
+ return null
340
+ }
341
+ }
342
+
343
+ /** Offsets of an object literal, `open` being its `{` and `close` its matching `}`. */
344
+ interface ObjectRange {
345
+ open: number
346
+ close: number
347
+ }
348
+
349
+ /**
350
+ * Finds `providers.<providerId>`, walking the structure instead of searching
351
+ * for the first `"codebuddy"`: that literal also appears inside other
352
+ * providers' string values, and splicing there would drop the models into the
353
+ * wrong provider.
354
+ */
355
+ function locateProvider(bare: string, providerId: string = PROVIDER_IDS[0]): ObjectRange | null {
356
+ const root = objectAt(bare, skipSpace(bare, 0))
357
+ if (!root) return null
358
+ const providers = memberObject(bare, root.open, "providers")
359
+ return providers && memberObject(bare, providers.open, providerId)
360
+ }
361
+
362
+ /**
363
+ * Finds the `{`/`}` of the provider's models object. Duplicate keys are
364
+ * refused: text-level editing cannot tell which copy the parser would read, so
365
+ * a wrong guess would edit the one that is never used.
366
+ */
367
+ function locateModelsBlock(bare: string, provider: ObjectRange): ObjectRange | null {
368
+ return memberObject(bare, provider.open, "models")
369
+ }
370
+
371
+ /**
372
+ * Retargets the `package` directly under `providers.codebuddy` to `version`.
373
+ *
374
+ * Only that level is searched, so a `"package"` nested in `settings` or any
375
+ * other sibling is never touched. `problem` explains a rewrite that was wanted
376
+ * but could not be made, so the caller can say so instead of silently leaving
377
+ * the version behind.
378
+ */
379
+ function retargetPackage(deps: {
380
+ text: string
381
+ provider: ObjectRange
382
+ version: string
383
+ }): { text: string; applied: boolean; problem?: string } {
384
+ const { text, provider } = deps
385
+ const bare = stripComments(text)
386
+
387
+ const member = findMember(bare, provider.open, "package")
388
+ if (!member) return { text, applied: false, problem: "no package key in this provider" }
389
+
390
+ const spec = scalarAt(bare, member.valueAt)
391
+ if (!spec?.[0].startsWith('"')) return { text, applied: false, problem: "package is not a string" }
392
+
393
+ const current = JSON.parse(spec[0]) as string
394
+ const replacement = withVersion(current, deps.version)
395
+ if (!replacement) {
396
+ return { text, applied: false, problem: `package ${JSON.stringify(current)} is not a known @ai-sdk spec` }
397
+ }
398
+ if (current === replacement) return { text, applied: false }
399
+
400
+ return {
401
+ text: `${text.slice(0, member.valueAt)}${JSON.stringify(replacement)}${text.slice(member.valueAt + spec[0].length)}`,
402
+ applied: true,
403
+ }
404
+ }
405
+
406
+ function skipSpace(text: string, at: number): number {
407
+ let i = at
408
+ while (i < text.length && " \t\n\r".includes(text[i])) i++
409
+ return i
410
+ }
411
+
412
+ /** The end of the JSON string starting at `at` (just past the closing quote), or -1. */
413
+ function stringEnd(text: string, at: number): number {
414
+ let i = at + 1
415
+ while (i < text.length) {
416
+ if (text[i] === "\\") i += 2
417
+ else if (text[i] === '"') return i + 1
418
+ else i++
419
+ }
420
+ return -1
421
+ }
422
+
423
+ /** Just past a number or literal starting at `at`, or -1. */
424
+ function scalarEnd(text: string, at: number): number {
425
+ if (text[at] === '"') return stringEnd(text, at)
426
+ let i = at
427
+ while (i < text.length && !",}] \t\n\r".includes(text[i])) i++
428
+ return i === at ? -1 : i
429
+ }
430
+
431
+ function scalarAt(text: string, at: number): [string, number] | null {
432
+ const end = scalarEnd(text, at)
433
+ return end < 0 ? null : [text.slice(at, end), end]
434
+ }
435
+
436
+ /**
437
+ * The closing offset of the container opening at `at`, skipping nested
438
+ * containers and strings. [close, next] where `next` is just past the container.
439
+ */
440
+ function containerEnd(text: string, at: number): [number, number] | null {
441
+ const open = text[at]
442
+ const close = open === "{" ? "}" : open === "[" ? "]" : null
443
+ if (!close) return null
444
+ let depth = 0
445
+ for (let i = at; i < text.length; ) {
446
+ const ch = text[i]
447
+ if (ch === '"') {
448
+ const end = stringEnd(text, i)
449
+ if (end < 0) return null
450
+ i = end
451
+ continue
452
+ }
453
+ if (ch === open) depth++
454
+ else if (ch === close) {
455
+ depth--
456
+ if (depth === 0) return [i, i + 1]
457
+ }
458
+ i++
459
+ }
460
+ return null
461
+ }
462
+
463
+ /** Just past whatever value starts at `at`: a string, a number/literal, an `{}` or a `[]`. */
464
+ function valueEnd(text: string, at: number): number {
465
+ const container = containerEnd(text, at)
466
+ return container ? container[1] : scalarEnd(text, at)
467
+ }
468
+
469
+ /** The `{`/`}` of the object starting at `at`. */
470
+ function objectAt(text: string, at: number): ObjectRange | null {
471
+ const end = text[at] === "{" ? containerEnd(text, at) : null
472
+ return end ? { open: at, close: end[0] } : null
473
+ }
474
+
475
+ /** A top-level member of the object literal whose `{` is at `at`. */
476
+ interface Member {
477
+ /** Where the member's value starts. */
478
+ valueAt: number
479
+ /** True when that value is an object, for callers that need the braces. */
480
+ isObject: boolean
481
+ }
482
+
483
+ /** Walks the object literal at `at` and returns its member named `key`, or null. */
484
+ function findMember(text: string, at: number, key: string): Member | null {
485
+ const body = objectAt(text, at)
486
+ if (!body) return null
487
+ let i = skipSpace(text, body.open + 1)
488
+ while (i < body.close && text[i] === '"') {
489
+ const keyEnd = stringEnd(text, i)
490
+ if (keyEnd < 0) return null
491
+ const colon = skipSpace(text, keyEnd)
492
+ if (text[colon] !== ":") return null
493
+ const valueAt = skipSpace(text, colon + 1)
494
+ if (JSON.parse(text.slice(i, keyEnd)) === key) {
495
+ return { valueAt, isObject: text[valueAt] === "{" }
496
+ }
497
+ const end = valueEnd(text, valueAt)
498
+ if (end < 0) return null
499
+ i = skipSpace(text, end)
500
+ if (text[i] !== ",") return null
501
+ i = skipSpace(text, i + 1)
502
+ }
503
+ return null
504
+ }
505
+
506
+ /** The range of the object directly under `key`, or null when the member is missing or not an object. */
507
+ function memberObject(text: string, at: number, key: string): ObjectRange | null {
508
+ const member = findMember(text, at, key)
509
+ return member?.isObject ? { open: member.valueAt, close: containerEnd(text, member.valueAt)![0] } : null
510
+ }
511
+
512
+ export interface WriteProviderDeps extends WriteModelsDeps {
513
+ providerId: "codebuddy-cn" | "codebuddy-intl"
514
+ /** Port the local proxy listens on; baked into the provider's baseURL. */
515
+ proxyPort?: number
516
+ backup?: (path: string, content: string) => void
517
+ }
518
+
519
+ /**
520
+ * Create (or update) a v2 provider. When the block is absent, a complete provider
521
+ * object is inserted into `providers` — baseURL points at the local proxy path for
522
+ * this site — then the models are written by the same text-level path as before.
523
+ * The legacy `codebuddy` block is never located or edited.
524
+ */
525
+ export function writeProvider(deps: WriteProviderDeps): WriteModelsResult {
526
+ const read = deps.readFile ?? ((p: string) => readFileSync(p, "utf8"))
527
+ const write = deps.writeFile ?? ((p: string, c: string) => writeFileSync(p, c, "utf8"))
528
+ let original: string
529
+ try {
530
+ original = read(deps.jsoncPath)
531
+ } catch {
532
+ return { status: "skipped", reason: "config file could not be read" }
533
+ }
534
+
535
+ const bare = stripComments(original)
536
+ if (!isJsonObject(bare)) {
537
+ return { status: "skipped", reason: "config file is not valid JSON/JSONC" }
538
+ }
539
+
540
+ // An explicitly provided package version must be valid; never silently fall
541
+ // back, or a stray value could reach the provider's `package` spec downstream.
542
+ if (deps.packageVersion !== undefined && deps.packageVersion !== null && !isVersion(deps.packageVersion)) {
543
+ return { status: "skipped", reason: "invalid package version" }
544
+ }
545
+
546
+ const port = deps.proxyPort ?? 7688
547
+ const site = deps.providerId === "codebuddy-intl" ? "intl" : "cn"
548
+ const baseURL = `http://127.0.0.1:${port}/${site}/v2`
549
+
550
+ let text = original
551
+ if (!locateProvider(bare, deps.providerId)) {
552
+ // Locate the `providers` object and insert a new member just inside it.
553
+ const root = objectAt(bare, skipSpace(bare, 0))
554
+ const providers = root && memberObject(bare, root.open, "providers")
555
+ if (!providers) {
556
+ return { status: "skipped", reason: "could not locate providers object in the config text" }
557
+ }
558
+ const eol = newlineOf(original)
559
+ // Indent relative to the `providers` line, not the (possibly empty) line
560
+ // just after `{`, so a freshly inserted block is never flush-left.
561
+ const indent = `${indentOf(original, providers.open)} `
562
+ const pkg = isVersion(deps.packageVersion) ? packageSpec(deps.packageVersion) : packageSpec("2.0.90")
563
+ // Only append a comma when the object already has a member; appending one
564
+ // to an empty `{}` yields `},}}` which is only "valid" because trailing
565
+ // commas get blanked out — two bugs cancelling each other.
566
+ const inner = bare.slice(providers.open + 1, providers.close)
567
+ const hadMembers = skipSpace(bare, providers.open + 1) < providers.close && inner.trim().length > 0
568
+ const block =
569
+ `${eol}${indent}${JSON.stringify(deps.providerId)}: {` +
570
+ `${eol}${indent} "name": ${JSON.stringify(deps.providerId)},` +
571
+ `${eol}${indent} "package": ${JSON.stringify(pkg)},` +
572
+ `${eol}${indent} "compatibility": { "reasoningField": "reasoning_content" },` +
573
+ `${eol}${indent} "settings": { "baseURL": ${JSON.stringify(baseURL)}, "apiKey": "" },` +
574
+ `${eol}${indent} "models": {}` +
575
+ `${eol}${indent}}${hadMembers ? "," : ""}`
576
+ text = `${original.slice(0, providers.open + 1)}${block}${original.slice(providers.open + 1)}`
577
+ }
578
+
579
+ if (text === original) {
580
+ // Provider exists: delegate straight to the models writer.
581
+ return writeModels({
582
+ ...deps,
583
+ providerId: deps.providerId,
584
+ readFile: () => original,
585
+ writeFile: deps.writeFile,
586
+ backup: deps.backup,
587
+ })
588
+ }
589
+
590
+ // Freshly inserted provider: write its models into the intermediate text, then
591
+ // commit once. The writer callback captures the rendered text.
592
+ let committed = ""
593
+ const final = writeModels({
594
+ ...deps,
595
+ providerId: deps.providerId,
596
+ readFile: () => text,
597
+ writeFile: (_p, c) => { committed = c },
598
+ backup: undefined,
599
+ })
600
+ if (final.status === "skipped") return final
601
+ if (final.status === "written") {
602
+ // Final gate: the new provider must land under `providers` alongside the
603
+ // originals — never somewhere else in the file.
604
+ const originalKeys = Object.keys(
605
+ (((JSON.parse(stripComments(original)) as { providers?: Record<string, unknown> }).providers) ?? {}),
606
+ )
607
+ const renderedKeys = Object.keys(
608
+ (((JSON.parse(stripComments(committed)) as { providers?: Record<string, unknown> }).providers) ?? {}),
609
+ )
610
+ const expected = [...originalKeys, deps.providerId].sort().join("\u0000")
611
+ if (renderedKeys.sort().join("\u0000") !== expected) {
612
+ return { status: "skipped", reason: "provider block did not land under providers; refusing to write" }
613
+ }
614
+ if (fileChangedOnDisk(deps, original)) {
615
+ return { status: "skipped", reason: "config file changed on disk while editing; refusing to overwrite" }
616
+ }
617
+ deps.backup?.(deps.jsoncPath, original)
618
+ write(deps.jsoncPath, committed)
619
+ }
620
+ return final
621
+ }