@pluswithai/cli 0.4.0 → 0.5.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 CHANGED
@@ -1,8 +1,12 @@
1
1
  # @pluswithai/cli
2
2
 
3
- Run your [Pluswithai](https://pluswithai.com) tests from CI and the terminal.
4
- It starts the runs, waits for them and exits non-zero when one fails.
3
+ Run your [Pluswithai](https://pluswithai.com) tests from CI and the terminal, and
4
+ send a team of agents to hunt bugs on your site.
5
5
 
6
+ ![pluswithai hunt following a real bug hunt on Gitea's issues: the areas each agent started and finished, and each verified bug as it arrived](https://raw.githubusercontent.com/pluswithai/cli/main/docs/hunt-live.png)
7
+
8
+ - `run` starts your tests, waits for them and exits non-zero when one fails.
9
+ - `hunt` starts a bug hunt and follows it live; every bug it lists was reproduced, with a video.
6
10
  - No runtime dependencies. Node 18.3 or later.
7
11
  - Readable CI logs, a GitHub step summary, failure annotations and JUnit XML.
8
12
  - Your API key is only read from the environment, and it is never printed.
@@ -76,6 +80,7 @@ Inside GitHub Actions, the CLI also:
76
80
  | Command | What it does |
77
81
  |---|---|
78
82
  | `pluswithai run --project <name>` | Start runs in the cloud, wait for them, exit with their verdict |
83
+ | `pluswithai hunt <project> --url <site>` | Start a bug hunt by a team of agents and follow it live |
79
84
  | `pluswithai local --project <name>` | Run the project's tests on this machine, e.g. against `localhost` |
80
85
  | `pluswithai pull --project <name>` | Download the project's files to run them yourself |
81
86
  | `pluswithai projects` | List your projects |
@@ -103,6 +108,42 @@ headers stay on Pluswithai: set `PLUSWITHAI_HTTP_USERNAME`,
103
108
  `PLUSWITHAI_HTTP_PASSWORD` and `PLUSWITHAI_EXTRA_HEADERS` (a JSON object) when
104
109
  the site needs them. Needs Node.js 18+.
105
110
 
111
+ ## Bug hunts
112
+
113
+ `pluswithai hunt` starts a bug hunt: a team of agents explores the site, each
114
+ in its own browser, and lists every bug it verified (reproduced and confirmed
115
+ a defect), one line each with a signed video link (clickable in a terminal,
116
+ the URL in CI). In a terminal it follows the hunt live;
117
+ in CI (`CI=1`) or a pipe it prints plain lines; `--json` waits for the hunt
118
+ to end and prints its bugs as one JSON array (id, title, severity, videoUrl,
119
+ steps, expected, actual).
120
+
121
+ ```bash
122
+ pluswithai hunt shop --url https://staging.example.com --agents 6
123
+ pluswithai hunt shop-run-7 --new-project --url https://staging.example.com --detach
124
+ pluswithai hunt shop --session s8kq2 # follow a hunt again
125
+ pluswithai hunt shop --session s8kq2 --bug 3 # bug #3 (or its id): steps, expected, actual
126
+ pluswithai hunt shop --stop --session s8kq2 # stop the lead and every agent
127
+ ```
128
+
129
+ Each agent works in its own browser. The `watch` link opens a live view of
130
+ them, with nothing else on the page:
131
+
132
+ ![The live view of a bug hunt: fifteen agents, each in its own browser, testing Gitea's issues](https://raw.githubusercontent.com/pluswithai/cli/main/docs/agents-live.gif)
133
+
134
+ When it ends, every bug is listed with its severity and a link to its video:
135
+
136
+ ![The end of the same hunt: twelve verified bugs by severity, each with its video, and the summary](https://raw.githubusercontent.com/pluswithai/cli/main/docs/hunt-done.png)
137
+
138
+ When the account's agents are busy, `--wait` (the default) retries until
139
+ `--wait-timeout` (30m), `--take-available` starts with the free ones and
140
+ `--no-wait` exits 2. Ctrl+C stops following; the hunt keeps running. The
141
+ `watch` line is a public live view of the agents' browsers. The key needs
142
+ Agent (write + run) access. Exit codes: 0 finished, stopped or detached, 1 ended
143
+ in error or out of credits, 2 usage or busy pool (`--no-wait`), 3 Pluswithai or
144
+ network error, 4 gave up waiting for agents (or, with `--stop`, the agents
145
+ are still stopping).
146
+
106
147
  ## AI agents (MCP)
107
148
 
108
149
  Pluswithai is also an MCP server. With it, an agent like Claude Code, Cursor or Codex can run your tests, read the failures, push new tests and schedule them.
package/dist/args.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * node:util parseArgs so the CLI keeps zero runtime dependencies.
4
4
  */
5
5
  import { parseArgs } from "node:util";
6
- const COMMANDS = ["run", "local", "pull", "projects", "tests", "runs", "whoami", "mcp"];
6
+ const COMMANDS = ["run", "hunt", "local", "pull", "projects", "tests", "runs", "whoami", "mcp"];
7
7
  export class UsageError extends Error {
8
8
  topic;
9
9
  constructor(message, topic) {
@@ -32,6 +32,23 @@ const OPTIONS = {
32
32
  junit: { type: "string" },
33
33
  "no-summary": { type: "boolean" },
34
34
  },
35
+ hunt: {
36
+ ...GLOBAL,
37
+ ...PROJECT,
38
+ url: { type: "string" },
39
+ agents: { type: "string" },
40
+ context: { type: "string" },
41
+ "new-project": { type: "boolean" },
42
+ wait: { type: "boolean" },
43
+ "take-available": { type: "boolean" },
44
+ "no-wait": { type: "boolean" },
45
+ "wait-timeout": { type: "string" },
46
+ follow: { type: "boolean" },
47
+ detach: { type: "boolean" },
48
+ session: { type: "string" },
49
+ stop: { type: "boolean" },
50
+ bug: { type: "string" },
51
+ },
35
52
  local: {
36
53
  ...GLOBAL,
37
54
  ...PROJECT,
@@ -49,6 +66,94 @@ const OPTIONS = {
49
66
  mcp: { "api-url": GLOBAL["api-url"], help: GLOBAL.help },
50
67
  };
51
68
  const isCommand = (value) => COMMANDS.includes(value);
69
+ /** Project names as the API takes them: lowercase letters, digits and single hyphens. */
70
+ const PROJECT_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
71
+ /** "30m", "90s", "1h" or a number of seconds. */
72
+ export function duration(value, fallbackSec, flag, topic) {
73
+ if (value === undefined)
74
+ return fallbackSec;
75
+ const m = /^(\d+(?:\.\d+)?)([smh]?)$/.exec(value.trim());
76
+ const n = m ? Number(m[1]) * { "": 1, s: 1, m: 60, h: 3600 }[m[2]] : NaN;
77
+ if (!(n > 0))
78
+ throw new UsageError(`${flag} must be a duration like 90s, 30m or 2h.`, topic);
79
+ return n;
80
+ }
81
+ function httpUrlFlag(value, topic) {
82
+ let url;
83
+ try {
84
+ url = new URL(value);
85
+ }
86
+ catch {
87
+ throw new UsageError("--url must be an http(s) address, e.g. https://staging.example.com.", topic);
88
+ }
89
+ if (url.protocol !== "https:" && url.protocol !== "http:")
90
+ throw new UsageError("--url must be an http(s) address, e.g. https://staging.example.com.", topic);
91
+ return value;
92
+ }
93
+ function huntCommand(values, positionals, global, json, topic) {
94
+ if (positionals.length > 1)
95
+ throw new UsageError(`Unexpected argument "${positionals[1]}".`, topic);
96
+ const project = values.project ?? positionals[0];
97
+ if (!project)
98
+ throw new UsageError("Missing the project: pluswithai hunt <project> --url <site>.", topic);
99
+ if (values.project !== undefined && positionals[0] !== undefined)
100
+ throw new UsageError("Name the project once, either as the first argument or with --project.", topic);
101
+ const policies = ["wait", "take-available", "no-wait"].filter((f) => values[f] === true);
102
+ if (policies.length > 1)
103
+ throw new UsageError("Pass only one of --wait, --take-available and --no-wait.", topic);
104
+ if (values.follow === true && values.detach === true)
105
+ throw new UsageError("Pass either --follow or --detach, not both.", topic);
106
+ const sessionId = values.session;
107
+ const newProject = values["new-project"] === true;
108
+ if (values.bug !== undefined) {
109
+ if (sessionId === undefined)
110
+ throw new UsageError("--bug needs --session <id>: the hunt that found it.", topic);
111
+ const extra = ["url", "agents", "context", "new-project", "wait", "take-available", "no-wait", "wait-timeout", "follow", "detach", "stop"].find((f) => values[f] !== undefined);
112
+ if (extra)
113
+ throw new UsageError(`--bug takes only --session: drop --${extra}.`, topic);
114
+ return { kind: "hunt-bug", global, project, sessionId, bugId: values.bug, json };
115
+ }
116
+ if (values.stop === true) {
117
+ if (sessionId === undefined)
118
+ throw new UsageError("--stop needs --session <id>: the hunt to stop.", topic);
119
+ const extra = ["url", "agents", "context", "new-project", "wait", "take-available", "no-wait", "wait-timeout", "follow", "detach"].find((f) => values[f] !== undefined);
120
+ if (extra)
121
+ throw new UsageError(`--stop takes only --session: drop --${extra}.`, topic);
122
+ return { kind: "hunt-stop", global, project, sessionId, json };
123
+ }
124
+ if (sessionId !== undefined) {
125
+ const starting = ["url", "agents", "context", "new-project", "wait", "take-available", "no-wait", "wait-timeout", "detach"].filter((f) => values[f] !== undefined);
126
+ if (starting.length)
127
+ throw new UsageError(`--session follows a hunt that already started: drop --${starting[0]}.`, topic);
128
+ }
129
+ else if (values.url === undefined) {
130
+ throw new UsageError("Missing --url <site> (the site to hunt).", topic);
131
+ }
132
+ if (newProject && !PROJECT_NAME.test(project)) {
133
+ throw new UsageError("A new project's name takes lowercase letters, digits and single hyphens, e.g. gitea-issues-1.", topic);
134
+ }
135
+ let agents;
136
+ if (values.agents !== undefined) {
137
+ agents = Number(values.agents);
138
+ if (!Number.isInteger(agents) || agents < 1 || agents > 45)
139
+ throw new UsageError("--agents must be a whole number from 1 to 45.", topic);
140
+ }
141
+ const pool = policies[0] === "take-available" ? "available" : policies[0] === "no-wait" ? "none" : "wait";
142
+ return {
143
+ kind: "hunt",
144
+ global,
145
+ project,
146
+ sessionId,
147
+ url: values.url === undefined ? undefined : httpUrlFlag(values.url, topic),
148
+ agents,
149
+ context: values.context,
150
+ newProject,
151
+ pool,
152
+ waitTimeoutSec: duration(values["wait-timeout"], 1800, "--wait-timeout", topic),
153
+ follow: values.detach !== true,
154
+ json,
155
+ };
156
+ }
52
157
  function seconds(value, fallback, flag, topic) {
53
158
  if (value === undefined)
54
159
  return fallback;
@@ -77,8 +182,10 @@ export function parseCommand(argv) {
77
182
  throw new UsageError("There is no --api-key flag: set PLUSWITHAI_API_KEY in the environment instead.", topic);
78
183
  }
79
184
  let values;
185
+ let positionals;
80
186
  try {
81
- ({ values } = parseArgs({ args: rest, options: OPTIONS[topic], strict: true, allowPositionals: false }));
187
+ // Only `hunt` takes a positional: its project (pluswithai hunt <project> --url …).
188
+ ({ values, positionals } = parseArgs({ args: rest, options: OPTIONS[topic], strict: true, allowPositionals: topic === "hunt" }));
82
189
  }
83
190
  catch (e) {
84
191
  throw new UsageError(e.message, topic);
@@ -98,6 +205,8 @@ export function parseCommand(argv) {
98
205
  return project;
99
206
  };
100
207
  switch (topic) {
208
+ case "hunt":
209
+ return huntCommand(values, positionals, global, json, topic);
101
210
  case "run":
102
211
  if (values.env !== undefined && values["base-url"] !== undefined) {
103
212
  throw new UsageError("Pass either --env or --base-url, not both.", topic);
@@ -175,6 +284,42 @@ Exit codes:
175
284
  0 every run passed 1 a run failed
176
285
  2 usage or configuration 3 Pluswithai or network error
177
286
  4 timed out waiting`,
287
+ hunt: `Usage: pluswithai hunt <project> --url <site> [options]
288
+
289
+ Start a bug hunt: a team of agents explores the site, each in its own
290
+ browser, and reports the bugs it finds with a video of each. Follows the hunt
291
+ until it ends and prints every bug and the final summary.
292
+
293
+ Options:
294
+ --url <site> The site to hunt (required unless --session)
295
+ --agents <n> How many agents (default: your plan's default size)
296
+ --context <text> What the agents should know about the app
297
+ --new-project Create <project> first (one project per run keeps
298
+ each hunt independent)
299
+ --wait Wait for free agents when the account's pool is busy (default)
300
+ --take-available Start at once with the agents that are free
301
+ --no-wait Stop with exit code 2 when the pool is busy
302
+ --wait-timeout <time> Give up waiting after this long, e.g. 30m (default 30m)
303
+ --follow Follow the hunt until it ends (default)
304
+ --detach Start it and exit; follow later with --session
305
+ --session <id> Follow a hunt that already started
306
+ --stop Stop the hunt --session names: its lead and every agent;
307
+ waits up to 2 minutes for their current steps to end
308
+ --bug <id|n> Print one bug of the hunt --session names in full:
309
+ steps, expected, actual and video. n is the bug's
310
+ number (#3 in the hunt's view: the third it found)
311
+ -p, --project <name> The project, instead of the first argument
312
+
313
+ Ctrl+C stops following; the hunt keeps running.
314
+
315
+ ${GLOBAL_HELP}
316
+
317
+ Exit codes:
318
+ 0 the hunt finished, was stopped, or detached
319
+ 1 the hunt ended in error, or no credits
320
+ 2 usage, or the pool was busy (--no-wait)
321
+ 3 Pluswithai or network error 4 gave up waiting for free agents
322
+ (--stop: the agents are still stopping)`,
178
323
  local: `Usage: pluswithai local --project <name> [options]
179
324
 
180
325
  Run a project's tests on this machine: pull its files, install Playwright the
@@ -256,6 +401,7 @@ Run Pluswithai tests from CI and the terminal.
256
401
 
257
402
  Commands:
258
403
  run Start runs in the cloud, wait for the results, exit non-zero on failure
404
+ hunt Start a bug hunt on a site and follow it as the bugs arrive
259
405
  local Run a project's tests on this machine (e.g. against localhost)
260
406
  pull Download a project's files to run them yourself
261
407
  projects List your projects
package/dist/client.js CHANGED
@@ -57,6 +57,22 @@ export class Client {
57
57
  };
58
58
  return (await this.request("POST", `/projects/${encodeURIComponent(project)}/run-tests`, body)).results;
59
59
  }
60
+ /** A new project (one project per run). */
61
+ async createProject(name, url) {
62
+ await this.request("POST", "/projects", { name, url });
63
+ }
64
+ startHunt(project, body) {
65
+ return this.request("POST", `/projects/${encodeURIComponent(project)}/agent/hunt`, body);
66
+ }
67
+ hunt(project, sessionId, since) {
68
+ const path = `/projects/${encodeURIComponent(project)}/agent/hunt/${encodeURIComponent(sessionId)}?since=${since}`;
69
+ return this.request("GET", path);
70
+ }
71
+ /** Stops the lead and every agent of the hunt. */
72
+ stopHunt(project, sessionId) {
73
+ const path = `/projects/${encodeURIComponent(project)}/agent/hunt/${encodeURIComponent(sessionId)}/stop`;
74
+ return this.request("POST", path, {});
75
+ }
60
76
  async request(method, path, body) {
61
77
  const host = new URL(this.opts.apiUrl).host;
62
78
  const headers = {
@@ -0,0 +1,435 @@
1
+ /**
2
+ * How `pluswithai hunt` looks, with no dependency:
3
+ * ANSI colours and box-drawing characters.
4
+ *
5
+ * - live (a terminal): the header once (the name in block letters; nothing in it changes); the activity appended
6
+ * as it arrives; a new-bug highlight, the team and a status line redrawn in place at the bottom.
7
+ * - plain (not a terminal, or CI=1): the same header and activity lines appended, nothing redrawn.
8
+ * - json: one JSON document, the hunt's bugs, when it ended.
9
+ *
10
+ * An API key cannot open the app, so the view never links to it: videos are
11
+ * the signed evidence links the API returns.
12
+ */
13
+ import { colorCode, WORDMARK_WIDTH, wordmarkLines } from "./wordmark.js";
14
+ const ESC = "\u001b[";
15
+ const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
16
+ /** Agents the team block lists; the rest are counted on one line. */
17
+ export const TEAM_ROWS = 5;
18
+ /** How long a new bug stays highlighted above the team: about two polls. */
19
+ export const HIGHLIGHT_MS = 5000;
20
+ /** Every line starts this far in. */
21
+ const PAD = " ";
22
+ /** high #ef4444, medium #f59e0b, low #eab308. */
23
+ export const SEVERITY_HEX = { high: "#ef4444", medium: "#f59e0b", low: "#eab308" };
24
+ export function palette(color, depth = "256") {
25
+ const wrap = (open) => (text) => (color ? `${ESC}${open}m${text}${ESC}0m` : text);
26
+ const bySev = (paint) => ({
27
+ high: paint(SEVERITY_HEX.high),
28
+ medium: paint(SEVERITY_HEX.medium),
29
+ low: paint(SEVERITY_HEX.low),
30
+ });
31
+ return {
32
+ bold: wrap("1"),
33
+ dim: wrap("2"),
34
+ green: wrap("32"),
35
+ red: wrap("31"),
36
+ blue: wrap("34"),
37
+ link: wrap("4;36"),
38
+ cyan: wrap("36"),
39
+ sev: bySev((hex) => wrap(colorCode(38, hex, depth))),
40
+ };
41
+ }
42
+ /** mm:ss, or h:mm:ss past an hour. */
43
+ export function clock(ms) {
44
+ const total = Math.max(0, Math.floor(ms / 1000));
45
+ const h = Math.floor(total / 3600);
46
+ const m = Math.floor((total % 3600) / 60);
47
+ const s = String(total % 60).padStart(2, "0");
48
+ return h ? `${h}:${String(m).padStart(2, "0")}:${s}` : `${String(m).padStart(2, "0")}:${s}`;
49
+ }
50
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
51
+ const width = (columns) => Math.max(60, Math.min(100, columns));
52
+ /** A section's title on its own line, dim, with what it counts after it: " team 00:35 elapsed". No rules. */
53
+ export function section(p, title, right = "") {
54
+ return `${PAD}${p.dim(right ? `${title} ${right}` : title)}`;
55
+ }
56
+ /** Words to lines no wider than `w`; a word longer than the line is cut. */
57
+ export function wrapText(text, w) {
58
+ const out = [];
59
+ for (const para of text.split("\n")) {
60
+ let line = "";
61
+ for (const word of para.split(/\s+/).filter(Boolean)) {
62
+ const piece = word.length > w ? word.slice(0, w) : word;
63
+ if (!line)
64
+ line = piece;
65
+ else if (line.length + 1 + piece.length <= w)
66
+ line += ` ${piece}`;
67
+ else {
68
+ out.push(line);
69
+ line = piece;
70
+ }
71
+ }
72
+ out.push(line);
73
+ }
74
+ return out;
75
+ }
76
+ const LABEL = { high: "HIGH", medium: "MED", low: "LOW" };
77
+ /** A severity this CLI does not know yet is shown as low. */
78
+ const severityOf = (s) => (s && s in LABEL ? s : "low");
79
+ const RANK = { high: 0, medium: 1, low: 2 };
80
+ /** High first, then medium, then low; the API's order within each. */
81
+ const rank = (b) => RANK[b.severity] ?? 3;
82
+ export function bySeverity(bugs) {
83
+ return bugs.map((b, i) => ({ b, i })).sort((x, y) => rank(x.b) - rank(y.b) || x.i - y.i).map(({ b }) => b);
84
+ }
85
+ /** One bug per id (the API's ids are opaque), the latest copy kept, in the API's order. */
86
+ export function uniqueBugs(bugs) {
87
+ const byId = new Map();
88
+ for (const bug of bugs)
89
+ byId.set(bug.id, bug);
90
+ return [...byId.values()];
91
+ }
92
+ /**
93
+ * The bug a `--bug` value names: its id, or its number (#3 = the third bug the hunt found, in the snapshot's
94
+ * order, which is the order they arrived in).
95
+ */
96
+ export function findBug(bugs, ref) {
97
+ const list = uniqueBugs(bugs);
98
+ const exact = list.find((b) => b.id === ref);
99
+ if (exact)
100
+ return exact;
101
+ const n = /^#?(\d+)$/.exec(ref);
102
+ return n ? list[Number(n[1]) - 1] : undefined;
103
+ }
104
+ /** An OSC 8 hyperlink: `text` opens `url` in terminals that support it, and reads as plain `text` elsewhere. */
105
+ export const hyperlink = (url, text) => `\u001b]8;;${url}\u001b\\${text}\u001b]8;;\u001b\\`;
106
+ /**
107
+ * A bug on one line: `▌ #3 HIGH title ▶ video`. The title gives way to fit the width; the video is a hyperlink
108
+ * where the terminal makes one (`links`), else its URL in full, so it is never lost.
109
+ */
110
+ export function bugLine(p, bug, n, columns, links) {
111
+ const sev = severityOf(bug.severity);
112
+ const num = `#${n}`.padEnd(4);
113
+ // Padding, bar, number, label: 2 + 2 + 5 + 6; then 2 before the video; at least 12 characters of the title stay.
114
+ // A URL printed as text makes the line long anyway (logs, pipes): there the title stays whole.
115
+ const room = links ? Math.max(12, width(columns) - 1 - 15 - (bug.videoUrl ? "▶ video".length + 2 : 0)) : Infinity;
116
+ const parts = [p.bold(fit(bug.title, room))];
117
+ if (bug.videoUrl)
118
+ parts.push(links ? p.link(hyperlink(bug.videoUrl, "▶ video")) : `${p.dim("video")} ${bug.videoUrl}`);
119
+ return `${PAD}${p.sev[sev]("▌")} ${p.dim(num)} ${p.bold(p.sev[sev](LABEL[sev].padEnd(4)))} ${parts.join(" ")}`;
120
+ }
121
+ /** Everything about one bug (`pluswithai hunt <p> --session <id> --bug <id or number>`). */
122
+ export function bugDetail(p, bug) {
123
+ const sev = severityOf(bug.severity);
124
+ const field = (name, value) => ` ${p.dim(name.padEnd(9))}${value}`;
125
+ const lines = [`${p.bold(p.sev[sev](LABEL[sev]))} ${p.bold(bug.title)}`, ""];
126
+ lines.push(field("id", bug.id));
127
+ if (bug.videoUrl)
128
+ lines.push(field("video", bug.videoUrl));
129
+ if (bug.steps?.length)
130
+ lines.push("", ` ${p.dim("steps")}`, ...bug.steps.map((step, i) => ` ${i + 1}. ${step}`));
131
+ if (bug.expected)
132
+ lines.push("", field("expected", bug.expected));
133
+ if (bug.actual)
134
+ lines.push(field("actual", bug.actual));
135
+ return lines;
136
+ }
137
+ /** `text` cut to `max` characters, with an ellipsis when it was longer. */
138
+ export function fit(text, max) {
139
+ if (max < 2)
140
+ return "";
141
+ return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
142
+ }
143
+ /**
144
+ * One event as an activity line, timed from the hunt's start, never wider than the view (a wrapped line would
145
+ * throw the redraw off). A new bug gets a short line with its number; its title and video are in the bugs list.
146
+ */
147
+ export function eventLine(p, ev, startedAt, columns, n) {
148
+ const t = `${PAD}${p.dim(clock(ev.at - startedAt).padEnd(6))}`;
149
+ switch (ev.type) {
150
+ case "hunt-started":
151
+ return `${t} hunt started`;
152
+ case "area-started":
153
+ return `${t} started ${p.bold(fit(ev.area ?? "an area", width(columns) - 18))}`;
154
+ case "area-finished":
155
+ return `${t} finished ${p.bold(ev.area ?? "an area")}: ${plural(ev.bugs ?? 0, "bug")}`;
156
+ case "bug": {
157
+ const sev = severityOf(ev.severity);
158
+ const num = n ? `${p.dim(`#${n}`)} ` : "";
159
+ // The bug's title, not its area: several bugs of one area read alike otherwise.
160
+ return `${t} ${p.sev[sev]("▌")} ${num}new bug (${LABEL[sev].toLowerCase()})${ev.title ? `: ${p.bold(fit(ev.title, width(columns) - 34))}` : ""}`;
161
+ }
162
+ case "hunt-finished":
163
+ return `${t} hunt ${ev.status}`;
164
+ default:
165
+ return null;
166
+ }
167
+ }
168
+ const STATUS_PAINT = { hunting: "cyan", done: "green", waiting: "dim", error: "red" };
169
+ /** The team panel lists the agents at work, and the ones in trouble; the rest are counted on one line. */
170
+ const SHOWN = new Set(["hunting", "error"]);
171
+ /** A hunt by one agent has no team: its lead hunts alone and gets the one row. */
172
+ function teamOf(snap) {
173
+ if (snap.team.length)
174
+ return snap.team;
175
+ const status = snap.status === "running" ? "hunting" : snap.status === "done" ? "done" : "error";
176
+ const found = bySeverity(uniqueBugs(snap.bugs));
177
+ return [{ agent: "lead", area: null, status, bugs: found.length, severity: found[0]?.severity ?? null }];
178
+ }
179
+ /**
180
+ * The team panel in fixed columns: mark · the agent by its area, as the app names it ("Hunter 2" while it has none)
181
+ * · status · bugs · time in the area. Only the agents hunting
182
+ * (and any in error) are listed, at most TEAM_ROWS; one line counts the others. Bugs are coloured by the worst
183
+ * severity that agent found; "hunting" turns green once it found one; the time shows while it hunts an area
184
+ * whose start this CLI saw.
185
+ */
186
+ export function teamBlock(p, snap, now, { spinner = "●", areaSince = new Map() } = {}) {
187
+ const lines = [section(p, "team", `${clock(now - snap.startedAt)} elapsed`)];
188
+ const team = teamOf(snap);
189
+ const shown = team.filter((m) => SHOWN.has(m.status)).slice(0, TEAM_ROWS);
190
+ for (const m of shown) {
191
+ // The API counts on a row the bugs of the area it names, and gives the worst of them.
192
+ const n = m.bugs;
193
+ const paint = p[m.status === "hunting" && n > 0 ? "green" : STATUS_PAINT[m.status]];
194
+ const mark = m.status === "hunting" ? spinner : "✗";
195
+ const area = fit(m.area ?? hunterName(m.agent), 30).padEnd(30);
196
+ const count = plural(n, "bug").padEnd(7);
197
+ const bugText = !n ? p.dim(count) : m.severity ? p.sev[severityOf(m.severity)](count) : p.bold(count);
198
+ const since = m.status === "hunting" ? areaSince.get(m.agent) : undefined;
199
+ const time = since === undefined ? "" : ` ${p.dim(clock(now - since))}`;
200
+ lines.push(`${PAD}${paint(mark)} ${area} ${paint(m.status.padEnd(8))} ${bugText}${time}`.trimEnd());
201
+ }
202
+ const hidden = team.filter((m) => !shown.includes(m));
203
+ if (hidden.length) {
204
+ const done = hidden.filter((m) => m.status === "done").length;
205
+ const found = hidden.reduce((k, m) => k + m.bugs, 0);
206
+ lines.push(p.dim(`${PAD} … ${plural(hidden.length, "more agent")} · ${done} done · ${plural(found, "bug")}`));
207
+ }
208
+ return lines;
209
+ }
210
+ /** An agent with no area yet, as the app words it: "Hunter 2" for agent2; the lead hunting alone covers the whole site. */
211
+ export function hunterName(agent) {
212
+ if (agent === "lead")
213
+ return "Whole site";
214
+ const n = /(\d+)$/.exec(agent)?.[1];
215
+ return n ? `Hunter ${n}` : "Hunter";
216
+ }
217
+ /** "● LIVE · 6 bugs · 15 agents · 0/12 areas"; `pulse` dims the dot every other beat while the hunt runs. */
218
+ export function statusLine(p, snap, pulse = false) {
219
+ const state = { running: ["LIVE", p.green], done: ["DONE", p.green], stopped: ["STOPPED", p.dim], error: ["ERROR", p.red] };
220
+ const [label, paint] = state[snap.status] ?? ["ERROR", p.red];
221
+ const dot = snap.status === "running" && pulse ? p.dim(p.green("●")) : paint("●");
222
+ const facts = [plural(uniqueBugs(snap.bugs).length, "bug"), plural(snap.agents.granted, "agent"), `${snap.areas.done}/${snap.areas.total} areas`];
223
+ return `${dot} ${p.bold(paint(label))} ${p.dim("·")} ${facts.join(` ${p.dim("·")} `)}`;
224
+ }
225
+ /** The final summary in a box, wrapped to the view's width. */
226
+ export function summaryBox(p, snap, columns) {
227
+ const w = width(columns) - 4 - PAD.length;
228
+ const found = uniqueBugs(snap.bugs);
229
+ const counts = ["high", "medium", "low"].map((s) => `${found.filter((b) => b.severity === s).length} ${s}`);
230
+ const head = `${plural(found.length, "bug")} in ${plural(snap.areas.done, "area")} · ${counts.join(" · ")} · ${snap.creditsUsed.toLocaleString("en-US")} credits`;
231
+ const body = [{ text: "" }, ...wrapText(head, w - 2).map((text) => ({ text, paint: p.bold }))];
232
+ if (snap.summary?.text)
233
+ body.push({ text: "" }, ...wrapText(snap.summary.text, w - 2).map((text) => ({ text })));
234
+ if (snap.summary?.notCovered?.length)
235
+ body.push({ text: "" }, ...wrapText(`Not covered: ${snap.summary.notCovered.join("; ")}`, w - 2).map((text) => ({ text, paint: p.dim })));
236
+ // Stopped (by a person, or a harness's time limit) is an end, not a failure.
237
+ if (snap.status === "stopped")
238
+ body.push({ text: "" }, { text: "The hunt was stopped before it finished.", paint: p.dim });
239
+ else if (snap.status !== "done")
240
+ body.push({ text: "" }, { text: `The hunt ended with status "${snap.status}".`, paint: p.red });
241
+ body.push({ text: "" });
242
+ const top = PAD + p.green(`╭─ Summary ${"─".repeat(w - 10)}╮`);
243
+ const bottom = PAD + p.green(`╰${"─".repeat(w)}╯`);
244
+ return [top, ...body.map(({ text, paint }) => `${PAD}${p.green("│")} ${(paint ?? ((t) => t))(text.padEnd(w - 2))} ${p.green("│")}`), bottom];
245
+ }
246
+ /** "acme-shop-run-15 · staging.acme.dev · s3e3a0b": the site without its scheme. */
247
+ const detailsOf = (project, snap) => [project, snap.site.replace(/^https?:\/\//, "").replace(/\/$/, ""), snap.sessionId].join(" · ");
248
+ /**
249
+ * The header. Plain: "◆ Pluswithai · bug hunt" and the project, site, agents, session and watch link on their own
250
+ * lines. With `banner` (the name in block letters) it is lighter: the wordmark, then one dim line with the project,
251
+ * site and session, and the watch link. A terminal too narrow for the wordmark gets the name as text. Nothing in
252
+ * the header changes while the hunt runs: the counts are in the bottom block.
253
+ */
254
+ export function headerLines(p, project, snap, banner, columns = 100) {
255
+ if (!banner) {
256
+ const agents = snap.agents.granted === snap.agents.requested ? String(snap.agents.granted) : `${snap.agents.granted} of ${snap.agents.requested} asked for`;
257
+ return [
258
+ `${PAD}${p.green("◆")} ${p.bold("Pluswithai")} ${p.dim("· bug hunt")}`,
259
+ `${PAD}${p.dim("project")} ${project}`,
260
+ `${PAD}${p.dim("site ")} ${snap.site}`,
261
+ `${PAD}${p.dim("agents ")} ${agents}`,
262
+ `${PAD}${p.dim("session")} ${snap.sessionId}`,
263
+ // The watch page needs no sign-in, so it is safe to show to a caller with only an API key.
264
+ ...(snap.watchUrl ? [`${PAD}${p.dim("watch ")} ${p.link(snap.watchUrl)}`] : []),
265
+ "",
266
+ ];
267
+ }
268
+ const fits = columns >= PAD.length + WORDMARK_WIDTH;
269
+ return [
270
+ ...(fits ? [...banner.map((line) => `${PAD}${line}`), ""] : [`${PAD}${p.bold(p.green("Pluswithai"))}`]),
271
+ `${PAD}${p.dim(`bug hunt ${fit(detailsOf(project, snap), Math.max(10, columns - PAD.length - 10))}`)}`,
272
+ ...(snap.watchUrl ? [`${PAD}${p.dim("watch")} ${p.link(snap.watchUrl)}`] : []),
273
+ "",
274
+ ];
275
+ }
276
+ /** Terminal rows a printed line takes, its escape codes left out and its wrapping counted. */
277
+ export function rowsOf(line, columns) {
278
+ // eslint-disable-next-line no-control-regex
279
+ const visible = line.replace(/\u001b\]8;;[^\u001b]*\u001b\\/g, "").replace(/\u001b\[[0-9;]*[A-Za-z]/g, "");
280
+ return Math.max(1, Math.ceil(visible.length / Math.max(1, columns)));
281
+ }
282
+ export function createHuntView(opts) {
283
+ return opts.json ? jsonView(opts) : textView(opts);
284
+ }
285
+ /**
286
+ * `--json`: one JSON document on stdout, the hunt's bugs, once it ended (or `{ sessionId, status }` when the
287
+ * command leaves a hunt running, so a script can read it later). Nothing else is printed there; what a person
288
+ * would want to know meanwhile (waiting for agents, a retry) goes to `warn`.
289
+ */
290
+ function jsonView(opts) {
291
+ const out = (value) => opts.write(`${JSON.stringify(value, null, 2)}\n`);
292
+ const warn = (text) => opts.warn?.(text);
293
+ return {
294
+ projectCreated: () => { },
295
+ started: () => { },
296
+ waiting: (message, retryInSeconds) => warn(`${message} Trying again in ${retryInSeconds}s…`),
297
+ update: () => { },
298
+ tick: () => { },
299
+ finished: (snap) => out(uniqueBugs(snap.bugs)),
300
+ detached: (sessionId) => out({ sessionId, status: "running" }),
301
+ notice: (message) => warn(message),
302
+ };
303
+ }
304
+ function textView(opts) {
305
+ const p = palette(opts.color, opts.depth);
306
+ let w = opts.columns;
307
+ const fancy = opts.live && opts.banner !== null;
308
+ const say = (lines) => opts.write(lines.map((l) => `${l}\n`).join(""));
309
+ let header = false;
310
+ let latest = null;
311
+ /** The bottom block as drawn, and the rows it takes (its lines may wrap). */
312
+ let liveDrawn = [];
313
+ let liveHeight = 0;
314
+ const rowsIn = (lines) => lines.reduce((n, l) => n + rowsOf(l, w), 0);
315
+ let frame = 0;
316
+ /** Bug numbers in order of arrival (#1, #2…), by id. */
317
+ const numbers = new Map();
318
+ const numberOf = (id) => {
319
+ if (!numbers.has(id))
320
+ numbers.set(id, numbers.size + 1);
321
+ return numbers.get(id);
322
+ };
323
+ const areaSince = new Map();
324
+ /** New bugs highlighted above the team until HIGHLIGHT_MS after they arrived. */
325
+ let highlights = [];
326
+ const spin = () => SPINNER[frame % SPINNER.length];
327
+ const liveLines = () => {
328
+ if (!latest)
329
+ return [];
330
+ const now = opts.now();
331
+ highlights = highlights.filter((h) => h.until > now);
332
+ // The severity's bar and "NEW #n" in its colour, the title in plain text: light, and gone in a few seconds.
333
+ const lit = highlights.map(({ bug, n }) => {
334
+ const sev = severityOf(bug.severity);
335
+ const head = `NEW #${n}`;
336
+ return `${PAD}${p.sev[sev]("▌")} ${p.bold(p.sev[sev](head))} ${fit(bug.title, width(w) - PAD.length - head.length - 5)}`;
337
+ });
338
+ // The hunt's state and counts, here and not in the header: this block is redrawn on every tick.
339
+ const footer = `${statusLine(p, latest, Math.floor(frame / 2) % 2 === 1)} ${p.dim(`· ${latest.creditsUsed.toLocaleString("en-US")} credits · Ctrl+C to detach`)}`;
340
+ return ["", ...(lit.length ? [...lit, ""] : []), ...teamBlock(p, latest, now, { spinner: spin(), areaSince }), "", PAD + footer];
341
+ };
342
+ /** Clears the bottom block, prints what is new above it, and draws the block again. */
343
+ const render = (above) => {
344
+ if (!opts.live) {
345
+ if (above.length)
346
+ say(above);
347
+ return;
348
+ }
349
+ let text = liveHeight ? `${ESC}${liveHeight}F${ESC}J` : "";
350
+ text += above.map((l) => `${l}\n`).join("");
351
+ const live = liveLines();
352
+ text += live.map((l) => `${l}\n`).join("");
353
+ liveDrawn = live;
354
+ liveHeight = rowsIn(live);
355
+ opts.write(text);
356
+ };
357
+ const clearLive = () => {
358
+ if (opts.live && liveHeight)
359
+ opts.write(`${ESC}${liveHeight}F${ESC}J`);
360
+ liveHeight = 0;
361
+ };
362
+ return {
363
+ // A terminal goes straight to the header; logs (CI, pipes) keep these lines.
364
+ projectCreated: (project) => {
365
+ if (!opts.live)
366
+ render([PAD + p.dim(`Created project ${project}.`)]);
367
+ },
368
+ started: (start) => {
369
+ if (opts.live)
370
+ return;
371
+ const granted = start.agents.granted === start.agents.requested ? "" : ` (${start.agents.requested} asked for; the rest of the pool is busy)`;
372
+ render([PAD + p.dim(`Started a bug hunt with ${plural(start.agents.granted, "agent")}${granted}.`)]);
373
+ },
374
+ waiting: (message, retryInSeconds) => render([PAD + p.dim(`${message} Trying again in ${retryInSeconds}s…`)]),
375
+ update: (snap, events) => {
376
+ latest = snap;
377
+ for (const b of uniqueBugs(snap.bugs))
378
+ numberOf(b.id);
379
+ const above = [];
380
+ if (!header) {
381
+ header = true;
382
+ above.push(...(fancy ? headerLines(p, opts.project, snap, wordmarkLines(opts.banner), w) : headerLines(p, opts.project, snap)));
383
+ above.push(section(p, "activity"));
384
+ }
385
+ const now = opts.now();
386
+ for (const ev of events) {
387
+ if (ev.type === "area-started" && ev.agent)
388
+ areaSince.set(ev.agent, ev.at);
389
+ if (ev.type === "area-finished" && ev.agent)
390
+ areaSince.delete(ev.agent);
391
+ const n = ev.type === "bug" && ev.bugId ? numberOf(ev.bugId) : undefined;
392
+ const line = eventLine(p, ev, snap.startedAt, w, n);
393
+ if (line)
394
+ above.push(line);
395
+ const bug = n ? snap.bugs.find((b) => b.id === ev.bugId) : undefined;
396
+ if (bug && fancy)
397
+ highlights.push({ bug, n: n, until: now + HIGHLIGHT_MS });
398
+ }
399
+ render(above);
400
+ },
401
+ tick: () => {
402
+ const size = opts.size?.();
403
+ if (size && size.columns !== w) {
404
+ w = size.columns;
405
+ liveHeight = rowsIn(liveDrawn);
406
+ }
407
+ frame++;
408
+ render([]);
409
+ },
410
+ finished: (snap) => {
411
+ latest = snap;
412
+ for (const b of uniqueBugs(snap.bugs))
413
+ numberOf(b.id);
414
+ clearLive();
415
+ const found = uniqueBugs(snap.bugs);
416
+ const lines = ["", section(p, "bugs", `${found.length} found`)];
417
+ if (!found.length)
418
+ lines.push(PAD + p.dim("No bugs found."));
419
+ const listed = bySeverity(found);
420
+ for (const b of listed)
421
+ lines.push(bugLine(p, b, numberOf(b.id), w, opts.links));
422
+ lines.push("", section(p, "done", `${clock((snap.endedAt ?? opts.now()) - snap.startedAt)} elapsed`), ...summaryBox(p, snap, w), "");
423
+ lines.push(`${PAD}${p.dim("json")} pluswithai hunt ${opts.project} --session ${snap.sessionId} --json`);
424
+ if (found.length)
425
+ lines.push(`${PAD}${p.dim("a bug")} pluswithai hunt ${opts.project} --session ${snap.sessionId} --bug ${numberOf(listed[0].id)}`);
426
+ say(lines);
427
+ },
428
+ detached: (sessionId, interrupted) => {
429
+ clearLive();
430
+ const why = interrupted ? "Detached." : "Started.";
431
+ say([`${PAD}${why} The hunt keeps running. Follow it with: pluswithai hunt ${opts.project} --session ${sessionId}`]);
432
+ },
433
+ notice: (message) => render([PAD + p.dim(message)]),
434
+ };
435
+ }
package/dist/hunt.js ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * `pluswithai hunt`: start a bug hunt, wait for the account's pool when asked,
3
+ * follow it and end with its verdict. Time,
4
+ * sleeping and Ctrl+C are injected so the loop runs instantly under test;
5
+ * what it prints is the view's business (hunt-view.ts).
6
+ */
7
+ import { ApiError } from "./client.js";
8
+ export const HUNT_EXIT = { done: 0, failed: 1, busy: 2, api: 3, timeout: 4 };
9
+ /** How long to wait between two tries when the pool is busy and the API names no delay. */
10
+ export const DEFAULT_POOL_RETRY_SECONDS = 30;
11
+ export const MAX_POOL_RETRY_SECONDS = 60;
12
+ /** Polls of a running hunt that may fail in a row before the CLI gives up. */
13
+ export const MAX_POLL_FAILURES = 5;
14
+ /** Starts that may fail on a network error or a 5xx before the CLI gives up. */
15
+ export const MAX_START_RETRIES = 3;
16
+ /** --wait sends "wait" and retries on 409; --no-wait sends "none" and stops; --take-available starts with what is free. */
17
+ const POOL_BODY = { wait: "wait", none: "none", available: "available" };
18
+ /** The API's message without its status code ("409 The account's…" → "The account's…"). */
19
+ const plainMessage = (e) => e.message.replace(/^\d{3} /, "");
20
+ const retrySeconds = (e) => Math.min(Math.max(1, e.retryAfterSeconds ?? DEFAULT_POOL_RETRY_SECONDS), MAX_POOL_RETRY_SECONDS);
21
+ export async function executeHunt(deps, opts) {
22
+ let interrupted = false;
23
+ const stopListening = deps.onInterrupt(() => {
24
+ interrupted = true;
25
+ });
26
+ try {
27
+ let sessionId = opts.sessionId;
28
+ if (!sessionId) {
29
+ if (opts.newProject) {
30
+ await deps.client.createProject(opts.project, opts.url);
31
+ deps.view.projectCreated(opts.project);
32
+ }
33
+ const started = await start(deps, opts, () => interrupted);
34
+ if (typeof started === "number")
35
+ return started;
36
+ deps.view.started(started);
37
+ sessionId = started.sessionId;
38
+ if (!opts.follow) {
39
+ deps.view.detached(sessionId, false);
40
+ return HUNT_EXIT.done;
41
+ }
42
+ }
43
+ return await follow(deps, opts, sessionId, () => interrupted);
44
+ }
45
+ finally {
46
+ stopListening();
47
+ }
48
+ }
49
+ /** Starts the hunt, waiting on a busy pool when the policy says so. A number is an exit code. */
50
+ async function start(deps, opts, interrupted) {
51
+ const body = {
52
+ url: opts.url,
53
+ pool: POOL_BODY[opts.pool],
54
+ ...(opts.agents !== undefined ? { agents: opts.agents } : {}),
55
+ ...(opts.context ? { context: opts.context } : {}),
56
+ };
57
+ const deadline = deps.now() + opts.waitTimeoutMs;
58
+ let failures = 0;
59
+ for (;;) {
60
+ try {
61
+ return await deps.client.startHunt(opts.project, body);
62
+ }
63
+ catch (e) {
64
+ if (!(e instanceof ApiError))
65
+ throw e;
66
+ if (e.status === 409) {
67
+ if (opts.pool !== "wait") {
68
+ deps.view.notice(plainMessage(e));
69
+ return HUNT_EXIT.busy;
70
+ }
71
+ const wait = retrySeconds(e);
72
+ if (deps.now() + wait * 1000 > deadline) {
73
+ deps.view.notice(`Gave up waiting for free agents: ${plainMessage(e)}`);
74
+ return HUNT_EXIT.timeout;
75
+ }
76
+ deps.view.waiting(plainMessage(e), wait);
77
+ await deps.sleep(wait * 1000);
78
+ if (interrupted()) {
79
+ deps.view.notice("Stopped waiting: no hunt was started.");
80
+ return HUNT_EXIT.done;
81
+ }
82
+ continue;
83
+ }
84
+ if (!e.transient || ++failures > MAX_START_RETRIES)
85
+ throw e;
86
+ deps.view.notice(`${e.message} — retrying`);
87
+ await deps.sleep(Math.min(e.retryAfterSeconds ?? 5, MAX_POOL_RETRY_SECONDS) * 1000);
88
+ }
89
+ }
90
+ }
91
+ /** Polls the hunt until it ends or the person presses Ctrl+C. */
92
+ async function follow(deps, opts, sessionId, interrupted) {
93
+ let since = 0;
94
+ let failures = 0;
95
+ for (;;) {
96
+ let snapshot = null;
97
+ try {
98
+ snapshot = await deps.client.hunt(opts.project, sessionId, since);
99
+ failures = 0;
100
+ }
101
+ catch (e) {
102
+ if (!(e instanceof ApiError) || !e.transient || ++failures > MAX_POLL_FAILURES)
103
+ throw e;
104
+ deps.view.notice(`${e.message} — retrying`);
105
+ }
106
+ if (snapshot) {
107
+ // Only events not seen yet: a repeated `since` must not print one twice.
108
+ const fresh = snapshot.events.filter((ev) => ev.seq > since);
109
+ deps.view.update(snapshot, fresh);
110
+ since = Math.max(since, snapshot.seq);
111
+ if (snapshot.status !== "running") {
112
+ deps.view.finished(snapshot);
113
+ // Stopped (by a person, or a harness's time limit) is an end like done; only an error fails.
114
+ return snapshot.status === "error" ? HUNT_EXIT.failed : HUNT_EXIT.done;
115
+ }
116
+ }
117
+ for (let waited = 0; waited < opts.intervalMs; waited += opts.tickMs) {
118
+ if (interrupted()) {
119
+ deps.view.detached(sessionId, true);
120
+ return HUNT_EXIT.done;
121
+ }
122
+ deps.view.tick();
123
+ await deps.sleep(Math.min(opts.tickMs, opts.intervalMs - waited));
124
+ }
125
+ }
126
+ }
package/dist/main.js CHANGED
@@ -8,6 +8,9 @@ import { ApiError, Client } from "./client.js";
8
8
  import { redact, resolveConfig } from "./config.js";
9
9
  import { annotations, junitXml, markdownSummary, progressLine, projectsText, runJson, runsText, startedLine, summaryText, testsText, whoamiText, } from "./report.js";
10
10
  import { executeRun, NoTestsError } from "./run.js";
11
+ import { executeHunt, HUNT_EXIT } from "./hunt.js";
12
+ import { bugDetail, createHuntView, findBug, palette } from "./hunt-view.js";
13
+ import { colorDepthOf } from "./wordmark.js";
11
14
  import { runMcpProxy } from "./mcp-proxy.js";
12
15
  import { defaultDir, LocalSetupError, pullProject, testLocally } from "./local.js";
13
16
  import { VERSION } from "./version.js";
@@ -67,6 +70,24 @@ export async function main(deps) {
67
70
  }
68
71
  case "run":
69
72
  return await runCommand(deps, config, client, command);
73
+ case "hunt":
74
+ return await huntCommand(deps, client, command);
75
+ case "hunt-bug": {
76
+ const snap = await client.hunt(command.project, command.sessionId, 0);
77
+ // An id, or the bug's number in order of arrival (#3, as the hunt view shows it).
78
+ const bug = findBug(snap.bugs, command.bugId);
79
+ if (!bug) {
80
+ deps.stderr(line(`error: Hunt ${command.sessionId} lists no bug ${command.bugId}. Its bugs and their ids: pluswithai hunt ${command.project} --session ${command.sessionId} --json`));
81
+ return EXIT.usage;
82
+ }
83
+ print(command.json, bug, bugDetail(palette(deps.terminal().tty && deps.env.NO_COLOR === undefined, colorDepthOf(deps.env.COLORTERM)), bug).join("\n"));
84
+ return EXIT.ok;
85
+ }
86
+ case "hunt-stop": {
87
+ const stopped = await stopHunt(deps, client, command);
88
+ print(command.json, stopped.state, stopped.text);
89
+ return stopped.exitCode;
90
+ }
70
91
  case "pull": {
71
92
  const dir = command.dir ?? defaultDir(command.project);
72
93
  const pulled = await pullProject(deps, client, command.project, dir);
@@ -112,7 +133,8 @@ export async function main(deps) {
112
133
  const hint = hintFor(e, command);
113
134
  if (hint)
114
135
  deps.stderr(line(hint));
115
- return EXIT.api;
136
+ // No credits is the hunt's own failure, not the API's: the same exit as a hunt that ended in error.
137
+ return e.status === 402 && command.kind === "hunt" ? HUNT_EXIT.failed : EXIT.api;
116
138
  }
117
139
  deps.stderr(line(`unexpected error: ${redact(describe(e), config.apiKey)}`));
118
140
  return EXIT.api;
@@ -121,10 +143,17 @@ export async function main(deps) {
121
143
  function hintFor(e, command) {
122
144
  if (e.status === 401)
123
145
  return "Check PLUSWITHAI_API_KEY (create one on the app's API keys page).";
146
+ if (e.status === 403 && (command.kind === "hunt" || command.kind === "hunt-stop" || command.kind === "hunt-bug"))
147
+ return "Starting a hunt needs a key with Agent (write + run) access, and a plan with bug hunts.";
148
+ if (e.status === 402 && command.kind === "hunt")
149
+ return "The account is out of credits.";
124
150
  if (e.status === 403 && command.kind === "run")
125
151
  return "Starting runs needs a key with CI / CLI (read + run) access.";
126
152
  if (e.status === 402 && (command.kind === "pull" || command.kind === "local"))
127
153
  return "Your plan cannot download this project's files.";
154
+ // A hunt followed, stopped or read by its session: either name may be the wrong one.
155
+ if (e.status === 404 && "sessionId" in command && command.sessionId)
156
+ return `Check the session id "${command.sessionId}" and the project name "${command.project}": the hunt is looked up in that project.`;
128
157
  if (e.status === 404 && "project" in command)
129
158
  return `Check the project name "${command.project}" (pluswithai projects lists them).`;
130
159
  return null;
@@ -165,3 +194,59 @@ async function runCommand(deps, config, client, command) {
165
194
  }
166
195
  return outcome.exitCode;
167
196
  }
197
+ /** After --stop, the hunt reads "running" until its agents' current steps end: wait this long for "stopped". */
198
+ export const HUNT_STOP_WAIT_MS = 120_000;
199
+ async function stopHunt(deps, client, command) {
200
+ let state = await client.stopHunt(command.project, command.sessionId);
201
+ const deadline = deps.now() + HUNT_STOP_WAIT_MS;
202
+ if (state.status === "running" && !command.json)
203
+ deps.stdout(line(`Stopping hunt ${state.sessionId}: its agents finish their current step…`));
204
+ while (state.status === "running" && deps.now() < deadline) {
205
+ await deps.sleep(HUNT_POLL_MS);
206
+ const snap = await client.hunt(command.project, command.sessionId, 0);
207
+ state = { sessionId: snap.sessionId, status: snap.status };
208
+ }
209
+ const stillRunning = state.status === "running";
210
+ const text = stillRunning
211
+ ? `Hunt ${state.sessionId} is still stopping. Check it with: pluswithai hunt ${command.project} --session ${state.sessionId}`
212
+ : `Hunt ${state.sessionId}: ${state.status}.`;
213
+ return { state, text, exitCode: stillRunning ? HUNT_EXIT.timeout : EXIT.ok };
214
+ }
215
+ /** Polls a running hunt this often; the spinner moves in between. */
216
+ export const HUNT_POLL_MS = 3000;
217
+ export const HUNT_TICK_MS = 250;
218
+ async function huntCommand(deps, client, command) {
219
+ const terminal = deps.terminal();
220
+ // CI logs keep every line: no redrawing there, and no colour unless it is a terminal.
221
+ const ci = !!deps.env.CI && deps.env.CI !== "false" && deps.env.CI !== "0";
222
+ const view = createHuntView({
223
+ write: deps.stdout,
224
+ project: command.project,
225
+ json: command.json,
226
+ live: terminal.tty && !ci,
227
+ color: terminal.tty && deps.env.NO_COLOR === undefined,
228
+ // Clickable "▶ video" only where a terminal likely renders OSC 8; CI logs and NO_COLOR get the URL as text.
229
+ links: terminal.tty && !ci && deps.env.NO_COLOR === undefined,
230
+ // The name in block letters: a live, coloured terminal only; truecolor where COLORTERM says so.
231
+ banner: terminal.tty && !ci && deps.env.NO_COLOR === undefined && !command.json ? colorDepthOf(deps.env.COLORTERM) : null,
232
+ depth: colorDepthOf(deps.env.COLORTERM),
233
+ // Not a terminal (a CI log): lines are not wrapped by anyone, so the view may use its full width.
234
+ columns: terminal.tty ? terminal.columns : 100,
235
+ now: deps.now,
236
+ warn: (text) => deps.stderr(line(text)),
237
+ ...(terminal.tty ? { size: () => deps.terminal() } : {}),
238
+ });
239
+ return executeHunt({ client, view, sleep: deps.sleep, now: deps.now, onInterrupt: deps.onInterrupt }, {
240
+ project: command.project,
241
+ sessionId: command.sessionId,
242
+ url: command.url,
243
+ agents: command.agents,
244
+ context: command.context,
245
+ newProject: command.newProject,
246
+ pool: command.pool,
247
+ waitTimeoutMs: command.waitTimeoutSec * 1000,
248
+ follow: command.follow,
249
+ intervalMs: HUNT_POLL_MS,
250
+ tickMs: terminal.tty && !ci && !command.json ? HUNT_TICK_MS : HUNT_POLL_MS,
251
+ });
252
+ }
package/dist/node-deps.js CHANGED
@@ -28,6 +28,15 @@ export function nodeDeps(proc) {
28
28
  await writeFile(path, bytes);
29
29
  },
30
30
  remove: (path) => rm(path, { force: true }),
31
+ terminal: () => ({ tty: process.stdout.isTTY === true, columns: process.stdout.columns ?? 80, rows: process.stdout.rows ?? 24 }),
32
+ onInterrupt: (handler) => {
33
+ // While a hunt is followed, Ctrl+C stops following instead of killing the process mid-line.
34
+ const listener = () => handler();
35
+ process.on("SIGINT", listener);
36
+ return () => {
37
+ process.off("SIGINT", listener);
38
+ };
39
+ },
31
40
  exists: (path) => access(path).then(() => true, () => false),
32
41
  spawn: (command, args, opts) => new Promise((resolve, reject) => {
33
42
  // npm and npx are .cmd scripts on Windows: they need a shell there.
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /** Kept equal to package.json's version by test/node-deps.test.ts. */
2
- export const VERSION = "0.4.0";
2
+ export const VERSION = "0.5.0";
@@ -0,0 +1,53 @@
1
+ /** COLORTERM=truecolor or 24bit: exact colours; any other terminal gets the nearest of the 256. */
2
+ export const colorDepthOf = (colorterm) => (colorterm === "truecolor" || colorterm === "24bit" ? "truecolor" : "256");
3
+ const rgbOf = (hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16));
4
+ /** The nearest colour of xterm's 256: the 6×6×6 cube or the grey ramp, whichever is closer. */
5
+ export function to256(hex) {
6
+ const [r, g, b] = rgbOf(hex);
7
+ const steps = [0, 95, 135, 175, 215, 255];
8
+ const nearest = (v) => steps.reduce((best, s, i) => (Math.abs(s - v) < Math.abs(steps[best] - v) ? i : best), 0);
9
+ const [cr, cg, cb] = [nearest(r), nearest(g), nearest(b)];
10
+ const cube = 16 + 36 * cr + 6 * cg + cb;
11
+ const greyIndex = Math.min(23, Math.max(0, Math.round(((r + g + b) / 3 - 8) / 10)));
12
+ const grey = 8 + greyIndex * 10;
13
+ const dist = (x, y, z) => (r - x) ** 2 + (g - y) ** 2 + (b - z) ** 2;
14
+ return dist(grey, grey, grey) < dist(steps[cr], steps[cg], steps[cb]) ? 232 + greyIndex : cube;
15
+ }
16
+ /** The SGR parameters for `hex` as foreground (38) or background (48): exact in truecolor, else the nearest of 256. */
17
+ export const colorCode = (layer, hex, depth) => depth === "truecolor" ? `${layer};2;${rgbOf(hex).join(";")}` : `${layer};5;${to256(hex)}`;
18
+ /** A 5-row pixel font for the letters of the name; "#" is a lit pixel. */
19
+ const FONT = {
20
+ P: ["###.", "#..#", "###.", "#...", "#..."],
21
+ L: ["#...", "#...", "#...", "#...", "####"],
22
+ U: ["#..#", "#..#", "#..#", "#..#", ".##."],
23
+ S: [".###", "#...", ".##.", "...#", "###."],
24
+ W: ["#...#", "#...#", "#.#.#", "##.##", "#...#"],
25
+ I: ["###", ".#.", ".#.", ".#.", "###"],
26
+ T: ["###", ".#.", ".#.", ".#.", ".#."],
27
+ H: ["#..#", "#..#", "####", "#..#", "#..#"],
28
+ A: [".##.", "#..#", "####", "#..#", "#..#"],
29
+ };
30
+ /** The name's pixels: 5 rows, the letters one column apart. */
31
+ const PIXELS = Array.from({ length: 5 }, (_, row) => [..."PLUSWITHAI"].map((letter) => FONT[letter][row]).join("."));
32
+ /** Columns the wordmark takes. */
33
+ export const WORDMARK_WIDTH = PIXELS[0].length;
34
+ /** The brand's gradient, left to right (the favicon's greens). */
35
+ const FROM = [0x14, 0xe6, 0x90];
36
+ const TO = [0x0a, 0xac, 0xab];
37
+ const hex = (n) => Math.round(n).toString(16).padStart(2, "0");
38
+ const gradientAt = (col) => `#${FROM.map((from, i) => hex(from + ((TO[i] - from) * col) / (WORDMARK_WIDTH - 1))).join("")}`;
39
+ /**
40
+ * The wordmark as 3 terminal lines: half blocks, two rows of pixels per line ("▀" upper, "▄" lower, "█" both),
41
+ * each column in its colour of the gradient.
42
+ */
43
+ export function wordmarkLines(depth) {
44
+ return Array.from({ length: 3 }, (_, line) => {
45
+ let text = "";
46
+ for (let col = 0; col < WORDMARK_WIDTH; col++) {
47
+ const upper = PIXELS[line * 2]?.[col] === "#";
48
+ const lower = PIXELS[line * 2 + 1]?.[col] === "#";
49
+ text += upper || lower ? `\u001b[${colorCode(38, gradientAt(col), depth)}m${upper && lower ? "█" : upper ? "▀" : "▄"}\u001b[0m` : " ";
50
+ }
51
+ return text.trimEnd();
52
+ });
53
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pluswithai/cli",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Run Pluswithai tests from CI and the terminal.",
5
5
  "license": "MIT",
6
6
  "repository": {