@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.
- package/dist/entrypoint.js +653 -408
- package/dist/index.cjs +671 -419
- package/dist/index.d.cts +36 -3
- package/dist/index.d.ts +36 -3
- package/dist/index.js +656 -411
- package/docs/entities/agents/horton.md +89 -0
- package/docs/entities/agents/worker.md +102 -0
- package/docs/entities/patterns/blackboard.md +111 -0
- package/docs/entities/patterns/dispatcher.md +77 -0
- package/docs/entities/patterns/manager-worker.md +127 -0
- package/docs/entities/patterns/map-reduce.md +81 -0
- package/docs/entities/patterns/pipeline.md +101 -0
- package/docs/entities/patterns/reactive-observers.md +125 -0
- package/docs/examples/mega-draw.md +106 -0
- package/docs/examples/playground.md +46 -0
- package/docs/index.md +208 -0
- package/docs/quickstart.md +201 -0
- package/docs/reference/agent-config.md +82 -0
- package/docs/reference/agent-tool.md +58 -0
- package/docs/reference/built-in-collections.md +334 -0
- package/docs/reference/cli.md +238 -0
- package/docs/reference/entity-definition.md +57 -0
- package/docs/reference/entity-handle.md +63 -0
- package/docs/reference/entity-registry.md +73 -0
- package/docs/reference/handler-context.md +108 -0
- package/docs/reference/runtime-handler.md +136 -0
- package/docs/reference/shared-state-handle.md +74 -0
- package/docs/reference/state-collection-proxy.md +41 -0
- package/docs/reference/wake-event.md +132 -0
- package/docs/usage/app-setup.md +165 -0
- package/docs/usage/clients-and-react.md +191 -0
- package/docs/usage/configuring-the-agent.md +136 -0
- package/docs/usage/context-composition.md +204 -0
- package/docs/usage/defining-entities.md +181 -0
- package/docs/usage/defining-tools.md +229 -0
- package/docs/usage/embedded-builtins.md +180 -0
- package/docs/usage/managing-state.md +93 -0
- package/docs/usage/overview.md +284 -0
- package/docs/usage/programmatic-runtime-client.md +216 -0
- package/docs/usage/shared-state.md +169 -0
- package/docs/usage/spawning-and-coordinating.md +165 -0
- package/docs/usage/testing.md +76 -0
- package/docs/usage/waking-entities.md +148 -0
- package/docs/usage/writing-handlers.md +267 -0
- package/package.json +6 -9
- package/skills/init.md +71 -0
- package/skills/quickstart/scaffold/package.json +30 -0
- package/skills/{tutorial → quickstart}/scaffold/tsconfig.json +8 -3
- package/skills/quickstart/scaffold/vite.config.ts +21 -0
- package/skills/quickstart/scaffold-ui/index.html +12 -0
- package/skills/quickstart/scaffold-ui/main.tsx +235 -0
- package/skills/quickstart.md +582 -0
- package/skills/tutorial/scaffold/package.json +0 -17
- package/skills/tutorial.md +0 -282
- /package/skills/{tutorial → quickstart}/scaffold/entities/.gitkeep +0 -0
- /package/skills/{tutorial → quickstart}/scaffold/lib/electric-tools.ts +0 -0
- /package/skills/{tutorial → quickstart}/scaffold/server.ts +0 -0
package/dist/index.cjs
CHANGED
|
@@ -27,18 +27,18 @@ const node_url = __toESM(require("node:url"));
|
|
|
27
27
|
const __electric_ax_agents_runtime = __toESM(require("@electric-ax/agents-runtime"));
|
|
28
28
|
const node_fs = __toESM(require("node:fs"));
|
|
29
29
|
const pino = __toESM(require("pino"));
|
|
30
|
+
const node_child_process = __toESM(require("node:child_process"));
|
|
31
|
+
const node_os = __toESM(require("node:os"));
|
|
32
|
+
const zod = __toESM(require("zod"));
|
|
33
|
+
const agent_session_protocol = __toESM(require("agent-session-protocol"));
|
|
30
34
|
const __anthropic_ai_sdk = __toESM(require("@anthropic-ai/sdk"));
|
|
31
35
|
const node_crypto = __toESM(require("node:crypto"));
|
|
32
36
|
const node_fs_promises = __toESM(require("node:fs/promises"));
|
|
33
37
|
const better_sqlite3 = __toESM(require("better-sqlite3"));
|
|
34
38
|
const __sinclair_typebox = __toESM(require("@sinclair/typebox"));
|
|
35
39
|
const sqlite_vec = __toESM(require("sqlite-vec"));
|
|
36
|
-
const node_child_process = __toESM(require("node:child_process"));
|
|
37
|
-
const node_module = __toESM(require("node:module"));
|
|
38
|
-
const __mozilla_readability = __toESM(require("@mozilla/readability"));
|
|
39
|
-
const jsdom = __toESM(require("jsdom"));
|
|
40
|
-
const turndown = __toESM(require("turndown"));
|
|
41
40
|
const nanoid = __toESM(require("nanoid"));
|
|
41
|
+
const __electric_ax_agents_runtime_tools = __toESM(require("@electric-ax/agents-runtime/tools"));
|
|
42
42
|
const node_http = __toESM(require("node:http"));
|
|
43
43
|
|
|
44
44
|
//#region src/log.ts
|
|
@@ -90,6 +90,516 @@ const serverLog = {
|
|
|
90
90
|
}
|
|
91
91
|
};
|
|
92
92
|
|
|
93
|
+
//#endregion
|
|
94
|
+
//#region src/agents/coding-session.ts
|
|
95
|
+
const defaultCliRunner = { async run(opts) {
|
|
96
|
+
return new Promise((resolve, reject) => {
|
|
97
|
+
const isClaude = opts.agent === `claude`;
|
|
98
|
+
const bin = isClaude ? `claude` : `codex`;
|
|
99
|
+
const args = isClaude ? opts.sessionId ? [
|
|
100
|
+
`-r`,
|
|
101
|
+
opts.sessionId,
|
|
102
|
+
`--dangerously-skip-permissions`,
|
|
103
|
+
`-p`
|
|
104
|
+
] : [`--dangerously-skip-permissions`, `-p`] : opts.sessionId ? [
|
|
105
|
+
`exec`,
|
|
106
|
+
`--skip-git-repo-check`,
|
|
107
|
+
`resume`,
|
|
108
|
+
opts.sessionId,
|
|
109
|
+
opts.prompt
|
|
110
|
+
] : [
|
|
111
|
+
`exec`,
|
|
112
|
+
`--skip-git-repo-check`,
|
|
113
|
+
opts.prompt
|
|
114
|
+
];
|
|
115
|
+
const child = (0, node_child_process.spawn)(bin, args, {
|
|
116
|
+
cwd: opts.cwd,
|
|
117
|
+
stdio: [
|
|
118
|
+
isClaude ? `pipe` : `ignore`,
|
|
119
|
+
`pipe`,
|
|
120
|
+
`pipe`
|
|
121
|
+
]
|
|
122
|
+
});
|
|
123
|
+
const MAX_BUF_CHARS = 4096;
|
|
124
|
+
let stdout = ``;
|
|
125
|
+
let stderr = ``;
|
|
126
|
+
child.stdout?.on(`data`, (d) => {
|
|
127
|
+
if (stdout.length < MAX_BUF_CHARS) stdout += d.toString().slice(0, MAX_BUF_CHARS - stdout.length);
|
|
128
|
+
});
|
|
129
|
+
child.stderr?.on(`data`, (d) => {
|
|
130
|
+
if (stderr.length < MAX_BUF_CHARS) stderr += d.toString().slice(0, MAX_BUF_CHARS - stderr.length);
|
|
131
|
+
});
|
|
132
|
+
child.on(`error`, reject);
|
|
133
|
+
child.on(`exit`, (code) => {
|
|
134
|
+
resolve({
|
|
135
|
+
exitCode: code ?? -1,
|
|
136
|
+
stdout,
|
|
137
|
+
stderr
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
if (isClaude && child.stdin) {
|
|
141
|
+
child.stdin.write(opts.prompt);
|
|
142
|
+
child.stdin.end();
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
} };
|
|
146
|
+
async function discoverNewestSession(agent, cwd, excludeIds) {
|
|
147
|
+
const all = await (0, agent_session_protocol.discoverSessions)(agent);
|
|
148
|
+
const candidates = all.filter((s) => !excludeIds.has(s.sessionId) && (!s.cwd || s.cwd === cwd));
|
|
149
|
+
if (candidates.length === 0) return null;
|
|
150
|
+
return candidates[0].sessionId;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Compute the candidate directories where Claude Code stores per-cwd
|
|
154
|
+
* session JSONL files. Claude resolves the cwd to its realpath when
|
|
155
|
+
* choosing the directory name (so /tmp/foo on macOS lands under
|
|
156
|
+
* `-private-tmp-foo`), but the entity may have been spawned with the
|
|
157
|
+
* non-realpath form. Return both candidates so the caller can union
|
|
158
|
+
* their contents.
|
|
159
|
+
*/
|
|
160
|
+
async function getClaudeProjectDirs(cwd) {
|
|
161
|
+
const home = (0, node_os.homedir)();
|
|
162
|
+
const make = (c) => node_path.default.join(home, `.claude`, `projects`, c.replace(/\//g, `-`));
|
|
163
|
+
const dirs = [make(cwd)];
|
|
164
|
+
try {
|
|
165
|
+
const real = await node_fs.promises.realpath(cwd);
|
|
166
|
+
if (real !== cwd) dirs.push(make(real));
|
|
167
|
+
} catch {}
|
|
168
|
+
return dirs;
|
|
169
|
+
}
|
|
170
|
+
async function listClaudeJsonlIdsByCwd(cwd) {
|
|
171
|
+
const ids = new Set();
|
|
172
|
+
for (const dir of await getClaudeProjectDirs(cwd)) try {
|
|
173
|
+
const files = await node_fs.promises.readdir(dir);
|
|
174
|
+
for (const f of files) if (f.endsWith(`.jsonl`)) ids.add(f.slice(0, -`.jsonl`.length));
|
|
175
|
+
} catch {}
|
|
176
|
+
return ids;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Deterministic-path discovery for a freshly created session. After the
|
|
180
|
+
* Claude CLI runs in `-p` mode it writes the new JSONL straight into
|
|
181
|
+
* `~/.claude/projects/<sanitize(cwd)>/<id>.jsonl` *without* leaving a
|
|
182
|
+
* `~/.claude/sessions/<pid>.json` lock file (those are interactive-only),
|
|
183
|
+
* so `discoverSessions` can miss it. Compute the expected dir directly
|
|
184
|
+
* and diff its contents against a pre-run snapshot. Returns the newest
|
|
185
|
+
* fresh sessionId or null. Codex falls back to discoverNewestSession.
|
|
186
|
+
*/
|
|
187
|
+
async function findNewSessionAfterRun(agent, cwd, preDirectIds, preDiscoveredIds) {
|
|
188
|
+
if (agent === `claude`) {
|
|
189
|
+
const dirs = await getClaudeProjectDirs(cwd);
|
|
190
|
+
let best = null;
|
|
191
|
+
for (const dir of dirs) try {
|
|
192
|
+
const files = await node_fs.promises.readdir(dir);
|
|
193
|
+
for (const f of files) {
|
|
194
|
+
if (!f.endsWith(`.jsonl`)) continue;
|
|
195
|
+
const id = f.slice(0, -`.jsonl`.length);
|
|
196
|
+
if (preDirectIds.has(id)) continue;
|
|
197
|
+
const st = await node_fs.promises.stat(node_path.default.join(dir, f)).catch(() => null);
|
|
198
|
+
if (!st) continue;
|
|
199
|
+
if (!best || st.mtimeMs > best.mtime) best = {
|
|
200
|
+
id,
|
|
201
|
+
mtime: st.mtimeMs
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
} catch {}
|
|
205
|
+
if (best) return best.id;
|
|
206
|
+
}
|
|
207
|
+
return discoverNewestSession(agent, cwd, preDiscoveredIds);
|
|
208
|
+
}
|
|
209
|
+
const sessionMetaRowSchema = zod.z.object({
|
|
210
|
+
key: zod.z.literal(`current`),
|
|
211
|
+
electricSessionId: zod.z.string(),
|
|
212
|
+
nativeSessionId: zod.z.string().optional(),
|
|
213
|
+
agent: zod.z.enum([`claude`, `codex`]),
|
|
214
|
+
cwd: zod.z.string(),
|
|
215
|
+
status: zod.z.enum([
|
|
216
|
+
`initializing`,
|
|
217
|
+
`idle`,
|
|
218
|
+
`running`,
|
|
219
|
+
`error`
|
|
220
|
+
]),
|
|
221
|
+
error: zod.z.string().optional(),
|
|
222
|
+
currentPromptInboxKey: zod.z.string().optional()
|
|
223
|
+
});
|
|
224
|
+
const cursorStateRowSchema = zod.z.object({
|
|
225
|
+
key: zod.z.literal(`current`),
|
|
226
|
+
cursor: zod.z.string(),
|
|
227
|
+
lastProcessedInboxKey: zod.z.string().optional()
|
|
228
|
+
});
|
|
229
|
+
const eventRowSchema = zod.z.object({
|
|
230
|
+
key: zod.z.string(),
|
|
231
|
+
ts: zod.z.number(),
|
|
232
|
+
type: zod.z.string(),
|
|
233
|
+
callId: zod.z.string().optional(),
|
|
234
|
+
payload: zod.z.looseObject({})
|
|
235
|
+
});
|
|
236
|
+
const creationArgsSchema = zod.z.object({
|
|
237
|
+
agent: zod.z.enum([`claude`, `codex`]),
|
|
238
|
+
cwd: zod.z.string().optional(),
|
|
239
|
+
nativeSessionId: zod.z.string().optional(),
|
|
240
|
+
importFrom: zod.z.object({
|
|
241
|
+
agent: zod.z.enum([`claude`, `codex`]),
|
|
242
|
+
sessionId: zod.z.string()
|
|
243
|
+
}).optional()
|
|
244
|
+
});
|
|
245
|
+
const promptMessageSchema = zod.z.object({ text: zod.z.string() });
|
|
246
|
+
/**
|
|
247
|
+
* Stable key for an events-collection row, derived from the event's content.
|
|
248
|
+
* Lets us re-insert the same event without producing duplicates — the caller
|
|
249
|
+
* (or the collection's uniqueness guard) uses this to de-dup across retries,
|
|
250
|
+
* replays, and crash recovery. Sorts chronologically by ts, then by type.
|
|
251
|
+
*/
|
|
252
|
+
function eventKey(event) {
|
|
253
|
+
const tsPart = String(event.ts).padStart(16, `0`);
|
|
254
|
+
return `${tsPart}_${event.type}_${contentHashHex(event)}`;
|
|
255
|
+
}
|
|
256
|
+
function contentHashHex(event) {
|
|
257
|
+
const json = JSON.stringify(event);
|
|
258
|
+
let h = 5381;
|
|
259
|
+
for (let i = 0; i < json.length; i++) h = (h * 33 ^ json.charCodeAt(i)) >>> 0;
|
|
260
|
+
return h.toString(16).padStart(8, `0`);
|
|
261
|
+
}
|
|
262
|
+
function buildEventRow(event) {
|
|
263
|
+
const callId = `callId` in event && typeof event.callId === `string` ? event.callId : void 0;
|
|
264
|
+
return {
|
|
265
|
+
key: eventKey(event),
|
|
266
|
+
ts: event.ts,
|
|
267
|
+
type: event.type,
|
|
268
|
+
...callId !== void 0 ? { callId } : {},
|
|
269
|
+
payload: event
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
function appendIfNew(ctx, event) {
|
|
273
|
+
const row = buildEventRow(event);
|
|
274
|
+
if (ctx.events.get(row.key) !== void 0) return;
|
|
275
|
+
ctx.actions.events_insert({ row });
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Mirror every event that lands in the JSONL file while `runWork` is
|
|
279
|
+
* executing (i.e. while the CLI is running). Returns the advanced cursor
|
|
280
|
+
* and the `runWork` result once everything has settled and every append
|
|
281
|
+
* has been persisted to the entity's durable stream.
|
|
282
|
+
*
|
|
283
|
+
* If setup fails (e.g. the session file can't be resolved), `runWork`
|
|
284
|
+
* still runs — but nothing is mirrored and `setupError` is populated so
|
|
285
|
+
* the caller can surface the condition. If `runWork` throws, the error
|
|
286
|
+
* propagates after the watcher has been cleaned up.
|
|
287
|
+
*/
|
|
288
|
+
async function runWithLiveMirror(opts) {
|
|
289
|
+
let cursor = null;
|
|
290
|
+
let setupError = void 0;
|
|
291
|
+
try {
|
|
292
|
+
const session = await (0, agent_session_protocol.resolveSession)(opts.nativeSessionId, opts.agent);
|
|
293
|
+
if (opts.serializedCursor) cursor = (0, agent_session_protocol.deserializeCursor)({
|
|
294
|
+
...opts.serializedCursor,
|
|
295
|
+
path: session.path
|
|
296
|
+
});
|
|
297
|
+
else {
|
|
298
|
+
const initial = await (0, agent_session_protocol.loadSession)({
|
|
299
|
+
sessionId: opts.nativeSessionId,
|
|
300
|
+
agent: opts.agent
|
|
301
|
+
});
|
|
302
|
+
for (const ev of initial.events) appendIfNew(opts.ctx, ev);
|
|
303
|
+
cursor = initial.cursor;
|
|
304
|
+
}
|
|
305
|
+
} catch (e) {
|
|
306
|
+
setupError = e;
|
|
307
|
+
}
|
|
308
|
+
if (!cursor) {
|
|
309
|
+
const result$1 = await opts.runWork();
|
|
310
|
+
return {
|
|
311
|
+
cursor: opts.serializedCursor,
|
|
312
|
+
setupError,
|
|
313
|
+
result: result$1
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
let activeCursor = cursor;
|
|
317
|
+
let busy = false;
|
|
318
|
+
let pending = false;
|
|
319
|
+
let stopped = false;
|
|
320
|
+
const drainOnce = async () => {
|
|
321
|
+
if (stopped && busy) return;
|
|
322
|
+
if (busy) {
|
|
323
|
+
pending = true;
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
busy = true;
|
|
327
|
+
try {
|
|
328
|
+
const res = await (0, agent_session_protocol.tailSession)({ cursor: activeCursor });
|
|
329
|
+
activeCursor = res.cursor;
|
|
330
|
+
for (const ev of res.newEvents) appendIfNew(opts.ctx, ev);
|
|
331
|
+
} catch {} finally {
|
|
332
|
+
busy = false;
|
|
333
|
+
if (pending && !stopped) {
|
|
334
|
+
pending = false;
|
|
335
|
+
drainOnce();
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
const fileWatcher = (0, node_fs.watch)(activeCursor.path, () => {
|
|
340
|
+
drainOnce();
|
|
341
|
+
});
|
|
342
|
+
const pollHandle = setInterval(() => {
|
|
343
|
+
drainOnce();
|
|
344
|
+
}, 1500);
|
|
345
|
+
let result;
|
|
346
|
+
try {
|
|
347
|
+
result = await opts.runWork();
|
|
348
|
+
} finally {
|
|
349
|
+
stopped = true;
|
|
350
|
+
clearInterval(pollHandle);
|
|
351
|
+
fileWatcher.close();
|
|
352
|
+
while (busy) await new Promise((r) => setTimeout(r, 10));
|
|
353
|
+
try {
|
|
354
|
+
const final = await (0, agent_session_protocol.tailSession)({ cursor: activeCursor });
|
|
355
|
+
activeCursor = final.cursor;
|
|
356
|
+
for (const ev of final.newEvents) appendIfNew(opts.ctx, ev);
|
|
357
|
+
} catch {}
|
|
358
|
+
}
|
|
359
|
+
return {
|
|
360
|
+
cursor: (0, agent_session_protocol.serializeCursor)(activeCursor),
|
|
361
|
+
setupError,
|
|
362
|
+
result
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
function registerCodingSession(registry, options = {}) {
|
|
366
|
+
const runner = options.cliRunner ?? defaultCliRunner;
|
|
367
|
+
const defaultCwd = options.defaultWorkingDirectory ?? process.cwd();
|
|
368
|
+
registry.define(`coder`, {
|
|
369
|
+
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.`,
|
|
370
|
+
creationSchema: creationArgsSchema,
|
|
371
|
+
inboxSchemas: { prompt: promptMessageSchema },
|
|
372
|
+
state: {
|
|
373
|
+
sessionMeta: {
|
|
374
|
+
schema: sessionMetaRowSchema,
|
|
375
|
+
type: __electric_ax_agents_runtime.CODING_SESSION_META_COLLECTION_TYPE,
|
|
376
|
+
primaryKey: `key`
|
|
377
|
+
},
|
|
378
|
+
cursorState: {
|
|
379
|
+
schema: cursorStateRowSchema,
|
|
380
|
+
type: __electric_ax_agents_runtime.CODING_SESSION_CURSOR_COLLECTION_TYPE,
|
|
381
|
+
primaryKey: `key`
|
|
382
|
+
},
|
|
383
|
+
events: {
|
|
384
|
+
schema: eventRowSchema,
|
|
385
|
+
type: __electric_ax_agents_runtime.CODING_SESSION_EVENT_COLLECTION_TYPE,
|
|
386
|
+
primaryKey: `key`
|
|
387
|
+
}
|
|
388
|
+
},
|
|
389
|
+
async handler(ctx, _wake) {
|
|
390
|
+
const existingMeta = ctx.db.collections.sessionMeta.get(`current`);
|
|
391
|
+
if (!existingMeta) {
|
|
392
|
+
const args = creationArgsSchema.parse(ctx.args);
|
|
393
|
+
const cwd = args.cwd ?? defaultCwd;
|
|
394
|
+
const electricSessionId = ctx.entityUrl.split(`/`).pop() ?? ctx.entityUrl;
|
|
395
|
+
let resolvedNativeId = args.nativeSessionId;
|
|
396
|
+
if (args.importFrom) {
|
|
397
|
+
const result = await (0, agent_session_protocol.importLocalSession)({
|
|
398
|
+
source: {
|
|
399
|
+
sessionId: args.importFrom.sessionId,
|
|
400
|
+
agent: args.importFrom.agent
|
|
401
|
+
},
|
|
402
|
+
target: {
|
|
403
|
+
agent: args.agent,
|
|
404
|
+
cwd
|
|
405
|
+
}
|
|
406
|
+
});
|
|
407
|
+
resolvedNativeId = result.sessionId;
|
|
408
|
+
}
|
|
409
|
+
const hasNative = resolvedNativeId !== void 0;
|
|
410
|
+
ctx.db.actions.sessionMeta_insert({ row: {
|
|
411
|
+
key: `current`,
|
|
412
|
+
electricSessionId,
|
|
413
|
+
...hasNative ? { nativeSessionId: resolvedNativeId } : {},
|
|
414
|
+
agent: args.agent,
|
|
415
|
+
cwd,
|
|
416
|
+
status: hasNative ? `idle` : `initializing`
|
|
417
|
+
} });
|
|
418
|
+
}
|
|
419
|
+
if (!ctx.db.collections.cursorState.get(`current`)) ctx.db.actions.cursorState_insert({ row: {
|
|
420
|
+
key: `current`,
|
|
421
|
+
cursor: ``
|
|
422
|
+
} });
|
|
423
|
+
const metaRow = ctx.db.collections.sessionMeta.get(`current`);
|
|
424
|
+
const cursorRow = ctx.db.collections.cursorState.get(`current`);
|
|
425
|
+
if (!metaRow || !cursorRow) throw new Error(`[coding-session] expected sessionMeta and cursorState rows to exist after init`);
|
|
426
|
+
if (metaRow.nativeSessionId && !cursorRow.cursor) {
|
|
427
|
+
const mirrorCtx = {
|
|
428
|
+
events: { get: (k) => ctx.db.collections.events.get(k) },
|
|
429
|
+
actions: { events_insert: ctx.db.actions.events_insert }
|
|
430
|
+
};
|
|
431
|
+
try {
|
|
432
|
+
const initial = await (0, agent_session_protocol.loadSession)({
|
|
433
|
+
sessionId: metaRow.nativeSessionId,
|
|
434
|
+
agent: metaRow.agent
|
|
435
|
+
});
|
|
436
|
+
for (const ev of initial.events) appendIfNew(mirrorCtx, ev);
|
|
437
|
+
const serialized = (0, agent_session_protocol.serializeCursor)(initial.cursor);
|
|
438
|
+
ctx.db.actions.cursorState_update({
|
|
439
|
+
key: `current`,
|
|
440
|
+
updater: (d) => {
|
|
441
|
+
d.cursor = JSON.stringify(serialized);
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
} catch (e) {
|
|
445
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
446
|
+
ctx.db.actions.sessionMeta_update({
|
|
447
|
+
key: `current`,
|
|
448
|
+
updater: (d) => {
|
|
449
|
+
d.error = `initial mirror failed: ${message}`;
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
const inboxRows = ctx.db.collections.inbox.toArray.slice().sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
|
|
455
|
+
const lastKey = cursorRow.lastProcessedInboxKey ?? ``;
|
|
456
|
+
const pending = inboxRows.filter((m) => m.key > lastKey);
|
|
457
|
+
if (pending.length === 0) {
|
|
458
|
+
if (metaRow.status === `running` || metaRow.status === `error`) ctx.db.actions.sessionMeta_update({
|
|
459
|
+
key: `current`,
|
|
460
|
+
updater: (d) => {
|
|
461
|
+
d.status = `idle`;
|
|
462
|
+
delete d.currentPromptInboxKey;
|
|
463
|
+
delete d.error;
|
|
464
|
+
}
|
|
465
|
+
});
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
let runningMeta = metaRow;
|
|
469
|
+
let runningCursor = cursorRow;
|
|
470
|
+
for (const inboxMsg of pending) {
|
|
471
|
+
const parsed = promptMessageSchema.safeParse(inboxMsg.payload);
|
|
472
|
+
if (!parsed.success) {
|
|
473
|
+
ctx.db.actions.cursorState_update({
|
|
474
|
+
key: `current`,
|
|
475
|
+
updater: (d) => {
|
|
476
|
+
d.lastProcessedInboxKey = inboxMsg.key;
|
|
477
|
+
}
|
|
478
|
+
});
|
|
479
|
+
runningCursor = {
|
|
480
|
+
...runningCursor,
|
|
481
|
+
lastProcessedInboxKey: inboxMsg.key
|
|
482
|
+
};
|
|
483
|
+
continue;
|
|
484
|
+
}
|
|
485
|
+
const prompt = parsed.data.text;
|
|
486
|
+
const existingTitle = ctx.tags.title;
|
|
487
|
+
if (typeof existingTitle !== `string` || existingTitle.length === 0) ctx.setTag(`title`, prompt.slice(0, 80));
|
|
488
|
+
ctx.db.actions.sessionMeta_update({
|
|
489
|
+
key: `current`,
|
|
490
|
+
updater: (d) => {
|
|
491
|
+
d.status = `running`;
|
|
492
|
+
d.currentPromptInboxKey = inboxMsg.key;
|
|
493
|
+
delete d.error;
|
|
494
|
+
}
|
|
495
|
+
});
|
|
496
|
+
const recordedRun = ctx.recordRun();
|
|
497
|
+
const eventKeysBefore = new Set(ctx.db.collections.events.toArray.map((e) => e.key));
|
|
498
|
+
try {
|
|
499
|
+
const mirrorCtx = {
|
|
500
|
+
events: { get: (k) => ctx.db.collections.events.get(k) },
|
|
501
|
+
actions: { events_insert: ctx.db.actions.events_insert }
|
|
502
|
+
};
|
|
503
|
+
let nextCursorJson = runningCursor.cursor;
|
|
504
|
+
if (!runningMeta.nativeSessionId) {
|
|
505
|
+
const preDirectIds = runningMeta.agent === `claude` ? await listClaudeJsonlIdsByCwd(runningMeta.cwd) : new Set();
|
|
506
|
+
const preDiscoveredIds = new Set((await (0, agent_session_protocol.discoverSessions)(runningMeta.agent)).map((s) => s.sessionId));
|
|
507
|
+
const cliResult = await runner.run({
|
|
508
|
+
agent: runningMeta.agent,
|
|
509
|
+
cwd: runningMeta.cwd,
|
|
510
|
+
prompt
|
|
511
|
+
});
|
|
512
|
+
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>`}`);
|
|
513
|
+
const foundId = await findNewSessionAfterRun(runningMeta.agent, runningMeta.cwd, preDirectIds, preDiscoveredIds);
|
|
514
|
+
if (!foundId) throw new Error(`[coding-session] ${runningMeta.agent} CLI succeeded but no new session file was found`);
|
|
515
|
+
ctx.db.actions.sessionMeta_update({
|
|
516
|
+
key: `current`,
|
|
517
|
+
updater: (d) => {
|
|
518
|
+
d.nativeSessionId = foundId;
|
|
519
|
+
}
|
|
520
|
+
});
|
|
521
|
+
runningMeta = {
|
|
522
|
+
...runningMeta,
|
|
523
|
+
nativeSessionId: foundId
|
|
524
|
+
};
|
|
525
|
+
const initial = await (0, agent_session_protocol.loadSession)({
|
|
526
|
+
sessionId: foundId,
|
|
527
|
+
agent: runningMeta.agent
|
|
528
|
+
});
|
|
529
|
+
for (const ev of initial.events) appendIfNew(mirrorCtx, ev);
|
|
530
|
+
nextCursorJson = JSON.stringify((0, agent_session_protocol.serializeCursor)(initial.cursor));
|
|
531
|
+
} else {
|
|
532
|
+
const serializedCursor = runningCursor.cursor ? JSON.parse(runningCursor.cursor) : null;
|
|
533
|
+
const { cursor: nextSerialized, setupError, result: cliResult } = await runWithLiveMirror({
|
|
534
|
+
agent: runningMeta.agent,
|
|
535
|
+
nativeSessionId: runningMeta.nativeSessionId,
|
|
536
|
+
serializedCursor,
|
|
537
|
+
ctx: mirrorCtx,
|
|
538
|
+
runWork: () => runner.run({
|
|
539
|
+
agent: runningMeta.agent,
|
|
540
|
+
sessionId: runningMeta.nativeSessionId,
|
|
541
|
+
cwd: runningMeta.cwd,
|
|
542
|
+
prompt
|
|
543
|
+
})
|
|
544
|
+
});
|
|
545
|
+
if (setupError) throw setupError instanceof Error ? setupError : new Error(String(setupError));
|
|
546
|
+
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>`}`);
|
|
547
|
+
const persistedCursor = nextSerialized ?? serializedCursor;
|
|
548
|
+
nextCursorJson = persistedCursor ? JSON.stringify(persistedCursor) : ``;
|
|
549
|
+
}
|
|
550
|
+
ctx.db.actions.cursorState_update({
|
|
551
|
+
key: `current`,
|
|
552
|
+
updater: (d) => {
|
|
553
|
+
d.cursor = nextCursorJson;
|
|
554
|
+
d.lastProcessedInboxKey = inboxMsg.key;
|
|
555
|
+
}
|
|
556
|
+
});
|
|
557
|
+
runningCursor = {
|
|
558
|
+
...runningCursor,
|
|
559
|
+
cursor: nextCursorJson,
|
|
560
|
+
lastProcessedInboxKey: inboxMsg.key
|
|
561
|
+
};
|
|
562
|
+
for (const row of ctx.db.collections.events.toArray) {
|
|
563
|
+
if (eventKeysBefore.has(row.key)) continue;
|
|
564
|
+
if (row.type !== `assistant_message`) continue;
|
|
565
|
+
const text = row.payload?.text;
|
|
566
|
+
if (typeof text === `string` && text.length > 0) recordedRun.attachResponse(text);
|
|
567
|
+
}
|
|
568
|
+
recordedRun.end({ status: `completed` });
|
|
569
|
+
} catch (e) {
|
|
570
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
571
|
+
recordedRun.end({
|
|
572
|
+
status: `failed`,
|
|
573
|
+
finishReason: `error`
|
|
574
|
+
});
|
|
575
|
+
ctx.db.actions.sessionMeta_update({
|
|
576
|
+
key: `current`,
|
|
577
|
+
updater: (d) => {
|
|
578
|
+
d.status = `error`;
|
|
579
|
+
d.error = message;
|
|
580
|
+
}
|
|
581
|
+
});
|
|
582
|
+
ctx.db.actions.cursorState_update({
|
|
583
|
+
key: `current`,
|
|
584
|
+
updater: (d) => {
|
|
585
|
+
d.lastProcessedInboxKey = inboxMsg.key;
|
|
586
|
+
}
|
|
587
|
+
});
|
|
588
|
+
throw e;
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
ctx.db.actions.sessionMeta_update({
|
|
592
|
+
key: `current`,
|
|
593
|
+
updater: (d) => {
|
|
594
|
+
d.status = `idle`;
|
|
595
|
+
delete d.currentPromptInboxKey;
|
|
596
|
+
delete d.error;
|
|
597
|
+
}
|
|
598
|
+
});
|
|
599
|
+
}
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
|
|
93
603
|
//#endregion
|
|
94
604
|
//#region src/docs/embed.ts
|
|
95
605
|
const EMBEDDING_DIMENSIONS = 128;
|
|
@@ -309,6 +819,8 @@ function resolveDocsRoot(workingDirectory) {
|
|
|
309
819
|
process.env.HORTON_DOCS_ROOT,
|
|
310
820
|
node_path.default.resolve(workingDirectory, `electric-agents-docs/docs`),
|
|
311
821
|
node_path.default.resolve(process.cwd(), `electric-agents-docs/docs`),
|
|
822
|
+
node_path.default.resolve(MODULE_DIR, `../docs`),
|
|
823
|
+
node_path.default.resolve(MODULE_DIR, `../../docs`),
|
|
312
824
|
node_path.default.resolve(MODULE_DIR, `../../../../../electric-agents-docs/docs`)
|
|
313
825
|
].filter((value) => typeof value === `string`);
|
|
314
826
|
for (const candidate of candidates) if (node_fs.default.existsSync(candidate)) return candidate;
|
|
@@ -862,319 +1374,6 @@ function listRefFiles(dir, prefix = ``) {
|
|
|
862
1374
|
}
|
|
863
1375
|
}
|
|
864
1376
|
|
|
865
|
-
//#endregion
|
|
866
|
-
//#region src/tools/bash.ts
|
|
867
|
-
const TIMEOUT_MS = 3e4;
|
|
868
|
-
const MAX_OUTPUT_CHARS = 5e4;
|
|
869
|
-
function createBashTool(workingDirectory) {
|
|
870
|
-
return {
|
|
871
|
-
name: `bash`,
|
|
872
|
-
label: `Bash`,
|
|
873
|
-
description: `Execute a shell command and return its output. Commands run in a sandboxed working directory with a 30-second timeout.`,
|
|
874
|
-
parameters: __sinclair_typebox.Type.Object({ command: __sinclair_typebox.Type.String({ description: `The shell command to execute` }) }),
|
|
875
|
-
execute: async (_toolCallId, params) => {
|
|
876
|
-
const { command } = params;
|
|
877
|
-
return new Promise((resolve$3) => {
|
|
878
|
-
const child = (0, node_child_process.exec)(command, {
|
|
879
|
-
cwd: workingDirectory,
|
|
880
|
-
timeout: TIMEOUT_MS,
|
|
881
|
-
maxBuffer: 1024 * 1024,
|
|
882
|
-
env: {
|
|
883
|
-
...process.env,
|
|
884
|
-
HOME: workingDirectory
|
|
885
|
-
}
|
|
886
|
-
});
|
|
887
|
-
let stdout = ``;
|
|
888
|
-
let stderr = ``;
|
|
889
|
-
child.stdout?.on(`data`, (data) => {
|
|
890
|
-
stdout += data;
|
|
891
|
-
});
|
|
892
|
-
child.stderr?.on(`data`, (data) => {
|
|
893
|
-
stderr += data;
|
|
894
|
-
});
|
|
895
|
-
child.on(`close`, (code, signal) => {
|
|
896
|
-
const timedOut = signal === `SIGTERM`;
|
|
897
|
-
let output = stdout;
|
|
898
|
-
if (stderr) output += output ? `\n\nSTDERR:\n${stderr}` : stderr;
|
|
899
|
-
if (timedOut) output += `\n\n[Command timed out after ${TIMEOUT_MS / 1e3}s]`;
|
|
900
|
-
output = output.slice(0, MAX_OUTPUT_CHARS);
|
|
901
|
-
resolve$3({
|
|
902
|
-
content: [{
|
|
903
|
-
type: `text`,
|
|
904
|
-
text: output || `(no output)`
|
|
905
|
-
}],
|
|
906
|
-
details: {
|
|
907
|
-
exitCode: code ?? 1,
|
|
908
|
-
timedOut
|
|
909
|
-
}
|
|
910
|
-
});
|
|
911
|
-
});
|
|
912
|
-
child.on(`error`, (err) => {
|
|
913
|
-
resolve$3({
|
|
914
|
-
content: [{
|
|
915
|
-
type: `text`,
|
|
916
|
-
text: `Command failed: ${err.message}`
|
|
917
|
-
}],
|
|
918
|
-
details: {
|
|
919
|
-
exitCode: 1,
|
|
920
|
-
timedOut: false
|
|
921
|
-
}
|
|
922
|
-
});
|
|
923
|
-
});
|
|
924
|
-
});
|
|
925
|
-
}
|
|
926
|
-
};
|
|
927
|
-
}
|
|
928
|
-
|
|
929
|
-
//#endregion
|
|
930
|
-
//#region src/tools/edit.ts
|
|
931
|
-
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).`;
|
|
932
|
-
function createEditTool(workingDirectory, readSet) {
|
|
933
|
-
return {
|
|
934
|
-
name: `edit`,
|
|
935
|
-
label: `Edit File`,
|
|
936
|
-
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.`,
|
|
937
|
-
parameters: __sinclair_typebox.Type.Object({
|
|
938
|
-
path: __sinclair_typebox.Type.String({ description: `File path (relative to working directory)` }),
|
|
939
|
-
old_string: __sinclair_typebox.Type.String({ description: `The literal text to find. Must be unique unless replace_all is true.` }),
|
|
940
|
-
new_string: __sinclair_typebox.Type.String({ description: `The replacement text.` }),
|
|
941
|
-
replace_all: __sinclair_typebox.Type.Optional(__sinclair_typebox.Type.Boolean({ description: `Replace every occurrence (default false).` }))
|
|
942
|
-
}),
|
|
943
|
-
execute: async (_toolCallId, params) => {
|
|
944
|
-
const { path: filePath, old_string, new_string, replace_all } = params;
|
|
945
|
-
try {
|
|
946
|
-
const resolved = (0, node_path.resolve)(workingDirectory, filePath);
|
|
947
|
-
const rel = (0, node_path.relative)(workingDirectory, resolved);
|
|
948
|
-
if (rel.startsWith(`..`)) return {
|
|
949
|
-
content: [{
|
|
950
|
-
type: `text`,
|
|
951
|
-
text: `Error: Path "${filePath}" is outside the working directory`
|
|
952
|
-
}],
|
|
953
|
-
details: { replacements: 0 }
|
|
954
|
-
};
|
|
955
|
-
if (!readSet.has(resolved)) return {
|
|
956
|
-
content: [{
|
|
957
|
-
type: `text`,
|
|
958
|
-
text: READ_GUARD_MESSAGE(rel)
|
|
959
|
-
}],
|
|
960
|
-
details: { replacements: 0 }
|
|
961
|
-
};
|
|
962
|
-
const original = await (0, node_fs_promises.readFile)(resolved, `utf-8`);
|
|
963
|
-
if (!replace_all) {
|
|
964
|
-
const first = original.indexOf(old_string);
|
|
965
|
-
if (first === -1) return {
|
|
966
|
-
content: [{
|
|
967
|
-
type: `text`,
|
|
968
|
-
text: `Error: old_string not found in ${rel}`
|
|
969
|
-
}],
|
|
970
|
-
details: { replacements: 0 }
|
|
971
|
-
};
|
|
972
|
-
const second = original.indexOf(old_string, first + 1);
|
|
973
|
-
if (second !== -1) {
|
|
974
|
-
const matches = original.split(old_string).length - 1;
|
|
975
|
-
return {
|
|
976
|
-
content: [{
|
|
977
|
-
type: `text`,
|
|
978
|
-
text: `Error: found ${matches} matches for old_string in ${rel}; pass replace_all=true to replace all, or provide a more specific old_string.`
|
|
979
|
-
}],
|
|
980
|
-
details: { replacements: 0 }
|
|
981
|
-
};
|
|
982
|
-
}
|
|
983
|
-
const updated = original.slice(0, first) + new_string + original.slice(first + old_string.length);
|
|
984
|
-
await (0, node_fs_promises.writeFile)(resolved, updated, `utf-8`);
|
|
985
|
-
return {
|
|
986
|
-
content: [{
|
|
987
|
-
type: `text`,
|
|
988
|
-
text: `Edited ${rel}: 1 replacement`
|
|
989
|
-
}],
|
|
990
|
-
details: { replacements: 1 }
|
|
991
|
-
};
|
|
992
|
-
}
|
|
993
|
-
const parts = original.split(old_string);
|
|
994
|
-
const count = parts.length - 1;
|
|
995
|
-
if (count === 0) return {
|
|
996
|
-
content: [{
|
|
997
|
-
type: `text`,
|
|
998
|
-
text: `Error: old_string not found in ${rel}`
|
|
999
|
-
}],
|
|
1000
|
-
details: { replacements: 0 }
|
|
1001
|
-
};
|
|
1002
|
-
await (0, node_fs_promises.writeFile)(resolved, parts.join(new_string), `utf-8`);
|
|
1003
|
-
return {
|
|
1004
|
-
content: [{
|
|
1005
|
-
type: `text`,
|
|
1006
|
-
text: `Edited ${rel}: ${count} occurrences replaced`
|
|
1007
|
-
}],
|
|
1008
|
-
details: { replacements: count }
|
|
1009
|
-
};
|
|
1010
|
-
} catch (err) {
|
|
1011
|
-
serverLog.warn(`[edit tool] failed to edit ${filePath}: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0);
|
|
1012
|
-
return {
|
|
1013
|
-
content: [{
|
|
1014
|
-
type: `text`,
|
|
1015
|
-
text: `Error editing file: ${err instanceof Error ? err.message : `Unknown error`}`
|
|
1016
|
-
}],
|
|
1017
|
-
details: { replacements: 0 }
|
|
1018
|
-
};
|
|
1019
|
-
}
|
|
1020
|
-
}
|
|
1021
|
-
};
|
|
1022
|
-
}
|
|
1023
|
-
|
|
1024
|
-
//#endregion
|
|
1025
|
-
//#region src/tools/fetch-url.ts
|
|
1026
|
-
const MAX_RAW_CHARS = 1e5;
|
|
1027
|
-
const require$1 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
|
|
1028
|
-
const { gfm } = require$1(`turndown-plugin-gfm`);
|
|
1029
|
-
function htmlToMarkdown(html, url) {
|
|
1030
|
-
const virtualConsole = new jsdom.VirtualConsole();
|
|
1031
|
-
const dom = new jsdom.JSDOM(html, {
|
|
1032
|
-
url,
|
|
1033
|
-
virtualConsole
|
|
1034
|
-
});
|
|
1035
|
-
const reader = new __mozilla_readability.Readability(dom.window.document);
|
|
1036
|
-
const article = reader.parse();
|
|
1037
|
-
const turndown$1 = new turndown.default({ headingStyle: `atx` });
|
|
1038
|
-
turndown$1.use(gfm);
|
|
1039
|
-
return turndown$1.turndown(article?.content ?? html);
|
|
1040
|
-
}
|
|
1041
|
-
let anthropic$1 = null;
|
|
1042
|
-
function getClient$1() {
|
|
1043
|
-
if (!anthropic$1) anthropic$1 = new __anthropic_ai_sdk.default();
|
|
1044
|
-
return anthropic$1;
|
|
1045
|
-
}
|
|
1046
|
-
async function extractWithLLM(text, prompt) {
|
|
1047
|
-
const client = getClient$1();
|
|
1048
|
-
const res = await client.messages.create({
|
|
1049
|
-
model: `claude-haiku-4-5-20251001`,
|
|
1050
|
-
max_tokens: 2048,
|
|
1051
|
-
messages: [{
|
|
1052
|
-
role: `user`,
|
|
1053
|
-
content: `${prompt}\n\n<page_content>\n${text.slice(0, MAX_RAW_CHARS)}\n</page_content>`
|
|
1054
|
-
}]
|
|
1055
|
-
});
|
|
1056
|
-
const block = res.content[0];
|
|
1057
|
-
return block?.type === `text` ? block.text : ``;
|
|
1058
|
-
}
|
|
1059
|
-
const fetchUrlTool = {
|
|
1060
|
-
name: `fetch_url`,
|
|
1061
|
-
label: `Fetch URL`,
|
|
1062
|
-
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.`,
|
|
1063
|
-
parameters: __sinclair_typebox.Type.Object({
|
|
1064
|
-
url: __sinclair_typebox.Type.String({ description: `The URL to fetch` }),
|
|
1065
|
-
prompt: __sinclair_typebox.Type.String({ description: `What to extract from the page, e.g. 'Extract the main article content' or 'Find the pricing information'` })
|
|
1066
|
-
}),
|
|
1067
|
-
execute: async (_toolCallId, params) => {
|
|
1068
|
-
const { url, prompt } = params;
|
|
1069
|
-
try {
|
|
1070
|
-
const res = await fetch(url, {
|
|
1071
|
-
headers: {
|
|
1072
|
-
"User-Agent": `Mozilla/5.0 (compatible; DurableStreamsAgent/1.0)`,
|
|
1073
|
-
Accept: `text/html,application/xhtml+xml,text/plain,*/*`
|
|
1074
|
-
},
|
|
1075
|
-
redirect: `follow`,
|
|
1076
|
-
signal: AbortSignal.timeout(1e4)
|
|
1077
|
-
});
|
|
1078
|
-
if (!res.ok) return {
|
|
1079
|
-
content: [{
|
|
1080
|
-
type: `text`,
|
|
1081
|
-
text: `Failed to fetch: ${res.status} ${res.statusText}`
|
|
1082
|
-
}],
|
|
1083
|
-
details: {
|
|
1084
|
-
charCount: 0,
|
|
1085
|
-
usedLLM: false
|
|
1086
|
-
}
|
|
1087
|
-
};
|
|
1088
|
-
const contentType = res.headers.get(`content-type`) ?? ``;
|
|
1089
|
-
const raw = await res.text();
|
|
1090
|
-
const markdown = contentType.includes(`text/html`) ? htmlToMarkdown(raw, url) : raw;
|
|
1091
|
-
const extracted = await extractWithLLM(markdown, prompt);
|
|
1092
|
-
return {
|
|
1093
|
-
content: [{
|
|
1094
|
-
type: `text`,
|
|
1095
|
-
text: extracted
|
|
1096
|
-
}],
|
|
1097
|
-
details: {
|
|
1098
|
-
charCount: extracted.length,
|
|
1099
|
-
usedLLM: true
|
|
1100
|
-
}
|
|
1101
|
-
};
|
|
1102
|
-
} catch (err) {
|
|
1103
|
-
return {
|
|
1104
|
-
content: [{
|
|
1105
|
-
type: `text`,
|
|
1106
|
-
text: `Error fetching URL: ${err instanceof Error ? err.message : `Unknown error`}`
|
|
1107
|
-
}],
|
|
1108
|
-
details: {
|
|
1109
|
-
charCount: 0,
|
|
1110
|
-
usedLLM: false
|
|
1111
|
-
}
|
|
1112
|
-
};
|
|
1113
|
-
}
|
|
1114
|
-
}
|
|
1115
|
-
};
|
|
1116
|
-
|
|
1117
|
-
//#endregion
|
|
1118
|
-
//#region src/tools/read-file.ts
|
|
1119
|
-
const MAX_FILE_SIZE = 512 * 1024;
|
|
1120
|
-
function createReadFileTool(workingDirectory, readSet) {
|
|
1121
|
-
return {
|
|
1122
|
-
name: `read`,
|
|
1123
|
-
label: `Read File`,
|
|
1124
|
-
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.`,
|
|
1125
|
-
parameters: __sinclair_typebox.Type.Object({ path: __sinclair_typebox.Type.String({ description: `File path (relative to working directory)` }) }),
|
|
1126
|
-
execute: async (_toolCallId, params) => {
|
|
1127
|
-
const { path: filePath } = params;
|
|
1128
|
-
try {
|
|
1129
|
-
const resolved = (0, node_path.resolve)(workingDirectory, filePath);
|
|
1130
|
-
const rel = (0, node_path.relative)(workingDirectory, resolved);
|
|
1131
|
-
if (rel.startsWith(`..`)) return {
|
|
1132
|
-
content: [{
|
|
1133
|
-
type: `text`,
|
|
1134
|
-
text: `Error: Path "${filePath}" is outside the working directory`
|
|
1135
|
-
}],
|
|
1136
|
-
details: { charCount: 0 }
|
|
1137
|
-
};
|
|
1138
|
-
const fileStat = await (0, node_fs_promises.stat)(resolved);
|
|
1139
|
-
if (fileStat.size > MAX_FILE_SIZE) return {
|
|
1140
|
-
content: [{
|
|
1141
|
-
type: `text`,
|
|
1142
|
-
text: `Error: File is too large (${(fileStat.size / 1024).toFixed(0)}KB > ${MAX_FILE_SIZE / 1024}KB limit)`
|
|
1143
|
-
}],
|
|
1144
|
-
details: { charCount: 0 }
|
|
1145
|
-
};
|
|
1146
|
-
const buffer = await (0, node_fs_promises.readFile)(resolved);
|
|
1147
|
-
const sample = buffer.subarray(0, 8192);
|
|
1148
|
-
if (sample.includes(0)) return {
|
|
1149
|
-
content: [{
|
|
1150
|
-
type: `text`,
|
|
1151
|
-
text: `Error: "${filePath}" appears to be a binary file`
|
|
1152
|
-
}],
|
|
1153
|
-
details: { charCount: 0 }
|
|
1154
|
-
};
|
|
1155
|
-
const text = buffer.toString(`utf-8`);
|
|
1156
|
-
readSet?.add(resolved);
|
|
1157
|
-
return {
|
|
1158
|
-
content: [{
|
|
1159
|
-
type: `text`,
|
|
1160
|
-
text
|
|
1161
|
-
}],
|
|
1162
|
-
details: { charCount: text.length }
|
|
1163
|
-
};
|
|
1164
|
-
} catch (err) {
|
|
1165
|
-
serverLog.warn(`[read tool] failed to read ${filePath}: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0);
|
|
1166
|
-
return {
|
|
1167
|
-
content: [{
|
|
1168
|
-
type: `text`,
|
|
1169
|
-
text: `Error reading file: ${err instanceof Error ? err.message : `Unknown error`}`
|
|
1170
|
-
}],
|
|
1171
|
-
details: { charCount: 0 }
|
|
1172
|
-
};
|
|
1173
|
-
}
|
|
1174
|
-
}
|
|
1175
|
-
};
|
|
1176
|
-
}
|
|
1177
|
-
|
|
1178
1377
|
//#endregion
|
|
1179
1378
|
//#region src/tools/spawn-worker.ts
|
|
1180
1379
|
const WORKER_TOOL_NAMES = [
|
|
@@ -1250,114 +1449,117 @@ function createSpawnWorkerTool(ctx) {
|
|
|
1250
1449
|
}
|
|
1251
1450
|
|
|
1252
1451
|
//#endregion
|
|
1253
|
-
//#region src/tools/
|
|
1254
|
-
|
|
1452
|
+
//#region src/tools/spawn-coder.ts
|
|
1453
|
+
const CODER_AGENT_NAMES = [`claude`, `codex`];
|
|
1454
|
+
function createSpawnCoderTool(ctx) {
|
|
1255
1455
|
return {
|
|
1256
|
-
name: `
|
|
1257
|
-
label: `
|
|
1258
|
-
description: `
|
|
1456
|
+
name: `spawn_coder`,
|
|
1457
|
+
label: `Spawn Coder`,
|
|
1458
|
+
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.`,
|
|
1259
1459
|
parameters: __sinclair_typebox.Type.Object({
|
|
1260
|
-
|
|
1261
|
-
|
|
1460
|
+
prompt: __sinclair_typebox.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.` }),
|
|
1461
|
+
agent: __sinclair_typebox.Type.Optional(__sinclair_typebox.Type.Union(CODER_AGENT_NAMES.map((n) => __sinclair_typebox.Type.Literal(n)), { description: `Which coding agent to use. Defaults to "claude". Use "codex" only if the user explicitly asks for it.` })),
|
|
1462
|
+
cwd: __sinclair_typebox.Type.Optional(__sinclair_typebox.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.` }))
|
|
1262
1463
|
}),
|
|
1263
1464
|
execute: async (_toolCallId, params) => {
|
|
1264
|
-
const {
|
|
1465
|
+
const { prompt, agent, cwd } = params;
|
|
1466
|
+
if (typeof prompt !== `string` || prompt.length === 0) return {
|
|
1467
|
+
content: [{
|
|
1468
|
+
type: `text`,
|
|
1469
|
+
text: `Error: prompt is required and must be a non-empty string.`
|
|
1470
|
+
}],
|
|
1471
|
+
details: { spawned: false }
|
|
1472
|
+
};
|
|
1473
|
+
const id = (0, nanoid.nanoid)(10);
|
|
1474
|
+
const spawnArgs = { agent: agent ?? `claude` };
|
|
1475
|
+
if (cwd) spawnArgs.cwd = cwd;
|
|
1265
1476
|
try {
|
|
1266
|
-
const
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
};
|
|
1275
|
-
await (0, node_fs_promises.mkdir)((0, node_path.dirname)(resolved), { recursive: true });
|
|
1276
|
-
await (0, node_fs_promises.writeFile)(resolved, content, `utf-8`);
|
|
1277
|
-
readSet?.add(resolved);
|
|
1278
|
-
const bytesWritten = Buffer.byteLength(content, `utf-8`);
|
|
1477
|
+
const handle = await ctx.spawn(`coder`, id, spawnArgs, {
|
|
1478
|
+
initialMessage: { text: prompt },
|
|
1479
|
+
wake: {
|
|
1480
|
+
on: `runFinished`,
|
|
1481
|
+
includeResponse: true
|
|
1482
|
+
}
|
|
1483
|
+
});
|
|
1484
|
+
const coderUrl = handle.entityUrl;
|
|
1279
1485
|
return {
|
|
1280
1486
|
content: [{
|
|
1281
1487
|
type: `text`,
|
|
1282
|
-
text: `
|
|
1488
|
+
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.`
|
|
1283
1489
|
}],
|
|
1284
|
-
details: {
|
|
1490
|
+
details: {
|
|
1491
|
+
spawned: true,
|
|
1492
|
+
coderUrl
|
|
1493
|
+
}
|
|
1285
1494
|
};
|
|
1286
1495
|
} catch (err) {
|
|
1287
|
-
serverLog.warn(`[
|
|
1496
|
+
serverLog.warn(`[spawn_coder tool] failed to spawn coder ${id}: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0);
|
|
1288
1497
|
return {
|
|
1289
1498
|
content: [{
|
|
1290
1499
|
type: `text`,
|
|
1291
|
-
text: `Error
|
|
1500
|
+
text: `Error spawning coder: ${err instanceof Error ? err.message : `Unknown error`}`
|
|
1292
1501
|
}],
|
|
1293
|
-
details: {
|
|
1502
|
+
details: { spawned: false }
|
|
1294
1503
|
};
|
|
1295
1504
|
}
|
|
1296
1505
|
}
|
|
1297
1506
|
};
|
|
1298
1507
|
}
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
content: [{
|
|
1312
|
-
type: `text`,
|
|
1313
|
-
text: `Search failed: BRAVE_SEARCH_API_KEY not set`
|
|
1314
|
-
}],
|
|
1315
|
-
details: { resultCount: 0 }
|
|
1316
|
-
};
|
|
1317
|
-
const { query } = params;
|
|
1318
|
-
try {
|
|
1319
|
-
const url = `${BRAVE_API_URL}?q=${encodeURIComponent(query)}&count=5`;
|
|
1320
|
-
const res = await fetch(url, { headers: { "X-Subscription-Token": apiKey } });
|
|
1321
|
-
if (!res.ok) return {
|
|
1322
|
-
content: [{
|
|
1323
|
-
type: `text`,
|
|
1324
|
-
text: `Search failed: ${res.status} ${res.statusText}`
|
|
1325
|
-
}],
|
|
1326
|
-
details: { resultCount: 0 }
|
|
1327
|
-
};
|
|
1328
|
-
const data = await res.json();
|
|
1329
|
-
const results = data.web?.results ?? [];
|
|
1330
|
-
if (results.length === 0) return {
|
|
1331
|
-
content: [{
|
|
1332
|
-
type: `text`,
|
|
1333
|
-
text: `No results found for "${query}"`
|
|
1334
|
-
}],
|
|
1335
|
-
details: { resultCount: 0 }
|
|
1336
|
-
};
|
|
1337
|
-
const formatted = results.map((r, i) => `${i + 1}. **${r.title}**\n ${r.url}\n ${r.description}`).join(`\n\n`);
|
|
1338
|
-
return {
|
|
1508
|
+
function createPromptCoderTool(ctx) {
|
|
1509
|
+
return {
|
|
1510
|
+
name: `prompt_coder`,
|
|
1511
|
+
label: `Prompt Coder`,
|
|
1512
|
+
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.`,
|
|
1513
|
+
parameters: __sinclair_typebox.Type.Object({
|
|
1514
|
+
coder_url: __sinclair_typebox.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.` }),
|
|
1515
|
+
prompt: __sinclair_typebox.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.` })
|
|
1516
|
+
}),
|
|
1517
|
+
execute: async (_toolCallId, params) => {
|
|
1518
|
+
const { coder_url, prompt } = params;
|
|
1519
|
+
if (typeof coder_url !== `string` || !coder_url.startsWith(`/coder/`)) return {
|
|
1339
1520
|
content: [{
|
|
1340
1521
|
type: `text`,
|
|
1341
|
-
text:
|
|
1522
|
+
text: `Error: coder_url must be a path like "/coder/<id>".`
|
|
1342
1523
|
}],
|
|
1343
|
-
details: {
|
|
1524
|
+
details: { sent: false }
|
|
1344
1525
|
};
|
|
1345
|
-
|
|
1346
|
-
return {
|
|
1526
|
+
if (typeof prompt !== `string` || prompt.length === 0) return {
|
|
1347
1527
|
content: [{
|
|
1348
1528
|
type: `text`,
|
|
1349
|
-
text: `
|
|
1529
|
+
text: `Error: prompt is required and must be a non-empty string.`
|
|
1350
1530
|
}],
|
|
1351
|
-
details: {
|
|
1531
|
+
details: { sent: false }
|
|
1352
1532
|
};
|
|
1533
|
+
try {
|
|
1534
|
+
ctx.send(coder_url, { text: prompt });
|
|
1535
|
+
return {
|
|
1536
|
+
content: [{
|
|
1537
|
+
type: `text`,
|
|
1538
|
+
text: `Prompt queued for ${coder_url}. End your turn — you'll be woken when the coder's reply lands.`
|
|
1539
|
+
}],
|
|
1540
|
+
details: {
|
|
1541
|
+
sent: true,
|
|
1542
|
+
coderUrl: coder_url
|
|
1543
|
+
}
|
|
1544
|
+
};
|
|
1545
|
+
} catch (err) {
|
|
1546
|
+
serverLog.warn(`[prompt_coder tool] failed to send to ${coder_url}: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0);
|
|
1547
|
+
return {
|
|
1548
|
+
content: [{
|
|
1549
|
+
type: `text`,
|
|
1550
|
+
text: `Error sending prompt to coder: ${err instanceof Error ? err.message : `Unknown error`}`
|
|
1551
|
+
}],
|
|
1552
|
+
details: { sent: false }
|
|
1553
|
+
};
|
|
1554
|
+
}
|
|
1353
1555
|
}
|
|
1354
|
-
}
|
|
1355
|
-
}
|
|
1556
|
+
};
|
|
1557
|
+
}
|
|
1356
1558
|
|
|
1357
1559
|
//#endregion
|
|
1358
1560
|
//#region src/agents/horton.ts
|
|
1359
1561
|
const TITLE_MODEL = `claude-haiku-4-5-20251001`;
|
|
1360
|
-
const HORTON_MODEL = `claude-sonnet-4-
|
|
1562
|
+
const HORTON_MODEL = `claude-sonnet-4-6`;
|
|
1361
1563
|
let anthropic = null;
|
|
1362
1564
|
function getClient() {
|
|
1363
1565
|
if (!anthropic) anthropic = new __anthropic_ai_sdk.default();
|
|
@@ -1460,10 +1662,10 @@ async function generateTitle(userMessage, llmCall = defaultHaikuCall) {
|
|
|
1460
1662
|
function buildHortonSystemPrompt(workingDirectory, opts = {}) {
|
|
1461
1663
|
const docsTools = opts.hasDocsSupport ? `\n- search_durable_agents_docs: hybrid search over the built-in Durable Agents docs index` : ``;
|
|
1462
1664
|
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` : ``;
|
|
1463
|
-
const docsGuidance = opts.hasDocsSupport ? `\n-
|
|
1665
|
+
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.` : ``;
|
|
1464
1666
|
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.
|
|
1465
1667
|
|
|
1466
|
-
Some skills are user-invocable — the user can trigger them with a slash command like \`/
|
|
1668
|
+
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.
|
|
1467
1669
|
|
|
1468
1670
|
## IMPORTANT: How to use a loaded skill
|
|
1469
1671
|
|
|
@@ -1475,8 +1677,33 @@ When you load a skill, it becomes your primary directive for that interaction. F
|
|
|
1475
1677
|
4. **Unload when done.** Use remove_skill to free context space when the skill's workflow is complete.
|
|
1476
1678
|
|
|
1477
1679
|
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.` : ``;
|
|
1680
|
+
const onboardingGuidance = `\n# Onboarding
|
|
1681
|
+
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:
|
|
1682
|
+
|
|
1683
|
+
- **Learn the concepts first** → Explain what Electric Agents is, answer questions, point to docs.
|
|
1684
|
+
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.
|
|
1685
|
+
|
|
1686
|
+
- **Hands-on guided tutorial** → Load the quickstart skill (or tell them to type \`/quickstart\`).
|
|
1687
|
+
This is a step-by-step build that takes them from zero to a running app.
|
|
1688
|
+
Only load it when the user explicitly wants to build something hands-on.
|
|
1689
|
+
|
|
1690
|
+
- **Scaffold a new project** → Load the init skill.
|
|
1691
|
+
This sets up project structure and orients them in the codebase.
|
|
1692
|
+
|
|
1693
|
+
- **Have a specific question?** → Answer it directly.
|
|
1694
|
+
Use search_durable_agents_docs first, then fall back to fetch_url or general knowledge if needed.
|
|
1695
|
+
|
|
1696
|
+
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.`;
|
|
1697
|
+
const docsUrlGuidance = opts.docsUrl ? `\n# Electric Agents documentation
|
|
1698
|
+
- ${opts.hasDocsSupport ? `If search_durable_agents_docs is available, use it first (faster, hybrid search).` : `Use fetch_url to look up documentation pages.`}
|
|
1699
|
+
- The Electric Agents docs site is at ${opts.docsUrl}
|
|
1700
|
+
- 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).
|
|
1701
|
+
- For general coding questions unrelated to Electric Agents, use brave_search or your own knowledge.` : ``;
|
|
1478
1702
|
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.
|
|
1479
1703
|
|
|
1704
|
+
# Greetings
|
|
1705
|
+
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.
|
|
1706
|
+
|
|
1480
1707
|
# Tools
|
|
1481
1708
|
- bash: run shell commands
|
|
1482
1709
|
- read: read a file
|
|
@@ -1485,13 +1712,15 @@ Do NOT load a skill and then ignore its instructions. The skill is there because
|
|
|
1485
1712
|
- brave_search: search the web
|
|
1486
1713
|
- fetch_url: fetch and convert a URL to markdown
|
|
1487
1714
|
- spawn_worker: dispatch a subagent for an isolated task
|
|
1715
|
+
- spawn_coder: spawn a long-lived coding agent (Claude Code or Codex CLI) for code changes, file edits, debugging
|
|
1716
|
+
- prompt_coder: send a follow-up prompt to a coder you previously spawned
|
|
1488
1717
|
${docsTools}${skillsTools}
|
|
1489
1718
|
|
|
1490
1719
|
# Working with files
|
|
1491
1720
|
- Prefer edit over write when modifying existing files.
|
|
1492
1721
|
- You must read a file before you can edit it.
|
|
1493
1722
|
- Use absolute paths or paths relative to the current working directory.
|
|
1494
|
-
${docsGuidance}${skillsGuidance}
|
|
1723
|
+
${docsGuidance}${skillsGuidance}${onboardingGuidance}${docsUrlGuidance}
|
|
1495
1724
|
|
|
1496
1725
|
# Risky actions
|
|
1497
1726
|
Pause and confirm with the user before:
|
|
@@ -1512,6 +1741,13 @@ When you spawn a worker, write its system prompt the way you'd brief a colleague
|
|
|
1512
1741
|
|
|
1513
1742
|
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.
|
|
1514
1743
|
|
|
1744
|
+
# When to spawn a coder
|
|
1745
|
+
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.
|
|
1746
|
+
|
|
1747
|
+
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.
|
|
1748
|
+
|
|
1749
|
+
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.
|
|
1750
|
+
|
|
1515
1751
|
# Reporting
|
|
1516
1752
|
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.
|
|
1517
1753
|
|
|
@@ -1520,13 +1756,15 @@ The current year is ${new Date().getFullYear()}.`;
|
|
|
1520
1756
|
}
|
|
1521
1757
|
function createHortonTools(workingDirectory, ctx, readSet, opts = {}) {
|
|
1522
1758
|
return [
|
|
1523
|
-
createBashTool(workingDirectory),
|
|
1524
|
-
createReadFileTool(workingDirectory, readSet),
|
|
1525
|
-
createWriteTool(workingDirectory, readSet),
|
|
1526
|
-
createEditTool(workingDirectory, readSet),
|
|
1527
|
-
braveSearchTool,
|
|
1528
|
-
fetchUrlTool,
|
|
1759
|
+
(0, __electric_ax_agents_runtime_tools.createBashTool)(workingDirectory),
|
|
1760
|
+
(0, __electric_ax_agents_runtime_tools.createReadFileTool)(workingDirectory, readSet),
|
|
1761
|
+
(0, __electric_ax_agents_runtime_tools.createWriteTool)(workingDirectory, readSet),
|
|
1762
|
+
(0, __electric_ax_agents_runtime_tools.createEditTool)(workingDirectory, readSet),
|
|
1763
|
+
__electric_ax_agents_runtime_tools.braveSearchTool,
|
|
1764
|
+
__electric_ax_agents_runtime_tools.fetchUrlTool,
|
|
1529
1765
|
createSpawnWorkerTool(ctx),
|
|
1766
|
+
createSpawnCoderTool(ctx),
|
|
1767
|
+
createPromptCoderTool(ctx),
|
|
1530
1768
|
...opts.docsSearchTool ? [opts.docsSearchTool] : []
|
|
1531
1769
|
];
|
|
1532
1770
|
}
|
|
@@ -1542,7 +1780,7 @@ function extractFirstUserMessage(events) {
|
|
|
1542
1780
|
return null;
|
|
1543
1781
|
}
|
|
1544
1782
|
function createAssistantHandler(options) {
|
|
1545
|
-
const { workingDirectory, streamFn, docsSupport, docsSearchTool, skillsRegistry } = options;
|
|
1783
|
+
const { workingDirectory, streamFn, docsSupport, docsSearchTool, skillsRegistry, docsUrl } = options;
|
|
1546
1784
|
const hasSkills = Boolean(skillsRegistry && skillsRegistry.catalog.size > 0);
|
|
1547
1785
|
return async function assistantHandler(ctx, wake) {
|
|
1548
1786
|
const readSet = new Set();
|
|
@@ -1592,7 +1830,8 @@ function createAssistantHandler(options) {
|
|
|
1592
1830
|
ctx.useAgent({
|
|
1593
1831
|
systemPrompt: buildHortonSystemPrompt(workingDirectory, {
|
|
1594
1832
|
hasDocsSupport: Boolean(docsSupport),
|
|
1595
|
-
hasSkills
|
|
1833
|
+
hasSkills,
|
|
1834
|
+
docsUrl
|
|
1596
1835
|
}),
|
|
1597
1836
|
model: HORTON_MODEL,
|
|
1598
1837
|
tools,
|
|
@@ -1620,6 +1859,9 @@ function createAssistantHandler(options) {
|
|
|
1620
1859
|
}
|
|
1621
1860
|
function registerHorton(registry, options) {
|
|
1622
1861
|
const { workingDirectory, streamFn, skillsRegistry = null } = options;
|
|
1862
|
+
const docsUrl = options.docsUrl ?? process.env.HORTON_DOCS_URL;
|
|
1863
|
+
if (process.env.BRAVE_SEARCH_API_KEY) serverLog.info(`[horton] Web search: using Brave Search API`);
|
|
1864
|
+
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)`);
|
|
1623
1865
|
const docsSupport = createHortonDocsSupport(workingDirectory);
|
|
1624
1866
|
const docsSearchTool = docsSupport?.createSearchTool();
|
|
1625
1867
|
docsSupport?.ensureReady().catch((error) => {
|
|
@@ -1630,7 +1872,8 @@ function registerHorton(registry, options) {
|
|
|
1630
1872
|
streamFn,
|
|
1631
1873
|
docsSupport,
|
|
1632
1874
|
docsSearchTool,
|
|
1633
|
-
skillsRegistry
|
|
1875
|
+
skillsRegistry,
|
|
1876
|
+
docsUrl
|
|
1634
1877
|
});
|
|
1635
1878
|
registry.define(`horton`, {
|
|
1636
1879
|
description: `Friendly capable assistant — chat, code, research, dispatch`,
|
|
@@ -1684,22 +1927,22 @@ function buildToolsForWorker(tools, workingDirectory, ctx, readSet) {
|
|
|
1684
1927
|
const out = [];
|
|
1685
1928
|
for (const name of tools) switch (name) {
|
|
1686
1929
|
case `bash`:
|
|
1687
|
-
out.push(createBashTool(workingDirectory));
|
|
1930
|
+
out.push((0, __electric_ax_agents_runtime_tools.createBashTool)(workingDirectory));
|
|
1688
1931
|
break;
|
|
1689
1932
|
case `read`:
|
|
1690
|
-
out.push(createReadFileTool(workingDirectory, readSet));
|
|
1933
|
+
out.push((0, __electric_ax_agents_runtime_tools.createReadFileTool)(workingDirectory, readSet));
|
|
1691
1934
|
break;
|
|
1692
1935
|
case `write`:
|
|
1693
|
-
out.push(createWriteTool(workingDirectory, readSet));
|
|
1936
|
+
out.push((0, __electric_ax_agents_runtime_tools.createWriteTool)(workingDirectory, readSet));
|
|
1694
1937
|
break;
|
|
1695
1938
|
case `edit`:
|
|
1696
|
-
out.push(createEditTool(workingDirectory, readSet));
|
|
1939
|
+
out.push((0, __electric_ax_agents_runtime_tools.createEditTool)(workingDirectory, readSet));
|
|
1697
1940
|
break;
|
|
1698
1941
|
case `brave_search`:
|
|
1699
|
-
out.push(braveSearchTool);
|
|
1942
|
+
out.push(__electric_ax_agents_runtime_tools.braveSearchTool);
|
|
1700
1943
|
break;
|
|
1701
1944
|
case `fetch_url`:
|
|
1702
|
-
out.push(fetchUrlTool);
|
|
1945
|
+
out.push(__electric_ax_agents_runtime_tools.fetchUrlTool);
|
|
1703
1946
|
break;
|
|
1704
1947
|
case `spawn_worker`:
|
|
1705
1948
|
out.push(createSpawnWorkerTool(ctx));
|
|
@@ -2116,6 +2359,8 @@ async function createBuiltinAgentHandler(options) {
|
|
|
2116
2359
|
streamFn
|
|
2117
2360
|
});
|
|
2118
2361
|
typeNames.push(`worker`);
|
|
2362
|
+
registerCodingSession(registry, { defaultWorkingDirectory: cwd });
|
|
2363
|
+
typeNames.push(`coder`);
|
|
2119
2364
|
const runtime = (0, __electric_ax_agents_runtime.createRuntimeHandler)({
|
|
2120
2365
|
baseUrl: agentServerUrl,
|
|
2121
2366
|
serveEndpoint,
|
|
@@ -2168,7 +2413,7 @@ var BuiltinAgentsServer = class {
|
|
|
2168
2413
|
}
|
|
2169
2414
|
async start() {
|
|
2170
2415
|
if (this.server) throw new Error(`Builtin agents server already started`);
|
|
2171
|
-
return new Promise((resolve
|
|
2416
|
+
return new Promise((resolve, reject) => {
|
|
2172
2417
|
this.server = (0, node_http.createServer)((req, res) => {
|
|
2173
2418
|
this.handleRequest(req, res).catch((error) => {
|
|
2174
2419
|
serverLog.error(`[builtin-agents] unhandled request error`, error);
|
|
@@ -2201,7 +2446,7 @@ var BuiltinAgentsServer = class {
|
|
|
2201
2446
|
if (!this.bootstrap) throw new Error(`ANTHROPIC_API_KEY must be set before starting builtin agents`);
|
|
2202
2447
|
await registerBuiltinAgentTypes(this.bootstrap);
|
|
2203
2448
|
serverLog.info(`[builtin-agents] webhook handler listening at ${serveEndpoint}`);
|
|
2204
|
-
resolve
|
|
2449
|
+
resolve(this._url);
|
|
2205
2450
|
} catch (error) {
|
|
2206
2451
|
await this.stop().catch(() => {});
|
|
2207
2452
|
reject(error);
|
|
@@ -2212,13 +2457,13 @@ var BuiltinAgentsServer = class {
|
|
|
2212
2457
|
async stop() {
|
|
2213
2458
|
if (this.bootstrap) {
|
|
2214
2459
|
this.bootstrap.runtime.abortWakes();
|
|
2215
|
-
await Promise.race([this.bootstrap.runtime.drainWakes().catch(() => {}), new Promise((resolve
|
|
2460
|
+
await Promise.race([this.bootstrap.runtime.drainWakes().catch(() => {}), new Promise((resolve) => setTimeout(resolve, 5e3))]);
|
|
2216
2461
|
this.bootstrap = null;
|
|
2217
2462
|
}
|
|
2218
2463
|
if (this.server) {
|
|
2219
2464
|
const server = this.server;
|
|
2220
|
-
await new Promise((resolve
|
|
2221
|
-
server.close(() => resolve
|
|
2465
|
+
await new Promise((resolve) => {
|
|
2466
|
+
server.close(() => resolve());
|
|
2222
2467
|
});
|
|
2223
2468
|
this.server = null;
|
|
2224
2469
|
}
|
|
@@ -2227,14 +2472,14 @@ var BuiltinAgentsServer = class {
|
|
|
2227
2472
|
}
|
|
2228
2473
|
async handleRequest(req, res) {
|
|
2229
2474
|
const method = req.method?.toUpperCase();
|
|
2230
|
-
const path$
|
|
2475
|
+
const path$6 = new URL(req.url ?? `/`, `http://localhost`).pathname;
|
|
2231
2476
|
const webhookPath = this.options.webhookPath ?? DEFAULT_BUILTIN_AGENT_HANDLER_PATH;
|
|
2232
|
-
if (path$
|
|
2477
|
+
if (path$6 === `/_electric/health` && method === `GET`) {
|
|
2233
2478
|
res.writeHead(200, { "content-type": `application/json` });
|
|
2234
2479
|
res.end(JSON.stringify({ status: `ok` }));
|
|
2235
2480
|
return;
|
|
2236
2481
|
}
|
|
2237
|
-
if (path$
|
|
2482
|
+
if (path$6 === webhookPath && method === `POST` && this.bootstrap) {
|
|
2238
2483
|
await this.bootstrap.handler(req, res);
|
|
2239
2484
|
return;
|
|
2240
2485
|
}
|
|
@@ -2301,6 +2546,12 @@ exports.BuiltinAgentsServer = BuiltinAgentsServer
|
|
|
2301
2546
|
exports.DEFAULT_BUILTIN_AGENT_HANDLER_PATH = DEFAULT_BUILTIN_AGENT_HANDLER_PATH
|
|
2302
2547
|
exports.HORTON_MODEL = HORTON_MODEL
|
|
2303
2548
|
exports.WORKER_TOOL_NAMES = WORKER_TOOL_NAMES
|
|
2549
|
+
Object.defineProperty(exports, 'braveSearchTool', {
|
|
2550
|
+
enumerable: true,
|
|
2551
|
+
get: function () {
|
|
2552
|
+
return __electric_ax_agents_runtime_tools.braveSearchTool;
|
|
2553
|
+
}
|
|
2554
|
+
});
|
|
2304
2555
|
exports.buildHortonSystemPrompt = buildHortonSystemPrompt
|
|
2305
2556
|
exports.createAgentHandler = createAgentHandler
|
|
2306
2557
|
exports.createBuiltinAgentHandler = createBuiltinAgentHandler
|
|
@@ -2310,6 +2561,7 @@ exports.createSpawnWorkerTool = createSpawnWorkerTool
|
|
|
2310
2561
|
exports.generateTitle = generateTitle
|
|
2311
2562
|
exports.registerAgentTypes = registerAgentTypes
|
|
2312
2563
|
exports.registerBuiltinAgentTypes = registerBuiltinAgentTypes
|
|
2564
|
+
exports.registerCodingSession = registerCodingSession
|
|
2313
2565
|
exports.registerHorton = registerHorton
|
|
2314
2566
|
exports.registerWorker = registerWorker
|
|
2315
2567
|
exports.resolveBuiltinAgentsEntrypointOptions = resolveBuiltinAgentsEntrypointOptions
|