ai-agentmanager 1.11.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/builder.js ADDED
@@ -0,0 +1,332 @@
1
+ // The agent builder: a task or workflow in words → an analysis and an agentkit agent
2
+ // (docs/agentkit.md) with test cases, which the person reviews, tests, runs and downloads. Built
3
+ // agents live in ~/.agentmanager/built/<name>/ as ordinary agentkit folders.
4
+ import { spawn } from 'node:child_process';
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import YAML from 'yaml';
9
+ import { Agent } from './agentkit/agent.js';
10
+ import { turn as engineTurn } from './agentkit/engines.js';
11
+ import { HOST, PLATFORMS, packageAgent } from './agentkit/package.js';
12
+ import { checkAgent, loadAgent } from './agentkit/spec.js';
13
+ import { parseJsonReply } from './brief.js';
14
+ import { paths } from './config.js';
15
+
16
+ const AGENTKIT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'agentkit.js');
17
+ const root = () => path.join(paths.home, 'built');
18
+ const err = (status, message) => Object.assign(new Error(message), { status });
19
+ const now = () => new Date().toISOString();
20
+ const slug = (s) => String(s ?? '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'agent';
21
+
22
+ export function designPrompt({ task, engine, attachments = [] }) {
23
+ return [
24
+ 'You design an autonomous agent that will run continuously on its own and do one job well. It runs through',
25
+ `${engine === 'claude' ? 'Claude Code' : engine} as its engine, uses tools through MCP servers, and is reached by people (chat) and other agents (A2A, MCP).`,
26
+ 'From the task below, write the analysis and the agent. Be concrete; do not invent systems the task does not mention.',
27
+ '',
28
+ 'Reply with one JSON object only:',
29
+ '{',
30
+ ' "analysis": {"problem": "<what the job is and why>", "inputs": ["<what it receives>"], "outputs": ["<what it produces>"], "risks": ["<what could go wrong, and what needs a person>"]},',
31
+ ' "name": "<lowercase-with-dashes, 2-40 chars>", "title": "<short>", "description": "<one line>",',
32
+ ' "goal": "<what is true when it has done its job, for each input; one or two sentences>",',
33
+ ' "instructions": "<Markdown: how to do the job, step by step; what to never do; when to ask>",',
34
+ ' "tools": [{"name": "<short id>", "why": "<what it needs it for>", "command": "<MCP server command, e.g. npx>", "args": ["…"], "env": {"VAR": "${VAR}"}}],',
35
+ ' "allow": ["<engine tool names it may use without asking, e.g. Read, Grep, mcp__<tool>__*>"],',
36
+ ' "approve": ["<tools that change things in the outside world and need a person\'s yes>"],',
37
+ ' "triggers": [{"every": "30m"} | {"cron": "0 9 * * 1-5"} | {"webhook": "/hooks/<name>"} | {"watch": "./inbox"}],',
38
+ ' "tests": [{"input": "<a realistic input>", "expect": "<what a good result does or contains>"}]',
39
+ '}',
40
+ '',
41
+ 'Rules: 3 to 5 tests that cover the normal case, an edge case and a case it should refuse or escalate.',
42
+ 'Only MCP servers that really exist and fit (leave "tools" empty when none is needed). Secrets only as "${VAR}".',
43
+ 'Triggers only when the task implies running on its own (a schedule, events); chat-only agents have none.',
44
+ '',
45
+ '<task>',
46
+ task,
47
+ '</task>',
48
+ ...(attachments.length ? ['<attached_files>', ...attachments.map((a) => `--- ${a.name}\n${a.text}`), '</attached_files>'] : []),
49
+ ].join('\n');
50
+ }
51
+
52
+ export function judgePrompt({ goal, input, expect, result }) {
53
+ return [
54
+ "You check one test of an autonomous agent. Decide if the agent's result meets the expectation for the input.",
55
+ 'Be strict about substance, lenient about wording. Reply with JSON only: {"pass": true|false, "why": "<one sentence>"}.',
56
+ `<goal>\n${goal}\n</goal>`,
57
+ `<input>\n${input}\n</input>`,
58
+ `<expectation>\n${expect}\n</expectation>`,
59
+ `<result>\n${result}\n</result>`,
60
+ ].join('\n');
61
+ }
62
+
63
+ /** agent.yaml text from a design. */
64
+ export function yamlOf(d, engine) {
65
+ const tools = Object.fromEntries((d.tools ?? []).filter((t) => t?.name && t.command).map((t) => [slug(t.name), { command: t.command, ...(t.args?.length ? { args: t.args } : {}), ...(t.env && Object.keys(t.env).length ? { env: t.env } : {}) }]));
66
+ const doc = {
67
+ name: slug(d.name),
68
+ title: d.title || d.name,
69
+ description: d.description ?? '',
70
+ goal: d.goal,
71
+ instructions: 'instructions.md',
72
+ engine,
73
+ tools,
74
+ allow: d.allow ?? [],
75
+ approve: d.approve ?? [],
76
+ triggers: d.triggers ?? [],
77
+ loop: { plan: true, check: true, maxSteps: 4 },
78
+ memory: true,
79
+ interfaces: { http: { port: 0 }, a2a: true, acp: true, mcp: true },
80
+ };
81
+ return YAML.stringify(doc, { lineWidth: 0 });
82
+ }
83
+
84
+ export class Builder {
85
+ /** `oneShot(prompt)` answers a design or judge prompt (the daemon's writer engine). */
86
+ /** `reportEnv()`: settings that make an agent started here report to this daemon. */
87
+ constructor({ oneShot, env = process.env, runTurn = engineTurn, pack = packageAgent, reportEnv = () => ({}) }) {
88
+ this.reportEnv = reportEnv;
89
+ this.oneShot = oneShot;
90
+ this.env = env;
91
+ this.runTurn = runTurn;
92
+ this.pack = pack;
93
+ this.procs = new Map(); // name -> child process of `agentkit run`
94
+ this.pending = new Map(); // name -> what's in progress (designing, testing)
95
+ }
96
+
97
+ dir(name) {
98
+ if (!/^[a-z][a-z0-9-]{1,40}$/.test(String(name))) throw err(400, 'Unknown agent');
99
+ return path.join(root(), name);
100
+ }
101
+
102
+ meta(name) {
103
+ try {
104
+ return JSON.parse(fs.readFileSync(path.join(this.dir(name), 'build.json'), 'utf8'));
105
+ } catch {
106
+ return null;
107
+ }
108
+ }
109
+
110
+ saveMeta(name, patch) {
111
+ const next = { ...this.meta(name), ...patch, updatedAt: now() };
112
+ fs.writeFileSync(path.join(this.dir(name), 'build.json'), JSON.stringify(next, null, 2));
113
+ return next;
114
+ }
115
+
116
+ list() {
117
+ let names = [];
118
+ try {
119
+ names = fs.readdirSync(root()).filter((n) => fs.existsSync(path.join(root(), n, 'build.json')));
120
+ } catch {}
121
+ return names.map((n) => this.view(n)).sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)));
122
+ }
123
+
124
+ view(name) {
125
+ const m = this.meta(name);
126
+ if (!m) throw err(404, `No built agent "${name}"`);
127
+ const dir = this.dir(name);
128
+ const read = (f) => (fs.existsSync(path.join(dir, f)) ? fs.readFileSync(path.join(dir, f), 'utf8') : '');
129
+ let spec = null;
130
+ let specError = null;
131
+ try {
132
+ spec = loadAgent(dir, { env: this.env });
133
+ } catch (e) {
134
+ specError = e.message;
135
+ }
136
+ const p = this.procs.get(name);
137
+ let runs = [];
138
+ if (spec) runs = new Agent(spec, { env: this.env }).runs(20);
139
+ return {
140
+ ...m,
141
+ name,
142
+ title: spec?.title ?? name,
143
+ description: spec?.description ?? '',
144
+ dir,
145
+ yaml: read('agent.yaml'),
146
+ instructionsText: read('instructions.md'),
147
+ specError,
148
+ engine: spec?.engine ?? null,
149
+ triggers: spec?.triggers.map((t) => t.label) ?? [],
150
+ missingEnv: spec?.missingEnv ?? [],
151
+ pending: this.pending.get(name) ?? null,
152
+ running: p ? { pid: p.child.pid, url: p.url, since: p.since } : null,
153
+ runs,
154
+ platforms: PLATFORMS.filter((x) => process.platform === 'darwin' || !x.startsWith('macos-')),
155
+ host: HOST,
156
+ // Executables built since the last edit that are still there.
157
+ executables: Object.fromEntries(Object.entries(m.executables ?? {}).filter(([, x]) => fs.existsSync(path.join(dir, 'dist', x.file)))),
158
+ };
159
+ }
160
+
161
+ /** Design an agent from a task (one model call); writes the folder and returns it. */
162
+ async design({ task, engine = 'claude', attachments = [] }) {
163
+ task = String(task ?? '').trim();
164
+ if (!task) throw err(400, 'Describe the task or workflow');
165
+ if (!['claude', 'codex', 'muse'].includes(engine) && !/^acp:[a-z0-9-]+$/.test(engine)) throw err(400, 'engine: claude, codex, muse or acp:<name>');
166
+ const d = parseJsonReply(await this.oneShot(designPrompt({ task, engine, attachments })));
167
+ if (!d.goal || !d.name) throw err(502, 'The design was missing a name or goal; try again');
168
+ let name = slug(d.name);
169
+ for (let i = 2; fs.existsSync(path.join(root(), name)); i++) name = `${slug(d.name).slice(0, 36)}-${i}`;
170
+ const dir = path.join(root(), name);
171
+ fs.mkdirSync(dir, { recursive: true });
172
+ fs.writeFileSync(path.join(dir, 'agent.yaml'), yamlOf({ ...d, name }, engine));
173
+ fs.writeFileSync(path.join(dir, 'instructions.md'), String(d.instructions ?? '').trim() + '\n');
174
+ const tests = (d.tests ?? []).filter((t) => t?.input).slice(0, 8).map((t) => ({ input: String(t.input), expect: String(t.expect ?? '') }));
175
+ fs.writeFileSync(path.join(dir, 'tests.yaml'), YAML.stringify(tests));
176
+ // Check it loads; a broken design is kept so the person can fix it.
177
+ let specError = null;
178
+ try {
179
+ checkAgent(YAML.parse(fs.readFileSync(path.join(dir, 'agent.yaml'), 'utf8')), { dir, env: this.env });
180
+ } catch (e) {
181
+ specError = e.message;
182
+ }
183
+ this.saveMeta(name, { task, analysis: d.analysis ?? null, tools: (d.tools ?? []).map((t) => ({ name: t.name, why: t.why ?? '' })), tests, results: null, status: specError ? 'needs-fixing' : 'designed', createdAt: now() });
184
+ return this.view(name);
185
+ }
186
+
187
+ /** Save edits to agent.yaml, the instructions or the tests (each checked before it's written). */
188
+ update(name, { yaml, instructions, tests } = {}) {
189
+ const dir = this.dir(name);
190
+ if (!this.meta(name)) throw err(404, `No built agent "${name}"`);
191
+ if (yaml != null) {
192
+ let raw;
193
+ try {
194
+ raw = YAML.parse(String(yaml));
195
+ } catch (e) {
196
+ throw err(400, `agent.yaml: ${e.message.split('\n')[0]}`);
197
+ }
198
+ if (raw?.name !== name) throw err(400, `agent.yaml: keep the name "${name}" (it is the agent's folder)`);
199
+ fs.writeFileSync(path.join(dir, 'instructions.md'), instructions != null ? String(instructions) : fs.readFileSync(path.join(dir, 'instructions.md'), 'utf8'));
200
+ try {
201
+ checkAgent(raw, { dir, env: this.env });
202
+ } catch (e) {
203
+ throw err(400, e.message);
204
+ }
205
+ fs.writeFileSync(path.join(dir, 'agent.yaml'), String(yaml));
206
+ } else if (instructions != null) fs.writeFileSync(path.join(dir, 'instructions.md'), String(instructions));
207
+ if (tests != null) {
208
+ const list = (Array.isArray(tests) ? tests : []).filter((t) => t?.input).slice(0, 8).map((t) => ({ input: String(t.input), expect: String(t.expect ?? '') }));
209
+ fs.writeFileSync(path.join(dir, 'tests.yaml'), YAML.stringify(list));
210
+ this.saveMeta(name, { tests: list });
211
+ }
212
+ // Executables built before carry the old files; build them again after an edit.
213
+ if (yaml != null || instructions != null || tests != null) {
214
+ fs.rmSync(path.join(dir, 'dist'), { recursive: true, force: true });
215
+ this.saveMeta(name, { executables: {} });
216
+ }
217
+ return this.view(name);
218
+ }
219
+
220
+ /** Run every test through the real runtime, and judge each result against its expectation. */
221
+ async test(name) {
222
+ const dir = this.dir(name);
223
+ if (this.pending.get(name)) throw err(409, `Already ${this.pending.get(name)}`);
224
+ const spec = loadAgent(dir, { env: this.env });
225
+ const tests = YAML.parse(fs.readFileSync(path.join(dir, 'tests.yaml'), 'utf8') || '[]') ?? [];
226
+ if (!tests.length) throw err(400, 'No test cases; add some first');
227
+ this.pending.set(name, 'testing');
228
+ this.saveMeta(name, { status: 'testing' });
229
+ try {
230
+ // Tests don't wait for people: approval tools are simply not available in them.
231
+ const agent = new Agent({ ...spec, triggers: [], report: null }, { env: this.env, engineTurn: this.runTurn, approvals: 'deny' });
232
+ const results = [];
233
+ for (const t of tests) {
234
+ const r = await agent.run(t.input, { source: 'test' });
235
+ let verdict = { pass: false, why: 'The run failed' };
236
+ if (r.status !== 'failed') {
237
+ try {
238
+ const v = parseJsonReply(await this.oneShot(judgePrompt({ goal: spec.goal, input: t.input, expect: t.expect, result: r.result })));
239
+ verdict = { pass: v.pass === true, why: String(v.why ?? '') };
240
+ } catch (e) {
241
+ verdict = { pass: false, why: `Could not judge: ${e.message}` };
242
+ }
243
+ }
244
+ results.push({ input: t.input, expect: t.expect, result: r.result, status: r.status, costUsd: r.costUsd, ...verdict });
245
+ }
246
+ const passed = results.filter((r) => r.pass).length;
247
+ this.saveMeta(name, { results: { at: now(), passed, total: results.length, list: results }, status: passed === results.length ? 'tested' : 'failing' });
248
+ } catch (e) {
249
+ this.saveMeta(name, { status: 'failing', results: { at: now(), passed: 0, total: 0, list: [], error: e.message } });
250
+ } finally {
251
+ this.pending.delete(name);
252
+ }
253
+ return this.view(name);
254
+ }
255
+
256
+ /** Build its single executable for a platform into dist/ (in the background; the view says when). */
257
+ package(name, platform = HOST) {
258
+ const dir = this.dir(name);
259
+ if (!this.meta(name)) throw err(404, `No built agent "${name}"`);
260
+ if (this.pending.get(name)) throw err(409, `Already ${this.pending.get(name)}`);
261
+ if (!PLATFORMS.includes(platform)) throw err(400, `platform: one of ${PLATFORMS.join(', ')}`);
262
+ if (platform.startsWith('macos-') && process.platform !== 'darwin') throw err(400, 'macOS executables are built on a Mac');
263
+ loadAgent(dir, { env: this.env });
264
+ this.pending.set(name, `packaging for ${platform}`);
265
+ this.saveMeta(name, { packageError: null });
266
+ return this.#pack(name, dir, platform);
267
+ }
268
+
269
+ async #pack(name, dir, platform) {
270
+ try {
271
+ const r = await this.pack(dir, { outDir: path.join(dir, 'dist'), platform });
272
+ const executables = { ...this.meta(name).executables, [platform]: { file: path.basename(r.file), size: r.size, at: now() } };
273
+ this.saveMeta(name, { executables });
274
+ } catch (e) {
275
+ this.saveMeta(name, { packageError: `${platform}: ${e.message}` });
276
+ } finally {
277
+ this.pending.delete(name);
278
+ }
279
+ return this.view(name);
280
+ }
281
+
282
+ /** The path of a built executable, for download. */
283
+ executable(name, platform) {
284
+ const x = this.view(name).executables[platform];
285
+ if (!x) throw err(404, `No ${platform} executable built yet`);
286
+ return path.join(this.dir(name), 'dist', x.file);
287
+ }
288
+
289
+ /** Run it continuously on this computer (`agentkit run`); its output goes to agent.log. */
290
+ start(name) {
291
+ const dir = this.dir(name);
292
+ if (this.procs.has(name)) return this.view(name);
293
+ loadAgent(dir, { env: this.env });
294
+ const log = fs.openSync(path.join(dir, 'agent.log'), 'a');
295
+ const child = spawn(process.execPath, [AGENTKIT, 'run', dir], { env: { ...this.env, ...this.reportEnv() }, stdio: ['ignore', log, log], detached: false });
296
+ const entry = { child, url: null, since: now() };
297
+ this.procs.set(name, entry);
298
+ // Its chat address, from the log line it prints when listening.
299
+ const watch = setInterval(() => {
300
+ const m = /chat and API: (http:\/\/\S+)/.exec(fs.readFileSync(path.join(dir, 'agent.log'), 'utf8').split('\n').slice(-40).join('\n'));
301
+ if (m) {
302
+ entry.url = m[1];
303
+ clearInterval(watch);
304
+ }
305
+ }, 300);
306
+ setTimeout(() => clearInterval(watch), 20_000);
307
+ child.on('exit', () => {
308
+ clearInterval(watch);
309
+ if (this.procs.get(name) === entry) this.procs.delete(name);
310
+ this.saveMeta(name, { lastStoppedAt: now() });
311
+ });
312
+ this.saveMeta(name, { status: this.meta(name).status === 'tested' ? 'running' : this.meta(name).status, lastStartedAt: now() });
313
+ return this.view(name);
314
+ }
315
+
316
+ stop(name) {
317
+ const p = this.procs.get(name);
318
+ if (p) p.child.kill('SIGTERM');
319
+ this.procs.delete(name);
320
+ return this.view(name);
321
+ }
322
+
323
+ stopAll() {
324
+ for (const name of [...this.procs.keys()]) this.stop(name);
325
+ }
326
+
327
+ remove(name) {
328
+ this.stop(name);
329
+ fs.rmSync(this.dir(name), { recursive: true, force: true });
330
+ return { ok: true };
331
+ }
332
+ }
package/src/manager.js CHANGED
@@ -1797,6 +1797,11 @@ export class AgentManager extends EventEmitter {
1797
1797
  return [String(intent ?? '').trim(), attachmentNote(files)].filter(Boolean).join('\n\n');
1798
1798
  }
1799
1799
 
1800
+ /** Staged uploads as text, for a model to read (the builder's attachments): name and up to 100 KB each. */
1801
+ stagedText(attachments) {
1802
+ return stagedFiles(attachments).map((f) => ({ name: path.basename(f).replace(/^\d{4}-\d\d-\d\dT[\d-]+Z-[0-9a-f]{6}-/, ''), text: fs.readFileSync(f, 'utf8').slice(0, 100_000) }));
1803
+ }
1804
+
1800
1805
  /** A file attached before its agent exists (New agents, Ask); create() copies it to the agent. */
1801
1806
  stageUpload(name, data) {
1802
1807
  fs.mkdirSync(stagedDir(), { recursive: true });
package/src/server.js CHANGED
@@ -5,6 +5,7 @@ import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import { createRequire } from 'node:module';
7
7
  import { fileURLToPath } from 'node:url';
8
+ import { spawn } from 'node:child_process';
8
9
  import express from 'express';
9
10
  import { WebSocketServer } from 'ws';
10
11
  import { ensureHome, HOST, loadConfig, paths, PORT, saveConfig } from './config.js';
@@ -35,6 +36,8 @@ import * as remote from './remote.js';
35
36
  import * as service from './service.js';
36
37
  import { jiraView, saveJira } from './jira.js';
37
38
  import { CONTAINER_ENGINES, buildImage, claudeToken, dockerStatus, isBuilding, saveSecrets } from './container.js';
39
+ import { AgentkitReports } from './agentkit-reports.js';
40
+ import { Builder } from './builder.js';
38
41
  import { Store } from './store.js';
39
42
  import { about, latestRelease } from './about.js';
40
43
 
@@ -64,8 +67,9 @@ function isAllowedOrigin(origin, port) {
64
67
  const PUBLIC_REMOTE_API = new Set(['POST /api/login', 'GET /api/session']);
65
68
  // Updates are not here: a signed-in device (a phone) can install the newest release too. It only
66
69
  // ever installs an official release from where this copy came from (git tag or npm) and restarts.
67
- const LOCAL_ONLY_API = /^\/api\/(remote(\/|$)|notify(\/|$)|hub(\/|$)|triggers(\/|$)|service$|jira$|isolation\/|editors$|agents\/[\w-]+\/open-in$|shutdown$)/;
70
+ const LOCAL_ONLY_API = /^\/api\/(remote(\/|$)|notify(\/|$)|hub(\/|$)|triggers(\/|$)|service$|jira$|isolation\/|editors$|agentkit\/connect$|agents\/[\w-]+\/open-in$|shutdown$)/;
68
71
  const HOOK_PATH = '/api/hooks/agents';
72
+ const REPORT_PATH = '/api/agentkit/report';
69
73
  const NO_REPO_KINDS = new Set(['general', 'assistant']);
70
74
 
71
75
  export async function startServer({ port = PORT, host = HOST } = {}) {
@@ -162,6 +166,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
162
166
  return req.device ? null : 'Sign in required';
163
167
  }
164
168
 
169
+ const reports = new AgentkitReports();
165
170
  const app = express();
166
171
  app.disable('x-powered-by');
167
172
  app.use((req, res, next) => {
@@ -171,10 +176,14 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
171
176
  // The webhook signs in with its token instead of a device session or the client header.
172
177
  const bearer = /^Bearer (.+)$/i.exec(req.headers.authorization ?? '')?.[1];
173
178
  const hook = req.method === 'POST' && req.url.split('?')[0] === HOOK_PATH && tokenMatches(req.headers['x-agentmgr-token'] ?? bearer, config.triggers?.webhook?.enabled ? config.triggers.webhook.token : null);
179
+ // So do agents built with agentkit reporting in (from this computer or another one).
180
+ const reportPath = req.method === 'POST' && req.url.split('?')[0] === REPORT_PATH;
181
+ const reporting = reportPath && tokenMatches(bearer, reports.token);
174
182
  const why = denied(req);
175
- if (why && !(hook && why === 'Sign in required')) return res.status(why === 'Sign in required' ? 401 : 403).json({ error: why });
183
+ if (why && !((hook || reporting) && why === 'Sign in required')) return res.status(why === 'Sign in required' ? 401 : 403).json({ error: why });
176
184
  if (req.url.split('?')[0] === HOOK_PATH && !hook) return res.status(401).json({ error: 'Bad or missing token' });
177
- if (!hook && !['GET', 'HEAD'].includes(req.method) && req.headers[CLIENT_HEADER] !== '1') {
185
+ if (reportPath && !reporting) return res.status(401).json({ error: 'Bad or missing report token' });
186
+ if (!hook && !reporting && !['GET', 'HEAD'].includes(req.method) && req.headers[CLIENT_HEADER] !== '1') {
178
187
  return res.status(403).json({ error: `Missing ${CLIENT_HEADER} header` });
179
188
  }
180
189
  next();
@@ -516,6 +525,53 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
516
525
  api.get('/agents/:id/memory', wrap((req) => memory.read(req.params.id)));
517
526
  api.put('/agents/:id/memory', wrap((req) => memory.write(req.params.id, req.body?.text)));
518
527
  api.post('/agents/:id/learn', wrap((req) => memory.learn(req.params.id, req.body?.text, { by: req.headers['x-agentmgr-agent'] ? undefined : 'you' })));
528
+ // The agent builder (agentkit agents designed from a task): design, edit, test, run, download.
529
+ // Agents started here report to this daemon (runs, cost, approvals).
530
+ const builder = new Builder({ oneShot: (prompt) => manager.oneShot(null, prompt, { ...manager.writerFor({}), timeoutMs: 300_000 }), reportEnv: () => ({ AGENTKIT_REPORT_URL: `http://127.0.0.1:${port}`, AGENTKIT_REPORT_TOKEN: reports.reportToken() }) });
531
+ api.post('/agentkit/report', wrap((req) => reports.report(req.body ?? {})));
532
+ api.get('/agentkit/agents', wrap(() => reports.list()));
533
+ api.post('/agentkit/agents/:key/approvals/:id', wrap((req) => reports.decide(req.params.key, req.params.id, req.body?.allow === true, req.device ? `${req.device.name ?? 'a signed-in device'}` : 'you')));
534
+ api.delete('/agentkit/agents/:key', wrap((req) => reports.forget(req.params.key)));
535
+ // What an agent elsewhere needs to report here (this computer only: it shows the token).
536
+ api.get('/agentkit/connect', wrap(() => ({ token: reports.reportToken(), local: `http://127.0.0.1:${port}`, remote: remoteServer ? remote.remoteUrls(remotePort).map((u) => u.url) : [], cert: remoteServer ? remote.certificateFingerprint() : null })));
537
+ api.get('/builder', wrap(() => builder.list()));
538
+ api.post('/builder', wrap((req) => builder.design({ task: req.body?.task, engine: req.body?.engine || 'claude', attachments: req.body?.attachments?.length ? manager.stagedText(req.body.attachments) : [] })));
539
+ api.get('/builder/:name', wrap((req) => builder.view(req.params.name)));
540
+ api.put('/builder/:name', wrap((req) => builder.update(req.params.name, req.body ?? {})));
541
+ api.post('/builder/:name/test', wrap((req) => {
542
+ builder.test(req.params.name).catch(() => {}); // in the background; the view says when it's done
543
+ return new Promise((r) => setTimeout(() => r(builder.view(req.params.name)), 50));
544
+ }));
545
+ api.post('/builder/:name/package', wrap((req) => {
546
+ builder.package(req.params.name, req.body?.platform || undefined).catch(() => {}); // checks first, then builds in the background
547
+ return new Promise((r) => setTimeout(() => r(builder.view(req.params.name)), 50));
548
+ }));
549
+ api.get('/builder/:name/executable/:platform', (req, res) => {
550
+ let file;
551
+ try {
552
+ file = builder.executable(req.params.name, req.params.platform);
553
+ } catch (e) {
554
+ return res.status(e.status ?? 500).json({ error: e.message });
555
+ }
556
+ res.download(file, path.basename(file));
557
+ });
558
+ api.post('/builder/:name/start', wrap((req) => builder.start(req.params.name)));
559
+ api.post('/builder/:name/stop', wrap((req) => builder.stop(req.params.name)));
560
+ api.delete('/builder/:name', wrap((req) => builder.remove(req.params.name)));
561
+ // The agent's folder as a .tar.gz (its own files; not its runs, memory or log).
562
+ api.get('/builder/:name/download', (req, res) => {
563
+ let dir;
564
+ try {
565
+ dir = builder.view(req.params.name).dir;
566
+ } catch (e) {
567
+ return res.status(e.status ?? 500).json({ error: e.message });
568
+ }
569
+ res.setHeader('content-type', 'application/gzip');
570
+ res.setHeader('content-disposition', `attachment; filename="${req.params.name}.tar.gz"`);
571
+ const tar = spawn('tar', ['-czf', '-', '--exclude', '.agentkit', '--exclude', 'agent.log', '--exclude', 'build.json', '--exclude', 'work', '--exclude', 'dist', '-C', path.dirname(dir), path.basename(dir)]);
572
+ tar.stdout.pipe(res);
573
+ tar.on('error', () => res.end());
574
+ });
519
575
  // Isolation: Docker, the agent image, the Claude token for containers, and the default for new agents.
520
576
  let buildError = null;
521
577
  const isolationView = async () => ({ ...(await dockerStatus(config)), building: isBuilding(), buildError, hasClaudeToken: Boolean(claudeToken()), engines: [...CONTAINER_ENGINES], default: config.isolation?.default ?? null });
@@ -751,7 +807,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
751
807
  const eventSinks = new Set();
752
808
  api.get('/events/stream', (req, res) => {
753
809
  const send = sse(req, res);
754
- send({ t: 'snapshot', agents: manager.list(), backlog: backlog.view(), projects: manager.listProjects(), races: races.list(), teams: teams.list() });
810
+ send({ t: 'snapshot', agents: manager.list(), backlog: backlog.view(), projects: manager.listProjects(), races: races.list(), teams: teams.list(), built: reports.list() });
755
811
  eventSinks.add(send);
756
812
  req.on('close', () => eventSinks.delete(send));
757
813
  });
@@ -844,6 +900,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
844
900
  for (const send of eventSinks) send(msg);
845
901
  };
846
902
  manager.on('change', (agent) => broadcast({ t: 'agent', agent }));
903
+ reports.on('change', () => broadcast({ t: 'built', reports: reports.list() }));
847
904
  manager.on('removed', (id) => {
848
905
  broadcast({ t: 'removed', id });
849
906
  live.closeAgent(id).catch(() => {});
@@ -880,7 +937,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
880
937
  const url = new URL(req.url, 'http://x');
881
938
  if (url.pathname === '/ws/events') {
882
939
  eventClients.add(ws);
883
- ws.send(JSON.stringify({ t: 'snapshot', agents: manager.list(), backlog: backlog.view(), projects: manager.listProjects(), races: races.list(), teams: teams.list() }));
940
+ ws.send(JSON.stringify({ t: 'snapshot', agents: manager.list(), backlog: backlog.view(), projects: manager.listProjects(), races: races.list(), teams: teams.list(), built: reports.list() }));
884
941
  ws.on('close', () => eventClients.delete(ws));
885
942
  return;
886
943
  }
@@ -967,6 +1024,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
967
1024
  updates.close();
968
1025
  assistant.close();
969
1026
  console.log(`[agentmgr] shutting down (${reason}); closing agents so their sessions are saved`);
1027
+ builder.stopAll();
970
1028
  await manager.stopAll({ final: true });
971
1029
  await manager.flush().catch((err) => console.error(`[agentmgr] final flush failed: ${err.message}`));
972
1030
  try {