@kilncraft/core 1.0.0 → 1.1.0

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.
package/README.md ADDED
@@ -0,0 +1,307 @@
1
+ # @kilncraft/core
2
+
3
+ The Kilncraft agent runtime: provider adapters, the tool loop, permissions,
4
+ sessions, compaction, plugins, checkpoints, and audit logging.
5
+
6
+ `@kilncraft/cli`, `@kilncraft/server`, `@kilncraft/sdk`, and `@kilncraft/tui` all
7
+ build on this package. Use it directly when you want the agent loop without the
8
+ HTTP server, CLI, or terminal UI.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ npm i @kilncraft/core @kilncraft/shared
14
+ ```
15
+
16
+ Requires Node.js >= 24 (uses `node:sqlite`).
17
+
18
+ ## What it provides
19
+
20
+ | Area | Main exports |
21
+ | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
22
+ | Agent | `Agent`, `AgentEvent`, `AgentOptions`, `TurnResult` |
23
+ | Providers | `ProviderRegistry`, `createDefaultProviderRegistry`, `AnthropicProvider`, `OpenAIProvider`, `GeminiProvider`, `MODEL_CATALOG`, `listKnownModels`, `modelInfoFor` |
24
+ | Tools | `ToolRegistry`, `createDefaultToolRegistry`, individual tools |
25
+ | Sessions | `SessionStore`, `resolveDataDir`, `SearchResult` |
26
+ | Permissions | `PermissionEngine` |
27
+ | Compaction | `estimateTokens`, `estimateMessagesTokens`, `shouldCompact`, `compactMessages` |
28
+ | Prompts | `buildSystemPrompt` |
29
+ | Plugins | `PluginHost`, `loadPlugins` |
30
+ | Audit | `AuditLog` |
31
+ | Checkpoints | `CheckpointManager` |
32
+ | Utilities | `isPathInside`, `matchesGlob`, `diffText`, `truncateText`, `lineNumbered` |
33
+
34
+ ## Agent loop
35
+
36
+ ```ts
37
+ import {
38
+ Agent,
39
+ createDefaultProviderRegistry,
40
+ createDefaultToolRegistry,
41
+ PermissionEngine,
42
+ } from "@kilncraft/core";
43
+ import { createLogger } from "@kilncraft/shared";
44
+
45
+ const registry = createDefaultProviderRegistry(process.env, {
46
+ anthropic: { apiKey: "{env:ANTHROPIC_API_KEY}" },
47
+ });
48
+ const provider = registry.get("anthropic");
49
+ if (!provider) throw new Error("ANTHROPIC_API_KEY is not set");
50
+
51
+ const agent = new Agent({
52
+ cwd: process.cwd(),
53
+ provider,
54
+ model: "claude-sonnet-4-5",
55
+ tools: createDefaultToolRegistry(),
56
+ permissions: new PermissionEngine({ mode: "acceptEdits", cwd: process.cwd() }),
57
+ logger: createLogger({ level: "info" }),
58
+ askPermission: async (request) => {
59
+ console.log("Permission requested:", request.tool, request.input);
60
+ return "allow";
61
+ },
62
+ });
63
+
64
+ const result = await agent.prompt("Summarize this repository", {
65
+ onEvent: (event) => {
66
+ if (event.type === "assistant.text") process.stdout.write(event.text);
67
+ },
68
+ });
69
+
70
+ console.log(result.text, result.usage, result.cost, result.stopReason);
71
+ ```
72
+
73
+ `AgentOptions`:
74
+
75
+ | Field | Required | Purpose |
76
+ | --------------- | -------- | --------------------------------------- |
77
+ | `cwd` | yes | Workspace root |
78
+ | `provider` | yes | A `ProviderAdapter` |
79
+ | `model` | yes | Model id without the provider prefix |
80
+ | `tools` | yes | `ToolRegistry` |
81
+ | `permissions` | yes | `PermissionEngine` |
82
+ | `logger` | yes | Pino logger |
83
+ | `maxTurns` | no | Tool-loop turn cap (default 25) |
84
+ | `maxTokens` | no | Max output tokens per request |
85
+ | `systemPrompt` | no | Override the generated system prompt |
86
+ | `agent` | no | Agent preset name stored on the session |
87
+ | `store` | no | Persist sessions/messages |
88
+ | `session` | no | Resume an existing session |
89
+ | `audit` | no | Permission audit log |
90
+ | `checkpoints` | no | File snapshot manager |
91
+ | `askPermission` | no | Interactive approval callback |
92
+ | `plugins` | no | Loaded `PluginHost` |
93
+ | `sandbox` | no | Wrap `bash` in a sandbox adapter |
94
+ | `lsp` | no | Language-server manager |
95
+
96
+ `Agent` methods: `prompt`, `compact`, `getSession`, `getMessages`,
97
+ `replaceMessages`, `getUsage`, `getCost`, `getPermissions`, `getTodos`, `id`.
98
+
99
+ `AgentEvent` covers `turn.start`, `assistant.text`, `assistant.message`,
100
+ `tool.call`, `tool.result`, `permission.requested`, `permission.denied`,
101
+ `compaction.started`, `compaction.completed`, `turn.end`, and `error`.
102
+
103
+ ## Providers
104
+
105
+ `createDefaultProviderRegistry(env, providerConfigs)` registers a provider only
106
+ when it has credentials:
107
+
108
+ | Provider | Credential source | Notes |
109
+ | ------------ | --------------------------------------------------------- | --------------------------------- |
110
+ | `anthropic` | `ANTHROPIC_API_KEY` or `providers.anthropic.apiKey` | Messages API |
111
+ | `openai` | `OPENAI_API_KEY` or `providers.openai.apiKey` | Chat Completions |
112
+ | `openrouter` | `OPENROUTER_API_KEY` or `providers.openrouter.apiKey` | OpenAI-compatible |
113
+ | `gemini` | `GEMINI_API_KEY` / `GOOGLE_API_KEY` or config | `streamGenerateContent` |
114
+ | `ollama` | always registered | `OLLAMA_HOST` or config `baseURL` |
115
+ | `custom` | `providers.custom.baseURL` or `KILNCRAFT_CUSTOM_BASE_URL` | Any OpenAI-compatible endpoint |
116
+
117
+ Config values accept `{env:NAME}`:
118
+
119
+ ```ts
120
+ createDefaultProviderRegistry(process.env, {
121
+ openrouter: {
122
+ apiKey: "{env:OPENROUTER_API_KEY}",
123
+ baseURL: "https://openrouter.ai/api/v1",
124
+ headers: { "X-Title": "my-app" },
125
+ },
126
+ });
127
+ ```
128
+
129
+ `availableProviderIds(env, providerConfigs)` reports the ids that would actually
130
+ be registered. `MODEL_CATALOG`, `listKnownModels()`, and `modelInfoFor()` expose
131
+ known models, context windows, pricing, and capabilities.
132
+
133
+ ## Built-in tools
134
+
135
+ `createDefaultToolRegistry()` registers:
136
+
137
+ | Tool | Kind | Purpose |
138
+ | ----------------- | --------- | -------------------------------------------- |
139
+ | `read` | read-only | Read a file, optional line range |
140
+ | `write` | mutating | Create or overwrite a file |
141
+ | `edit` | mutating | Exact string replacement |
142
+ | `glob` | read-only | Fast filename matching |
143
+ | `grep` | read-only | Content search (ripgrep when available) |
144
+ | `ls` | read-only | List directory entries |
145
+ | `bash` | mutating | Run a shell command (sandboxed when enabled) |
146
+ | `todo_write` | read-only | Replace the task checklist |
147
+ | `lsp_diagnostics` | read-only | Diagnostics from a language server |
148
+ | `lsp_symbols` | read-only | Document symbols from a language server |
149
+
150
+ Tools are plain objects:
151
+
152
+ ```ts
153
+ import type { ToolDefinition, ToolOutput } from "@kilncraft/shared";
154
+ import { z } from "zod";
155
+
156
+ const input = z.object({ path: z.string() });
157
+
158
+ export const myTool: ToolDefinition<z.infer<typeof input>> = {
159
+ id: "my_tool",
160
+ description: "Read a file and return its size",
161
+ input,
162
+ readOnly: true,
163
+ parallelizable: true,
164
+ defaultDecision: "allow",
165
+ async execute({ path }, context): Promise<ToolOutput> {
166
+ context.logger.debug({ path }, "my_tool");
167
+ return { kind: "text", text: path };
168
+ },
169
+ };
170
+ ```
171
+
172
+ `ToolRegistry` provides `register`, `get`, `list`, `toSpecs`, and validated
173
+ `execute`. Read-only tools may run in parallel; mutating tools are serialized by
174
+ the agent loop.
175
+
176
+ ## Permissions
177
+
178
+ `PermissionEngine` evaluates rules first, then the mode:
179
+
180
+ | Mode | Behavior |
181
+ | ------------------- | ------------------------------------------------ |
182
+ | `default` | Ask for mutating tools, allow read-only tools |
183
+ | `acceptEdits` | Allow edits inside the workspace; ask outside it |
184
+ | `plan` | Deny mutating tools; read-only allowed |
185
+ | `bypassPermissions` | Allow everything (use with care) |
186
+ | `custom` | Behaves like `default`; combine with rules |
187
+
188
+ ```ts
189
+ const permissions = new PermissionEngine({
190
+ mode: "acceptEdits",
191
+ cwd: process.cwd(),
192
+ rules: [
193
+ { tool: "bash", pattern: "git status", decision: "allow", scope: "session" },
194
+ { tool: "bash", pattern: "rm -rf *", decision: "deny", scope: "session" },
195
+ ],
196
+ });
197
+
198
+ permissions.decide({ tool: "read", input: { path: "a.ts" } }); // "allow"
199
+ permissions.decide({ tool: "bash", input: { command: "git status" } }); // "allow"
200
+ ```
201
+
202
+ Deny beats allow. Dangerous commands (`rm -rf /`, `mkfs`, `curl … | sh`,
203
+ force-push, etc.) require approval unless `bypassPermissions` is set.
204
+
205
+ ## Sessions and persistence
206
+
207
+ `SessionStore` uses SQLite (`node:sqlite`) plus a JSONL event mirror under the
208
+ data directory (default `~/.kilncraft`, override with `KILNCRAFT_DATA_DIR`).
209
+
210
+ ```ts
211
+ const store = new SessionStore({ dataDir: "/tmp/kilncraft-data" });
212
+
213
+ const session = store.create({
214
+ cwd: process.cwd(),
215
+ model: "anthropic/claude-sonnet-4-5",
216
+ title: "My session",
217
+ });
218
+
219
+ store.appendMessage(session.id, { role: "user", content: "hello" });
220
+ const messages = store.readMessages(session.id);
221
+ const events = store.readEvents(session.id);
222
+
223
+ store.search("hello");
224
+ store.export(session.id, "md");
225
+ store.delete(session.id);
226
+ store.close();
227
+ ```
228
+
229
+ `SessionStore` also provides `get`, `list`, `update`, `replaceMessages`, and
230
+ `sessionDirectory`.
231
+
232
+ ## Compaction
233
+
234
+ ```ts
235
+ import { compactMessages, estimateMessagesTokens } from "@kilncraft/core";
236
+
237
+ const used = estimateMessagesTokens(messages);
238
+ const result = compactMessages(messages, {
239
+ contextWindow: 200_000,
240
+ keepRecent: 6,
241
+ threshold: 0.8,
242
+ });
243
+
244
+ console.log(result.omitted, result.tokensBefore, result.tokensAfter);
245
+ ```
246
+
247
+ `Agent.prompt` compacts automatically when the estimated context exceeds the
248
+ threshold, emitting `compaction.started` and `compaction.completed` events.
249
+
250
+ ## Plugins
251
+
252
+ ```ts
253
+ import { loadPlugins } from "@kilncraft/core";
254
+
255
+ const host = await loadPlugins(["./my-plugin.ts"], {
256
+ cwd: process.cwd(),
257
+ dataDir: "/tmp/kilncraft-data",
258
+ logger,
259
+ });
260
+
261
+ const tools = host.getTools();
262
+ const commands = host.getCommands();
263
+ ```
264
+
265
+ Plugin hooks are `session.start`, `message.received`, `tool.before`,
266
+ `tool.after`, and `event`. See `@kilncraft/plugin-sdk` for types and an example.
267
+
268
+ ## Checkpoints and audit
269
+
270
+ `CheckpointManager` snapshots files before edits and can restore them:
271
+
272
+ ```ts
273
+ const checkpoints = new CheckpointManager("/tmp/kilncraft-data");
274
+ const checkpoint = checkpoints.snapshot(sessionID, "/repo/src/a.ts");
275
+ checkpoints.latest(sessionID);
276
+ checkpoints.restoreLatest(sessionID);
277
+ ```
278
+
279
+ `AuditLog` appends JSONL permission decisions:
280
+
281
+ ```ts
282
+ const audit = new AuditLog("/tmp/kilncraft-data/audit.jsonl");
283
+ audit.record({
284
+ sessionID,
285
+ tool: "bash",
286
+ decision: "allow",
287
+ cwd: process.cwd(),
288
+ inputHash: "sha256:…",
289
+ summary: "git status",
290
+ });
291
+ ```
292
+
293
+ ## Development
294
+
295
+ ```sh
296
+ pnpm --filter @kilncraft/core build
297
+ pnpm --filter @kilncraft/core test
298
+ pnpm --filter @kilncraft/core typecheck
299
+ ```
300
+
301
+ ## Related packages
302
+
303
+ - `@kilncraft/shared` — types and schemas
304
+ - `@kilncraft/sdk` — in-process facade over this package
305
+ - `@kilncraft/server` — HTTP/SSE daemon
306
+ - `@kilncraft/tui` — terminal UI
307
+ - [Root README](../../README.md)
package/dist/index.d.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  import * as _kilncraft_shared from '@kilncraft/shared';
2
- import { PermissionMode, PermissionRule, PermissionDecision, Plugin, PluginContext, ChatMessage, ToolCall, ToolOutput, KilncraftEvent, Session, ToolDefinition, ToolSpec, ToolContext, ProviderAdapter, SandboxAdapter, LspManagerLike, Usage, KilncraftError, ProviderCapabilities, ModelInfo, StreamRequest, StreamEvent } from '@kilncraft/shared';
2
+ import { PermissionMode, PermissionRule, PermissionDecision, Plugin, PluginContext, ChatMessage, ToolCall, ToolOutput, KilncraftEvent, Session, ToolDefinition, ToolSpec, ToolContext, ProviderAdapter, SandboxAdapter, LspManagerLike, Usage, KilncraftError, ProviderCapabilities, ModelInfo, StreamRequest, StreamEvent, ProviderConfig } from '@kilncraft/shared';
3
3
  import { Logger } from 'pino';
4
4
  import { z } from 'zod';
5
5
 
6
6
  interface PermissionRequest {
7
7
  tool: string;
8
8
  input: unknown;
9
+ /** Set by the agent when the tool declares itself read-only. */
10
+ readOnly?: boolean;
9
11
  }
10
12
  interface PermissionEngineOptions {
11
13
  mode: PermissionMode;
@@ -317,6 +319,7 @@ declare function buildSystemPrompt(options: PromptOptions): string;
317
319
  interface AnthropicOptions {
318
320
  apiKey: string;
319
321
  baseURL?: string;
322
+ headers?: Record<string, string>;
320
323
  }
321
324
  declare class AnthropicProvider implements ProviderAdapter {
322
325
  private readonly options;
@@ -332,6 +335,7 @@ declare class AnthropicProvider implements ProviderAdapter {
332
335
  interface GeminiOptions {
333
336
  apiKey: string;
334
337
  baseURL?: string;
338
+ headers?: Record<string, string>;
335
339
  }
336
340
  declare class GeminiProvider implements ProviderAdapter {
337
341
  private readonly options;
@@ -339,6 +343,7 @@ declare class GeminiProvider implements ProviderAdapter {
339
343
  readonly capabilities: ProviderCapabilities;
340
344
  constructor(options: GeminiOptions);
341
345
  private get baseURL();
346
+ private headers;
342
347
  listModels(): Promise<ModelInfo[]>;
343
348
  stream(request: StreamRequest): AsyncIterable<StreamEvent>;
344
349
  }
@@ -396,8 +401,8 @@ declare class ProviderRegistry {
396
401
  has(id: string): boolean;
397
402
  list(): ProviderAdapter[];
398
403
  }
399
- declare function createDefaultProviderRegistry(env?: NodeJS.ProcessEnv): ProviderRegistry;
400
- declare function availableProviderIds(env?: NodeJS.ProcessEnv): string[];
404
+ declare function createDefaultProviderRegistry(env?: NodeJS.ProcessEnv, providerConfigs?: Record<string, ProviderConfig>): ProviderRegistry;
405
+ declare function availableProviderIds(env?: NodeJS.ProcessEnv, providerConfigs?: Record<string, ProviderConfig>): string[];
401
406
 
402
407
  declare const bashInput: z.ZodObject<{
403
408
  command: z.ZodString;
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@ import { dirname, resolve, relative, isAbsolute, join, basename } from 'path';
5
5
  import { realpath, stat, readFile, mkdir, writeFile, rename, rm, readdir } from 'fs/promises';
6
6
  import { createTwoFilesPatch } from 'diff';
7
7
  import { z } from 'zod';
8
+ import { createRequire } from 'module';
8
9
  import { pathToFileURL } from 'url';
9
10
  import { homedir } from 'os';
10
11
  import { spawn } from 'child_process';
@@ -294,8 +295,14 @@ function diffText(path, before, after) {
294
295
  }
295
296
  async function atomicWrite(path, content) {
296
297
  await mkdir(dirname(path), { recursive: true });
298
+ let mode;
299
+ try {
300
+ mode = (await stat(path)).mode & 511;
301
+ } catch {
302
+ mode = void 0;
303
+ }
297
304
  const temporary = `${path}.kilncraft-tmp-${process.pid}-${Date.now()}`;
298
- await writeFile(temporary, content, "utf8");
305
+ await writeFile(temporary, content, { encoding: "utf8", mode: mode ?? 438 });
299
306
  try {
300
307
  await rename(temporary, path);
301
308
  } catch (error) {
@@ -824,15 +831,21 @@ var Agent = class {
824
831
  return { text, calls };
825
832
  }
826
833
  async executeCalls(calls, signal, emit) {
827
- const readOnly = calls.filter((call) => this.options.tools.get(call.name)?.readOnly === true);
828
- const mutating = calls.filter((call) => this.options.tools.get(call.name)?.readOnly !== true);
834
+ const isParallelizable = (call) => {
835
+ const tool = this.options.tools.get(call.name);
836
+ return tool?.readOnly === true && tool.parallelizable === true;
837
+ };
838
+ const serial = calls.filter((call) => !isParallelizable(call));
839
+ const parallel = calls.filter((call) => isParallelizable(call));
829
840
  const results = [];
830
- for (const call of mutating) {
841
+ for (const call of serial) {
831
842
  if (signal.aborted) throw errors.aborted();
832
843
  results.push(await this.executeOne(call, signal, emit));
833
844
  }
834
- const parallel = await Promise.all(readOnly.map((call) => this.executeOne(call, signal, emit)));
835
- results.push(...parallel);
845
+ const parallelResults = await Promise.all(
846
+ parallel.map((call) => this.executeOne(call, signal, emit))
847
+ );
848
+ results.push(...parallelResults);
836
849
  return results;
837
850
  }
838
851
  async executeOne(call, signal, emit) {
@@ -876,7 +889,8 @@ var Agent = class {
876
889
  }
877
890
  let decision = this.options.permissions.decide({
878
891
  tool: call.name,
879
- input: parsed.data
892
+ input: parsed.data,
893
+ readOnly: tool.readOnly
880
894
  });
881
895
  if (decision === "ask" && this.options.askPermission) {
882
896
  const requestID = ids.request();
@@ -1044,7 +1058,7 @@ var PermissionEngine = class {
1044
1058
  return this.options.mode === "plan" ? "deny" : "ask";
1045
1059
  }
1046
1060
  }
1047
- const isReadOnly = this.options.isReadOnly?.(request.tool) ?? READ_ONLY_TOOLS.has(request.tool);
1061
+ const isReadOnly = request.readOnly ?? this.options.isReadOnly?.(request.tool) ?? READ_ONLY_TOOLS.has(request.tool);
1048
1062
  if (isReadOnly) return "allow";
1049
1063
  if (this.options.mode === "plan") return "deny";
1050
1064
  if (this.options.mode === "acceptEdits" && WRITE_TOOLS.has(request.tool)) {
@@ -1152,8 +1166,10 @@ function unwrapPlugin(module) {
1152
1166
  }
1153
1167
  async function loadPlugins(paths, context) {
1154
1168
  const plugins = [];
1169
+ const requireFromCwd = createRequire(join(context.cwd, "package.json"));
1155
1170
  for (const [index, entry] of paths.entries()) {
1156
- const resolved = entry.startsWith(".") || entry.startsWith("/") ? pathToFileURL(resolve(context.cwd, entry)).href : entry;
1171
+ const isFile = entry.startsWith(".") || isAbsolute(entry);
1172
+ const resolved = isFile ? pathToFileURL(resolve(context.cwd, entry)).href : pathToFileURL(requireFromCwd.resolve(entry)).href;
1157
1173
  const imported = await import(`${resolved}?v=${Date.now()}-${index}`);
1158
1174
  const plugin = unwrapPlugin(imported);
1159
1175
  if (!plugin || typeof plugin.id !== "string" || plugin.id.length === 0) {
@@ -1337,7 +1353,8 @@ var AnthropicProvider = class {
1337
1353
  return {
1338
1354
  "content-type": "application/json",
1339
1355
  "x-api-key": this.options.apiKey,
1340
- "anthropic-version": "2023-06-01"
1356
+ "anthropic-version": "2023-06-01",
1357
+ ...this.options.headers
1341
1358
  };
1342
1359
  }
1343
1360
  async listModels() {
@@ -1546,10 +1563,17 @@ var GeminiProvider = class {
1546
1563
  ""
1547
1564
  );
1548
1565
  }
1566
+ headers() {
1567
+ return {
1568
+ "content-type": "application/json",
1569
+ "x-goog-api-key": this.options.apiKey,
1570
+ ...this.options.headers
1571
+ };
1572
+ }
1549
1573
  async listModels() {
1550
1574
  const response = await fetchJson(
1551
1575
  `${this.baseURL}/models`,
1552
- { headers: { "x-goog-api-key": this.options.apiKey } },
1576
+ { headers: this.headers() },
1553
1577
  new AbortController().signal
1554
1578
  );
1555
1579
  return (response.models ?? []).map((model) => model.name?.replace(/^models\//, "")).filter((id) => typeof id === "string" && id.length > 0).map((id) => modelInfoFor("gemini", id));
@@ -1582,10 +1606,7 @@ var GeminiProvider = class {
1582
1606
  `${this.baseURL}/models/${encodeURIComponent(model)}:streamGenerateContent?alt=sse`,
1583
1607
  {
1584
1608
  method: "POST",
1585
- headers: {
1586
- "content-type": "application/json",
1587
- "x-goog-api-key": this.options.apiKey
1588
- },
1609
+ headers: this.headers(),
1589
1610
  body: JSON.stringify(body)
1590
1611
  },
1591
1612
  request.signal
@@ -1794,6 +1815,15 @@ function isOpenAiChunk(value) {
1794
1815
  }
1795
1816
 
1796
1817
  // src/provider/registry.ts
1818
+ function envValue(value, env) {
1819
+ if (!value) return void 0;
1820
+ const match = /^\{env:([^}]+)\}$/.exec(value);
1821
+ if (match?.[1]) return env[match[1]];
1822
+ return value;
1823
+ }
1824
+ function providerConfig(providers, id) {
1825
+ return providers[id] ?? {};
1826
+ }
1797
1827
  var ProviderRegistry = class {
1798
1828
  providers = /* @__PURE__ */ new Map();
1799
1829
  register(provider) {
@@ -1810,72 +1840,99 @@ var ProviderRegistry = class {
1810
1840
  return [...this.providers.values()];
1811
1841
  }
1812
1842
  };
1813
- function createDefaultProviderRegistry(env = process.env) {
1843
+ function createDefaultProviderRegistry(env = process.env, providerConfigs = {}) {
1814
1844
  const registry = new ProviderRegistry();
1815
- if (env.ANTHROPIC_API_KEY) {
1845
+ const anthropic = providerConfig(providerConfigs, "anthropic");
1846
+ const anthropicKey = envValue(anthropic.apiKey, env) ?? env.ANTHROPIC_API_KEY;
1847
+ if (anthropicKey) {
1816
1848
  registry.register(
1817
1849
  new AnthropicProvider({
1818
- apiKey: env.ANTHROPIC_API_KEY,
1819
- baseURL: env.ANTHROPIC_BASE_URL
1850
+ apiKey: anthropicKey,
1851
+ baseURL: anthropic.baseURL ?? env.ANTHROPIC_BASE_URL,
1852
+ headers: anthropic.headers
1820
1853
  })
1821
1854
  );
1822
1855
  }
1823
- if (env.OPENAI_API_KEY) {
1856
+ const openai = providerConfig(providerConfigs, "openai");
1857
+ const openaiKey = envValue(openai.apiKey, env) ?? env.OPENAI_API_KEY;
1858
+ if (openaiKey) {
1824
1859
  registry.register(
1825
1860
  new OpenAIProvider({
1826
1861
  id: "openai",
1827
- apiKey: env.OPENAI_API_KEY,
1828
- baseURL: env.OPENAI_BASE_URL ?? "https://api.openai.com/v1"
1862
+ apiKey: openaiKey,
1863
+ baseURL: openai.baseURL ?? env.OPENAI_BASE_URL ?? "https://api.openai.com/v1",
1864
+ headers: openai.headers
1829
1865
  })
1830
1866
  );
1831
1867
  }
1832
- if (env.OPENROUTER_API_KEY) {
1833
- const headers = {};
1868
+ const openrouter = providerConfig(providerConfigs, "openrouter");
1869
+ const openrouterKey = envValue(openrouter.apiKey, env) ?? env.OPENROUTER_API_KEY;
1870
+ if (openrouterKey) {
1871
+ const headers = { ...openrouter.headers ?? {} };
1834
1872
  if (env.OPENROUTER_REFERER) headers["HTTP-Referer"] = env.OPENROUTER_REFERER;
1835
1873
  if (env.OPENROUTER_TITLE) headers["X-Title"] = env.OPENROUTER_TITLE;
1836
1874
  registry.register(
1837
1875
  new OpenAIProvider({
1838
1876
  id: "openrouter",
1839
- apiKey: env.OPENROUTER_API_KEY,
1840
- baseURL: env.OPENROUTER_BASE_URL ?? "https://openrouter.ai/api/v1",
1877
+ apiKey: openrouterKey,
1878
+ baseURL: openrouter.baseURL ?? env.OPENROUTER_BASE_URL ?? "https://openrouter.ai/api/v1",
1841
1879
  headers
1842
1880
  })
1843
1881
  );
1844
1882
  }
1845
- const geminiKey = env.GEMINI_API_KEY ?? env.GOOGLE_API_KEY;
1883
+ const gemini = providerConfig(providerConfigs, "gemini");
1884
+ const geminiKey = envValue(gemini.apiKey, env) ?? env.GEMINI_API_KEY ?? env.GOOGLE_API_KEY;
1846
1885
  if (geminiKey) {
1847
1886
  registry.register(
1848
1887
  new GeminiProvider({
1849
1888
  apiKey: geminiKey,
1850
- baseURL: env.GEMINI_BASE_URL
1889
+ baseURL: gemini.baseURL ?? env.GEMINI_BASE_URL,
1890
+ headers: gemini.headers
1851
1891
  })
1852
1892
  );
1853
1893
  }
1854
- const ollamaHost = (env.OLLAMA_HOST ?? "http://localhost:11434").replace(/\/$/, "");
1894
+ const ollama = providerConfig(providerConfigs, "ollama");
1895
+ const ollamaHost = (ollama.baseURL ?? env.OLLAMA_HOST ?? "http://localhost:11434").replace(
1896
+ /\/$/,
1897
+ ""
1898
+ );
1855
1899
  registry.register(
1856
1900
  new OpenAIProvider({
1857
1901
  id: "ollama",
1858
- baseURL: ollamaHost.endsWith("/v1") ? ollamaHost : `${ollamaHost}/v1`
1902
+ baseURL: ollamaHost.endsWith("/v1") ? ollamaHost : `${ollamaHost}/v1`,
1903
+ headers: ollama.headers
1859
1904
  })
1860
1905
  );
1861
- if (env.KILNCRAFT_CUSTOM_BASE_URL) {
1906
+ const custom = providerConfig(providerConfigs, "custom");
1907
+ const customBase = custom.baseURL ?? env.KILNCRAFT_CUSTOM_BASE_URL ?? env.HARNESS_CUSTOM_BASE_URL;
1908
+ if (customBase) {
1862
1909
  registry.register(
1863
1910
  new OpenAIProvider({
1864
1911
  id: "custom",
1865
- apiKey: env.KILNCRAFT_CUSTOM_API_KEY,
1866
- baseURL: env.KILNCRAFT_CUSTOM_BASE_URL
1912
+ apiKey: envValue(custom.apiKey, env) ?? env.KILNCRAFT_CUSTOM_API_KEY ?? env.HARNESS_CUSTOM_API_KEY,
1913
+ baseURL: customBase,
1914
+ headers: custom.headers
1867
1915
  })
1868
1916
  );
1869
1917
  }
1870
1918
  return registry;
1871
1919
  }
1872
- function availableProviderIds(env = process.env) {
1920
+ function availableProviderIds(env = process.env, providerConfigs = {}) {
1921
+ const hasKey = (id) => {
1922
+ const raw = providerConfigs[id]?.apiKey;
1923
+ if (!raw) return false;
1924
+ const match = /^\{env:([^}]+)\}$/.exec(raw);
1925
+ return match?.[1] ? Boolean(env[match[1]]) : true;
1926
+ };
1927
+ const hasCustom = Boolean(providerConfigs.custom?.baseURL) || hasKey("custom");
1873
1928
  const ids3 = ["ollama"];
1874
- if (env.ANTHROPIC_API_KEY) ids3.push("anthropic");
1875
- if (env.OPENAI_API_KEY) ids3.push("openai");
1876
- if (env.OPENROUTER_API_KEY) ids3.push("openrouter");
1877
- if (env.GEMINI_API_KEY ?? env.GOOGLE_API_KEY) ids3.push("gemini");
1878
- if (env.KILNCRAFT_CUSTOM_BASE_URL) ids3.push("custom");
1929
+ if (env.ANTHROPIC_API_KEY || hasKey("anthropic")) ids3.push("anthropic");
1930
+ if (env.OPENAI_API_KEY || hasKey("openai")) ids3.push("openai");
1931
+ if (env.OPENROUTER_API_KEY || hasKey("openrouter")) ids3.push("openrouter");
1932
+ if (env.GEMINI_API_KEY || env.GOOGLE_API_KEY || hasKey("gemini")) ids3.push("gemini");
1933
+ if (env.KILNCRAFT_CUSTOM_BASE_URL || env.HARNESS_CUSTOM_BASE_URL || hasCustom) {
1934
+ ids3.push("custom");
1935
+ }
1879
1936
  return ids3;
1880
1937
  }
1881
1938
  function readMeta(directory) {