From ef4dee44d52179de10348b0b9b9fa9ff511ec1f0 Mon Sep 17 00:00:00 2001 From: Chris Ostrouchov Date: Sun, 8 Nov 2026 13:56:41 -0500 Subject: [PATCH 1/3] fix(ai-config): treat a blank providers.json as missing The first mutation creates providers.json with an exclusive open and then writes the seed through that descriptor. A process stopped between the two, such as an extension host killed by a window reload, leaves an empty file. Every reader then reported it as invalid JSONC, mutations aborted until the file was fixed, and nothing ever reseeded it, because the exclusive open sees the file exists. An empty or whitespace-only file holds no configuration, so readers now treat it as missing and the next mutation seeds it as if it had created it. This also repairs files that are already blank. --- .../src/__tests__/load-config.test.ts | 12 ++++++++++- .../src/__tests__/mutate-config.test.ts | 18 ++++++++++++++++ .../read-user-custom-provider-entries.test.ts | 9 ++++++++ packages/ai-config/src/node/load-config.ts | 5 +++++ packages/ai-config/src/node/mutate-config.ts | 21 ++++++++++++------- packages/ai-config/src/node/parse-jsonc.ts | 10 +++++++++ .../node/read-user-custom-provider-entries.ts | 5 +++++ 7 files changed, 72 insertions(+), 8 deletions(-) diff --git a/packages/ai-config/src/__tests__/load-config.test.ts b/packages/ai-config/src/__tests__/load-config.test.ts index adf3108d..a6d21c7d 100644 --- a/packages/ai-config/src/__tests__/load-config.test.ts +++ b/packages/ai-config/src/__tests__/load-config.test.ts @@ -9,7 +9,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createConfigFileFixture } from "../../tests/helpers/config-file-fixture.js"; import type { ConfigFileFixture } from "../../tests/helpers/config-file-fixture.js"; import { loadProviderCatalogReport, loadResolvedProviderCatalog } from "../node/load-catalog.js"; -import { readEnvFragment } from "../node/load-config.js"; +import { readEnvFragment, readFileConfig } from "../node/load-config.js"; import type { ResolvedProvider } from "../types.js"; import { BUILTIN_PROVIDER_IDS } from "../vocabulary.js"; @@ -184,6 +184,16 @@ describe("loadResolvedProviderCatalog", () => { expect(findProvider(catalog, "anthropic")?.enabled).toBe(true); }); + it("reads a blank file as missing, without an issue", async () => { + await fixture.writeRawJsonc(""); + + const report = await readFileConfig(configPath); + + expect(report.layer.state).toBe("missing"); + expect(report.source?.config).toEqual({}); + expect(report.issues).toEqual([]); + }); + it("should return all built-in providers for empty config", async () => { await fixture.writeTypedConfig({}); diff --git a/packages/ai-config/src/__tests__/mutate-config.test.ts b/packages/ai-config/src/__tests__/mutate-config.test.ts index 4ff05127..1b5ff9c0 100644 --- a/packages/ai-config/src/__tests__/mutate-config.test.ts +++ b/packages/ai-config/src/__tests__/mutate-config.test.ts @@ -480,6 +480,24 @@ describe("mutateProvidersConfig first creation and seed boundaries", () => { expect(content.version).toBe(PROVIDERS_CONFIG_VERSION); }); + it.each([ + ["an empty", ""], + ["a whitespace-only", " \n"], + ])("seeds %s file left by an interrupted creation", async (_, blank) => { + await fixture.writeRawJsonc(blank); + + const wrote = await mutateProvidersConfig( + (current) => ({ ...current, providers: { anthropic: { enabled: true } } }), + { configPath, logger: mockLogger }, + ); + + expect(wrote).toBe(true); + const content = JSON.parse(await fixture.readRaw()); + expect(content.providers?.anthropic?.enabled).toBe(true); + expect(content.$schema).toBe(PROVIDERS_SCHEMA_URL); + expect(content.version).toBe(PROVIDERS_CONFIG_VERSION); + }); + it("does NOT re-inject $schema/version when a user removes them", async () => { // Create an initial file without $schema or version await fixture.writeTypedConfig({ diff --git a/packages/ai-config/src/__tests__/read-user-custom-provider-entries.test.ts b/packages/ai-config/src/__tests__/read-user-custom-provider-entries.test.ts index 6c3aec46..5a604985 100644 --- a/packages/ai-config/src/__tests__/read-user-custom-provider-entries.test.ts +++ b/packages/ai-config/src/__tests__/read-user-custom-provider-entries.test.ts @@ -58,6 +58,15 @@ describe("readUserCustomProviderEntries", () => { ).resolves.toEqual(new Map()); }); + it("returns an empty map when providers.json is blank", async () => { + const fixture = await configFixture(); + await fixture.writeRawJsonc(""); + + await expect( + readUserCustomProviderEntries({ configPath: fixture.configPath }), + ).resolves.toEqual(new Map()); + }); + it("returns an empty map for an empty custom map", async () => { const fixture = await configFixture(); await fixture.writeTypedConfig({ version: 1, providers: { custom: {} } }); diff --git a/packages/ai-config/src/node/load-config.ts b/packages/ai-config/src/node/load-config.ts index 83b577e5..b38b2493 100644 --- a/packages/ai-config/src/node/load-config.ts +++ b/packages/ai-config/src/node/load-config.ts @@ -13,6 +13,7 @@ import type { ProviderConfigSource } from "../resolve-catalog.js"; import { salvageProvidersConfigFragment } from "../salvage-config.js"; import type { SalvageFailureReason } from "../salvage-config.js"; import type { LoggerLike } from "../types.js"; +import { isBlankConfigText } from "./parse-jsonc.js"; import { parseProvidersConfigTolerant } from "./parse-providers-config.js"; import { DEFAULT_ENV_VAR, ENFORCED_ENV_VAR, PROVIDERS_CONFIG_PATH } from "./paths.js"; @@ -94,6 +95,10 @@ export async function readFileConfig(configPath: string): Promise issue.severity === "error"); diff --git a/packages/ai-config/src/node/mutate-config.ts b/packages/ai-config/src/node/mutate-config.ts index f511585c..33f1d1d4 100644 --- a/packages/ai-config/src/node/mutate-config.ts +++ b/packages/ai-config/src/node/mutate-config.ts @@ -24,7 +24,7 @@ import { PROVIDERS_CONFIG_VERSION } from "../index.js"; import { isPlainObject } from "../is-plain-object.js"; import { providersConfigSchema } from "../schema.js"; import type { ProvidersConfig } from "../types.js"; -import { parseJsonc } from "./parse-jsonc.js"; +import { isBlankConfigText, parseJsonc } from "./parse-jsonc.js"; import { parseProvidersConfig } from "./parse-providers-config.js"; import { LEGACY_PROVIDERS_SCHEMA_PATH, @@ -233,6 +233,10 @@ async function performLockedMutation( // Re-read current state under lock const { raw, config: current } = await readCurrentConfig(configPath); + // A blank file is one whose creation was interrupted before its seed + // was written: seed it now, as if this call had created it. + const seeding = fileCreated || isBlankConfigText(raw); + // Apply mutation let updated = await mutator(current); @@ -240,10 +244,10 @@ async function performLockedMutation( // into the first mutation result so mutators don't need to preserve them. // This is seed-only — subsequent mutations pass through whatever the // user/mutator wrote. If a user later removes $schema, that's their choice. - if (fileCreated && updated.$schema === undefined) { + if (seeding && updated.$schema === undefined) { updated = { $schema: PROVIDERS_SCHEMA_URL, ...updated }; } - if (fileCreated && updated.version === undefined) { + if (seeding && updated.version === undefined) { updated = { ...updated, version: PROVIDERS_CONFIG_VERSION }; } @@ -264,7 +268,7 @@ async function performLockedMutation( } const normalized = normalizeJsonValue(result.data); - const output = fileCreated ? JSON.stringify(normalized, null, 2) : editJsonc(raw, result.data); + const output = seeding ? JSON.stringify(normalized, null, 2) : editJsonc(raw, result.data); if (output === raw) { logger?.debug("[ai-config] Config mutation made no changes"); @@ -296,14 +300,15 @@ async function performLockedMutation( * after race-safe creation, an unreadable or missing file is anomalous, and * treating invalid content as `{}` would silently discard user configuration. * Invalid content throws {@link ProvidersConfigInvalidError} so hosts can say - * why; read failures throw a plain error. + * why; read failures throw a plain error. A blank file holds no configuration + * to discard, so it reads as `{}`. */ async function readCurrentConfig( configPath: string, ): Promise<{ raw: string; config: ProvidersConfig }> { try { const raw = await fs.readFile(configPath, "utf-8"); - return { raw, config: parseProvidersConfig(raw) }; + return { raw, config: isBlankConfigText(raw) ? {} : parseProvidersConfig(raw) }; } catch (error) { const invalid = existingFileInvalidError(configPath, error); if (invalid) { @@ -346,7 +351,9 @@ async function atomicWrite(configPath: string, text: string): Promise { * where two concurrent callers both observe ENOENT and then one clobbers the * other's completed write with an empty `{}`. * - * On file creation, seeds the file with `$schema` and `version` fields. + * On file creation, seeds the file with `$schema` and `version` fields. The + * open and the write are separate steps, so a process stopped between them + * leaves a blank file; readers and the next mutation treat that as missing. * * @returns `true` if this call created the file (first write), `false` if * it already existed. The caller uses this to inject seed metadata into diff --git a/packages/ai-config/src/node/parse-jsonc.ts b/packages/ai-config/src/node/parse-jsonc.ts index f514f164..bb594acc 100644 --- a/packages/ai-config/src/node/parse-jsonc.ts +++ b/packages/ai-config/src/node/parse-jsonc.ts @@ -31,6 +31,16 @@ export class JsoncSyntaxError extends SyntaxError { } } +/** + * Whether a config file's text is empty or whitespace only. Such a file holds + * no configuration, so readers and writers treat it as missing rather than as + * invalid JSONC: a writer interrupted between creating the file and seeding + * it leaves exactly this, and it must not lock the user out for good. + */ +export function isBlankConfigText(text: string): boolean { + return text.trim() === ""; +} + /** Parse JSONC into null-prototype objects, throwing `JsoncSyntaxError` on invalid input. */ export function parseJsonc(text: string): unknown { const errors: ParseError[] = []; diff --git a/packages/ai-config/src/node/read-user-custom-provider-entries.ts b/packages/ai-config/src/node/read-user-custom-provider-entries.ts index 759ec888..e000ffc3 100644 --- a/packages/ai-config/src/node/read-user-custom-provider-entries.ts +++ b/packages/ai-config/src/node/read-user-custom-provider-entries.ts @@ -5,6 +5,7 @@ import { promises as fs } from "node:fs"; import type { CustomProviderEntry } from "../types.js"; +import { isBlankConfigText } from "./parse-jsonc.js"; import { parseProvidersConfig } from "./parse-providers-config.js"; import { PROVIDERS_CONFIG_PATH } from "./paths.js"; @@ -50,6 +51,10 @@ export async function readUserCustomProviderEntries( ); } + if (isBlankConfigText(raw)) { + return new Map(); + } + try { const customProviders = parseProvidersConfig(raw).providers?.custom ?? {}; return new Map(Object.entries(customProviders)); From 8a57af467ce2c399c68eab1dd215b0424d63f791 Mon Sep 17 00:00:00 2001 From: Chris Ostrouchov Date: Sun, 8 Nov 2026 20:37:48 -0500 Subject: [PATCH 2/3] Report a blank providers.json as empty, and test the repair Label a blank file as empty rather than missing, since it exists, which is what a settings report shows. Note that a comments-only file stays invalid, document that repairing a blank file reports true, and test that loading a blank file raises no issue or warning and that repairing one with an unchanged config still writes the seed. --- .../src/__tests__/load-config.test.ts | 26 ++++++++++++------- .../src/__tests__/mutate-config.test.ts | 14 ++++++++++ packages/ai-config/src/node/load-config.ts | 2 +- packages/ai-config/src/node/mutate-config.ts | 3 ++- packages/ai-config/src/node/parse-jsonc.ts | 5 ++-- 5 files changed, 36 insertions(+), 14 deletions(-) diff --git a/packages/ai-config/src/__tests__/load-config.test.ts b/packages/ai-config/src/__tests__/load-config.test.ts index a6d21c7d..0a3f14a5 100644 --- a/packages/ai-config/src/__tests__/load-config.test.ts +++ b/packages/ai-config/src/__tests__/load-config.test.ts @@ -184,16 +184,6 @@ describe("loadResolvedProviderCatalog", () => { expect(findProvider(catalog, "anthropic")?.enabled).toBe(true); }); - it("reads a blank file as missing, without an issue", async () => { - await fixture.writeRawJsonc(""); - - const report = await readFileConfig(configPath); - - expect(report.layer.state).toBe("missing"); - expect(report.source?.config).toEqual({}); - expect(report.issues).toEqual([]); - }); - it("should return all built-in providers for empty config", async () => { await fixture.writeTypedConfig({}); @@ -1088,6 +1078,22 @@ describe("loadResolvedProviderCatalog", () => { // ======================================================================== describe("whole-source failures", () => { + it("reads a blank file as empty, without an issue", async () => { + await fixture.writeRawJsonc(" \n"); + + const report = await loadProviderCatalogReport({ + envVars: process.env, + configPath, + logger: mockLogger, + }); + const file = await readFileConfig(configPath); + + expect(report.issues).toEqual([]); + expect(mockLogger.warn).not.toHaveBeenCalled(); + expect(file.layer.state).toBe("empty"); + expect(file.source?.config).toEqual({}); + }); + it("reports a syntax error as an error-severity issue with line and column", async () => { // Missing comma after the `providers` block: the parser reports // CommaExpected at the `"version"` token on line 3. diff --git a/packages/ai-config/src/__tests__/mutate-config.test.ts b/packages/ai-config/src/__tests__/mutate-config.test.ts index 1b5ff9c0..c751e44c 100644 --- a/packages/ai-config/src/__tests__/mutate-config.test.ts +++ b/packages/ai-config/src/__tests__/mutate-config.test.ts @@ -498,6 +498,20 @@ describe("mutateProvidersConfig first creation and seed boundaries", () => { expect(content.version).toBe(PROVIDERS_CONFIG_VERSION); }); + it("repairs a blank file when the mutation changes nothing", async () => { + await fixture.writeRawJsonc(""); + + const wrote = await mutateProvidersConfig((current) => current, { + configPath, + logger: mockLogger, + }); + + expect(wrote).toBe(true); + const content = JSON.parse(await fixture.readRaw()); + expect(content.$schema).toBe(PROVIDERS_SCHEMA_URL); + expect(content.version).toBe(PROVIDERS_CONFIG_VERSION); + }); + it("does NOT re-inject $schema/version when a user removes them", async () => { // Create an initial file without $schema or version await fixture.writeTypedConfig({ diff --git a/packages/ai-config/src/node/load-config.ts b/packages/ai-config/src/node/load-config.ts index b38b2493..05419be6 100644 --- a/packages/ai-config/src/node/load-config.ts +++ b/packages/ai-config/src/node/load-config.ts @@ -96,7 +96,7 @@ export async function readFileConfig(configPath: string): Promise(configPath: string, fn: () => Promise): Promise { * @param opts - Optional path override and logger. * @returns `true` if the mutation wrote new content to the file, `false` if * the result was unchanged and nothing was written. (Creating a missing file - * whose only content is the seed metadata reports `false`.) + * whose only content is the seed metadata reports `false`. Repairing a blank + * file reports `true`.) */ export async function mutateProvidersConfig( mutator: (current: ProvidersConfig) => ProvidersConfig | Promise, diff --git a/packages/ai-config/src/node/parse-jsonc.ts b/packages/ai-config/src/node/parse-jsonc.ts index bb594acc..bf5589bd 100644 --- a/packages/ai-config/src/node/parse-jsonc.ts +++ b/packages/ai-config/src/node/parse-jsonc.ts @@ -33,9 +33,10 @@ export class JsoncSyntaxError extends SyntaxError { /** * Whether a config file's text is empty or whitespace only. Such a file holds - * no configuration, so readers and writers treat it as missing rather than as + * no configuration, so readers and writers treat it as empty rather than as * invalid JSONC: a writer interrupted between creating the file and seeding - * it leaves exactly this, and it must not lock the user out for good. + * it leaves exactly this, and it must not lock the user out for good. A file + * holding only comments is still invalid, since a user wrote it. */ export function isBlankConfigText(text: string): boolean { return text.trim() === ""; From 527c53526de7fcdfdb22ea80f6c6a7cf7aa959fc Mon Sep 17 00:00:00 2001 From: Winston Chang Date: Thu, 12 Nov 2026 13:29:02 -0600 Subject: [PATCH 3/3] Own the blank-file rule in the providers.json parse seam parseProvidersConfig and parseProvidersConfigTolerant now read blank text as {}, so the loader, the custom-entry reader, and the mutation no longer each repeat the check. The mutation still checks blank text to decide whether to seed. Also: correct the raceSafeEnsureFile comment (readers report a blank file as empty, and other processes can see it blank during a normal creation), test that a comment-only file stays invalid, and update the ai-config memory bank, which still said a zero-byte file is invalid. --- memory-bank/aiConfig.md | 13 +++++++--- .../src/__tests__/load-config.test.ts | 18 +++++++++++++ packages/ai-config/src/node/load-config.ts | 5 ---- packages/ai-config/src/node/mutate-config.ts | 12 +++++---- packages/ai-config/src/node/parse-jsonc.ts | 11 -------- .../src/node/parse-providers-config.ts | 26 ++++++++++++++++--- .../node/read-user-custom-provider-entries.ts | 5 ---- 7 files changed, 56 insertions(+), 34 deletions(-) diff --git a/memory-bank/aiConfig.md b/memory-bank/aiConfig.md index 9ba5fd25..c0dd00bd 100644 --- a/memory-bank/aiConfig.md +++ b/memory-bank/aiConfig.md @@ -345,9 +345,10 @@ from severity, scope, path and source). It is read-only and silent, and shares t - **Read state.** Each reader's report carries a `layer` (`ProviderConfigLayer`, the ref plus its source `kind`). The user file is `missing` (ENOENT), `invalid` (unreadable, bad JSONC, or a - whole-file salvage failure; a zero-byte file is invalid, as its issue says), `empty` (sets no - `providers`/`agentEngines` key) or `found`; env payloads and legacy layers are `not set` when - absent. + whole-file salvage failure; a comment-only file is invalid), `empty` (sets no + `providers`/`agentEngines` key, or is blank: zero bytes or whitespace only, with no issue) or + `found`; env payloads and legacy layers are `not set` when absent. `parseProvidersConfig` and + `parseProvidersConfigTolerant` own the blank rule, so every reader and the mutation path agree. - **No second copy of precedence.** `resolveProviderCatalogReport` and the explainer both run `foldProviderCatalog` (rank, recover, enablement layers, `agentEngines` fold). The explainer replays the same merge step (`foldConfigLayers`, also used by `mergeAndValidate` and the @@ -558,7 +559,11 @@ without managing locking, atomicity, or watch lifecycle themselves. a `proper-lockfile` lock (with retries and stale detection), an in-process serialization queue per config path, race-safe first-creation via the exclusive `wx` flag, atomic write (temp file + rename), and seed-metadata - injection (`$schema`, `version`) on first creation. `$schema` is seeded with + injection (`$schema`, `version`) on first creation. Creation opens the file + and writes the seed before the lock, so the file can be blank in between (or + for good, if the writer stops there); a mutation that finds it blank seeds it + as if it had created it, writes through `atomicWrite`, and returns `true`. + `$schema` is seeded with `PROVIDERS_SCHEMA_URL` (`node/paths.ts`), the hosted `providers.schema.json` at `assistant.posit.co/schemas/providers.schema.json` — editors resolve and cache that URL natively, so no local sidecar file or diff --git a/packages/ai-config/src/__tests__/load-config.test.ts b/packages/ai-config/src/__tests__/load-config.test.ts index 0a3f14a5..f5ff79b1 100644 --- a/packages/ai-config/src/__tests__/load-config.test.ts +++ b/packages/ai-config/src/__tests__/load-config.test.ts @@ -1094,6 +1094,24 @@ describe("loadResolvedProviderCatalog", () => { expect(file.source?.config).toEqual({}); }); + it("reads a comment-only file as invalid", async () => { + await fixture.writeRawJsonc("// nothing\n"); + + const report = await loadProviderCatalogReport({ + envVars: process.env, + configPath, + }); + const file = await readFileConfig(configPath); + + expect(report.issues).toEqual([ + expect.objectContaining({ + severity: "error", + message: expect.stringContaining("Invalid JSONC"), + }), + ]); + expect(file.layer.state).toBe("invalid"); + }); + it("reports a syntax error as an error-severity issue with line and column", async () => { // Missing comma after the `providers` block: the parser reports // CommaExpected at the `"version"` token on line 3. diff --git a/packages/ai-config/src/node/load-config.ts b/packages/ai-config/src/node/load-config.ts index 05419be6..83b577e5 100644 --- a/packages/ai-config/src/node/load-config.ts +++ b/packages/ai-config/src/node/load-config.ts @@ -13,7 +13,6 @@ import type { ProviderConfigSource } from "../resolve-catalog.js"; import { salvageProvidersConfigFragment } from "../salvage-config.js"; import type { SalvageFailureReason } from "../salvage-config.js"; import type { LoggerLike } from "../types.js"; -import { isBlankConfigText } from "./parse-jsonc.js"; import { parseProvidersConfigTolerant } from "./parse-providers-config.js"; import { DEFAULT_ENV_VAR, ENFORCED_ENV_VAR, PROVIDERS_CONFIG_PATH } from "./paths.js"; @@ -95,10 +94,6 @@ export async function readFileConfig(configPath: string): Promise issue.severity === "error"); diff --git a/packages/ai-config/src/node/mutate-config.ts b/packages/ai-config/src/node/mutate-config.ts index 99e3d5e1..d1f10fca 100644 --- a/packages/ai-config/src/node/mutate-config.ts +++ b/packages/ai-config/src/node/mutate-config.ts @@ -24,8 +24,8 @@ import { PROVIDERS_CONFIG_VERSION } from "../index.js"; import { isPlainObject } from "../is-plain-object.js"; import { providersConfigSchema } from "../schema.js"; import type { ProvidersConfig } from "../types.js"; -import { isBlankConfigText, parseJsonc } from "./parse-jsonc.js"; -import { parseProvidersConfig } from "./parse-providers-config.js"; +import { parseJsonc } from "./parse-jsonc.js"; +import { isBlankConfigText, parseProvidersConfig } from "./parse-providers-config.js"; import { LEGACY_PROVIDERS_SCHEMA_PATH, PROVIDERS_CONFIG_PATH, @@ -309,7 +309,7 @@ async function readCurrentConfig( ): Promise<{ raw: string; config: ProvidersConfig }> { try { const raw = await fs.readFile(configPath, "utf-8"); - return { raw, config: isBlankConfigText(raw) ? {} : parseProvidersConfig(raw) }; + return { raw, config: parseProvidersConfig(raw) }; } catch (error) { const invalid = existingFileInvalidError(configPath, error); if (invalid) { @@ -353,8 +353,10 @@ async function atomicWrite(configPath: string, text: string): Promise { * other's completed write with an empty `{}`. * * On file creation, seeds the file with `$schema` and `version` fields. The - * open and the write are separate steps, so a process stopped between them - * leaves a blank file; readers and the next mutation treat that as missing. + * open and the write are separate steps taken before the lock, so other + * processes can see the file blank in between, and a process stopped there + * leaves it blank. Readers report a blank file as empty, and the next + * mutation seeds it. * * @returns `true` if this call created the file (first write), `false` if * it already existed. The caller uses this to inject seed metadata into diff --git a/packages/ai-config/src/node/parse-jsonc.ts b/packages/ai-config/src/node/parse-jsonc.ts index bf5589bd..f514f164 100644 --- a/packages/ai-config/src/node/parse-jsonc.ts +++ b/packages/ai-config/src/node/parse-jsonc.ts @@ -31,17 +31,6 @@ export class JsoncSyntaxError extends SyntaxError { } } -/** - * Whether a config file's text is empty or whitespace only. Such a file holds - * no configuration, so readers and writers treat it as empty rather than as - * invalid JSONC: a writer interrupted between creating the file and seeding - * it leaves exactly this, and it must not lock the user out for good. A file - * holding only comments is still invalid, since a user wrote it. - */ -export function isBlankConfigText(text: string): boolean { - return text.trim() === ""; -} - /** Parse JSONC into null-prototype objects, throwing `JsoncSyntaxError` on invalid input. */ export function parseJsonc(text: string): unknown { const errors: ParseError[] = []; diff --git a/packages/ai-config/src/node/parse-providers-config.ts b/packages/ai-config/src/node/parse-providers-config.ts index 8fc03d80..13cf599c 100644 --- a/packages/ai-config/src/node/parse-providers-config.ts +++ b/packages/ai-config/src/node/parse-providers-config.ts @@ -11,17 +11,35 @@ import type { ProvidersConfig } from "../types.js"; import { parseJsonc } from "./parse-jsonc.js"; /** - * Parse providers.json as JSONC and validate its complete on-disk shape. + * Whether providers.json text is empty or whitespace only. Such a file holds + * no configuration, so it parses as `{}` rather than as invalid JSONC: another + * process sees exactly this while a first mutation is between creating the + * file and seeding it, and a writer stopped there leaves it behind for good. + * A file holding only comments is still invalid, since only a user writes + * comments. + */ +export function isBlankConfigText(text: string): boolean { + return text.trim() === ""; +} + +/** + * Parse providers.json as JSONC and validate its complete on-disk shape. Blank + * text is `{}`. * * Syntax failures propagate as `SyntaxError`; schema failures propagate as a * Zod error. Loaders can therefore report and degrade by failure kind, while * mutations can abort without duplicating either policy. */ export function parseProvidersConfig(text: string): ProvidersConfig { - return providersConfigSchema.parse(parseJsonc(text)); + return isBlankConfigText(text) ? {} : providersConfigSchema.parse(parseJsonc(text)); } -/** Parse JSONC syntax, then salvage independently valid provider blocks. */ +/** + * Parse JSONC syntax, then salvage independently valid provider blocks. Blank + * text is `{}`, with no issues. + */ export function parseProvidersConfigTolerant(text: string): SalvagedProvidersConfig { - return salvageProvidersConfig(parseJsonc(text)); + return isBlankConfigText(text) + ? { config: {}, issues: [] } + : salvageProvidersConfig(parseJsonc(text)); } diff --git a/packages/ai-config/src/node/read-user-custom-provider-entries.ts b/packages/ai-config/src/node/read-user-custom-provider-entries.ts index e000ffc3..759ec888 100644 --- a/packages/ai-config/src/node/read-user-custom-provider-entries.ts +++ b/packages/ai-config/src/node/read-user-custom-provider-entries.ts @@ -5,7 +5,6 @@ import { promises as fs } from "node:fs"; import type { CustomProviderEntry } from "../types.js"; -import { isBlankConfigText } from "./parse-jsonc.js"; import { parseProvidersConfig } from "./parse-providers-config.js"; import { PROVIDERS_CONFIG_PATH } from "./paths.js"; @@ -51,10 +50,6 @@ export async function readUserCustomProviderEntries( ); } - if (isBlankConfigText(raw)) { - return new Map(); - } - try { const customProviders = parseProvidersConfig(raw).providers?.custom ?? {}; return new Map(Object.entries(customProviders));