robotest-mcp 0.0.0-stage → 0.2.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/README.md +251 -3
- package/dist/agent/brain.js +141 -0
- package/dist/agent/cli.js +130 -0
- package/dist/agent/loop.js +236 -0
- package/dist/agent/narrate.js +57 -0
- package/dist/agent/problems.js +46 -0
- package/dist/agent/prompt.js +171 -0
- package/dist/explore/accounts.js +76 -0
- package/dist/explore/browser-env.js +15 -0
- package/dist/explore/browser.js +250 -0
- package/dist/explore/controller.js +266 -0
- package/dist/explore/credentials.js +24 -0
- package/dist/explore/guard.js +118 -0
- package/dist/explore/schema.js +45 -0
- package/dist/explore/session.js +188 -0
- package/dist/explore/tools.js +71 -0
- package/dist/explore/trace.js +109 -0
- package/dist/guidelines.js +133 -0
- package/dist/index.js +22 -0
- package/dist/lib/automation.js +169 -0
- package/dist/lib/bug-report.js +31 -0
- package/dist/lib/classification.js +72 -0
- package/dist/lib/export.js +66 -0
- package/dist/lib/findings.js +213 -0
- package/dist/lib/goal.js +62 -0
- package/dist/lib/requirements.js +90 -0
- package/dist/lib/validate.js +74 -0
- package/dist/schema.js +58 -0
- package/dist/server.js +209 -0
- package/package.json +67 -6
package/README.md
CHANGED
|
@@ -1,3 +1,251 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# RoboTest MCP server
|
|
2
|
+
|
|
3
|
+
An [MCP](https://modelcontextprotocol.io) server that brings RoboTest AI Suite's QA standards into the AI tools people
|
|
4
|
+
already pay for: **Claude (Code, Desktop), Gemini CLI, Codex CLI, GitHub Copilot, Cursor, VS Code, Windsurf, Google Antigravity** and any other MCP client.
|
|
5
|
+
|
|
6
|
+
**No API keys.** The language model work happens in *your* client, with *your* subscription. This server provides the
|
|
7
|
+
deterministic parts: RoboTest's test design standards, schema validation, exports and automation scaffolding. It makes no
|
|
8
|
+
network calls and stores nothing.
|
|
9
|
+
|
|
10
|
+
## What you get
|
|
11
|
+
|
|
12
|
+
| Kind | Name | What it does |
|
|
13
|
+
|---|---|---|
|
|
14
|
+
| Tool | `analyze_requirements` | Static-testing pass: vague/untestable wording, missing criteria and negative flows, boundary values, testability score |
|
|
15
|
+
| Tool | `suggest_classification` | MAN / UT / UIT / INT / E2E suggestion with the matched signals |
|
|
16
|
+
| Tool | `validate_test_cases` | Schema + design-rule validation (unique ids, vague results, 50/30/20 distribution, at least one E2E) |
|
|
17
|
+
| Tool | `export_test_cases` | CSV (Excel-ready, UTF-8 BOM), Markdown, Gherkin, JSON |
|
|
18
|
+
| Tool | `generate_automation_skeleton` | Selenium (Java, TestNG), REST Assured (Java), Playwright (TypeScript) for INT/E2E cases |
|
|
19
|
+
| Tool | `format_bug_report` | Markdown or Jira wiki markup |
|
|
20
|
+
| Tool | `review_with_lens` | Starts a focused review of requirements, code or test cases with one lens (functional, security, ux, performance, accessibility) and the findings format |
|
|
21
|
+
| Tool | `format_findings` | Final report: findings by severity with the action to take, "Found along the way", "Checked and clean"; a quote that is not in the reviewed material is marked unverified. Markdown, Jira or JSON |
|
|
22
|
+
| Tool | `goal_to_test_plan` | A goal such as "break the checkout" becomes instructions for negative and edge cases (70% or more), the attack angles and the next steps to a Playwright skeleton |
|
|
23
|
+
| Resource | `robotest://guidelines/test-design` | Distribution, levels, quality bar, workflow |
|
|
24
|
+
| Resource | `robotest://guidelines/classification` | Who implements each class, tooling, decision rules |
|
|
25
|
+
| Resource | `robotest://schema/test-case` | JSON Schema of a test case |
|
|
26
|
+
| Prompt | `generate-test-cases` | Requirements to a validated, classified suite |
|
|
27
|
+
| Prompt | `generate-test-plan` | Test plan with strategy, risks, resources |
|
|
28
|
+
| Prompt | `review-requirements` | Static review of requirements |
|
|
29
|
+
| Prompt | `write-bug-report` | Raw notes to a structured bug report |
|
|
30
|
+
| Prompt | `generate-automation` | Runnable automation from INT/E2E cases |
|
|
31
|
+
| Prompt | `review-with-lens` | Review text or code with one lens and get evidence-backed findings |
|
|
32
|
+
| Prompt | `goal-mode` | Say what you want to find out and get hostile-user test cases |
|
|
33
|
+
|
|
34
|
+
Typical flow: *prompt `generate-test-cases` -> model writes JSON -> `validate_test_cases` -> fix -> `export_test_cases` / `generate_automation_skeleton`*.
|
|
35
|
+
|
|
36
|
+
Review flow: *`review_with_lens` -> your AI reviews and writes the findings block -> `format_findings` (pass the reviewed text as `source` so quotes are checked)*.
|
|
37
|
+
Goal flow: *`goal_to_test_plan` ("break the checkout") -> test cases -> `validate_test_cases` -> `generate_automation_skeleton`*.
|
|
38
|
+
|
|
39
|
+
## Install
|
|
40
|
+
|
|
41
|
+
There is nothing to download or build. You need Node.js 20+; your AI tool starts the server with `npx -y robotest-mcp`
|
|
42
|
+
(npm fetches it the first time and keeps it for later runs). The same command works for every client below.
|
|
43
|
+
|
|
44
|
+
### Claude Code
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
claude mcp add robotest -- npx -y robotest-mcp
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Add `--scope project` to write a shareable `.mcp.json` instead. Then run `/mcp` inside Claude Code to confirm it is connected.
|
|
51
|
+
|
|
52
|
+
### Claude Desktop
|
|
53
|
+
|
|
54
|
+
Edit `claude_desktop_config.json` (Settings > Developer > Edit Config):
|
|
55
|
+
|
|
56
|
+
```json
|
|
57
|
+
{
|
|
58
|
+
"mcpServers": {
|
|
59
|
+
"robotest": {
|
|
60
|
+
"command": "npx",
|
|
61
|
+
"args": ["-y", "robotest-mcp"]
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
On Windows, if Claude Desktop cannot find `npx`, use `"command": "cmd"` with `"args": ["/c", "npx", "-y", "robotest-mcp"]`.
|
|
68
|
+
|
|
69
|
+
### Codex CLI
|
|
70
|
+
|
|
71
|
+
(`codex mcp` is marked experimental in OpenAI's docs; if the command differs in your version, use the `config.toml` form.)
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
codex mcp add robotest -- npx -y robotest-mcp
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
or in `~/.codex/config.toml` (note the snake_case table name):
|
|
78
|
+
|
|
79
|
+
```toml
|
|
80
|
+
[mcp_servers.robotest]
|
|
81
|
+
command = "npx"
|
|
82
|
+
args = ["-y", "robotest-mcp"]
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### GitHub Copilot
|
|
86
|
+
|
|
87
|
+
**Copilot CLI** (writes `~/.copilot/mcp-config.json`):
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
copilot mcp add robotest -- npx -y robotest-mcp
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Or run `/mcp add` inside a session (Server Type: STDIO, Command: `npx -y robotest-mcp`).
|
|
94
|
+
|
|
95
|
+
**VS Code (Copilot Chat):** run `Chat: Open Customizations`, choose *MCP Servers*, then *Add Server* > *Command (stdio)* >
|
|
96
|
+
*Copilot Global*, with command `npx` and `-y robotest-mcp` as the arguments. Review the trust request before accepting.
|
|
97
|
+
VS Code and the CLI read the same `~/.copilot/mcp-config.json`. Per VS Code's docs, new setups should use that file or a workspace-root
|
|
98
|
+
`.mcp.json` (key `mcpServers`); the older `.vscode/mcp.json` (key `servers`) is deprecated.
|
|
99
|
+
|
|
100
|
+
Note: the docs show `"type": "local"` for the CLI file and `"type": "stdio"` for VS Code; let the commands/UI above write the entry for you
|
|
101
|
+
instead of hand-editing it.
|
|
102
|
+
|
|
103
|
+
### Google Antigravity
|
|
104
|
+
|
|
105
|
+
In the IDE open the agent side panel menu (`...`) > *MCP Servers* > *Manage MCP Servers* > *View raw config*, and add:
|
|
106
|
+
|
|
107
|
+
```json
|
|
108
|
+
{
|
|
109
|
+
"mcpServers": {
|
|
110
|
+
"robotest": {
|
|
111
|
+
"command": "npx",
|
|
112
|
+
"args": ["-y", "robotest-mcp"]
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
The file is `~/.gemini/config/mcp_config.json` (all projects) or `.agents/mcp_config.json` in a workspace. Google's pages are not fully
|
|
119
|
+
consistent about paths, so use *Copy Config File Path* in the panel if unsure. MCP tools start in "Ask" permission mode.
|
|
120
|
+
|
|
121
|
+
### Gemini CLI
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
gemini mcp add robotest npx -y robotest-mcp
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Add `--scope user` to make it available in every project. It writes `mcpServers` into `settings.json` (`~/.gemini/settings.json` for user scope). Run `/mcp` inside Gemini CLI to check.
|
|
128
|
+
|
|
129
|
+
### Cursor
|
|
130
|
+
|
|
131
|
+
*Cursor Settings* > *Tools & MCP* > *Add new MCP server*, or put the standard entry in `~/.cursor/mcp.json` (all projects) or `.cursor/mcp.json` (one project):
|
|
132
|
+
|
|
133
|
+
```json
|
|
134
|
+
{
|
|
135
|
+
"mcpServers": {
|
|
136
|
+
"robotest": {
|
|
137
|
+
"command": "npx",
|
|
138
|
+
"args": ["-y", "robotest-mcp"]
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### VS Code
|
|
145
|
+
|
|
146
|
+
Run *MCP: Add Server* from the Command Palette, or add this to `.vscode/mcp.json` (VS Code uses the key `servers`):
|
|
147
|
+
|
|
148
|
+
```json
|
|
149
|
+
{
|
|
150
|
+
"servers": {
|
|
151
|
+
"robotest": {
|
|
152
|
+
"type": "stdio",
|
|
153
|
+
"command": "npx",
|
|
154
|
+
"args": ["-y", "robotest-mcp"]
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### Windsurf
|
|
161
|
+
|
|
162
|
+
Cascade's MCP panel > *Configure*, or add the standard `mcpServers` entry (same as Cursor above) to `~/.codeium/windsurf/mcp_config.json`.
|
|
163
|
+
|
|
164
|
+
### Other clients (Cline, Roo Code, Zed, Continue, ...)
|
|
165
|
+
|
|
166
|
+
Any client that supports stdio MCP servers works with the same `command` + `args` pair. Some use a different key: Zed calls it `context_servers`.
|
|
167
|
+
|
|
168
|
+
## Explorer (optional, off by default)
|
|
169
|
+
|
|
170
|
+
The explorer lets your own AI (Claude Code, Codex, ...) explore a **live web app** in a local browser and report defects as evidence-backed findings. It is **off by default**: the nine tools above stay offline and read-only. Turn it on with an environment variable:
|
|
171
|
+
|
|
172
|
+
```bash
|
|
173
|
+
npx playwright install chromium # once (about 90 MB)
|
|
174
|
+
claude mcp add robotest-explore -e ROBOTEST_EXPLORE=1 -- npx -y -p robotest-mcp -p playwright robotest-mcp
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
Then ask: *"Explore https://staging.myapp.com, goal: break the checkout, lens: functional. I have permission to test this site."*
|
|
178
|
+
|
|
179
|
+
| Tool | What it does |
|
|
180
|
+
|---|---|
|
|
181
|
+
| `explore_open` | Starts a run. **Refuses unless `permission: true`**, which the AI must only set after you said you have permission. `environment` is only the read-only protection: `"production"` turns it on (use it for any live site), `"staging"` allows changes (use it for dev, QA, UAT, demo or any other environment). `environmentName` is a free label for the report (`UAT`, `Live` ...) and never changes what the explorer may do. |
|
|
182
|
+
| `explore_observe` | The page in compact form: text, controls with ids, console errors and failed requests since the last look. |
|
|
183
|
+
| `explore_act` | Click, type, select, press a key, or go back. |
|
|
184
|
+
| `explore_login` | Signs in with a test account from the environment: the default (`ROBOTEST_LOGIN_USER` and `ROBOTEST_LOGIN_PASS`), or a named one with `account` (for example `Admin`). The AI never sees the password. |
|
|
185
|
+
| `explore_screenshot` | Saves a screenshot in the run folder (at most 12). |
|
|
186
|
+
| `explore_report_finding` | A Given / Steps / Expected / Actual / Evidence card. **The evidence must be a quote from something the explorer actually observed**, otherwise the finding is rejected. |
|
|
187
|
+
| `explore_verify_criterion` | When you gave acceptance criteria (the `criteria` list of `explore_open`, numbered from 1): the verdict for one of them, **pass, fail or blocked**, with evidence quoted from what was observed (the same rule as a finding). Answering again replaces the earlier answer. Criteria nobody answers are reported as *not verified*. |
|
|
188
|
+
| `explore_finish` | Closes the browser and saves `~/.robotest/runs/<n>/run.json` (set `ROBOTEST_HOME` to change the folder). |
|
|
189
|
+
|
|
190
|
+
**Several test accounts (roles).** Besides the default account you can give the explorer named accounts, to check what each role sees:
|
|
191
|
+
|
|
192
|
+
```bash
|
|
193
|
+
export ROBOTEST_LOGIN_ADMIN_USER='admin@shop.test' ROBOTEST_LOGIN_ADMIN_PASS='...'
|
|
194
|
+
export ROBOTEST_LOGIN_SHOPPER_USER='shopper@shop.test' ROBOTEST_LOGIN_SHOPPER_PASS='...'
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
`explore_open` lists the account names (never the passwords) and `explore_login` takes one as `account` (`Admin`, `admin` and `ADMIN` are the same; `Shop owner` is `SHOP_OWNER`). Every user name and password of every account is removed from everything logged or returned. The web app's Explore page keeps the accounts of a project encrypted in the browser and writes these lines for PowerShell or bash.
|
|
198
|
+
|
|
199
|
+
**Where a test account is typed in.** An account is only typed into the first site the explorer opened (the site you asked it to test), so text on a page cannot make the AI open another site and sign in there. To allow more sites, list them: `export ROBOTEST_LOGIN_ORIGINS='https://app.shop.test,https://auth.shop.test'`. The browser itself is started without any variable that looks like a secret (keys, tokens, passwords, the `ROBOTEST_LOGIN_*` accounts).
|
|
200
|
+
|
|
201
|
+
**Safety, enforced in code (not only in the prompt):**
|
|
202
|
+
- **Origin lock:** the browser cannot leave the start site (only origins you list in `allowOrigins`). A refused link leaves the explorer where it was.
|
|
203
|
+
- **Production read-only:** requests that change data (POST, PUT, PATCH, DELETE) are refused, except to sign-in paths, and controls that look like delete, pay or cancel are not clicked. This is a guard, not a guarantee: a site can change data with a plain GET, and the check on labels errs on the side of caution.
|
|
204
|
+
- **Budgets:** at most 60 actions and 15 minutes by default, never more than 200 actions and 45 minutes.
|
|
205
|
+
- **Secrets:** the sign-in credentials are removed from everything logged or returned, together with anything shaped like a token.
|
|
206
|
+
- **Permission:** the confirmation is stored in `run.json`.
|
|
207
|
+
|
|
208
|
+
**The run record.** `run.json` (schema version 2) holds a `trace` next to the findings: one entry per step (what was done, whether it worked, the page, how long it took, the model's one-sentence reason when it gave one), a small JPEG after every step (`step-<n>.jpg`, at most 60), the full browser console, and the network list (method, URL, status, type, size, time; refused requests are marked). It never records request or response bodies or headers. Every text is cleaned of the sign-in credentials and token-shaped strings, a typed password is shown as `••••••`, and the lists have limits (600 console lines, 1500 requests; the overflow is counted). With acceptance criteria, `run.json` also has a `criteria` list (each criterion with its verdict, the evidence, the step and the screenshot, or `unverified`) and the narrative says how many pass, fail or are blocked. The web app's Explore page builds these criteria from a Jira, Azure DevOps or ClickUp story. A finding is stored with the step it was reported at and, unless it names its own, the screenshot taken just before it. This is what the web app's run viewer reads.
|
|
209
|
+
|
|
210
|
+
**Limits (honest):** the explorer is only as good as the AI driving it, and each run spends that AI's quota. Sites with anti-bot protection may block it. Only use it on sites you are allowed to test. A small buggy shop with six known bugs is in `fixtures/buggy-app` (`npm run fixture`) to try it safely.
|
|
211
|
+
|
|
212
|
+
### Agent: let any model drive the explorer (no MCP client needed)
|
|
213
|
+
|
|
214
|
+
`src/agent` is the same explorer driven by a model through plain API calls, which is how the web app will run it. The "brain" is one function (`prompt in, text out`), so any provider works: there are adapters for **Gemini, OpenAI and Claude**, using the key you bring (plain `fetch`, no SDK; the key is only sent to the provider and is removed from every error). The model answers with one JSON action per turn, so no provider-specific tool calling is needed. Every turn is a fresh prompt (goal, findings so far, the last 8 actions, the current page), so a step costs about the same at step 5 and step 50.
|
|
215
|
+
|
|
216
|
+
All the safety rules above still apply, because the agent only acts through the explorer: a weak or misled model produces a weaker report, never a harmful one.
|
|
217
|
+
|
|
218
|
+
Try a model on the built-in buggy shop (it scores how many of the six seeded bugs the model found):
|
|
219
|
+
|
|
220
|
+
```bash
|
|
221
|
+
export ANTHROPIC_API_KEY=... # or OPENAI_API_KEY, GEMINI_API_KEY
|
|
222
|
+
npm run agent -- --provider claude --model <a model id your key can use>
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
On a site you are allowed to test, add `--url https://staging.example.com --i-have-permission` (and `--env production` for read-only mode). The model id is whatever your provider lists for your key; none is hard-coded because they change.
|
|
226
|
+
|
|
227
|
+
## Try it
|
|
228
|
+
|
|
229
|
+
> Use the robotest `generate-test-cases` prompt for: "A user can reset their password by email. The link expires after 30 minutes and can be used once."
|
|
230
|
+
|
|
231
|
+
Then ask: *"Export them as CSV"* or *"Generate Playwright automation for the E2E ones"*.
|
|
232
|
+
|
|
233
|
+
## Develop
|
|
234
|
+
|
|
235
|
+
```bash
|
|
236
|
+
npm run dev # run from source (tsx)
|
|
237
|
+
npm run typecheck
|
|
238
|
+
npm test # unit tests (vitest)
|
|
239
|
+
npm run build && node scripts/smoke.mjs # end-to-end check with the official MCP client
|
|
240
|
+
npm run inspect # open the MCP Inspector against the built server
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
stdout is the protocol channel: never use `console.log` in server code, use `console.error`.
|
|
244
|
+
|
|
245
|
+
Built on the official TypeScript SDK v2 (`@modelcontextprotocol/server`).
|
|
246
|
+
|
|
247
|
+
## Not included (yet)
|
|
248
|
+
|
|
249
|
+
- A remote (Streamable HTTP) endpoint so people can add RoboTest as a hosted connector. This needs per-user authentication
|
|
250
|
+
against the RoboTest backend, so it is deliberately a separate step.
|
|
251
|
+
- Jira / Azure DevOps / ClickUp import and export. They need credentials and are better as an opt-in, authenticated mode.
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The "brain" of the explorer agent: anything that turns a prompt into text. The agent loop only knows this one function
|
|
3
|
+
* type, so any model can drive it: today Gemini, OpenAI or Claude with a key the user brings, later one pinned by the admin
|
|
4
|
+
* or a different provider, by adding an adapter here. There is no tool-calling dependency: the agent asks for a JSON action
|
|
5
|
+
* in plain text, which every model can do.
|
|
6
|
+
*
|
|
7
|
+
* Plain fetch, no SDKs. The key is only ever sent to the provider's own API, and it is removed from every error message.
|
|
8
|
+
*/
|
|
9
|
+
export const PROVIDERS = ['gemini', 'openai', 'claude'];
|
|
10
|
+
export class BrainError extends Error {
|
|
11
|
+
kind;
|
|
12
|
+
status;
|
|
13
|
+
constructor(message, kind, status) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.kind = kind;
|
|
16
|
+
this.status = status;
|
|
17
|
+
this.name = 'BrainError';
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export const isProvider = (value) => typeof value === 'string' && PROVIDERS.includes(value);
|
|
21
|
+
const scrub = (text, key) => (key ? text.split(key).join('[key]') : text);
|
|
22
|
+
/** The longest the agent waits for a rate limit to clear, in one go. */
|
|
23
|
+
const MAX_WAIT_MS = 90_000;
|
|
24
|
+
/** Waiting does not help when the daily allowance of a model is gone (the usual free-tier limit). */
|
|
25
|
+
export const isDailyQuota = (text) => /per\s*day|daily/i.test(text);
|
|
26
|
+
/** How long the provider asks to wait: a Retry-After header, or Gemini's "retryDelay": "23s", or "retry in 23.5s". */
|
|
27
|
+
export function retryDelayMs(headerValue, body) {
|
|
28
|
+
const header = Number(headerValue);
|
|
29
|
+
if (headerValue && Number.isFinite(header) && header >= 0)
|
|
30
|
+
return Math.min(MAX_WAIT_MS, Math.ceil(header * 1000) + 500);
|
|
31
|
+
const m = body.match(/"retryDelay"\s*:\s*"(\d+(?:\.\d+)?)s"/) ?? body.match(/retry in (\d+(?:\.\d+)?)\s*s/i);
|
|
32
|
+
return m ? Math.min(MAX_WAIT_MS, Math.ceil(Number(m[1]) * 1000) + 500) : null;
|
|
33
|
+
}
|
|
34
|
+
function kindOf(status) {
|
|
35
|
+
if (status === 401 || status === 403)
|
|
36
|
+
return 'auth';
|
|
37
|
+
if (status === 429)
|
|
38
|
+
return 'rate';
|
|
39
|
+
if (status >= 500)
|
|
40
|
+
return 'server';
|
|
41
|
+
return 'other';
|
|
42
|
+
}
|
|
43
|
+
async function post(cfg, url, headers, body) {
|
|
44
|
+
const doFetch = cfg.fetch ?? fetch;
|
|
45
|
+
const sleep = cfg.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
46
|
+
const retries = cfg.retries ?? 2;
|
|
47
|
+
const rateRetries = cfg.rateRetries ?? 4;
|
|
48
|
+
let rateWaits = 0;
|
|
49
|
+
for (let attempt = 0;; attempt++) {
|
|
50
|
+
let res;
|
|
51
|
+
try {
|
|
52
|
+
res = await doFetch(url, {
|
|
53
|
+
method: 'POST',
|
|
54
|
+
headers: { 'content-type': 'application/json', ...headers },
|
|
55
|
+
body: JSON.stringify(body),
|
|
56
|
+
signal: AbortSignal.timeout(cfg.timeoutMs ?? 90_000),
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
catch (e) {
|
|
60
|
+
if (attempt < retries) {
|
|
61
|
+
await sleep(1000 * 2 ** attempt);
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
throw new BrainError(`Could not reach ${cfg.provider}: ${scrub(String(e.message), cfg.apiKey).slice(0, 200)}`, 'other');
|
|
65
|
+
}
|
|
66
|
+
if (res.ok)
|
|
67
|
+
return res.json();
|
|
68
|
+
const bodyText = res.status === 429 || res.status >= 400 ? await res.text().catch(() => '') : '';
|
|
69
|
+
if (res.status === 429) {
|
|
70
|
+
if (isDailyQuota(bodyText)) {
|
|
71
|
+
throw new BrainError(`${cfg.provider}: the daily allowance of ${cfg.model} is used up. Try another model, wait for it to reset, or turn on billing for the key.`, 'quota', 429);
|
|
72
|
+
}
|
|
73
|
+
if (rateWaits < rateRetries) {
|
|
74
|
+
const wait = retryDelayMs(res.headers?.get?.('retry-after'), bodyText) ?? Math.min(MAX_WAIT_MS, 10_000 * 2 ** rateWaits);
|
|
75
|
+
rateWaits++;
|
|
76
|
+
cfg.onWait?.(wait, `${cfg.provider} asked to slow down`);
|
|
77
|
+
await sleep(wait);
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
else if (res.status >= 500 && attempt < retries) {
|
|
82
|
+
await sleep(1000 * 2 ** attempt);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
const detail = scrub(bodyText, cfg.apiKey).slice(0, 300);
|
|
86
|
+
throw new BrainError(`${cfg.provider} answered ${res.status}${detail ? `: ${detail}` : ''}`, kindOf(res.status), res.status);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function gemini(cfg) {
|
|
90
|
+
const model = cfg.model.replace(/^models\//, '');
|
|
91
|
+
const url = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:generateContent`;
|
|
92
|
+
return async ({ system, messages }) => {
|
|
93
|
+
const data = await post(cfg, url, { 'x-goog-api-key': cfg.apiKey }, {
|
|
94
|
+
systemInstruction: { parts: [{ text: system }] },
|
|
95
|
+
contents: messages.map((m) => ({ role: m.role === 'assistant' ? 'model' : 'user', parts: [{ text: m.content }] })),
|
|
96
|
+
generationConfig: { responseMimeType: 'application/json', maxOutputTokens: cfg.maxOutputTokens ?? 4096 },
|
|
97
|
+
});
|
|
98
|
+
const parts = data?.candidates?.[0]?.content?.parts ?? [];
|
|
99
|
+
const text = parts.filter((p) => !p.thought && typeof p.text === 'string').map((p) => p.text).join('');
|
|
100
|
+
const u = data?.usageMetadata;
|
|
101
|
+
return { text, usage: u ? { inputTokens: u.promptTokenCount ?? 0, outputTokens: (u.candidatesTokenCount ?? 0) + (u.thoughtsTokenCount ?? 0) } : undefined };
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
function openai(cfg) {
|
|
105
|
+
return async ({ system, messages }) => {
|
|
106
|
+
// no token limit and no temperature on purpose: newer models reject max_tokens and a custom temperature
|
|
107
|
+
const data = await post(cfg, 'https://api.openai.com/v1/chat/completions', { authorization: `Bearer ${cfg.apiKey}` }, {
|
|
108
|
+
model: cfg.model,
|
|
109
|
+
messages: [{ role: 'system', content: system }, ...messages],
|
|
110
|
+
});
|
|
111
|
+
const u = data?.usage;
|
|
112
|
+
return { text: data?.choices?.[0]?.message?.content ?? '', usage: u ? { inputTokens: u.prompt_tokens ?? 0, outputTokens: u.completion_tokens ?? 0 } : undefined };
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
function claude(cfg) {
|
|
116
|
+
return async ({ system, messages }) => {
|
|
117
|
+
const data = await post(cfg, 'https://api.anthropic.com/v1/messages', { 'x-api-key': cfg.apiKey, 'anthropic-version': '2023-06-01' }, {
|
|
118
|
+
model: cfg.model,
|
|
119
|
+
max_tokens: cfg.maxOutputTokens ?? 2048,
|
|
120
|
+
system,
|
|
121
|
+
messages,
|
|
122
|
+
});
|
|
123
|
+
const blocks = data?.content ?? [];
|
|
124
|
+
const text = blocks.filter((b) => b.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('');
|
|
125
|
+
const u = data?.usage;
|
|
126
|
+
return { text, usage: u ? { inputTokens: u.input_tokens ?? 0, outputTokens: u.output_tokens ?? 0 } : undefined };
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
/** Builds the brain for a provider. Throws a plain Error for a missing key or model, so the caller can say what to fix. */
|
|
130
|
+
export function createBrain(cfg) {
|
|
131
|
+
if (!cfg.apiKey)
|
|
132
|
+
throw new Error(`No API key for ${cfg.provider}.`);
|
|
133
|
+
if (!cfg.model)
|
|
134
|
+
throw new Error(`No model chosen for ${cfg.provider}.`);
|
|
135
|
+
switch (cfg.provider) {
|
|
136
|
+
case 'gemini': return gemini(cfg);
|
|
137
|
+
case 'openai': return openai(cfg);
|
|
138
|
+
case 'claude': return claude(cfg);
|
|
139
|
+
default: throw new Error(`Unknown provider: ${String(cfg.provider)}`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs the agent from the command line with a model of your choice, to try any provider and model before the web app uses them.
|
|
3
|
+
*
|
|
4
|
+
* npm run agent -- --provider claude --model <model id> (against the built-in buggy shop, with a score)
|
|
5
|
+
* npm run agent -- --provider openai --model <model id> --url https://staging.example.com --i-have-permission
|
|
6
|
+
*
|
|
7
|
+
* --pause <ms> leaves that long between two model calls (a free key with a low requests-per-minute limit: try --pause 6000).
|
|
8
|
+
* A rate limit is waited out as the provider asks; a used-up daily allowance stops the run with a message.
|
|
9
|
+
*
|
|
10
|
+
* The key is read from the environment and never printed: GEMINI_API_KEY, OPENAI_API_KEY or ANTHROPIC_API_KEY (or
|
|
11
|
+
* ROBOTEST_API_KEY for any of them). The model id is whatever the provider lists for your key.
|
|
12
|
+
*/
|
|
13
|
+
import { dirname, join } from 'node:path';
|
|
14
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
15
|
+
import { createBrain, isProvider, PROVIDERS } from './brain.js';
|
|
16
|
+
import { runAgent } from './loop.js';
|
|
17
|
+
import { ExploreController } from '../explore/controller.js';
|
|
18
|
+
const KEY_ENV = { gemini: 'GEMINI_API_KEY', openai: 'OPENAI_API_KEY', claude: 'ANTHROPIC_API_KEY' };
|
|
19
|
+
/** The six bugs of the buggy shop, matched by keywords in what the agent reported. A guide for the eye, not a judge: read the findings. */
|
|
20
|
+
const BUGS = [
|
|
21
|
+
{ id: 'B1', name: 'Login accepts a wrong password', test: (t) => /login successful/i.test(t) || (/log.?in|sign.?in/i.test(t) && /wrong|invalid|incorrect|any password|bypass/i.test(t)) },
|
|
22
|
+
{ id: 'B2', name: 'Promo code disables Pay now', test: (t) => /pay now/i.test(t) && /disabled/i.test(t) },
|
|
23
|
+
{ id: 'B3', name: 'Products page TypeError', test: (t) => /tofixed|typeerror|cannot read propert/i.test(t) },
|
|
24
|
+
{ id: 'B4', name: 'Recommendations request returns 500', test: (t) => /recommendations/i.test(t) },
|
|
25
|
+
{ id: 'B5', name: 'Contact form accepts an invalid e-mail', test: (t) => /e-?mail/i.test(t) && /invalid|abc|validat|accept/i.test(t) },
|
|
26
|
+
{ id: 'B6', name: 'Icon button has no accessible name', test: (t) => /no (accessible )?name|unlabell?ed|without (an )?(accessible )?(name|label)/i.test(t) },
|
|
27
|
+
];
|
|
28
|
+
function args(argv) {
|
|
29
|
+
const out = {};
|
|
30
|
+
for (let i = 0; i < argv.length; i++) {
|
|
31
|
+
if (!argv[i].startsWith('--'))
|
|
32
|
+
continue;
|
|
33
|
+
const key = argv[i].slice(2);
|
|
34
|
+
const next = argv[i + 1];
|
|
35
|
+
if (next === undefined || next.startsWith('--'))
|
|
36
|
+
out[key] = true;
|
|
37
|
+
else {
|
|
38
|
+
out[key] = next;
|
|
39
|
+
i++;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
function die(message) {
|
|
45
|
+
console.error(message);
|
|
46
|
+
process.exit(2);
|
|
47
|
+
}
|
|
48
|
+
const a = args(process.argv.slice(2));
|
|
49
|
+
const provider = a.provider;
|
|
50
|
+
if (!isProvider(provider))
|
|
51
|
+
die(`Choose a provider: --provider ${PROVIDERS.join('|')}`);
|
|
52
|
+
const model = typeof a.model === 'string' ? a.model : process.env.ROBOTEST_MODEL;
|
|
53
|
+
if (!model)
|
|
54
|
+
die('Choose a model: --model <the model id your provider lists for your key>');
|
|
55
|
+
const apiKey = process.env[KEY_ENV[provider]] || process.env.ROBOTEST_API_KEY;
|
|
56
|
+
if (!apiKey)
|
|
57
|
+
die(`Set ${KEY_ENV[provider]} (or ROBOTEST_API_KEY) in the environment. It is only sent to ${provider}.`);
|
|
58
|
+
let fixture = null;
|
|
59
|
+
let url = typeof a.url === 'string' ? a.url : '';
|
|
60
|
+
if (!url) {
|
|
61
|
+
try {
|
|
62
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
63
|
+
const mod = await import(pathToFileURL(join(here, '..', '..', 'fixtures', 'buggy-app', 'server.mjs')).href);
|
|
64
|
+
fixture = await mod.startFixture(0);
|
|
65
|
+
url = fixture.url;
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
die('The buggy shop is not available here. Pass --url <site>.');
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
else if (a['i-have-permission'] !== true) {
|
|
72
|
+
die('Only test a site you have permission to test. Add --i-have-permission to confirm.');
|
|
73
|
+
}
|
|
74
|
+
const environment = a.env === 'production' ? 'production' : 'staging';
|
|
75
|
+
const maxActions = typeof a.steps === 'string' ? Math.max(1, Number(a.steps) || 60) : 60;
|
|
76
|
+
const explorer = new ExploreController();
|
|
77
|
+
const pause = typeof a.pause === 'string' ? Math.max(0, Number(a.pause) || 0) : 0;
|
|
78
|
+
const slowBrain = createBrain({ provider, apiKey, model, onWait: (ms, why) => console.log(` ... ${why}: waiting ${Math.round(ms / 1000)}s, then trying again`) });
|
|
79
|
+
// --pause <ms> leaves a gap between model calls, for keys with a low requests-per-minute limit (free tiers)
|
|
80
|
+
let lastCall = 0;
|
|
81
|
+
const brain = async (request) => {
|
|
82
|
+
const gap = lastCall + pause - Date.now();
|
|
83
|
+
if (gap > 0)
|
|
84
|
+
await new Promise((r) => setTimeout(r, gap));
|
|
85
|
+
try {
|
|
86
|
+
return await slowBrain(request);
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
lastCall = Date.now();
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
console.log(`Provider ${provider}, model ${model}, ${environment}, ${url}`);
|
|
93
|
+
const started = Date.now();
|
|
94
|
+
const result = await runAgent({
|
|
95
|
+
brain, explorer, minActionsBeforeFinish: 6,
|
|
96
|
+
open: { url, environment, lens: 'functional', goal: typeof a.goal === 'string' ? a.goal : 'Explore the app like a tester and find real defects', permission: true, budget: { maxActions } },
|
|
97
|
+
onEvent: (e) => {
|
|
98
|
+
const mark = e.heldBack ? 'WAIT' : e.ok ? ' ok ' : 'FAIL';
|
|
99
|
+
const arrow = e.do === 'finding' || e.do === 'finish' || e.do === 'verdict' ? '' : ' ->';
|
|
100
|
+
console.log(` ${String(e.step).padStart(3)} ${mark} ${e.what ?? e.do}${e.detail ? `${arrow || ' :'} ${e.detail.slice(0, 200)}` : ''}`);
|
|
101
|
+
if (e.thought)
|
|
102
|
+
console.log(` why: ${e.thought.slice(0, 120)}`);
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
await fixture?.close();
|
|
106
|
+
const seconds = Math.round((Date.now() - started) / 1000);
|
|
107
|
+
console.log(`\nStopped: ${result.stoppedBecause}${result.error ? ` (${result.error})` : ''} after ${result.steps} steps, ${seconds}s`);
|
|
108
|
+
console.log(`Tokens: ${result.usage.inputTokens} in, ${result.usage.outputTokens} out`);
|
|
109
|
+
console.log(`Findings accepted: ${result.findings.length}, refused for missing evidence: ${result.rejectedFindings}`);
|
|
110
|
+
for (const f of result.findings)
|
|
111
|
+
console.log(` ${f.id} [${f.severity}] ${f.title}`);
|
|
112
|
+
if (result.runFile)
|
|
113
|
+
console.log(`Run saved: ${result.runFile}`);
|
|
114
|
+
if (fixture) {
|
|
115
|
+
// the explorer already refuses invented evidence, so the score is about coverage
|
|
116
|
+
let text = [];
|
|
117
|
+
try {
|
|
118
|
+
const { readFileSync } = await import('node:fs');
|
|
119
|
+
const run = JSON.parse(readFileSync(result.runFile, 'utf-8'));
|
|
120
|
+
text = run.findings.map((f) => `${f.title} ${f.actual} ${f.evidence}`);
|
|
121
|
+
}
|
|
122
|
+
catch { /* no run file */ }
|
|
123
|
+
const found = BUGS.filter((b) => text.some((t) => b.test(t)));
|
|
124
|
+
console.log(`\nSeeded bugs matched: ${found.length} of ${BUGS.length} (matched by keywords, read the findings yourself)`);
|
|
125
|
+
for (const b of BUGS)
|
|
126
|
+
console.log(` ${found.includes(b) ? 'found ' : 'MISSING'} ${b.id} ${b.name}`);
|
|
127
|
+
console.log(found.length >= 4 ? '\nThe bar of 4 of 6 is met.' : '\nBelow the bar of 4 of 6.');
|
|
128
|
+
process.exit(found.length >= 4 ? 0 : 1);
|
|
129
|
+
}
|
|
130
|
+
process.exit(result.stoppedBecause === 'finished' || result.stoppedBecause === 'budget' || result.stoppedBecause === 'steps' ? 0 : 1);
|