@wraith-ai/core 0.1.0 → 0.1.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 (153) hide show
  1. package/README.md +1 -1
  2. package/dist/{attempt-BeB7EltG.d.mts → attempt-HgararU3.d.mts} +2 -1
  3. package/dist/attempt-HgararU3.d.mts.map +1 -0
  4. package/dist/{capabilities-BPb5HSH6.d.mts → capabilities-CNsPrkB7.d.mts} +2 -1
  5. package/dist/capabilities-CNsPrkB7.d.mts.map +1 -0
  6. package/dist/index.d.mts +6 -5
  7. package/dist/index.d.mts.map +1 -0
  8. package/dist/index.mjs +11 -9
  9. package/dist/index.mjs.map +1 -0
  10. package/dist/{methods-CZp6XGn8.mjs → methods-7Ryz6zbd.mjs} +4 -2
  11. package/dist/methods-7Ryz6zbd.mjs.map +1 -0
  12. package/dist/{model-B6tJ9kX_.mjs → model-C16NUwXW.mjs} +2 -0
  13. package/dist/model-C16NUwXW.mjs.map +1 -0
  14. package/dist/{model-D6LQSveS.d.mts → model-_wqePNTL.d.mts} +4 -3
  15. package/dist/model-_wqePNTL.d.mts.map +1 -0
  16. package/dist/{models-dev-Y0ZikMBQ.d.mts → models-dev-DNgymZy3.d.mts} +3 -2
  17. package/dist/models-dev-DNgymZy3.d.mts.map +1 -0
  18. package/dist/{openai-codex-BhtZvNpm.mjs → openai-codex-Bz1EFPEi.mjs} +3 -1
  19. package/dist/openai-codex-Bz1EFPEi.mjs.map +1 -0
  20. package/dist/{openai-codex-Bk-iG7MZ.mjs → openai-codex-uvjhVoVy.mjs} +6 -4
  21. package/dist/openai-codex-uvjhVoVy.mjs.map +1 -0
  22. package/dist/{openai-compatible-hkXv-P74.mjs → openai-compatible-DBppnQ_N.mjs} +4 -2
  23. package/dist/openai-compatible-DBppnQ_N.mjs.map +1 -0
  24. package/dist/{openrouter-BflQBug2.mjs → openrouter-D8nTOAQo.mjs} +5 -3
  25. package/dist/openrouter-D8nTOAQo.mjs.map +1 -0
  26. package/dist/providers/openai-codex.d.mts +4 -3
  27. package/dist/providers/openai-codex.d.mts.map +1 -0
  28. package/dist/providers/openai-codex.mjs +1 -1
  29. package/dist/providers/openai-compatible.d.mts +3 -2
  30. package/dist/providers/openai-compatible.d.mts.map +1 -0
  31. package/dist/providers/openai-compatible.mjs +1 -1
  32. package/dist/providers/openrouter.d.mts +3 -2
  33. package/dist/providers/openrouter.d.mts.map +1 -0
  34. package/dist/providers/openrouter.mjs +1 -1
  35. package/dist/{shared-8d7RsyPH.mjs → shared-BIJaPhMm.mjs} +3 -1
  36. package/dist/shared-BIJaPhMm.mjs.map +1 -0
  37. package/dist/snapshot.d.mts +3 -2
  38. package/dist/snapshot.d.mts.map +1 -0
  39. package/dist/snapshot.mjs +4999 -4977
  40. package/dist/snapshot.mjs.map +1 -0
  41. package/dist/{turn-effort-DquDDwdE.mjs → turn-effort-C61L4JIt.mjs} +2 -0
  42. package/dist/turn-effort-C61L4JIt.mjs.map +1 -0
  43. package/package.json +3 -2
  44. package/src/agent/agent.ts +90 -0
  45. package/src/agent/attachments.ts +195 -0
  46. package/src/agent/classifier.ts +525 -0
  47. package/src/agent/compact.ts +384 -0
  48. package/src/agent/conversation.ts +300 -0
  49. package/src/agent/cost.ts +164 -0
  50. package/src/agent/inbox.ts +80 -0
  51. package/src/agent/instructions.ts +62 -0
  52. package/src/agent/loop.ts +675 -0
  53. package/src/agent/messages.ts +252 -0
  54. package/src/agent/on-demand.ts +58 -0
  55. package/src/agent/prompts.ts +35 -0
  56. package/src/agent/request-images.ts +94 -0
  57. package/src/agent/stop.ts +37 -0
  58. package/src/agent/title.ts +122 -0
  59. package/src/agent/tool-groups.ts +186 -0
  60. package/src/agent/tools.ts +106 -0
  61. package/src/app.ts +67 -0
  62. package/src/config/credential-file-store.ts +66 -0
  63. package/src/config/environment.ts +105 -0
  64. package/src/config/instructions.ts +157 -0
  65. package/src/config/load.ts +667 -0
  66. package/src/config/locked-file.ts +85 -0
  67. package/src/config/paths.ts +368 -0
  68. package/src/config/schema.ts +363 -0
  69. package/src/config/subagents.ts +156 -0
  70. package/src/config/trust.ts +53 -0
  71. package/src/config/write.ts +241 -0
  72. package/src/errors.ts +85 -0
  73. package/src/events/types.ts +258 -0
  74. package/src/glob.ts +161 -0
  75. package/src/index.ts +681 -0
  76. package/src/logger.ts +47 -0
  77. package/src/paths.ts +143 -0
  78. package/src/permissions/chain.ts +42 -0
  79. package/src/permissions/command.ts +233 -0
  80. package/src/permissions/layered.ts +77 -0
  81. package/src/permissions/match.ts +80 -0
  82. package/src/permissions/modes.ts +48 -0
  83. package/src/permissions/policy.ts +160 -0
  84. package/src/permissions/types.ts +159 -0
  85. package/src/providers/cache.ts +107 -0
  86. package/src/providers/capabilities.ts +77 -0
  87. package/src/providers/catalog-view.ts +91 -0
  88. package/src/providers/catalog.ts +65 -0
  89. package/src/providers/errors.ts +108 -0
  90. package/src/providers/factories/index.ts +15 -0
  91. package/src/providers/factories/openai-codex.ts +382 -0
  92. package/src/providers/factories/openai-compatible.ts +81 -0
  93. package/src/providers/factories/openrouter.ts +165 -0
  94. package/src/providers/factories/shared.ts +22 -0
  95. package/src/providers/model.ts +197 -0
  96. package/src/providers/models-dev.ts +355 -0
  97. package/src/providers/oauth/methods.ts +10 -0
  98. package/src/providers/oauth/openai-codex.ts +228 -0
  99. package/src/providers/oauth.ts +177 -0
  100. package/src/providers/openai-codex.ts +7 -0
  101. package/src/providers/openai-compatible.ts +2 -0
  102. package/src/providers/openrouter.ts +2 -0
  103. package/src/providers/registry.ts +464 -0
  104. package/src/providers/turn-effort.ts +156 -0
  105. package/src/providers/types.ts +83 -0
  106. package/src/session/backend.ts +44 -0
  107. package/src/session/file-store.ts +278 -0
  108. package/src/session/format.ts +1037 -0
  109. package/src/session/memory-store.ts +73 -0
  110. package/src/session/session.ts +153 -0
  111. package/src/session/store.ts +219 -0
  112. package/src/sign-in/attempt.ts +166 -0
  113. package/src/sign-in/loopback.ts +74 -0
  114. package/src/snapshot/data.json +8936 -0
  115. package/src/snapshot/index.ts +37 -0
  116. package/src/tools/bin.ts +364 -0
  117. package/src/tools/builtin.ts +48 -0
  118. package/src/tools/change.ts +88 -0
  119. package/src/tools/define.ts +267 -0
  120. package/src/tools/describe.ts +96 -0
  121. package/src/tools/fs/edit-file.ts +129 -0
  122. package/src/tools/fs/glob.ts +75 -0
  123. package/src/tools/fs/grep.ts +212 -0
  124. package/src/tools/fs/line-endings.ts +17 -0
  125. package/src/tools/fs/list-dir.ts +85 -0
  126. package/src/tools/fs/read-file.ts +230 -0
  127. package/src/tools/fs/ripgrep.ts +211 -0
  128. package/src/tools/fs/write-file.ts +97 -0
  129. package/src/tools/job.ts +252 -0
  130. package/src/tools/mcp/auth-store.ts +127 -0
  131. package/src/tools/mcp/command.ts +151 -0
  132. package/src/tools/mcp/config.ts +168 -0
  133. package/src/tools/mcp/servers.ts +463 -0
  134. package/src/tools/mcp/sign-in.ts +226 -0
  135. package/src/tools/mcp/stdio.ts +204 -0
  136. package/src/tools/mcp/tools.ts +173 -0
  137. package/src/tools/on-demand.ts +184 -0
  138. package/src/tools/registry.ts +935 -0
  139. package/src/tools/shell/bash.ts +217 -0
  140. package/src/tools/shell/find-bash.ts +162 -0
  141. package/src/tools/source.ts +35 -0
  142. package/src/tools/spill.ts +127 -0
  143. package/src/tools/subagents.ts +597 -0
  144. package/src/tools/tasks.ts +603 -0
  145. package/src/tools/to-model.ts +33 -0
  146. package/src/tools/web/address.ts +95 -0
  147. package/src/tools/web/exa.ts +163 -0
  148. package/src/tools/web/fetch.ts +373 -0
  149. package/src/tools/web/html.ts +173 -0
  150. package/src/tools/web/search.ts +111 -0
  151. package/src/tools/web/source.ts +51 -0
  152. package/src/units.ts +18 -0
  153. package/src/version.ts +23 -0
@@ -0,0 +1,667 @@
1
+ import { readFileSync, readdirSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join, posix, win32 } from "node:path";
4
+ import type { z } from "zod";
5
+ import { LOCAL_CONFIG_FILE_NAME, WRAITH, type AppIdentity, envVar } from "../app";
6
+ import { AgentError } from "../errors";
7
+ import { projectInstructionFiles } from "./instructions";
8
+ import { AGENT_FILE_EXTENSION, type AppPaths, type EntryKind, resolveAppPaths } from "./paths";
9
+ import {
10
+ type Config,
11
+ type ConfigInput,
12
+ DEFAULT_INSTRUCTION_FILES,
13
+ configSchema,
14
+ SERVICE_KEY_ENV,
15
+ type ServiceName,
16
+ credentialsSchema,
17
+ defaultApiKeyEnv,
18
+ parseConfig,
19
+ } from "./schema";
20
+
21
+ /**
22
+ * Precedence, lowest to highest: schema defaults → user config → project config
23
+ * → project local config → credentials → environment → explicit overrides.
24
+ *
25
+ * Everything arrives here as a partial input; the schema fills the gaps exactly
26
+ * once. Only this module in the core is allowed to read `process.env`. A
27
+ * library host skips all of this and parses its own object with `configSchema`:
28
+ * no disk, no home directory, no environment.
29
+ */
30
+
31
+ export type ConfigOrigin =
32
+ | "defaults"
33
+ | "user"
34
+ | "project"
35
+ | "local"
36
+ | "credentials"
37
+ | "env"
38
+ | "overrides";
39
+
40
+ /** Whether the project's own files may configure this run. The host decides. */
41
+ export type ProjectTrust = "trusted" | "untrusted";
42
+
43
+ /** A setting that was present and not applied — reported, never dropped silently. */
44
+ export interface IgnoredSetting {
45
+ /** The file it came from. */
46
+ source: string;
47
+ /** A dotted config path, or a variable name for a `.env` file; `*` for a whole file. */
48
+ setting: string;
49
+ reason: string;
50
+ }
51
+
52
+ /** What a trust decision would change here, found without applying any of it. */
53
+ export interface ProjectInspection {
54
+ /** Resolved without a `<APP>_HOME` the workspace declared — a repo must not move `~/.wraith`. */
55
+ paths: AppPaths;
56
+ /** The project's files that exist: its config, its prompt, its agents, its AGENTS.md. */
57
+ files: string[];
58
+ /** Our variables declared by the workspace's `.env` files — names only. */
59
+ variables: { name: string; file: string }[];
60
+ }
61
+
62
+ export interface LoadedConfig<C extends Config = Config> {
63
+ config: C;
64
+ paths: AppPaths;
65
+ /** The decision this was loaded under, echoed for whoever prints the result. */
66
+ project: ProjectTrust;
67
+ /** Everything the project tried to set and did not get to. */
68
+ ignored: IgnoredSetting[];
69
+ /** Which layers actually contributed, for `wraith config show`. */
70
+ origins: ConfigOrigin[];
71
+ /** Config files that were read, in the order they were applied. */
72
+ configFiles: string[];
73
+ /**
74
+ * Providers whose key came from `credentials.json` rather than the config
75
+ * files; `wraith key list` names that file. The key never leaves this module.
76
+ */
77
+ credentialProviders: string[];
78
+ /**
79
+ * Keys stored for providers that are not configured at all. Without this the
80
+ * file looks right, the key is ignored, and nothing says so.
81
+ */
82
+ strandedCredentials: string[];
83
+ /**
84
+ * Stored keys for services that are not providers (`SERVICE_KEY_ENV`). The
85
+ * host hands one to the tool that needs it, after the environment variable
86
+ * that wins over it.
87
+ */
88
+ serviceKeys: Partial<Record<ServiceName, string>>;
89
+ /**
90
+ * Key variables declared by a `.env` inside the project, for providers and
91
+ * services. The name only, never the value: this is not a `.env` parser, and
92
+ * filling `process.env` stays the runtime's job. They have to be surfaced by
93
+ * whatever the user is looking at, not only by a command they might run,
94
+ * because `process.env` cannot tell a shell export from a `.env` file the
95
+ * agent can read.
96
+ */
97
+ workspaceEnvKeys: string[];
98
+ }
99
+
100
+ export interface LoadConfigOptions {
101
+ /**
102
+ * Required, with no default. `"untrusted"` skips the project's files and the
103
+ * variables its `.env` declares.
104
+ */
105
+ project: ProjectTrust;
106
+ /**
107
+ * The host's own settings, validated and defaulted with the core's.
108
+ * Give `setConfigValue` the same one, or what it writes is never checked.
109
+ */
110
+ extend?: z.ZodObject;
111
+ cwd?: string;
112
+ home?: string;
113
+ platform?: string;
114
+ env?: Record<string, string | undefined>;
115
+ overrides?: ConfigInput;
116
+ /** Which product's directories and variables to look for. */
117
+ app?: AppIdentity;
118
+ /** Injectable so tests never touch the disk. Returns null when absent. */
119
+ readFile?: (path: string) => string | null;
120
+ /** Same, for the walk up to the project root (`paths.ts`). */
121
+ hasProjectDir?: (directory: string) => boolean;
122
+ /** Same, for finding the git checkout and its repository (`paths.ts`). */
123
+ entryKind?: (path: string) => EntryKind | undefined;
124
+ /** Same, for the names in a directory; none when it is not there. */
125
+ listDir?: (directory: string) => string[];
126
+ }
127
+
128
+ function defaultReadFile(path: string): string | null {
129
+ try {
130
+ return readFileSync(path, "utf8");
131
+ } catch {
132
+ return null;
133
+ }
134
+ }
135
+
136
+ function defaultEntryKind(path: string): EntryKind | undefined {
137
+ try {
138
+ const stat = statSync(path);
139
+ return stat.isDirectory() ? "directory" : stat.isFile() ? "file" : undefined;
140
+ } catch {
141
+ return undefined;
142
+ }
143
+ }
144
+
145
+ function defaultListDir(directory: string): string[] {
146
+ try {
147
+ return readdirSync(directory);
148
+ } catch {
149
+ return [];
150
+ }
151
+ }
152
+
153
+ /**
154
+ * The project's own kinds of agent, as files. A role for an agent that runs
155
+ * with the user's tools is settings like the rest, so it is asked about.
156
+ */
157
+ function projectAgentFiles(
158
+ paths: AppPaths,
159
+ listDir: (directory: string) => string[],
160
+ platform: string,
161
+ ): string[] {
162
+ const directory = paths.projectAgentsDir;
163
+ if (directory === undefined) return [];
164
+ const path = platform === "win32" ? win32 : posix;
165
+ return listDir(directory)
166
+ .filter((name) => name.endsWith(AGENT_FILE_EXTENSION))
167
+ .sort()
168
+ .map((name) => path.join(directory, name));
169
+ }
170
+
171
+ function defaultHasProjectDir(app: AppIdentity): (directory: string) => boolean {
172
+ return (directory) => {
173
+ try {
174
+ return statSync(join(directory, app.projectDirName)).isDirectory();
175
+ } catch {
176
+ return false;
177
+ }
178
+ };
179
+ }
180
+
181
+ /**
182
+ * Whether the project's `.env` declares a variable — the name, never the value.
183
+ *
184
+ * Not a `.env` parser, and it must not become one. Anchored per line, so a name
185
+ * mentioned inside a comment or somebody else's value does not count.
186
+ */
187
+ function declaredInEnvFile(
188
+ envFile: string,
189
+ variables: readonly string[],
190
+ readFile: (path: string) => string | null,
191
+ ): string[] {
192
+ if (variables.length === 0) return [];
193
+ const contents = readFile(envFile);
194
+ if (contents === null) return [];
195
+
196
+ return variables.filter((variable) =>
197
+ new RegExp(
198
+ `^[ \\t]*(?:export[ \\t]+)?${variable.replace(/[^A-Za-z0-9_]/g, "\\$&")}[ \\t]*=`,
199
+ "m",
200
+ ).test(contents),
201
+ );
202
+ }
203
+
204
+ /** The files Bun loads into `process.env` on its own — the same list for every app. */
205
+ const ENV_FILE_NAMES = [".env", ".env.local", ".env.development", ".env.production", ".env.test"];
206
+
207
+ /** Bun reads them from the working directory; the project root is where people keep them. */
208
+ function envFilesAt(roots: readonly string[], platform: string): string[] {
209
+ const path = platform === "win32" ? win32 : posix;
210
+ return [...new Set(roots.flatMap((root) => ENV_FILE_NAMES.map((name) => path.join(root, name))))];
211
+ }
212
+
213
+ /** Every variable with our prefix a `.env` file assigns — names only, never values. */
214
+ function declaredWithPrefix(
215
+ envFile: string,
216
+ prefix: string,
217
+ readFile: (path: string) => string | null,
218
+ ): string[] {
219
+ const contents = readFile(envFile);
220
+ if (contents === null) return [];
221
+ const pattern = new RegExp(`^[ \\t]*(?:export[ \\t]+)?(${prefix}_[A-Za-z0-9_]+)[ \\t]*=`, "gm");
222
+ return [...contents.matchAll(pattern)].map((match) => match[1] as string);
223
+ }
224
+
225
+ export type InspectProjectOptions = Omit<LoadConfigOptions, "project">;
226
+
227
+ /**
228
+ * The instruction file names to ask about, before any config is loaded: the
229
+ * host's own, else the user's, else the default. A project's own choice needs
230
+ * no guess, since its config file is asked about already.
231
+ */
232
+ function instructionNames(
233
+ overrides: ConfigInput | undefined,
234
+ userConfig: string,
235
+ readFile: (path: string) => string | null,
236
+ ): readonly string[] {
237
+ const valid = (raw: unknown): readonly string[] | undefined => {
238
+ if (raw === undefined) return undefined;
239
+ const parsed = configSchema.shape.instructions.safeParse(raw);
240
+ return parsed.success ? parsed.data.files : undefined;
241
+ };
242
+ const fromOverrides = valid(overrides?.instructions);
243
+ if (fromOverrides !== undefined) return fromOverrides;
244
+ const contents = readFile(userConfig);
245
+ if (contents !== null) {
246
+ try {
247
+ const fromUser = valid(parseFile(userConfig, contents)["instructions"]);
248
+ if (fromUser !== undefined) return fromUser;
249
+ } catch {
250
+ // loadConfig reports an unreadable file; the question goes on with the default.
251
+ }
252
+ }
253
+ return DEFAULT_INSTRUCTION_FILES;
254
+ }
255
+
256
+ /**
257
+ * What a trust decision would change, for the host that has to ask about it.
258
+ * Nothing found means nothing to ask: the question is only worth a keypress when
259
+ * the project brings settings of its own.
260
+ */
261
+ export function inspectProject(options: InspectProjectOptions = {}): ProjectInspection {
262
+ const env = options.env ?? process.env;
263
+ const readFile = options.readFile ?? defaultReadFile;
264
+ const app = options.app ?? WRAITH;
265
+ const cwd = options.cwd ?? process.cwd();
266
+ const platform = options.platform ?? process.platform;
267
+ const base = {
268
+ cwd,
269
+ home: options.home ?? homedir(),
270
+ platform,
271
+ app,
272
+ hasProjectDir: options.hasProjectDir ?? defaultHasProjectDir(app),
273
+ entryKind: options.entryKind ?? defaultEntryKind,
274
+ readFile,
275
+ };
276
+
277
+ const variablesIn = (roots: readonly string[]): { name: string; file: string }[] =>
278
+ envFilesAt(roots, platform).flatMap((file) =>
279
+ declaredWithPrefix(file, app.envPrefix, readFile).map((name) => ({ name, file })),
280
+ );
281
+
282
+ let paths = resolveAppPaths({ ...base, env });
283
+ let variables = variablesIn([cwd, paths.projectRoot]);
284
+
285
+ // A repo that moves the user's directory brings its own user config and
286
+ // its own record of what the user trusts.
287
+ const home = envVar("HOME", app);
288
+ if (variables.some((variable) => variable.name === home)) {
289
+ const { [home]: _dropped, ...rest } = env;
290
+ paths = resolveAppPaths({ ...base, env: rest });
291
+ variables = variablesIn([cwd, paths.projectRoot]);
292
+ }
293
+
294
+ const files = [paths.projectConfig, paths.projectLocalConfig, paths.projectPrompt].filter(
295
+ (file): file is string => file !== undefined && readFile(file) !== null,
296
+ );
297
+ files.push(...projectAgentFiles(paths, options.listDir ?? defaultListDir, platform));
298
+ files.push(
299
+ ...projectInstructionFiles(
300
+ paths.checkoutRoot,
301
+ cwd,
302
+ instructionNames(options.overrides, paths.userConfig, readFile),
303
+ (file) => readFile(file) !== null,
304
+ platform === "win32" ? win32 : posix,
305
+ ),
306
+ );
307
+ return { paths, files, variables };
308
+ }
309
+
310
+ /**
311
+ * What no project gets to switch on, trusted or not: people click "yes"
312
+ * by reflex, and these two turn every later question off.
313
+ */
314
+ function applyFloor(
315
+ layer: Record<string, unknown>,
316
+ source: string,
317
+ ignored: IgnoredSetting[],
318
+ ): Record<string, unknown> {
319
+ const permissions = layer.permissions;
320
+ if (!isPlainObject(permissions)) return layer;
321
+
322
+ const next: Record<string, unknown> = { ...permissions };
323
+ if (next.mode === "yolo") {
324
+ delete next.mode;
325
+ ignored.push({ source, setting: "permissions.mode", reason: "a project may not turn yolo on" });
326
+ }
327
+ const classifier = next.classifier;
328
+ if (isPlainObject(classifier) && classifier.enabled === true) {
329
+ const { enabled: _enabled, ...rest } = classifier;
330
+ next.classifier = rest;
331
+ ignored.push({
332
+ source,
333
+ setting: "permissions.classifier.enabled",
334
+ reason: "a project may not turn auto mode on",
335
+ });
336
+ }
337
+ return { ...layer, permissions: next };
338
+ }
339
+
340
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
341
+ return typeof value === "object" && value !== null && !Array.isArray(value);
342
+ }
343
+
344
+ /** Objects merge recursively; arrays and scalars are replaced wholesale. */
345
+ function deepMerge(
346
+ base: Record<string, unknown>,
347
+ patch: Record<string, unknown>,
348
+ ): Record<string, unknown> {
349
+ const result: Record<string, unknown> = { ...base };
350
+ for (const [key, value] of Object.entries(patch)) {
351
+ if (value === undefined) continue;
352
+ const existing = result[key];
353
+ result[key] =
354
+ isPlainObject(existing) && isPlainObject(value) ? deepMerge(existing, value) : value;
355
+ }
356
+ return result;
357
+ }
358
+
359
+ function parseFile(path: string, contents: string): Record<string, unknown> {
360
+ let parsed: unknown;
361
+ try {
362
+ // Windows editors and PowerShell save JSON with a byte order mark,
363
+ // which JSON.parse rejects.
364
+ parsed = JSON.parse(contents.replace(/^/, ""));
365
+ } catch (cause) {
366
+ throw new AgentError("config/unreadable", `Config file is not valid JSON: ${path}`, {
367
+ cause,
368
+ details: { path },
369
+ });
370
+ }
371
+ if (!isPlainObject(parsed)) {
372
+ throw new AgentError("config/unreadable", `Config file must contain an object: ${path}`, {
373
+ details: { path },
374
+ });
375
+ }
376
+ return parsed;
377
+ }
378
+
379
+ function readNumber(raw: string, variable: string): number {
380
+ const value = Number(raw);
381
+ if (!Number.isFinite(value)) {
382
+ throw new AgentError("config/invalid", `${variable} must be a number, got "${raw}"`, {
383
+ details: { variable, value: raw },
384
+ });
385
+ }
386
+ return value;
387
+ }
388
+
389
+ const TRUE_WORDS = new Set(["1", "true", "yes", "on"]);
390
+ const FALSE_WORDS = new Set(["0", "false", "no", "off"]);
391
+
392
+ function readBoolean(raw: string, variable: string): boolean {
393
+ const word = raw.trim().toLowerCase();
394
+ if (TRUE_WORDS.has(word)) return true;
395
+ if (FALSE_WORDS.has(word)) return false;
396
+ throw new AgentError("config/invalid", `${variable} must be true or false, got "${raw}"`, {
397
+ details: { variable, value: raw },
398
+ });
399
+ }
400
+
401
+ /**
402
+ * Provider API keys are absent here: they are read by the provider registry
403
+ * from each provider's `apiKeyEnv`, so a secret never lands in the Config
404
+ * object that gets printed, logged or serialised.
405
+ */
406
+ function fromEnvironment(
407
+ env: Record<string, string | undefined>,
408
+ app: AppIdentity,
409
+ ): Record<string, unknown> {
410
+ const limits: Record<string, unknown> = {};
411
+ const permissions: Record<string, unknown> = {};
412
+ const session: Record<string, unknown> = {};
413
+ const cache: Record<string, unknown> = {};
414
+ const root: Record<string, unknown> = {};
415
+
416
+ const read = (name: string): string | undefined => env[envVar(name, app)];
417
+
418
+ const model = read("MODEL");
419
+ if (model) root.defaultModel = model;
420
+
421
+ const logLevel = read("LOG_LEVEL");
422
+ if (logLevel) root.logLevel = logLevel;
423
+
424
+ const maxSteps = read("MAX_STEPS");
425
+ if (maxSteps) limits.maxSteps = readNumber(maxSteps, envVar("MAX_STEPS", app));
426
+
427
+ const permissionsMode = read("PERMISSIONS_MODE");
428
+ if (permissionsMode) permissions.mode = permissionsMode;
429
+
430
+ const sessionStore = read("SESSION_STORE");
431
+ if (sessionStore) session.store = sessionStore;
432
+
433
+ const sessionDir = read("SESSION_DIR");
434
+ if (sessionDir) session.dir = sessionDir;
435
+
436
+ // Its own variable, so one run can turn the cache off and see what it saves.
437
+ const cacheEnabled = read("CACHE");
438
+ if (cacheEnabled) cache.enabled = readBoolean(cacheEnabled, envVar("CACHE", app));
439
+
440
+ const cacheTtl = read("CACHE_TTL");
441
+ if (cacheTtl) cache.ttl = cacheTtl;
442
+
443
+ if (Object.keys(limits).length > 0) root.limits = limits;
444
+ if (Object.keys(permissions).length > 0) root.permissions = permissions;
445
+ if (Object.keys(session).length > 0) root.session = session;
446
+ if (Object.keys(cache).length > 0) root.cache = cache;
447
+
448
+ return root;
449
+ }
450
+
451
+ // Two signatures so that a call without an extension gets `Config` exactly,
452
+ // and one with it gets the host's keys typed.
453
+ export function loadConfig<S extends z.ZodObject>(
454
+ options: Omit<LoadConfigOptions, "extend" | "overrides"> & {
455
+ extend: S;
456
+ overrides?: ConfigInput & z.input<S>;
457
+ },
458
+ ): LoadedConfig<Config & z.infer<S>>;
459
+ export function loadConfig(options: LoadConfigOptions): LoadedConfig;
460
+ export function loadConfig(options: LoadConfigOptions): LoadedConfig {
461
+ const env = options.env ?? process.env;
462
+ const readFile = options.readFile ?? defaultReadFile;
463
+ const app = options.app ?? WRAITH;
464
+ const trusted = options.project === "trusted";
465
+
466
+ const inspection = inspectProject(options);
467
+ const { paths } = inspection;
468
+ const ignored: IgnoredSetting[] = [];
469
+
470
+ const origins: ConfigOrigin[] = ["defaults"];
471
+ const configFiles: string[] = [];
472
+ let merged: Record<string, unknown> = {};
473
+
474
+ const layers: { path: string | undefined; origin: ConfigOrigin; project: boolean }[] = [
475
+ { path: paths.userConfig, origin: "user", project: false },
476
+ { path: paths.projectConfig, origin: "project", project: true },
477
+ { path: paths.projectLocalConfig, origin: "local", project: true },
478
+ ];
479
+
480
+ for (const layer of layers) {
481
+ if (layer.path === undefined) continue;
482
+ const contents = readFile(layer.path);
483
+ if (contents === null) continue;
484
+ if (layer.project && !trusted) {
485
+ ignored.push({ source: layer.path, setting: "*", reason: "the project is not trusted" });
486
+ continue;
487
+ }
488
+ const parsed = parseFile(layer.path, contents);
489
+ merged = deepMerge(merged, layer.project ? applyFloor(parsed, layer.path, ignored) : parsed);
490
+ configFiles.push(layer.path);
491
+ origins.push(layer.origin);
492
+ }
493
+
494
+ // A worktree's personal file is the main checkout's; one of its own is
495
+ // not read.
496
+ const pathModule = (options.platform ?? process.platform) === "win32" ? win32 : posix;
497
+ const ownLocal =
498
+ paths.projectDir === undefined
499
+ ? undefined
500
+ : pathModule.join(paths.projectDir, LOCAL_CONFIG_FILE_NAME);
501
+ if (
502
+ ownLocal !== undefined &&
503
+ paths.projectLocalConfig !== undefined &&
504
+ ownLocal !== paths.projectLocalConfig &&
505
+ readFile(ownLocal) !== null
506
+ ) {
507
+ ignored.push({
508
+ source: ownLocal,
509
+ setting: "*",
510
+ reason: `a worktree shares the main checkout's file, ${paths.projectLocalConfig}`,
511
+ });
512
+ }
513
+
514
+ // A project's prompt is its instructions to the agent: settings like the rest.
515
+ const refusedPrompt =
516
+ !trusted && paths.projectPrompt !== undefined && readFile(paths.projectPrompt) !== null
517
+ ? paths.projectPrompt
518
+ : undefined;
519
+ if (refusedPrompt !== undefined) {
520
+ ignored.push({ source: refusedPrompt, setting: "*", reason: "the project is not trusted" });
521
+ }
522
+
523
+ // So are its kinds of agent. The directory is withheld, not only reported: a
524
+ // host that forgot to look at the trust decision then has nothing to read.
525
+ const refusedAgents =
526
+ !trusted &&
527
+ paths.projectAgentsDir !== undefined &&
528
+ projectAgentFiles(paths, options.listDir ?? defaultListDir, options.platform ?? process.platform).length > 0
529
+ ? paths.projectAgentsDir
530
+ : undefined;
531
+ if (refusedAgents !== undefined) {
532
+ ignored.push({ source: refusedAgents, setting: "*", reason: "the project is not trusted" });
533
+ }
534
+
535
+ // Variables a workspace `.env` declared arrive through `process.env` looking
536
+ // exactly like the shell's, so they are sorted out by name.
537
+ const settingsEnv: Record<string, string | undefined> = { ...env };
538
+ const home = envVar("HOME", app);
539
+ const permissionsMode = envVar("PERMISSIONS_MODE", app);
540
+ for (const { name, file } of inspection.variables) {
541
+ if (!(name in settingsEnv)) continue;
542
+ const reason = !trusted
543
+ ? "the project is not trusted"
544
+ : name === home
545
+ ? "a project may not move the user's directory"
546
+ : name === permissionsMode && settingsEnv[name] === "yolo"
547
+ ? "a project may not turn yolo on"
548
+ : undefined;
549
+ if (reason === undefined) continue;
550
+ delete settingsEnv[name];
551
+ ignored.push({ source: file, setting: name, reason });
552
+ }
553
+
554
+ const fromEnv = fromEnvironment(settingsEnv, app);
555
+ if (Object.keys(fromEnv).length > 0) {
556
+ merged = deepMerge(merged, fromEnv);
557
+ origins.push("env");
558
+ }
559
+
560
+ if (options.overrides && Object.keys(options.overrides).length > 0) {
561
+ merged = deepMerge(merged, options.overrides as Record<string, unknown>);
562
+ origins.push("overrides");
563
+ }
564
+
565
+ const data = parseConfig(merged, options.extend);
566
+
567
+ // Read by the host, not here; reported here, with the rest the project did not get.
568
+ if (!trusted) {
569
+ const refusedInstructions = projectInstructionFiles(
570
+ paths.checkoutRoot,
571
+ options.cwd ?? process.cwd(),
572
+ data.instructions.files,
573
+ (file) => readFile(file) !== null,
574
+ pathModule,
575
+ );
576
+ for (const file of refusedInstructions) {
577
+ ignored.push({ source: file, setting: "*", reason: "the project is not trusted" });
578
+ }
579
+ }
580
+
581
+ // Applied after the schema, not merged before it: a stored key must not
582
+ // conjure a provider entry without a `type`, and the schema's default
583
+ // providers must exist before a key is attached to one.
584
+ const credentials = readCredentials(paths.userCredentials, readFile);
585
+ const credentialProviders: string[] = [];
586
+ const strandedCredentials: string[] = [];
587
+ const serviceKeys: Partial<Record<ServiceName, string>> = {};
588
+ const providers: Config["providers"] = { ...data.providers };
589
+
590
+ for (const [name, entry] of Object.entries(credentials)) {
591
+ const service = Object.hasOwn(SERVICE_KEY_ENV, name);
592
+ if (service) serviceKeys[name as ServiceName] = entry.apiKey;
593
+
594
+ const provider = providers[name];
595
+ if (provider === undefined) {
596
+ // A service's key is in use without a provider entry, so it is not stranded.
597
+ if (!service) strandedCredentials.push(name);
598
+ continue;
599
+ }
600
+ // Beats an inline key: the stored one is personal, the config file is
601
+ // shared with the team.
602
+ providers[name] = { ...provider, apiKey: entry.apiKey };
603
+ credentialProviders.push(name);
604
+ }
605
+
606
+ if (credentialProviders.length > 0) origins.push("credentials");
607
+
608
+ const keyVariables = [
609
+ ...Object.entries(providers).map(
610
+ ([name, provider]) => provider.apiKeyEnv ?? defaultApiKeyEnv(name),
611
+ ),
612
+ ...Object.values(SERVICE_KEY_ENV),
613
+ ];
614
+
615
+ return {
616
+ config: { ...data, providers },
617
+ paths: {
618
+ ...paths,
619
+ ...(refusedPrompt === undefined ? {} : { projectPrompt: undefined }),
620
+ // Withheld from every untrusted project, also one that has no such file yet.
621
+ ...(trusted ? {} : { projectAgentsDir: undefined }),
622
+ },
623
+ project: options.project,
624
+ ignored,
625
+ origins,
626
+ configFiles,
627
+ credentialProviders,
628
+ strandedCredentials,
629
+ serviceKeys,
630
+ workspaceEnvKeys: [
631
+ ...new Set(
632
+ envFilesAt([options.cwd ?? process.cwd(), paths.projectRoot], options.platform ?? process.platform).flatMap(
633
+ (file) => declaredInEnvFile(file, keyVariables, readFile),
634
+ ),
635
+ ),
636
+ ],
637
+ };
638
+ }
639
+
640
+ function readCredentials(
641
+ path: string,
642
+ readFile: (path: string) => string | null,
643
+ ): Record<string, { apiKey: string }> {
644
+ const contents = readFile(path);
645
+ if (contents === null) return {};
646
+
647
+ const parsed = credentialsSchema.safeParse(parseFile(path, contents));
648
+ if (!parsed.success) {
649
+ // Named separately from config/invalid: the fix is a different command and
650
+ // a different file, and the message must not quote the value it rejected.
651
+ throw new AgentError(
652
+ "config/invalid",
653
+ `Credentials file is not in the expected shape: ${path}. Expected {"<provider>": {"apiKey": "..."}}.`,
654
+ { details: { path } },
655
+ );
656
+ }
657
+ return parsed.data;
658
+ }
659
+
660
+ /** Config with any inline provider keys masked, safe to print or log. */
661
+ export function redactConfig(config: Config): Config {
662
+ const providers: Config["providers"] = {};
663
+ for (const [name, provider] of Object.entries(config.providers)) {
664
+ providers[name] = provider.apiKey === undefined ? provider : { ...provider, apiKey: "***" };
665
+ }
666
+ return { ...config, providers };
667
+ }