@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.
- package/LICENSE +21 -0
- package/README.md +79 -2
- package/bin/mcp-dev-studio.js +2 -0
- package/dist/agent/fill.js +69 -0
- package/dist/agent/judge.js +24 -0
- package/dist/agent/loop-skill.js +103 -0
- package/dist/agent/providers.js +162 -0
- package/dist/agent/runner.js +252 -0
- package/dist/agent/starters.js +47 -0
- package/dist/analysis/estimate.js +7 -0
- package/dist/analysis/lint.js +149 -0
- package/dist/analysis/prefill.js +411 -0
- package/dist/analysis/surface.js +268 -0
- package/dist/analysis/tokens.js +69 -0
- package/dist/analytics/aggregate.js +106 -0
- package/dist/analytics/recorder.js +75 -0
- package/dist/analytics/tracker.js +58 -0
- package/dist/cli.js +264 -0
- package/dist/demo/seed.js +138 -0
- package/dist/demo/server.js +282 -0
- package/dist/demo/stdio.js +7 -0
- package/dist/discover.js +317 -0
- package/dist/eval/attempts.js +54 -0
- package/dist/eval/cli.js +183 -0
- package/dist/eval/journeys.js +161 -0
- package/dist/hosts/claude-code.js +403 -0
- package/dist/hosts/codex.js +328 -0
- package/dist/hosts/index.js +85 -0
- package/dist/hosts/models.js +51 -0
- package/dist/mcp/connection.js +330 -0
- package/dist/server/app.js +602 -0
- package/dist/server/listen.js +12 -0
- package/dist/skills/skills.js +203 -0
- package/dist/store-watch.js +75 -0
- package/dist/store.js +327 -0
- package/dist/types.js +3 -0
- package/dist/ui/assets/index-D9hmZSmq.js +55 -0
- package/dist/ui/assets/index-G_SSBQNV.css +2 -0
- package/dist/ui/index.html +17 -0
- package/dist/workspace.js +195 -0
- package/package.json +79 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
// studio — local dev studio for an Agent Surface (MCP server + Skills).
|
|
2
|
+
//
|
|
3
|
+
// studio finds this folder's server, or asks in the browser
|
|
4
|
+
// studio demo built-in messy SaaS server
|
|
5
|
+
// studio "node ./server.js" spawn a local stdio server
|
|
6
|
+
// studio http://localhost:3001/mcp Streamable HTTP (falls back to SSE)
|
|
7
|
+
// studio eval [target] [--journey x] run saved journeys headlessly
|
|
8
|
+
// studio proxy --stdio "node server.js" record real client usage
|
|
9
|
+
import { parseArgs } from 'node:util';
|
|
10
|
+
import { spawn } from 'node:child_process';
|
|
11
|
+
import { homedir } from 'node:os';
|
|
12
|
+
import { dirname, join, relative, resolve } from 'node:path';
|
|
13
|
+
import { fileURLToPath } from 'node:url';
|
|
14
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
15
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
16
|
+
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
17
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
18
|
+
import { splitCommand } from './mcp/connection.js';
|
|
19
|
+
import { createApp } from './server/app.js';
|
|
20
|
+
import { listenFrom } from './server/listen.js';
|
|
21
|
+
import { runEvalCli } from './eval/cli.js';
|
|
22
|
+
import { fileSink, httpSink, recordingPipe } from './analytics/recorder.js';
|
|
23
|
+
import { DEMO_ENTRY, Workspace } from './workspace.js';
|
|
24
|
+
import { autoPick, discover } from './discover.js';
|
|
25
|
+
import { detectClaudeCode } from './hosts/claude-code.js';
|
|
26
|
+
import { detectCodex } from './hosts/codex.js';
|
|
27
|
+
import { SKILL_DIRS, loopSkill, outdatedSkills } from './agent/loop-skill.js';
|
|
28
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
29
|
+
const pkg = JSON.parse(readFileSync(join(here, '..', 'package.json'), 'utf8'));
|
|
30
|
+
const HELP = `mcp-dev-studio ${pkg.version} — design, test and iterate on an Agent Surface (MCP + Skills)
|
|
31
|
+
|
|
32
|
+
Usage (run with npx @chapterdev/mcp-dev-studio …)
|
|
33
|
+
mcp-dev-studio Open on this folder's server (finds it, or asks)
|
|
34
|
+
mcp-dev-studio "node server.js" A stdio server
|
|
35
|
+
mcp-dev-studio http://localhost:3001/mcp An HTTP server (Streamable HTTP, falls back to SSE)
|
|
36
|
+
mcp-dev-studio demo Built-in messy SaaS MCP server
|
|
37
|
+
mcp-dev-studio eval [--journey <name>] Run saved tests in real agents, print pass rates
|
|
38
|
+
mcp-dev-studio setup Teach Claude Code / Codex here to iterate with the studio
|
|
39
|
+
mcp-dev-studio proxy --stdio "<cmd>" | --url Transparent MCP proxy that records usage
|
|
40
|
+
mcp-dev-studio demo-server Run the demo server over stdio
|
|
41
|
+
|
|
42
|
+
Options
|
|
43
|
+
--skills <dir> SKILL.md folder to co-edit (default skills/, .claude/skills or .agents/skills)
|
|
44
|
+
--store <dir> Data dir (default ~/.mcp-dev-studio/projects/<repo>)
|
|
45
|
+
--cwd <dir> Working directory for --stdio
|
|
46
|
+
--header "K: V" HTTP header for --url (repeatable)
|
|
47
|
+
--token-file <path> Read a bearer token for --url from a file (keeps it out of ps)
|
|
48
|
+
--watch <path> Restart the server when this path changes (repeatable)
|
|
49
|
+
--port <n> UI port (default 4300)
|
|
50
|
+
--no-open Don't open the browser
|
|
51
|
+
--json (eval) machine-readable output
|
|
52
|
+
--ingest <url> (proxy) send events to a running studio instead of disk
|
|
53
|
+
--samples (proxy) keep response text locally, so test forms pre-fill real values
|
|
54
|
+
--trials <n> (eval) runs per test (default from settings, 3)
|
|
55
|
+
--host <ids> (eval) claude-code, codex or api; comma-separate to run each (default from settings)
|
|
56
|
+
--failed (eval) only the tests that failed in the last attempt
|
|
57
|
+
--note <text> (eval) say what this attempt changed; shown in the studio's history
|
|
58
|
+
|
|
59
|
+
Keys: ANTHROPIC_API_KEY / OPENAI_API_KEY, or Settings in the UI.`;
|
|
60
|
+
async function main() {
|
|
61
|
+
const argv = process.argv.slice(2);
|
|
62
|
+
const COMMANDS = ['serve', 'eval', 'proxy', 'demo-server', 'skill', 'setup'];
|
|
63
|
+
const command = argv[0] && COMMANDS.includes(argv[0]) ? argv.shift() : 'serve';
|
|
64
|
+
const { values, positionals } = parseArgs({
|
|
65
|
+
args: argv,
|
|
66
|
+
options: {
|
|
67
|
+
demo: { type: 'boolean' },
|
|
68
|
+
stdio: { type: 'string' },
|
|
69
|
+
url: { type: 'string' },
|
|
70
|
+
skills: { type: 'string' },
|
|
71
|
+
store: { type: 'string' },
|
|
72
|
+
cwd: { type: 'string' },
|
|
73
|
+
header: { type: 'string', multiple: true },
|
|
74
|
+
'token-file': { type: 'string' },
|
|
75
|
+
watch: { type: 'string', multiple: true },
|
|
76
|
+
port: { type: 'string' },
|
|
77
|
+
'no-open': { type: 'boolean' },
|
|
78
|
+
journey: { type: 'string' },
|
|
79
|
+
json: { type: 'boolean' },
|
|
80
|
+
ingest: { type: 'string' },
|
|
81
|
+
session: { type: 'string' },
|
|
82
|
+
samples: { type: 'boolean' },
|
|
83
|
+
source: { type: 'string' },
|
|
84
|
+
overrides: { type: 'string' },
|
|
85
|
+
trials: { type: 'string' },
|
|
86
|
+
host: { type: 'string' },
|
|
87
|
+
note: { type: 'string' },
|
|
88
|
+
failed: { type: 'boolean' },
|
|
89
|
+
print: { type: 'boolean' },
|
|
90
|
+
help: { type: 'boolean', short: 'h' },
|
|
91
|
+
version: { type: 'boolean', short: 'v' },
|
|
92
|
+
},
|
|
93
|
+
strict: true,
|
|
94
|
+
allowPositionals: true,
|
|
95
|
+
});
|
|
96
|
+
if (values.help)
|
|
97
|
+
return console.log(HELP);
|
|
98
|
+
if (values.version)
|
|
99
|
+
return console.log(pkg.version);
|
|
100
|
+
if (command === 'demo-server') {
|
|
101
|
+
await import('./demo/stdio.js');
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (!['serve', 'eval', 'proxy', 'skill', 'setup'].includes(command)) {
|
|
105
|
+
console.error(`Unknown command "${command}".\n\n${HELP}`);
|
|
106
|
+
process.exit(2);
|
|
107
|
+
}
|
|
108
|
+
// ── which server ──
|
|
109
|
+
// Flags or a bare argument win; then .mcp-dev-studio/server.json; then whatever the project declares.
|
|
110
|
+
const project = process.cwd();
|
|
111
|
+
const demo = !!values.demo || positionals[0] === 'demo';
|
|
112
|
+
let explicit;
|
|
113
|
+
const bare = demo ? undefined : positionals.join(' ').trim();
|
|
114
|
+
const targetUrl = values.url ?? (bare && /^https?:\/\//.test(bare) ? bare : undefined);
|
|
115
|
+
if (targetUrl) {
|
|
116
|
+
const headers = {
|
|
117
|
+
// Headers handed to a proxy by the studio arrive via env, never argv (tokens stay out of `ps`).
|
|
118
|
+
...(process.env.STUDIO_PROXY_HEADERS ? JSON.parse(process.env.STUDIO_PROXY_HEADERS) : {}),
|
|
119
|
+
...Object.fromEntries((values.header ?? []).map((h) => [h.slice(0, h.indexOf(':')).trim(), h.slice(h.indexOf(':') + 1).trim()])),
|
|
120
|
+
};
|
|
121
|
+
if (values['token-file'])
|
|
122
|
+
headers.Authorization = `Bearer ${readFileSync(resolve(values['token-file']), 'utf8').trim()}`;
|
|
123
|
+
explicit = { kind: 'http', url: targetUrl, ...(Object.keys(headers).length ? { headers } : {}) };
|
|
124
|
+
}
|
|
125
|
+
else if (values.stdio || bare)
|
|
126
|
+
explicit = { kind: 'stdio', command: (values.stdio || bare), cwd: values.cwd ? resolve(values.cwd) : project };
|
|
127
|
+
else if (demo)
|
|
128
|
+
explicit = { kind: 'stdio', command: `"${process.execPath}" "${DEMO_ENTRY}"` };
|
|
129
|
+
const ws = new Workspace(project, { store: values.store ? resolve(values.store) : undefined, skills: values.skills ? resolve(values.skills) : undefined, watch: values.watch?.map((w) => resolve(w)) });
|
|
130
|
+
// ── skill: teach the coding agent in this repo (Claude Code, Codex) to iterate with the studio ──
|
|
131
|
+
if (command === 'skill' || command === 'setup') {
|
|
132
|
+
// Inside the repo: relative. In the private store: ~/… so the path reads the same for everyone.
|
|
133
|
+
const rel = (p) => (relative(project, p).startsWith('..') ? p.replace(homedir(), '~') : relative(project, p) || '.');
|
|
134
|
+
const text = loopSkill({ store: rel(ws.store.root), skills: rel(ws.skills.dir), tests: rel(ws.store.testsDir), server: ws.store.savedServer()?.name ?? 'the MCP server', version: pkg.version });
|
|
135
|
+
if (values.print)
|
|
136
|
+
return void process.stdout.write(text);
|
|
137
|
+
for (const dir of SKILL_DIRS) {
|
|
138
|
+
mkdirSync(join(project, dir), { recursive: true });
|
|
139
|
+
writeFileSync(join(project, dir, 'SKILL.md'), text);
|
|
140
|
+
console.log(` wrote ${dir}/SKILL.md`);
|
|
141
|
+
}
|
|
142
|
+
console.log(`\n Claude Code and Codex in this folder now know how to test and tune your server with mcp-dev-studio.\n Try: "test how agents use this server and fix what fails" · keep \`npx @chapterdev/mcp-dev-studio\` open to watch\n`);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
/** What to connect to without asking, and why (for the startup banner). */
|
|
146
|
+
const choose = async () => {
|
|
147
|
+
if (demo)
|
|
148
|
+
return { choice: { demo: true, target: explicit }, why: 'built-in demo', found: 0 };
|
|
149
|
+
if (explicit)
|
|
150
|
+
return { choice: { target: explicit, save: command === 'serve' }, why: 'from the command line', found: 0 };
|
|
151
|
+
const saved = ws.store.savedServer();
|
|
152
|
+
if (saved)
|
|
153
|
+
return { choice: saved, why: 'the server you picked last time', found: 0 };
|
|
154
|
+
const list = await discover(project);
|
|
155
|
+
const pick = autoPick(list);
|
|
156
|
+
return pick ? { choice: { name: pick.name, target: pick.target, start: pick.start, save: true }, why: `found in ${pick.from}`, found: list.length } : { why: '', found: list.length };
|
|
157
|
+
};
|
|
158
|
+
// ── proxy: stdout is the MCP channel, so log only to stderr ──
|
|
159
|
+
if (command === 'proxy') {
|
|
160
|
+
const target = explicit ?? ws.store.savedServer()?.target;
|
|
161
|
+
if (!target) {
|
|
162
|
+
console.error('studio proxy needs a server: --stdio "<cmd>" or --url <url>');
|
|
163
|
+
process.exit(2);
|
|
164
|
+
}
|
|
165
|
+
const storeRoot = ws.store.root;
|
|
166
|
+
// --ingest sends to a running studio (which persists); otherwise write to disk directly.
|
|
167
|
+
const sinks = [values.ingest ? httpSink(values.ingest) : values.samples ? (e) => ws.store.appendTraffic([e]) : fileSink(join(storeRoot, 'traffic'))];
|
|
168
|
+
let upstream;
|
|
169
|
+
if (target.kind === 'stdio') {
|
|
170
|
+
const [cmd, ...args] = splitCommand(target.command);
|
|
171
|
+
upstream = new StdioClientTransport({ command: cmd, args, cwd: target.cwd, env: { ...process.env, ...target.env }, stderr: 'inherit' });
|
|
172
|
+
}
|
|
173
|
+
else
|
|
174
|
+
upstream = new StreamableHTTPClientTransport(new URL(target.url), { requestInit: { headers: target.headers } });
|
|
175
|
+
const overrides = values.overrides ? JSON.parse(readFileSync(values.overrides, 'utf8')) : undefined;
|
|
176
|
+
await recordingPipe(new StdioServerTransport(), upstream, (e) => sinks.forEach((s) => s(e)), { sessionId: values.session, source: values.source ?? 'proxy', overrides, samples: values.samples });
|
|
177
|
+
// When the client (Claude Code, Cursor…) goes away, take the server down with us.
|
|
178
|
+
const quit = () => void upstream.close().finally(() => process.exit(0));
|
|
179
|
+
process.stdin.on('end', quit);
|
|
180
|
+
process.stdin.on('close', quit);
|
|
181
|
+
process.on('SIGTERM', quit);
|
|
182
|
+
process.stderr.write(`[mcp-dev-studio proxy] recording to ${values.ingest ?? join(storeRoot, 'traffic')}\n`);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (command === 'eval') {
|
|
186
|
+
const { choice } = await choose();
|
|
187
|
+
if (!choice) {
|
|
188
|
+
console.error('No server to test. Pass --stdio "<cmd>" or --url <url>, or run `npx @chapterdev/mcp-dev-studio` once and pick one.');
|
|
189
|
+
process.exit(2);
|
|
190
|
+
}
|
|
191
|
+
try {
|
|
192
|
+
await ws.open({ ...choice, save: false });
|
|
193
|
+
}
|
|
194
|
+
catch (e) {
|
|
195
|
+
console.error(`Could not connect to ${ws.conn.state.label}: ${e.message}\n${ws.conn.state.stderr.slice(-10).join('\n')}`);
|
|
196
|
+
await ws.close();
|
|
197
|
+
process.exit(2);
|
|
198
|
+
}
|
|
199
|
+
// Agents read this too, so an upgrade's better instructions reach them.
|
|
200
|
+
const stale = outdatedSkills(project, pkg.version);
|
|
201
|
+
if (stale.length)
|
|
202
|
+
console.error(`Note: the mcp-dev-studio skill in ${stale.join(' and ')} is from an older version. Run \`npx @chapterdev/mcp-dev-studio setup\` to update it.`);
|
|
203
|
+
const code = await runEvalCli({ conn: ws.conn, store: ws.store, skills: ws.skills, filter: values.journey, json: values.json, trials: values.trials ? Number(values.trials) : undefined, failed: values.failed, note: values.note, hosts: values.host ? values.host.split(',').map((h) => h.trim()).filter(Boolean) : undefined });
|
|
204
|
+
await ws.close();
|
|
205
|
+
process.exit(code);
|
|
206
|
+
}
|
|
207
|
+
// ── serve ──
|
|
208
|
+
const first = Number(values.port ?? process.env.PORT ?? 4300);
|
|
209
|
+
// Already open on this project? Just show it.
|
|
210
|
+
for (let p = first; p < first + 20; p++) {
|
|
211
|
+
const other = await fetch(`http://127.0.0.1:${p}/api/state`, { signal: AbortSignal.timeout(800) }).then((r) => r.json()).catch(() => undefined);
|
|
212
|
+
if (other?.project === project && !explicit && !demo) {
|
|
213
|
+
const url = `http://localhost:${p}`;
|
|
214
|
+
console.log(`\n MCP Dev Studio is already open for this folder.\n\n → ${url}\n`);
|
|
215
|
+
openBrowser(url);
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
const started = await listenFrom((port) => createApp({ workspace: ws, uiDir: join(here, 'ui'), version: pkg.version, ingestUrl: `http://127.0.0.1:${port}/api/ingest` }), first);
|
|
220
|
+
if (!started) {
|
|
221
|
+
console.error(`Ports ${first}–${first + 19} are all in use. Pass --port <n>.`);
|
|
222
|
+
process.exit(2);
|
|
223
|
+
}
|
|
224
|
+
const { server, port } = started;
|
|
225
|
+
const url = `http://localhost:${port}`;
|
|
226
|
+
const shutdown = async () => {
|
|
227
|
+
server.close();
|
|
228
|
+
await ws.close();
|
|
229
|
+
process.exit(0);
|
|
230
|
+
};
|
|
231
|
+
process.on('SIGINT', shutdown);
|
|
232
|
+
process.on('SIGTERM', shutdown);
|
|
233
|
+
const agents = Promise.all([detectClaudeCode(), detectCodex()]);
|
|
234
|
+
const { choice, why, found } = await choose();
|
|
235
|
+
const dim = (t) => (process.stdout.isTTY ? `\x1b[2m${t}\x1b[22m` : t);
|
|
236
|
+
console.log(`\n MCP Dev Studio ${pkg.version} ${dim(project)}\n`);
|
|
237
|
+
if (choice) {
|
|
238
|
+
const label = choice.demo ? 'Ledgerly (demo)' : (choice.name ? `${choice.name} ` : '') + dim(choice.target.kind === 'http' ? choice.target.url : choice.target.command);
|
|
239
|
+
console.log(` server ${label}\n ${dim(why)}`);
|
|
240
|
+
}
|
|
241
|
+
else
|
|
242
|
+
console.log(found ? ` server ${found} found in this project: pick one in the browser` : ' server none found yet: add one in the browser, or try the demo');
|
|
243
|
+
const [cc, cx] = await agents;
|
|
244
|
+
if (cc.available || cx.available)
|
|
245
|
+
console.log(` agents ${[cc.available && `Claude Code ${cc.version}`, cx.available && `Codex ${cx.version}`].filter(Boolean).join(' · ')}`);
|
|
246
|
+
else
|
|
247
|
+
console.log(`\n ! Agents run in Claude Code or Codex, and neither is ready.\n ${cc.installed ? cc.fix : cx.installed ? cx.fix : cc.fix}`);
|
|
248
|
+
console.log(`\n → ${url}\n`);
|
|
249
|
+
if (!values['no-open'] && process.stdout.isTTY)
|
|
250
|
+
openBrowser(url);
|
|
251
|
+
if (choice) {
|
|
252
|
+
ws.open(choice, (l) => process.stdout.write(dim(` │ ${l}\n`))).then(() => console.log(` ✓ connected: ${ws.conn.surface?.tools.length ?? 0} tools`), (e) => console.error(` ! ${e.message.split('\n')[0]}\n Fix it, or pick another server in the browser.`));
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
function openBrowser(url) {
|
|
256
|
+
const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
|
|
257
|
+
const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
|
|
258
|
+
spawn(cmd, args, { stdio: 'ignore', detached: true }).on('error', () => { }).unref();
|
|
259
|
+
}
|
|
260
|
+
main().catch((e) => {
|
|
261
|
+
console.error(e instanceof Error ? e.message : e);
|
|
262
|
+
process.exit(1);
|
|
263
|
+
});
|
|
264
|
+
//# sourceMappingURL=cli.js.map
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// Demo-only fixtures, written into .mcp-dev-studio on first --demo run:
|
|
2
|
+
// - a skills folder with one decent skill and one with a stale tool name
|
|
3
|
+
// - a few saved tests (one fails on purpose: nothing can cancel a subscription)
|
|
4
|
+
// - 14 days of SIMULATED traffic (source: "simulated"), shaped like what the
|
|
5
|
+
// Ledgerly surface would really produce: find/list confusion, blind
|
|
6
|
+
// retries on create_subscription's "Error: failed", cancel requests that
|
|
7
|
+
// dead-end, and get_customer's huge payloads. The UI labels it simulated
|
|
8
|
+
// and it can be cleared in one click.
|
|
9
|
+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
const BILLING_SKILL = `---
|
|
12
|
+
name: ledgerly-billing
|
|
13
|
+
description: Invoice Ledgerly customers end to end — look up the customer, create a draft invoice, preview it, and send it. Use when the user asks to bill, invoice or charge a customer.
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
# Billing a customer
|
|
17
|
+
|
|
18
|
+
1. Resolve the customer with \`find_customer\` (by name or email). Don't use \`search_records\` for this.
|
|
19
|
+
2. Create a draft with \`create_invoice\`. Amounts are in cents.
|
|
20
|
+
3. Show the user \`preview_invoice\` before sending.
|
|
21
|
+
4. Send with \`send_invoice\` — never \`email_customer\`, which doesn't change invoice status.
|
|
22
|
+
|
|
23
|
+
If the user asks for a refund, use \`refund_invoice\`.
|
|
24
|
+
`;
|
|
25
|
+
const SUBS_SKILL = `---
|
|
26
|
+
name: ledgerly-subscriptions
|
|
27
|
+
description: Subscribe customers to plans.
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
Use \`create_subscription\` with the customer id and the plan.
|
|
31
|
+
To cancel, use \`cancel_subscription\`.
|
|
32
|
+
`;
|
|
33
|
+
export function seedDemo(store, skillsDir) {
|
|
34
|
+
if (!existsSync(skillsDir)) {
|
|
35
|
+
mkdirSync(join(skillsDir, 'ledgerly-billing'), { recursive: true });
|
|
36
|
+
mkdirSync(join(skillsDir, 'ledgerly-subscriptions'), { recursive: true });
|
|
37
|
+
writeFileSync(join(skillsDir, 'ledgerly-billing', 'SKILL.md'), BILLING_SKILL);
|
|
38
|
+
writeFileSync(join(skillsDir, 'ledgerly-subscriptions', 'SKILL.md'), SUBS_SKILL);
|
|
39
|
+
}
|
|
40
|
+
if (!store.journeys().length) {
|
|
41
|
+
const now = new Date().toISOString();
|
|
42
|
+
store.saveJourney('invoice-grace', {
|
|
43
|
+
slug: 'invoice-grace',
|
|
44
|
+
name: 'Invoice Grace for a workshop',
|
|
45
|
+
prompts: ['Bill Grace Hopper $1,200 for a two-hour architecture workshop and send it to her.'],
|
|
46
|
+
skills: ['*'],
|
|
47
|
+
trials: 3,
|
|
48
|
+
assertions: { expectTools: ['create_invoice', 'send_invoice'], forbidTools: ['email_customer'], maxTurns: 20, judge: 'A $1,200.00 invoice (120000 cents) was created for Grace Hopper and sent with send_invoice.' },
|
|
49
|
+
createdAt: now,
|
|
50
|
+
});
|
|
51
|
+
store.saveJourney('subscribe-alan', {
|
|
52
|
+
slug: 'subscribe-alan',
|
|
53
|
+
name: 'Move Alan to the Growth plan',
|
|
54
|
+
prompts: ['Alan Turing is converting from trial. Put him on the monthly Growth plan.'],
|
|
55
|
+
skills: ['*'],
|
|
56
|
+
trials: 3,
|
|
57
|
+
assertions: { expectTools: ['create_subscription'], maxTurns: 20, judge: 'A subscription to plan_growth_m was created for Alan Turing.' },
|
|
58
|
+
createdAt: now,
|
|
59
|
+
});
|
|
60
|
+
// Ledgerly has no way to cancel a subscription, so this one fails: the gap the Overview flags, seen in a real run.
|
|
61
|
+
store.saveJourney('cancel-ada', {
|
|
62
|
+
slug: 'cancel-ada',
|
|
63
|
+
name: 'Cancel Ada’s subscription',
|
|
64
|
+
prompts: ['Ada Lovelace wants to cancel her subscription at the end of this month. Please sort it out.'],
|
|
65
|
+
skills: ['*'],
|
|
66
|
+
trials: 3,
|
|
67
|
+
assertions: { maxTurns: 20, judge: 'Ada Lovelace’s subscription was cancelled (or set to cancel at period end), as shown by a tool result.' },
|
|
68
|
+
createdAt: now,
|
|
69
|
+
});
|
|
70
|
+
// Trigger tests for the billing skill (shown in the Skills editor).
|
|
71
|
+
const trigger = (slug, prompt, should) => store.saveJourney(slug, { slug, name: `${should ? 'Loads' : 'Skips'} ledgerly-billing: ${prompt.slice(0, 50)}`, prompts: [prompt], skills: ['*'], skill: 'ledgerly-billing', trials: 3, assertions: should ? { usesServer: false, expectSkills: ['ledgerly-billing'] } : { usesServer: false, forbidSkills: ['ledgerly-billing'] }, createdAt: now });
|
|
72
|
+
trigger('billing-charge-ada', 'Charge Ada $500 for the extra seats she added this month', true);
|
|
73
|
+
trigger('billing-skip-trials', 'Which of our customers are still on a trial?', false);
|
|
74
|
+
}
|
|
75
|
+
if (!store.traffic(30).some((e) => e.source === 'simulated'))
|
|
76
|
+
store.appendTraffic(simulatedTraffic());
|
|
77
|
+
}
|
|
78
|
+
/** Deterministic PRNG so the demo looks the same every time. */
|
|
79
|
+
function rng(seed) {
|
|
80
|
+
return () => {
|
|
81
|
+
seed = (seed * 1664525 + 1013904223) % 4294967296;
|
|
82
|
+
return seed / 4294967296;
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
export function simulatedTraffic(days = 14) {
|
|
86
|
+
const r = rng(42);
|
|
87
|
+
const pick = (xs) => xs[Math.floor(r() * xs.length)];
|
|
88
|
+
const clients = [...Array(6).fill('claude-code'), ...Array(3).fill('cursor'), ...Array(2).fill('claude-ai'), 'codex'];
|
|
89
|
+
const lat = (base) => Math.round(base * (0.6 + r() * 0.9) + (r() < 0.05 ? base * 4 : 0));
|
|
90
|
+
const ok = (tool, tokens, base = 80) => ({ tool, isError: false, durationMs: lat(base), resultTokens: Math.round(tokens * (0.7 + r() * 0.6)) });
|
|
91
|
+
const err = (tool, text, base = 60) => ({ tool, isError: true, durationMs: lat(base), resultTokens: 6, errorText: text });
|
|
92
|
+
const lookup = () => (r() < 0.45 ? [ok('list_customers', 420), ok('find_customer', 90)] : r() < 0.8 ? [ok('find_customer', 90)] : [ok('search_records', 160, 220), ok('find_customer', 90)]);
|
|
93
|
+
const journeys = [
|
|
94
|
+
// bill a customer
|
|
95
|
+
() => [...lookup(), ...(r() < 0.35 ? [ok('get_customer', 6200, 140)] : []), ok('create_invoice', 260, 120), ...(r() < 0.5 ? [ok('preview_invoice', 40, 90)] : []), r() < 0.22 ? ok('email_customer', 30, 300) : ok('send_invoice', 50, 280)],
|
|
96
|
+
// look someone up
|
|
97
|
+
() => [...lookup(), ok('get_customer', 6200, 140)],
|
|
98
|
+
// subscribe: blind retries on "Error: failed"
|
|
99
|
+
() => {
|
|
100
|
+
const calls = [...lookup()];
|
|
101
|
+
const tries = r() < 0.62 ? 1 + Math.floor(r() * 3) : 0;
|
|
102
|
+
for (let i = 0; i < tries; i++)
|
|
103
|
+
calls.push(err('create_subscription', 'Error: failed'));
|
|
104
|
+
if (r() < 0.55)
|
|
105
|
+
calls.push(ok('create_subscription', 80, 150));
|
|
106
|
+
return calls;
|
|
107
|
+
},
|
|
108
|
+
// cancel a subscription: dead end
|
|
109
|
+
() => [...lookup(), ok('list_subscriptions', 180), ...(r() < 0.4 ? [ok('get_customer', 6200, 140)] : [])],
|
|
110
|
+
// invoices overview
|
|
111
|
+
() => [ok('list_invoices', 520), ...(r() < 0.3 ? [ok('list_customers', 420)] : [])],
|
|
112
|
+
// new customer
|
|
113
|
+
() => [ok('find_customer', 60), r() < 0.15 ? err('create_customer', 'Error: customer already exists') : ok('create_customer', 70, 130)],
|
|
114
|
+
];
|
|
115
|
+
const weights = [0.3, 0.2, 0.14, 0.11, 0.15, 0.1];
|
|
116
|
+
const events = [];
|
|
117
|
+
const now = Date.now();
|
|
118
|
+
for (let d = days - 1; d >= 0; d--) {
|
|
119
|
+
const weekday = new Date(now - d * 86400_000).getUTCDay();
|
|
120
|
+
const sessions = Math.round((weekday === 0 || weekday === 6 ? 14 : 34) * (0.75 + (days - d) / days / 1.5) * (0.85 + r() * 0.3));
|
|
121
|
+
for (let s = 0; s < sessions; s++) {
|
|
122
|
+
let x = r(), k = 0;
|
|
123
|
+
while (k < weights.length - 1 && x > weights[k])
|
|
124
|
+
x -= weights[k++];
|
|
125
|
+
const client = pick(clients);
|
|
126
|
+
const sessionId = `sim-${d}-${s}`;
|
|
127
|
+
let t = now - d * 86400_000 - Math.floor(r() * 10 * 3600_000);
|
|
128
|
+
for (const call of journeys[k]()) {
|
|
129
|
+
t += 800 + Math.floor(r() * 9000);
|
|
130
|
+
if (t > now)
|
|
131
|
+
t = now - Math.floor(r() * 60_000);
|
|
132
|
+
events.push({ ts: new Date(t).toISOString(), source: 'simulated', sessionId, client, tool: call.tool, durationMs: call.durationMs, isError: call.isError, errorText: call.errorText, resultChars: Math.round(call.resultTokens * 3), resultTokens: call.resultTokens });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return events;
|
|
137
|
+
}
|
|
138
|
+
//# sourceMappingURL=seed.js.map
|