@chapterdev/mcp-dev-studio 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +79 -2
  3. package/bin/mcp-dev-studio.js +2 -0
  4. package/dist/agent/fill.js +69 -0
  5. package/dist/agent/judge.js +24 -0
  6. package/dist/agent/loop-skill.js +103 -0
  7. package/dist/agent/providers.js +162 -0
  8. package/dist/agent/runner.js +252 -0
  9. package/dist/agent/starters.js +47 -0
  10. package/dist/analysis/estimate.js +7 -0
  11. package/dist/analysis/lint.js +149 -0
  12. package/dist/analysis/prefill.js +411 -0
  13. package/dist/analysis/surface.js +268 -0
  14. package/dist/analysis/tokens.js +69 -0
  15. package/dist/analytics/aggregate.js +106 -0
  16. package/dist/analytics/recorder.js +75 -0
  17. package/dist/analytics/tracker.js +58 -0
  18. package/dist/cli.js +264 -0
  19. package/dist/demo/seed.js +138 -0
  20. package/dist/demo/server.js +282 -0
  21. package/dist/demo/stdio.js +7 -0
  22. package/dist/discover.js +317 -0
  23. package/dist/eval/attempts.js +54 -0
  24. package/dist/eval/cli.js +183 -0
  25. package/dist/eval/journeys.js +161 -0
  26. package/dist/hosts/claude-code.js +403 -0
  27. package/dist/hosts/codex.js +328 -0
  28. package/dist/hosts/index.js +85 -0
  29. package/dist/hosts/models.js +51 -0
  30. package/dist/mcp/connection.js +330 -0
  31. package/dist/server/app.js +602 -0
  32. package/dist/server/listen.js +12 -0
  33. package/dist/skills/skills.js +203 -0
  34. package/dist/store-watch.js +75 -0
  35. package/dist/store.js +327 -0
  36. package/dist/types.js +3 -0
  37. package/dist/ui/assets/index-D9hmZSmq.js +55 -0
  38. package/dist/ui/assets/index-G_SSBQNV.css +2 -0
  39. package/dist/ui/index.html +17 -0
  40. package/dist/workspace.js +195 -0
  41. package/package.json +79 -4
@@ -0,0 +1,602 @@
1
+ // The studio's local HTTP API (+ the built UI). Bound to 127.0.0.1 only.
2
+ import express from 'express';
3
+ import { execFileSync } from 'node:child_process';
4
+ import { existsSync, readdirSync } from 'node:fs';
5
+ import { join, relative } from 'node:path';
6
+ import { autoPick, discover } from '../discover.js';
7
+ import { watchStore } from '../store-watch.js';
8
+ import { modelOptions } from '../hosts/models.js';
9
+ import { changesBetween, movement } from '../eval/attempts.js';
10
+ import { buildProductMap } from '../analysis/surface.js';
11
+ import { lintSurface, lintTraffic } from '../analysis/lint.js';
12
+ import { estimateToolCost, exactToolTokens } from '../analysis/tokens.js';
13
+ import { draftSkill, lintSkill, polishSkill } from '../skills/skills.js';
14
+ import { addSummaries } from '../agent/runner.js';
15
+ import { providerFor } from '../agent/providers.js';
16
+ import { average, loadSkills as loadSkillIds, ratesOf, runJourney, runTrial, slugify } from '../eval/journeys.js';
17
+ import { aggregate } from '../analytics/aggregate.js';
18
+ import { anyAgentAvailable, askAgent, createSession, detectHosts } from '../hosts/index.js';
19
+ import { coerceArgs, planPrefill } from '../analysis/prefill.js';
20
+ import { fillWithModel } from '../agent/fill.js';
21
+ import { DEMO_STARTERS, startersKey, templateStarters, writeStarters } from '../agent/starters.js';
22
+ export function createApp({ workspace: ws, uiDir, version, ingestUrl, sessionFactory }) {
23
+ const app = express();
24
+ // The API can start processes (connect, reset commands), so only this machine's
25
+ // own pages may use it. A Host check stops DNS rebinding (evil.example → 127.0.0.1);
26
+ // an Origin check stops other sites' pages from posting. CLIs and proxies send no Origin.
27
+ app.use((req, res, next) => {
28
+ if (!isLocalHost(req.headers.host))
29
+ return void res.status(403).json({ error: 'MCP Dev Studio only answers on localhost' });
30
+ const origin = req.headers.origin;
31
+ if (origin && !isLocalOrigin(origin))
32
+ return void res.status(403).json({ error: 'Cross-origin requests are not allowed' });
33
+ next();
34
+ });
35
+ app.use(express.json({ limit: '20mb' }));
36
+ /** Live Playground conversations. `chat` groups the agents answering side by side, so history reopens them together. */
37
+ const sessions = new Map();
38
+ // The server can change under us (connect screen); these follow the workspace.
39
+ let { conn, store, skills } = ws;
40
+ const hostDeps = () => ({ conn, store, ingestUrl });
41
+ const newSession = (spec, source = 'sandbox') => (sessionFactory ?? createSession)(spec, { ...hostDeps(), source });
42
+ // Close conversations nobody has touched for 30 minutes (each one holds a Claude Code process and a server).
43
+ setInterval(() => {
44
+ for (const [id, x] of sessions)
45
+ if (Date.now() - x.lastUsed > 30 * 60_000)
46
+ void x.session.close(), sessions.delete(id);
47
+ }, 60_000).unref();
48
+ const clients = new Set();
49
+ let exact;
50
+ const broadcast = (event, data) => {
51
+ for (const res of clients)
52
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
53
+ };
54
+ /** The UI never needs auth headers; keep tokens out of the browser. */
55
+ const publicState = (s = conn.state) => (s.target.kind === 'http' && s.target.headers ? { ...s, target: { ...s.target, headers: Object.fromEntries(Object.keys(s.target.headers).map((k) => [k, '•••'])) } } : s);
56
+ const attach = () => {
57
+ conn.on('state', (s) => broadcast('state', publicState(s)));
58
+ conn.on('surface', (surface, diff) => broadcast('surface', { hash: surface.hash, diff }));
59
+ conn.on('hot-reload', (file) => broadcast('hot-reload', { file }));
60
+ };
61
+ attach();
62
+ // Files changed by anyone (the UI, Claude in a terminal, CI results) reach the page as they land.
63
+ let unwatch = () => { };
64
+ const rewatch = () => {
65
+ unwatch();
66
+ unwatch = watchStore(store.root, skills.dir, (areas) => broadcast('store', { areas }), store.testsDir);
67
+ };
68
+ rewatch();
69
+ ws.on('tests-moved', () => (rewatch(), broadcast('store', { areas: ['tests'] })));
70
+ ws.on('switch', () => {
71
+ ;
72
+ ({ conn, store, skills } = ws);
73
+ rewatch();
74
+ exact = undefined;
75
+ for (const [id, x] of sessions)
76
+ void x.session.close(), sessions.delete(id);
77
+ attach();
78
+ broadcast('state', publicState());
79
+ });
80
+ const keyFor = (p) => store.apiKey(p);
81
+ /** A text-only model for one-shot jobs: the API if there's a key, else Claude Code on the developer's plan. */
82
+ const writer = () => {
83
+ const s = store.settings();
84
+ const key = keyFor(s.provider);
85
+ if (key)
86
+ return providerFor(s.provider, key);
87
+ const no = () => Promise.reject(new Error('not supported'));
88
+ return { id: 'anthropic', chat: no, json: no, text: async ({ system, prompt }) => (await askAgent(prompt, { system })).result };
89
+ };
90
+ const requireSurface = () => {
91
+ if (!conn.surface)
92
+ throw httpError(503, 'Not connected to an MCP server');
93
+ return conn.surface;
94
+ };
95
+ const loadSkills = (ids = [], inline = []) => [...loadSkillIds(ids, skills), ...inline];
96
+ // ── state ──
97
+ app.get('/api/state', (_req, res) => {
98
+ res.json({
99
+ version,
100
+ connection: publicState(),
101
+ surface: conn.surface,
102
+ settings: store.settings(),
103
+ keys: { anthropic: !!keyFor('anthropic'), openai: !!keyFor('openai'), anthropicFromEnv: !!process.env.ANTHROPIC_API_KEY, openaiFromEnv: !!process.env.OPENAI_API_KEY },
104
+ storeDir: store.root,
105
+ skillsDir: skills.dir,
106
+ project: ws.project,
107
+ tests: { shared: store.testsShared, dir: store.testsDir, canShare: !ws.demo },
108
+ });
109
+ });
110
+ // ── choosing a server ──
111
+ // Candidates keep their headers server-side; the UI only sees ids.
112
+ let found = [];
113
+ const publicCandidate = (c) => ({ ...c, target: c.target.kind === 'http' ? { kind: 'http', url: c.target.url, hasHeaders: !!c.target.headers } : { kind: 'stdio', command: c.target.command, cwd: c.target.cwd } });
114
+ app.get('/api/discover', wrap(async (_req, res) => {
115
+ const [list, hosts] = await Promise.all([discover(ws.project), detectHosts(store)]);
116
+ found = list;
117
+ res.json({ project: ws.project, candidates: list.map(publicCandidate), suggested: autoPick(list)?.id, agents: hosts.filter((h) => h.id !== 'api'), saved: !!store.savedServer() });
118
+ }));
119
+ app.post('/api/connect', wrap(async (req, res) => {
120
+ const body = req.body;
121
+ const bearer = body.token?.trim() ? { Authorization: /^bearer /i.test(body.token.trim()) ? body.token.trim() : `Bearer ${body.token.trim()}` } : undefined;
122
+ let choice;
123
+ if (body.demo)
124
+ choice = { demo: true, target: { kind: 'stdio', command: '' } };
125
+ else if (body.id) {
126
+ const c = found.find((x) => x.id === body.id);
127
+ if (!c)
128
+ throw httpError(404, 'That server is no longer listed; refresh');
129
+ const target = c.target.kind === 'http' && bearer ? { ...c.target, headers: { ...c.target.headers, ...bearer } } : c.target;
130
+ choice = { name: c.name, target, start: c.start, save: true };
131
+ }
132
+ else if (body.url?.trim()) {
133
+ choice = { target: { kind: 'http', url: body.url.trim(), ...(bearer ? { headers: bearer } : {}) }, start: body.start?.trim() ? { command: body.start.trim(), cwd: ws.project } : undefined, save: true };
134
+ }
135
+ else if (body.command?.trim()) {
136
+ choice = { target: { kind: 'stdio', command: body.command.trim(), cwd: body.cwd || ws.project }, save: true };
137
+ }
138
+ else
139
+ throw httpError(400, 'Pick a server, or enter a command or URL');
140
+ try {
141
+ await ws.open(choice);
142
+ }
143
+ catch (e) {
144
+ const c = ws.conn.state;
145
+ throw httpError(400, e.message + (c.stderr.length ? `\n\n${c.stderr.slice(-12).join('\n')}` : ''));
146
+ }
147
+ res.json({ connection: publicState(), surface: conn.surface });
148
+ }));
149
+ app.get('/api/events', (req, res) => {
150
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' });
151
+ res.write(`event: state\ndata: ${JSON.stringify(publicState())}\n\n`);
152
+ clients.add(res);
153
+ const ping = setInterval(() => res.write(': ping\n\n'), 15000);
154
+ req.on('close', () => {
155
+ clearInterval(ping);
156
+ clients.delete(res);
157
+ });
158
+ });
159
+ app.post('/api/reconnect', wrap(async (_req, res) => {
160
+ if (!conn.state.unset)
161
+ await conn.reconnect().catch(() => { });
162
+ res.json({ connection: publicState(), surface: conn.surface });
163
+ }));
164
+ app.post('/api/refresh', wrap(async (_req, res) => {
165
+ await conn.refresh();
166
+ res.json({ connection: publicState(), surface: conn.surface });
167
+ }));
168
+ // ── surface analysis ──
169
+ app.get('/api/analysis', (_req, res) => {
170
+ const surface = conn.surface;
171
+ if (!surface)
172
+ return void res.json({ connected: false });
173
+ const overrides = store.overrides();
174
+ const visible = { ...surface, tools: surface.tools.filter((t) => !overrides[t.name]?.hidden) };
175
+ const map = buildProductMap(visible);
176
+ const traffic = store.traffic(30);
177
+ const lint = [...lintSurface(surface, overrides), ...lintTraffic(traffic.filter((e) => visible.tools.some((t) => t.name === e.tool)))];
178
+ const useExact = exact && exact.hash === surface.hash + JSON.stringify(overrides);
179
+ const costs = visible.tools.map((t) => {
180
+ const est = estimateToolCost(t, overrides);
181
+ return useExact && exact.perTool[t.name] !== undefined ? { ...est, total: exact.perTool[t.name], exact: true } : est;
182
+ });
183
+ const instructions = surface.server.instructions ? Math.ceil(surface.server.instructions.length / 3.6) : 0;
184
+ res.json({
185
+ connected: true,
186
+ map,
187
+ lint,
188
+ costs,
189
+ budget: {
190
+ tools: costs.reduce((s, c) => s + c.total, 0),
191
+ preamble: useExact ? exact.preamble : 0,
192
+ instructions,
193
+ total: useExact ? exact.total + instructions : costs.reduce((s, c) => s + c.total, 0) + instructions,
194
+ exact: !!useExact,
195
+ model: useExact ? exact.model : undefined,
196
+ },
197
+ });
198
+ });
199
+ app.post('/api/tokens/exact', wrap(async (_req, res) => {
200
+ const surface = requireSurface();
201
+ const key = keyFor('anthropic');
202
+ if (!key)
203
+ throw httpError(400, 'Exact counts need an Anthropic API key (count_tokens is free).');
204
+ const overrides = store.overrides();
205
+ const model = store.settings().provider === 'anthropic' ? store.settings().model : 'claude-opus-5-5';
206
+ const tools = surface.tools.filter((t) => !overrides[t.name]?.hidden);
207
+ const r = await exactToolTokens(key, model, tools, overrides);
208
+ exact = { ...r, hash: surface.hash + JSON.stringify(overrides), model };
209
+ res.json(exact);
210
+ }));
211
+ app.post('/api/tools/call', wrap(async (req, res) => {
212
+ requireSurface();
213
+ const { name, args } = req.body;
214
+ const out = await conn.callTool(name, args ?? {}, { source: 'sandbox', sessionId: 'manual' });
215
+ res.json({ text: out.text, isError: out.isError, durationMs: out.durationMs, resultTokens: out.resultTokens, ui: out.ui, result: out.result });
216
+ }));
217
+ // ── pre-fill: real values for references, made-up ones for everything else ──
218
+ const prefillCtx = () => ({ tools: requireSurface().tools, samples: store.samples(), traffic: store.traffic(30) });
219
+ app.get('/api/tools/:name/prefill', wrap(async (req, res) => {
220
+ const plan = planPrefill(String(req.params.name), prefillCtx());
221
+ if (!plan)
222
+ throw httpError(404, 'No such tool');
223
+ res.json(plan);
224
+ }));
225
+ // Run the tool that lists a field's values (read-only tools only), then plan again.
226
+ app.post('/api/tools/:name/lookup', wrap(async (req, res) => {
227
+ const name = String(req.params.name);
228
+ const { field } = req.body;
229
+ const plan = planPrefill(name, prefillCtx());
230
+ const lookup = plan?.fields[field]?.lookup;
231
+ if (!lookup)
232
+ throw httpError(400, `Nothing lists values for ${field}`);
233
+ if (!lookup.ready)
234
+ throw httpError(400, `${lookup.tool} needs ${lookup.missing.join(', ')} first`);
235
+ const sub = planPrefill(lookup.tool, prefillCtx(), 0);
236
+ const lister = requireSurface().tools.find((t) => t.name === lookup.tool);
237
+ const args = coerceArgs(lister, Object.fromEntries(Object.entries(sub.fields).filter(([k]) => (lister.inputSchema?.required ?? []).includes(k)).map(([k, f]) => [k, f.value])));
238
+ const out = await conn.callTool(lookup.tool, args, { source: 'sandbox', sessionId: 'manual' });
239
+ res.json({ plan: planPrefill(name, prefillCtx()), ran: { tool: lookup.tool, args, isError: out.isError, text: out.text.slice(0, 400) } });
240
+ }));
241
+ app.post('/api/tools/:name/fill-ai', wrap(async (req, res) => {
242
+ const name = String(req.params.name);
243
+ const tool = requireSurface().tools.find((t) => t.name === name);
244
+ const plan = planPrefill(name, prefillCtx());
245
+ if (!tool || !plan)
246
+ throw httpError(404, 'No such tool');
247
+ const { intent } = (req.body ?? {});
248
+ res.json(await fillWithModel(tool, plan, store.samples(), intent, { key: keyFor('anthropic') }));
249
+ }));
250
+ // ── first prompts for the Playground ──
251
+ const writing = new Set();
252
+ app.get('/api/starters', wrap(async (_req, res) => {
253
+ const surface = requireSurface();
254
+ if (conn.state.demo)
255
+ return void res.json({ prompts: DEMO_STARTERS, source: 'demo' });
256
+ const key = startersKey(surface);
257
+ const cached = store.starters();
258
+ if (cached?.key === key && cached.prompts.length)
259
+ return void res.json({ prompts: cached.prompts, source: 'ai' });
260
+ const fallback = templateStarters(buildProductMap(surface));
261
+ // One small Haiku call per set of tools, in the background; the page asks again.
262
+ const apiKey = keyFor('anthropic');
263
+ const canWrite = !!apiKey || (await anyAgentAvailable());
264
+ if (canWrite && !writing.has(key)) {
265
+ writing.add(key);
266
+ const target = store;
267
+ void writeStarters(surface, store.samples(), apiKey)
268
+ .then((prompts) => prompts.length && target.saveStarters({ key, prompts }))
269
+ .catch((e) => conn.note(`couldn't write starter prompts: ${e.message}`))
270
+ .finally(() => writing.delete(key));
271
+ }
272
+ res.json({ prompts: fallback, source: 'template', pending: writing.has(key) });
273
+ }));
274
+ app.get('/api/resource', wrap(async (req, res) => {
275
+ res.json(await conn.readResource(String(req.query.uri)));
276
+ }));
277
+ // ── settings ──
278
+ app.get('/api/settings', (_req, res) => void res.json(store.settings()));
279
+ app.put('/api/settings', (req, res) => void res.json(store.saveSettings(req.body)));
280
+ app.put('/api/secrets', (req, res) => {
281
+ const { anthropicApiKey, openaiApiKey } = req.body;
282
+ store.saveSecrets({ anthropicApiKey, openaiApiKey });
283
+ res.json({ anthropic: !!keyFor('anthropic'), openai: !!keyFor('openai') });
284
+ });
285
+ app.get('/api/overrides', (_req, res) => void res.json(store.overrides()));
286
+ app.put('/api/overrides', (req, res) => {
287
+ store.saveOverrides(req.body);
288
+ res.json(store.overrides());
289
+ });
290
+ // ── skills ──
291
+ app.get('/api/skills', (_req, res) => {
292
+ const list = skills.list().map((s) => ({ ...s, lint: lintSkill(s.content, conn.surface, store.overrides()) }));
293
+ res.json({ dir: skills.dir, skills: list });
294
+ });
295
+ app.get('/api/skill', wrap(async (req, res) => void res.json(skills.load(String(req.query.id)))));
296
+ app.put('/api/skill', wrap(async (req, res) => {
297
+ const s = skills.save(String(req.query.id), String(req.body.content));
298
+ res.json({ ...s, lint: lintSkill(s.content, conn.surface, store.overrides()) });
299
+ }));
300
+ app.post('/api/skills', wrap(async (req, res) => {
301
+ const { name, content } = req.body;
302
+ const body = content ?? `---\nname: ${slugify(name)}\ndescription: \n---\n\n# ${name}\n\n`;
303
+ res.json(skills.create(name, body));
304
+ }));
305
+ app.post('/api/skills/lint', (req, res) => void res.json(lintSkill(String(req.body.content ?? ''), conn.surface, store.overrides())));
306
+ app.post('/api/skills/generate', wrap(async (req, res) => {
307
+ const surface = requireSurface();
308
+ const overrides = store.overrides();
309
+ const map = buildProductMap(surface);
310
+ const draft = draftSkill(surface, map, [...lintSurface(surface, overrides), ...lintTraffic(store.traffic(30))]);
311
+ const { polish } = req.body;
312
+ if (!polish)
313
+ return void res.json({ content: draft, polished: false });
314
+ const content = await polishSkill(writer(), store.settings().model, draft, surface);
315
+ res.json({ content, polished: true, draft });
316
+ }));
317
+ // Draft trigger tests for a skill: prompts that should load it, and near-misses that shouldn't.
318
+ app.post('/api/skills/suggest-tests', wrap(async (req, res) => {
319
+ const { content } = req.body;
320
+ const tools = (conn.surface?.tools ?? []).map((t) => t.name).join(', ');
321
+ const text = await writer().text({
322
+ model: store.settings().model,
323
+ system: 'You write trigger tests for agent skills. Output only JSON.',
324
+ prompt: `This SKILL.md is installed in Claude Code next to an MCP server with these tools: ${tools}.\n\n${content}\n\nWrite 3 short, realistic user requests that SHOULD make Claude load this skill (phrased the way a real user would, not mentioning the skill), and 2 near-miss requests on the same server that should NOT load it. Reply as JSON: {"should": [..], "shouldNot": [..]}`,
325
+ });
326
+ const m = /\{[\s\S]*\}/.exec(text);
327
+ const parsed = m ? JSON.parse(m[0]) : {};
328
+ res.json({ should: (parsed.should ?? []).slice(0, 5), shouldNot: (parsed.shouldNot ?? []).slice(0, 5) });
329
+ }));
330
+ // ── hosts ──
331
+ app.get('/api/hosts', wrap(async (_req, res) => void res.json(await detectHosts(store))));
332
+ app.get('/api/models', (_req, res) => void res.json(modelOptions(store.settings())));
333
+ const specFrom = (v, label) => ({
334
+ host: v.host,
335
+ skills: loadSkills(v.skills, v.skillsInline),
336
+ overrides: v.overrides ?? store.overrides(),
337
+ label,
338
+ ...(v.model !== undefined ? { settings: v.host === 'codex' ? { codexModel: v.model } : v.host === 'api' ? (v.model ? { model: v.model } : {}) : { hostModel: v.model } } : {}),
339
+ });
340
+ app.post('/api/sessions', wrap(async (req, res) => {
341
+ requireSurface();
342
+ const body = (req.body ?? {});
343
+ const session = newSession(specFrom(body, 'playground'));
344
+ sessions.set(session.id, { session, lastUsed: Date.now(), chat: body.chat, lane: { host: body.host, model: body.model } });
345
+ res.json({ id: session.id, host: session.hostId });
346
+ }));
347
+ app.post('/api/sessions/:id/send', wrap(async (req, res) => {
348
+ const x = sessions.get(String(req.params.id));
349
+ if (!x)
350
+ throw httpError(404, 'This conversation has ended; start a new one');
351
+ x.lastUsed = Date.now();
352
+ const stream = ndjson(res);
353
+ let closed = false;
354
+ res.on('close', () => (closed = true));
355
+ await x.session.send(String(req.body.prompt), (e) => !closed && stream(e));
356
+ store.saveRun(x.session.id, { ...x.session.toJSON(), chat: x.chat ?? x.session.id, lane: x.lane });
357
+ res.end();
358
+ }));
359
+ // Past Playground conversations, newest first; agents that answered side by side come back together.
360
+ app.get('/api/chats', (_req, res) => {
361
+ const chats = new Map();
362
+ for (const r of store.listRuns(300)) {
363
+ if (r.config?.label !== 'playground' || !r.prompts?.length)
364
+ continue;
365
+ const key = r.chat ?? r.id;
366
+ const c = chats.get(key) ?? { chat: key, at: r.createdAt, prompt: r.prompts[0], turns: 0, lanes: [] };
367
+ c.turns = Math.max(c.turns, r.prompts.length);
368
+ if (r.createdAt > c.at)
369
+ c.at = r.createdAt;
370
+ c.lanes.push({ runId: r.id, host: r.lane?.host ?? r.host ?? 'claude-code', model: r.lane?.model ?? '' });
371
+ chats.set(key, c);
372
+ }
373
+ res.json([...chats.values()].sort((a, b) => b.at.localeCompare(a.at)).slice(0, 60));
374
+ });
375
+ app.post('/api/sessions/:id/close', wrap(async (req, res) => {
376
+ const x = sessions.get(String(req.params.id));
377
+ sessions.delete(String(req.params.id));
378
+ await x?.session.close();
379
+ res.json({ ok: true });
380
+ }));
381
+ // ── compare: same prompts, before vs after, N real runs each ──
382
+ app.post('/api/compare', wrap(async (req, res) => {
383
+ requireSurface();
384
+ const { prompts, a, b, judge, trials } = req.body;
385
+ const n = Math.max(1, Math.min(10, trials ?? 1));
386
+ const stream = ndjson(res);
387
+ const side = async (variant, v) => {
388
+ const results = [];
389
+ for (let t = 0; t < n; t++) {
390
+ stream({ type: 'trial_start', variant, trial: t });
391
+ try {
392
+ const r = await runTrial({ ...specFrom(v, `compare-${variant}`), prompts, judge }, hostDeps(), (event) => stream({ variant, trial: t, event }));
393
+ const pass = judge ? !!r.verdict?.pass : !r.error && !!r.session.summary.host?.usedServer;
394
+ store.saveRun(r.session.id, { ...r.session.toJSON(), compare: variant, trial: t, verdict: r.verdict });
395
+ const out = { pass, summary: r.session.summary, verdict: r.verdict, error: r.error, sessionId: r.session.id };
396
+ results.push(out);
397
+ stream({ type: 'trial_end', variant, trial: t, result: out });
398
+ }
399
+ catch (e) {
400
+ const out = { pass: false, summary: addSummaries([]), error: e.message, sessionId: '' };
401
+ results.push(out);
402
+ stream({ type: 'trial_end', variant, trial: t, result: out });
403
+ }
404
+ }
405
+ const skillNames = [...new Set(results.flatMap((r) => r.summary.host?.skillsInstalled ?? []))];
406
+ return { rates: ratesOf(results, undefined), skillLoaded: results.filter((r) => (r.summary.host?.skillsLoaded.length ?? 0) > 0).length, skillsInstalled: skillNames, avg: average(results.map((r) => r.summary)), costUsd: results.reduce((x, r) => x + (r.summary.host?.costUsd ?? 0), 0), trials: results };
407
+ };
408
+ const [ra, rb] = await Promise.all([side('a', a), side('b', b)]);
409
+ stream({ type: 'compare_end', a: ra, b: rb });
410
+ res.end();
411
+ }));
412
+ // ── tests ──
413
+ // A test that names a skill the project doesn't have can't fail for the right reason; say so.
414
+ const withLast = (j) => {
415
+ const names = new Set(skills.list().flatMap((s) => [s.name, s.id.replace(/\/SKILL\.md$/, '')]));
416
+ const named = [...(j.assertions.expectSkills ?? []), ...(j.assertions.forbidSkills ?? []), ...(j.skill ? [j.skill] : [])];
417
+ const missingSkills = [...new Set(named.filter((n) => !names.has(n)))];
418
+ return { ...j, last: store.lastJourneyResult(j.slug), ...(missingSkills.length ? { missingSkills } : {}) };
419
+ };
420
+ app.get('/api/journeys', (_req, res) => void res.json(store.journeys().map(withLast)));
421
+ app.post('/api/journeys', wrap(async (req, res) => {
422
+ const { last: _last, ...j } = req.body;
423
+ const slug = j.slug || slugify(j.name);
424
+ const now = new Date().toISOString();
425
+ const existing = store.journeys().find((x) => x.slug === slug);
426
+ const saved = { ...j, slug, createdAt: existing?.createdAt ?? now, updatedAt: now };
427
+ store.saveJourney(slug, saved);
428
+ res.json(withLast(saved));
429
+ }));
430
+ app.delete('/api/journeys/:slug', wrap(async (req, res) => {
431
+ store.deleteJourney(String(req.params.slug));
432
+ res.json({ ok: true });
433
+ }));
434
+ app.post('/api/journeys/:slug/run', wrap(async (req, res) => {
435
+ requireSurface();
436
+ const j = store.journeys().find((x) => x.slug === req.params.slug);
437
+ if (!j)
438
+ throw httpError(404, 'No such test');
439
+ const { trials, skillOverride } = (req.body ?? {});
440
+ const stream = ndjson(res);
441
+ const result = await runJourney(j, {
442
+ ...hostDeps(),
443
+ skills,
444
+ trials,
445
+ skillOverride,
446
+ onEvent: (trial, event) => stream({ trial, event }),
447
+ onTrial: (t) => stream({ type: 'trial_end', trial: t.index, result: { ...t, events: undefined } }),
448
+ });
449
+ const lite = { ...result, trials: result.trials.map((t) => ({ ...t, events: undefined })) };
450
+ store.saveJourneyResult(j.slug, { ...lite, at: new Date().toISOString(), draft: !!skillOverride });
451
+ stream({ type: 'journey_result', result: lite });
452
+ res.end();
453
+ }));
454
+ // Tests are private by default; sharing moves them into the repo so teammates get them.
455
+ // What sharing would do, for the confirm dialog: which files, and what git will make of them.
456
+ app.get('/api/tests/share', (_req, res) => {
457
+ const git = (...args) => {
458
+ try {
459
+ return { ok: true, out: execFileSync('git', args, { cwd: ws.project, stdio: ['ignore', 'pipe', 'ignore'] }).toString() };
460
+ }
461
+ catch {
462
+ return { ok: false, out: '' };
463
+ }
464
+ };
465
+ const dir = ws.sharedTestsDir;
466
+ const inRepo = git('rev-parse', '--is-inside-work-tree').ok;
467
+ let files = [];
468
+ try {
469
+ files = readdirSync(store.testsDir).filter((f) => f.endsWith('.json')).sort();
470
+ }
471
+ catch {
472
+ /* no tests yet */
473
+ }
474
+ res.json({
475
+ shared: store.testsShared,
476
+ dir: relative(ws.project, dir),
477
+ files,
478
+ inRepo,
479
+ // check-ignore exits 0 when the path is ignored.
480
+ ignored: inRepo && git('check-ignore', '-q', join(dir, 'x.json')).ok,
481
+ uncommitted: inRepo && store.testsShared && git('status', '--porcelain', '--', dir).out.trim().length > 0,
482
+ });
483
+ });
484
+ app.post('/api/tests/share', (req, res) => {
485
+ if (ws.demo)
486
+ return void res.status(400).json({ error: 'The demo has no repo to share tests in' });
487
+ ws.shareTests(!!req.body.shared);
488
+ res.json({ shared: store.testsShared, dir: store.testsDir });
489
+ });
490
+ app.get('/api/live', (_req, res) => void res.json(store.liveRuns()));
491
+ // ── attempts: every eval run, what it changed, and whether that helped ──
492
+ /** The attempt before this one on the same agent, which is what it's compared with. */
493
+ const previousOf = (list, i) => list.slice(i + 1).find((a) => a.hostId === list[i].hostId);
494
+ app.get('/api/attempts', (_req, res) => {
495
+ const list = store.attempts(100);
496
+ res.json(list.map((a, i) => {
497
+ const prev = previousOf(list, i);
498
+ const changes = changesBetween(prev?.snapshot, a.snapshot);
499
+ const moves = movement(prev, a);
500
+ return {
501
+ id: a.id,
502
+ at: a.at,
503
+ note: a.note,
504
+ host: a.host,
505
+ hostId: a.hostId,
506
+ source: a.source ?? 'cli',
507
+ filter: a.filter,
508
+ passed: a.results.filter((r) => r.pass).length,
509
+ total: a.results.length,
510
+ fixed: moves.filter((m) => m.change === 'fixed').map((m) => m.name),
511
+ broke: moves.filter((m) => m.change === 'broke').map((m) => m.name),
512
+ changed: { skills: changes.skills.map((c) => c.id), tools: changes.tools.map((c) => c.name) },
513
+ };
514
+ }));
515
+ });
516
+ app.get('/api/attempts/:id', (req, res) => {
517
+ const list = store.attempts(100);
518
+ const i = list.findIndex((a) => a.id === req.params.id);
519
+ if (i < 0)
520
+ return void res.status(404).json({ error: 'No such attempt' });
521
+ const a = list[i];
522
+ const prev = previousOf(list, i);
523
+ res.json({ previous: prev?.id, changes: changesBetween(prev?.snapshot, a.snapshot), tests: movement(prev, a), results: a.results });
524
+ });
525
+ app.get('/api/evals/latest', (_req, res) => void res.json(store.evalBaseline() ?? null));
526
+ app.get('/api/runs', (_req, res) => void res.json(store.listRuns(40).map(({ events: _e, ...r }) => r)));
527
+ app.get('/api/runs/:id', wrap(async (req, res) => void res.json(store.run(String(req.params.id)) ?? null)));
528
+ // ── analytics ──
529
+ app.get('/api/analytics', (req, res) => {
530
+ const days = Math.min(90, Number(req.query.days) || 14);
531
+ const source = String(req.query.source ?? 'all');
532
+ let events = store.traffic(days);
533
+ if (source === 'real')
534
+ events = events.filter((e) => e.source !== 'simulated');
535
+ else if (source !== 'all')
536
+ events = events.filter((e) => e.source === source);
537
+ const all = store.traffic(days);
538
+ const counts = {};
539
+ for (const e of all)
540
+ counts[e.source] = (counts[e.source] ?? 0) + 1;
541
+ res.json({ ...aggregate(events, conn.surface, store.overrides(), days), availableSources: counts });
542
+ });
543
+ app.post('/api/ingest', (req, res) => {
544
+ const events = (Array.isArray(req.body) ? req.body : [req.body]);
545
+ store.appendTraffic(events.filter((e) => e && e.tool && e.ts).map((e) => ({ ...e, source: e.source ?? 'ingest' })));
546
+ broadcast('traffic', { count: events.length });
547
+ res.json({ ok: true, received: events.length });
548
+ });
549
+ app.delete('/api/traffic', (req, res) => {
550
+ store.clearTraffic(req.query.source ? String(req.query.source) : undefined);
551
+ res.json({ ok: true });
552
+ });
553
+ // ── UI ──
554
+ if (existsSync(join(uiDir, 'index.html'))) {
555
+ app.use(express.static(uiDir));
556
+ app.get(/^(?!\/api\/).*/, (_req, res) => res.sendFile(join(uiDir, 'index.html')));
557
+ }
558
+ else {
559
+ app.get('/', (_req, res) => void res.type('text').send('UI not built. Run `npm run build`, or `npm run dev:ui` and open http://localhost:5173.'));
560
+ }
561
+ app.use((err, _req, res, _next) => {
562
+ if (res.headersSent) {
563
+ res.write(JSON.stringify({ type: 'error', message: err.message }) + '\n');
564
+ return void res.end();
565
+ }
566
+ res.status(err.status ?? 500).json({ error: err.message });
567
+ });
568
+ return app;
569
+ }
570
+ const LOCAL_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
571
+ /** A Host header naming this machine (any port). */
572
+ export function isLocalHost(host) {
573
+ if (!host)
574
+ return false;
575
+ try {
576
+ return LOCAL_HOSTNAMES.has(new URL(`http://${host}`).hostname);
577
+ }
578
+ catch {
579
+ return false;
580
+ }
581
+ }
582
+ /** An Origin served from this machine over http (the studio itself, or the Vite dev server). */
583
+ export function isLocalOrigin(origin) {
584
+ try {
585
+ const u = new URL(origin);
586
+ return u.protocol === 'http:' && LOCAL_HOSTNAMES.has(u.hostname);
587
+ }
588
+ catch {
589
+ return false;
590
+ }
591
+ }
592
+ function ndjson(res) {
593
+ res.writeHead(200, { 'content-type': 'application/x-ndjson', 'cache-control': 'no-cache', 'x-accel-buffering': 'no' });
594
+ return (obj) => res.write(JSON.stringify(obj) + '\n');
595
+ }
596
+ function httpError(status, message) {
597
+ return Object.assign(new Error(message), { status });
598
+ }
599
+ function wrap(fn) {
600
+ return (req, res, next) => void fn(req, res).catch(next);
601
+ }
602
+ //# sourceMappingURL=app.js.map
@@ -0,0 +1,12 @@
1
+ export async function listenFrom(make, first, tries = 20) {
2
+ for (let port = first; port < first + tries; port++) {
3
+ // Express 5 calls listen's callback on errors too (a busy port included), so check for one.
4
+ const server = await new Promise((ok) => {
5
+ const s = make(port).listen(port, '127.0.0.1', (err) => ok(err ? undefined : s));
6
+ });
7
+ if (server)
8
+ return { server, port };
9
+ }
10
+ return undefined;
11
+ }
12
+ //# sourceMappingURL=listen.js.map