@electric-ax/agents 0.1.5 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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;
@@ -838,319 +1348,6 @@ function listRefFiles(dir, prefix = ``) {
838
1348
  }
839
1349
  }
840
1350
 
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
1351
  //#endregion
1155
1352
  //#region src/tools/spawn-worker.ts
1156
1353
  const WORKER_TOOL_NAMES = [
@@ -1226,114 +1423,117 @@ function createSpawnWorkerTool(ctx) {
1226
1423
  }
1227
1424
 
1228
1425
  //#endregion
1229
- //#region src/tools/write.ts
1230
- function createWriteTool(workingDirectory, readSet) {
1426
+ //#region src/tools/spawn-coder.ts
1427
+ const CODER_AGENT_NAMES = [`claude`, `codex`];
1428
+ function createSpawnCoderTool(ctx) {
1231
1429
  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.`,
1430
+ name: `spawn_coder`,
1431
+ label: `Spawn Coder`,
1432
+ 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
1433
  parameters: Type.Object({
1236
- path: Type.String({ description: `File path (relative to working directory)` }),
1237
- content: Type.String({ description: `Full file contents to write` })
1434
+ 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.` }),
1435
+ 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.` })),
1436
+ 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
1437
  }),
1239
1438
  execute: async (_toolCallId, params) => {
1240
- const { path: filePath, content } = params;
1439
+ const { prompt, agent, cwd } = params;
1440
+ if (typeof prompt !== `string` || prompt.length === 0) return {
1441
+ content: [{
1442
+ type: `text`,
1443
+ text: `Error: prompt is required and must be a non-empty string.`
1444
+ }],
1445
+ details: { spawned: false }
1446
+ };
1447
+ const id = nanoid(10);
1448
+ const spawnArgs = { agent: agent ?? `claude` };
1449
+ if (cwd) spawnArgs.cwd = cwd;
1241
1450
  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`);
1451
+ const handle = await ctx.spawn(`coder`, id, spawnArgs, {
1452
+ initialMessage: { text: prompt },
1453
+ wake: {
1454
+ on: `runFinished`,
1455
+ includeResponse: true
1456
+ }
1457
+ });
1458
+ const coderUrl = handle.entityUrl;
1255
1459
  return {
1256
1460
  content: [{
1257
1461
  type: `text`,
1258
- text: `Wrote ${bytesWritten} bytes to ${rel}`
1462
+ 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
1463
  }],
1260
- details: { bytesWritten }
1464
+ details: {
1465
+ spawned: true,
1466
+ coderUrl
1467
+ }
1261
1468
  };
1262
1469
  } catch (err) {
1263
- serverLog.warn(`[write tool] failed to write ${filePath}: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0);
1470
+ serverLog.warn(`[spawn_coder tool] failed to spawn coder ${id}: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0);
1264
1471
  return {
1265
1472
  content: [{
1266
1473
  type: `text`,
1267
- text: `Error writing file: ${err instanceof Error ? err.message : `Unknown error`}`
1474
+ text: `Error spawning coder: ${err instanceof Error ? err.message : `Unknown error`}`
1268
1475
  }],
1269
- details: { bytesWritten: 0 }
1476
+ details: { spawned: false }
1270
1477
  };
1271
1478
  }
1272
1479
  }
1273
1480
  };
1274
1481
  }
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 {
1482
+ function createPromptCoderTool(ctx) {
1483
+ return {
1484
+ name: `prompt_coder`,
1485
+ label: `Prompt Coder`,
1486
+ 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.`,
1487
+ parameters: Type.Object({
1488
+ 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.` }),
1489
+ 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.` })
1490
+ }),
1491
+ execute: async (_toolCallId, params) => {
1492
+ const { coder_url, prompt } = params;
1493
+ if (typeof coder_url !== `string` || !coder_url.startsWith(`/coder/`)) return {
1315
1494
  content: [{
1316
1495
  type: `text`,
1317
- text: formatted
1496
+ text: `Error: coder_url must be a path like "/coder/<id>".`
1318
1497
  }],
1319
- details: { resultCount: results.length }
1498
+ details: { sent: false }
1320
1499
  };
1321
- } catch (err) {
1322
- return {
1500
+ if (typeof prompt !== `string` || prompt.length === 0) return {
1323
1501
  content: [{
1324
1502
  type: `text`,
1325
- text: `Search failed: ${err instanceof Error ? err.message : `Unknown error`}`
1503
+ text: `Error: prompt is required and must be a non-empty string.`
1326
1504
  }],
1327
- details: { resultCount: 0 }
1505
+ details: { sent: false }
1328
1506
  };
1507
+ try {
1508
+ ctx.send(coder_url, { text: prompt });
1509
+ return {
1510
+ content: [{
1511
+ type: `text`,
1512
+ text: `Prompt queued for ${coder_url}. End your turn — you'll be woken when the coder's reply lands.`
1513
+ }],
1514
+ details: {
1515
+ sent: true,
1516
+ coderUrl: coder_url
1517
+ }
1518
+ };
1519
+ } catch (err) {
1520
+ serverLog.warn(`[prompt_coder tool] failed to send to ${coder_url}: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0);
1521
+ return {
1522
+ content: [{
1523
+ type: `text`,
1524
+ text: `Error sending prompt to coder: ${err instanceof Error ? err.message : `Unknown error`}`
1525
+ }],
1526
+ details: { sent: false }
1527
+ };
1528
+ }
1329
1529
  }
1330
- }
1331
- };
1530
+ };
1531
+ }
1332
1532
 
1333
1533
  //#endregion
1334
1534
  //#region src/agents/horton.ts
1335
1535
  const TITLE_MODEL = `claude-haiku-4-5-20251001`;
1336
- const HORTON_MODEL = `claude-sonnet-4-5-20250929`;
1536
+ const HORTON_MODEL = `claude-sonnet-4-6`;
1337
1537
  let anthropic = null;
1338
1538
  function getClient() {
1339
1539
  if (!anthropic) anthropic = new Anthropic();
@@ -1439,7 +1639,7 @@ function buildHortonSystemPrompt(workingDirectory, opts = {}) {
1439
1639
  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.` : ``;
1440
1640
  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
1641
 
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.
1642
+ 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
1643
 
1444
1644
  ## IMPORTANT: How to use a loaded skill
1445
1645
 
@@ -1451,8 +1651,33 @@ When you load a skill, it becomes your primary directive for that interaction. F
1451
1651
  4. **Unload when done.** Use remove_skill to free context space when the skill's workflow is complete.
1452
1652
 
1453
1653
  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.` : ``;
1654
+ const onboardingGuidance = `\n# Onboarding
1655
+ 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:
1656
+
1657
+ - **Learn the concepts first** → Explain what Electric Agents is, answer questions, point to docs.
1658
+ Use your docs tools or fetch_url. Only load the quickstart skill if the user explicitly asks for a hands-on guided tutorial.
1659
+
1660
+ - **Hands-on guided tutorial** → Load the quickstart skill (or tell them to type \`/quickstart\`).
1661
+ This is a step-by-step build that takes them from zero to a running app.
1662
+ Only load it when the user explicitly wants to build something hands-on.
1663
+
1664
+ - **Scaffold a new project** → Load the init skill.
1665
+ This sets up project structure and orients them in the codebase.
1666
+
1667
+ - **Have a specific question?** → Answer it directly.
1668
+ Use your docs tools, fetch_url, or general coding knowledge.
1669
+
1670
+ 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.`;
1671
+ const docsUrlGuidance = opts.docsUrl ? `\n# Electric Agents documentation
1672
+ - ${opts.hasDocsSupport ? `If search_durable_agents_docs is available, use it first (faster, hybrid search).` : `Use fetch_url to look up documentation pages.`}
1673
+ - The Electric Agents docs site is at ${opts.docsUrl}
1674
+ - 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).
1675
+ - For general coding questions unrelated to Electric Agents, use brave_search or your own knowledge.` : ``;
1454
1676
  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
1677
 
1678
+ # Greetings
1679
+ 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.
1680
+
1456
1681
  # Tools
1457
1682
  - bash: run shell commands
1458
1683
  - read: read a file
@@ -1461,13 +1686,15 @@ Do NOT load a skill and then ignore its instructions. The skill is there because
1461
1686
  - brave_search: search the web
1462
1687
  - fetch_url: fetch and convert a URL to markdown
1463
1688
  - spawn_worker: dispatch a subagent for an isolated task
1689
+ - spawn_coder: spawn a long-lived coding agent (Claude Code or Codex CLI) for code changes, file edits, debugging
1690
+ - prompt_coder: send a follow-up prompt to a coder you previously spawned
1464
1691
  ${docsTools}${skillsTools}
1465
1692
 
1466
1693
  # Working with files
1467
1694
  - Prefer edit over write when modifying existing files.
1468
1695
  - You must read a file before you can edit it.
1469
1696
  - Use absolute paths or paths relative to the current working directory.
1470
- ${docsGuidance}${skillsGuidance}
1697
+ ${docsGuidance}${skillsGuidance}${onboardingGuidance}${docsUrlGuidance}
1471
1698
 
1472
1699
  # Risky actions
1473
1700
  Pause and confirm with the user before:
@@ -1488,6 +1715,13 @@ When you spawn a worker, write its system prompt the way you'd brief a colleague
1488
1715
 
1489
1716
  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
1717
 
1718
+ # When to spawn a coder
1719
+ 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.
1720
+
1721
+ 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.
1722
+
1723
+ 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.
1724
+
1491
1725
  # Reporting
1492
1726
  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
1727
 
@@ -1500,9 +1734,11 @@ function createHortonTools(workingDirectory, ctx, readSet, opts = {}) {
1500
1734
  createReadFileTool(workingDirectory, readSet),
1501
1735
  createWriteTool(workingDirectory, readSet),
1502
1736
  createEditTool(workingDirectory, readSet),
1503
- braveSearchTool,
1737
+ braveSearchTool$1,
1504
1738
  fetchUrlTool,
1505
1739
  createSpawnWorkerTool(ctx),
1740
+ createSpawnCoderTool(ctx),
1741
+ createPromptCoderTool(ctx),
1506
1742
  ...opts.docsSearchTool ? [opts.docsSearchTool] : []
1507
1743
  ];
1508
1744
  }
@@ -1518,7 +1754,7 @@ function extractFirstUserMessage(events) {
1518
1754
  return null;
1519
1755
  }
1520
1756
  function createAssistantHandler(options) {
1521
- const { workingDirectory, streamFn, docsSupport, docsSearchTool, skillsRegistry } = options;
1757
+ const { workingDirectory, streamFn, docsSupport, docsSearchTool, skillsRegistry, docsUrl } = options;
1522
1758
  const hasSkills = Boolean(skillsRegistry && skillsRegistry.catalog.size > 0);
1523
1759
  return async function assistantHandler(ctx, wake) {
1524
1760
  const readSet = new Set();
@@ -1568,7 +1804,8 @@ function createAssistantHandler(options) {
1568
1804
  ctx.useAgent({
1569
1805
  systemPrompt: buildHortonSystemPrompt(workingDirectory, {
1570
1806
  hasDocsSupport: Boolean(docsSupport),
1571
- hasSkills
1807
+ hasSkills,
1808
+ docsUrl
1572
1809
  }),
1573
1810
  model: HORTON_MODEL,
1574
1811
  tools,
@@ -1596,6 +1833,9 @@ function createAssistantHandler(options) {
1596
1833
  }
1597
1834
  function registerHorton(registry, options) {
1598
1835
  const { workingDirectory, streamFn, skillsRegistry = null } = options;
1836
+ const docsUrl = options.docsUrl ?? process.env.HORTON_DOCS_URL;
1837
+ if (process.env.BRAVE_SEARCH_API_KEY) serverLog.info(`[horton] Web search: using Brave Search API`);
1838
+ 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
1839
  const docsSupport = createHortonDocsSupport(workingDirectory);
1600
1840
  const docsSearchTool = docsSupport?.createSearchTool();
1601
1841
  docsSupport?.ensureReady().catch((error) => {
@@ -1606,7 +1846,8 @@ function registerHorton(registry, options) {
1606
1846
  streamFn,
1607
1847
  docsSupport,
1608
1848
  docsSearchTool,
1609
- skillsRegistry
1849
+ skillsRegistry,
1850
+ docsUrl
1610
1851
  });
1611
1852
  registry.define(`horton`, {
1612
1853
  description: `Friendly capable assistant — chat, code, research, dispatch`,
@@ -1672,7 +1913,7 @@ function buildToolsForWorker(tools, workingDirectory, ctx, readSet) {
1672
1913
  out.push(createEditTool(workingDirectory, readSet));
1673
1914
  break;
1674
1915
  case `brave_search`:
1675
- out.push(braveSearchTool);
1916
+ out.push(braveSearchTool$1);
1676
1917
  break;
1677
1918
  case `fetch_url`:
1678
1919
  out.push(fetchUrlTool);
@@ -2092,6 +2333,8 @@ async function createBuiltinAgentHandler(options) {
2092
2333
  streamFn
2093
2334
  });
2094
2335
  typeNames.push(`worker`);
2336
+ registerCodingSession(registry, { defaultWorkingDirectory: cwd });
2337
+ typeNames.push(`coder`);
2095
2338
  const runtime = createRuntimeHandler({
2096
2339
  baseUrl: agentServerUrl,
2097
2340
  serveEndpoint,
@@ -2144,7 +2387,7 @@ var BuiltinAgentsServer = class {
2144
2387
  }
2145
2388
  async start() {
2146
2389
  if (this.server) throw new Error(`Builtin agents server already started`);
2147
- return new Promise((resolve$1, reject) => {
2390
+ return new Promise((resolve, reject) => {
2148
2391
  this.server = createServer((req, res) => {
2149
2392
  this.handleRequest(req, res).catch((error) => {
2150
2393
  serverLog.error(`[builtin-agents] unhandled request error`, error);
@@ -2177,7 +2420,7 @@ var BuiltinAgentsServer = class {
2177
2420
  if (!this.bootstrap) throw new Error(`ANTHROPIC_API_KEY must be set before starting builtin agents`);
2178
2421
  await registerBuiltinAgentTypes(this.bootstrap);
2179
2422
  serverLog.info(`[builtin-agents] webhook handler listening at ${serveEndpoint}`);
2180
- resolve$1(this._url);
2423
+ resolve(this._url);
2181
2424
  } catch (error) {
2182
2425
  await this.stop().catch(() => {});
2183
2426
  reject(error);
@@ -2188,13 +2431,13 @@ var BuiltinAgentsServer = class {
2188
2431
  async stop() {
2189
2432
  if (this.bootstrap) {
2190
2433
  this.bootstrap.runtime.abortWakes();
2191
- await Promise.race([this.bootstrap.runtime.drainWakes().catch(() => {}), new Promise((resolve$1) => setTimeout(resolve$1, 5e3))]);
2434
+ await Promise.race([this.bootstrap.runtime.drainWakes().catch(() => {}), new Promise((resolve) => setTimeout(resolve, 5e3))]);
2192
2435
  this.bootstrap = null;
2193
2436
  }
2194
2437
  if (this.server) {
2195
2438
  const server = this.server;
2196
- await new Promise((resolve$1) => {
2197
- server.close(() => resolve$1());
2439
+ await new Promise((resolve) => {
2440
+ server.close(() => resolve());
2198
2441
  });
2199
2442
  this.server = null;
2200
2443
  }
@@ -2273,4 +2516,4 @@ async function runBuiltinAgentsEntrypoint({ env = process.env, cwd = process.cwd
2273
2516
  }
2274
2517
 
2275
2518
  //#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 };
2519
+ 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 };