@chapterdev/mcp-dev-studio 0.0.0-stage → 0.1.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/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 +67 -0
- package/dist/agent/providers.js +162 -0
- package/dist/agent/runner.js +247 -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 +267 -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 +572 -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-89JVDkhA.css +2 -0
- package/dist/ui/assets/index-DWc84XNR.js +54 -0
- package/dist/ui/index.html +17 -0
- package/dist/workspace.js +195 -0
- package/package.json +79 -4
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
// Real Codex (OpenAI's coding agent CLI) as a test host.
|
|
2
|
+
//
|
|
3
|
+
// Each conversation is a Codex thread in a scratch folder:
|
|
4
|
+
// - your server is attached through `studio proxy` with -c mcp_servers.<key>…
|
|
5
|
+
// - your skills are installed in .agents/skills/, where Codex finds project
|
|
6
|
+
// skills. Codex loads a skill by reading its SKILL.md with a shell command,
|
|
7
|
+
// so that read is what counts as "loaded".
|
|
8
|
+
// - read-only sandbox, approvals never: nothing gets written or escalated.
|
|
9
|
+
// Shell reads are how Codex works, so they're allowed and reported.
|
|
10
|
+
// - turn 1 is `codex exec --json`, later turns `codex exec resume <thread>`.
|
|
11
|
+
// The thread is deleted from Codex's history when the conversation closes.
|
|
12
|
+
//
|
|
13
|
+
// "clean" setup: --ignore-user-config (your Codex login, none of your config,
|
|
14
|
+
// MCP servers or profiles). "mine": your normal Codex config too.
|
|
15
|
+
import { spawn, execFile } from 'node:child_process';
|
|
16
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
17
|
+
import { tmpdir } from 'node:os';
|
|
18
|
+
import { join } from 'node:path';
|
|
19
|
+
import { createInterface } from 'node:readline';
|
|
20
|
+
import { estimateTokens } from '../analysis/tokens.js';
|
|
21
|
+
import { emptySummary, FlagTracker, newSessionId, stripRaw, summaryDelta, transcriptFromEvents } from '../agent/runner.js';
|
|
22
|
+
import { hostEnv, live, proxyServer, serverKeyFor, skillSlug } from './claude-code.js';
|
|
23
|
+
const codexBin = () => process.env.STUDIO_CODEX_BIN || 'codex';
|
|
24
|
+
const run = (args) => new Promise((resolve) => execFile(codexBin(), args, { env: hostEnv(), timeout: 15_000 }, (err, stdout, stderr) => resolve({ ok: !err, out: `${stdout}${stderr}` })));
|
|
25
|
+
let detected;
|
|
26
|
+
/** Is `codex` installed and signed in? Free: no model call. Cached for a minute. */
|
|
27
|
+
export async function detectCodex() {
|
|
28
|
+
if (detected && Date.now() - detected.at < 60_000)
|
|
29
|
+
return detected.value;
|
|
30
|
+
const v = await run(['--version']);
|
|
31
|
+
let value;
|
|
32
|
+
if (!v.ok)
|
|
33
|
+
value = { available: false, installed: false, reason: 'Codex isn’t installed.', fix: 'npm install -g @openai/codex && codex login' };
|
|
34
|
+
else {
|
|
35
|
+
const version = /(\d+\.\d+\.\d+\S*)/.exec(v.out)?.[1];
|
|
36
|
+
const auth = await run(['login', 'status']);
|
|
37
|
+
value = auth.ok && /logged in/i.test(auth.out) ? { available: true, installed: true, version } : { available: false, installed: true, version, reason: 'Codex is installed but not signed in.', fix: 'codex login' };
|
|
38
|
+
}
|
|
39
|
+
detected = { at: Date.now(), value };
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
/** TOML for a -c override: strings and string arrays/tables, JSON-quoted (valid TOML basic strings). */
|
|
43
|
+
const toml = (v) => Array.isArray(v) ? `[${v.map(toml).join(',')}]` : v && typeof v === 'object' ? `{${Object.entries(v).map(([k, x]) => `${JSON.stringify(k)}=${toml(x)}`).join(',')}}` : JSON.stringify(String(v));
|
|
44
|
+
const SKILL_READ = /\.agents\/skills\/([^/\s'"]+)\/SKILL\.md/;
|
|
45
|
+
export class CodexSession {
|
|
46
|
+
cfg;
|
|
47
|
+
id = newSessionId();
|
|
48
|
+
hostId = 'codex';
|
|
49
|
+
key;
|
|
50
|
+
events = [];
|
|
51
|
+
prompts = [];
|
|
52
|
+
summary = emptySummary();
|
|
53
|
+
dir;
|
|
54
|
+
thread;
|
|
55
|
+
proc;
|
|
56
|
+
busy = false;
|
|
57
|
+
steps = 0;
|
|
58
|
+
lastWasTool = false;
|
|
59
|
+
pending = new Map();
|
|
60
|
+
tracker = new FlagTracker();
|
|
61
|
+
stderr = [];
|
|
62
|
+
initSent = false;
|
|
63
|
+
constructor(cfg) {
|
|
64
|
+
this.cfg = cfg;
|
|
65
|
+
this.key = serverKeyFor(cfg.serverName).replace(/-/g, '_');
|
|
66
|
+
this.summary.host = { id: 'codex', model: cfg.model || undefined, costUsd: 0, usedServer: false, skillsInstalled: cfg.skills.map(skillSlug), skillsLoaded: [], otherTools: [], toolSearches: 0 };
|
|
67
|
+
}
|
|
68
|
+
setup() {
|
|
69
|
+
const dir = mkdtempSync(join(tmpdir(), 'mcp-dev-studio-codex-'));
|
|
70
|
+
this.dir = dir;
|
|
71
|
+
for (const s of this.cfg.skills) {
|
|
72
|
+
const d = join(dir, '.agents', 'skills', skillSlug(s));
|
|
73
|
+
mkdirSync(d, { recursive: true });
|
|
74
|
+
writeFileSync(join(d, 'SKILL.md'), s.content);
|
|
75
|
+
}
|
|
76
|
+
return dir;
|
|
77
|
+
}
|
|
78
|
+
/** The server's env (e.g. its auth headers), handed to Codex through its own environment. */
|
|
79
|
+
serverEnv() {
|
|
80
|
+
return proxyServer(this.cfg, this.dir, this.id).env ?? {};
|
|
81
|
+
}
|
|
82
|
+
args(prompt) {
|
|
83
|
+
const server = proxyServer(this.cfg, this.dir, this.id);
|
|
84
|
+
const k = `mcp_servers.${this.key}`;
|
|
85
|
+
const common = [
|
|
86
|
+
'--json',
|
|
87
|
+
'--skip-git-repo-check',
|
|
88
|
+
'-c', 'sandbox_mode="read-only"',
|
|
89
|
+
'-c', 'approval_policy="never"',
|
|
90
|
+
'-c', `${k}.command=${toml(server.command)}`,
|
|
91
|
+
'-c', `${k}.args=${toml(server.args)}`,
|
|
92
|
+
// Your server's tools run without asking, like a user who trusts it (Claude Code: --allowedTools).
|
|
93
|
+
'-c', `${k}.default_tools_approval_mode="approve"`,
|
|
94
|
+
// Only the variable names go on the command line; the values (auth headers) travel in the environment, out of `ps`.
|
|
95
|
+
...(server.env ? ['-c', `${k}.env_vars=${toml(Object.keys(server.env))}`] : []),
|
|
96
|
+
...(this.cfg.setup === 'clean' ? ['--ignore-user-config'] : []),
|
|
97
|
+
...(this.cfg.model ? ['-m', this.cfg.model] : []),
|
|
98
|
+
];
|
|
99
|
+
return this.thread ? ['exec', 'resume', ...common, this.thread, prompt] : ['exec', ...common, prompt];
|
|
100
|
+
}
|
|
101
|
+
send(prompt, emit = () => { }) {
|
|
102
|
+
if (this.busy)
|
|
103
|
+
return Promise.reject(new Error('A turn is already running'));
|
|
104
|
+
this.busy = true;
|
|
105
|
+
const dir = this.dir ?? this.setup();
|
|
106
|
+
const index = this.prompts.length;
|
|
107
|
+
this.prompts.push(prompt);
|
|
108
|
+
const before = structuredClone(this.summary);
|
|
109
|
+
const turnTools = [];
|
|
110
|
+
const out = (e) => (this.events.push(e), emit(e));
|
|
111
|
+
out({ type: 'turn_start', turnIndex: index, prompt });
|
|
112
|
+
let lastAt = performance.now();
|
|
113
|
+
const t0 = performance.now();
|
|
114
|
+
let done = false;
|
|
115
|
+
let turnSteps = 0;
|
|
116
|
+
return new Promise((resolve) => {
|
|
117
|
+
const finish = (stopReason, error) => {
|
|
118
|
+
if (done)
|
|
119
|
+
return;
|
|
120
|
+
done = true;
|
|
121
|
+
this.busy = false;
|
|
122
|
+
const s = this.summary;
|
|
123
|
+
s.stopReason = stopReason;
|
|
124
|
+
s.latencyMs += Math.round(performance.now() - t0);
|
|
125
|
+
if (error)
|
|
126
|
+
out({ type: 'error', message: error });
|
|
127
|
+
const delta = summaryDelta(before, s, turnTools);
|
|
128
|
+
const e = { type: 'turn_end', turnIndex: index, summary: delta };
|
|
129
|
+
this.events.push(e);
|
|
130
|
+
emit(e);
|
|
131
|
+
resolve(delta);
|
|
132
|
+
};
|
|
133
|
+
const proc = spawn(codexBin(), this.args(prompt), { cwd: dir, env: { ...hostEnv(), ...this.serverEnv() }, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
134
|
+
live.add(proc);
|
|
135
|
+
this.proc = proc;
|
|
136
|
+
proc.stderr.on('data', (d) => this.stderr.push(...d.toString().split('\n').filter(Boolean)));
|
|
137
|
+
proc.on('error', (err) => finish('error', `Couldn't start Codex: ${err.message}`));
|
|
138
|
+
proc.on('exit', (code) => {
|
|
139
|
+
live.delete(proc);
|
|
140
|
+
if (this.proc === proc)
|
|
141
|
+
this.proc = undefined;
|
|
142
|
+
if (!done)
|
|
143
|
+
finish(code === 0 ? 'end_turn' : 'error', code === 0 ? undefined : `Codex exited (${code ?? 'killed'}). ${this.stderr.filter((l) => !/Reading additional input/.test(l)).slice(-5).join(' ')}`.trim());
|
|
144
|
+
});
|
|
145
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
146
|
+
createInterface({ input: proc.stdout }).on('line', (line) => {
|
|
147
|
+
if (!line.trim())
|
|
148
|
+
return;
|
|
149
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
150
|
+
let e;
|
|
151
|
+
try {
|
|
152
|
+
e = JSON.parse(line);
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
const s = this.summary;
|
|
158
|
+
const host = s.host;
|
|
159
|
+
if (e.type === 'thread.started') {
|
|
160
|
+
this.thread ??= e.thread_id;
|
|
161
|
+
if (!this.initSent) {
|
|
162
|
+
this.initSent = true;
|
|
163
|
+
out({ type: 'host_init', init: { host: 'Codex', model: this.cfg.model || 'default', serverStatus: 'connected', skillsInstalled: host.skillsInstalled, skillsAvailable: host.skillsInstalled.length, toolCount: 0 } });
|
|
164
|
+
}
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
const step = () => {
|
|
168
|
+
this.steps++;
|
|
169
|
+
turnSteps++;
|
|
170
|
+
s.modelCalls++;
|
|
171
|
+
out({ type: 'model_start', step: this.steps });
|
|
172
|
+
if (turnSteps > this.cfg.maxTurns) {
|
|
173
|
+
proc.kill('SIGTERM');
|
|
174
|
+
finish('max_turns');
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
const item = e.item;
|
|
178
|
+
if (e.type === 'item.started' && item && (item.type === 'mcp_tool_call' || item.type === 'command_execution' || item.type === 'web_search')) {
|
|
179
|
+
if (!this.lastWasTool)
|
|
180
|
+
step();
|
|
181
|
+
this.lastWasTool = true;
|
|
182
|
+
let p;
|
|
183
|
+
if (item.type === 'mcp_tool_call') {
|
|
184
|
+
const ours = item.server === this.key;
|
|
185
|
+
p = { name: ours ? item.tool : `${item.server} · ${item.tool}`, kind: ours ? 'server' : 'other_server', step: this.steps, args: item.arguments ?? {}, t0: performance.now() };
|
|
186
|
+
}
|
|
187
|
+
else if (item.type === 'command_execution' && SKILL_READ.test(item.command ?? '')) {
|
|
188
|
+
p = { name: 'Skill', kind: 'skill', step: this.steps, args: { skill: SKILL_READ.exec(item.command)[1] }, t0: performance.now() };
|
|
189
|
+
}
|
|
190
|
+
else if (item.type === 'command_execution') {
|
|
191
|
+
p = { name: 'shell', kind: 'builtin', step: this.steps, args: { command: String(item.command ?? '').replace(/^\/bin\/\w+ -lc /, '') }, t0: performance.now() };
|
|
192
|
+
}
|
|
193
|
+
else
|
|
194
|
+
p = { name: 'web_search', kind: 'builtin', step: this.steps, args: { query: item.query ?? '' }, t0: performance.now() };
|
|
195
|
+
this.pending.set(item.id, p);
|
|
196
|
+
out({ type: 'tool_start', step: p.step, callId: item.id, name: p.name, args: p.args, kind: p.kind });
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (e.type === 'item.completed' && item) {
|
|
200
|
+
if (item.type === 'agent_message') {
|
|
201
|
+
step();
|
|
202
|
+
this.lastWasTool = false;
|
|
203
|
+
s.finalText = item.text ?? '';
|
|
204
|
+
out({ type: 'model_end', step: this.steps, latencyMs: Math.round(performance.now() - lastAt), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, text: item.text ?? '', calls: [], stopReason: '', model: this.cfg.model || 'codex', raw: null });
|
|
205
|
+
lastAt = performance.now();
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const p = this.pending.get(item.id);
|
|
209
|
+
if (!p)
|
|
210
|
+
return;
|
|
211
|
+
this.pending.delete(item.id);
|
|
212
|
+
let text;
|
|
213
|
+
let isError;
|
|
214
|
+
let denied = false;
|
|
215
|
+
if (item.type === 'mcp_tool_call') {
|
|
216
|
+
const content = (item.result?.content ?? []);
|
|
217
|
+
text = item.error ? String(item.error.message ?? item.error) : content.map((c) => c.text ?? `[${c.type}]`).join('\n');
|
|
218
|
+
isError = !!item.error || !!item.result?.is_error || !!item.result?.isError;
|
|
219
|
+
denied = isError && /approval|declined|denied|cancel/i.test(text);
|
|
220
|
+
}
|
|
221
|
+
else {
|
|
222
|
+
text = String(item.aggregated_output ?? '');
|
|
223
|
+
isError = item.exit_code !== 0 && item.exit_code !== undefined && item.exit_code !== null;
|
|
224
|
+
denied = isError && /sandbox|not permitted|read-only|denied/i.test(text);
|
|
225
|
+
}
|
|
226
|
+
const tokens = estimateTokens(text, /^\s*[[{]/.test(text) ? 'json' : 'prose');
|
|
227
|
+
const flags = p.kind === 'server' ? this.tracker.flags(p.name, p.args, isError, text, tokens) : [];
|
|
228
|
+
if (p.kind === 'server') {
|
|
229
|
+
s.toolCalls++;
|
|
230
|
+
host.usedServer = true;
|
|
231
|
+
if (isError)
|
|
232
|
+
s.toolErrors++;
|
|
233
|
+
if (!s.toolsUsed.includes(p.name))
|
|
234
|
+
s.toolsUsed.push(p.name);
|
|
235
|
+
if (!turnTools.includes(p.name))
|
|
236
|
+
turnTools.push(p.name);
|
|
237
|
+
for (const f of flags)
|
|
238
|
+
s.flags[f] = (s.flags[f] ?? 0) + 1;
|
|
239
|
+
}
|
|
240
|
+
else if (p.kind === 'skill') {
|
|
241
|
+
const skill = String(p.args.skill);
|
|
242
|
+
if (!host.skillsLoaded.includes(skill))
|
|
243
|
+
host.skillsLoaded.push(skill);
|
|
244
|
+
}
|
|
245
|
+
else {
|
|
246
|
+
const o = host.otherTools.find((x) => x.name === p.name) ?? (host.otherTools.push({ name: p.name, count: 0, denied: 0 }), host.otherTools.at(-1));
|
|
247
|
+
o.count++;
|
|
248
|
+
if (denied)
|
|
249
|
+
o.denied++;
|
|
250
|
+
}
|
|
251
|
+
out({ type: 'tool_end', step: p.step, callId: item.id, name: p.name, durationMs: Math.round(performance.now() - p.t0), isError, text, resultTokens: tokens, flags, kind: p.kind, denied });
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
if (e.type === 'turn.completed') {
|
|
255
|
+
const u = e.usage ?? {};
|
|
256
|
+
if (index === 0 && !s.upfrontTokens)
|
|
257
|
+
s.upfrontTokens = 0;
|
|
258
|
+
s.inputTokens += u.input_tokens ?? 0;
|
|
259
|
+
s.cacheReadTokens += u.cached_input_tokens ?? 0;
|
|
260
|
+
s.outputTokens += (u.output_tokens ?? 0) + (u.reasoning_output_tokens ?? 0);
|
|
261
|
+
s.totalTokens = s.inputTokens + s.outputTokens;
|
|
262
|
+
finish('end_turn');
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
if (e.type === 'turn.failed' || e.type === 'error') {
|
|
266
|
+
const msg = String(e.error?.message ?? e.message ?? 'Codex failed');
|
|
267
|
+
// Codex reports MCP startup problems as errors; surface them as a server problem.
|
|
268
|
+
if (/mcp/i.test(msg) && msg.includes(this.key))
|
|
269
|
+
host.serverStatus = 'failed';
|
|
270
|
+
if (e.type === 'turn.failed')
|
|
271
|
+
finish('error', msg);
|
|
272
|
+
else
|
|
273
|
+
out({ type: 'error', message: msg });
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
transcript() {
|
|
279
|
+
return transcriptFromEvents(this.events);
|
|
280
|
+
}
|
|
281
|
+
async close() {
|
|
282
|
+
this.proc?.kill('SIGTERM');
|
|
283
|
+
if (this.dir)
|
|
284
|
+
rmSync(this.dir, { recursive: true, force: true });
|
|
285
|
+
// Keep the developer's Codex history clean.
|
|
286
|
+
if (this.thread)
|
|
287
|
+
await new Promise((r) => execFile(codexBin(), ['delete', '--force', this.thread], { env: hostEnv(), timeout: 15_000 }, r));
|
|
288
|
+
}
|
|
289
|
+
toJSON() {
|
|
290
|
+
return { id: this.id, host: this.hostId, config: { serverName: this.cfg.serverName, skills: this.cfg.skills.map((s) => s.name), model: this.summary.host?.model, setup: this.cfg.setup, label: this.cfg.label }, prompts: this.prompts, events: this.events.map(stripRaw), summary: this.summary, createdAt: new Date().toISOString() };
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
/** One-shot Codex call with a JSON answer (judging, fills), for people who don't have Claude Code. */
|
|
294
|
+
export async function askCodex(prompt, opts = {}) {
|
|
295
|
+
const dir = mkdtempSync(join(tmpdir(), 'mcp-dev-studio-codex-ask-'));
|
|
296
|
+
try {
|
|
297
|
+
const args = ['exec', '--json', '--ephemeral', '--skip-git-repo-check', '--ignore-user-config', '-s', 'read-only', '-c', 'approval_policy="never"', '-o', join(dir, 'out.txt')];
|
|
298
|
+
if (opts.jsonSchema) {
|
|
299
|
+
writeFileSync(join(dir, 'schema.json'), JSON.stringify(opts.jsonSchema));
|
|
300
|
+
args.push('--output-schema', join(dir, 'schema.json'));
|
|
301
|
+
}
|
|
302
|
+
args.push(`${opts.system ? `${opts.system}\n\n` : ''}${prompt}\n\nDon't run any commands; answer directly.`);
|
|
303
|
+
await new Promise((resolve, reject) => {
|
|
304
|
+
const p = spawn(codexBin(), args, { cwd: dir, env: hostEnv(), stdio: ['ignore', 'ignore', 'pipe'] });
|
|
305
|
+
live.add(p);
|
|
306
|
+
let err = '';
|
|
307
|
+
p.stderr.on('data', (d) => (err += d));
|
|
308
|
+
p.on('exit', (code) => (live.delete(p), code === 0 ? resolve() : reject(new Error(`Codex exited ${code}: ${err.trim().slice(-300)}`))));
|
|
309
|
+
p.on('error', reject);
|
|
310
|
+
});
|
|
311
|
+
const { readFileSync } = await import('node:fs');
|
|
312
|
+
const result = readFileSync(join(dir, 'out.txt'), 'utf8').trim();
|
|
313
|
+
let structured;
|
|
314
|
+
if (opts.jsonSchema) {
|
|
315
|
+
try {
|
|
316
|
+
structured = JSON.parse(/\{[\s\S]*\}/.exec(result)?.[0] ?? result);
|
|
317
|
+
}
|
|
318
|
+
catch {
|
|
319
|
+
/* caller falls back to the text */
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return { result, structured };
|
|
323
|
+
}
|
|
324
|
+
finally {
|
|
325
|
+
rmSync(dir, { recursive: true, force: true });
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
//# sourceMappingURL=codex.js.map
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// Host registry: where agents run, and how to grade them.
|
|
2
|
+
import { McpConnection } from '../mcp/connection.js';
|
|
3
|
+
import { AgentSession } from '../agent/runner.js';
|
|
4
|
+
import { providerFor } from '../agent/providers.js';
|
|
5
|
+
import { judgeRun } from '../agent/judge.js';
|
|
6
|
+
import { askClaudeCode, ClaudeCodeSession, detectClaudeCode } from './claude-code.js';
|
|
7
|
+
import { askCodex, CodexSession, detectCodex } from './codex.js';
|
|
8
|
+
import { JUDGE_SCHEMA, JUDGE_SYSTEM, judgePrompt, normalizeVerdict } from '../agent/judge.js';
|
|
9
|
+
export async function detectHosts(store) {
|
|
10
|
+
const [cc, cx] = await Promise.all([detectClaudeCode(), detectCodex()]);
|
|
11
|
+
const s = store.settings();
|
|
12
|
+
const key = store.apiKey(s.provider);
|
|
13
|
+
return [
|
|
14
|
+
{ id: 'claude-code', label: 'Claude Code', available: cc.available, detail: cc.available ? `v${cc.version} · real Claude Code with your server and skills installed` : cc.reason, fix: cc.fix },
|
|
15
|
+
{ id: 'codex', label: 'Codex', available: cx.available, detail: cx.available ? `v${cx.version} · real Codex with your server and skills installed` : cx.reason, fix: cx.fix },
|
|
16
|
+
{ id: 'api', label: 'Bare model', available: !!key, detail: key ? `${s.model} with only your tools. Skills are pasted into the prompt.` : `Needs an ${s.provider === 'anthropic' ? 'Anthropic' : 'OpenAI'} API key` },
|
|
17
|
+
];
|
|
18
|
+
}
|
|
19
|
+
export function createSession(spec, deps) {
|
|
20
|
+
const s = { ...deps.store.settings(), ...spec.settings };
|
|
21
|
+
const host = spec.host ?? s.host;
|
|
22
|
+
const surface = deps.conn.surface;
|
|
23
|
+
if (!surface)
|
|
24
|
+
throw Object.assign(new Error('Not connected to an MCP server'), { status: 503 });
|
|
25
|
+
if (host === 'claude-code' || host === 'codex') {
|
|
26
|
+
return new (host === 'codex' ? CodexSession : ClaudeCodeSession)({
|
|
27
|
+
serverName: surface.server.name,
|
|
28
|
+
target: deps.conn.target,
|
|
29
|
+
overrides: spec.overrides,
|
|
30
|
+
skills: spec.skills,
|
|
31
|
+
model: (host === 'codex' ? s.codexModel : s.hostModel) || undefined,
|
|
32
|
+
maxTurns: s.maxTurns,
|
|
33
|
+
maxBudgetUsd: s.maxBudgetUsd,
|
|
34
|
+
setup: s.hostSetup,
|
|
35
|
+
ingestUrl: deps.ingestUrl,
|
|
36
|
+
storeRoot: deps.store.root,
|
|
37
|
+
label: spec.label,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
const key = deps.store.apiKey(s.provider);
|
|
41
|
+
if (!key)
|
|
42
|
+
throw Object.assign(new Error(`The bare-model host needs an ${s.provider} API key (Settings).`), { status: 400 });
|
|
43
|
+
// A fresh server process per session, so runs never see each other's data.
|
|
44
|
+
const own = new McpConnection(deps.conn.target, { watch: [], poll: false, onTraffic: (e) => deps.store.appendTraffic([e]) });
|
|
45
|
+
return new AgentSession(own, providerFor(s.provider, key), { ...s, overrides: spec.overrides, skills: spec.skills, label: spec.label }, deps.source ?? 'sandbox', true);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* A one-shot, tool-less answer from whichever agent CLI the developer has:
|
|
49
|
+
* Claude Code first, else Codex. Runs on their plan; no API key needed.
|
|
50
|
+
*/
|
|
51
|
+
export async function askAgent(prompt, opts = {}) {
|
|
52
|
+
const [cc, cx] = await Promise.all([detectClaudeCode(), detectCodex()]);
|
|
53
|
+
const useCodex = cx.available && (!cc.available || opts.prefer === 'codex');
|
|
54
|
+
if (useCodex)
|
|
55
|
+
return askCodex(prompt, opts);
|
|
56
|
+
if (!cc.available)
|
|
57
|
+
throw Object.assign(new Error(`${cc.reason} (or install Codex). Run: ${cc.fix}`), { status: 400 });
|
|
58
|
+
return askClaudeCode(prompt, { ...opts, model: opts.small ? 'haiku' : undefined });
|
|
59
|
+
}
|
|
60
|
+
export async function anyAgentAvailable() {
|
|
61
|
+
const [cc, cx] = await Promise.all([detectClaudeCode(), detectCodex()]);
|
|
62
|
+
return cc.available || cx.available;
|
|
63
|
+
}
|
|
64
|
+
/** Grade on the same footing as the run: agent runs are graded by an agent on the developer's plan (no key needed). */
|
|
65
|
+
export async function judge(session, criteria, store) {
|
|
66
|
+
const s = store.settings();
|
|
67
|
+
const key = store.apiKey(s.provider);
|
|
68
|
+
if (session.hostId !== 'api' || !key) {
|
|
69
|
+
try {
|
|
70
|
+
const r = await askAgent(judgePrompt(session.transcript(), criteria), { system: JUDGE_SYSTEM, jsonSchema: JUDGE_SCHEMA, prefer: session.hostId, small: true });
|
|
71
|
+
if (r.structured && typeof r.structured === 'object')
|
|
72
|
+
return normalizeVerdict(r.structured);
|
|
73
|
+
const m = /\{[\s\S]*\}/.exec(r.result);
|
|
74
|
+
if (!m)
|
|
75
|
+
throw new Error(`judge gave no verdict: ${r.result.slice(0, 200)}`);
|
|
76
|
+
return normalizeVerdict(JSON.parse(m[0]));
|
|
77
|
+
}
|
|
78
|
+
catch (e) {
|
|
79
|
+
if (!key)
|
|
80
|
+
throw e;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return judgeRun(providerFor(s.provider, key), s.model, session.transcript(), criteria);
|
|
84
|
+
}
|
|
85
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// The models each agent can run, for the Playground's picker.
|
|
2
|
+
//
|
|
3
|
+
// Codex: the list Codex itself caches for your account (~/.codex/models_cache.json),
|
|
4
|
+
// so it's current and only shows what you can use. Claude Code: the current
|
|
5
|
+
// Claude lineup (Claude Code takes these ids with --model).
|
|
6
|
+
import { readFileSync } from 'node:fs';
|
|
7
|
+
import { homedir } from 'node:os';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
const CLAUDE = [
|
|
10
|
+
{ id: 'claude-fable-5-2', name: 'Fable 5.2', latest: true },
|
|
11
|
+
{ id: 'claude-opus-5-5', name: 'Opus 5.5', latest: true },
|
|
12
|
+
{ id: 'claude-sonnet-5-5', name: 'Sonnet 5.5', latest: true },
|
|
13
|
+
{ id: 'claude-haiku-5-5', name: 'Haiku 5.5', note: 'Fastest', latest: true },
|
|
14
|
+
];
|
|
15
|
+
function codexHome() {
|
|
16
|
+
return process.env.CODEX_HOME || join(homedir(), '.codex');
|
|
17
|
+
}
|
|
18
|
+
/** Codex's configured default model, from config.toml (just the top-level `model = "…"`). */
|
|
19
|
+
function codexDefault() {
|
|
20
|
+
try {
|
|
21
|
+
const toml = readFileSync(join(codexHome(), 'config.toml'), 'utf8');
|
|
22
|
+
return /^model\s*=\s*"([^"]+)"/m.exec(toml)?.[1];
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function codexModels() {
|
|
29
|
+
try {
|
|
30
|
+
const cache = JSON.parse(readFileSync(join(codexHome(), 'models_cache.json'), 'utf8'));
|
|
31
|
+
const listed = (cache.models ?? []).filter((m) => m.visibility === 'list').sort((a, b) => (a.priority ?? 99) - (b.priority ?? 99));
|
|
32
|
+
// Codex orders them newest-and-best first; descriptions say which are previous generations.
|
|
33
|
+
return listed.map((m, i) => ({
|
|
34
|
+
id: m.slug,
|
|
35
|
+
name: m.display_name ?? m.slug,
|
|
36
|
+
...(m.description ? { note: m.description.replace(/\.$/, '') } : {}),
|
|
37
|
+
...(i === 0 || (!/previous|legacy/i.test(m.description ?? '') && i < 3) ? { latest: true } : {}),
|
|
38
|
+
}));
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return [];
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export function modelOptions(settings) {
|
|
45
|
+
const cxDefault = settings.codexModel || codexDefault();
|
|
46
|
+
return {
|
|
47
|
+
'claude-code': [{ id: '', name: 'Default', note: settings.hostModel ? `Your setting: ${settings.hostModel}` : 'Your Claude Code default' }, ...CLAUDE],
|
|
48
|
+
codex: [{ id: '', name: 'Default', note: cxDefault ? `Your setting: ${cxDefault}` : 'Your Codex default' }, ...codexModels()],
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
//# sourceMappingURL=models.js.map
|