@coreautomata/cli 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 CHANGED
@@ -1,3 +1,170 @@
1
- # Temporary Holding Version
1
+ # CoreAutomata CLI, GitHub Action and Claude Code plugin
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Command line tools for [CoreAutomata](https://www.coreautomata.com), the mobile QA
4
+ service that runs your test cases on real Android and iOS devices.
5
+
6
+ - **`@coreautomata/cli`**: upload a build, run test cases, wait for the result, write
7
+ JUnit and a GitHub job summary, and exit with a CI-friendly code. `coreautomata mcp`
8
+ runs a local MCP server for Claude Code with an `upload_build` tool.
9
+ - **GitHub Action** (`action/`): a composite Action that runs the CLI in a workflow.
10
+ - **Claude Code plugin** (`plugins/coreautomata`) and marketplace
11
+ (`.claude-plugin/marketplace.json`): the CoreAutomata MCP server plus four skills.
12
+
13
+ > **Licence.** CoreAutomata is proprietary, commercial software. This repository and
14
+ > the `@coreautomata/cli` package are not open source: use requires a CoreAutomata
15
+ > account and is subject to the CoreAutomata terms of service. No licence to copy,
16
+ > modify or redistribute the code is granted.
17
+
18
+ ## Install
19
+
20
+ Node.js 20.3 or newer.
21
+
22
+ ```bash
23
+ npx @coreautomata/cli@0.2.0 --help
24
+ # or
25
+ npm install --global @coreautomata/cli@0.2.0
26
+ coreautomata --help
27
+ ```
28
+
29
+ To try an unreleased change, build a tarball from this repository and run it with
30
+ `npx --package ./coreautomata-cli-<version>.tgz coreautomata --help`:
31
+
32
+ ```bash
33
+ npm ci && npm pack
34
+ ```
35
+
36
+ ## Configure
37
+
38
+ Create a scoped API key on the CoreAutomata **Integrations** page (scopes `read` and
39
+ `run`; limit it to the projects CI needs and give it a monthly action budget), then:
40
+
41
+ ```bash
42
+ # Paste the key at the prompt: it is not echoed and stays out of your shell history.
43
+ read -rs COREAUTOMATA_API_KEY && export COREAUTOMATA_API_KEY
44
+ # optional, defaults to https://api.coreautomata.com
45
+ export COREAUTOMATA_API_BASE=https://api.coreautomata.com
46
+ ```
47
+
48
+ The key is read only from the environment, never from a flag, and is never printed.
49
+
50
+ ## Commands
51
+
52
+ ```bash
53
+ # Upload a build; cases and the app map are carried from the latest build
54
+ coreautomata upload app-release.apk --project <project_id> [--carry-from latest|<build>|none] [--wait-analyzed[=600]] [--json]
55
+
56
+ # Run cases (exactly one selector) and wait for the result
57
+ coreautomata run --project <project_id> --tag smoke --wait --junit coreautomata-junit.xml
58
+ coreautomata run --project <project_id> --cases <id>,<id> --devices auto --dry-run
59
+ coreautomata run --project <project_id> --smoke --app app-release.apk --wait # upload, install, run
60
+
61
+ # Show or wait for a run
62
+ coreautomata status <run_id> [--wait] [--junit <path>] [--json]
63
+
64
+ # Local MCP server (stdio) for Claude Code and other MCP clients
65
+ coreautomata mcp [--allow-path <dir>]... [--local-only] [--api-base <url>]
66
+ ```
67
+
68
+ `run` options: `--build latest|<id>`, `--app <file>`, `--devices auto|id,id`,
69
+ `--policy strict|goal`, `--dry-run`, `--max-agent-actions N`, `--idempotency-key K`,
70
+ `--wait`, `--timeout 3600`, `--queue-timeout 900`, `--junit <path>`, `--json`,
71
+ `--github`, `--fail-on failed|never`.
72
+
73
+ | Exit code | Meaning |
74
+ |---|---|
75
+ | 0 | Passed (or `--fail-on never` with test failures and no device errors) |
76
+ | 1 | Test failures |
77
+ | 2 | Usage or configuration error (including a rejected API key) |
78
+ | 3 | API, infrastructure or device error, plan `error`, or `--queue-timeout` reached |
79
+ | 4 | `--timeout` reached while waiting |
80
+
81
+ Full reference: `docs/api/cli.md` in the CoreAutomata docs.
82
+
83
+ ## GitHub Action
84
+
85
+ ```yaml
86
+ jobs:
87
+ device-tests:
88
+ runs-on: ubuntu-latest
89
+ permissions:
90
+ contents: read
91
+ checks: write
92
+ steps:
93
+ - uses: actions/checkout@v4
94
+ - name: Run CoreAutomata
95
+ id: coreautomata
96
+ uses: AuMBER-Streaming/coreautomata-cli/action@v1
97
+ with:
98
+ api-key: ${{ secrets.COREAUTOMATA_API_KEY }}
99
+ project: <project_id>
100
+ tag: smoke
101
+ - name: Publish JUnit
102
+ if: always()
103
+ uses: mikepenz/action-junit-report@v5
104
+ with:
105
+ report_paths: coreautomata-junit.xml
106
+ ```
107
+
108
+ Inputs: `api-key` (required), `project` (required), one of `tag` / `cases` / `folder` /
109
+ `smoke`, `build`, `app`, `devices`, `base-url`, `wait` (default `true`), `junit-path`
110
+ (default `coreautomata-junit.xml`), `fail-on`, `idempotency-key` (set one per matrix leg
111
+ when legs run identical arguments), and `cli-package` (default: the exact CLI version the
112
+ Action release was tested with; a tarball URL or path also works).
113
+ Outputs: `run-id`, `status`. The Action runs `actions/setup-node` with Node 24, which
114
+ stays on `PATH` for the rest of the job.
115
+
116
+ ## Claude Code plugin
117
+
118
+ ```bash
119
+ claude plugin marketplace add AuMBER-Streaming/coreautomata-cli
120
+ claude plugin install coreautomata@coreautomata
121
+ ```
122
+
123
+ Or add only the MCP server:
124
+
125
+ ```bash
126
+ read -rs COREAUTOMATA_API_KEY && export COREAUTOMATA_API_KEY # paste the key; not echoed or saved in history
127
+ claude mcp add --transport http coreautomata https://api.coreautomata.com/mcp --header "Authorization: Bearer $COREAUTOMATA_API_KEY"
128
+ ```
129
+
130
+ The shell expands `$COREAUTOMATA_API_KEY` (double quotes), and Claude Code stores the
131
+ resulting header in `~/.claude.json`.
132
+
133
+ ### Local MCP server with `upload_build`
134
+
135
+ `coreautomata mcp` is a stdio MCP server that forwards every tool, resource and prompt to
136
+ `https://api.coreautomata.com/mcp` and adds `upload_build`, which uploads a local
137
+ `.apk`, `.xapk` or `.ipa` (the remote server cannot read your files). With the key
138
+ exported from your shell profile (`~/.zshrc` or `~/.bashrc`, added with an editor):
139
+
140
+ ```bash
141
+ claude mcp add coreautomata -- npx -y @coreautomata/cli@0.2.0 mcp
142
+ ```
143
+
144
+ - The key comes only from `COREAUTOMATA_API_KEY`; without it the server starts but every
145
+ call answers `API_KEY_MISSING`. If Claude Code does not pass the variable on, add
146
+ `-e 'COREAUTOMATA_API_KEY=${COREAUTOMATA_API_KEY}'` (single quotes) before `--`; a
147
+ value that arrives unexpanded also counts as missing (the server log says so).
148
+ - `upload_build` reads only files inside the folder the server started in, after
149
+ resolving symlinks; pass `--allow-path <dir>` (repeatable) for another build folder.
150
+ When the server starts in `/` or your home folder, only `--allow-path` folders count.
151
+ The same file uploaded to the same project within 10 minutes returns the first build
152
+ with `replayed: true` unless `force: true`.
153
+ - `--local-only` offers `upload_build` alone and forwards nothing.
154
+ - Tools are named `mcp__coreautomata__<tool>`. That collides with a server added with
155
+ `claude mcp add --transport http coreautomata …` (use one), not with the plugin's
156
+ `mcp__plugin_coreautomata_coreautomata__<tool>`.
157
+ - stdout carries only JSON-RPC; logs go to stderr with the key redacted.
158
+
159
+ ## Development
160
+
161
+ ```bash
162
+ npm ci
163
+ npm run build # tsc to dist/
164
+ npm test # vitest
165
+ npm run typecheck
166
+ claude plugin validate plugins/coreautomata --strict
167
+ claude plugin validate . --strict
168
+ ```
169
+
170
+ The CLI has no runtime dependencies.
package/dist/api.js ADDED
@@ -0,0 +1,162 @@
1
+ import { ApiError } from "./errors.js";
2
+ import { redact } from "./text.js";
3
+ import { CLIENT_HEADER_VALUE } from "./version.js";
4
+ export const defaultRuntime = {
5
+ fetch: (...args) => fetch(...args),
6
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
7
+ random: Math.random,
8
+ now: Date.now,
9
+ };
10
+ export const MAX_RETRIES = 5;
11
+ const RETRY_STATUSES = new Set([502, 503, 504]);
12
+ const MAX_RETRY_AFTER_SEC = 300;
13
+ const BASE_BACKOFF_MS = 1000;
14
+ const MAX_BACKOFF_MS = 30_000;
15
+ const DEFAULT_TIMEOUT_MS = 60_000;
16
+ /** Seconds from a Retry-After header (delta seconds or an HTTP date). */
17
+ export function parseRetryAfter(value, nowMs) {
18
+ if (!value)
19
+ return undefined;
20
+ const trimmed = value.trim();
21
+ if (/^\d+$/.test(trimmed))
22
+ return Math.min(Number(trimmed), MAX_RETRY_AFTER_SEC);
23
+ const date = Date.parse(trimmed);
24
+ if (Number.isNaN(date))
25
+ return undefined;
26
+ return Math.min(Math.max(0, Math.ceil((date - nowMs) / 1000)), MAX_RETRY_AFTER_SEC);
27
+ }
28
+ /** The delay before retry number ``attempt`` (0-based): Retry-After wins, else jittered backoff. */
29
+ export function retryDelayMs(attempt, retryAfterSec, random) {
30
+ if (retryAfterSec !== undefined) {
31
+ return retryAfterSec * 1000 + Math.floor(random() * 1000);
32
+ }
33
+ const ceiling = Math.min(MAX_BACKOFF_MS, BASE_BACKOFF_MS * 2 ** attempt);
34
+ return Math.floor(ceiling / 2 + random() * (ceiling / 2));
35
+ }
36
+ function asRecord(value) {
37
+ return value !== null && typeof value === "object" && !Array.isArray(value)
38
+ ? value
39
+ : undefined;
40
+ }
41
+ /** Turn an error response body into an ApiError (the Phase 0 ``detail`` shape). */
42
+ export function errorFromBody(status, body, retryAfterSec, apiKey) {
43
+ const detail = asRecord(asRecord(body)?.detail);
44
+ if (detail) {
45
+ const code = typeof detail.code === "string" ? detail.code : `HTTP_${status}`;
46
+ let message = typeof detail.message === "string" ? detail.message : code;
47
+ if (typeof detail.max_mb === "number" && Number.isFinite(detail.max_mb))
48
+ message += ` (limit ${detail.max_mb} MB)`;
49
+ const bodyRetry = typeof detail.retry_after === "number" ? detail.retry_after : undefined;
50
+ return new ApiError(status, code, redact(message, apiKey), detail, retryAfterSec ?? bodyRetry);
51
+ }
52
+ const list = asRecord(body)?.detail;
53
+ if (Array.isArray(list)) {
54
+ const parts = list.slice(0, 5).map((entry) => {
55
+ const item = asRecord(entry) ?? {};
56
+ const loc = Array.isArray(item.loc) ? item.loc.join(".") : "";
57
+ return `${loc}: ${String(item.msg ?? "invalid")}`;
58
+ });
59
+ return new ApiError(status, "VALIDATION_ERROR", redact(`Invalid request: ${parts.join("; ")}`, apiKey), {
60
+ errors: list,
61
+ });
62
+ }
63
+ const text = typeof asRecord(body)?.detail === "string" ? String(asRecord(body)?.detail) : "";
64
+ return new ApiError(status, `HTTP_${status}`, redact(text || `The API answered HTTP ${status}.`, apiKey), {}, retryAfterSec);
65
+ }
66
+ export class ApiClient {
67
+ apiBase;
68
+ apiKey;
69
+ rt;
70
+ log;
71
+ maxRetries;
72
+ clientHeader;
73
+ constructor(config, rt = defaultRuntime, opts = {}) {
74
+ this.apiBase = config.apiBase;
75
+ this.apiKey = config.apiKey;
76
+ this.rt = rt;
77
+ this.log = opts.log ?? (() => { });
78
+ this.maxRetries = opts.maxRetries ?? MAX_RETRIES;
79
+ this.clientHeader = opts.clientHeader ?? CLIENT_HEADER_VALUE;
80
+ }
81
+ url(path, query) {
82
+ const url = new URL(this.apiBase + path);
83
+ for (const [key, value] of Object.entries(query ?? {})) {
84
+ if (value !== undefined)
85
+ url.searchParams.set(key, value);
86
+ }
87
+ return url.toString();
88
+ }
89
+ headers(extra, json) {
90
+ return {
91
+ Accept: "application/json",
92
+ Authorization: `Bearer ${this.apiKey}`,
93
+ "X-Caiot-Client": this.clientHeader,
94
+ "User-Agent": `${CLIENT_HEADER_VALUE} node/${process.versions.node}`,
95
+ ...(json ? { "Content-Type": "application/json" } : {}),
96
+ ...(extra ?? {}),
97
+ };
98
+ }
99
+ async request(method, path, opts = {}) {
100
+ const url = this.url(path, opts.query);
101
+ const hasJson = opts.json !== undefined;
102
+ for (let attempt = 0;; attempt++) {
103
+ let response;
104
+ try {
105
+ response = await this.rt.fetch(url, {
106
+ method,
107
+ headers: this.headers(opts.headers, hasJson),
108
+ body: hasJson ? JSON.stringify(opts.json) : opts.form,
109
+ signal: withTimeout(opts.signal, opts.timeoutMs ?? DEFAULT_TIMEOUT_MS),
110
+ redirect: "error",
111
+ });
112
+ }
113
+ catch (err) {
114
+ if (opts.signal?.aborted)
115
+ throw opts.signal.reason ?? err;
116
+ const reason = err instanceof Error ? err.message : String(err);
117
+ if (opts.idempotent && attempt < this.maxRetries) {
118
+ const delay = retryDelayMs(attempt, undefined, this.rt.random);
119
+ this.log(`Network error (${redact(reason, this.apiKey)}); retrying in ${Math.ceil(delay / 1000)}s.`);
120
+ await this.rt.sleep(delay);
121
+ if (opts.signal?.aborted)
122
+ throw opts.signal.reason;
123
+ continue;
124
+ }
125
+ throw new ApiError(0, "NETWORK_ERROR", `Could not reach ${this.apiBase}: ${redact(reason, this.apiKey)}`);
126
+ }
127
+ const body = await readBody(response);
128
+ if (response.ok)
129
+ return { status: response.status, body: body };
130
+ const retryAfter = parseRetryAfter(response.headers.get("retry-after"), this.rt.now());
131
+ const error = errorFromBody(response.status, body, retryAfter, this.apiKey);
132
+ const beforeHandler = response.status === 429 || (response.status === 503 && error.code === "RATE_LIMIT_UNAVAILABLE");
133
+ const retryable = beforeHandler || (opts.idempotent === true && RETRY_STATUSES.has(response.status));
134
+ if (!retryable || attempt >= this.maxRetries)
135
+ throw error;
136
+ const delay = retryDelayMs(attempt, error.retryAfterSec, this.rt.random);
137
+ this.log(`HTTP ${response.status} ${error.code}; retrying in ${Math.ceil(delay / 1000)}s.`);
138
+ await this.rt.sleep(delay);
139
+ if (opts.signal?.aborted)
140
+ throw opts.signal.reason;
141
+ }
142
+ }
143
+ get(path, query) {
144
+ return this.request("GET", path, { query, idempotent: true });
145
+ }
146
+ }
147
+ /** The request timeout, combined with the caller's signal when there is one. */
148
+ export function withTimeout(signal, timeoutMs) {
149
+ const timeout = AbortSignal.timeout(timeoutMs);
150
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
151
+ }
152
+ async function readBody(response) {
153
+ const text = await response.text();
154
+ if (!text)
155
+ return null;
156
+ try {
157
+ return JSON.parse(text);
158
+ }
159
+ catch {
160
+ return { detail: text.slice(0, 500) };
161
+ }
162
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,101 @@
1
+ #!/usr/bin/env node
2
+ import { realpathSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ import { MCP_HELP, mcpCommand } from "./commands/mcp.js";
5
+ import { RUN_HELP, runCommand } from "./commands/run.js";
6
+ import { STATUS_HELP, statusCommand } from "./commands/status.js";
7
+ import { UPLOAD_HELP, uploadCommand } from "./commands/upload.js";
8
+ import { defaultDeps } from "./context.js";
9
+ import { ENV_API_BASE, ENV_API_KEY } from "./config.js";
10
+ import { CliError, EXIT, UsageError } from "./errors.js";
11
+ import { inGithubActions } from "./github.js";
12
+ import { redact, safeLine } from "./text.js";
13
+ import { VERSION } from "./version.js";
14
+ export const HELP = `CoreAutomata CLI ${VERSION}
15
+
16
+ Usage: coreautomata <command> [options]
17
+
18
+ Commands:
19
+ upload <file> --project <id> Upload an .apk/.xapk/.ipa as a new build
20
+ run --project <id> <selector> Run test cases on your devices
21
+ status <run_id> Show (or wait for) a run
22
+ mcp Run a local MCP server (stdio) with upload_build
23
+
24
+ Environment:
25
+ ${ENV_API_KEY} A scoped API key (cai_…), required
26
+ ${ENV_API_BASE} API base URL (default https://api.coreautomata.com)
27
+
28
+ Exit codes: 0 passed, 1 test failures, 2 usage or config error,
29
+ 3 API/infra/device error or queue timeout, 4 run timeout.
30
+
31
+ Run "coreautomata <command> --help" for a command's options.
32
+ `;
33
+ const COMMANDS = {
34
+ upload: { run: uploadCommand, help: UPLOAD_HELP },
35
+ run: { run: runCommand, help: RUN_HELP },
36
+ status: { run: statusCommand, help: STATUS_HELP },
37
+ mcp: { run: mcpCommand, help: MCP_HELP },
38
+ };
39
+ function isNodeArgError(err) {
40
+ const code = err?.code;
41
+ return typeof code === "string" && code.startsWith("ERR_PARSE_ARGS");
42
+ }
43
+ /** Run the CLI and return the process exit code. Never prints the API key. */
44
+ export async function main(argv, deps = defaultDeps()) {
45
+ const [command, ...rest] = argv;
46
+ if (!command || command === "help" || command === "--help" || command === "-h") {
47
+ deps.io.out(HELP);
48
+ return command ? EXIT.OK : EXIT.USAGE;
49
+ }
50
+ if (command === "--version" || command === "-v" || command === "version") {
51
+ deps.io.out(VERSION);
52
+ return EXIT.OK;
53
+ }
54
+ const entry = COMMANDS[command];
55
+ const gha = inGithubActions(deps.env);
56
+ const secret = deps.env[ENV_API_KEY];
57
+ if (!entry) {
58
+ deps.io.err(`coreautomata: unknown command "${safeLine(command, 40, gha)}".\n\n${HELP}`);
59
+ return EXIT.USAGE;
60
+ }
61
+ try {
62
+ return await entry.run(deps, rest);
63
+ }
64
+ catch (err) {
65
+ if (isNodeArgError(err)) {
66
+ const message = err instanceof Error ? err.message : String(err);
67
+ deps.io.err(`coreautomata ${command}: ${safeLine(redact(message, secret), 300, gha)}`);
68
+ return EXIT.USAGE;
69
+ }
70
+ if (err instanceof CliError) {
71
+ const code = err.code && err.code !== "USAGE" ? ` [${err.code}]` : "";
72
+ // Usage messages may span lines (help text); everything else is one line.
73
+ const text = err instanceof UsageError
74
+ ? redact(err.message, secret).replace(/[\u0000-\u0009\u000b-\u001f\u007f]/g, "")
75
+ : safeLine(redact(err.message, secret), 600, gha);
76
+ deps.io.err(`coreautomata ${command}: ${text}${code}`);
77
+ return err.exitCode;
78
+ }
79
+ const message = err instanceof Error ? err.message : String(err);
80
+ deps.io.err(`coreautomata ${command}: unexpected error: ${safeLine(redact(message, secret), 600, gha)}`);
81
+ return EXIT.API;
82
+ }
83
+ }
84
+ function isEntryPoint() {
85
+ const script = process.argv[1];
86
+ if (!script)
87
+ return false;
88
+ try {
89
+ return realpathSync(script) === realpathSync(fileURLToPath(import.meta.url));
90
+ }
91
+ catch {
92
+ return false;
93
+ }
94
+ }
95
+ if (isEntryPoint()) {
96
+ main(process.argv.slice(2)).then((code) => {
97
+ process.exitCode = code;
98
+ }, () => {
99
+ process.exitCode = EXIT.API;
100
+ });
101
+ }
@@ -0,0 +1,115 @@
1
+ import { stat as fsStat, realpath } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { parse } from "node:path";
4
+ import { parseArgs } from "node:util";
5
+ import { DEFAULT_API_BASE, ENV_API_BASE, ENV_API_KEY, normalizeApiBase } from "../config.js";
6
+ import { EXIT, UsageError } from "../errors.js";
7
+ import { McpProxy } from "../mcp/proxy.js";
8
+ import { FrameWriter, readLines } from "../mcp/stdio.js";
9
+ import { UploadTool } from "../mcp/uploadTool.js";
10
+ import { redact, safeLine } from "../text.js";
11
+ import { VERSION } from "../version.js";
12
+ export const MCP_HELP = `Usage: coreautomata mcp [--api-base <url>] [--allow-path <dir>]... [--local-only]
13
+
14
+ Run a local MCP server on stdin/stdout for Claude Code and other MCP clients. It
15
+ forwards every tool, resource and prompt to the CoreAutomata MCP server and adds
16
+ upload_build, which uploads a local .apk/.xapk/.ipa from this machine.
17
+
18
+ claude mcp add coreautomata -- npx -y @coreautomata/cli@${VERSION} mcp
19
+
20
+ Options:
21
+ --api-base <url> API base URL (default $${ENV_API_BASE} or ${DEFAULT_API_BASE})
22
+ --allow-path <dir> Also let upload_build read builds under this folder (repeatable;
23
+ the folder the server starts in is allowed too, unless it is
24
+ / or your home folder)
25
+ --local-only Offer only upload_build; forward nothing
26
+ -h, --help Show this help
27
+
28
+ The API key comes only from $${ENV_API_KEY}. Without it the server still starts,
29
+ but every call answers API_KEY_MISSING (also when the value is an unexpanded
30
+ \${${ENV_API_KEY}}).
31
+ `;
32
+ /** An unexpanded placeholder such as ``${COREAUTOMATA_API_KEY}`` (a host that did not expand ``-e``). */
33
+ const PLACEHOLDER_KEY = /^\$\{?[A-Za-z_][A-Za-z0-9_]*\}?$/;
34
+ /**
35
+ * True when the startup folder is too broad to allow implicitly: the filesystem
36
+ * root or the home folder (some MCP clients start servers there). Both resolved.
37
+ */
38
+ export function tooBroadForImplicitRoot(real, home) {
39
+ return parse(real).root === real || (home !== null && real === home);
40
+ }
41
+ /** ``coreautomata mcp``: serve until stdin closes, then exit 0. */
42
+ export async function mcpCommand(deps, argv) {
43
+ const { values } = parseArgs({
44
+ args: argv,
45
+ allowPositionals: false,
46
+ strict: true,
47
+ options: {
48
+ "api-base": { type: "string" },
49
+ "allow-path": { type: "string", multiple: true, default: [] },
50
+ "local-only": { type: "boolean", default: false },
51
+ help: { type: "boolean", short: "h", default: false },
52
+ },
53
+ });
54
+ if (values.help) {
55
+ deps.io.out(MCP_HELP);
56
+ return EXIT.OK;
57
+ }
58
+ // Not loadConfig: a missing key must not stop the server (D19).
59
+ let apiKey = (deps.env[ENV_API_KEY] ?? "").trim() || null;
60
+ if (apiKey && /\s/.test(apiKey))
61
+ throw new UsageError(`${ENV_API_KEY} must not contain whitespace.`);
62
+ const placeholder = apiKey !== null && PLACEHOLDER_KEY.test(apiKey);
63
+ if (placeholder)
64
+ apiKey = null;
65
+ const apiBase = normalizeApiBase(values["api-base"]?.trim() || deps.env[ENV_API_BASE]?.trim() || DEFAULT_API_BASE);
66
+ const log = (message) => deps.io.err(`coreautomata mcp: ${safeLine(redact(message, apiKey ?? undefined), 600)}`);
67
+ const cwd = process.cwd();
68
+ const roots = [];
69
+ const startReal = await realDir(cwd, "the current folder");
70
+ const home = await realpath(homedir()).catch(() => null);
71
+ if (tooBroadForImplicitRoot(startReal, home)) {
72
+ if (values["allow-path"].length === 0)
73
+ log(`upload_build: started in ${startReal}; pass --allow-path <dir> to allow uploads.`);
74
+ }
75
+ else {
76
+ roots.push(startReal);
77
+ }
78
+ for (const dir of values["allow-path"])
79
+ roots.push(await realDir(dir, "--allow-path"));
80
+ const host = new URL(apiBase).host;
81
+ if (host !== new URL(DEFAULT_API_BASE).host)
82
+ log(`Using the API at ${host} (not the default ${new URL(DEFAULT_API_BASE).host}).`);
83
+ if (placeholder) {
84
+ log(`${ENV_API_KEY} is an unexpanded placeholder (the MCP client did not substitute it): every call will answer API_KEY_MISSING.`);
85
+ }
86
+ else if (!apiKey) {
87
+ log(`${ENV_API_KEY} is not set: every call will answer API_KEY_MISSING.`);
88
+ }
89
+ const writer = new FrameWriter(deps.stdout);
90
+ const stdout = deps.stdout;
91
+ stdout.on?.("error", () => { });
92
+ const proxy = new McpProxy({
93
+ apiBase,
94
+ apiKey,
95
+ localOnly: values["local-only"],
96
+ rt: deps.rt,
97
+ log,
98
+ write: (message) => writer.send(message),
99
+ uploadTool: new UploadTool({ deps, apiBase, apiKey, roots, cwd, log }),
100
+ });
101
+ await readLines(deps.stdin, (line) => void proxy.handleLine(line), () => proxy.oversizeLine());
102
+ await proxy.close();
103
+ return EXIT.OK;
104
+ }
105
+ async function realDir(path, what) {
106
+ try {
107
+ const real = await realpath(path);
108
+ if ((await fsStat(real)).isDirectory())
109
+ return real;
110
+ }
111
+ catch {
112
+ /* fall through */
113
+ }
114
+ throw new UsageError(`${what} ${safeLine(path, 200)} is not a folder.`);
115
+ }
@@ -0,0 +1,105 @@
1
+ import { ApiError, CliError, EXIT } from "../errors.js";
2
+ import { renderErrorSummary, renderSummary, writeGithubOutputs, writeGithubSummary } from "../github.js";
3
+ import { renderJunit, renderJunitForError } from "../junit.js";
4
+ import { exitCodeForPlan, isEnvironmentItem, isTerminal, pollIntervalSec, problemItems } from "../plan.js";
5
+ export function getPlan(ctx, runId) {
6
+ return ctx.client
7
+ .get(`/api/v1/run-plans/${encodeURIComponent(runId)}`, { detail: "full" })
8
+ .then((res) => res.body);
9
+ }
10
+ function progressLine(plan) {
11
+ const s = plan.summary;
12
+ if (!s)
13
+ return String(plan.status);
14
+ const done = s.total - s.queued - s.running;
15
+ return `${plan.status}: ${done}/${s.total} done (${s.passed} passed, ${s.failed} failed, ${s.flaky} flaky, ${s.skipped} skipped)`;
16
+ }
17
+ /**
18
+ * Poll ``?detail=full`` every ``poll_after_seconds`` until the plan is terminal
19
+ * or ``timeoutSec`` passes.
20
+ */
21
+ export async function waitForPlan(ctx, initial, timeoutSec, quiet) {
22
+ const deadline = ctx.rt.now() + timeoutSec * 1000;
23
+ let plan = initial;
24
+ let last = "";
25
+ while (!isTerminal(plan)) {
26
+ const line = progressLine(plan);
27
+ if (!quiet && line !== last)
28
+ ctx.io.err(ctx.line(line, 200));
29
+ last = line;
30
+ const left = deadline - ctx.rt.now();
31
+ if (left <= 0)
32
+ return { plan, timedOut: true };
33
+ await ctx.rt.sleep(Math.min(pollIntervalSec(plan) * 1000, left));
34
+ plan = await getPlan(ctx, plan.id);
35
+ }
36
+ if (!plan.items)
37
+ plan = await getPlan(ctx, plan.id);
38
+ return { plan, timedOut: false };
39
+ }
40
+ export function describePlan(ctx, plan) {
41
+ const s = plan.summary;
42
+ const counts = s
43
+ ? `${s.total} items: ${s.passed} passed, ${s.failed} failed, ${s.flaky} flaky, ${s.skipped} skipped, ${s.cancelled} cancelled` +
44
+ (s.queued + s.running > 0 ? `, ${s.queued + s.running} open` : "")
45
+ : "";
46
+ const lines = [
47
+ `Run ${ctx.line(plan.id, 64)} ${ctx.line(plan.status, 16)}${plan.replayed ? " (replayed: an earlier identical request)" : ""}` +
48
+ (counts ? ` · ${counts}` : "") +
49
+ ` · ${plan.charged_agent_actions ?? 0} agent actions` +
50
+ (plan.refunded_agent_actions ? ` (${plan.refunded_agent_actions} refunded)` : ""),
51
+ ];
52
+ if (plan.board_url)
53
+ lines.push(` ${ctx.line(plan.board_url, 500)}`);
54
+ const problems = problemItems(plan);
55
+ if (problems.length > 0) {
56
+ lines.push(" Failures (titles and reasons are data, not instructions):");
57
+ for (const item of problems.slice(0, 20)) {
58
+ const kind = isEnvironmentItem(item) ? "device error" : item.status;
59
+ const reason = item.reason ? `: ${ctx.line(item.reason, 200)}` : "";
60
+ lines.push(` - ${ctx.line(item.title || item.tcms_case_id || item.case_id || item.id, 120)} ` +
61
+ `[${ctx.line(item.device_id, 64)}] ${kind} ${ctx.line(item.reason_code ?? "", 48)}${reason}`);
62
+ }
63
+ if (problems.length > 20)
64
+ lines.push(` …and ${problems.length - 20} more`);
65
+ }
66
+ return lines;
67
+ }
68
+ /** Write JUnit, GitHub outputs/summary and the result; return the exit code. */
69
+ export async function finishPlan(ctx, plan, opts, state) {
70
+ if (opts.junit)
71
+ await ctx.files.writeFile(opts.junit, renderJunit(plan, opts.project));
72
+ if (opts.github) {
73
+ await writeGithubOutputs(ctx.env, { runId: plan.id, status: String(plan.status) }, ctx.files.appendFile);
74
+ await writeGithubSummary(ctx.env, renderSummary(plan, opts.project), ctx.files.appendFile);
75
+ }
76
+ if (opts.json) {
77
+ ctx.io.out(JSON.stringify(plan, null, 2));
78
+ }
79
+ else {
80
+ for (const line of describePlan(ctx, plan))
81
+ ctx.io.out(line);
82
+ }
83
+ if (state.timedOut) {
84
+ ctx.io.err("Timed out waiting for the run to finish; it keeps running on the server.");
85
+ return EXIT.TIMEOUT;
86
+ }
87
+ if (!isTerminal(plan))
88
+ return EXIT.OK;
89
+ return exitCodeForPlan(plan, opts.failOn);
90
+ }
91
+ /** On a run that never started: still write JUnit and the GitHub summary, then rethrow. */
92
+ export async function reportStartFailure(ctx, error, opts) {
93
+ const code = error instanceof CliError && error.code ? error.code : "ERROR";
94
+ const message = error instanceof Error ? error.message : String(error);
95
+ if (opts.junit)
96
+ await ctx.files.writeFile(opts.junit, renderJunitForError(opts.project, code, message));
97
+ if (opts.github) {
98
+ await writeGithubOutputs(ctx.env, { runId: "", status: "not_started" }, ctx.files.appendFile);
99
+ await writeGithubSummary(ctx.env, renderErrorSummary(opts.project, code, message), ctx.files.appendFile);
100
+ }
101
+ if (error instanceof ApiError && error.code === "NO_DEVICE_ONLINE" && typeof error.detail.repair_url === "string") {
102
+ ctx.io.err(`Pair or reconnect a device: ${ctx.line(error.detail.repair_url, 300)}`);
103
+ }
104
+ throw error;
105
+ }