@gaunt-sloth/core 2.0.0-alpha.1 → 2.0.0-alpha.10

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 (114) hide show
  1. package/.gsloth.code.md +10 -0
  2. package/LICENSE +7 -0
  3. package/README.md +3 -4
  4. package/dist/config/defaults.d.ts +85 -0
  5. package/dist/config/defaults.js +101 -0
  6. package/dist/config/defaults.js.map +1 -0
  7. package/dist/config/jsonc.d.ts +12 -0
  8. package/dist/config/jsonc.js +41 -0
  9. package/dist/config/jsonc.js.map +1 -0
  10. package/dist/config/loader.d.ts +109 -0
  11. package/dist/config/loader.js +663 -0
  12. package/dist/config/loader.js.map +1 -0
  13. package/dist/config/schema.d.ts +509 -0
  14. package/dist/config/schema.js +349 -0
  15. package/dist/config/schema.js.map +1 -0
  16. package/dist/config/shell-policy.d.ts +212 -0
  17. package/dist/config/shell-policy.js +142 -0
  18. package/dist/config/shell-policy.js.map +1 -0
  19. package/dist/config/types.d.ts +490 -0
  20. package/dist/config/types.js +12 -0
  21. package/dist/config/types.js.map +1 -0
  22. package/dist/config.d.ts +18 -647
  23. package/dist/config.js +15 -516
  24. package/dist/config.js.map +1 -1
  25. package/dist/constants.d.ts +24 -0
  26. package/dist/constants.js +24 -0
  27. package/dist/constants.js.map +1 -1
  28. package/dist/core/GthAbstractAgent.d.ts +57 -1
  29. package/dist/core/GthAbstractAgent.js +171 -4
  30. package/dist/core/GthAbstractAgent.js.map +1 -1
  31. package/dist/core/GthAgentRunner.d.ts +158 -1
  32. package/dist/core/GthAgentRunner.js +367 -4
  33. package/dist/core/GthAgentRunner.js.map +1 -1
  34. package/dist/core/GthLangChainAgent.js +94 -5
  35. package/dist/core/GthLangChainAgent.js.map +1 -1
  36. package/dist/core/debugCapture.d.ts +59 -0
  37. package/dist/core/debugCapture.js +101 -0
  38. package/dist/core/debugCapture.js.map +1 -0
  39. package/dist/core/gthLeanAgentFactory.d.ts +9 -0
  40. package/dist/core/gthLeanAgentFactory.js +10 -0
  41. package/dist/core/gthLeanAgentFactory.js.map +1 -0
  42. package/dist/core/runStats.d.ts +41 -0
  43. package/dist/core/runStats.js +73 -0
  44. package/dist/core/runStats.js.map +1 -0
  45. package/dist/core/shell/ShellCommandFailedError.d.ts +54 -0
  46. package/dist/core/shell/ShellCommandFailedError.js +68 -0
  47. package/dist/core/shell/ShellCommandFailedError.js.map +1 -0
  48. package/dist/core/shell/allowlist.d.ts +75 -0
  49. package/dist/core/shell/allowlist.js +187 -0
  50. package/dist/core/shell/allowlist.js.map +1 -0
  51. package/dist/core/shell/arity.d.ts +75 -0
  52. package/dist/core/shell/arity.js +313 -0
  53. package/dist/core/shell/arity.js.map +1 -0
  54. package/dist/core/shell/judge.d.ts +161 -0
  55. package/dist/core/shell/judge.js +261 -0
  56. package/dist/core/shell/judge.js.map +1 -0
  57. package/dist/core/shell/normalize.d.ts +27 -0
  58. package/dist/core/shell/normalize.js +53 -0
  59. package/dist/core/shell/normalize.js.map +1 -0
  60. package/dist/core/types.d.ts +104 -0
  61. package/dist/core/types.js.map +1 -1
  62. package/dist/history/historyFormat.d.ts +19 -0
  63. package/dist/history/historyFormat.js +85 -0
  64. package/dist/history/historyFormat.js.map +1 -0
  65. package/dist/history/historyStore.d.ts +121 -0
  66. package/dist/history/historyStore.js +315 -0
  67. package/dist/history/historyStore.js.map +1 -0
  68. package/dist/history/recordSession.d.ts +28 -0
  69. package/dist/history/recordSession.js +29 -0
  70. package/dist/history/recordSession.js.map +1 -0
  71. package/dist/index.d.ts +4 -0
  72. package/dist/index.js +4 -0
  73. package/dist/index.js.map +1 -1
  74. package/dist/providers/anthropic.d.ts +1 -1
  75. package/dist/providers/anthropic.js +5 -10
  76. package/dist/providers/anthropic.js.map +1 -1
  77. package/dist/providers/deepseek.d.ts +1 -1
  78. package/dist/providers/deepseek.js +5 -10
  79. package/dist/providers/deepseek.js.map +1 -1
  80. package/dist/providers/google-genai.d.ts +1 -1
  81. package/dist/providers/google-genai.js +5 -10
  82. package/dist/providers/google-genai.js.map +1 -1
  83. package/dist/providers/groq.d.ts +1 -1
  84. package/dist/providers/groq.js +5 -10
  85. package/dist/providers/groq.js.map +1 -1
  86. package/dist/providers/modelDiscovery.d.ts +54 -1
  87. package/dist/providers/modelDiscovery.js +106 -8
  88. package/dist/providers/modelDiscovery.js.map +1 -1
  89. package/dist/providers/ollama.d.ts +1 -1
  90. package/dist/providers/ollama.js +5 -15
  91. package/dist/providers/ollama.js.map +1 -1
  92. package/dist/providers/openai.d.ts +1 -1
  93. package/dist/providers/openai.js +5 -10
  94. package/dist/providers/openai.js.map +1 -1
  95. package/dist/providers/openrouter.d.ts +1 -1
  96. package/dist/providers/openrouter.js +7 -12
  97. package/dist/providers/openrouter.js.map +1 -1
  98. package/dist/providers/vertexai.d.ts +1 -1
  99. package/dist/providers/vertexai.js +5 -10
  100. package/dist/providers/vertexai.js.map +1 -1
  101. package/dist/providers/xai.d.ts +1 -1
  102. package/dist/providers/xai.js +5 -10
  103. package/dist/providers/xai.js.map +1 -1
  104. package/dist/runtime/singleShot.d.ts +5 -2
  105. package/dist/runtime/singleShot.js +36 -3
  106. package/dist/runtime/singleShot.js.map +1 -1
  107. package/dist/utils/fileUtils.d.ts +24 -2
  108. package/dist/utils/fileUtils.js +54 -12
  109. package/dist/utils/fileUtils.js.map +1 -1
  110. package/dist/utils/systemUtils.d.ts +31 -0
  111. package/dist/utils/systemUtils.js +38 -0
  112. package/dist/utils/systemUtils.js.map +1 -1
  113. package/package.json +16 -11
  114. package/schema/gsloth-config.schema.json +1579 -0
@@ -0,0 +1,663 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * Configuration discovery + the layered load/merge pipeline (global + project layers,
4
+ * format fall-through JSON → JS → MJS, schema validation, deep-merge with defaults).
5
+ * Extracted from the former `config.ts` god-file; behaviour is unchanged.
6
+ */
7
+ import { GSLOTH_DIR, GSLOTH_SETTINGS_DIR, USER_PROJECT_CONFIG_JS, USER_PROJECT_CONFIG_JSON, USER_PROJECT_CONFIG_MJS, USER_PROJECT_CONFIG_TS, } from '#src/constants.js';
8
+ import { StatusLevel } from '#src/core/types.js';
9
+ import { displayDebug, displayError, displayInfo, displayWarning, setConsoleLevel, } from '#src/utils/consoleUtils.js';
10
+ import { findUnknownTopLevelKeys, formatConfigValidationError, preMapDeprecatedConfigNames, rawGthConfigSchema, validateRawGthConfig, } from '#src/config/schema.js';
11
+ import { parseJsonc } from '#src/config/jsonc.js';
12
+ import { getGslothConfigReadPath, importExternalFile } from '#src/utils/fileUtils.js';
13
+ import { getGlobalGslothConfigReadPath } from '#src/utils/globalConfigUtils.js';
14
+ import { error, exit, getCurrentWorkDir, isTTY, setProjectDir, setUseColour, } from '#src/utils/systemUtils.js';
15
+ import { existsSync, readFileSync } from 'node:fs';
16
+ import { homedir } from 'node:os';
17
+ import { dirname, resolve } from 'node:path';
18
+ import { DEFAULT_CONFIG } from '#src/config/defaults.js';
19
+ /**
20
+ * Validate (and normalize) a freshly loaded raw config layer (global or project)
21
+ * against {@link rawGthConfigSchema}, the single source of truth for the on-disk
22
+ * config shape.
23
+ *
24
+ * Steps, in order:
25
+ * 1. B3 pre-map: map deprecated key names one-way to their canonical names (root +
26
+ * per-command) via {@link preMapDeprecatedConfigNames}, emitting a deprecation
27
+ * `displayWarning` for each occurrence. This runs FIRST so renamed keys are not
28
+ * later mistaken for unknown keys.
29
+ * 2. Unknown top-level keys: warn (do NOT fail) so likely typos are surfaced while
30
+ * forward-compatible / extension keys still pass through untouched.
31
+ * 3. Schema parse: on a genuine type mismatch on a known field, emit a friendly,
32
+ * path-scoped error and exit (matching the loader's existing invalid-config
33
+ * behaviour). Validation is shape-only — the loose schema preserves unknown keys,
34
+ * so the original `raw` (pre-mapped) is returned unchanged on success.
35
+ *
36
+ * @param raw The freshly loaded config layer (mutated in place by the pre-map).
37
+ * @param sourceLabel Human-readable source name for messages (e.g. the filename).
38
+ */
39
+ function validateRawConfigLayer(raw, sourceLabel) {
40
+ const { config, warnings } = preMapDeprecatedConfigNames(raw);
41
+ for (const warning of warnings) {
42
+ displayWarning(warning);
43
+ }
44
+ const unknownKeys = findUnknownTopLevelKeys(config);
45
+ if (unknownKeys.length > 0) {
46
+ displayWarning(`Unknown top-level config ${unknownKeys.length === 1 ? 'key' : 'keys'} in ${sourceLabel}: ` +
47
+ `${unknownKeys.join(', ')}. ${unknownKeys.length === 1 ? 'It is' : 'They are'} kept as-is ` +
48
+ 'but ignored by Gaunt Sloth; check for typos.');
49
+ }
50
+ const result = rawGthConfigSchema.safeParse(config);
51
+ if (!result.success) {
52
+ displayError(`Invalid configuration in ${sourceLabel}:\n${formatConfigValidationError(result.error)}`);
53
+ exit(1);
54
+ }
55
+ return config;
56
+ }
57
+ /**
58
+ * Project config file lookup order, highest precedence first. JSON wins, then the
59
+ * `configure()`-style module formats (JS → MJS → TS). Used to pick THE config within a dir.
60
+ */
61
+ const PROJECT_CONFIG_FORMATS = [
62
+ USER_PROJECT_CONFIG_JSON,
63
+ USER_PROJECT_CONFIG_JS,
64
+ USER_PROJECT_CONFIG_MJS,
65
+ USER_PROJECT_CONFIG_TS,
66
+ ];
67
+ /**
68
+ * Dir-aware version of {@link getGslothConfigReadPath} for ancestor dirs during the up-tree
69
+ * walk. Mirrors its `.gsloth/.gsloth-settings[/<profile>]/<filename>` resolution but against an
70
+ * explicit `dir` instead of the cwd, falling back to `<dir>/<filename>`. Implemented with
71
+ * `node:path`/`node:fs` directly (no `fileUtils` round-trip) so the cwd level can keep
72
+ * delegating to the original cwd-bound resolver.
73
+ */
74
+ function resolveProjectConfigPathInDir(dir, filename, identityProfileRaw) {
75
+ const identityProfile = identityProfileRaw?.trim();
76
+ const gslothDirPath = resolve(dir, GSLOTH_DIR);
77
+ if (existsSync(gslothDirPath)) {
78
+ const gslothSettingsPath = resolve(gslothDirPath, GSLOTH_SETTINGS_DIR);
79
+ const configPath = identityProfile
80
+ ? resolve(gslothSettingsPath, identityProfile, filename)
81
+ : resolve(gslothSettingsPath, filename);
82
+ if (existsSync(configPath)) {
83
+ return configPath;
84
+ }
85
+ }
86
+ return resolve(dir, filename);
87
+ }
88
+ /**
89
+ * Resolve where a config `filename` would live for the given base dir, composing with
90
+ * `identityProfile`. The cwd level delegates to the existing cwd-bound
91
+ * {@link getGslothConfigReadPath} (preserving its behaviour and test seams); ancestor dirs use
92
+ * {@link resolveProjectConfigPathInDir}.
93
+ */
94
+ function resolveConfigPath(baseDir, filename, identityProfile) {
95
+ return baseDir === getCurrentWorkDir()
96
+ ? getGslothConfigReadPath(filename, identityProfile)
97
+ : resolveProjectConfigPathInDir(baseDir, filename, identityProfile);
98
+ }
99
+ /**
100
+ * Find THE project config by walking up from cwd toward a stop boundary, returning the FIRST
101
+ * match (first-match-win: nearest dir, then format precedence within that dir — NOT a merged
102
+ * stack). Detection ({@link hasProjectConfig}/{@link hasAnyConfig}) and loading ({@link initConfig})
103
+ * both go through this, so they can never disagree.
104
+ *
105
+ * Stop boundary — the dir is SEARCHED, then ascent stops at: a dir containing `.git` (the git
106
+ * root), the user's home dir, or the filesystem root — whichever comes first. So a config IN the
107
+ * git root (or home) is found; a config ABOVE it is not.
108
+ *
109
+ * A `customConfigPath` override wins outright (no walking).
110
+ *
111
+ * @returns the matched `{ dir, path }`, or `undefined` when no project config exists within the
112
+ * boundary.
113
+ */
114
+ export function findProjectConfigPath(commandLineConfigOverrides) {
115
+ if (commandLineConfigOverrides.customConfigPath) {
116
+ return existsSync(commandLineConfigOverrides.customConfigPath)
117
+ ? {
118
+ dir: dirname(commandLineConfigOverrides.customConfigPath),
119
+ path: commandLineConfigOverrides.customConfigPath,
120
+ }
121
+ : undefined;
122
+ }
123
+ const home = homedir();
124
+ let dir = getCurrentWorkDir();
125
+ // Walk up: search each dir, then stop at the boundary (git root / home / fs root).
126
+ for (;;) {
127
+ for (const filename of PROJECT_CONFIG_FORMATS) {
128
+ const candidate = resolveConfigPath(dir, filename, commandLineConfigOverrides.identityProfile);
129
+ if (existsSync(candidate)) {
130
+ return { dir, path: candidate };
131
+ }
132
+ }
133
+ const parent = dirname(dir);
134
+ if (existsSync(resolve(dir, '.git')) || dir === home || parent === dir) {
135
+ break;
136
+ }
137
+ dir = parent;
138
+ }
139
+ return undefined;
140
+ }
141
+ /**
142
+ * Loads the global gsloth config (if present) from the global `~/.gsloth` folder.
143
+ *
144
+ * Precedence support: the returned raw config is intended to act as the BASE that the
145
+ * project config (and CLI overrides) merge on top of, so any value here is the lowest
146
+ * user-controlled layer (still above {@link DEFAULT_CONFIG}).
147
+ *
148
+ * Lookup order within the global folder, first match wins:
149
+ * `.gsloth.config.json` -> `.gsloth.config.js` -> `.gsloth.config.mjs`
150
+ *
151
+ * Absence of every variant is a no-op: returns `undefined` so behaviour is unchanged.
152
+ *
153
+ * NOTE: secrets (API keys) may live in this file; this function must never log its
154
+ * contents. Only non-sensitive diagnostics (the resolved path / parse failure) are emitted.
155
+ *
156
+ * @returns The raw global config object, or `undefined` when no global config exists.
157
+ */
158
+ export async function loadGlobalRawConfig() {
159
+ // JSON first (the must-have format).
160
+ const jsonPath = getGlobalGslothConfigReadPath(USER_PROJECT_CONFIG_JSON);
161
+ if (existsSync(jsonPath)) {
162
+ try {
163
+ const parsed = parseJsonc(readFileSync(jsonPath, 'utf8'), `${USER_PROJECT_CONFIG_JSON} (global)`);
164
+ return validateRawConfigLayer(parsed, `${USER_PROJECT_CONFIG_JSON} (global)`);
165
+ }
166
+ catch (e) {
167
+ displayDebug(e instanceof Error ? e : String(e));
168
+ displayWarning(`Failed to read global config from ${jsonPath}, ignoring it.`);
169
+ return undefined;
170
+ }
171
+ }
172
+ // Then JS / MJS variants (dynamic import of a `configure()` module).
173
+ for (const filename of [USER_PROJECT_CONFIG_JS, USER_PROJECT_CONFIG_MJS]) {
174
+ const modulePath = getGlobalGslothConfigReadPath(filename);
175
+ if (existsSync(modulePath)) {
176
+ try {
177
+ const imported = await importExternalFile(modulePath);
178
+ const configured = await imported.configure();
179
+ return validateRawConfigLayer(configured, `${filename} (global)`);
180
+ }
181
+ catch (e) {
182
+ displayDebug(e instanceof Error ? e : String(e));
183
+ displayWarning(`Failed to read global config from ${modulePath}, ignoring it.`);
184
+ return undefined;
185
+ }
186
+ }
187
+ }
188
+ return undefined;
189
+ }
190
+ /**
191
+ * Deep-merges a loaded global raw config UNDER the given project raw config, so the
192
+ * project config wins on conflicting keys. When no global config exists this is a no-op
193
+ * and the original project config is returned unchanged.
194
+ */
195
+ async function applyGlobalConfigBase(projectRawConfig) {
196
+ const globalRawConfig = await loadGlobalRawConfig();
197
+ if (!globalRawConfig) {
198
+ return projectRawConfig;
199
+ }
200
+ return deepMerge(globalRawConfig, projectRawConfig);
201
+ }
202
+ /**
203
+ * ORDERING INVARIANT (GS2-11): detection ({@link hasProjectConfig}/{@link hasAnyConfig}) MUST run
204
+ * before {@link initConfig} in a given process. Both resolve cwd-level candidates via
205
+ * `getGslothConfigReadPath`, which reads `getProjectDir()`; {@link initConfig} clears `projectDir`
206
+ * at the start of its run, so detection stays cwd-correct as long as it precedes initConfig (it
207
+ * does: startSession calls hasAnyConfig before any initConfig, and the ACP/agent path calls
208
+ * initConfig directly without detection). Calling detection AFTER an initConfig with a changed cwd
209
+ * in a long-lived process would read a stale projectDir (currently unreachable). If that call
210
+ * order is ever introduced, decouple discovery's cwd-branch from `getProjectDir()`.
211
+ */
212
+ /**
213
+ * Returns true when a project-level config file (json/js/mjs) exists for the given
214
+ * overrides. Honours `customConfigPath` and the active identity profile so the check
215
+ * matches exactly what {@link initConfig} would attempt to load.
216
+ *
217
+ * This is the project half of CFG-10's "is any config present?" detection; the global
218
+ * half is {@link loadGlobalRawConfig} (used by {@link hasAnyConfig}).
219
+ */
220
+ export function hasProjectConfig(commandLineConfigOverrides) {
221
+ return findProjectConfigPath(commandLineConfigOverrides) !== undefined;
222
+ }
223
+ /**
224
+ * CFG-10 — true when ANY usable configuration is present, either a project config file
225
+ * (json/js/mjs) or a standalone global config (`~/.gsloth/.gsloth.config.*`). When this
226
+ * returns false the caller should run the first-run dialog instead of erroring.
227
+ *
228
+ * Reuses CFG-8's project + global detection so the two paths can never disagree.
229
+ */
230
+ export async function hasAnyConfig(commandLineConfigOverrides) {
231
+ if (hasProjectConfig(commandLineConfigOverrides)) {
232
+ return true;
233
+ }
234
+ return (await loadGlobalRawConfig()) !== undefined;
235
+ }
236
+ /**
237
+ * Initialize configuration by loading from available config files
238
+ * @returns The loaded GthConfig
239
+ */
240
+ export async function initConfig(commandLineConfigOverrides) {
241
+ if (commandLineConfigOverrides.customConfigPath &&
242
+ !existsSync(commandLineConfigOverrides.customConfigPath)) {
243
+ throw new Error(`Provided manual config "${commandLineConfigOverrides.customConfigPath}" does not exist`);
244
+ }
245
+ // Clear the project root BEFORE discovery. Discovery and detection must resolve against cwd,
246
+ // and the up-tree walk itself goes through getGslothConfigReadPath -> getProjectDir(); clearing
247
+ // first guarantees getProjectDir() falls back to cwd during the walk, even on a SECOND initConfig
248
+ // call in a long-lived process (ACP server) or across tests where a stale projectDir would
249
+ // otherwise poison the walk and miss the real config.
250
+ setProjectDir(undefined);
251
+ // Discover the project config location: a customConfigPath wins outright, otherwise walk up
252
+ // from cwd to the stop boundary (see findProjectConfigPath). Detection and loading share this
253
+ // resolver, and the discovered dir becomes the base for the per-format cascade below.
254
+ const discovered = findProjectConfigPath(commandLineConfigOverrides);
255
+ const baseDir = discovered?.dir ?? getCurrentWorkDir();
256
+ // Set the project root for post-config, project-relative artifact resolution (guidelines,
257
+ // prompts, .gsloth-settings, outputs). up-tree and --config both set it here; a global-only /
258
+ // no-config run leaves it undefined so those artifacts stay cwd-bound (see getProjectDir).
259
+ // Safe for the in-function load below: when discovered.dir === cwd getProjectDir() is unchanged,
260
+ // and when it is an ancestor resolveConfigPath takes its explicit-dir branch (never getProjectDir).
261
+ setProjectDir(discovered?.dir);
262
+ const jsonConfigPath = commandLineConfigOverrides.customConfigPath ??
263
+ resolveConfigPath(baseDir, USER_PROJECT_CONFIG_JSON, commandLineConfigOverrides.identityProfile);
264
+ // CFG-8 — when no project config file of any format exists (anywhere up-tree), fall back to a
265
+ // standalone global config (loaded alone) before erroring. Project config still takes
266
+ // precedence: this branch only runs when there is no project file to apply the global under.
267
+ if (!discovered) {
268
+ const globalRawConfig = await loadGlobalRawConfig();
269
+ if (globalRawConfig) {
270
+ if (globalRawConfig.llm &&
271
+ typeof globalRawConfig.llm === 'object' &&
272
+ 'type' in globalRawConfig.llm) {
273
+ // Route the global config through the same path the project JSON uses.
274
+ return await tryJsonConfig(globalRawConfig, commandLineConfigOverrides);
275
+ }
276
+ displayError('Global configuration found but it is not in valid format. Should at least define llm.type');
277
+ exit(1);
278
+ // Unreachable past exit(1) in production; keeps TS happy and prevents test exit.
279
+ throw new Error('Unexpected error occurred.');
280
+ }
281
+ }
282
+ // Try loading the JSON config file first
283
+ if (jsonConfigPath.endsWith('.json') && existsSync(jsonConfigPath)) {
284
+ try {
285
+ // Validate the project config layer against the Zod schema (single source of
286
+ // truth): pre-map deprecated names, warn on unknown top-level keys, and fail
287
+ // with a friendly, path-scoped message on a genuine type mismatch.
288
+ const projectJsonConfig = validateRawConfigLayer(parseJsonc(readFileSync(jsonConfigPath, 'utf8'), USER_PROJECT_CONFIG_JSON), USER_PROJECT_CONFIG_JSON);
289
+ // Apply global config as the base layer (project config wins on conflicts).
290
+ const jsonConfig = (await applyGlobalConfigBase(projectJsonConfig));
291
+ // If the config has an LLM with a type, create the appropriate LLM instance
292
+ if (jsonConfig.llm && typeof jsonConfig.llm === 'object' && 'type' in jsonConfig.llm) {
293
+ return await tryJsonConfig(jsonConfig, commandLineConfigOverrides);
294
+ }
295
+ else {
296
+ error(`${jsonConfigPath} is not in valid format. Should at least define llm.type`);
297
+ exit(1);
298
+ // noinspection ExceptionCaughtLocallyJS
299
+ // This throw is unreachable due to exit(1) above, but satisfies TS type analysis and prevents tests from exiting
300
+ // noinspection ExceptionCaughtLocallyJS
301
+ throw new Error('Unexpected error occurred.');
302
+ }
303
+ }
304
+ catch (e) {
305
+ displayDebug(e instanceof Error ? e : String(e));
306
+ displayError(`Failed to read config from ${USER_PROJECT_CONFIG_JSON}, will try other formats.`);
307
+ // Continue to try other formats
308
+ return await tryModuleConfig('js', commandLineConfigOverrides, baseDir);
309
+ }
310
+ }
311
+ else {
312
+ // JSON config not found, try JS
313
+ return tryModuleConfig('js', commandLineConfigOverrides, baseDir);
314
+ }
315
+ }
316
+ /**
317
+ * Module-format fall-through order (lowest precedence among project formats; JSON is tried
318
+ * first by {@link initConfig}). `.ts` (B2b) is last, loaded via jiti by `importExternalFile`.
319
+ */
320
+ const MODULE_CONFIG_FORMATS = ['js', 'mjs', 'ts'];
321
+ const MODULE_CONFIG_FILENAME = {
322
+ js: USER_PROJECT_CONFIG_JS,
323
+ mjs: USER_PROJECT_CONFIG_MJS,
324
+ ts: USER_PROJECT_CONFIG_TS,
325
+ };
326
+ const MODULE_CONFIG_EXT = {
327
+ js: '.js',
328
+ mjs: '.mjs',
329
+ ts: '.ts',
330
+ };
331
+ /**
332
+ * Try loading a `configure()`-style module config (JS → MJS → TS), preserving the format
333
+ * fall-through: a missing/failed format falls through to the next in {@link MODULE_CONFIG_FORMATS};
334
+ * exhausting the chain is the terminal "no usable config" error. Collapses the formerly-duplicated
335
+ * `tryJsConfig`/`tryMjsConfig` helpers into one format-parameterized loader.
336
+ *
337
+ * NOTE: the terminal "No configuration file found" message intentionally advertises only
338
+ * json/js/mjs (the historical, asserted wording) — `.ts` is a quiet lowest-precedence fallback.
339
+ */
340
+ async function tryModuleConfig(format, commandLineConfigOverrides, baseDir) {
341
+ const filename = MODULE_CONFIG_FILENAME[format];
342
+ const ext = MODULE_CONFIG_EXT[format];
343
+ const nextFormat = MODULE_CONFIG_FORMATS[MODULE_CONFIG_FORMATS.indexOf(format) + 1];
344
+ const configPath = commandLineConfigOverrides.customConfigPath ??
345
+ resolveConfigPath(baseDir, filename, commandLineConfigOverrides.identityProfile);
346
+ if (configPath.endsWith(ext) && existsSync(configPath)) {
347
+ try {
348
+ const i = await importExternalFile(configPath);
349
+ const customConfig = validateRawConfigLayer((await i.configure()), filename);
350
+ const mergedWithGlobal = await applyGlobalConfigBase(customConfig);
351
+ return await mergeConfig(mergedWithGlobal, commandLineConfigOverrides);
352
+ }
353
+ catch (e) {
354
+ displayDebug(e instanceof Error ? e : String(e));
355
+ if (nextFormat) {
356
+ displayError(`Failed to read config from ${filename}, will try other formats.`);
357
+ // Continue to try other formats
358
+ return await tryModuleConfig(nextFormat, commandLineConfigOverrides, baseDir);
359
+ }
360
+ displayError(`Failed to read config from ${filename}.`);
361
+ displayError(`No valid configuration found. Please create a valid configuration file.`);
362
+ exit(1);
363
+ }
364
+ }
365
+ else if (nextFormat) {
366
+ // This format not found, try the next one
367
+ return await tryModuleConfig(nextFormat, commandLineConfigOverrides, baseDir);
368
+ }
369
+ else {
370
+ // No config files found
371
+ displayError('No configuration file found. Please create one of: ' +
372
+ `${USER_PROJECT_CONFIG_JSON}, ${USER_PROJECT_CONFIG_JS}, or ${USER_PROJECT_CONFIG_MJS} ` +
373
+ 'in your project directory.');
374
+ exit(1);
375
+ }
376
+ // This throw is unreachable due to exit(1) above, but satisfies TS type analysis and prevents tests from exiting
377
+ throw new Error('Unexpected error occurred.');
378
+ }
379
+ /**
380
+ * Process JSON LLM config by creating the appropriate LLM instance
381
+ * @param jsonConfig - The parsed JSON config
382
+ * @param commandLineConfigOverrides - command line config overrides
383
+ * @returns Promise<GthConfig>
384
+ */
385
+ export async function tryJsonConfig(jsonConfig, commandLineConfigOverrides) {
386
+ try {
387
+ if (jsonConfig.llm && typeof jsonConfig.llm === 'object') {
388
+ // Get the type of LLM (e.g. 'vertexai', 'anthropic') - this should exist
389
+ const llmType = jsonConfig.llm.type;
390
+ if (!llmType) {
391
+ displayError('LLM type not specified in config.');
392
+ exit(1);
393
+ }
394
+ // Get the configuration for the specific LLM type
395
+ const llmConfig = jsonConfig.llm;
396
+ if (commandLineConfigOverrides.verbose) {
397
+ // Necessary to avoid https://github.com/langchain-ai/langchainjs/issues/8705
398
+ llmConfig.verbose = commandLineConfigOverrides.verbose;
399
+ }
400
+ // Import the appropriate config module
401
+ const configModule = await import(`#src/providers/${llmType}.js`);
402
+ if (configModule.processJsonConfig) {
403
+ const llm = (await configModule.processJsonConfig(llmConfig));
404
+ const mergedConfig = mergeRawConfig(jsonConfig, llm, commandLineConfigOverrides);
405
+ if (configModule.postProcessJsonConfig) {
406
+ return await configModule.postProcessJsonConfig(mergedConfig);
407
+ }
408
+ else {
409
+ return await mergedConfig;
410
+ }
411
+ }
412
+ else {
413
+ displayWarning(`Config module for ${llmType} does not have processJsonConfig function.`);
414
+ exit(1);
415
+ }
416
+ }
417
+ else {
418
+ displayError('No LLM configuration found in config.');
419
+ exit(1);
420
+ }
421
+ }
422
+ catch (e) {
423
+ if (e instanceof Error && e.message.includes('Cannot find module')) {
424
+ displayError(`LLM type '${jsonConfig.llm.type}' not supported.`);
425
+ }
426
+ else {
427
+ displayError(`Error processing LLM config: ${e instanceof Error ? e.message : String(e)}`);
428
+ }
429
+ exit(1);
430
+ }
431
+ // This throw is unreachable due to exit(1) above, but satisfies TS type analysis and prevents tests from exiting
432
+ throw new Error('Unexpected error occurred.');
433
+ }
434
+ /**
435
+ * Config array fields whose values ADD UP across merge layers (global → project): the
436
+ * merged result is both layers concatenated (target/lower-precedence first) and de-duplicated
437
+ * by value, instead of the higher-precedence layer replacing the lower. Keyed by dotted path
438
+ * from the config root.
439
+ *
440
+ * CONSERVATIVE BY DESIGN — only genuinely-cumulative lists are additive. Everything else keeps
441
+ * REPLACE semantics, because those express "this is THE set" and silently unioning them across
442
+ * global + project would surprise users.
443
+ *
444
+ * | array field | policy | rationale |
445
+ * | -------------------- | -------- | ---------------------------------------------------- |
446
+ * | `allowDirs` | ADDITIVE | extra sandbox roots accumulate across layers |
447
+ * | `aiignore.patterns` | ADDITIVE | ignore patterns accumulate across layers |
448
+ * | `allowedTools` | replace | the explicit allow-list IS the set |
449
+ * | `builtInTools` | replace | the explicit tool selection IS the set |
450
+ * | `tools` | replace | live tool instances; union would be surprising |
451
+ * | `middleware` | replace | ordered pipeline; union would reorder/duplicate |
452
+ * | `binaryFormats` | replace | the declared format policy IS the set |
453
+ * | (every other array) | replace | default; preserves historical behaviour |
454
+ *
455
+ * NOTE: the additive fields only live at the config ROOT, so only the
456
+ * `applyGlobalConfigBase(global, project)` merge can trigger them; the per-command
457
+ * `deepMerge` calls start at command scope and never reach these paths.
458
+ *
459
+ * NAMESPACE CAVEAT: these keys are config-ROOT-relative, but the per-command
460
+ * `deepMerge(DEFAULT_CONFIG.commands.X, …)` calls also start at `path === ''`. No command
461
+ * default carries `allowDirs`/`aiignore`, so there is no collision today — but do NOT add a
462
+ * key here that could also appear as a per-command field, or it would silently become additive
463
+ * inside command merges too.
464
+ */
465
+ const ADDITIVE_ARRAY_FIELDS = new Set(['allowDirs', 'aiignore.patterns']);
466
+ /**
467
+ * Deep merge two objects, with source overriding target properties.
468
+ * Objects are merged recursively. Arrays REPLACE by default; arrays at an
469
+ * {@link ADDITIVE_ARRAY_FIELDS} path are concatenated (target-first) then de-duplicated by
470
+ * value. Every other non-plain-object value is replaced by the source value.
471
+ * @param target - The target object with default values (lower-precedence layer)
472
+ * @param source - The source object with user overrides (higher-precedence layer)
473
+ * @param path - Dotted path from the config root, used to look up the array merge policy.
474
+ */
475
+ function deepMerge(target, source, path = '') {
476
+ if (!source)
477
+ return target;
478
+ if (!target)
479
+ return source;
480
+ const result = { ...target };
481
+ for (const key in source) {
482
+ const sourceValue = source[key];
483
+ const targetValue = target[key];
484
+ const fieldPath = path ? `${path}.${key}` : key;
485
+ if (sourceValue &&
486
+ typeof sourceValue === 'object' &&
487
+ !Array.isArray(sourceValue) &&
488
+ targetValue &&
489
+ typeof targetValue === 'object' &&
490
+ !Array.isArray(targetValue)) {
491
+ // Recursively merge nested objects
492
+ result[key] = deepMerge(targetValue, sourceValue, fieldPath);
493
+ }
494
+ else if (Array.isArray(sourceValue) &&
495
+ Array.isArray(targetValue) &&
496
+ ADDITIVE_ARRAY_FIELDS.has(fieldPath)) {
497
+ // Additive list: concat both layers (target/lower-precedence first), de-dupe by value.
498
+ result[key] = [...new Set([...targetValue, ...sourceValue])];
499
+ }
500
+ else if (sourceValue !== undefined) {
501
+ // Override with source value if it exists (arrays REPLACE by default)
502
+ result[key] = sourceValue;
503
+ }
504
+ }
505
+ return result;
506
+ }
507
+ /**
508
+ * Resolve a fully-merged {@link GthConfig} from a partial config + CLI overrides WITHOUT
509
+ * any global side effects (a pure transform). It deep-merges defaults, applies CLI overrides,
510
+ * resolves the numeric `consoleLevel` (warning + defaulting to INFO on an invalid value), and
511
+ * computes `canInterruptInferenceWithEsc`. The process-global setters (`setUseColour` /
512
+ * `setConsoleLevel`) are applied separately by {@link mergeConfig}, so this function can be
513
+ * reasoned about and reused without touching global state.
514
+ */
515
+ export function resolveConfig(partialConfig, commandLineConfigOverrides) {
516
+ const config = partialConfig;
517
+ // Deep merge command configs while preserving defaults
518
+ // Type complexity from DEFAULT_CONFIG.commands 'as const' requires any cast for deep merge result
519
+ const mergedCommands = {
520
+ pr: deepMerge(DEFAULT_CONFIG.commands.pr, config?.commands?.pr), // eslint-disable-line @typescript-eslint/no-explicit-any
521
+ review: deepMerge(DEFAULT_CONFIG.commands.review, config?.commands?.review), // eslint-disable-line @typescript-eslint/no-explicit-any
522
+ code: deepMerge(DEFAULT_CONFIG.commands.code, config?.commands?.code), // eslint-disable-line @typescript-eslint/no-explicit-any
523
+ exec: deepMerge(DEFAULT_CONFIG.commands.exec, config?.commands?.exec), // eslint-disable-line @typescript-eslint/no-explicit-any
524
+ ask: deepMerge(DEFAULT_CONFIG.commands.ask, config?.commands?.ask), // eslint-disable-line @typescript-eslint/no-explicit-any
525
+ chat: deepMerge(DEFAULT_CONFIG.commands.chat, config?.commands?.chat), // eslint-disable-line @typescript-eslint/no-explicit-any
526
+ api: deepMerge(DEFAULT_CONFIG.commands.api, config?.commands?.api), // eslint-disable-line @typescript-eslint/no-explicit-any
527
+ };
528
+ const mergedConfig = {
529
+ ...DEFAULT_CONFIG,
530
+ ...config,
531
+ commands: mergedCommands,
532
+ };
533
+ if (commandLineConfigOverrides.identityProfile !== undefined) {
534
+ displayInfo(`Activating profile: ${commandLineConfigOverrides.identityProfile}`);
535
+ mergedConfig.identityProfile = commandLineConfigOverrides.identityProfile.trim();
536
+ }
537
+ if (commandLineConfigOverrides.verbose !== undefined) {
538
+ mergedConfig.llm.verbose = commandLineConfigOverrides.verbose;
539
+ }
540
+ if (commandLineConfigOverrides.writeOutputToFile !== undefined) {
541
+ mergedConfig.writeOutputToFile = commandLineConfigOverrides.writeOutputToFile;
542
+ }
543
+ // Resolve console logging level (value only; the global setter is applied in mergeConfig).
544
+ if (mergedConfig.consoleLevel !== undefined) {
545
+ const resolvedConsoleLevel = resolveConsoleLevel(mergedConfig.consoleLevel);
546
+ if (resolvedConsoleLevel !== undefined) {
547
+ mergedConfig.consoleLevel = resolvedConsoleLevel;
548
+ }
549
+ else {
550
+ displayWarning(`Invalid consoleLevel "${String(mergedConfig.consoleLevel)}", using default ${StatusLevel.INFO}.`);
551
+ mergedConfig.consoleLevel = StatusLevel.INFO;
552
+ }
553
+ }
554
+ mergedConfig.canInterruptInferenceWithEsc = mergedConfig.canInterruptInferenceWithEsc && isTTY();
555
+ return mergedConfig;
556
+ }
557
+ /**
558
+ * Merge config with default config, then apply the resolved colour + console-level settings
559
+ * to the process globals. Thin wrapper over the pure {@link resolveConfig}; kept `async` with
560
+ * the same signature so every existing caller (`mergeRawConfig`, `tryJsConfig`, `tryMjsConfig`)
561
+ * behaves identically — the two `set*` calls are the only global mutations in the merge path.
562
+ */
563
+ async function mergeConfig(partialConfig, commandLineConfigOverrides) {
564
+ const mergedConfig = resolveConfig(partialConfig, commandLineConfigOverrides);
565
+ // Set the useColour value in systemUtils.
566
+ setUseColour(mergedConfig.useColour);
567
+ // Set console logging level.
568
+ if (mergedConfig.consoleLevel !== undefined) {
569
+ setConsoleLevel(mergedConfig.consoleLevel);
570
+ }
571
+ return mergedConfig;
572
+ }
573
+ const CONSOLE_LEVELS_BY_NAME = {
574
+ debug: StatusLevel.DEBUG,
575
+ info: StatusLevel.INFO,
576
+ display: StatusLevel.DISPLAY,
577
+ success: StatusLevel.SUCCESS,
578
+ warning: StatusLevel.WARNING,
579
+ error: StatusLevel.ERROR,
580
+ stream: StatusLevel.STREAM,
581
+ };
582
+ function resolveConsoleLevel(level) {
583
+ if (typeof level === 'number') {
584
+ return StatusLevel[level] !== undefined ? level : undefined;
585
+ }
586
+ if (typeof level === 'string') {
587
+ const normalized = level.trim().toLowerCase();
588
+ if (normalized in CONSOLE_LEVELS_BY_NAME) {
589
+ return CONSOLE_LEVELS_BY_NAME[normalized];
590
+ }
591
+ const enumValue = StatusLevel[level];
592
+ if (typeof enumValue === 'number') {
593
+ return enumValue;
594
+ }
595
+ }
596
+ return undefined;
597
+ }
598
+ /**
599
+ * Read a raw config object from an on-disk path WITHOUT validating, building an LLM, or
600
+ * merging defaults. JSON/JSONC files are parsed leniently ({@link parseJsonc}); module
601
+ * formats (`.js`/`.mjs`/`.ts`) are imported and their `configure()` invoked. Used by the
602
+ * read-side {@link validateConfig}; may throw on a parse/module error (surfaced by the caller).
603
+ */
604
+ async function readRawConfigAtPath(path) {
605
+ if (path.endsWith('.json') || path.endsWith('.jsonc')) {
606
+ return parseJsonc(readFileSync(path, 'utf8'), path);
607
+ }
608
+ const imported = await importExternalFile(path);
609
+ return (await imported.configure());
610
+ }
611
+ /**
612
+ * Global config read for the read-side {@link validateConfig}: mirrors
613
+ * {@link loadGlobalRawConfig}'s lookup order (JSON → JS → MJS) but does NOT validate or
614
+ * `exit` — it just returns the raw object + a source label so the validator owns the verdict.
615
+ */
616
+ async function loadGlobalRawConfigUnvalidated() {
617
+ const jsonPath = getGlobalGslothConfigReadPath(USER_PROJECT_CONFIG_JSON);
618
+ if (existsSync(jsonPath)) {
619
+ const label = `${USER_PROJECT_CONFIG_JSON} (global)`;
620
+ return {
621
+ raw: parseJsonc(readFileSync(jsonPath, 'utf8'), label),
622
+ label,
623
+ };
624
+ }
625
+ for (const filename of [USER_PROJECT_CONFIG_JS, USER_PROJECT_CONFIG_MJS]) {
626
+ const modulePath = getGlobalGslothConfigReadPath(filename);
627
+ if (existsSync(modulePath)) {
628
+ const imported = await importExternalFile(modulePath);
629
+ return {
630
+ raw: (await imported.configure()),
631
+ label: `${filename} (global)`,
632
+ };
633
+ }
634
+ }
635
+ return undefined;
636
+ }
637
+ /**
638
+ * Locate and validate the effective raw config against the schema WITHOUT building the LLM
639
+ * or merging defaults (the read-side of GS2-1). Honours `--config`, up-tree discovery, and
640
+ * the identity profile via {@link findProjectConfigPath}, falling back to a standalone global
641
+ * config (CFG-8 order) when no project config exists. A JSONC/module parse failure is thrown
642
+ * to the caller (surfaced as a clear "invalid config" error + non-zero exit).
643
+ */
644
+ export async function validateConfig(commandLineConfigOverrides) {
645
+ const discovered = findProjectConfigPath(commandLineConfigOverrides);
646
+ if (discovered) {
647
+ const raw = await readRawConfigAtPath(discovered.path);
648
+ return { found: true, sourceLabel: discovered.path, ...validateRawGthConfig(raw) };
649
+ }
650
+ const globalRaw = await loadGlobalRawConfigUnvalidated();
651
+ if (globalRaw) {
652
+ return { found: true, sourceLabel: globalRaw.label, ...validateRawGthConfig(globalRaw.raw) };
653
+ }
654
+ return { found: false, ok: false, warnings: [] };
655
+ }
656
+ /**
657
+ * Merge raw with default config
658
+ */
659
+ async function mergeRawConfig(config, llm, commandLineConfigOverrides) {
660
+ const modelDisplayName = config.llm?.model;
661
+ return await mergeConfig({ ...config, llm, modelDisplayName }, commandLineConfigOverrides);
662
+ }
663
+ //# sourceMappingURL=loader.js.map