@gajae-code/coding-agent 0.21.0 → 0.21.1

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 (111) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/types/config/autorouting-contract.d.ts +4 -4
  3. package/dist/types/config/autorouting-tier-map.d.ts +1 -1
  4. package/dist/types/config/keybindings.d.ts +1 -5
  5. package/dist/types/config/model-profile-activation.d.ts +30 -3
  6. package/dist/types/config/model-registry.d.ts +2 -0
  7. package/dist/types/config/models-config-schema.d.ts +8 -0
  8. package/dist/types/config/settings-schema.d.ts +7 -3
  9. package/dist/types/coordinator-mcp/canonical-json.d.ts +7 -0
  10. package/dist/types/extensibility/gjc-plugins/metadata.d.ts +1 -1
  11. package/dist/types/harness-control-plane/receipts.d.ts +1 -1
  12. package/dist/types/modes/components/settings-selector.d.ts +5 -2
  13. package/dist/types/modes/controllers/command-controller.d.ts +1 -1
  14. package/dist/types/modes/controllers/input-controller.d.ts +12 -0
  15. package/dist/types/modes/controllers/selector-controller.d.ts +1 -1
  16. package/dist/types/modes/interactive-mode.d.ts +1 -1
  17. package/dist/types/modes/shared/agent-wire/workflow-gate-schema.d.ts +1 -1
  18. package/dist/types/modes/types.d.ts +1 -1
  19. package/dist/types/session/agent-session.d.ts +101 -6
  20. package/dist/types/session/session-manager.d.ts +124 -9
  21. package/dist/types/setup/provider-onboarding.d.ts +55 -2
  22. package/dist/types/slash-commands/builtin-registry.d.ts +11 -0
  23. package/dist/types/utils/clipboard.d.ts +18 -0
  24. package/dist/types/utils/pasted-image-path.d.ts +2 -0
  25. package/dist/types/web/search/providers/keenable.d.ts +30 -0
  26. package/dist/types/web/search/types.d.ts +2 -2
  27. package/package.json +7 -7
  28. package/scripts/generate-sdk-operation-inventory.ts +28 -0
  29. package/src/cli/doctor/config-repairs.ts +1 -4
  30. package/src/cli/local-provider-smoke.ts +1 -4
  31. package/src/cli/public-command-help.ts +1 -1
  32. package/src/config/autorouting-contract.ts +5 -8
  33. package/src/config/autorouting-tier-map.ts +1 -1
  34. package/src/config/keybindings.ts +1 -2
  35. package/src/config/model-profile-activation.ts +332 -28
  36. package/src/config/model-registry.ts +156 -8
  37. package/src/config/models-config-schema.ts +27 -0
  38. package/src/config/settings-schema.ts +6 -0
  39. package/src/coordinator-mcp/canonical-json.ts +15 -0
  40. package/src/coordinator-mcp/policy.ts +1 -0
  41. package/src/coordinator-mcp/question-gate-codec.ts +1 -2
  42. package/src/coordinator-mcp/question-state.ts +2 -12
  43. package/src/coordinator-mcp/server.ts +1 -10
  44. package/src/customization/import.ts +1 -5
  45. package/src/discovery/mcp-compat.ts +1 -5
  46. package/src/discovery/mcp-json.ts +1 -4
  47. package/src/edit/notebook.ts +1 -5
  48. package/src/extensibility/gjc-plugins/lifecycle.ts +1 -3
  49. package/src/extensibility/gjc-plugins/metadata.ts +2 -5
  50. package/src/extensibility/gjc-plugins/schema.ts +1 -4
  51. package/src/gjc-runtime/deep-interview-crystallize.ts +1 -4
  52. package/src/gjc-runtime/deep-interview-runtime.ts +1 -4
  53. package/src/gjc-runtime/state-renderer.ts +1 -5
  54. package/src/gjc-runtime/tmux-owner-isolation.ts +1 -3
  55. package/src/gjc-runtime/ultragoal-owner-loss-recovery.ts +1 -4
  56. package/src/gjc-runtime/ultragoal-succession.ts +1 -4
  57. package/src/goals/continuation-timeout-guard.ts +1 -4
  58. package/src/harness-control-plane/receipts.ts +1 -1
  59. package/src/internal-urls/docs-index.generated.ts +4 -4
  60. package/src/migrate/mcp-mapper.ts +2 -4
  61. package/src/modes/components/hook-editor.ts +4 -8
  62. package/src/modes/components/hook-selector.ts +3 -1
  63. package/src/modes/components/settings-selector.ts +26 -2
  64. package/src/modes/controllers/command-controller.ts +4 -98
  65. package/src/modes/controllers/extension-ui-controller.ts +6 -14
  66. package/src/modes/controllers/goal-mode-controller.ts +4 -4
  67. package/src/modes/controllers/input-controller.ts +110 -46
  68. package/src/modes/controllers/plan-mode-controller.ts +6 -10
  69. package/src/modes/controllers/selector-controller.ts +66 -23
  70. package/src/modes/controllers/todo-command-controller.ts +2 -2
  71. package/src/modes/interactive-mode.ts +2 -2
  72. package/src/modes/prompt-action-autocomplete.ts +1 -1
  73. package/src/modes/runtime-init.ts +4 -4
  74. package/src/modes/shared/agent-wire/workflow-gate-schema.ts +1 -1
  75. package/src/modes/types.ts +1 -1
  76. package/src/modes/utils/hotkeys-markdown.ts +1 -1
  77. package/src/runtime-mcp/client.ts +1 -4
  78. package/src/runtime-mcp/elicitation.ts +1 -5
  79. package/src/runtime-mcp/protocol.ts +2 -4
  80. package/src/sdk/broker/lifecycle-ledger.ts +1 -0
  81. package/src/sdk/broker/lifecycle.ts +1 -0
  82. package/src/sdk/cli/rows.ts +2 -3
  83. package/src/sdk/cli/session-cli.ts +2 -8
  84. package/src/sdk/host/query/cursor.ts +1 -0
  85. package/src/sdk/host/reverse-leases.ts +1 -0
  86. package/src/sdk/lifecycle/service.ts +1 -0
  87. package/src/sdk/protocol/operation-inventory.generated.json +154 -0
  88. package/src/session/agent-session.ts +1877 -224
  89. package/src/session/btw-prefix-ledger.ts +1 -4
  90. package/src/session/internal/managed-gc-retirement-codec.ts +1 -4
  91. package/src/session/session-manager.ts +732 -224
  92. package/src/session/task-artifact-owner-codec.ts +1 -4
  93. package/src/session-import/claude.ts +1 -4
  94. package/src/session-import/detect.ts +1 -6
  95. package/src/session-import/provider-codex.ts +1 -6
  96. package/src/session-import/provider-service.ts +4 -0
  97. package/src/setup/hermes-setup.ts +1 -4
  98. package/src/setup/provider-onboarding.ts +514 -26
  99. package/src/slash-commands/builtin-registry.ts +26 -13
  100. package/src/slash-commands/helpers/todo.ts +3 -1
  101. package/src/task/delegation-hint.ts +1 -4
  102. package/src/task/executor.ts +4 -2
  103. package/src/task/provider-retry-status.ts +1 -4
  104. package/src/tools/json-tree.ts +1 -4
  105. package/src/tools/recipe/runners/pkg.ts +1 -5
  106. package/src/utils/clipboard.ts +155 -2
  107. package/src/utils/mac-file-urls.applescript +37 -0
  108. package/src/utils/pasted-image-path.ts +5 -0
  109. package/src/web/search/provider.ts +6 -0
  110. package/src/web/search/providers/keenable.ts +207 -0
  111. package/src/web/search/types.ts +2 -0
@@ -1,7 +1,11 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import * as fs from "node:fs/promises";
3
3
  import * as path from "node:path";
4
- import { type AuthStorage, resolveOAuthStorageProvider } from "@gajae-code/ai/core";
4
+ import {
5
+ type AuthStorage,
6
+ isStoredApiKeyCredentialForProvider,
7
+ resolveOAuthStorageProvider,
8
+ } from "@gajae-code/ai/core";
5
9
  import {
6
10
  isSafeCatalogModelId,
7
11
  MODELS_LIST_REQUEST_TIMEOUT_MS,
@@ -10,12 +14,75 @@ import {
10
14
  import { getAgentDbPath, getAgentDir, logger } from "@gajae-code/utils";
11
15
  import { $rotatingCredentialEnv } from "@gajae-code/utils/env";
12
16
  import { YAML } from "bun";
17
+ import type { LoadResult } from "../config/config-file";
13
18
  import { withFileLock } from "../config/file-lock";
14
- import { type ModelsConfig, ModelsConfigSchema, type ProviderDiscovery } from "../config/models-config-schema";
19
+ import {
20
+ type ModelsConfig,
21
+ ModelsConfigSchema,
22
+ PROVIDER_CREDENTIAL_STORE,
23
+ type ProviderDiscovery,
24
+ } from "../config/models-config-schema";
15
25
  import { compareRankedProviders, famousProviderIndex } from "../config/provider-ranking";
16
26
  import { AuthStorage as AuthStorageImpl } from "../session/auth-storage";
17
27
  import providerPresets from "./provider-presets.json";
18
28
 
29
+ // Setup writes YAML, and the models reader parses JSON only for `.json`/`.jsonc`.
30
+ // Accepting those extensions here would rename YAML into a path the reader
31
+ // then rejects, after the config and credential were already committed.
32
+ const MODELS_CONFIG_PATH_EXTENSIONS = [".yml", ".yaml"] as const;
33
+
34
+ interface ModelsConfigFileLike {
35
+ relocate(configPath?: string): { invalidate(): void; tryLoad(): LoadResult<ModelsConfig> };
36
+ }
37
+
38
+ interface ModelRegistryModule {
39
+ validateModelsConfig(config: ModelsConfig): void;
40
+ ModelsConfigFile: ModelsConfigFileLike;
41
+ }
42
+
43
+ interface ConfigValueResolverModule {
44
+ resolveConfigValue(config: string, cacheScope?: string): Promise<string | undefined>;
45
+ }
46
+
47
+ // The models-config validator and loader live in model-registry, which is
48
+ // deliberately kept out of the eager `gjc setup <component>` module graph
49
+ // (#5949). Setup pays for it only when it validates or re-reads a provider
50
+ // config.
51
+ let modelRegistryModule: Promise<ModelRegistryModule> | undefined;
52
+ function loadModelRegistryModule(): Promise<ModelRegistryModule> {
53
+ if (!modelRegistryModule) {
54
+ const loading = import("../config/model-registry");
55
+ modelRegistryModule = loading;
56
+ // A rejected import must not memoize: a wizard retry after the environment
57
+ // is fixed has to be able to load the module again.
58
+ loading.catch(() => {
59
+ if (modelRegistryModule === loading) modelRegistryModule = undefined;
60
+ });
61
+ }
62
+ return modelRegistryModule;
63
+ }
64
+
65
+ // Stored credential values may be `!<command>` or env-name references. The
66
+ // runtime resolves them with this module's resolver, and setup must resolve
67
+ // them the same way before any value can reach a discovery request. Kept
68
+ // dynamic for the same eager-graph reason as the models registry.
69
+ let configValueResolverModule: Promise<ConfigValueResolverModule> | undefined;
70
+ function loadConfigValueResolverModule(): Promise<ConfigValueResolverModule> {
71
+ if (!configValueResolverModule) {
72
+ const loading = import("../config/resolve-config-value");
73
+ configValueResolverModule = loading;
74
+ loading.catch(() => {
75
+ if (configValueResolverModule === loading) configValueResolverModule = undefined;
76
+ });
77
+ }
78
+ return configValueResolverModule;
79
+ }
80
+
81
+ function assertModelsConfigPath(modelsPath: string): void {
82
+ if (MODELS_CONFIG_PATH_EXTENSIONS.some(extension => modelsPath.endsWith(extension))) return;
83
+ throw new Error(`Models config path must end with ${MODELS_CONFIG_PATH_EXTENSIONS.join(" or ")}: ${modelsPath}`);
84
+ }
85
+
19
86
  export type ProviderCompatibility = "openai" | "anthropic";
20
87
  export type ProviderSetupApi = "openai-responses" | "openai-completions" | "anthropic-messages";
21
88
 
@@ -77,12 +144,43 @@ export interface ProviderSetupResult {
77
144
  discoveryType?: string;
78
145
  preset?: string;
79
146
  presetName?: string;
147
+ /**
148
+ * Set only when a forced env replacement disabled stored API-key rows the
149
+ * replaced entry declared via `credential: store`. Present so setup can
150
+ * report the destructive half instead of silently dropping a credential.
151
+ * Rows are soft-disabled, not deleted: `gjc accounts list` shows them as
152
+ * `disabled` and `gjc accounts logout <provider> --all` removes them.
153
+ */
154
+ credentialCleanup?: { disabledApiKeys: number; envName: string };
155
+ /**
156
+ * Set when an env-source add succeeds while stored api_key rows for the
157
+ * provider remain. They outrank `apiKeyEnv` at runtime and are not removed
158
+ * by setup (the replaced entry never declared `credential: store`), so the
159
+ * success output must say the environment variable is being shadowed.
160
+ */
161
+ storedCredentialShadow?: { storedApiKeys: number; envName: string };
162
+ /**
163
+ * Set when an env-source add succeeds but the credential store could not be
164
+ * inspected, so setup cannot say whether stored api_key rows shadow the env
165
+ * var. Present so the success output discloses the unverified risk instead
166
+ * of reporting unconditional success.
167
+ */
168
+ storedCredentialShadowUnverified?: { envName: string };
80
169
  }
81
170
 
82
171
  type ProviderConfig = NonNullable<NonNullable<ModelsConfig["providers"]>[string]>;
83
172
  type ProviderCompatConfig = NonNullable<ProviderConfig["compat"]>;
84
- type ProviderSetupCredentialStore = Pick<AuthStorage, "set" | "remove" | "exportSnapshot"> & {
85
- peekApiKey?: (provider: string) => Promise<string | undefined>;
173
+ type ProviderSetupCredentialStore = Pick<
174
+ AuthStorage,
175
+ "set" | "remove" | "exportSnapshot" | "disableCredentialById" | "reload"
176
+ > & {
177
+ /**
178
+ * Resolves a stored api_key value the way the runtime does: a
179
+ * `!<command>` value is executed and an env-name value is read from the
180
+ * environment. Optional so test doubles can omit it; the probe then uses
181
+ * the raw stored value, refusing a command-backed reference it cannot run.
182
+ */
183
+ peekApiKey?: AuthStorage["peekApiKey"];
86
184
  };
87
185
 
88
186
  interface ProviderPreset {
@@ -162,6 +260,198 @@ export function parseModelList(values: readonly string[]): string[] {
162
260
  return [...new Set(models)];
163
261
  }
164
262
 
263
+ export function redactSecret(_secret: string): string {
264
+ return "***";
265
+ }
266
+
267
+ /**
268
+ * Raised when setup committed a config that replaces a `credential: store`
269
+ * declaration with an `apiKeyEnv` reference but could not disable the stored
270
+ * api_key rows. The config is rolled back before this reaches the caller, so
271
+ * the message always states both the failure and the recovery.
272
+ */
273
+ class CredentialCleanupError extends Error {
274
+ constructor(message: string, options?: ErrorOptions) {
275
+ super(message, options);
276
+ this.name = "CredentialCleanupError";
277
+ }
278
+ }
279
+
280
+ /**
281
+ * Recovery guidance shared by every cleanup failure. The add commands reject a
282
+ * raw `--api-key`, so a literal key can only be re-entered through the
283
+ * interactive wizard, while the command form re-adds the provider with an env
284
+ * reference.
285
+ */
286
+ function providerCredentialRecoveryHint(providerId: string): string {
287
+ return (
288
+ `Restore a working credential by running \`/provider\` with no arguments in the interactive TUI and pasting a literal key, ` +
289
+ `or by re-adding the provider with an env reference: ` +
290
+ `\`/provider add --compat <openai|anthropic> --provider ${providerId} --base-url <url> --api-key-env <ENV> (--model <id> | --discover) --force\` ` +
291
+ `(the same flags work on \`gjc setup provider\`).`
292
+ );
293
+ }
294
+
295
+ /**
296
+ * Disable this provider's stored api_key rows when setup replaces a
297
+ * `credential: store` entry with an `apiKeyEnv` reference. A stored api_key
298
+ * outranks the env indirection, so leaving it behind would keep resolving the
299
+ * old literal key. OAuth rows are never touched, and rows are soft-disabled
300
+ * (`gjc accounts list` shows them as `disabled`) rather than deleted.
301
+ *
302
+ * Only a confirmed disable (`disableCredentialById` returning `true`) counts:
303
+ * the store can swallow errors, and this count is what the user reasons about
304
+ * in a path that cannot restore the rows. Persistence is verified by
305
+ * re-reading the store, because remote (broker-owned) stores reject disables
306
+ * outright and a reload is the only proof the rows no longer resolve.
307
+ */
308
+ async function removeStoredApiKeyCredentials(store: ProviderSetupCredentialStore, providerId: string): Promise<number> {
309
+ const selectApiKeyRows = () =>
310
+ store.exportSnapshot().credentials.filter(entry => isStoredApiKeyCredentialForProvider(entry, providerId));
311
+ const apiKeyIds = selectApiKeyRows().map(entry => entry.id);
312
+ let disabledCount = 0;
313
+ for (const id of apiKeyIds) {
314
+ try {
315
+ if (
316
+ store.disableCredentialById(id, "provider setup switched to an environment-variable credential") === true
317
+ ) {
318
+ disabledCount += 1;
319
+ }
320
+ } catch (error) {
321
+ // Only this path proves the store refused the disable. A reload failure
322
+ // below has a different diagnosis and must not borrow this one.
323
+ throw new CredentialCleanupError(
324
+ `Provider '${providerId}' could not disable its stored API key credentials ` +
325
+ `(disabled ${disabledCount} of ${apiKeyIds.length} before the failure; disabled rows cannot be restored). ` +
326
+ `The credential store raised an error while disabling the rows (read-only, broker-owned, or a failure after a removal). ` +
327
+ `If a broker owns the credentials, disable them on the broker host with ` +
328
+ `\`gjc auth-broker logout ${providerId}\`, which applies to every credential type stored for this provider on the broker host, including OAuth rows; ` +
329
+ `for a local store, finish with \`gjc accounts logout ${providerId} --all\`, which removes every stored credential for this provider, including OAuth logins, and confirm with \`gjc accounts list\`. ` +
330
+ `The previous provider settings were restored; rows already disabled stay disabled, and rows not confirmed disabled still resolve and remain the provider's credential. ` +
331
+ providerCredentialRecoveryHint(providerId),
332
+ { cause: error },
333
+ );
334
+ }
335
+ }
336
+ try {
337
+ await store.reload();
338
+ } catch (error) {
339
+ // The disables were attempted; only the confirmation read failed. Rows may
340
+ // in fact be disabled, so this message must not claim a rejected disable.
341
+ throw new CredentialCleanupError(
342
+ `Provider '${providerId}': the store reported ${disabledCount} of ${apiKeyIds.length} stored API key credential(s) disabled, ` +
343
+ `but the confirmation read failed because the credential store could not be re-read. ` +
344
+ `Those rows may in fact be disabled. Confirm with \`gjc accounts list\` (disabled rows are listed as \`disabled\`), ` +
345
+ `then delete them with \`gjc accounts logout ${providerId} --all\`, which removes every stored credential for this provider, including OAuth logins. ` +
346
+ `The previous provider settings were restored; rows already disabled stay disabled, and rows whose disable was not confirmed may still resolve and remain the provider's credential. ` +
347
+ providerCredentialRecoveryHint(providerId),
348
+ { cause: error },
349
+ );
350
+ }
351
+ const remaining = selectApiKeyRows();
352
+ if (remaining.length > 0) {
353
+ throw new CredentialCleanupError(
354
+ `Provider '${providerId}' kept ${remaining.length} stored API key credential(s) after cleanup: ` +
355
+ `the store accepted the request but they still resolve. Delete them with ` +
356
+ `\`gjc accounts logout ${providerId} --all\`, which removes every stored credential for this provider, including OAuth logins, and confirm with \`gjc accounts list\`. ` +
357
+ `The previous provider settings were restored; rows already disabled stay disabled, and the surviving rows above still resolve and remain the provider's credential. ` +
358
+ providerCredentialRecoveryHint(providerId),
359
+ );
360
+ }
361
+ return disabledCount;
362
+ }
363
+
364
+ async function countStoredApiKeyCredentials(store: ProviderSetupCredentialStore, providerId: string): Promise<number> {
365
+ // Read persisted state: the in-memory snapshot can be ahead of the store.
366
+ await store.reload();
367
+ return store.exportSnapshot().credentials.filter(entry => isStoredApiKeyCredentialForProvider(entry, providerId))
368
+ .length;
369
+ }
370
+
371
+ /**
372
+ * A credential value may reach the network only when the runtime resolver has
373
+ * produced it: empty values and values that are still `!` references are
374
+ * unresolved and must be treated as absent.
375
+ */
376
+ function sanitizeResolvedCredentialValue(value: string | undefined): string | undefined {
377
+ const trimmed = value?.trim();
378
+ if (!trimmed || trimmed.startsWith("!")) return undefined;
379
+ return trimmed;
380
+ }
381
+
382
+ /**
383
+ * Resolve the stored api_key value a discovery probe may send. The invariant:
384
+ * a stored value reaches the network only when it was resolved by the same
385
+ * resolver the runtime uses. Presence is decided by the shared predicate; the
386
+ * value comes from the store's resolver when it has one, otherwise from the
387
+ * runtime's env-name-or-literal rule. Anything that is still a `!` reference
388
+ * after resolution is unresolved and is treated as absent.
389
+ *
390
+ * This is the only resolution path for both a caller-supplied store and the
391
+ * store setup opens itself.
392
+ */
393
+ async function resolveStoredApiKeyValue(
394
+ store: ProviderSetupCredentialStore,
395
+ providerId: string,
396
+ ): Promise<string | undefined> {
397
+ const rows = store
398
+ .exportSnapshot()
399
+ .credentials.filter(entry => isStoredApiKeyCredentialForProvider(entry, providerId));
400
+ if (rows.length === 0) return undefined;
401
+ let resolved: string | undefined;
402
+ if (store.peekApiKey) {
403
+ try {
404
+ resolved = await store.peekApiKey(providerId);
405
+ } catch {
406
+ // The stored value could not be resolved (for example its command failed).
407
+ return undefined;
408
+ }
409
+ } else {
410
+ const raw = rows[0]!.credential.key.trim();
411
+ // A command reference needs the store's resolver, which this store does not
412
+ // have; the remaining shape is the runtime's env-name-or-literal rule.
413
+ resolved = raw.startsWith("!") ? undefined : process.env[raw] || raw;
414
+ }
415
+ const value = resolved?.trim();
416
+ // Defense in depth for every store provenance: a resolver that returns the
417
+ // reference unchanged has not resolved it.
418
+ return sanitizeResolvedCredentialValue(value);
419
+ }
420
+
421
+ /**
422
+ * One construction for every store setup opens itself. The runtime resolver is
423
+ * injected so stored values and pasted literals resolve exactly as they do at
424
+ * request time (the default resolver treats a `!<command>` value as a literal).
425
+ */
426
+ async function createOwnedCredentialStore(): Promise<AuthStorageImpl> {
427
+ const { resolveConfigValue } = await loadConfigValueResolverModule();
428
+ return AuthStorageImpl.create(getAgentDbPath(), { configValueResolver: resolveConfigValue });
429
+ }
430
+
431
+ /**
432
+ * Resolve a pasted literal for the pre-write discovery probe. The value is
433
+ * stored verbatim and resolved by the same resolver at request time, so the
434
+ * probe must resolve it now: a `!<command>` or env-name-shaped paste otherwise
435
+ * diverges from what the runtime would send. Returns `undefined` when the
436
+ * reference cannot be resolved.
437
+ */
438
+ async function resolveLiteralApiKeyForProbe(value: string): Promise<string | undefined> {
439
+ const { resolveConfigValue } = await loadConfigValueResolverModule();
440
+ try {
441
+ return sanitizeResolvedCredentialValue(await resolveConfigValue(value));
442
+ } catch {
443
+ return undefined;
444
+ }
445
+ }
446
+
447
+ /**
448
+ * Pick the store a discovery probe resolves through. A caller-supplied store
449
+ * keeps the session's credential ranking (mode and preferences), so it resolves
450
+ * the same row a request would. The store setup opens itself has no session
451
+ * preferences: with multiple active rows it uses the store's default order,
452
+ * which can differ from a session that pins a preferred account. Setup never
453
+ * picks a row itself.
454
+ */
165
455
  async function resolveStoredApiKeyForProbe(
166
456
  providerId: string,
167
457
  inputStore: ProviderSetupCredentialStore | undefined,
@@ -169,28 +459,22 @@ async function resolveStoredApiKeyForProbe(
169
459
  let store = inputStore;
170
460
  let ownedStore: AuthStorageImpl | undefined;
171
461
  if (!store) {
172
- ownedStore = await AuthStorageImpl.create(getAgentDbPath());
462
+ ownedStore = await createOwnedCredentialStore();
173
463
  store = ownedStore;
174
464
  }
175
465
  try {
176
- const storageProvider = resolveOAuthStorageProvider(providerId);
177
- const snapshot = store.exportSnapshot();
178
- const hasStoredApiKey = snapshot.credentials.some(
179
- entry => entry.provider === storageProvider && entry.credential.type === "api_key",
180
- );
181
- if (!hasStoredApiKey) return undefined;
182
- if (store.peekApiKey) return (await store.peekApiKey(providerId))?.trim() || undefined;
183
- const entry = snapshot.credentials.find(
184
- candidate => candidate.provider === storageProvider && candidate.credential.type === "api_key",
185
- );
186
- return entry?.credential.type === "api_key" ? entry.credential.key.trim() || undefined : undefined;
466
+ return await resolveStoredApiKeyValue(store, providerId);
187
467
  } finally {
188
468
  ownedStore?.close();
189
469
  }
190
470
  }
191
471
 
192
- export function redactSecret(_secret: string): string {
193
- return "***";
472
+ function assertReplacementEnvResolves(providerId: string, envName: string): void {
473
+ if ($rotatingCredentialEnv(envName)?.trim()) return;
474
+ throw new Error(
475
+ `Cannot replace provider '${providerId}' with apiKeyEnv '${envName}': ${envName} is not set, so its stored API key would still take precedence. ` +
476
+ `Set ${envName} in the trusted environment, then re-run with --force. Nothing was changed.`,
477
+ );
194
478
  }
195
479
 
196
480
  function apiForCompatibility(compatibility: ProviderCompatibility): ProviderSetupApi {
@@ -365,11 +649,15 @@ function validateSetupInput(input: ProviderSetupInput): {
365
649
  }
366
650
 
367
651
  async function readModelsConfig(modelsPath: string): Promise<ModelsConfig> {
652
+ // The guard and the parse mode stay coupled: setup only writes YAML, and
653
+ // this reader only parses YAML, so an unsupported extension fails here
654
+ // before either half can drift.
655
+ assertModelsConfigPath(modelsPath);
368
656
  const file = Bun.file(modelsPath);
369
657
  if (!(await file.exists())) return {};
370
658
  const text = (await file.text()).trim();
371
659
  if (!text) return {};
372
- const parsed = modelsPath.endsWith(".json") || modelsPath.endsWith(".jsonc") ? JSON.parse(text) : YAML.parse(text);
660
+ const parsed = YAML.parse(text);
373
661
  const checked = ModelsConfigSchema.safeParse(parsed);
374
662
  if (!checked.success) {
375
663
  const first = checked.error.issues[0];
@@ -379,13 +667,30 @@ async function readModelsConfig(modelsPath: string): Promise<ModelsConfig> {
379
667
  return checked.data;
380
668
  }
381
669
 
382
- async function writeModelsConfig(modelsPath: string, config: ModelsConfig, signal?: AbortSignal): Promise<void> {
670
+ async function writeModelsConfig(
671
+ modelsPath: string,
672
+ config: ModelsConfig,
673
+ signal?: AbortSignal,
674
+ options: { bypassSemanticValidation?: boolean } = {},
675
+ ): Promise<void> {
383
676
  const checked = ModelsConfigSchema.safeParse(config);
384
677
  if (!checked.success) {
385
678
  const first = checked.error.issues[0];
386
679
  const where = first?.path.length ? `/${first.path.map(String).join("/")}` : "root";
387
680
  throw new Error(`Generated models config is invalid at ${where}: ${first?.message ?? "unknown schema error"}`);
388
681
  }
682
+ // The runtime loader applies semantic rules the zod schema cannot express.
683
+ // Run the loader's own validator before the atomic rename so setup never
684
+ // commits a file the product itself rejects. Restores bypass that check:
685
+ // after pre-rename validation the only reachable restore follows a
686
+ // concurrent external write, and restoring the prior document's semantics
687
+ // must not be refused merely because that document is already unloadable.
688
+ // The restore is re-serialized from the parsed config like every write, so
689
+ // comments and key order from the previous file are not preserved.
690
+ if (!options.bypassSemanticValidation) {
691
+ const { validateModelsConfig } = await loadModelRegistryModule();
692
+ validateModelsConfig(checked.data);
693
+ }
389
694
  const directory = path.dirname(modelsPath);
390
695
  await fs.mkdir(directory, { recursive: true });
391
696
  const tempPath = path.join(directory, `.${path.basename(modelsPath)}.${process.pid}.${randomUUID()}.tmp`);
@@ -418,10 +723,23 @@ async function writeModelsConfig(modelsPath: string, config: ModelsConfig, signa
418
723
  export async function addApiCompatibleProvider(input: ProviderSetupInput): Promise<ProviderSetupResult> {
419
724
  const validated = validateSetupInput(input);
420
725
  const modelsPath = input.modelsPath ?? getDefaultModelsPath();
726
+ assertModelsConfigPath(modelsPath);
727
+ // Evaluate the lazily imported registry module before taking the file lock:
728
+ // module evaluation has nothing to do with the config transaction and must
729
+ // not extend cross-process lock hold time.
730
+ await loadModelRegistryModule();
421
731
  const existing = await readModelsConfig(modelsPath);
422
732
  if (existing.providers?.[validated.providerId] && !input.force) {
423
733
  throw new Error(`Provider '${validated.providerId}' already exists. Use --force to replace it.`);
424
734
  }
735
+ // Cleanup only exists for a store-declared entry being switched to an env
736
+ // reference; anything else keeps its stored credential. The replacement env
737
+ // must also resolve, otherwise deleting the key would leave no credential.
738
+ const willRemoveStoredKey =
739
+ validated.credentialSource === "env" &&
740
+ input.force === true &&
741
+ existing.providers?.[validated.providerId]?.credential === PROVIDER_CREDENTIAL_STORE;
742
+ if (willRemoveStoredKey) assertReplacementEnvResolves(validated.providerId, validated.apiKey);
425
743
  // P2: a discovery-only add with no manual models must prove the endpoint
426
744
  // serves a catalog before config is written — otherwise an unreachable
427
745
  // endpoint or rejected credential would be recorded as configured while
@@ -437,14 +755,28 @@ export async function addApiCompatibleProvider(input: ProviderSetupInput): Promi
437
755
  if (validated.discovery?.type === "openai-models-list" && validated.models.length === 0 && !validated.preset) {
438
756
  const probe = input.probeDiscovery ?? probeOpenAIModelsList;
439
757
  const credentialSource = validated.credentialSource;
758
+ // Probe with the credential the runtime will resolve after this write. A
759
+ // stored api_key is dropped only for the store->env replacement above;
760
+ // otherwise it survives and outranks the env indirection (#5387).
440
761
  const storedApiKey =
441
- credentialSource === "env" && input.force
762
+ credentialSource === "env" && !willRemoveStoredKey
442
763
  ? await resolveStoredApiKeyForProbe(validated.providerId, input.authStorage)
443
764
  : undefined;
765
+ // A pasted literal is stored verbatim and resolved by the runtime resolver
766
+ // at request time, so the probe must resolve it now instead of sending a
767
+ // `!<command>` or env-name reference.
768
+ const literalApiKey =
769
+ credentialSource === "literal" ? await resolveLiteralApiKeyForProbe(validated.apiKey) : undefined;
770
+ if (credentialSource === "literal" && literalApiKey === undefined) {
771
+ throw new Error(
772
+ `Provider '${validated.providerId}' credential could not be resolved for model discovery: the pasted value is a command or environment reference that does not resolve. ` +
773
+ `Paste the key value itself, or pass \`--api-key-env <ENV>\` instead. No config or credential was written.`,
774
+ );
775
+ }
444
776
  const probed = await probe({
445
777
  baseUrl: validated.baseUrl,
446
778
  apiKeyEnv: credentialSource === "env" && !storedApiKey ? validated.apiKey : undefined,
447
- apiKey: credentialSource === "literal" ? validated.apiKey : storedApiKey,
779
+ apiKey: credentialSource === "literal" ? literalApiKey : storedApiKey,
448
780
  signal: input.discoverySignal,
449
781
  });
450
782
  // The caller (wizard revision/cancel) may have aborted while the probe
@@ -478,6 +810,11 @@ export async function addApiCompatibleProvider(input: ProviderSetupInput): Promi
478
810
  if (validated.discovery) provider.discovery = validated.discovery;
479
811
  if (validated.credentialSource === "env") {
480
812
  provider.apiKeyEnv = validated.apiKey;
813
+ } else {
814
+ // The literal key is published to the credential store below; the config
815
+ // only declares that the credential lives there. Without the declaration
816
+ // the loader rejects this brand-new provider as credential-less.
817
+ provider.credential = PROVIDER_CREDENTIAL_STORE;
481
818
  }
482
819
  // Serialize config merging under the file lock. Credential storage is a
483
820
  // separate authority, not an atomic transaction with models.yml. Publish the
@@ -500,13 +837,22 @@ export async function addApiCompatibleProvider(input: ProviderSetupInput): Promi
500
837
  await fn(input.authStorage);
501
838
  return;
502
839
  }
503
- const authStorage = await AuthStorageImpl.create(getAgentDbPath());
840
+ // Same construction as the probe path. Today no write-path call resolves a
841
+ // stored value, but sharing the construction keeps value resolution in one
842
+ // place if one ever does.
843
+ const authStorage = await createOwnedCredentialStore();
504
844
  try {
505
845
  await fn(authStorage);
506
846
  } finally {
507
847
  authStorage.close();
508
848
  }
509
849
  };
850
+ const credentialUpdate =
851
+ validated.credentialSource === "env" ? "disable the previous stored API key" : "publish credentials";
852
+ let credentialCleanup: ProviderSetupResult["credentialCleanup"];
853
+ let storedCredentialShadow: ProviderSetupResult["storedCredentialShadow"];
854
+ let storedCredentialShadowUnverified: ProviderSetupResult["storedCredentialShadowUnverified"];
855
+ let replacementCleanedStoredKeys = false;
510
856
  await withFileLock(modelsPath, async () => {
511
857
  if (input.discoverySignal?.aborted) {
512
858
  throw cancelledError();
@@ -516,6 +862,15 @@ export async function addApiCompatibleProvider(input: ProviderSetupInput): Promi
516
862
  if (current.providers?.[validated.providerId] && !input.force) {
517
863
  throw new Error(`Provider '${validated.providerId}' already exists. Use --force to replace it.`);
518
864
  }
865
+ // Cleanup only exists for one case: the entry being replaced declared
866
+ // `credential: store` and is now switched to an env reference. A provider
867
+ // that was env-pinned or hand-configured keeps its stored credential.
868
+ const replacedEntry = current.providers?.[validated.providerId];
869
+ const replacingStoreBackedEntry =
870
+ validated.credentialSource === "env" &&
871
+ input.force === true &&
872
+ replacedEntry?.credential === PROVIDER_CREDENTIAL_STORE;
873
+ if (replacingStoreBackedEntry) assertReplacementEnvResolves(validated.providerId, validated.apiKey);
519
874
  if (validated.credentialSource !== "env" && input.discoverySignal) {
520
875
  await withCredentialStore(async store => {
521
876
  if (hasUnrestorableCredentials(store)) {
@@ -541,6 +896,11 @@ export async function addApiCompatibleProvider(input: ProviderSetupInput): Promi
541
896
  input.discoverySignal,
542
897
  );
543
898
  configCommitted = true;
899
+ // Verify the just-written config through the loader before touching the
900
+ // credential authority: a disagreement rolls back cleanly with no
901
+ // credential change instead of stranding a committed config whose stored
902
+ // key was already disabled.
903
+ await assertWrittenModelsConfigLoads(modelsPath, validated.providerId);
544
904
  // Cancellation after the atomic config rename cannot undo the saved
545
905
  // provider. Finish publishing the matching literal credential even if
546
906
  // the caller dismissed the wizard during the rename.
@@ -548,27 +908,71 @@ export async function addApiCompatibleProvider(input: ProviderSetupInput): Promi
548
908
  await withCredentialStore(store =>
549
909
  store.set(validated.providerId, { type: "api_key", key: validated.apiKey }),
550
910
  );
911
+ } else if (replacingStoreBackedEntry) {
912
+ replacementCleanedStoredKeys = true;
913
+ // A stored api_key outranks an apiKeyEnv indirection, so replacing a
914
+ // store-backed provider with an env-backed one must disable the old
915
+ // literal rows; OAuth rows are never touched. The cleanup re-reads the
916
+ // store and fails loudly if the rows still resolve.
917
+ await withCredentialStore(async store => {
918
+ const disabledApiKeys = await removeStoredApiKeyCredentials(store, validated.providerId);
919
+ credentialCleanup = disabledApiKeys > 0 ? { disabledApiKeys, envName: validated.apiKey } : undefined;
920
+ });
551
921
  }
552
922
  } catch (error) {
553
923
  if (configCommitted) {
554
924
  try {
555
- if (configExistedBeforeCommit) await writeModelsConfig(modelsPath, current);
925
+ if (configExistedBeforeCommit)
926
+ await writeModelsConfig(modelsPath, current, undefined, { bypassSemanticValidation: true });
556
927
  else await fs.rm(modelsPath, { force: true });
557
928
  } catch {
558
929
  // Store/config errors can contain credentials; never log or
559
930
  // interpolate them. Log independently of the wizard, which may
560
931
  // already be dismissed.
561
- const message = `Provider '${validated.providerId}' setup failed while publishing credentials and could not restore the previous config; credential recovery is required.`;
932
+ const message = `Provider '${validated.providerId}' setup failed while updating credentials and could not restore the previous provider settings; credential recovery is required.`;
562
933
  logger.error(message);
563
934
  throw new Error(message, { cause: error });
564
935
  }
936
+ // A cleanup failure already explains rollback and recovery; do not
937
+ // replace it with the generic credential-update message.
938
+ if (error instanceof CredentialCleanupError) throw error;
939
+ // The written config never loaded, so nothing credential-related ran;
940
+ // keep the loader's detail and add the rollback outcome.
941
+ if (error instanceof WrittenModelsConfigLoadError) {
942
+ throw new WrittenModelsConfigLoadError(
943
+ `${error.message} Setup restored the previous provider settings and did not change any credential. ` +
944
+ `Fix the config, then re-run setup (adding --force if the provider already exists).`,
945
+ );
946
+ }
565
947
  throw new Error(
566
- `Provider '${validated.providerId}' setup could not publish credentials; the previous config was restored.`,
948
+ `Provider '${validated.providerId}' setup could not ${credentialUpdate}; the previous provider settings were restored.`,
567
949
  );
568
950
  }
569
951
  throw error;
570
952
  }
571
953
  });
954
+ // An env reference only supplies the key when nothing else outranks it. If
955
+ // cleanup did not run (the replaced entry never declared credential: store),
956
+ // disclose any stored api_key rows instead of claiming the env var wins.
957
+ if (validated.credentialSource === "env" && !replacementCleanedStoredKeys) {
958
+ try {
959
+ await withCredentialStore(async store => {
960
+ const storedApiKeys = await countStoredApiKeyCredentials(store, validated.providerId);
961
+ if (storedApiKeys > 0) {
962
+ storedCredentialShadow = { storedApiKeys, envName: validated.apiKey };
963
+ }
964
+ });
965
+ } catch (error) {
966
+ // Never fail the add for this: the provider and its env reference are
967
+ // already committed and valid. Disclose the unverified risk instead of
968
+ // reporting unconditional success, since a stored key would still win.
969
+ storedCredentialShadowUnverified = { envName: validated.apiKey };
970
+ logger.warn("could not inspect stored credentials after provider setup", {
971
+ provider: validated.providerId,
972
+ error: error instanceof Error ? error.name : typeof error,
973
+ });
974
+ }
975
+ }
572
976
  return {
573
977
  providerId: validated.providerId,
574
978
  compatibility: validated.compatibility,
@@ -582,9 +986,72 @@ export async function addApiCompatibleProvider(input: ProviderSetupInput): Promi
582
986
  discoveryType: validated.discovery?.type,
583
987
  preset: validated.preset?.id,
584
988
  presetName: validated.preset?.name,
989
+ ...(credentialCleanup ? { credentialCleanup } : {}),
990
+ ...(storedCredentialShadow ? { storedCredentialShadow } : {}),
991
+ ...(storedCredentialShadowUnverified ? { storedCredentialShadowUnverified } : {}),
585
992
  };
586
993
  }
587
994
 
995
+ /**
996
+ * Raised when the provider setup just wrote does not load through the
997
+ * runtime's own loader. Thrown before any credential mutation, so the caller
998
+ * can roll the config back without a credential change.
999
+ */
1000
+ class WrittenModelsConfigLoadError extends Error {
1001
+ constructor(message: string) {
1002
+ super(message);
1003
+ this.name = "WrittenModelsConfigLoadError";
1004
+ }
1005
+ }
1006
+
1007
+ /**
1008
+ * Reload the just-written models config through the same loader the runtime
1009
+ * uses. Setup must never report success for a file the product rejects, even
1010
+ * if every pre-write check passed. This runs before the credential mutation,
1011
+ * so a failure can be rolled back without leaving a stored key behind.
1012
+ */
1013
+ async function assertWrittenModelsConfigLoads(modelsPath: string, providerId: string): Promise<void> {
1014
+ const { ModelsConfigFile } = await loadModelRegistryModule();
1015
+ const configFile = ModelsConfigFile.relocate(modelsPath);
1016
+ // For the default agent path `relocate` returns the process-wide singleton a
1017
+ // live session already loaded (commonly `not-found` before the first add).
1018
+ // Drop that snapshot so the verdict reads the bytes just committed.
1019
+ configFile.invalidate();
1020
+ const loaded = configFile.tryLoad();
1021
+ if (loaded.status === "ok") return;
1022
+ const detail = loaded.status === "error" ? String(loaded.error) : `the file does not exist at ${modelsPath}`;
1023
+ throw new WrittenModelsConfigLoadError(
1024
+ `Provider '${providerId}' was written to ${modelsPath}, but the models config does not load: ${detail}.`,
1025
+ );
1026
+ }
1027
+
1028
+ /**
1029
+ * Post-refresh guard for setup callers that reload through a live registry.
1030
+ * `refresh` re-reads the written config, so a loader error there means the
1031
+ * provider is unusable even though setup wrote it.
1032
+ */
1033
+ export function assertProviderConfigLoaded(
1034
+ registry: { getError(): { id: string; message: string } | undefined },
1035
+ providerId: string,
1036
+ modelsPath: string,
1037
+ credentialSource: ProviderSetupResult["credentialSource"],
1038
+ ): void {
1039
+ const error = registry.getError();
1040
+ // getError() also reports accepted model-preset registry failures. Only a
1041
+ // models-config failure makes the provider setup itself unusable.
1042
+ if (error?.id !== "models") return;
1043
+ // The credential is not in models.yml either way; say which location applies
1044
+ // instead of claiming a credential was written there.
1045
+ const credentialLocation =
1046
+ credentialSource === "literal"
1047
+ ? "its API key was written to the credential store, not to models.yml"
1048
+ : "its apiKeyEnv reference is in models.yml and the key itself stays in the environment";
1049
+ throw new Error(
1050
+ `Provider '${providerId}' was written to ${modelsPath} (${credentialLocation}), but the models config did not load: ${error.message}. ` +
1051
+ `Fix the config, then re-run setup with --force to replace the provider.`,
1052
+ );
1053
+ }
1054
+
588
1055
  function isLocalHttpHost(hostname: string): boolean {
589
1056
  const normalized = hostname.toLowerCase().replace(/^\[(.*)]$/, "$1");
590
1057
  return (
@@ -760,6 +1227,12 @@ export async function reloadAndRefreshDiscoveryCatalog(
760
1227
  );
761
1228
  }
762
1229
 
1230
+ /**
1231
+ * Render the success banner. Only call this after the written config has been
1232
+ * verified to load: `addApiCompatibleProvider` re-reads the file it wrote, and
1233
+ * registry-backed callers re-check `modelRegistry.getError()` after their
1234
+ * post-write refresh. On any load failure the setup path must throw instead.
1235
+ */
763
1236
  export function formatProviderSetupResult(result: ProviderSetupResult): string {
764
1237
  return [
765
1238
  `Provider '${result.providerId}' configured as ${result.compatibility}-compatible.`,
@@ -774,6 +1247,21 @@ export function formatProviderSetupResult(result: ProviderSetupResult): string {
774
1247
  : []),
775
1248
  `Base URL: ${result.baseUrl}`,
776
1249
  `API key: ${result.credentialSource === "env" ? `${result.redactedApiKey} (environment variable)` : result.redactedApiKey}`,
1250
+ ...(result.credentialCleanup
1251
+ ? [
1252
+ `Stored API key: disabled ${result.credentialCleanup.disabledApiKeys} stored credential(s) for this provider; they no longer resolve and ${result.credentialCleanup.envName} now supplies the key. Delete them permanently with: gjc accounts logout ${result.providerId} --all (removes every stored credential for this provider, including OAuth logins)`,
1253
+ ]
1254
+ : []),
1255
+ ...(result.storedCredentialShadow
1256
+ ? [
1257
+ `Warning: ${result.storedCredentialShadow.storedApiKeys} stored API key credential(s) for this provider take precedence over ${result.storedCredentialShadow.envName}. Remove them with: gjc accounts logout ${result.providerId} --all (removes every stored credential for this provider, including OAuth logins); with a broker configuration run gjc auth-broker logout ${result.providerId} on the broker host instead (same breadth)`,
1258
+ ]
1259
+ : []),
1260
+ ...(result.storedCredentialShadowUnverified
1261
+ ? [
1262
+ `Warning: setup could not check the credential store for stored API key credentials; if any exist they would still take precedence over ${result.storedCredentialShadowUnverified.envName}. Verify with: gjc accounts list`,
1263
+ ]
1264
+ : []),
777
1265
  `Config: ${result.modelsPath}`,
778
1266
  ].join("\n");
779
1267
  }