@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/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Chapter Dev Pty Ltd
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,80 @@
|
|
|
1
|
-
#
|
|
1
|
+
# <img src="docs/logo.svg" alt="Chapter" height="36" align="absmiddle"> mcp-dev-studio
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@chapterdev/mcp-dev-studio) [](LICENSE)
|
|
4
|
+
|
|
5
|
+
### Test your MCP server and skills with real agents
|
|
6
|
+
|
|
7
|
+
MCP Dev Studio lets you:
|
|
8
|
+
|
|
9
|
+
1. **Test your MCP locally:** see if agents call the right tool and load the right skill.
|
|
10
|
+
2. **Run evals:** repeat every test in Claude Code and Codex and get a pass rate.
|
|
11
|
+
3. **Compare models:** one prompt, several agents and models, answers side by side.
|
|
12
|
+
4. **Auto-fix with your agent:** it writes tests aimed at your weak spots, then fixes your tool descriptions and skills until they pass.
|
|
13
|
+
|
|
14
|
+

|
|
15
|
+
|
|
16
|
+
## Quickstart
|
|
17
|
+
|
|
18
|
+
In your MCP server's repo:
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npx @chapterdev/mcp-dev-studio
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
It finds your server and opens the studio. Then let your agent do the iterating:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npx @chapterdev/mcp-dev-studio setup
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Now ask your agent to:
|
|
31
|
+
|
|
32
|
+
> Test my MCP server in Claude Code and Codex, and fix whatever fails.
|
|
33
|
+
|
|
34
|
+
> [!NOTE]
|
|
35
|
+
> You'll need Claude Code or Codex installed and signed in. Runs use your own plan.
|
|
36
|
+
|
|
37
|
+
## Why do I need a studio?
|
|
38
|
+
|
|
39
|
+
Your server can pass every unit test and still fail the agents that use it:
|
|
40
|
+
|
|
41
|
+
- **It never gets called.** The agent answers from memory, or reaches for another tool. The
|
|
42
|
+
studio shows whether your server was used in every answer.
|
|
43
|
+
- **The wrong tool gets picked.** Overlapping names and vague descriptions send agents down the
|
|
44
|
+
wrong path. The studio records every call, so you can see where they went.
|
|
45
|
+
- **Skills load at the wrong time.** A skill that never loads is wasted; one that loads for
|
|
46
|
+
everything gets in the way. Trigger tests check both.
|
|
47
|
+
- **Claude and Codex behave differently.** Run the same chat on both, side by side, on any model.
|
|
48
|
+
|
|
49
|
+
## Evals
|
|
50
|
+
|
|
51
|
+
Agents vary, so every test runs several times in real agents and reports a pass rate, with a
|
|
52
|
+
history of what changed and what it fixed. Run them from the studio, or from your terminal while
|
|
53
|
+
the studio follows along live.
|
|
54
|
+
|
|
55
|
+

|
|
56
|
+
|
|
57
|
+
> [!IMPORTANT]
|
|
58
|
+
> Tests call your real server. Hide any tool that changes real data before testing it.
|
|
59
|
+
|
|
60
|
+
## Features
|
|
61
|
+
|
|
62
|
+
- Playground with Claude Code and Codex side by side, on any model
|
|
63
|
+
- Skill editor with trigger tests
|
|
64
|
+
- Tests with pass rates, run live from the UI or your terminal
|
|
65
|
+
- History of every attempt: what changed, and what it fixed or broke
|
|
66
|
+
- Finds your server on its own, with nothing to configure
|
|
67
|
+
- Everything stays on your machine; tests can be shared with your team in the repo
|
|
68
|
+
|
|
69
|
+
## For AI agents
|
|
70
|
+
|
|
71
|
+
Asked to test or improve an MCP server with this studio? Don't clone this repository: it runs
|
|
72
|
+
from its npm package.
|
|
73
|
+
|
|
74
|
+
1. Run `npx @chapterdev/mcp-dev-studio setup` in the user's project. It installs the
|
|
75
|
+
`mcp-dev-studio` skill.
|
|
76
|
+
2. Read that skill's `SKILL.md` and follow it.
|
|
77
|
+
|
|
78
|
+
## Licence
|
|
79
|
+
|
|
80
|
+
MIT
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// "Fill with AI": a model writes realistic test arguments for one tool.
|
|
2
|
+
// It may invent free fields (titles, prompts, limits), but a reference must be
|
|
3
|
+
// a value the server actually returned; anything else is dropped, not trusted.
|
|
4
|
+
import { anthropicProvider } from './providers.js';
|
|
5
|
+
import { askAgent } from '../hosts/index.js';
|
|
6
|
+
const SCHEMA = {
|
|
7
|
+
type: 'object',
|
|
8
|
+
properties: {
|
|
9
|
+
args_json: { type: 'string', description: 'The arguments, as a JSON object.' },
|
|
10
|
+
notes: { type: 'string', description: 'At most 12 words: what this call will test.' },
|
|
11
|
+
},
|
|
12
|
+
required: ['args_json', 'notes'],
|
|
13
|
+
additionalProperties: false,
|
|
14
|
+
};
|
|
15
|
+
const SYSTEM = `You write arguments for testing one tool of an MCP server by hand. Reply with JSON only.
|
|
16
|
+
Rules:
|
|
17
|
+
- A field marked "reference" points at something that must already exist. Use only a value from its known values or from the server responses shown. If nothing fits, leave the field out. Never invent an id, name or path for a reference.
|
|
18
|
+
- Other fields are yours to invent. Make them realistic and specific to this product, the way a real user would write them, not "test" or "foo".
|
|
19
|
+
- Fill every required field you can. Include an optional field only when it makes the test more realistic.`;
|
|
20
|
+
export async function fillWithModel(tool, plan, samples, intent, opts) {
|
|
21
|
+
const props = tool.inputSchema?.properties ?? {};
|
|
22
|
+
const refs = Object.entries(plan.fields).filter(([, f]) => f.kind === 'ref');
|
|
23
|
+
const sources = new Set(refs.flatMap(([, f]) => [f.lookup?.tool, ...f.candidates.map((c) => c.from.replace(/^used in /, ''))]).filter(Boolean));
|
|
24
|
+
const relevant = samples.filter((s) => sources.has(s.tool) || s.tool === tool.name).slice(0, 8);
|
|
25
|
+
const prompt = [
|
|
26
|
+
`Tool: ${tool.name}`,
|
|
27
|
+
tool.description ? `Description: ${tool.description}` : '',
|
|
28
|
+
`Input schema:\n${JSON.stringify(tool.inputSchema).slice(0, 24000)}`,
|
|
29
|
+
refs.length
|
|
30
|
+
? `Reference fields and their known values:\n${refs.map(([k, f]) => `- ${k}: ${f.candidates.length ? f.candidates.slice(0, 12).map((c) => `${JSON.stringify(c.value)}${c.label ? ` (${c.label})` : ''}`).join(', ') : 'none known'}`).join('\n')}`
|
|
31
|
+
: 'No reference fields.',
|
|
32
|
+
plan.lastCall ? `The last call that worked used: ${JSON.stringify(plan.lastCall.args).slice(0, 1500)}` : '',
|
|
33
|
+
relevant.length ? `Recent server responses:\n${relevant.map((s) => `[${s.tool} ${JSON.stringify(s.args ?? {})}]\n${s.text.slice(0, 1800)}`).join('\n\n')}` : '',
|
|
34
|
+
intent ? `What the developer wants to test: ${intent}` : '',
|
|
35
|
+
]
|
|
36
|
+
.filter(Boolean)
|
|
37
|
+
.join('\n\n');
|
|
38
|
+
let out;
|
|
39
|
+
if (opts.key) {
|
|
40
|
+
out = await anthropicProvider(opts.key).json({ model: 'claude-haiku-5-5', system: SYSTEM, prompt, schema: SCHEMA, maxTokens: 2000 });
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
const r = await askAgent(prompt, { system: SYSTEM, small: true, jsonSchema: SCHEMA });
|
|
44
|
+
out = r.structured ?? JSON.parse(/\{[\s\S]*\}/.exec(r.result)?.[0] ?? '{}');
|
|
45
|
+
}
|
|
46
|
+
let args = {};
|
|
47
|
+
try {
|
|
48
|
+
args = JSON.parse(out.args_json ?? '{}');
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
throw new Error('The model returned arguments that were not valid JSON');
|
|
52
|
+
}
|
|
53
|
+
// Keep only known fields, and only references we can trace to real data.
|
|
54
|
+
const seen = (v) => {
|
|
55
|
+
const s = String(v);
|
|
56
|
+
return refs.some(([, f]) => f.candidates.some((c) => c.value === s)) || samples.some((x) => x.text.includes(s));
|
|
57
|
+
};
|
|
58
|
+
const dropped = [];
|
|
59
|
+
for (const k of Object.keys(args)) {
|
|
60
|
+
if (!(k in props))
|
|
61
|
+
delete args[k];
|
|
62
|
+
else if (plan.fields[k]?.kind === 'ref' && !(Array.isArray(args[k]) ? args[k].every(seen) : seen(args[k]))) {
|
|
63
|
+
dropped.push(k);
|
|
64
|
+
delete args[k];
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return { args, notes: out.notes ?? '', dropped };
|
|
68
|
+
}
|
|
69
|
+
//# sourceMappingURL=fill.js.map
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// LLM-as-judge: did the agent actually do what was asked?
|
|
2
|
+
// Runs on the bare API (a key) or through the host (src/hosts/claude-code.ts).
|
|
3
|
+
export const JUDGE_SCHEMA = {
|
|
4
|
+
type: 'object',
|
|
5
|
+
properties: {
|
|
6
|
+
pass: { type: 'boolean', description: 'True only if the criteria are fully met' },
|
|
7
|
+
score: { type: 'number', description: '0 to 1: how completely the criteria are met' },
|
|
8
|
+
reason: { type: 'string', description: 'One or two sentences citing what the agent did or failed to do' },
|
|
9
|
+
},
|
|
10
|
+
required: ['pass', 'score', 'reason'],
|
|
11
|
+
additionalProperties: false,
|
|
12
|
+
};
|
|
13
|
+
export const JUDGE_SYSTEM = 'You grade transcripts of an AI agent using tools. Judge only from the transcript: tool results are ground truth; the agent claiming success is not evidence. Be strict.';
|
|
14
|
+
export function judgePrompt(transcript, criteria) {
|
|
15
|
+
return `<transcript>\n${transcript}\n</transcript>\n\n<criteria>\n${criteria}\n</criteria>\n\nDid the agent meet the criteria? Answer as JSON: {"pass": boolean, "score": number 0-1, "reason": string}.`;
|
|
16
|
+
}
|
|
17
|
+
export function normalizeVerdict(v) {
|
|
18
|
+
return { pass: !!v.pass, score: Math.max(0, Math.min(1, Number(v.score) || 0)), reason: String(v.reason ?? '') };
|
|
19
|
+
}
|
|
20
|
+
export async function judgeRun(provider, model, transcript, criteria) {
|
|
21
|
+
const v = await provider.json({ model, system: JUDGE_SYSTEM, prompt: judgePrompt(transcript, criteria), schema: JUDGE_SCHEMA });
|
|
22
|
+
return normalizeVerdict(v);
|
|
23
|
+
}
|
|
24
|
+
//# sourceMappingURL=judge.js.map
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// The skill that teaches a coding agent (Claude Code, Codex) to iterate on an
|
|
2
|
+
// MCP server and its skills with mcp-dev-studio, while a person watches in the UI.
|
|
3
|
+
// `mcp-dev-studio setup` writes it into the project, stamped with the version that wrote it,
|
|
4
|
+
// so `eval` can tell people (and their agents) when an upgrade brought a newer one.
|
|
5
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
export const SKILL_DIRS = ['.claude/skills/mcp-dev-studio', '.agents/skills/mcp-dev-studio'];
|
|
8
|
+
export function loopSkill(p) {
|
|
9
|
+
return `---
|
|
10
|
+
name: mcp-dev-studio
|
|
11
|
+
description: Improve an MCP server's tool descriptions or its SKILL.md files by testing them in real agents (Claude Code, Codex) with mcp-dev-studio, then changing one thing at a time until the tests pass. Use when asked to fix, tune or test how agents use this MCP server or its skills, or why a skill does or doesn't load.
|
|
12
|
+
---
|
|
13
|
+
${p.version ? `\n<!-- Written by mcp-dev-studio ${p.version}. Update with: npx @chapterdev/mcp-dev-studio setup -->\n` : ''}
|
|
14
|
+
# Iterating with mcp-dev-studio
|
|
15
|
+
|
|
16
|
+
mcp-dev-studio runs saved tests against ${p.server} in real Claude Code and Codex, several times each, and records every run as an attempt. The person you're working with may have the studio open (\`npx @chapterdev/mcp-dev-studio\`); it shows each run live and the history of attempts, so leave notes that read well there.
|
|
17
|
+
|
|
18
|
+
## Write tests that can fail
|
|
19
|
+
|
|
20
|
+
The loop only finds what the tests probe, and happy-path tests usually pass. Before the baseline, read the server's tools (descriptions and parameters) and its skills, and list every weak spot you notice. Write at least one test aimed at each:
|
|
21
|
+
|
|
22
|
+
- **Vague or missing parameter descriptions**: ask the way a person would, not the way the schema wants. If a parameter takes an id but doesn't say so, ask to act on the item by its name.
|
|
23
|
+
- **Bare tool descriptions**: a prompt that needs what the description leaves out, like allowed values or formats.
|
|
24
|
+
- **Overlapping tools**: a prompt only one of them should handle, with \`forbidTools\` for the other.
|
|
25
|
+
- **Over-broad or vague skill descriptions**: a should-load test (\`expectSkills\`) and a shouldn't-load test (\`forbidSkills\`) on a nearby but unrelated prompt.
|
|
26
|
+
|
|
27
|
+
Make the checks strict enough to catch the agent working around the flaw. A capable agent recovers from a failed call with extra lookups and still gets there, so set \`maxToolCalls\` to what a clear description would need, or have \`judge\` require no failed tool calls.
|
|
28
|
+
|
|
29
|
+
Test only the agents the person asked for (\`--host claude-code\` if they said Claude Code); otherwise both.
|
|
30
|
+
|
|
31
|
+
## The loop
|
|
32
|
+
|
|
33
|
+
1. **Baseline.** \`npx @chapterdev/mcp-dev-studio eval --json --host claude-code,codex --note "baseline"\` (or just the agents the person asked for)
|
|
34
|
+
2. **Read why it failed.** In the JSON, each failing test has \`failures\` (check, detail, how many runs) and \`transcripts\`. Open a transcript before guessing: \`events\` shows every tool call and what the agent said.
|
|
35
|
+
3. **Change one thing** that explains the failure (see "What to change").
|
|
36
|
+
4. **Rerun what failed**, saying what you changed: \`npx @chapterdev/mcp-dev-studio eval --json --failed --host <same hosts> --note "<the change, in a few words>"\`. \`sinceLastAttempt.tests\` says which tests were fixed or broke.
|
|
37
|
+
5. **Check for regressions** with a full run once the failures pass. A change that fixes one test and breaks another isn't done.
|
|
38
|
+
6. **Keep or revert.** If an attempt made things worse, undo the change before trying the next idea.
|
|
39
|
+
7. **Stop** when everything passes, or after about five attempts without progress. Then say what you changed, what each attempt showed, and what's still failing.
|
|
40
|
+
|
|
41
|
+
A suite that passes on its first run hasn't found anything yet. Before calling it done, check the transcripts for workarounds (failed calls, extra lookups, guessed values), add harder tests for the weak spots you listed, and run again. If a weak spot still won't fail, say so rather than leaving it out.
|
|
42
|
+
|
|
43
|
+
Agents vary, so results are rates. Explore with \`--trials 1\` and confirm with the default (3) before calling something fixed. Every run is real agent time; rerun only what you need.
|
|
44
|
+
|
|
45
|
+
## What to change
|
|
46
|
+
|
|
47
|
+
- **A skill doesn't load, or loads when it shouldn't**: its \`description\` in the frontmatter is what agents choose by. Make it say when to use the skill and when not to. Skills are in \`${p.skills}/\`.
|
|
48
|
+
- **The agent picks the wrong tool, or misuses one**: the tool's description. Either edit it in the server's source (the studio restarts the server when files change), or try it first in \`${p.store}/overrides.json\` (\`{ "tool_name": { "description": "..." } }\`), which only changes what agents see in tests.
|
|
49
|
+
- **The skill says the wrong thing**: its body. Name tools in backticks exactly as the server names them.
|
|
50
|
+
- **The test is wrong**: change it, but say so. Never weaken a test just to make it pass; tests are the intent.
|
|
51
|
+
|
|
52
|
+
## Tests
|
|
53
|
+
|
|
54
|
+
Tests are JSON files in \`${p.tests}/\`. Add one for each weak spot (see above), and when the person describes behaviour no test covers:
|
|
55
|
+
|
|
56
|
+
\`\`\`json
|
|
57
|
+
{
|
|
58
|
+
"slug": "plain-lookup-skips-playbook",
|
|
59
|
+
"name": "A plain lookup doesn't load the playbook",
|
|
60
|
+
"prompts": ["List our projects."],
|
|
61
|
+
"skills": ["*"],
|
|
62
|
+
"assertions": {
|
|
63
|
+
"expectTools": ["list_projects"],
|
|
64
|
+
"forbidSkills": ["playbook"],
|
|
65
|
+
"maxTurns": 6
|
|
66
|
+
},
|
|
67
|
+
"createdAt": "2026-01-01T00:00:00.000Z"
|
|
68
|
+
}
|
|
69
|
+
\`\`\`
|
|
70
|
+
|
|
71
|
+
\`prompts\` is the conversation, one user message each. Assertions, all optional:
|
|
72
|
+
- \`usesServer\` (default true): must call at least one of the server's tools.
|
|
73
|
+
- \`expectTools\` / \`forbidTools\`: tool names that must or mustn't be called.
|
|
74
|
+
- \`expectSkills\` / \`forbidSkills\`: skill names that must or mustn't load.
|
|
75
|
+
- \`maxTurns\`, \`maxToolCalls\`, \`maxTokens\`: limits.
|
|
76
|
+
- \`judge\`: plain-language success criteria, graded by a model from the transcript.
|
|
77
|
+
- \`minPasses\`: how many runs must pass (default: all).
|
|
78
|
+
|
|
79
|
+
Run one test with \`--journey <part of its slug or name>\`.
|
|
80
|
+
|
|
81
|
+
## Careful
|
|
82
|
+
|
|
83
|
+
Tests call the real server. If a tool changes real data (creates, sends, deletes), hide it in \`${p.store}/overrides.json\` with \`{ "tool_name": { "hidden": true } }\` unless the test is about that tool, and say so before running.
|
|
84
|
+
`;
|
|
85
|
+
}
|
|
86
|
+
/** Installed copies of the loop skill written by an older version (or before versions were stamped). */
|
|
87
|
+
export function outdatedSkills(project, version) {
|
|
88
|
+
const older = (a, b) => {
|
|
89
|
+
const [x, y] = [a, b].map((v) => v.split(/[.-]/).slice(0, 3).map(Number));
|
|
90
|
+
for (let i = 0; i < 3; i++)
|
|
91
|
+
if (x[i] !== y[i])
|
|
92
|
+
return (x[i] ?? 0) < (y[i] ?? 0);
|
|
93
|
+
return false;
|
|
94
|
+
};
|
|
95
|
+
return SKILL_DIRS.map((d) => join(d, 'SKILL.md')).filter((f) => {
|
|
96
|
+
const path = join(project, f);
|
|
97
|
+
if (!existsSync(path))
|
|
98
|
+
return false;
|
|
99
|
+
const stamp = /Written by mcp-dev-studio (\d+\.\d+\.\d+)/.exec(readFileSync(path, 'utf8'))?.[1];
|
|
100
|
+
return !stamp || older(stamp, version);
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
//# sourceMappingURL=loop-skill.js.map
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// Model providers behind one small interface, so the runner, judge and skill
|
|
2
|
+
// generator don't care whether a run is on Claude or OpenAI.
|
|
3
|
+
//
|
|
4
|
+
// Transcripts are kept provider-neutral, except that Anthropic assistant turns
|
|
5
|
+
// also keep their raw content blocks: they are replayed verbatim on the next
|
|
6
|
+
// request, which preserves thinking blocks (required on current Claude models).
|
|
7
|
+
import Anthropic from '@anthropic-ai/sdk';
|
|
8
|
+
import OpenAI from 'openai';
|
|
9
|
+
import { safeToolName } from '../analysis/tokens.js';
|
|
10
|
+
// Models that accept server-side refusal fallbacks (beta). Others get a plain request.
|
|
11
|
+
const FALLBACK_MODELS = /^claude-(opus-5|opus-5-5|fable-5|fable-5-1|fable-5-2|sonnet-5-5)$/;
|
|
12
|
+
export function anthropicProvider(apiKey) {
|
|
13
|
+
const client = new Anthropic({ apiKey, maxRetries: 3 });
|
|
14
|
+
const nameMap = new Map();
|
|
15
|
+
const toMessages = (turns) => {
|
|
16
|
+
const out = [];
|
|
17
|
+
const push = (role, content) => {
|
|
18
|
+
const last = out[out.length - 1];
|
|
19
|
+
if (last && last.role === role && Array.isArray(last.content))
|
|
20
|
+
last.content.push(...content);
|
|
21
|
+
else
|
|
22
|
+
out.push({ role, content });
|
|
23
|
+
};
|
|
24
|
+
for (const t of turns) {
|
|
25
|
+
if (t.role === 'user')
|
|
26
|
+
push('user', [{ type: 'text', text: t.text }]);
|
|
27
|
+
else if (t.role === 'assistant') {
|
|
28
|
+
if (t.provider === 'anthropic' && Array.isArray(t.raw))
|
|
29
|
+
push('assistant', t.raw);
|
|
30
|
+
else
|
|
31
|
+
push('assistant', [
|
|
32
|
+
...(t.text ? [{ type: 'text', text: t.text }] : []),
|
|
33
|
+
...t.calls.map((c) => ({ type: 'tool_use', id: c.id, name: safeToolName(c.name), input: c.args })),
|
|
34
|
+
]);
|
|
35
|
+
}
|
|
36
|
+
else
|
|
37
|
+
push('user', t.results.map((r) => ({ type: 'tool_result', tool_use_id: r.id, content: r.text || '(empty result)', is_error: r.isError || undefined })));
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
};
|
|
41
|
+
const create = (params) => {
|
|
42
|
+
const fallback = FALLBACK_MODELS.test(params.model);
|
|
43
|
+
return client.beta.messages.create({
|
|
44
|
+
...params,
|
|
45
|
+
...(fallback ? { betas: ['server-side-fallback-2026-07-01'], fallbacks: 'default' } : {}),
|
|
46
|
+
});
|
|
47
|
+
};
|
|
48
|
+
return {
|
|
49
|
+
id: 'anthropic',
|
|
50
|
+
async chat({ model, system, turns, tools, effort, maxTokens }) {
|
|
51
|
+
for (const t of tools)
|
|
52
|
+
nameMap.set(safeToolName(t.name), t.name);
|
|
53
|
+
const res = await create({
|
|
54
|
+
model,
|
|
55
|
+
max_tokens: maxTokens ?? 16000,
|
|
56
|
+
system,
|
|
57
|
+
messages: toMessages(turns),
|
|
58
|
+
tools: tools.map((t) => ({ name: safeToolName(t.name), description: t.description, input_schema: { ...t.input_schema, type: 'object' } })),
|
|
59
|
+
...(effort ? { output_config: { effort: effort } } : {}),
|
|
60
|
+
});
|
|
61
|
+
const text = res.content.flatMap((b) => (b.type === 'text' ? [b.text] : [])).join('\n');
|
|
62
|
+
const calls = res.content.flatMap((b) => (b.type === 'tool_use' ? [{ id: b.id, name: nameMap.get(b.name) ?? b.name, args: (b.input ?? {}) }] : []));
|
|
63
|
+
return {
|
|
64
|
+
text,
|
|
65
|
+
calls,
|
|
66
|
+
usage: { input: res.usage.input_tokens, output: res.usage.output_tokens, cacheRead: res.usage.cache_read_input_tokens ?? 0, cacheWrite: res.usage.cache_creation_input_tokens ?? 0 },
|
|
67
|
+
stopReason: res.stop_reason ?? 'unknown',
|
|
68
|
+
raw: res.content,
|
|
69
|
+
model: res.model,
|
|
70
|
+
};
|
|
71
|
+
},
|
|
72
|
+
async json({ model, system, prompt, schema, maxTokens }) {
|
|
73
|
+
const res = await create({
|
|
74
|
+
model,
|
|
75
|
+
max_tokens: maxTokens ?? 4000,
|
|
76
|
+
system,
|
|
77
|
+
messages: [{ role: 'user', content: prompt }],
|
|
78
|
+
output_config: { effort: 'low', format: { type: 'json_schema', schema } },
|
|
79
|
+
});
|
|
80
|
+
if (res.stop_reason === 'refusal')
|
|
81
|
+
throw new Error('Model refused the request');
|
|
82
|
+
const text = res.content.flatMap((b) => (b.type === 'text' ? [b.text] : [])).join('');
|
|
83
|
+
return JSON.parse(text);
|
|
84
|
+
},
|
|
85
|
+
async text({ model, system, prompt, maxTokens }) {
|
|
86
|
+
const res = await create({ model, max_tokens: maxTokens ?? 8000, system, messages: [{ role: 'user', content: prompt }] });
|
|
87
|
+
if (res.stop_reason === 'refusal')
|
|
88
|
+
throw new Error('Model refused the request');
|
|
89
|
+
return res.content.flatMap((b) => (b.type === 'text' ? [b.text] : [])).join('\n');
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
export function openaiProvider(apiKey) {
|
|
94
|
+
const client = new OpenAI({ apiKey });
|
|
95
|
+
const nameMap = new Map();
|
|
96
|
+
const fn = (n) => safeToolName(n).slice(0, 64);
|
|
97
|
+
const toMessages = (system, turns) => {
|
|
98
|
+
const out = [{ role: 'system', content: system }];
|
|
99
|
+
for (const t of turns) {
|
|
100
|
+
if (t.role === 'user')
|
|
101
|
+
out.push({ role: 'user', content: t.text });
|
|
102
|
+
else if (t.role === 'assistant')
|
|
103
|
+
out.push({
|
|
104
|
+
role: 'assistant',
|
|
105
|
+
content: t.text || null,
|
|
106
|
+
...(t.calls.length ? { tool_calls: t.calls.map((c) => ({ id: c.id, type: 'function', function: { name: fn(c.name), arguments: JSON.stringify(c.args) } })) } : {}),
|
|
107
|
+
});
|
|
108
|
+
else
|
|
109
|
+
for (const r of t.results)
|
|
110
|
+
out.push({ role: 'tool', tool_call_id: r.id, content: (r.isError ? 'ERROR: ' : '') + (r.text || '(empty result)') });
|
|
111
|
+
}
|
|
112
|
+
return out;
|
|
113
|
+
};
|
|
114
|
+
return {
|
|
115
|
+
id: 'openai',
|
|
116
|
+
async chat({ model, system, turns, tools, effort }) {
|
|
117
|
+
for (const t of tools)
|
|
118
|
+
nameMap.set(fn(t.name), t.name);
|
|
119
|
+
const res = await client.chat.completions.create({
|
|
120
|
+
model,
|
|
121
|
+
messages: toMessages(system, turns),
|
|
122
|
+
...(tools.length ? { tools: tools.map((t) => ({ type: 'function', function: { name: fn(t.name), description: t.description, parameters: t.input_schema } })) } : {}),
|
|
123
|
+
...(effort && /^(o\d|gpt-5)/.test(model) ? { reasoning_effort: (effort === 'xhigh' || effort === 'max' ? 'high' : effort) } : {}),
|
|
124
|
+
});
|
|
125
|
+
const choice = res.choices[0];
|
|
126
|
+
const calls = (choice.message.tool_calls ?? []).flatMap((c) => c.type === 'function' ? [{ id: c.id, name: nameMap.get(c.function.name) ?? c.function.name, args: safeJson(c.function.arguments) }] : []);
|
|
127
|
+
return {
|
|
128
|
+
text: choice.message.content ?? '',
|
|
129
|
+
calls,
|
|
130
|
+
usage: { input: res.usage?.prompt_tokens ?? 0, output: res.usage?.completion_tokens ?? 0, cacheRead: res.usage?.prompt_tokens_details?.cached_tokens ?? 0, cacheWrite: 0 },
|
|
131
|
+
stopReason: choice.finish_reason === 'tool_calls' ? 'tool_use' : choice.finish_reason === 'stop' ? 'end_turn' : choice.finish_reason,
|
|
132
|
+
raw: choice.message,
|
|
133
|
+
model: res.model,
|
|
134
|
+
};
|
|
135
|
+
},
|
|
136
|
+
async json({ model, system, prompt, schema }) {
|
|
137
|
+
const res = await client.chat.completions.create({
|
|
138
|
+
model,
|
|
139
|
+
messages: [{ role: 'system', content: system }, { role: 'user', content: prompt }],
|
|
140
|
+
response_format: { type: 'json_schema', json_schema: { name: 'result', schema, strict: true } },
|
|
141
|
+
});
|
|
142
|
+
return JSON.parse(res.choices[0].message.content ?? '{}');
|
|
143
|
+
},
|
|
144
|
+
async text({ model, system, prompt }) {
|
|
145
|
+
const res = await client.chat.completions.create({ model, messages: [{ role: 'system', content: system }, { role: 'user', content: prompt }] });
|
|
146
|
+
return res.choices[0].message.content ?? '';
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
function safeJson(s) {
|
|
151
|
+
try {
|
|
152
|
+
const v = JSON.parse(s || '{}');
|
|
153
|
+
return v && typeof v === 'object' ? v : {};
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
return { _unparseable: s };
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
export function providerFor(id, apiKey) {
|
|
160
|
+
return id === 'anthropic' ? anthropicProvider(apiKey) : openaiProvider(apiKey);
|
|
161
|
+
}
|
|
162
|
+
//# sourceMappingURL=providers.js.map
|