@electric-ax/agents 0.1.5 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/entrypoint.js +653 -408
  2. package/dist/index.cjs +671 -419
  3. package/dist/index.d.cts +36 -3
  4. package/dist/index.d.ts +36 -3
  5. package/dist/index.js +656 -411
  6. package/docs/entities/agents/horton.md +89 -0
  7. package/docs/entities/agents/worker.md +102 -0
  8. package/docs/entities/patterns/blackboard.md +111 -0
  9. package/docs/entities/patterns/dispatcher.md +77 -0
  10. package/docs/entities/patterns/manager-worker.md +127 -0
  11. package/docs/entities/patterns/map-reduce.md +81 -0
  12. package/docs/entities/patterns/pipeline.md +101 -0
  13. package/docs/entities/patterns/reactive-observers.md +125 -0
  14. package/docs/examples/mega-draw.md +106 -0
  15. package/docs/examples/playground.md +46 -0
  16. package/docs/index.md +208 -0
  17. package/docs/quickstart.md +201 -0
  18. package/docs/reference/agent-config.md +82 -0
  19. package/docs/reference/agent-tool.md +58 -0
  20. package/docs/reference/built-in-collections.md +334 -0
  21. package/docs/reference/cli.md +238 -0
  22. package/docs/reference/entity-definition.md +57 -0
  23. package/docs/reference/entity-handle.md +63 -0
  24. package/docs/reference/entity-registry.md +73 -0
  25. package/docs/reference/handler-context.md +108 -0
  26. package/docs/reference/runtime-handler.md +136 -0
  27. package/docs/reference/shared-state-handle.md +74 -0
  28. package/docs/reference/state-collection-proxy.md +41 -0
  29. package/docs/reference/wake-event.md +132 -0
  30. package/docs/usage/app-setup.md +165 -0
  31. package/docs/usage/clients-and-react.md +191 -0
  32. package/docs/usage/configuring-the-agent.md +136 -0
  33. package/docs/usage/context-composition.md +204 -0
  34. package/docs/usage/defining-entities.md +181 -0
  35. package/docs/usage/defining-tools.md +229 -0
  36. package/docs/usage/embedded-builtins.md +180 -0
  37. package/docs/usage/managing-state.md +93 -0
  38. package/docs/usage/overview.md +284 -0
  39. package/docs/usage/programmatic-runtime-client.md +216 -0
  40. package/docs/usage/shared-state.md +169 -0
  41. package/docs/usage/spawning-and-coordinating.md +165 -0
  42. package/docs/usage/testing.md +76 -0
  43. package/docs/usage/waking-entities.md +148 -0
  44. package/docs/usage/writing-handlers.md +267 -0
  45. package/package.json +6 -9
  46. package/skills/init.md +71 -0
  47. package/skills/quickstart/scaffold/package.json +30 -0
  48. package/skills/{tutorial → quickstart}/scaffold/tsconfig.json +8 -3
  49. package/skills/quickstart/scaffold/vite.config.ts +21 -0
  50. package/skills/quickstart/scaffold-ui/index.html +12 -0
  51. package/skills/quickstart/scaffold-ui/main.tsx +235 -0
  52. package/skills/quickstart.md +582 -0
  53. package/skills/tutorial/scaffold/package.json +0 -17
  54. package/skills/tutorial.md +0 -282
  55. /package/skills/{tutorial → quickstart}/scaffold/entities/.gitkeep +0 -0
  56. /package/skills/{tutorial → quickstart}/scaffold/lib/electric-tools.ts +0 -0
  57. /package/skills/{tutorial → quickstart}/scaffold/server.ts +0 -0
package/dist/index.js CHANGED
@@ -1,20 +1,20 @@
1
- import path, { dirname, relative, resolve } from "node:path";
1
+ import path from "node:path";
2
2
  import { fileURLToPath } from "node:url";
3
- import { createEntityRegistry, createRuntimeHandler, db } from "@electric-ax/agents-runtime";
4
- import fsSync from "node:fs";
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";
5
5
  import pino from "pino";
6
+ import { spawn } from "node:child_process";
7
+ import { homedir } from "node:os";
8
+ import { z } from "zod";
9
+ import { deserializeCursor, discoverSessions, importLocalSession, loadSession, resolveSession, serializeCursor, tailSession } from "agent-session-protocol";
6
10
  import Anthropic from "@anthropic-ai/sdk";
7
11
  import { createHash } from "node:crypto";
8
- import fs, { mkdir, readFile, stat, writeFile } from "node:fs/promises";
12
+ import fs from "node:fs/promises";
9
13
  import Database from "better-sqlite3";
10
14
  import { Type } from "@sinclair/typebox";
11
15
  import { load } from "sqlite-vec";
12
- import { exec } from "node:child_process";
13
- import { createRequire } from "node:module";
14
- import { Readability } from "@mozilla/readability";
15
- import { JSDOM, VirtualConsole } from "jsdom";
16
- import TurndownService from "turndown";
17
16
  import { nanoid } from "nanoid";
17
+ import { braveSearchTool, braveSearchTool as braveSearchTool$1, createBashTool, createEditTool, createReadFileTool, createWriteTool, fetchUrlTool } from "@electric-ax/agents-runtime/tools";
18
18
  import { createServer } from "node:http";
19
19
 
20
20
  //#region src/log.ts
@@ -66,6 +66,516 @@ const serverLog = {
66
66
  }
67
67
  };
68
68
 
69
+ //#endregion
70
+ //#region src/agents/coding-session.ts
71
+ const defaultCliRunner = { async run(opts) {
72
+ return new Promise((resolve, reject) => {
73
+ const isClaude = opts.agent === `claude`;
74
+ const bin = isClaude ? `claude` : `codex`;
75
+ const args = isClaude ? opts.sessionId ? [
76
+ `-r`,
77
+ opts.sessionId,
78
+ `--dangerously-skip-permissions`,
79
+ `-p`
80
+ ] : [`--dangerously-skip-permissions`, `-p`] : opts.sessionId ? [
81
+ `exec`,
82
+ `--skip-git-repo-check`,
83
+ `resume`,
84
+ opts.sessionId,
85
+ opts.prompt
86
+ ] : [
87
+ `exec`,
88
+ `--skip-git-repo-check`,
89
+ opts.prompt
90
+ ];
91
+ const child = spawn(bin, args, {
92
+ cwd: opts.cwd,
93
+ stdio: [
94
+ isClaude ? `pipe` : `ignore`,
95
+ `pipe`,
96
+ `pipe`
97
+ ]
98
+ });
99
+ const MAX_BUF_CHARS = 4096;
100
+ let stdout = ``;
101
+ let stderr = ``;
102
+ child.stdout?.on(`data`, (d) => {
103
+ if (stdout.length < MAX_BUF_CHARS) stdout += d.toString().slice(0, MAX_BUF_CHARS - stdout.length);
104
+ });
105
+ child.stderr?.on(`data`, (d) => {
106
+ if (stderr.length < MAX_BUF_CHARS) stderr += d.toString().slice(0, MAX_BUF_CHARS - stderr.length);
107
+ });
108
+ child.on(`error`, reject);
109
+ child.on(`exit`, (code) => {
110
+ resolve({
111
+ exitCode: code ?? -1,
112
+ stdout,
113
+ stderr
114
+ });
115
+ });
116
+ if (isClaude && child.stdin) {
117
+ child.stdin.write(opts.prompt);
118
+ child.stdin.end();
119
+ }
120
+ });
121
+ } };
122
+ async function discoverNewestSession(agent, cwd, excludeIds) {
123
+ const all = await discoverSessions(agent);
124
+ const candidates = all.filter((s) => !excludeIds.has(s.sessionId) && (!s.cwd || s.cwd === cwd));
125
+ if (candidates.length === 0) return null;
126
+ return candidates[0].sessionId;
127
+ }
128
+ /**
129
+ * Compute the candidate directories where Claude Code stores per-cwd
130
+ * session JSONL files. Claude resolves the cwd to its realpath when
131
+ * choosing the directory name (so /tmp/foo on macOS lands under
132
+ * `-private-tmp-foo`), but the entity may have been spawned with the
133
+ * non-realpath form. Return both candidates so the caller can union
134
+ * their contents.
135
+ */
136
+ async function getClaudeProjectDirs(cwd) {
137
+ const home = homedir();
138
+ const make = (c) => path.join(home, `.claude`, `projects`, c.replace(/\//g, `-`));
139
+ const dirs = [make(cwd)];
140
+ try {
141
+ const real = await promises.realpath(cwd);
142
+ if (real !== cwd) dirs.push(make(real));
143
+ } catch {}
144
+ return dirs;
145
+ }
146
+ async function listClaudeJsonlIdsByCwd(cwd) {
147
+ const ids = new Set();
148
+ for (const dir of await getClaudeProjectDirs(cwd)) try {
149
+ const files = await promises.readdir(dir);
150
+ for (const f of files) if (f.endsWith(`.jsonl`)) ids.add(f.slice(0, -`.jsonl`.length));
151
+ } catch {}
152
+ return ids;
153
+ }
154
+ /**
155
+ * Deterministic-path discovery for a freshly created session. After the
156
+ * Claude CLI runs in `-p` mode it writes the new JSONL straight into
157
+ * `~/.claude/projects/<sanitize(cwd)>/<id>.jsonl` *without* leaving a
158
+ * `~/.claude/sessions/<pid>.json` lock file (those are interactive-only),
159
+ * so `discoverSessions` can miss it. Compute the expected dir directly
160
+ * and diff its contents against a pre-run snapshot. Returns the newest
161
+ * fresh sessionId or null. Codex falls back to discoverNewestSession.
162
+ */
163
+ async function findNewSessionAfterRun(agent, cwd, preDirectIds, preDiscoveredIds) {
164
+ if (agent === `claude`) {
165
+ const dirs = await getClaudeProjectDirs(cwd);
166
+ let best = null;
167
+ for (const dir of dirs) try {
168
+ const files = await promises.readdir(dir);
169
+ for (const f of files) {
170
+ if (!f.endsWith(`.jsonl`)) continue;
171
+ const id = f.slice(0, -`.jsonl`.length);
172
+ if (preDirectIds.has(id)) continue;
173
+ const st = await promises.stat(path.join(dir, f)).catch(() => null);
174
+ if (!st) continue;
175
+ if (!best || st.mtimeMs > best.mtime) best = {
176
+ id,
177
+ mtime: st.mtimeMs
178
+ };
179
+ }
180
+ } catch {}
181
+ if (best) return best.id;
182
+ }
183
+ return discoverNewestSession(agent, cwd, preDiscoveredIds);
184
+ }
185
+ const sessionMetaRowSchema = z.object({
186
+ key: z.literal(`current`),
187
+ electricSessionId: z.string(),
188
+ nativeSessionId: z.string().optional(),
189
+ agent: z.enum([`claude`, `codex`]),
190
+ cwd: z.string(),
191
+ status: z.enum([
192
+ `initializing`,
193
+ `idle`,
194
+ `running`,
195
+ `error`
196
+ ]),
197
+ error: z.string().optional(),
198
+ currentPromptInboxKey: z.string().optional()
199
+ });
200
+ const cursorStateRowSchema = z.object({
201
+ key: z.literal(`current`),
202
+ cursor: z.string(),
203
+ lastProcessedInboxKey: z.string().optional()
204
+ });
205
+ const eventRowSchema = z.object({
206
+ key: z.string(),
207
+ ts: z.number(),
208
+ type: z.string(),
209
+ callId: z.string().optional(),
210
+ payload: z.looseObject({})
211
+ });
212
+ const creationArgsSchema = z.object({
213
+ agent: z.enum([`claude`, `codex`]),
214
+ cwd: z.string().optional(),
215
+ nativeSessionId: z.string().optional(),
216
+ importFrom: z.object({
217
+ agent: z.enum([`claude`, `codex`]),
218
+ sessionId: z.string()
219
+ }).optional()
220
+ });
221
+ const promptMessageSchema = z.object({ text: z.string() });
222
+ /**
223
+ * Stable key for an events-collection row, derived from the event's content.
224
+ * Lets us re-insert the same event without producing duplicates — the caller
225
+ * (or the collection's uniqueness guard) uses this to de-dup across retries,
226
+ * replays, and crash recovery. Sorts chronologically by ts, then by type.
227
+ */
228
+ function eventKey(event) {
229
+ const tsPart = String(event.ts).padStart(16, `0`);
230
+ return `${tsPart}_${event.type}_${contentHashHex(event)}`;
231
+ }
232
+ function contentHashHex(event) {
233
+ const json = JSON.stringify(event);
234
+ let h = 5381;
235
+ for (let i = 0; i < json.length; i++) h = (h * 33 ^ json.charCodeAt(i)) >>> 0;
236
+ return h.toString(16).padStart(8, `0`);
237
+ }
238
+ function buildEventRow(event) {
239
+ const callId = `callId` in event && typeof event.callId === `string` ? event.callId : void 0;
240
+ return {
241
+ key: eventKey(event),
242
+ ts: event.ts,
243
+ type: event.type,
244
+ ...callId !== void 0 ? { callId } : {},
245
+ payload: event
246
+ };
247
+ }
248
+ function appendIfNew(ctx, event) {
249
+ const row = buildEventRow(event);
250
+ if (ctx.events.get(row.key) !== void 0) return;
251
+ ctx.actions.events_insert({ row });
252
+ }
253
+ /**
254
+ * Mirror every event that lands in the JSONL file while `runWork` is
255
+ * executing (i.e. while the CLI is running). Returns the advanced cursor
256
+ * and the `runWork` result once everything has settled and every append
257
+ * has been persisted to the entity's durable stream.
258
+ *
259
+ * If setup fails (e.g. the session file can't be resolved), `runWork`
260
+ * still runs — but nothing is mirrored and `setupError` is populated so
261
+ * the caller can surface the condition. If `runWork` throws, the error
262
+ * propagates after the watcher has been cleaned up.
263
+ */
264
+ async function runWithLiveMirror(opts) {
265
+ let cursor = null;
266
+ let setupError = void 0;
267
+ try {
268
+ const session = await resolveSession(opts.nativeSessionId, opts.agent);
269
+ if (opts.serializedCursor) cursor = deserializeCursor({
270
+ ...opts.serializedCursor,
271
+ path: session.path
272
+ });
273
+ else {
274
+ const initial = await loadSession({
275
+ sessionId: opts.nativeSessionId,
276
+ agent: opts.agent
277
+ });
278
+ for (const ev of initial.events) appendIfNew(opts.ctx, ev);
279
+ cursor = initial.cursor;
280
+ }
281
+ } catch (e) {
282
+ setupError = e;
283
+ }
284
+ if (!cursor) {
285
+ const result$1 = await opts.runWork();
286
+ return {
287
+ cursor: opts.serializedCursor,
288
+ setupError,
289
+ result: result$1
290
+ };
291
+ }
292
+ let activeCursor = cursor;
293
+ let busy = false;
294
+ let pending = false;
295
+ let stopped = false;
296
+ const drainOnce = async () => {
297
+ if (stopped && busy) return;
298
+ if (busy) {
299
+ pending = true;
300
+ return;
301
+ }
302
+ busy = true;
303
+ try {
304
+ const res = await tailSession({ cursor: activeCursor });
305
+ activeCursor = res.cursor;
306
+ for (const ev of res.newEvents) appendIfNew(opts.ctx, ev);
307
+ } catch {} finally {
308
+ busy = false;
309
+ if (pending && !stopped) {
310
+ pending = false;
311
+ drainOnce();
312
+ }
313
+ }
314
+ };
315
+ const fileWatcher = watch(activeCursor.path, () => {
316
+ drainOnce();
317
+ });
318
+ const pollHandle = setInterval(() => {
319
+ drainOnce();
320
+ }, 1500);
321
+ let result;
322
+ try {
323
+ result = await opts.runWork();
324
+ } finally {
325
+ stopped = true;
326
+ clearInterval(pollHandle);
327
+ fileWatcher.close();
328
+ while (busy) await new Promise((r) => setTimeout(r, 10));
329
+ try {
330
+ const final = await tailSession({ cursor: activeCursor });
331
+ activeCursor = final.cursor;
332
+ for (const ev of final.newEvents) appendIfNew(opts.ctx, ev);
333
+ } catch {}
334
+ }
335
+ return {
336
+ cursor: serializeCursor(activeCursor),
337
+ setupError,
338
+ result
339
+ };
340
+ }
341
+ function registerCodingSession(registry, options = {}) {
342
+ const runner = options.cliRunner ?? defaultCliRunner;
343
+ const defaultCwd = options.defaultWorkingDirectory ?? process.cwd();
344
+ registry.define(`coder`, {
345
+ 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.`,
346
+ creationSchema: creationArgsSchema,
347
+ inboxSchemas: { prompt: promptMessageSchema },
348
+ state: {
349
+ sessionMeta: {
350
+ schema: sessionMetaRowSchema,
351
+ type: CODING_SESSION_META_COLLECTION_TYPE,
352
+ primaryKey: `key`
353
+ },
354
+ cursorState: {
355
+ schema: cursorStateRowSchema,
356
+ type: CODING_SESSION_CURSOR_COLLECTION_TYPE,
357
+ primaryKey: `key`
358
+ },
359
+ events: {
360
+ schema: eventRowSchema,
361
+ type: CODING_SESSION_EVENT_COLLECTION_TYPE,
362
+ primaryKey: `key`
363
+ }
364
+ },
365
+ async handler(ctx, _wake) {
366
+ const existingMeta = ctx.db.collections.sessionMeta.get(`current`);
367
+ if (!existingMeta) {
368
+ const args = creationArgsSchema.parse(ctx.args);
369
+ const cwd = args.cwd ?? defaultCwd;
370
+ const electricSessionId = ctx.entityUrl.split(`/`).pop() ?? ctx.entityUrl;
371
+ let resolvedNativeId = args.nativeSessionId;
372
+ if (args.importFrom) {
373
+ const result = await importLocalSession({
374
+ source: {
375
+ sessionId: args.importFrom.sessionId,
376
+ agent: args.importFrom.agent
377
+ },
378
+ target: {
379
+ agent: args.agent,
380
+ cwd
381
+ }
382
+ });
383
+ resolvedNativeId = result.sessionId;
384
+ }
385
+ const hasNative = resolvedNativeId !== void 0;
386
+ ctx.db.actions.sessionMeta_insert({ row: {
387
+ key: `current`,
388
+ electricSessionId,
389
+ ...hasNative ? { nativeSessionId: resolvedNativeId } : {},
390
+ agent: args.agent,
391
+ cwd,
392
+ status: hasNative ? `idle` : `initializing`
393
+ } });
394
+ }
395
+ if (!ctx.db.collections.cursorState.get(`current`)) ctx.db.actions.cursorState_insert({ row: {
396
+ key: `current`,
397
+ cursor: ``
398
+ } });
399
+ const metaRow = ctx.db.collections.sessionMeta.get(`current`);
400
+ const cursorRow = ctx.db.collections.cursorState.get(`current`);
401
+ if (!metaRow || !cursorRow) throw new Error(`[coding-session] expected sessionMeta and cursorState rows to exist after init`);
402
+ if (metaRow.nativeSessionId && !cursorRow.cursor) {
403
+ const mirrorCtx = {
404
+ events: { get: (k) => ctx.db.collections.events.get(k) },
405
+ actions: { events_insert: ctx.db.actions.events_insert }
406
+ };
407
+ try {
408
+ const initial = await loadSession({
409
+ sessionId: metaRow.nativeSessionId,
410
+ agent: metaRow.agent
411
+ });
412
+ for (const ev of initial.events) appendIfNew(mirrorCtx, ev);
413
+ const serialized = serializeCursor(initial.cursor);
414
+ ctx.db.actions.cursorState_update({
415
+ key: `current`,
416
+ updater: (d) => {
417
+ d.cursor = JSON.stringify(serialized);
418
+ }
419
+ });
420
+ } catch (e) {
421
+ const message = e instanceof Error ? e.message : String(e);
422
+ ctx.db.actions.sessionMeta_update({
423
+ key: `current`,
424
+ updater: (d) => {
425
+ d.error = `initial mirror failed: ${message}`;
426
+ }
427
+ });
428
+ }
429
+ }
430
+ const inboxRows = ctx.db.collections.inbox.toArray.slice().sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
431
+ const lastKey = cursorRow.lastProcessedInboxKey ?? ``;
432
+ const pending = inboxRows.filter((m) => m.key > lastKey);
433
+ if (pending.length === 0) {
434
+ if (metaRow.status === `running` || metaRow.status === `error`) ctx.db.actions.sessionMeta_update({
435
+ key: `current`,
436
+ updater: (d) => {
437
+ d.status = `idle`;
438
+ delete d.currentPromptInboxKey;
439
+ delete d.error;
440
+ }
441
+ });
442
+ return;
443
+ }
444
+ let runningMeta = metaRow;
445
+ let runningCursor = cursorRow;
446
+ for (const inboxMsg of pending) {
447
+ const parsed = promptMessageSchema.safeParse(inboxMsg.payload);
448
+ if (!parsed.success) {
449
+ ctx.db.actions.cursorState_update({
450
+ key: `current`,
451
+ updater: (d) => {
452
+ d.lastProcessedInboxKey = inboxMsg.key;
453
+ }
454
+ });
455
+ runningCursor = {
456
+ ...runningCursor,
457
+ lastProcessedInboxKey: inboxMsg.key
458
+ };
459
+ continue;
460
+ }
461
+ const prompt = parsed.data.text;
462
+ const existingTitle = ctx.tags.title;
463
+ if (typeof existingTitle !== `string` || existingTitle.length === 0) ctx.setTag(`title`, prompt.slice(0, 80));
464
+ ctx.db.actions.sessionMeta_update({
465
+ key: `current`,
466
+ updater: (d) => {
467
+ d.status = `running`;
468
+ d.currentPromptInboxKey = inboxMsg.key;
469
+ delete d.error;
470
+ }
471
+ });
472
+ const recordedRun = ctx.recordRun();
473
+ const eventKeysBefore = new Set(ctx.db.collections.events.toArray.map((e) => e.key));
474
+ try {
475
+ const mirrorCtx = {
476
+ events: { get: (k) => ctx.db.collections.events.get(k) },
477
+ actions: { events_insert: ctx.db.actions.events_insert }
478
+ };
479
+ let nextCursorJson = runningCursor.cursor;
480
+ if (!runningMeta.nativeSessionId) {
481
+ const preDirectIds = runningMeta.agent === `claude` ? await listClaudeJsonlIdsByCwd(runningMeta.cwd) : new Set();
482
+ const preDiscoveredIds = new Set((await discoverSessions(runningMeta.agent)).map((s) => s.sessionId));
483
+ const cliResult = await runner.run({
484
+ agent: runningMeta.agent,
485
+ cwd: runningMeta.cwd,
486
+ prompt
487
+ });
488
+ 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>`}`);
489
+ const foundId = await findNewSessionAfterRun(runningMeta.agent, runningMeta.cwd, preDirectIds, preDiscoveredIds);
490
+ if (!foundId) throw new Error(`[coding-session] ${runningMeta.agent} CLI succeeded but no new session file was found`);
491
+ ctx.db.actions.sessionMeta_update({
492
+ key: `current`,
493
+ updater: (d) => {
494
+ d.nativeSessionId = foundId;
495
+ }
496
+ });
497
+ runningMeta = {
498
+ ...runningMeta,
499
+ nativeSessionId: foundId
500
+ };
501
+ const initial = await loadSession({
502
+ sessionId: foundId,
503
+ agent: runningMeta.agent
504
+ });
505
+ for (const ev of initial.events) appendIfNew(mirrorCtx, ev);
506
+ nextCursorJson = JSON.stringify(serializeCursor(initial.cursor));
507
+ } else {
508
+ const serializedCursor = runningCursor.cursor ? JSON.parse(runningCursor.cursor) : null;
509
+ const { cursor: nextSerialized, setupError, result: cliResult } = await runWithLiveMirror({
510
+ agent: runningMeta.agent,
511
+ nativeSessionId: runningMeta.nativeSessionId,
512
+ serializedCursor,
513
+ ctx: mirrorCtx,
514
+ runWork: () => runner.run({
515
+ agent: runningMeta.agent,
516
+ sessionId: runningMeta.nativeSessionId,
517
+ cwd: runningMeta.cwd,
518
+ prompt
519
+ })
520
+ });
521
+ if (setupError) throw setupError instanceof Error ? setupError : new Error(String(setupError));
522
+ 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>`}`);
523
+ const persistedCursor = nextSerialized ?? serializedCursor;
524
+ nextCursorJson = persistedCursor ? JSON.stringify(persistedCursor) : ``;
525
+ }
526
+ ctx.db.actions.cursorState_update({
527
+ key: `current`,
528
+ updater: (d) => {
529
+ d.cursor = nextCursorJson;
530
+ d.lastProcessedInboxKey = inboxMsg.key;
531
+ }
532
+ });
533
+ runningCursor = {
534
+ ...runningCursor,
535
+ cursor: nextCursorJson,
536
+ lastProcessedInboxKey: inboxMsg.key
537
+ };
538
+ for (const row of ctx.db.collections.events.toArray) {
539
+ if (eventKeysBefore.has(row.key)) continue;
540
+ if (row.type !== `assistant_message`) continue;
541
+ const text = row.payload?.text;
542
+ if (typeof text === `string` && text.length > 0) recordedRun.attachResponse(text);
543
+ }
544
+ recordedRun.end({ status: `completed` });
545
+ } catch (e) {
546
+ const message = e instanceof Error ? e.message : String(e);
547
+ recordedRun.end({
548
+ status: `failed`,
549
+ finishReason: `error`
550
+ });
551
+ ctx.db.actions.sessionMeta_update({
552
+ key: `current`,
553
+ updater: (d) => {
554
+ d.status = `error`;
555
+ d.error = message;
556
+ }
557
+ });
558
+ ctx.db.actions.cursorState_update({
559
+ key: `current`,
560
+ updater: (d) => {
561
+ d.lastProcessedInboxKey = inboxMsg.key;
562
+ }
563
+ });
564
+ throw e;
565
+ }
566
+ }
567
+ ctx.db.actions.sessionMeta_update({
568
+ key: `current`,
569
+ updater: (d) => {
570
+ d.status = `idle`;
571
+ delete d.currentPromptInboxKey;
572
+ delete d.error;
573
+ }
574
+ });
575
+ }
576
+ });
577
+ }
578
+
69
579
  //#endregion
70
580
  //#region src/docs/embed.ts
71
581
  const EMBEDDING_DIMENSIONS = 128;
@@ -285,6 +795,8 @@ function resolveDocsRoot(workingDirectory) {
285
795
  process.env.HORTON_DOCS_ROOT,
286
796
  path.resolve(workingDirectory, `electric-agents-docs/docs`),
287
797
  path.resolve(process.cwd(), `electric-agents-docs/docs`),
798
+ path.resolve(MODULE_DIR, `../docs`),
799
+ path.resolve(MODULE_DIR, `../../docs`),
288
800
  path.resolve(MODULE_DIR, `../../../../../electric-agents-docs/docs`)
289
801
  ].filter((value) => typeof value === `string`);
290
802
  for (const candidate of candidates) if (fsSync.existsSync(candidate)) return candidate;
@@ -838,319 +1350,6 @@ function listRefFiles(dir, prefix = ``) {
838
1350
  }
839
1351
  }
840
1352
 
841
- //#endregion
842
- //#region src/tools/bash.ts
843
- const TIMEOUT_MS = 3e4;
844
- const MAX_OUTPUT_CHARS = 5e4;
845
- function createBashTool(workingDirectory) {
846
- return {
847
- name: `bash`,
848
- label: `Bash`,
849
- description: `Execute a shell command and return its output. Commands run in a sandboxed working directory with a 30-second timeout.`,
850
- parameters: Type.Object({ command: Type.String({ description: `The shell command to execute` }) }),
851
- execute: async (_toolCallId, params) => {
852
- const { command } = params;
853
- return new Promise((resolve$1) => {
854
- const child = exec(command, {
855
- cwd: workingDirectory,
856
- timeout: TIMEOUT_MS,
857
- maxBuffer: 1024 * 1024,
858
- env: {
859
- ...process.env,
860
- HOME: workingDirectory
861
- }
862
- });
863
- let stdout = ``;
864
- let stderr = ``;
865
- child.stdout?.on(`data`, (data) => {
866
- stdout += data;
867
- });
868
- child.stderr?.on(`data`, (data) => {
869
- stderr += data;
870
- });
871
- child.on(`close`, (code, signal) => {
872
- const timedOut = signal === `SIGTERM`;
873
- let output = stdout;
874
- if (stderr) output += output ? `\n\nSTDERR:\n${stderr}` : stderr;
875
- if (timedOut) output += `\n\n[Command timed out after ${TIMEOUT_MS / 1e3}s]`;
876
- output = output.slice(0, MAX_OUTPUT_CHARS);
877
- resolve$1({
878
- content: [{
879
- type: `text`,
880
- text: output || `(no output)`
881
- }],
882
- details: {
883
- exitCode: code ?? 1,
884
- timedOut
885
- }
886
- });
887
- });
888
- child.on(`error`, (err) => {
889
- resolve$1({
890
- content: [{
891
- type: `text`,
892
- text: `Command failed: ${err.message}`
893
- }],
894
- details: {
895
- exitCode: 1,
896
- timedOut: false
897
- }
898
- });
899
- });
900
- });
901
- }
902
- };
903
- }
904
-
905
- //#endregion
906
- //#region src/tools/edit.ts
907
- const READ_GUARD_MESSAGE = (rel) => `File ${rel} has not been read in this session (sessions are per-wake — re-read after waking from a worker).`;
908
- function createEditTool(workingDirectory, readSet) {
909
- return {
910
- name: `edit`,
911
- label: `Edit File`,
912
- description: `Replace text in a file. The file must have been read with the read tool earlier in this session. By default the old_string must occur exactly once; set replace_all to true to replace every occurrence.`,
913
- parameters: Type.Object({
914
- path: Type.String({ description: `File path (relative to working directory)` }),
915
- old_string: Type.String({ description: `The literal text to find. Must be unique unless replace_all is true.` }),
916
- new_string: Type.String({ description: `The replacement text.` }),
917
- replace_all: Type.Optional(Type.Boolean({ description: `Replace every occurrence (default false).` }))
918
- }),
919
- execute: async (_toolCallId, params) => {
920
- const { path: filePath, old_string, new_string, replace_all } = params;
921
- try {
922
- const resolved = resolve(workingDirectory, filePath);
923
- const rel = relative(workingDirectory, resolved);
924
- if (rel.startsWith(`..`)) return {
925
- content: [{
926
- type: `text`,
927
- text: `Error: Path "${filePath}" is outside the working directory`
928
- }],
929
- details: { replacements: 0 }
930
- };
931
- if (!readSet.has(resolved)) return {
932
- content: [{
933
- type: `text`,
934
- text: READ_GUARD_MESSAGE(rel)
935
- }],
936
- details: { replacements: 0 }
937
- };
938
- const original = await readFile(resolved, `utf-8`);
939
- if (!replace_all) {
940
- const first = original.indexOf(old_string);
941
- if (first === -1) return {
942
- content: [{
943
- type: `text`,
944
- text: `Error: old_string not found in ${rel}`
945
- }],
946
- details: { replacements: 0 }
947
- };
948
- const second = original.indexOf(old_string, first + 1);
949
- if (second !== -1) {
950
- const matches = original.split(old_string).length - 1;
951
- return {
952
- content: [{
953
- type: `text`,
954
- text: `Error: found ${matches} matches for old_string in ${rel}; pass replace_all=true to replace all, or provide a more specific old_string.`
955
- }],
956
- details: { replacements: 0 }
957
- };
958
- }
959
- const updated = original.slice(0, first) + new_string + original.slice(first + old_string.length);
960
- await writeFile(resolved, updated, `utf-8`);
961
- return {
962
- content: [{
963
- type: `text`,
964
- text: `Edited ${rel}: 1 replacement`
965
- }],
966
- details: { replacements: 1 }
967
- };
968
- }
969
- const parts = original.split(old_string);
970
- const count = parts.length - 1;
971
- if (count === 0) return {
972
- content: [{
973
- type: `text`,
974
- text: `Error: old_string not found in ${rel}`
975
- }],
976
- details: { replacements: 0 }
977
- };
978
- await writeFile(resolved, parts.join(new_string), `utf-8`);
979
- return {
980
- content: [{
981
- type: `text`,
982
- text: `Edited ${rel}: ${count} occurrences replaced`
983
- }],
984
- details: { replacements: count }
985
- };
986
- } catch (err) {
987
- serverLog.warn(`[edit tool] failed to edit ${filePath}: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0);
988
- return {
989
- content: [{
990
- type: `text`,
991
- text: `Error editing file: ${err instanceof Error ? err.message : `Unknown error`}`
992
- }],
993
- details: { replacements: 0 }
994
- };
995
- }
996
- }
997
- };
998
- }
999
-
1000
- //#endregion
1001
- //#region src/tools/fetch-url.ts
1002
- const MAX_RAW_CHARS = 1e5;
1003
- const require = createRequire(import.meta.url);
1004
- const { gfm } = require(`turndown-plugin-gfm`);
1005
- function htmlToMarkdown(html, url) {
1006
- const virtualConsole = new VirtualConsole();
1007
- const dom = new JSDOM(html, {
1008
- url,
1009
- virtualConsole
1010
- });
1011
- const reader = new Readability(dom.window.document);
1012
- const article = reader.parse();
1013
- const turndown = new TurndownService({ headingStyle: `atx` });
1014
- turndown.use(gfm);
1015
- return turndown.turndown(article?.content ?? html);
1016
- }
1017
- let anthropic$1 = null;
1018
- function getClient$1() {
1019
- if (!anthropic$1) anthropic$1 = new Anthropic();
1020
- return anthropic$1;
1021
- }
1022
- async function extractWithLLM(text, prompt) {
1023
- const client = getClient$1();
1024
- const res = await client.messages.create({
1025
- model: `claude-haiku-4-5-20251001`,
1026
- max_tokens: 2048,
1027
- messages: [{
1028
- role: `user`,
1029
- content: `${prompt}\n\n<page_content>\n${text.slice(0, MAX_RAW_CHARS)}\n</page_content>`
1030
- }]
1031
- });
1032
- const block = res.content[0];
1033
- return block?.type === `text` ? block.text : ``;
1034
- }
1035
- const fetchUrlTool = {
1036
- name: `fetch_url`,
1037
- label: `Fetch URL`,
1038
- description: `Fetch a web page and extract its key content using AI. Provide a prompt describing what information you want from the page. Returns a focused extraction rather than raw HTML.`,
1039
- parameters: Type.Object({
1040
- url: Type.String({ description: `The URL to fetch` }),
1041
- prompt: Type.String({ description: `What to extract from the page, e.g. 'Extract the main article content' or 'Find the pricing information'` })
1042
- }),
1043
- execute: async (_toolCallId, params) => {
1044
- const { url, prompt } = params;
1045
- try {
1046
- const res = await fetch(url, {
1047
- headers: {
1048
- "User-Agent": `Mozilla/5.0 (compatible; DurableStreamsAgent/1.0)`,
1049
- Accept: `text/html,application/xhtml+xml,text/plain,*/*`
1050
- },
1051
- redirect: `follow`,
1052
- signal: AbortSignal.timeout(1e4)
1053
- });
1054
- if (!res.ok) return {
1055
- content: [{
1056
- type: `text`,
1057
- text: `Failed to fetch: ${res.status} ${res.statusText}`
1058
- }],
1059
- details: {
1060
- charCount: 0,
1061
- usedLLM: false
1062
- }
1063
- };
1064
- const contentType = res.headers.get(`content-type`) ?? ``;
1065
- const raw = await res.text();
1066
- const markdown = contentType.includes(`text/html`) ? htmlToMarkdown(raw, url) : raw;
1067
- const extracted = await extractWithLLM(markdown, prompt);
1068
- return {
1069
- content: [{
1070
- type: `text`,
1071
- text: extracted
1072
- }],
1073
- details: {
1074
- charCount: extracted.length,
1075
- usedLLM: true
1076
- }
1077
- };
1078
- } catch (err) {
1079
- return {
1080
- content: [{
1081
- type: `text`,
1082
- text: `Error fetching URL: ${err instanceof Error ? err.message : `Unknown error`}`
1083
- }],
1084
- details: {
1085
- charCount: 0,
1086
- usedLLM: false
1087
- }
1088
- };
1089
- }
1090
- }
1091
- };
1092
-
1093
- //#endregion
1094
- //#region src/tools/read-file.ts
1095
- const MAX_FILE_SIZE = 512 * 1024;
1096
- function createReadFileTool(workingDirectory, readSet) {
1097
- return {
1098
- name: `read`,
1099
- label: `Read File`,
1100
- description: `Read the contents of a file. Path must be relative to or within the working directory. Binary files and files over 512KB are rejected.`,
1101
- parameters: Type.Object({ path: Type.String({ description: `File path (relative to working directory)` }) }),
1102
- execute: async (_toolCallId, params) => {
1103
- const { path: filePath } = params;
1104
- try {
1105
- const resolved = resolve(workingDirectory, filePath);
1106
- const rel = relative(workingDirectory, resolved);
1107
- if (rel.startsWith(`..`)) return {
1108
- content: [{
1109
- type: `text`,
1110
- text: `Error: Path "${filePath}" is outside the working directory`
1111
- }],
1112
- details: { charCount: 0 }
1113
- };
1114
- const fileStat = await stat(resolved);
1115
- if (fileStat.size > MAX_FILE_SIZE) return {
1116
- content: [{
1117
- type: `text`,
1118
- text: `Error: File is too large (${(fileStat.size / 1024).toFixed(0)}KB > ${MAX_FILE_SIZE / 1024}KB limit)`
1119
- }],
1120
- details: { charCount: 0 }
1121
- };
1122
- const buffer = await readFile(resolved);
1123
- const sample = buffer.subarray(0, 8192);
1124
- if (sample.includes(0)) return {
1125
- content: [{
1126
- type: `text`,
1127
- text: `Error: "${filePath}" appears to be a binary file`
1128
- }],
1129
- details: { charCount: 0 }
1130
- };
1131
- const text = buffer.toString(`utf-8`);
1132
- readSet?.add(resolved);
1133
- return {
1134
- content: [{
1135
- type: `text`,
1136
- text
1137
- }],
1138
- details: { charCount: text.length }
1139
- };
1140
- } catch (err) {
1141
- serverLog.warn(`[read tool] failed to read ${filePath}: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0);
1142
- return {
1143
- content: [{
1144
- type: `text`,
1145
- text: `Error reading file: ${err instanceof Error ? err.message : `Unknown error`}`
1146
- }],
1147
- details: { charCount: 0 }
1148
- };
1149
- }
1150
- }
1151
- };
1152
- }
1153
-
1154
1353
  //#endregion
1155
1354
  //#region src/tools/spawn-worker.ts
1156
1355
  const WORKER_TOOL_NAMES = [
@@ -1226,114 +1425,117 @@ function createSpawnWorkerTool(ctx) {
1226
1425
  }
1227
1426
 
1228
1427
  //#endregion
1229
- //#region src/tools/write.ts
1230
- function createWriteTool(workingDirectory, readSet) {
1428
+ //#region src/tools/spawn-coder.ts
1429
+ const CODER_AGENT_NAMES = [`claude`, `codex`];
1430
+ function createSpawnCoderTool(ctx) {
1231
1431
  return {
1232
- name: `write`,
1233
- label: `Write File`,
1234
- description: `Create or overwrite a file. Path must be within the working directory. Parent directories are created as needed.`,
1432
+ name: `spawn_coder`,
1433
+ label: `Spawn Coder`,
1434
+ 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.`,
1235
1435
  parameters: Type.Object({
1236
- path: Type.String({ description: `File path (relative to working directory)` }),
1237
- content: Type.String({ description: `Full file contents to write` })
1436
+ 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.` }),
1437
+ 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.` })),
1438
+ 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.` }))
1238
1439
  }),
1239
1440
  execute: async (_toolCallId, params) => {
1240
- const { path: filePath, content } = params;
1441
+ const { prompt, agent, cwd } = params;
1442
+ if (typeof prompt !== `string` || prompt.length === 0) return {
1443
+ content: [{
1444
+ type: `text`,
1445
+ text: `Error: prompt is required and must be a non-empty string.`
1446
+ }],
1447
+ details: { spawned: false }
1448
+ };
1449
+ const id = nanoid(10);
1450
+ const spawnArgs = { agent: agent ?? `claude` };
1451
+ if (cwd) spawnArgs.cwd = cwd;
1241
1452
  try {
1242
- const resolved = resolve(workingDirectory, filePath);
1243
- const rel = relative(workingDirectory, resolved);
1244
- if (rel.startsWith(`..`)) return {
1245
- content: [{
1246
- type: `text`,
1247
- text: `Error: Path "${filePath}" is outside the working directory`
1248
- }],
1249
- details: { bytesWritten: 0 }
1250
- };
1251
- await mkdir(dirname(resolved), { recursive: true });
1252
- await writeFile(resolved, content, `utf-8`);
1253
- readSet?.add(resolved);
1254
- const bytesWritten = Buffer.byteLength(content, `utf-8`);
1453
+ const handle = await ctx.spawn(`coder`, id, spawnArgs, {
1454
+ initialMessage: { text: prompt },
1455
+ wake: {
1456
+ on: `runFinished`,
1457
+ includeResponse: true
1458
+ }
1459
+ });
1460
+ const coderUrl = handle.entityUrl;
1255
1461
  return {
1256
1462
  content: [{
1257
1463
  type: `text`,
1258
- text: `Wrote ${bytesWritten} bytes to ${rel}`
1464
+ 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.`
1259
1465
  }],
1260
- details: { bytesWritten }
1466
+ details: {
1467
+ spawned: true,
1468
+ coderUrl
1469
+ }
1261
1470
  };
1262
1471
  } catch (err) {
1263
- serverLog.warn(`[write tool] failed to write ${filePath}: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0);
1472
+ serverLog.warn(`[spawn_coder tool] failed to spawn coder ${id}: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0);
1264
1473
  return {
1265
1474
  content: [{
1266
1475
  type: `text`,
1267
- text: `Error writing file: ${err instanceof Error ? err.message : `Unknown error`}`
1476
+ text: `Error spawning coder: ${err instanceof Error ? err.message : `Unknown error`}`
1268
1477
  }],
1269
- details: { bytesWritten: 0 }
1478
+ details: { spawned: false }
1270
1479
  };
1271
1480
  }
1272
1481
  }
1273
1482
  };
1274
1483
  }
1275
-
1276
- //#endregion
1277
- //#region src/tools/brave-search.ts
1278
- const BRAVE_API_URL = `https://api.search.brave.com/res/v1/web/search`;
1279
- const braveSearchTool = {
1280
- name: `web_search`,
1281
- label: `Web Search`,
1282
- description: `Search the web for current information using Brave Search. Returns titles, URLs, and snippets from top results.`,
1283
- parameters: Type.Object({ query: Type.String({ description: `The search query` }) }),
1284
- execute: async (_toolCallId, params) => {
1285
- const apiKey = process.env.BRAVE_SEARCH_API_KEY;
1286
- if (!apiKey) return {
1287
- content: [{
1288
- type: `text`,
1289
- text: `Search failed: BRAVE_SEARCH_API_KEY not set`
1290
- }],
1291
- details: { resultCount: 0 }
1292
- };
1293
- const { query } = params;
1294
- try {
1295
- const url = `${BRAVE_API_URL}?q=${encodeURIComponent(query)}&count=5`;
1296
- const res = await fetch(url, { headers: { "X-Subscription-Token": apiKey } });
1297
- if (!res.ok) return {
1298
- content: [{
1299
- type: `text`,
1300
- text: `Search failed: ${res.status} ${res.statusText}`
1301
- }],
1302
- details: { resultCount: 0 }
1303
- };
1304
- const data = await res.json();
1305
- const results = data.web?.results ?? [];
1306
- if (results.length === 0) return {
1307
- content: [{
1308
- type: `text`,
1309
- text: `No results found for "${query}"`
1310
- }],
1311
- details: { resultCount: 0 }
1312
- };
1313
- const formatted = results.map((r, i) => `${i + 1}. **${r.title}**\n ${r.url}\n ${r.description}`).join(`\n\n`);
1314
- return {
1484
+ function createPromptCoderTool(ctx) {
1485
+ return {
1486
+ name: `prompt_coder`,
1487
+ label: `Prompt Coder`,
1488
+ 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.`,
1489
+ parameters: Type.Object({
1490
+ 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.` }),
1491
+ 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.` })
1492
+ }),
1493
+ execute: async (_toolCallId, params) => {
1494
+ const { coder_url, prompt } = params;
1495
+ if (typeof coder_url !== `string` || !coder_url.startsWith(`/coder/`)) return {
1315
1496
  content: [{
1316
1497
  type: `text`,
1317
- text: formatted
1498
+ text: `Error: coder_url must be a path like "/coder/<id>".`
1318
1499
  }],
1319
- details: { resultCount: results.length }
1500
+ details: { sent: false }
1320
1501
  };
1321
- } catch (err) {
1322
- return {
1502
+ if (typeof prompt !== `string` || prompt.length === 0) return {
1323
1503
  content: [{
1324
1504
  type: `text`,
1325
- text: `Search failed: ${err instanceof Error ? err.message : `Unknown error`}`
1505
+ text: `Error: prompt is required and must be a non-empty string.`
1326
1506
  }],
1327
- details: { resultCount: 0 }
1507
+ details: { sent: false }
1328
1508
  };
1509
+ try {
1510
+ ctx.send(coder_url, { text: prompt });
1511
+ return {
1512
+ content: [{
1513
+ type: `text`,
1514
+ text: `Prompt queued for ${coder_url}. End your turn — you'll be woken when the coder's reply lands.`
1515
+ }],
1516
+ details: {
1517
+ sent: true,
1518
+ coderUrl: coder_url
1519
+ }
1520
+ };
1521
+ } catch (err) {
1522
+ serverLog.warn(`[prompt_coder tool] failed to send to ${coder_url}: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0);
1523
+ return {
1524
+ content: [{
1525
+ type: `text`,
1526
+ text: `Error sending prompt to coder: ${err instanceof Error ? err.message : `Unknown error`}`
1527
+ }],
1528
+ details: { sent: false }
1529
+ };
1530
+ }
1329
1531
  }
1330
- }
1331
- };
1532
+ };
1533
+ }
1332
1534
 
1333
1535
  //#endregion
1334
1536
  //#region src/agents/horton.ts
1335
1537
  const TITLE_MODEL = `claude-haiku-4-5-20251001`;
1336
- const HORTON_MODEL = `claude-sonnet-4-5-20250929`;
1538
+ const HORTON_MODEL = `claude-sonnet-4-6`;
1337
1539
  let anthropic = null;
1338
1540
  function getClient() {
1339
1541
  if (!anthropic) anthropic = new Anthropic();
@@ -1436,10 +1638,10 @@ async function generateTitle(userMessage, llmCall = defaultHaikuCall) {
1436
1638
  function buildHortonSystemPrompt(workingDirectory, opts = {}) {
1437
1639
  const docsTools = opts.hasDocsSupport ? `\n- search_durable_agents_docs: hybrid search over the built-in Durable Agents docs index` : ``;
1438
1640
  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` : ``;
1439
- const docsGuidance = opts.hasDocsSupport ? `\n- You have built-in Durable Agents docs context plus a docs search tool. Use that before broad web search when the question is about this repo, Electric Agents, or Durable Agents.\n- The docs TOC and docs search results include concrete file paths under the docs tree. Use the normal read tool with those returned paths.\n- Use repo read/bash tools for non-doc files or when you need to inspect exact implementation code in the workspace.` : ``;
1641
+ 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.` : ``;
1440
1642
  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.
1441
1643
 
1442
- Some skills are user-invocable — the user can trigger them with a slash command like \`/tutorial\`. 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.
1644
+ 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.
1443
1645
 
1444
1646
  ## IMPORTANT: How to use a loaded skill
1445
1647
 
@@ -1451,8 +1653,33 @@ When you load a skill, it becomes your primary directive for that interaction. F
1451
1653
  4. **Unload when done.** Use remove_skill to free context space when the skill's workflow is complete.
1452
1654
 
1453
1655
  Do NOT load a skill and then ignore its instructions. The skill is there because it contains a tested, specific workflow. Your job is to execute it faithfully.` : ``;
1656
+ const onboardingGuidance = `\n# Onboarding
1657
+ When a user is new or asks how to get started with Electric Agents, **don't assume a single path**. Present the options and let them choose:
1658
+
1659
+ - **Learn the concepts first** → Explain what Electric Agents is, answer questions, point to docs.
1660
+ Use search_durable_agents_docs to look up answers. Only load the quickstart skill if the user explicitly asks for a hands-on guided tutorial.
1661
+
1662
+ - **Hands-on guided tutorial** → Load the quickstart skill (or tell them to type \`/quickstart\`).
1663
+ This is a step-by-step build that takes them from zero to a running app.
1664
+ Only load it when the user explicitly wants to build something hands-on.
1665
+
1666
+ - **Scaffold a new project** → Load the init skill.
1667
+ This sets up project structure and orients them in the codebase.
1668
+
1669
+ - **Have a specific question?** → Answer it directly.
1670
+ Use search_durable_agents_docs first, then fall back to fetch_url or general knowledge if needed.
1671
+
1672
+ Don't force onboarding. If someone just wants to chat or code, let them. When in doubt, ask what they'd like to do rather than picking a path for them.`;
1673
+ const docsUrlGuidance = opts.docsUrl ? `\n# Electric Agents documentation
1674
+ - ${opts.hasDocsSupport ? `If search_durable_agents_docs is available, use it first (faster, hybrid search).` : `Use fetch_url to look up documentation pages.`}
1675
+ - The Electric Agents docs site is at ${opts.docsUrl}
1676
+ - 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).
1677
+ - For general coding questions unrelated to Electric Agents, use brave_search or your own knowledge.` : ``;
1454
1678
  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.
1455
1679
 
1680
+ # Greetings
1681
+ When a user opens with a greeting ("hi", "hello", "hey", etc.) or a broad statement like "I want to learn about Electric Agents", respond warmly and introduce yourself. Briefly explain what you can help with and ask what they'd like to do — don't jump straight into a skill or workflow. Let the user tell you what they need before you start loading skills or running tools.
1682
+
1456
1683
  # Tools
1457
1684
  - bash: run shell commands
1458
1685
  - read: read a file
@@ -1461,13 +1688,15 @@ Do NOT load a skill and then ignore its instructions. The skill is there because
1461
1688
  - brave_search: search the web
1462
1689
  - fetch_url: fetch and convert a URL to markdown
1463
1690
  - spawn_worker: dispatch a subagent for an isolated task
1691
+ - spawn_coder: spawn a long-lived coding agent (Claude Code or Codex CLI) for code changes, file edits, debugging
1692
+ - prompt_coder: send a follow-up prompt to a coder you previously spawned
1464
1693
  ${docsTools}${skillsTools}
1465
1694
 
1466
1695
  # Working with files
1467
1696
  - Prefer edit over write when modifying existing files.
1468
1697
  - You must read a file before you can edit it.
1469
1698
  - Use absolute paths or paths relative to the current working directory.
1470
- ${docsGuidance}${skillsGuidance}
1699
+ ${docsGuidance}${skillsGuidance}${onboardingGuidance}${docsUrlGuidance}
1471
1700
 
1472
1701
  # Risky actions
1473
1702
  Pause and confirm with the user before:
@@ -1488,6 +1717,13 @@ When you spawn a worker, write its system prompt the way you'd brief a colleague
1488
1717
 
1489
1718
  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.
1490
1719
 
1720
+ # When to spawn a coder
1721
+ 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.
1722
+
1723
+ 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.
1724
+
1725
+ 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.
1726
+
1491
1727
  # Reporting
1492
1728
  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.
1493
1729
 
@@ -1500,9 +1736,11 @@ function createHortonTools(workingDirectory, ctx, readSet, opts = {}) {
1500
1736
  createReadFileTool(workingDirectory, readSet),
1501
1737
  createWriteTool(workingDirectory, readSet),
1502
1738
  createEditTool(workingDirectory, readSet),
1503
- braveSearchTool,
1739
+ braveSearchTool$1,
1504
1740
  fetchUrlTool,
1505
1741
  createSpawnWorkerTool(ctx),
1742
+ createSpawnCoderTool(ctx),
1743
+ createPromptCoderTool(ctx),
1506
1744
  ...opts.docsSearchTool ? [opts.docsSearchTool] : []
1507
1745
  ];
1508
1746
  }
@@ -1518,7 +1756,7 @@ function extractFirstUserMessage(events) {
1518
1756
  return null;
1519
1757
  }
1520
1758
  function createAssistantHandler(options) {
1521
- const { workingDirectory, streamFn, docsSupport, docsSearchTool, skillsRegistry } = options;
1759
+ const { workingDirectory, streamFn, docsSupport, docsSearchTool, skillsRegistry, docsUrl } = options;
1522
1760
  const hasSkills = Boolean(skillsRegistry && skillsRegistry.catalog.size > 0);
1523
1761
  return async function assistantHandler(ctx, wake) {
1524
1762
  const readSet = new Set();
@@ -1568,7 +1806,8 @@ function createAssistantHandler(options) {
1568
1806
  ctx.useAgent({
1569
1807
  systemPrompt: buildHortonSystemPrompt(workingDirectory, {
1570
1808
  hasDocsSupport: Boolean(docsSupport),
1571
- hasSkills
1809
+ hasSkills,
1810
+ docsUrl
1572
1811
  }),
1573
1812
  model: HORTON_MODEL,
1574
1813
  tools,
@@ -1596,6 +1835,9 @@ function createAssistantHandler(options) {
1596
1835
  }
1597
1836
  function registerHorton(registry, options) {
1598
1837
  const { workingDirectory, streamFn, skillsRegistry = null } = options;
1838
+ const docsUrl = options.docsUrl ?? process.env.HORTON_DOCS_URL;
1839
+ if (process.env.BRAVE_SEARCH_API_KEY) serverLog.info(`[horton] Web search: using Brave Search API`);
1840
+ 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)`);
1599
1841
  const docsSupport = createHortonDocsSupport(workingDirectory);
1600
1842
  const docsSearchTool = docsSupport?.createSearchTool();
1601
1843
  docsSupport?.ensureReady().catch((error) => {
@@ -1606,7 +1848,8 @@ function registerHorton(registry, options) {
1606
1848
  streamFn,
1607
1849
  docsSupport,
1608
1850
  docsSearchTool,
1609
- skillsRegistry
1851
+ skillsRegistry,
1852
+ docsUrl
1610
1853
  });
1611
1854
  registry.define(`horton`, {
1612
1855
  description: `Friendly capable assistant — chat, code, research, dispatch`,
@@ -1672,7 +1915,7 @@ function buildToolsForWorker(tools, workingDirectory, ctx, readSet) {
1672
1915
  out.push(createEditTool(workingDirectory, readSet));
1673
1916
  break;
1674
1917
  case `brave_search`:
1675
- out.push(braveSearchTool);
1918
+ out.push(braveSearchTool$1);
1676
1919
  break;
1677
1920
  case `fetch_url`:
1678
1921
  out.push(fetchUrlTool);
@@ -2092,6 +2335,8 @@ async function createBuiltinAgentHandler(options) {
2092
2335
  streamFn
2093
2336
  });
2094
2337
  typeNames.push(`worker`);
2338
+ registerCodingSession(registry, { defaultWorkingDirectory: cwd });
2339
+ typeNames.push(`coder`);
2095
2340
  const runtime = createRuntimeHandler({
2096
2341
  baseUrl: agentServerUrl,
2097
2342
  serveEndpoint,
@@ -2144,7 +2389,7 @@ var BuiltinAgentsServer = class {
2144
2389
  }
2145
2390
  async start() {
2146
2391
  if (this.server) throw new Error(`Builtin agents server already started`);
2147
- return new Promise((resolve$1, reject) => {
2392
+ return new Promise((resolve, reject) => {
2148
2393
  this.server = createServer((req, res) => {
2149
2394
  this.handleRequest(req, res).catch((error) => {
2150
2395
  serverLog.error(`[builtin-agents] unhandled request error`, error);
@@ -2177,7 +2422,7 @@ var BuiltinAgentsServer = class {
2177
2422
  if (!this.bootstrap) throw new Error(`ANTHROPIC_API_KEY must be set before starting builtin agents`);
2178
2423
  await registerBuiltinAgentTypes(this.bootstrap);
2179
2424
  serverLog.info(`[builtin-agents] webhook handler listening at ${serveEndpoint}`);
2180
- resolve$1(this._url);
2425
+ resolve(this._url);
2181
2426
  } catch (error) {
2182
2427
  await this.stop().catch(() => {});
2183
2428
  reject(error);
@@ -2188,13 +2433,13 @@ var BuiltinAgentsServer = class {
2188
2433
  async stop() {
2189
2434
  if (this.bootstrap) {
2190
2435
  this.bootstrap.runtime.abortWakes();
2191
- await Promise.race([this.bootstrap.runtime.drainWakes().catch(() => {}), new Promise((resolve$1) => setTimeout(resolve$1, 5e3))]);
2436
+ await Promise.race([this.bootstrap.runtime.drainWakes().catch(() => {}), new Promise((resolve) => setTimeout(resolve, 5e3))]);
2192
2437
  this.bootstrap = null;
2193
2438
  }
2194
2439
  if (this.server) {
2195
2440
  const server = this.server;
2196
- await new Promise((resolve$1) => {
2197
- server.close(() => resolve$1());
2441
+ await new Promise((resolve) => {
2442
+ server.close(() => resolve());
2198
2443
  });
2199
2444
  this.server = null;
2200
2445
  }
@@ -2273,4 +2518,4 @@ async function runBuiltinAgentsEntrypoint({ env = process.env, cwd = process.cwd
2273
2518
  }
2274
2519
 
2275
2520
  //#endregion
2276
- export { BuiltinAgentsServer, DEFAULT_BUILTIN_AGENT_HANDLER_PATH, HORTON_MODEL, WORKER_TOOL_NAMES, buildHortonSystemPrompt, createAgentHandler, createBuiltinAgentHandler, createHortonDocsSupport, createHortonTools, createSpawnWorkerTool, generateTitle, registerAgentTypes, registerBuiltinAgentTypes, registerHorton, registerWorker, resolveBuiltinAgentsEntrypointOptions, runBuiltinAgentsEntrypoint };
2521
+ 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 };