@electric-ax/agents 0.2.4 → 0.3.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/dist/index.js CHANGED
@@ -1,25 +1,24 @@
1
1
  import path from "node:path";
2
2
  import { fileURLToPath } from "node:url";
3
- import { CODING_SESSION_CURSOR_COLLECTION_TYPE, CODING_SESSION_EVENT_COLLECTION_TYPE, CODING_SESSION_META_COLLECTION_TYPE, createEntityRegistry, createRuntimeHandler, db } from "@electric-ax/agents-runtime";
4
- import fsSync, { promises, watch } from "node:fs";
3
+ import { completeWithLowCostModel, createEntityRegistry, createRuntimeHandler, db, detectAvailableProviders, readCodexAccessToken, registerToolProvider, unregisterToolProvider } from "@electric-ax/agents-runtime";
4
+ import fs from "node:fs";
5
5
  import pino from "pino";
6
- import { spawn } from "node:child_process";
7
- import { homedir } from "node:os";
6
+ import { eq, not, queryOnce } from "@durable-streams/state";
8
7
  import { z } from "zod";
9
- import { deserializeCursor, discoverSessions, importLocalSession, loadSession, resolveSession, serializeCursor, tailSession } from "agent-session-protocol";
10
- import Anthropic from "@anthropic-ai/sdk";
11
8
  import { createHash } from "node:crypto";
12
- import fs from "node:fs/promises";
9
+ import fs$1 from "node:fs/promises";
13
10
  import Database from "better-sqlite3";
14
11
  import { Type } from "@sinclair/typebox";
15
12
  import { load } from "sqlite-vec";
16
13
  import { nanoid } from "nanoid";
17
- import { braveSearchTool, braveSearchTool as braveSearchTool$1, createBashTool, createEditTool, createReadFileTool, createWriteTool, fetchUrlTool } from "@electric-ax/agents-runtime/tools";
14
+ import { getModels } from "@mariozechner/pi-ai";
15
+ import { braveSearchTool, braveSearchTool as braveSearchTool$1, createBashTool, createEditTool, createFetchUrlTool, createReadFileTool, createWriteTool, fetchUrlTool } from "@electric-ax/agents-runtime/tools";
16
+ import { bridgeMcpTool, buildPromptTools, buildResourceTools, createRegistry, keychainPersistence, loadConfig, mcp, watchConfig } from "@electric-ax/agents-mcp";
18
17
  import { createServer } from "node:http";
19
18
 
20
19
  //#region src/log.ts
21
20
  const LOG_DIR = process.env.ELECTRIC_AGENTS_LOG_DIR ?? path.resolve(process.cwd(), `logs`);
22
- fsSync.mkdirSync(LOG_DIR, { recursive: true });
21
+ fs.mkdirSync(LOG_DIR, { recursive: true });
23
22
  const LOG_FILE = path.join(LOG_DIR, `builtin-agents-${Date.now()}.jsonl`);
24
23
  const LOG_LEVEL = process.env.ELECTRIC_AGENTS_LOG_LEVEL ?? `info`;
25
24
  const USE_PRETTY_LOGS = LOG_LEVEL !== `silent` && !process.env.VITEST;
@@ -70,516 +69,6 @@ const serverLog = {
70
69
  }
71
70
  };
72
71
 
73
- //#endregion
74
- //#region src/agents/coding-session.ts
75
- const defaultCliRunner = { async run(opts) {
76
- return new Promise((resolve, reject) => {
77
- const isClaude = opts.agent === `claude`;
78
- const bin = isClaude ? `claude` : `codex`;
79
- const args = isClaude ? opts.sessionId ? [
80
- `-r`,
81
- opts.sessionId,
82
- `--dangerously-skip-permissions`,
83
- `-p`
84
- ] : [`--dangerously-skip-permissions`, `-p`] : opts.sessionId ? [
85
- `exec`,
86
- `--skip-git-repo-check`,
87
- `resume`,
88
- opts.sessionId,
89
- opts.prompt
90
- ] : [
91
- `exec`,
92
- `--skip-git-repo-check`,
93
- opts.prompt
94
- ];
95
- const child = spawn(bin, args, {
96
- cwd: opts.cwd,
97
- stdio: [
98
- isClaude ? `pipe` : `ignore`,
99
- `pipe`,
100
- `pipe`
101
- ]
102
- });
103
- const MAX_BUF_CHARS = 4096;
104
- let stdout = ``;
105
- let stderr = ``;
106
- child.stdout?.on(`data`, (d) => {
107
- if (stdout.length < MAX_BUF_CHARS) stdout += d.toString().slice(0, MAX_BUF_CHARS - stdout.length);
108
- });
109
- child.stderr?.on(`data`, (d) => {
110
- if (stderr.length < MAX_BUF_CHARS) stderr += d.toString().slice(0, MAX_BUF_CHARS - stderr.length);
111
- });
112
- child.on(`error`, reject);
113
- child.on(`exit`, (code) => {
114
- resolve({
115
- exitCode: code ?? -1,
116
- stdout,
117
- stderr
118
- });
119
- });
120
- if (isClaude && child.stdin) {
121
- child.stdin.write(opts.prompt);
122
- child.stdin.end();
123
- }
124
- });
125
- } };
126
- async function discoverNewestSession(agent, cwd, excludeIds) {
127
- const all = await discoverSessions(agent);
128
- const candidates = all.filter((s) => !excludeIds.has(s.sessionId) && (!s.cwd || s.cwd === cwd));
129
- if (candidates.length === 0) return null;
130
- return candidates[0].sessionId;
131
- }
132
- /**
133
- * Compute the candidate directories where Claude Code stores per-cwd
134
- * session JSONL files. Claude resolves the cwd to its realpath when
135
- * choosing the directory name (so /tmp/foo on macOS lands under
136
- * `-private-tmp-foo`), but the entity may have been spawned with the
137
- * non-realpath form. Return both candidates so the caller can union
138
- * their contents.
139
- */
140
- async function getClaudeProjectDirs(cwd) {
141
- const home = homedir();
142
- const make = (c) => path.join(home, `.claude`, `projects`, c.replace(/\//g, `-`));
143
- const dirs = [make(cwd)];
144
- try {
145
- const real = await promises.realpath(cwd);
146
- if (real !== cwd) dirs.push(make(real));
147
- } catch {}
148
- return dirs;
149
- }
150
- async function listClaudeJsonlIdsByCwd(cwd) {
151
- const ids = new Set();
152
- for (const dir of await getClaudeProjectDirs(cwd)) try {
153
- const files = await promises.readdir(dir);
154
- for (const f of files) if (f.endsWith(`.jsonl`)) ids.add(f.slice(0, -`.jsonl`.length));
155
- } catch {}
156
- return ids;
157
- }
158
- /**
159
- * Deterministic-path discovery for a freshly created session. After the
160
- * Claude CLI runs in `-p` mode it writes the new JSONL straight into
161
- * `~/.claude/projects/<sanitize(cwd)>/<id>.jsonl` *without* leaving a
162
- * `~/.claude/sessions/<pid>.json` lock file (those are interactive-only),
163
- * so `discoverSessions` can miss it. Compute the expected dir directly
164
- * and diff its contents against a pre-run snapshot. Returns the newest
165
- * fresh sessionId or null. Codex falls back to discoverNewestSession.
166
- */
167
- async function findNewSessionAfterRun(agent, cwd, preDirectIds, preDiscoveredIds) {
168
- if (agent === `claude`) {
169
- const dirs = await getClaudeProjectDirs(cwd);
170
- let best = null;
171
- for (const dir of dirs) try {
172
- const files = await promises.readdir(dir);
173
- for (const f of files) {
174
- if (!f.endsWith(`.jsonl`)) continue;
175
- const id = f.slice(0, -`.jsonl`.length);
176
- if (preDirectIds.has(id)) continue;
177
- const st = await promises.stat(path.join(dir, f)).catch(() => null);
178
- if (!st) continue;
179
- if (!best || st.mtimeMs > best.mtime) best = {
180
- id,
181
- mtime: st.mtimeMs
182
- };
183
- }
184
- } catch {}
185
- if (best) return best.id;
186
- }
187
- return discoverNewestSession(agent, cwd, preDiscoveredIds);
188
- }
189
- const sessionMetaRowSchema = z.object({
190
- key: z.literal(`current`),
191
- electricSessionId: z.string(),
192
- nativeSessionId: z.string().optional(),
193
- agent: z.enum([`claude`, `codex`]),
194
- cwd: z.string(),
195
- status: z.enum([
196
- `initializing`,
197
- `idle`,
198
- `running`,
199
- `error`
200
- ]),
201
- error: z.string().optional(),
202
- currentPromptInboxKey: z.string().optional()
203
- });
204
- const cursorStateRowSchema = z.object({
205
- key: z.literal(`current`),
206
- cursor: z.string(),
207
- lastProcessedInboxKey: z.string().optional()
208
- });
209
- const eventRowSchema = z.object({
210
- key: z.string(),
211
- ts: z.number(),
212
- type: z.string(),
213
- callId: z.string().optional(),
214
- payload: z.looseObject({})
215
- });
216
- const creationArgsSchema = z.object({
217
- agent: z.enum([`claude`, `codex`]),
218
- cwd: z.string().optional(),
219
- nativeSessionId: z.string().optional(),
220
- importFrom: z.object({
221
- agent: z.enum([`claude`, `codex`]),
222
- sessionId: z.string()
223
- }).optional()
224
- });
225
- const promptMessageSchema = z.object({ text: z.string() });
226
- /**
227
- * Stable key for an events-collection row, derived from the event's content.
228
- * Lets us re-insert the same event without producing duplicates — the caller
229
- * (or the collection's uniqueness guard) uses this to de-dup across retries,
230
- * replays, and crash recovery. Sorts chronologically by ts, then by type.
231
- */
232
- function eventKey(event) {
233
- const tsPart = String(event.ts).padStart(16, `0`);
234
- return `${tsPart}_${event.type}_${contentHashHex(event)}`;
235
- }
236
- function contentHashHex(event) {
237
- const json = JSON.stringify(event);
238
- let h = 5381;
239
- for (let i = 0; i < json.length; i++) h = (h * 33 ^ json.charCodeAt(i)) >>> 0;
240
- return h.toString(16).padStart(8, `0`);
241
- }
242
- function buildEventRow(event) {
243
- const callId = `callId` in event && typeof event.callId === `string` ? event.callId : void 0;
244
- return {
245
- key: eventKey(event),
246
- ts: event.ts,
247
- type: event.type,
248
- ...callId !== void 0 ? { callId } : {},
249
- payload: event
250
- };
251
- }
252
- function appendIfNew(ctx, event) {
253
- const row = buildEventRow(event);
254
- if (ctx.events.get(row.key) !== void 0) return;
255
- ctx.actions.events_insert({ row });
256
- }
257
- /**
258
- * Mirror every event that lands in the JSONL file while `runWork` is
259
- * executing (i.e. while the CLI is running). Returns the advanced cursor
260
- * and the `runWork` result once everything has settled and every append
261
- * has been persisted to the entity's durable stream.
262
- *
263
- * If setup fails (e.g. the session file can't be resolved), `runWork`
264
- * still runs — but nothing is mirrored and `setupError` is populated so
265
- * the caller can surface the condition. If `runWork` throws, the error
266
- * propagates after the watcher has been cleaned up.
267
- */
268
- async function runWithLiveMirror(opts) {
269
- let cursor = null;
270
- let setupError = void 0;
271
- try {
272
- const session = await resolveSession(opts.nativeSessionId, opts.agent);
273
- if (opts.serializedCursor) cursor = deserializeCursor({
274
- ...opts.serializedCursor,
275
- path: session.path
276
- });
277
- else {
278
- const initial = await loadSession({
279
- sessionId: opts.nativeSessionId,
280
- agent: opts.agent
281
- });
282
- for (const ev of initial.events) appendIfNew(opts.ctx, ev);
283
- cursor = initial.cursor;
284
- }
285
- } catch (e) {
286
- setupError = e;
287
- }
288
- if (!cursor) {
289
- const result$1 = await opts.runWork();
290
- return {
291
- cursor: opts.serializedCursor,
292
- setupError,
293
- result: result$1
294
- };
295
- }
296
- let activeCursor = cursor;
297
- let busy = false;
298
- let pending = false;
299
- let stopped = false;
300
- const drainOnce = async () => {
301
- if (stopped && busy) return;
302
- if (busy) {
303
- pending = true;
304
- return;
305
- }
306
- busy = true;
307
- try {
308
- const res = await tailSession({ cursor: activeCursor });
309
- activeCursor = res.cursor;
310
- for (const ev of res.newEvents) appendIfNew(opts.ctx, ev);
311
- } catch {} finally {
312
- busy = false;
313
- if (pending && !stopped) {
314
- pending = false;
315
- drainOnce();
316
- }
317
- }
318
- };
319
- const fileWatcher = watch(activeCursor.path, () => {
320
- drainOnce();
321
- });
322
- const pollHandle = setInterval(() => {
323
- drainOnce();
324
- }, 1500);
325
- let result;
326
- try {
327
- result = await opts.runWork();
328
- } finally {
329
- stopped = true;
330
- clearInterval(pollHandle);
331
- fileWatcher.close();
332
- while (busy) await new Promise((r) => setTimeout(r, 10));
333
- try {
334
- const final = await tailSession({ cursor: activeCursor });
335
- activeCursor = final.cursor;
336
- for (const ev of final.newEvents) appendIfNew(opts.ctx, ev);
337
- } catch {}
338
- }
339
- return {
340
- cursor: serializeCursor(activeCursor),
341
- setupError,
342
- result
343
- };
344
- }
345
- function registerCodingSession(registry, options = {}) {
346
- const runner = options.cliRunner ?? defaultCliRunner;
347
- const defaultCwd = options.defaultWorkingDirectory ?? process.cwd();
348
- registry.define(`coder`, {
349
- description: `Runs a Claude Code / Codex CLI session and mirrors its normalized event stream into a durable store. Prompts arrive via message_received (type: "prompt") and are executed serially.`,
350
- creationSchema: creationArgsSchema,
351
- inboxSchemas: { prompt: promptMessageSchema },
352
- state: {
353
- sessionMeta: {
354
- schema: sessionMetaRowSchema,
355
- type: CODING_SESSION_META_COLLECTION_TYPE,
356
- primaryKey: `key`
357
- },
358
- cursorState: {
359
- schema: cursorStateRowSchema,
360
- type: CODING_SESSION_CURSOR_COLLECTION_TYPE,
361
- primaryKey: `key`
362
- },
363
- events: {
364
- schema: eventRowSchema,
365
- type: CODING_SESSION_EVENT_COLLECTION_TYPE,
366
- primaryKey: `key`
367
- }
368
- },
369
- async handler(ctx, _wake) {
370
- const existingMeta = ctx.db.collections.sessionMeta.get(`current`);
371
- if (!existingMeta) {
372
- const args = creationArgsSchema.parse(ctx.args);
373
- const cwd = args.cwd ?? defaultCwd;
374
- const electricSessionId = ctx.entityUrl.split(`/`).pop() ?? ctx.entityUrl;
375
- let resolvedNativeId = args.nativeSessionId;
376
- if (args.importFrom) {
377
- const result = await importLocalSession({
378
- source: {
379
- sessionId: args.importFrom.sessionId,
380
- agent: args.importFrom.agent
381
- },
382
- target: {
383
- agent: args.agent,
384
- cwd
385
- }
386
- });
387
- resolvedNativeId = result.sessionId;
388
- }
389
- const hasNative = resolvedNativeId !== void 0;
390
- ctx.db.actions.sessionMeta_insert({ row: {
391
- key: `current`,
392
- electricSessionId,
393
- ...hasNative ? { nativeSessionId: resolvedNativeId } : {},
394
- agent: args.agent,
395
- cwd,
396
- status: hasNative ? `idle` : `initializing`
397
- } });
398
- }
399
- if (!ctx.db.collections.cursorState.get(`current`)) ctx.db.actions.cursorState_insert({ row: {
400
- key: `current`,
401
- cursor: ``
402
- } });
403
- const metaRow = ctx.db.collections.sessionMeta.get(`current`);
404
- const cursorRow = ctx.db.collections.cursorState.get(`current`);
405
- if (!metaRow || !cursorRow) throw new Error(`[coding-session] expected sessionMeta and cursorState rows to exist after init`);
406
- if (metaRow.nativeSessionId && !cursorRow.cursor) {
407
- const mirrorCtx = {
408
- events: { get: (k) => ctx.db.collections.events.get(k) },
409
- actions: { events_insert: ctx.db.actions.events_insert }
410
- };
411
- try {
412
- const initial = await loadSession({
413
- sessionId: metaRow.nativeSessionId,
414
- agent: metaRow.agent
415
- });
416
- for (const ev of initial.events) appendIfNew(mirrorCtx, ev);
417
- const serialized = serializeCursor(initial.cursor);
418
- ctx.db.actions.cursorState_update({
419
- key: `current`,
420
- updater: (d) => {
421
- d.cursor = JSON.stringify(serialized);
422
- }
423
- });
424
- } catch (e) {
425
- const message = e instanceof Error ? e.message : String(e);
426
- ctx.db.actions.sessionMeta_update({
427
- key: `current`,
428
- updater: (d) => {
429
- d.error = `initial mirror failed: ${message}`;
430
- }
431
- });
432
- }
433
- }
434
- const inboxRows = ctx.db.collections.inbox.toArray.slice().sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
435
- const lastKey = cursorRow.lastProcessedInboxKey ?? ``;
436
- const pending = inboxRows.filter((m) => m.key > lastKey);
437
- if (pending.length === 0) {
438
- if (metaRow.status === `running` || metaRow.status === `error`) ctx.db.actions.sessionMeta_update({
439
- key: `current`,
440
- updater: (d) => {
441
- d.status = `idle`;
442
- delete d.currentPromptInboxKey;
443
- delete d.error;
444
- }
445
- });
446
- return;
447
- }
448
- let runningMeta = metaRow;
449
- let runningCursor = cursorRow;
450
- for (const inboxMsg of pending) {
451
- const parsed = promptMessageSchema.safeParse(inboxMsg.payload);
452
- if (!parsed.success) {
453
- ctx.db.actions.cursorState_update({
454
- key: `current`,
455
- updater: (d) => {
456
- d.lastProcessedInboxKey = inboxMsg.key;
457
- }
458
- });
459
- runningCursor = {
460
- ...runningCursor,
461
- lastProcessedInboxKey: inboxMsg.key
462
- };
463
- continue;
464
- }
465
- const prompt = parsed.data.text;
466
- const existingTitle = ctx.tags.title;
467
- if (typeof existingTitle !== `string` || existingTitle.length === 0) ctx.setTag(`title`, prompt.slice(0, 80));
468
- ctx.db.actions.sessionMeta_update({
469
- key: `current`,
470
- updater: (d) => {
471
- d.status = `running`;
472
- d.currentPromptInboxKey = inboxMsg.key;
473
- delete d.error;
474
- }
475
- });
476
- const recordedRun = ctx.recordRun();
477
- const eventKeysBefore = new Set(ctx.db.collections.events.toArray.map((e) => e.key));
478
- try {
479
- const mirrorCtx = {
480
- events: { get: (k) => ctx.db.collections.events.get(k) },
481
- actions: { events_insert: ctx.db.actions.events_insert }
482
- };
483
- let nextCursorJson = runningCursor.cursor;
484
- if (!runningMeta.nativeSessionId) {
485
- const preDirectIds = runningMeta.agent === `claude` ? await listClaudeJsonlIdsByCwd(runningMeta.cwd) : new Set();
486
- const preDiscoveredIds = new Set((await discoverSessions(runningMeta.agent)).map((s) => s.sessionId));
487
- const cliResult = await runner.run({
488
- agent: runningMeta.agent,
489
- cwd: runningMeta.cwd,
490
- prompt
491
- });
492
- if (cliResult.exitCode !== 0) throw new Error(`[coding-session] ${runningMeta.agent} CLI exited ${cliResult.exitCode}. stderr=${cliResult.stderr.slice(0, 800) || `<empty>`} stdout=${cliResult.stdout.slice(0, 800) || `<empty>`}`);
493
- const foundId = await findNewSessionAfterRun(runningMeta.agent, runningMeta.cwd, preDirectIds, preDiscoveredIds);
494
- if (!foundId) throw new Error(`[coding-session] ${runningMeta.agent} CLI succeeded but no new session file was found`);
495
- ctx.db.actions.sessionMeta_update({
496
- key: `current`,
497
- updater: (d) => {
498
- d.nativeSessionId = foundId;
499
- }
500
- });
501
- runningMeta = {
502
- ...runningMeta,
503
- nativeSessionId: foundId
504
- };
505
- const initial = await loadSession({
506
- sessionId: foundId,
507
- agent: runningMeta.agent
508
- });
509
- for (const ev of initial.events) appendIfNew(mirrorCtx, ev);
510
- nextCursorJson = JSON.stringify(serializeCursor(initial.cursor));
511
- } else {
512
- const serializedCursor = runningCursor.cursor ? JSON.parse(runningCursor.cursor) : null;
513
- const { cursor: nextSerialized, setupError, result: cliResult } = await runWithLiveMirror({
514
- agent: runningMeta.agent,
515
- nativeSessionId: runningMeta.nativeSessionId,
516
- serializedCursor,
517
- ctx: mirrorCtx,
518
- runWork: () => runner.run({
519
- agent: runningMeta.agent,
520
- sessionId: runningMeta.nativeSessionId,
521
- cwd: runningMeta.cwd,
522
- prompt
523
- })
524
- });
525
- if (setupError) throw setupError instanceof Error ? setupError : new Error(String(setupError));
526
- if (cliResult.exitCode !== 0) throw new Error(`[coding-session] ${runningMeta.agent} CLI exited ${cliResult.exitCode}. stderr=${cliResult.stderr.slice(0, 800) || `<empty>`} stdout=${cliResult.stdout.slice(0, 800) || `<empty>`}`);
527
- const persistedCursor = nextSerialized ?? serializedCursor;
528
- nextCursorJson = persistedCursor ? JSON.stringify(persistedCursor) : ``;
529
- }
530
- ctx.db.actions.cursorState_update({
531
- key: `current`,
532
- updater: (d) => {
533
- d.cursor = nextCursorJson;
534
- d.lastProcessedInboxKey = inboxMsg.key;
535
- }
536
- });
537
- runningCursor = {
538
- ...runningCursor,
539
- cursor: nextCursorJson,
540
- lastProcessedInboxKey: inboxMsg.key
541
- };
542
- for (const row of ctx.db.collections.events.toArray) {
543
- if (eventKeysBefore.has(row.key)) continue;
544
- if (row.type !== `assistant_message`) continue;
545
- const text = row.payload?.text;
546
- if (typeof text === `string` && text.length > 0) recordedRun.attachResponse(text);
547
- }
548
- recordedRun.end({ status: `completed` });
549
- } catch (e) {
550
- const message = e instanceof Error ? e.message : String(e);
551
- recordedRun.end({
552
- status: `failed`,
553
- finishReason: `error`
554
- });
555
- ctx.db.actions.sessionMeta_update({
556
- key: `current`,
557
- updater: (d) => {
558
- d.status = `error`;
559
- d.error = message;
560
- }
561
- });
562
- ctx.db.actions.cursorState_update({
563
- key: `current`,
564
- updater: (d) => {
565
- d.lastProcessedInboxKey = inboxMsg.key;
566
- }
567
- });
568
- throw e;
569
- }
570
- }
571
- ctx.db.actions.sessionMeta_update({
572
- key: `current`,
573
- updater: (d) => {
574
- d.status = `idle`;
575
- delete d.currentPromptInboxKey;
576
- delete d.error;
577
- }
578
- });
579
- }
580
- });
581
- }
582
-
583
72
  //#endregion
584
73
  //#region src/docs/embed.ts
585
74
  const EMBEDDING_DIMENSIONS = 128;
@@ -650,7 +139,7 @@ function normalizeWhitespace(value) {
650
139
  }
651
140
  async function collectMarkdownFiles(root) {
652
141
  async function walk(dir) {
653
- const entries = await fs.readdir(dir, { withFileTypes: true });
142
+ const entries = await fs$1.readdir(dir, { withFileTypes: true });
654
143
  const files = [];
655
144
  for (const entry of entries) {
656
145
  const fullPath = path.join(dir, entry.name);
@@ -826,7 +315,7 @@ function resolveDocsRoot(workingDirectory) {
826
315
  requireIndex: false
827
316
  }
828
317
  ].filter((value) => Boolean(value));
829
- for (const candidate of candidates) if (fsSync.existsSync(candidate.path) && (!candidate.requireIndex || fsSync.existsSync(path.join(candidate.path, `index.md`)))) return candidate.path;
318
+ for (const candidate of candidates) if (fs.existsSync(candidate.path) && (!candidate.requireIndex || fs.existsSync(path.join(candidate.path, `index.md`)))) return candidate.path;
830
319
  return null;
831
320
  }
832
321
  var DocsKnowledgeBase = class {
@@ -847,7 +336,7 @@ var DocsKnowledgeBase = class {
847
336
  this.readyPromise = this.ensureIngested();
848
337
  }
849
338
  openDatabase() {
850
- fsSync.mkdirSync(path.dirname(this.dbPath), { recursive: true });
339
+ fs.mkdirSync(path.dirname(this.dbPath), { recursive: true });
851
340
  try {
852
341
  const db$1 = new Database(this.dbPath);
853
342
  load(db$1);
@@ -914,11 +403,11 @@ var DocsKnowledgeBase = class {
914
403
  };
915
404
  }
916
405
  async ensureIngested() {
917
- await fs.mkdir(path.dirname(this.dbPath), { recursive: true });
406
+ await fs$1.mkdir(path.dirname(this.dbPath), { recursive: true });
918
407
  const files = (await collectMarkdownFiles(this.docsRoot)).sort();
919
408
  const docs = await Promise.all(files.map(async (filePath) => ({
920
409
  path: path.relative(this.docsRoot, filePath),
921
- content: await fs.readFile(filePath, `utf8`)
410
+ content: await fs$1.readFile(filePath, `utf8`)
922
411
  })));
923
412
  const fingerprint = createFingerprint(docs);
924
413
  if (!this.db) {
@@ -1265,7 +754,7 @@ function createSkillTools(registry, ctx) {
1265
754
  const mdFiles = allRefFiles.filter((f) => f.endsWith(`.md`));
1266
755
  const refContents = [];
1267
756
  for (const f of mdFiles) try {
1268
- const refContent = await fs.readFile(path.join(skillDir, f), `utf-8`);
757
+ const refContent = await fs$1.readFile(path.join(skillDir, f), `utf-8`);
1269
758
  const refId = `${skillContextId(name)}:${f}`;
1270
759
  ctx.insertContext(refId, {
1271
760
  name: `skill_reference`,
@@ -1365,10 +854,10 @@ function substituteArgs(content, rawArgs, argNames) {
1365
854
  function listRefFiles(dir, prefix = ``) {
1366
855
  try {
1367
856
  const results = [];
1368
- for (const entry of fsSync.readdirSync(dir)) {
857
+ for (const entry of fs.readdirSync(dir)) {
1369
858
  const full = path.join(dir, entry);
1370
859
  const rel = prefix ? `${prefix}/${entry}` : entry;
1371
- if (fsSync.statSync(full).isDirectory()) results.push(...listRefFiles(full, rel));
860
+ if (fs.statSync(full).isDirectory()) results.push(...listRefFiles(full, rel));
1372
861
  else results.push(rel);
1373
862
  }
1374
863
  return results;
@@ -1384,11 +873,11 @@ const WORKER_TOOL_NAMES = [
1384
873
  `read`,
1385
874
  `write`,
1386
875
  `edit`,
1387
- `brave_search`,
876
+ `web_search`,
1388
877
  `fetch_url`,
1389
878
  `spawn_worker`
1390
879
  ];
1391
- function createSpawnWorkerTool(ctx) {
880
+ function createSpawnWorkerTool(ctx, modelConfig) {
1392
881
  return {
1393
882
  name: `spawn_worker`,
1394
883
  label: `Spawn Worker`,
@@ -1415,10 +904,16 @@ function createSpawnWorkerTool(ctx) {
1415
904
  details: { spawned: false }
1416
905
  };
1417
906
  const id = nanoid(10);
907
+ const workerModelArgs = modelConfig ? {
908
+ provider: modelConfig.provider,
909
+ model: modelConfig.model,
910
+ ...modelConfig.reasoningEffort && { reasoningEffort: modelConfig.reasoningEffort }
911
+ } : {};
1418
912
  try {
1419
913
  const handle = await ctx.spawn(`worker`, id, {
1420
914
  systemPrompt,
1421
- tools
915
+ tools,
916
+ ...workerModelArgs
1422
917
  }, {
1423
918
  initialMessage,
1424
919
  wake: {
@@ -1452,140 +947,138 @@ function createSpawnWorkerTool(ctx) {
1452
947
  }
1453
948
 
1454
949
  //#endregion
1455
- //#region src/tools/spawn-coder.ts
1456
- const CODER_AGENT_NAMES = [`claude`, `codex`];
1457
- function createSpawnCoderTool(ctx) {
950
+ //#region src/model-catalog.ts
951
+ const REASONING_EFFORT_VALUES = [
952
+ `auto`,
953
+ `minimal`,
954
+ `low`,
955
+ `medium`,
956
+ `high`
957
+ ];
958
+ const DEFAULT_ANTHROPIC_MODEL = `claude-sonnet-4-6`;
959
+ const DEFAULT_OPENAI_MODEL = `gpt-4.1`;
960
+ const DEFAULT_CODEX_MODEL = `gpt-5.4`;
961
+ function modelValue(provider, id) {
962
+ return `${provider}:${id}`;
963
+ }
964
+ function providerLabel(provider) {
965
+ if (provider === `anthropic`) return `Anthropic`;
966
+ if (provider === `openai-codex`) return `OpenAI Codex`;
967
+ return `OpenAI`;
968
+ }
969
+ function configuredProviders() {
970
+ return detectAvailableProviders();
971
+ }
972
+ function mockFallbackCatalog() {
973
+ const fallback = {
974
+ provider: `anthropic`,
975
+ id: DEFAULT_ANTHROPIC_MODEL,
976
+ label: `Anthropic ${DEFAULT_ANTHROPIC_MODEL}`,
977
+ value: modelValue(`anthropic`, DEFAULT_ANTHROPIC_MODEL),
978
+ reasoning: true
979
+ };
1458
980
  return {
1459
- name: `spawn_coder`,
1460
- label: `Spawn Coder`,
1461
- description: `Spawn a coding-session subagent (a coder) that drives a Claude Code or Codex CLI session in a working directory. Use when the user asks for code changes, file edits, debugging, or any task that benefits from a real coding agent with tool access. The coder is long-lived — its URL stays valid across many turns, so you can keep prompting it via prompt_coder without re-spawning. End your turn after spawning; you'll be woken when the coder finishes its first reply.`,
1462
- parameters: Type.Object({
1463
- prompt: Type.String({ description: `First user message sent to the coder. This is what kicks off the run — without it the coder will idle. Be concrete: describe the task, mention the files/paths involved, and what form of answer you want back.` }),
1464
- agent: Type.Optional(Type.Union(CODER_AGENT_NAMES.map((n) => Type.Literal(n)), { description: `Which coding agent to use. Defaults to "claude". Use "codex" only if the user explicitly asks for it.` })),
1465
- cwd: Type.Optional(Type.String({ description: `Working directory the coder runs in. Defaults to the runtime's cwd (the same directory Horton is running in). Set this when the user wants the coder to operate on a different repo.` }))
1466
- }),
1467
- execute: async (_toolCallId, params) => {
1468
- const { prompt, agent, cwd } = params;
1469
- if (typeof prompt !== `string` || prompt.length === 0) return {
1470
- content: [{
1471
- type: `text`,
1472
- text: `Error: prompt is required and must be a non-empty string.`
1473
- }],
1474
- details: { spawned: false }
1475
- };
1476
- const id = nanoid(10);
1477
- const spawnArgs = { agent: agent ?? `claude` };
1478
- if (cwd) spawnArgs.cwd = cwd;
1479
- try {
1480
- const handle = await ctx.spawn(`coder`, id, spawnArgs, {
1481
- initialMessage: { text: prompt },
1482
- wake: {
1483
- on: `runFinished`,
1484
- includeResponse: true
1485
- }
1486
- });
1487
- const coderUrl = handle.entityUrl;
1488
- return {
1489
- content: [{
1490
- type: `text`,
1491
- text: `Coder dispatched at ${coderUrl}. End your turn — when the coder finishes its current reply you'll be woken with the response. To send follow-up prompts to the same coder, call prompt_coder with this URL.`
1492
- }],
1493
- details: {
1494
- spawned: true,
1495
- coderUrl
1496
- }
1497
- };
1498
- } catch (err) {
1499
- serverLog.warn(`[spawn_coder tool] failed to spawn coder ${id}: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0);
1500
- return {
1501
- content: [{
1502
- type: `text`,
1503
- text: `Error spawning coder: ${err instanceof Error ? err.message : `Unknown error`}`
1504
- }],
1505
- details: { spawned: false }
1506
- };
1507
- }
1508
- }
981
+ choices: [fallback],
982
+ defaultChoice: fallback
1509
983
  };
1510
984
  }
1511
- function createPromptCoderTool(ctx) {
985
+ async function fetchAvailableModelIds(provider) {
986
+ try {
987
+ const res = provider === `anthropic` ? await fetch(`https://api.anthropic.com/v1/models`, {
988
+ headers: {
989
+ "x-api-key": process.env.ANTHROPIC_API_KEY ?? ``,
990
+ "anthropic-version": `2023-06-01`
991
+ },
992
+ signal: AbortSignal.timeout(3e3)
993
+ }) : await fetch(`https://api.openai.com/v1/models`, {
994
+ headers: { authorization: `Bearer ${process.env.OPENAI_API_KEY ?? ``}` },
995
+ signal: AbortSignal.timeout(3e3)
996
+ });
997
+ if (res.status === 401 || res.status === 403) return new Set();
998
+ if (!res.ok) return null;
999
+ const body = await res.json();
1000
+ const ids = new Set((body.data ?? []).map((model) => model.id).filter((id) => typeof id === `string`));
1001
+ return ids.size > 0 ? ids : null;
1002
+ } catch {
1003
+ return null;
1004
+ }
1005
+ }
1006
+ async function choicesForProvider(provider) {
1007
+ const knownModels = getModels(provider);
1008
+ if (provider === `openai-codex`) return knownModels.map((model) => ({
1009
+ provider,
1010
+ id: model.id,
1011
+ label: `${providerLabel(provider)} ${model.name}`,
1012
+ value: modelValue(provider, model.id),
1013
+ reasoning: model.reasoning
1014
+ }));
1015
+ const availableIds = await fetchAvailableModelIds(provider);
1016
+ const models = availableIds === null ? knownModels : knownModels.filter((model) => availableIds.has(model.id));
1017
+ return models.map((model) => ({
1018
+ provider,
1019
+ id: model.id,
1020
+ label: `${providerLabel(provider)} ${model.name}`,
1021
+ value: modelValue(provider, model.id),
1022
+ reasoning: model.reasoning
1023
+ }));
1024
+ }
1025
+ function withProviderPayloadDefaults(config, choice, reasoningEffort) {
1026
+ if (choice.provider !== `openai` && choice.provider !== `openai-codex` || !choice.reasoning) return config;
1027
+ const defaultEffort = choice.provider === `openai-codex` ? `low` : `minimal`;
1028
+ const effort = reasoningEffort === `minimal` && choice.provider === `openai-codex` ? `low` : reasoningEffort ?? defaultEffort;
1512
1029
  return {
1513
- name: `prompt_coder`,
1514
- label: `Prompt Coder`,
1515
- description: `Send a follow-up prompt to a coder you previously spawned. The prompt is queued on the coder's inbox and runs as the next CLI turn. End your turn after calling — you'll be woken when the coder's reply lands.`,
1516
- parameters: Type.Object({
1517
- coder_url: Type.String({ description: `Entity URL returned by spawn_coder, e.g. "/coder/abc123". Must be the URL of a coder you previously spawned in this conversation.` }),
1518
- prompt: Type.String({ description: `Follow-up message to send to the coder. Treat this like the next turn in a chat — reference earlier context the coder already saw rather than restating it.` })
1519
- }),
1520
- execute: async (_toolCallId, params) => {
1521
- const { coder_url, prompt } = params;
1522
- if (typeof coder_url !== `string` || !coder_url.startsWith(`/coder/`)) return {
1523
- content: [{
1524
- type: `text`,
1525
- text: `Error: coder_url must be a path like "/coder/<id>".`
1526
- }],
1527
- details: { sent: false }
1528
- };
1529
- if (typeof prompt !== `string` || prompt.length === 0) return {
1530
- content: [{
1531
- type: `text`,
1532
- text: `Error: prompt is required and must be a non-empty string.`
1533
- }],
1534
- details: { sent: false }
1030
+ ...config,
1031
+ onPayload: (payload) => {
1032
+ if (typeof payload !== `object` || payload === null) return void 0;
1033
+ const body = payload;
1034
+ const existingReasoning = typeof body.reasoning === `object` && body.reasoning !== null ? body.reasoning : {};
1035
+ return {
1036
+ ...body,
1037
+ reasoning: {
1038
+ ...existingReasoning,
1039
+ effort
1040
+ }
1535
1041
  };
1536
- try {
1537
- ctx.send(coder_url, { text: prompt });
1538
- return {
1539
- content: [{
1540
- type: `text`,
1541
- text: `Prompt queued for ${coder_url}. End your turn — you'll be woken when the coder's reply lands.`
1542
- }],
1543
- details: {
1544
- sent: true,
1545
- coderUrl: coder_url
1546
- }
1547
- };
1548
- } catch (err) {
1549
- serverLog.warn(`[prompt_coder tool] failed to send to ${coder_url}: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0);
1550
- return {
1551
- content: [{
1552
- type: `text`,
1553
- text: `Error sending prompt to coder: ${err instanceof Error ? err.message : `Unknown error`}`
1554
- }],
1555
- details: { sent: false }
1556
- };
1557
- }
1558
1042
  }
1559
1043
  };
1560
1044
  }
1045
+ function parseReasoningEffort(value) {
1046
+ return value === `minimal` || value === `low` || value === `medium` || value === `high` ? value : null;
1047
+ }
1048
+ async function createBuiltinModelCatalog(options = {}) {
1049
+ const providers = configuredProviders();
1050
+ if (providers.length === 0 && options.allowMockFallback) return mockFallbackCatalog();
1051
+ const choices = (await Promise.all(providers.map((provider) => choicesForProvider(provider)))).flat();
1052
+ if (choices.length === 0) return options.allowMockFallback ? mockFallbackCatalog() : null;
1053
+ const defaultChoice = choices.find((choice) => choice.provider === `anthropic` && choice.id === DEFAULT_ANTHROPIC_MODEL) ?? choices.find((choice) => choice.provider === `openai` && choice.id === DEFAULT_OPENAI_MODEL) ?? choices.find((choice) => choice.provider === `openai-codex` && choice.id === DEFAULT_CODEX_MODEL) ?? choices[0];
1054
+ return {
1055
+ choices,
1056
+ defaultChoice
1057
+ };
1058
+ }
1059
+ function resolveBuiltinModelConfig(catalog, args) {
1060
+ const modelArg = args.model;
1061
+ const providerArg = args.provider;
1062
+ const reasoningEffort = parseReasoningEffort(args.reasoningEffort);
1063
+ const selected = typeof modelArg === `string` ? catalog.choices.find((choice$1) => choice$1.value === modelArg || choice$1.id === modelArg && choice$1.provider === providerArg) : void 0;
1064
+ const choice = selected ?? catalog.defaultChoice;
1065
+ const config = {
1066
+ provider: choice.provider,
1067
+ model: choice.id,
1068
+ ...reasoningEffort && { reasoningEffort },
1069
+ ...choice.provider === `openai-codex` && { getApiKey: () => readCodexAccessToken() }
1070
+ };
1071
+ return withProviderPayloadDefaults(config, choice, reasoningEffort);
1072
+ }
1073
+ function modelChoiceValues(catalog) {
1074
+ return catalog.choices.map((choice) => choice.value);
1075
+ }
1561
1076
 
1562
1077
  //#endregion
1563
1078
  //#region src/agents/horton.ts
1564
- const TITLE_MODEL = `claude-haiku-4-5-20251001`;
1565
1079
  const HORTON_MODEL = `claude-sonnet-4-6`;
1566
- let anthropic = null;
1567
- function getClient() {
1568
- if (!anthropic) anthropic = new Anthropic();
1569
- return anthropic;
1570
- }
1571
- async function defaultHaikuCall(prompt) {
1572
- const client = getClient();
1573
- const res = await client.messages.create({
1574
- model: TITLE_MODEL,
1575
- max_tokens: 64,
1576
- messages: [{
1577
- role: `user`,
1578
- content: prompt
1579
- }]
1580
- });
1581
- const block = res.content[0];
1582
- return block?.type === `text` ? block.text : ``;
1583
- }
1584
- const TITLE_PROMPT = (userMessage) => `Summarize the following user request in 3-5 words for use as a chat session title.
1585
- Respond with only the title, no quotes, no punctuation, no preamble.
1586
-
1587
- User request:
1588
- ${userMessage}`;
1080
+ const TITLE_SYSTEM_PROMPT = "You generate concise chat session titles in 3-5 words. Respond with only the title, no quotes, no punctuation, no preamble.";
1081
+ const TITLE_USER_PROMPT = (userMessage) => `User request:\n${userMessage}`;
1589
1082
  const TITLE_STOP_WORDS = new Set([
1590
1083
  `a`,
1591
1084
  `an`,
@@ -1653,19 +1146,34 @@ function buildFallbackTitle(userMessage) {
1653
1146
  const selected = informativeWords.length >= 2 ? informativeWords.slice(0, 5) : backupWords;
1654
1147
  return selected.join(` `).slice(0, 80).trim() || `Untitled Chat`;
1655
1148
  }
1656
- async function generateTitle(userMessage, llmCall = defaultHaikuCall) {
1149
+ function createConfiguredTitleCall(catalog, modelConfig, logPrefix) {
1150
+ return (prompt) => completeWithLowCostModel({
1151
+ catalog,
1152
+ modelConfig,
1153
+ log: (message) => serverLog.info(message),
1154
+ logPrefix,
1155
+ purpose: `title generation`,
1156
+ systemPrompt: TITLE_SYSTEM_PROMPT,
1157
+ prompt,
1158
+ maxTokens: 64
1159
+ });
1160
+ }
1161
+ async function generateTitle(userMessage, llmCall, onFallback) {
1657
1162
  try {
1658
- const raw = await llmCall(TITLE_PROMPT(userMessage));
1163
+ const raw = await llmCall(TITLE_USER_PROMPT(userMessage));
1659
1164
  const title = raw.trim();
1660
- return title.length > 0 ? title : buildFallbackTitle(userMessage);
1661
- } catch {
1165
+ if (title.length > 0) return title;
1166
+ onFallback?.(`empty LLM title response`);
1167
+ return buildFallbackTitle(userMessage);
1168
+ } catch (err) {
1169
+ onFallback?.(err instanceof Error ? err.message : String(err));
1662
1170
  return buildFallbackTitle(userMessage);
1663
1171
  }
1664
1172
  }
1665
1173
  function buildHortonSystemPrompt(workingDirectory, opts = {}) {
1666
1174
  const docsTools = opts.hasDocsSupport ? `\n- search_durable_agents_docs: hybrid search over the built-in Durable Agents docs index` : ``;
1667
1175
  const skillsTools = opts.hasSkills ? `\n- use_skill: load a skill (knowledge, instructions, or a tutorial) into your context to help with the user's request\n- remove_skill: unload a skill from context when you're done with it` : ``;
1668
- const docsGuidance = opts.hasDocsSupport ? `\n- For ANY question about Electric Agents, Durable Agents, or this framework, ALWAYS use search_durable_agents_docs FIRST. Do not use brave_search or fetch_url for Electric Agents topics unless the docs search returns no useful results.\n- The search tool returns chunk content directly — you do not need to read the source files.\n- Use repo read/bash tools only for non-doc files or when you need to inspect exact implementation code in the workspace.` : ``;
1176
+ const docsGuidance = opts.hasDocsSupport ? `\n- For ANY question about Electric Agents, Durable Agents, or this framework, ALWAYS use search_durable_agents_docs FIRST. Do not use web_search or fetch_url for Electric Agents topics unless the docs search returns no useful results.\n- The search tool returns chunk content directly — you do not need to read the source files.\n- Use repo read/bash tools only for non-doc files or when you need to inspect exact implementation code in the workspace.` : ``;
1669
1177
  const skillsGuidance = opts.hasSkills ? `\n# Skills\nYou have access to skills — specialized knowledge and guided workflows you can load on demand. Your context includes a skills catalog listing what's available. When the user's request matches a skill's description or keywords, load it with use_skill.
1670
1178
 
1671
1179
  Some skills are user-invocable — the user can trigger them with a slash command like \`/quickstart\`. When you see a message starting with \`/\` followed by a skill name, load that skill immediately with use_skill. Pass any text after the skill name as args.
@@ -1701,7 +1209,9 @@ Don't force onboarding. If someone just wants to chat or code, let them. When in
1701
1209
  - ${opts.hasDocsSupport ? `If search_durable_agents_docs is available, use it first (faster, hybrid search).` : `Use fetch_url to look up documentation pages.`}
1702
1210
  - The Electric Agents docs site is at ${opts.docsUrl}
1703
1211
  - The docs site covers: Usage (entity definition, handlers, tools, state, spawning, coordination, waking, shared state, client integration, app setup), Reference (handler context, entity definitions, configurations, tools, state proxies, wake events, registries), Entities (Horton, Worker), and Patterns (Manager-Worker, Pipeline, Map-Reduce, Dispatcher, Blackboard, Reactive Observers).
1704
- - For general coding questions unrelated to Electric Agents, use brave_search or your own knowledge.` : ``;
1212
+ - For general coding questions unrelated to Electric Agents, use web_search or your own knowledge.` : ``;
1213
+ const modelGuidance = opts.modelProvider && opts.modelId ? `\n# Runtime model
1214
+ You are currently running via provider "${opts.modelProvider}" with model "${opts.modelId}". If the user asks what model or provider you are using, answer with these exact runtime values. Do not infer your model identity from training data or from the name of another coding tool.` : ``;
1705
1215
  return `You are Horton, a friendly and capable assistant. You can chat, research the web, read and edit code, run shell commands, and dispatch subagents (workers) for isolated subtasks. Be warm and engaging in conversation; be precise and concrete when working with code.
1706
1216
 
1707
1217
  # Greetings
@@ -1712,18 +1222,16 @@ When a user opens with a greeting ("hi", "hello", "hey", etc.) or a broad statem
1712
1222
  - read: read a file
1713
1223
  - write: create or overwrite a file
1714
1224
  - edit: targeted string replacement in an existing file (you must read the file first)
1715
- - brave_search: search the web
1225
+ - web_search: search the web
1716
1226
  - fetch_url: fetch and convert a URL to markdown
1717
1227
  - spawn_worker: dispatch a subagent for an isolated task
1718
- - spawn_coder: spawn a long-lived coding agent (Claude Code or Codex CLI) for code changes, file edits, debugging
1719
- - prompt_coder: send a follow-up prompt to a coder you previously spawned
1720
1228
  ${docsTools}${skillsTools}
1721
1229
 
1722
1230
  # Working with files
1723
1231
  - Prefer edit over write when modifying existing files.
1724
1232
  - You must read a file before you can edit it.
1725
1233
  - Use absolute paths or paths relative to the current working directory.
1726
- ${docsGuidance}${skillsGuidance}${onboardingGuidance}${docsUrlGuidance}
1234
+ ${modelGuidance}${docsGuidance}${skillsGuidance}${onboardingGuidance}${docsUrlGuidance}
1727
1235
 
1728
1236
  # Risky actions
1729
1237
  Pause and confirm with the user before:
@@ -1744,13 +1252,6 @@ When you spawn a worker, write its system prompt the way you'd brief a colleague
1744
1252
 
1745
1253
  After spawning, end your turn (optionally with a brief "I've dispatched a worker for X; I'll respond when it finishes"). When the worker finishes, you'll receive a message describing which worker completed and what it returned. Multiple workers may finish at different times — check the message for the worker URL to know which one you're hearing about.
1746
1254
 
1747
- # When to spawn a coder
1748
- Spawn a coder when the user asks for code changes, file edits, debugging, or any task that benefits from a real coding agent with full tool access (bash, file edits, etc.). A coder runs Claude Code or Codex CLI under the hood.
1749
-
1750
- Unlike a worker, a coder is **long-lived**: its URL stays valid across many turns. Spawn once with spawn_coder, then keep prompting it via prompt_coder for follow-ups — don't spawn a new coder for each turn. Treat the coder URL like a chat handle.
1751
-
1752
- After calling spawn_coder or prompt_coder, end your turn. When the coder's reply lands, you'll be woken with the response in the wake message — relay it (or a summary) back to the user, and call prompt_coder again if there's a follow-up.
1753
-
1754
1255
  # Reporting
1755
1256
  Report outcomes faithfully. If a command failed, say so with the relevant output. If you didn't run a verification step, say that rather than implying you did. Don't hedge confirmed results with unnecessary disclaimers.
1756
1257
 
@@ -1764,34 +1265,82 @@ function createHortonTools(workingDirectory, ctx, readSet, opts = {}) {
1764
1265
  createWriteTool(workingDirectory, readSet),
1765
1266
  createEditTool(workingDirectory, readSet),
1766
1267
  braveSearchTool$1,
1767
- fetchUrlTool,
1768
- createSpawnWorkerTool(ctx),
1769
- createSpawnCoderTool(ctx),
1770
- createPromptCoderTool(ctx),
1268
+ ...opts.modelCatalog && opts.modelConfig ? [createFetchUrlTool({
1269
+ catalog: opts.modelCatalog,
1270
+ modelConfig: opts.modelConfig,
1271
+ log: (message) => serverLog.info(message),
1272
+ logPrefix: opts.logPrefix ?? `[horton]`
1273
+ })] : [fetchUrlTool],
1274
+ createSpawnWorkerTool(ctx, opts.modelConfig),
1771
1275
  ...opts.docsSearchTool ? [opts.docsSearchTool] : []
1772
1276
  ];
1773
1277
  }
1774
- function extractFirstUserMessage(events) {
1775
- for (const event of events) {
1776
- if (event.type !== `message_received`) continue;
1777
- const value = event.value;
1778
- if (!value || value.from === `system`) continue;
1779
- const payload = value.payload;
1780
- if (typeof payload === `string`) return payload;
1781
- if (payload != null) return JSON.stringify(payload);
1278
+ function payloadToTitleText(payload) {
1279
+ if (typeof payload === `string`) return payload;
1280
+ if (payload == null) return ``;
1281
+ if (typeof payload === `object`) {
1282
+ const text = payload.text;
1283
+ return typeof text === `string` ? text : JSON.stringify(payload);
1284
+ }
1285
+ return String(payload);
1286
+ }
1287
+ async function extractFirstUserMessage(ctx) {
1288
+ const firstMessage = await queryOnce((q) => q.from({ inbox: ctx.db.collections.inbox }).where(({ inbox }) => not(eq(inbox.from, `system`))).orderBy(({ inbox }) => inbox._seq, `asc`).findOne());
1289
+ if (!firstMessage) return null;
1290
+ const text = payloadToTitleText(firstMessage.payload);
1291
+ return text.length > 0 ? text : null;
1292
+ }
1293
+ function readAgentsMd(workingDirectory) {
1294
+ const agentsMdPath = path.join(workingDirectory, `AGENTS.md`);
1295
+ try {
1296
+ if (!fs.existsSync(agentsMdPath) || !fs.statSync(agentsMdPath).isFile()) return null;
1297
+ const content = fs.readFileSync(agentsMdPath, `utf8`);
1298
+ return [
1299
+ `<context_file kind="instructions" path="${agentsMdPath}">`,
1300
+ content,
1301
+ `</context_file>`
1302
+ ].join(`\n`);
1303
+ } catch {
1304
+ return null;
1782
1305
  }
1783
- return null;
1784
1306
  }
1785
1307
  function createAssistantHandler(options) {
1786
- const { workingDirectory, streamFn, docsSupport, docsSearchTool, skillsRegistry, docsUrl } = options;
1308
+ const { workingDirectory, streamFn, docsSupport, docsSearchTool, skillsRegistry, modelCatalog, docsUrl } = options;
1787
1309
  const hasSkills = Boolean(skillsRegistry && skillsRegistry.catalog.size > 0);
1788
1310
  return async function assistantHandler(ctx, wake) {
1789
1311
  const readSet = new Set();
1312
+ const effectiveCwd = typeof ctx.args.workingDirectory === `string` && ctx.args.workingDirectory.trim().length > 0 ? ctx.args.workingDirectory : workingDirectory;
1313
+ const modelConfig = resolveBuiltinModelConfig(modelCatalog, ctx.args);
1314
+ const agentsMd = readAgentsMd(effectiveCwd);
1790
1315
  const tools = [
1791
1316
  ...ctx.electricTools,
1792
- ...createHortonTools(workingDirectory, ctx, readSet, { docsSearchTool }),
1793
- ...skillsRegistry && skillsRegistry.catalog.size > 0 ? createSkillTools(skillsRegistry, ctx) : []
1317
+ ...createHortonTools(effectiveCwd, ctx, readSet, {
1318
+ docsSearchTool,
1319
+ modelConfig,
1320
+ modelCatalog,
1321
+ logPrefix: `[horton ${ctx.entityUrl}]`
1322
+ }),
1323
+ ...skillsRegistry && skillsRegistry.catalog.size > 0 ? createSkillTools(skillsRegistry, ctx) : [],
1324
+ ...mcp.tools()
1794
1325
  ];
1326
+ const titlePromise = ctx.firstWake && !ctx.tags.title ? (async () => {
1327
+ const firstUserMessage = await extractFirstUserMessage(ctx);
1328
+ if (!firstUserMessage) return;
1329
+ let title = null;
1330
+ try {
1331
+ const result = await generateTitle(firstUserMessage, createConfiguredTitleCall(modelCatalog, modelConfig, `[horton ${ctx.entityUrl}]`), (reason) => {
1332
+ serverLog.warn(`[horton ${ctx.entityUrl}] title generation fell back to local title: ${reason}`);
1333
+ });
1334
+ if (result.length > 0) title = result;
1335
+ } catch (err) {
1336
+ serverLog.warn(`[horton ${ctx.entityUrl}] title generation failed: ${err instanceof Error ? err.message : String(err)}`);
1337
+ }
1338
+ if (title !== null) try {
1339
+ await ctx.setTag(`title`, title);
1340
+ } catch (err) {
1341
+ serverLog.warn(`[horton ${ctx.entityUrl}] setTag failed: ${err instanceof Error ? err.message : String(err)}`);
1342
+ }
1343
+ })() : Promise.resolve();
1795
1344
  if (docsSupport) ctx.useContext({
1796
1345
  sourceBudget: 1e5,
1797
1346
  sources: {
@@ -1809,6 +1358,11 @@ function createAssistantHandler(options) {
1809
1358
  content: () => ctx.timelineMessages(),
1810
1359
  cache: `volatile`
1811
1360
  },
1361
+ ...agentsMd ? { agents_md: {
1362
+ content: () => agentsMd,
1363
+ max: 2e4,
1364
+ cache: `stable`
1365
+ } } : {},
1812
1366
  ...skillsRegistry && skillsRegistry.catalog.size > 0 ? { skills_catalog: {
1813
1367
  content: () => skillsRegistry.renderCatalog(2e3),
1814
1368
  max: 2e3,
@@ -1827,41 +1381,46 @@ function createAssistantHandler(options) {
1827
1381
  conversation: {
1828
1382
  content: () => ctx.timelineMessages(),
1829
1383
  cache: `volatile`
1384
+ },
1385
+ ...agentsMd ? { agents_md: {
1386
+ content: () => agentsMd,
1387
+ max: 2e4,
1388
+ cache: `stable`
1389
+ } } : {}
1390
+ }
1391
+ });
1392
+ else if (agentsMd) ctx.useContext({
1393
+ sourceBudget: 1e5,
1394
+ sources: {
1395
+ conversation: {
1396
+ content: () => ctx.timelineMessages(),
1397
+ cache: `volatile`
1398
+ },
1399
+ agents_md: {
1400
+ content: () => agentsMd,
1401
+ max: 2e4,
1402
+ cache: `stable`
1830
1403
  }
1831
1404
  }
1832
1405
  });
1833
1406
  ctx.useAgent({
1834
- systemPrompt: buildHortonSystemPrompt(workingDirectory, {
1407
+ systemPrompt: buildHortonSystemPrompt(effectiveCwd, {
1835
1408
  hasDocsSupport: Boolean(docsSupport),
1836
1409
  hasSkills,
1837
- docsUrl
1410
+ docsUrl,
1411
+ modelProvider: modelConfig.provider,
1412
+ modelId: String(modelConfig.model)
1838
1413
  }),
1839
- model: HORTON_MODEL,
1414
+ ...modelConfig,
1840
1415
  tools,
1841
1416
  ...streamFn && { streamFn }
1842
1417
  });
1843
1418
  await ctx.agent.run();
1844
- if (ctx.firstWake && !ctx.tags.title) {
1845
- const firstUserMessage = extractFirstUserMessage(ctx.events);
1846
- if (firstUserMessage) {
1847
- let title = null;
1848
- try {
1849
- const result = await generateTitle(firstUserMessage);
1850
- if (result.length > 0) title = result;
1851
- } catch (err) {
1852
- serverLog.warn(`[horton ${ctx.entityUrl}] title generation failed: ${err instanceof Error ? err.message : String(err)}`);
1853
- }
1854
- if (title !== null) try {
1855
- await ctx.setTag(`title`, title);
1856
- } catch (err) {
1857
- serverLog.warn(`[horton ${ctx.entityUrl}] setTag failed: ${err instanceof Error ? err.message : String(err)}`);
1858
- }
1859
- }
1860
- }
1419
+ await titlePromise;
1861
1420
  };
1862
1421
  }
1863
1422
  function registerHorton(registry, options) {
1864
- const { workingDirectory, streamFn, skillsRegistry = null } = options;
1423
+ const { workingDirectory, streamFn, skillsRegistry = null, modelCatalog } = options;
1865
1424
  const docsUrl = options.docsUrl ?? process.env.HORTON_DOCS_URL;
1866
1425
  if (process.env.BRAVE_SEARCH_API_KEY) serverLog.info(`[horton] Web search: using Brave Search API`);
1867
1426
  else serverLog.warn(`[horton] BRAVE_SEARCH_API_KEY not set — web search will fall back to Anthropic built-in search (uses your ANTHROPIC_API_KEY)`);
@@ -1876,10 +1435,17 @@ function registerHorton(registry, options) {
1876
1435
  docsSupport,
1877
1436
  docsSearchTool,
1878
1437
  skillsRegistry,
1438
+ modelCatalog,
1879
1439
  docsUrl
1880
1440
  });
1441
+ const hortonCreationSchema = z.object({
1442
+ model: z.enum(modelChoiceValues(modelCatalog)).default(modelCatalog.defaultChoice.value),
1443
+ reasoningEffort: z.enum(REASONING_EFFORT_VALUES).default(`auto`).describe(`Reasoning effort for compatible reasoning models. Auto uses a safe provider default.`),
1444
+ workingDirectory: z.string().optional().describe(`Working directory for file operations. Defaults to the server's configured cwd.`)
1445
+ });
1881
1446
  registry.define(`horton`, {
1882
1447
  description: `Friendly capable assistant — chat, code, research, dispatch`,
1448
+ creationSchema: hortonCreationSchema,
1883
1449
  handler: assistantHandler
1884
1450
  });
1885
1451
  const typeNames = [`horton`];
@@ -1924,6 +1490,9 @@ function parseWorkerArgs(value) {
1924
1490
  };
1925
1491
  }
1926
1492
  if (tools.length === 0 && !args.sharedDb) throw new Error(`[worker] must provide tools and/or sharedDb`);
1493
+ if (typeof value.model === `string`) args.model = value.model;
1494
+ if (typeof value.provider === `string`) args.provider = value.provider;
1495
+ if (typeof value.reasoningEffort === `string` && REASONING_EFFORT_VALUES.includes(value.reasoningEffort)) args.reasoningEffort = value.reasoningEffort;
1927
1496
  return args;
1928
1497
  }
1929
1498
  function buildToolsForWorker(tools, workingDirectory, ctx, readSet) {
@@ -1941,7 +1510,7 @@ function buildToolsForWorker(tools, workingDirectory, ctx, readSet) {
1941
1510
  case `edit`:
1942
1511
  out.push(createEditTool(workingDirectory, readSet));
1943
1512
  break;
1944
- case `brave_search`:
1513
+ case `web_search`:
1945
1514
  out.push(braveSearchTool$1);
1946
1515
  break;
1947
1516
  case `fetch_url`:
@@ -2050,13 +1619,14 @@ function buildSharedStateTools(shared, schema, mode) {
2050
1619
  return tools;
2051
1620
  }
2052
1621
  function registerWorker(registry, options) {
2053
- const { workingDirectory, streamFn } = options;
1622
+ const { workingDirectory, streamFn, modelCatalog } = options;
2054
1623
  registry.define(`worker`, {
2055
1624
  description: `Internal — generic worker spawned by other agents. Configure via spawn args (systemPrompt + tools + optional sharedDb).`,
2056
1625
  async handler(ctx) {
2057
1626
  const args = parseWorkerArgs(ctx.args);
2058
1627
  const readSet = new Set();
2059
1628
  const builtinTools = buildToolsForWorker(args.tools, workingDirectory, ctx, readSet);
1629
+ const modelConfig = resolveBuiltinModelConfig(modelCatalog, args);
2060
1630
  const sharedStateTools = [];
2061
1631
  if (args.sharedDb) {
2062
1632
  const shared = await ctx.observe(db(args.sharedDb.id, args.sharedDb.schema));
@@ -2064,7 +1634,7 @@ function registerWorker(registry, options) {
2064
1634
  }
2065
1635
  ctx.useAgent({
2066
1636
  systemPrompt: `${args.systemPrompt}${WORKER_PROMPT_FOOTER}`,
2067
- model: HORTON_MODEL,
1637
+ ...modelConfig,
2068
1638
  tools: [...builtinTools, ...sharedStateTools],
2069
1639
  ...streamFn && { streamFn }
2070
1640
  });
@@ -2154,7 +1724,6 @@ function stripQuotes(value) {
2154
1724
 
2155
1725
  //#endregion
2156
1726
  //#region src/skills/extract-meta.ts
2157
- const EXTRACT_MODEL = `claude-haiku-4-5-20251001`;
2158
1727
  const DEFAULT_MAX = 1e4;
2159
1728
  async function extractSkillMeta(name, content) {
2160
1729
  const preamble = parsePreamble(content);
@@ -2167,7 +1736,7 @@ async function extractSkillMeta(name, content) {
2167
1736
  ...preamble.userInvocable && { userInvocable: true },
2168
1737
  max: preamble.max ?? DEFAULT_MAX
2169
1738
  };
2170
- if (process.env.ANTHROPIC_API_KEY) try {
1739
+ try {
2171
1740
  return await llmExtract(name, content, preamble);
2172
1741
  } catch (err) {
2173
1742
  serverLog.warn(`[skills] LLM metadata extraction failed for "${name}": ${err instanceof Error ? err.message : String(err)}`);
@@ -2180,7 +1749,6 @@ async function extractSkillMeta(name, content) {
2180
1749
  };
2181
1750
  }
2182
1751
  async function llmExtract(name, content, partial) {
2183
- const client = new Anthropic();
2184
1752
  const truncated = content.slice(0, 8e3);
2185
1753
  const prompt = `Analyze this skill document and extract metadata. The skill is named "${name}".
2186
1754
 
@@ -2194,15 +1762,14 @@ Return ONLY a JSON object with these fields:
2194
1762
  - "keywords": array of 3-8 relevant keywords
2195
1763
 
2196
1764
  Return raw JSON, no markdown fences.`;
2197
- const res = await client.messages.create({
2198
- model: EXTRACT_MODEL,
2199
- max_tokens: 256,
2200
- messages: [{
2201
- role: `user`,
2202
- content: prompt
2203
- }]
1765
+ const text = await completeWithLowCostModel({
1766
+ purpose: `skill metadata extraction`,
1767
+ systemPrompt: `Extract metadata from skill documents. Return only valid JSON that matches the requested schema.`,
1768
+ prompt,
1769
+ maxTokens: 256,
1770
+ log: (message) => serverLog.info(message),
1771
+ logPrefix: `[skills]`
2204
1772
  });
2205
- const text = res.content[0]?.type === `text` ? res.content[0].text : ``;
2206
1773
  const parsed = JSON.parse(text);
2207
1774
  return {
2208
1775
  description: partial.description ?? parsed.description ?? humanize(name),
@@ -2227,7 +1794,7 @@ async function createSkillsRegistry(opts) {
2227
1794
  if (appSkillsDir) await scanDir(appSkillsDir, files);
2228
1795
  const catalog = new Map();
2229
1796
  for (const [name, filePath] of files) {
2230
- const content = await fs.readFile(filePath, `utf-8`);
1797
+ const content = await fs$1.readFile(filePath, `utf-8`);
2231
1798
  const hash = sha256(content);
2232
1799
  const cached = existingCache[name];
2233
1800
  if (cached && cached.contentHash === hash && cached.source === filePath) {
@@ -2261,7 +1828,7 @@ async function createSkillsRegistry(opts) {
2261
1828
  const meta = catalog.get(name);
2262
1829
  if (!meta) return null;
2263
1830
  try {
2264
- return await fs.readFile(meta.source, `utf-8`);
1831
+ return await fs$1.readFile(meta.source, `utf-8`);
2265
1832
  } catch {
2266
1833
  return null;
2267
1834
  }
@@ -2271,7 +1838,7 @@ async function createSkillsRegistry(opts) {
2271
1838
  async function scanDir(dir, out) {
2272
1839
  let entries;
2273
1840
  try {
2274
- entries = await fs.readdir(dir, { withFileTypes: true });
1841
+ entries = await fs$1.readdir(dir, { withFileTypes: true });
2275
1842
  } catch {
2276
1843
  return;
2277
1844
  }
@@ -2283,7 +1850,7 @@ async function scanDir(dir, out) {
2283
1850
  }
2284
1851
  async function loadCache(cachePath) {
2285
1852
  try {
2286
- const raw = await fs.readFile(cachePath, `utf-8`);
1853
+ const raw = await fs$1.readFile(cachePath, `utf-8`);
2287
1854
  return JSON.parse(raw);
2288
1855
  } catch {
2289
1856
  return {};
@@ -2292,9 +1859,9 @@ async function loadCache(cachePath) {
2292
1859
  async function saveCache(cachePath, catalog, cacheDir) {
2293
1860
  const obj = {};
2294
1861
  for (const [name, meta] of catalog) obj[name] = meta;
2295
- fsSync.mkdirSync(cacheDir, { recursive: true });
2296
- await fs.writeFile(path.join(cacheDir, `.gitignore`), `*\n`, `utf-8`);
2297
- await fs.writeFile(cachePath, JSON.stringify(obj, null, 2), `utf-8`);
1862
+ fs.mkdirSync(cacheDir, { recursive: true });
1863
+ await fs$1.writeFile(path.join(cacheDir, `.gitignore`), `*\n`, `utf-8`);
1864
+ await fs$1.writeFile(cachePath, JSON.stringify(obj, null, 2), `utf-8`);
2298
1865
  }
2299
1866
  function sha256(content) {
2300
1867
  return createHash(`sha256`).update(content).digest(`hex`);
@@ -2333,9 +1900,10 @@ function truncate(str, max) {
2333
1900
  //#region src/bootstrap.ts
2334
1901
  const DEFAULT_BUILTIN_AGENT_HANDLER_PATH = `/_electric/builtin-agent-handler`;
2335
1902
  async function createBuiltinAgentHandler(options) {
2336
- const { agentServerUrl, serveEndpoint = `${agentServerUrl}${DEFAULT_BUILTIN_AGENT_HANDLER_PATH}`, workingDirectory, streamFn, createElectricTools } = options;
2337
- if (!streamFn && !process.env.ANTHROPIC_API_KEY) {
2338
- serverLog.warn(`[builtin-agents] ANTHROPIC_API_KEY not set — skipping built-in agent registration`);
1903
+ const { agentServerUrl, serveEndpoint = `${agentServerUrl}${DEFAULT_BUILTIN_AGENT_HANDLER_PATH}`, workingDirectory, streamFn, createElectricTools, publicUrl, runtimeName } = options;
1904
+ const modelCatalog = await createBuiltinModelCatalog({ allowMockFallback: Boolean(streamFn) });
1905
+ if (!modelCatalog) {
1906
+ serverLog.warn(`[builtin-agents] no supported model provider API key found — set ANTHROPIC_API_KEY or OPENAI_API_KEY`);
2339
1907
  return null;
2340
1908
  }
2341
1909
  const cwd = workingDirectory ?? process.cwd();
@@ -2356,22 +1924,24 @@ async function createBuiltinAgentHandler(options) {
2356
1924
  const typeNames = registerHorton(registry, {
2357
1925
  workingDirectory: cwd,
2358
1926
  streamFn,
2359
- skillsRegistry
1927
+ skillsRegistry,
1928
+ modelCatalog
2360
1929
  });
2361
1930
  registerWorker(registry, {
2362
1931
  workingDirectory: cwd,
2363
- streamFn
1932
+ streamFn,
1933
+ modelCatalog
2364
1934
  });
2365
1935
  typeNames.push(`worker`);
2366
- registerCodingSession(registry, { defaultWorkingDirectory: cwd });
2367
- typeNames.push(`coder`);
2368
1936
  const runtime = createRuntimeHandler({
2369
1937
  baseUrl: agentServerUrl,
2370
1938
  serveEndpoint,
2371
1939
  registry,
2372
1940
  subscriptionPathForType: (name) => `/${name}/*/main`,
2373
1941
  idleTimeout: 5e3,
2374
- createElectricTools
1942
+ createElectricTools,
1943
+ publicUrl,
1944
+ name: runtimeName ?? `builtin-agents`
2375
1945
  });
2376
1946
  return {
2377
1947
  handler: runtime.onEnter,
@@ -2403,10 +1973,19 @@ var BuiltinAgentsServer = class {
2403
1973
  bootstrap = null;
2404
1974
  _url = null;
2405
1975
  publicBaseUrl = null;
1976
+ _mcpRegistry = null;
1977
+ mcpWatcherCloser = null;
1978
+ mcpToolProviderName = null;
1979
+ mcpApplyInFlight = new Set();
1980
+ mcpStopping = false;
2406
1981
  options;
2407
1982
  constructor(options) {
2408
1983
  this.options = options;
2409
1984
  }
1985
+ /** Embedded MCP registry. `null` until `start()` has run. */
1986
+ get mcpRegistry() {
1987
+ return this._mcpRegistry;
1988
+ }
2410
1989
  get url() {
2411
1990
  if (!this._url) throw new Error(`Builtin agents server not started`);
2412
1991
  return this._url;
@@ -2440,14 +2019,124 @@ var BuiltinAgentsServer = class {
2440
2019
  this.publicBaseUrl = this.options.baseUrl ?? this._url;
2441
2020
  const webhookPath = this.options.webhookPath ?? DEFAULT_BUILTIN_AGENT_HANDLER_PATH;
2442
2021
  const serveEndpoint = new URL(webhookPath, this.publicBaseUrl.endsWith(`/`) ? this.publicBaseUrl : `${this.publicBaseUrl}/`).toString();
2022
+ const publicUrl = this.options.mcpOAuthRedirectBase ?? this.publicBaseUrl;
2023
+ const mcpRegistry = createRegistry({
2024
+ publicUrl,
2025
+ openAuthorizeUrl: this.options.openAuthorizeUrl
2026
+ });
2027
+ this._mcpRegistry = mcpRegistry;
2028
+ const mcpConfigPath = this.options.loadProjectMcpConfig ? path.resolve(this.options.workingDirectory ?? process.cwd(), `mcp.json`) : null;
2029
+ const extras = this.options.extraMcpServers ?? [];
2030
+ const wirePersistence = async (cfg) => {
2031
+ const servers = [];
2032
+ for (const s of cfg.servers) if (s.transport === `http` && s.auth?.mode === `authorizationCode`) {
2033
+ const persist = await keychainPersistence({ server: s.name });
2034
+ servers.push({
2035
+ ...s,
2036
+ auth: {
2037
+ ...s.auth,
2038
+ ...persist
2039
+ }
2040
+ });
2041
+ } else servers.push(s);
2042
+ return {
2043
+ ...cfg,
2044
+ servers
2045
+ };
2046
+ };
2047
+ const merge = (jsonCfg) => {
2048
+ const jsonServers = jsonCfg?.servers ?? [];
2049
+ const jsonNames = new Set(jsonServers.map((s) => s.name));
2050
+ const filteredExtras = extras.filter((s) => !jsonNames.has(s.name));
2051
+ return {
2052
+ servers: [...filteredExtras, ...jsonServers],
2053
+ raw: jsonCfg?.raw
2054
+ };
2055
+ };
2056
+ const onConfigError = this.options.onConfigError;
2057
+ const runApply = async (jsonCfg) => {
2058
+ if (this.mcpStopping) return;
2059
+ try {
2060
+ const wired = await wirePersistence(merge(jsonCfg));
2061
+ if (this.mcpStopping) return;
2062
+ await mcpRegistry.applyConfig(wired);
2063
+ } catch (e) {
2064
+ serverLog.error(`[mcp] applyConfig:`, e);
2065
+ try {
2066
+ onConfigError?.(e);
2067
+ } catch (cbErr) {
2068
+ serverLog.error(`[mcp] onConfigError callback failed:`, cbErr);
2069
+ }
2070
+ }
2071
+ };
2072
+ const applyMerged = (jsonCfg) => {
2073
+ const p = runApply(jsonCfg);
2074
+ this.mcpApplyInFlight.add(p);
2075
+ p.finally(() => this.mcpApplyInFlight.delete(p));
2076
+ return p;
2077
+ };
2078
+ if (mcpConfigPath) {
2079
+ try {
2080
+ const cfg = await loadConfig(mcpConfigPath, process.env);
2081
+ applyMerged(cfg);
2082
+ } catch (err) {
2083
+ if (err.code !== `ENOENT`) throw err;
2084
+ if (extras.length === 0) serverLog.info(`[mcp] no ${mcpConfigPath} — starting with no servers`);
2085
+ else serverLog.info(`[mcp] no ${mcpConfigPath} — starting with ${extras.length} server(s) from extras`);
2086
+ applyMerged(null);
2087
+ }
2088
+ try {
2089
+ this.mcpWatcherCloser = await watchConfig(mcpConfigPath, {
2090
+ onChange: (cfg) => void applyMerged(cfg),
2091
+ onError: (e) => serverLog.error(`[mcp] config error:`, e)
2092
+ });
2093
+ } catch (e) {
2094
+ serverLog.error(`[mcp] config watcher failed to start:`, e);
2095
+ }
2096
+ } else {
2097
+ if (extras.length > 0) serverLog.info(`[mcp] starting with ${extras.length} server(s) from extras`);
2098
+ applyMerged(null);
2099
+ }
2100
+ this.mcpToolProviderName = `mcp`;
2101
+ registerToolProvider({
2102
+ name: `mcp`,
2103
+ tools: () => {
2104
+ const tools = [];
2105
+ for (const entry of mcpRegistry.list()) {
2106
+ if (entry.status !== `ready`) continue;
2107
+ const live = mcpRegistry.get(entry.name);
2108
+ if (!live?.transport) continue;
2109
+ for (const t of entry.tools) tools.push(bridgeMcpTool({
2110
+ server: entry.name,
2111
+ tool: t,
2112
+ client: live.transport.client,
2113
+ timeoutMs: live.config.timeoutMs
2114
+ }));
2115
+ const caps = live.transport.client.getServerCapabilities?.();
2116
+ if (caps?.resources) tools.push(...buildResourceTools({
2117
+ server: entry.name,
2118
+ client: live.transport.client,
2119
+ timeoutMs: live.config.timeoutMs
2120
+ }));
2121
+ if (caps?.prompts) tools.push(...buildPromptTools({
2122
+ server: entry.name,
2123
+ client: live.transport.client,
2124
+ timeoutMs: live.config.timeoutMs
2125
+ }));
2126
+ }
2127
+ return tools;
2128
+ }
2129
+ });
2443
2130
  this.bootstrap = await createBuiltinAgentHandler({
2444
2131
  agentServerUrl: this.options.agentServerUrl,
2445
2132
  serveEndpoint,
2446
2133
  workingDirectory: this.options.workingDirectory,
2447
2134
  streamFn: this.options.mockStreamFn,
2448
- createElectricTools: this.options.createElectricTools
2135
+ createElectricTools: this.options.createElectricTools,
2136
+ publicUrl,
2137
+ runtimeName: `builtin-agents`
2449
2138
  });
2450
- if (!this.bootstrap) throw new Error(`ANTHROPIC_API_KEY must be set before starting builtin agents`);
2139
+ if (!this.bootstrap) throw new Error(`ANTHROPIC_API_KEY or OPENAI_API_KEY must be set before starting builtin agents`);
2451
2140
  await registerBuiltinAgentTypes(this.bootstrap);
2452
2141
  serverLog.info(`[builtin-agents] webhook handler listening at ${serveEndpoint}`);
2453
2142
  resolve(this._url);
@@ -2464,6 +2153,26 @@ var BuiltinAgentsServer = class {
2464
2153
  await Promise.race([this.bootstrap.runtime.drainWakes().catch(() => {}), new Promise((resolve) => setTimeout(resolve, 5e3))]);
2465
2154
  this.bootstrap = null;
2466
2155
  }
2156
+ this.mcpStopping = true;
2157
+ if (this.mcpWatcherCloser) {
2158
+ try {
2159
+ this.mcpWatcherCloser();
2160
+ } catch (e) {
2161
+ serverLog.error(`[mcp] watcher close failed:`, e);
2162
+ }
2163
+ this.mcpWatcherCloser = null;
2164
+ }
2165
+ if (this.mcpApplyInFlight.size > 0) await Promise.allSettled([...this.mcpApplyInFlight]);
2166
+ if (this.mcpToolProviderName) {
2167
+ unregisterToolProvider(this.mcpToolProviderName);
2168
+ this.mcpToolProviderName = null;
2169
+ }
2170
+ if (this._mcpRegistry) {
2171
+ await this._mcpRegistry.close().catch((e) => {
2172
+ serverLog.error(`[mcp] registry close failed:`, e);
2173
+ });
2174
+ this._mcpRegistry = null;
2175
+ }
2467
2176
  if (this.server) {
2468
2177
  const server = this.server;
2469
2178
  await new Promise((resolve) => {
@@ -2471,19 +2180,20 @@ var BuiltinAgentsServer = class {
2471
2180
  });
2472
2181
  this.server = null;
2473
2182
  }
2183
+ this.mcpStopping = false;
2474
2184
  this._url = null;
2475
2185
  this.publicBaseUrl = null;
2476
2186
  }
2477
2187
  async handleRequest(req, res) {
2478
2188
  const method = req.method?.toUpperCase();
2479
- const path$1 = new URL(req.url ?? `/`, `http://localhost`).pathname;
2189
+ const pathname = new URL(req.url ?? `/`, `http://localhost`).pathname;
2480
2190
  const webhookPath = this.options.webhookPath ?? DEFAULT_BUILTIN_AGENT_HANDLER_PATH;
2481
- if (path$1 === `/_electric/health` && method === `GET`) {
2191
+ if (pathname === `/_electric/health` && method === `GET`) {
2482
2192
  res.writeHead(200, { "content-type": `application/json` });
2483
2193
  res.end(JSON.stringify({ status: `ok` }));
2484
2194
  return;
2485
2195
  }
2486
- if (path$1 === webhookPath && method === `POST` && this.bootstrap) {
2196
+ if (pathname === webhookPath && method === `POST` && this.bootstrap) {
2487
2197
  await this.bootstrap.handler(req, res);
2488
2198
  return;
2489
2199
  }
@@ -2546,4 +2256,4 @@ async function runBuiltinAgentsEntrypoint({ env = process.env, cwd = process.cwd
2546
2256
  }
2547
2257
 
2548
2258
  //#endregion
2549
- export { BuiltinAgentsServer, DEFAULT_BUILTIN_AGENT_HANDLER_PATH, HORTON_MODEL, WORKER_TOOL_NAMES, braveSearchTool, buildHortonSystemPrompt, createAgentHandler, createBuiltinAgentHandler, createHortonDocsSupport, createHortonTools, createSpawnWorkerTool, generateTitle, registerAgentTypes, registerBuiltinAgentTypes, registerCodingSession, registerHorton, registerWorker, resolveBuiltinAgentsEntrypointOptions, runBuiltinAgentsEntrypoint };
2259
+ export { BuiltinAgentsServer, DEFAULT_BUILTIN_AGENT_HANDLER_PATH, HORTON_MODEL, WORKER_TOOL_NAMES, braveSearchTool, buildHortonSystemPrompt, createAgentHandler, createBuiltinAgentHandler, createHortonDocsSupport, createHortonTools, createSpawnWorkerTool, generateTitle, registerAgentTypes, registerBuiltinAgentTypes, registerHorton, registerWorker, resolveBuiltinAgentsEntrypointOptions, runBuiltinAgentsEntrypoint };