@coreautomata/cli 0.1.0 → 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.
@@ -0,0 +1,347 @@
1
+ /**
2
+ * The remote side of ``coreautomata mcp``: one HTTP POST to ``${apiBase}/mcp`` per
3
+ * JSON-RPC message (the server is stateless, handshake era ``2025-11-25``). Replies
4
+ * are ``application/json`` or an SSE stream; notifications in the stream are passed
5
+ * on as they arrive, and the stream ends at the response whose ``id`` matches.
6
+ */
7
+ import { errorFromBody, MAX_RETRIES, parseRetryAfter, retryDelayMs } from "../api.js";
8
+ import { ApiError } from "../errors.js";
9
+ import { redact } from "../text.js";
10
+ import { CLIENT_HEADER_VALUE, MCP_CLIENT_HEADER_VALUE } from "../version.js";
11
+ import { isJsonRpcId, isRecord, isResponse } from "./stdio.js";
12
+ export const UPSTREAM_PROTOCOL_VERSION = "2025-11-25";
13
+ /** Cap on everything read for one request. */
14
+ export const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
15
+ /** Cap on one SSE line (or a JSON body's single line). */
16
+ export const MAX_LINE_CHARS = 1024 * 1024;
17
+ export const IDLE_TIMEOUT_MS = 90_000;
18
+ export const OVERALL_TIMEOUT_MS = 15 * 60_000;
19
+ const RETRY_STATUSES = new Set([502, 503, 504]);
20
+ /** Server notifications written to the host as they arrive; others are dropped. */
21
+ export const FORWARDED_NOTIFICATIONS = new Set(["notifications/progress", "notifications/message"]);
22
+ /** The host cancelled the request (``notifications/cancelled``) or the proxy is shutting down. */
23
+ export class RequestCancelled extends Error {
24
+ constructor() {
25
+ super("cancelled");
26
+ this.name = "RequestCancelled";
27
+ }
28
+ }
29
+ class ReadFailure extends Error {
30
+ code;
31
+ constructor(code, message) {
32
+ super(message);
33
+ this.code = code;
34
+ }
35
+ }
36
+ /** Sleep that ends early (rejecting) when ``signal`` aborts. */
37
+ export function abortableSleep(rt, ms, signal) {
38
+ if (!signal)
39
+ return rt.sleep(ms);
40
+ if (signal.aborted)
41
+ return Promise.reject(new RequestCancelled());
42
+ return new Promise((resolve, reject) => {
43
+ const onAbort = () => reject(new RequestCancelled());
44
+ signal.addEventListener("abort", onAbort, { once: true });
45
+ rt.sleep(ms).then(() => {
46
+ signal.removeEventListener("abort", onAbort);
47
+ resolve();
48
+ }, (err) => {
49
+ signal.removeEventListener("abort", onAbort);
50
+ reject(err);
51
+ });
52
+ });
53
+ }
54
+ export class Upstream {
55
+ url;
56
+ cfg;
57
+ constructor(cfg) {
58
+ this.cfg = cfg;
59
+ this.url = `${cfg.apiBase}/mcp`;
60
+ }
61
+ headers() {
62
+ return {
63
+ Authorization: `Bearer ${this.cfg.apiKey}`,
64
+ "mcp-protocol-version": UPSTREAM_PROTOCOL_VERSION,
65
+ Accept: "application/json, text/event-stream",
66
+ "Content-Type": "application/json",
67
+ "X-Caiot-Client": MCP_CLIENT_HEADER_VALUE,
68
+ "User-Agent": `${CLIENT_HEADER_VALUE} node/${process.versions.node}`,
69
+ };
70
+ }
71
+ redact(text) {
72
+ return redact(text, this.cfg.apiKey);
73
+ }
74
+ /**
75
+ * POST one message. For a request, resolves with the upstream response (same ``id``);
76
+ * for a notification (no ``id``), resolves with null once the server accepts it.
77
+ * Throws ``ApiError`` for HTTP and transport failures, ``RequestCancelled`` when
78
+ * ``opts.signal`` aborts.
79
+ */
80
+ async post(message, opts) {
81
+ const { rt } = this.cfg;
82
+ const maxRetries = opts.maxRetries ?? this.cfg.maxRetries ?? MAX_RETRIES;
83
+ const overallMs = opts.timeoutMs ?? this.cfg.overallMs ?? OVERALL_TIMEOUT_MS;
84
+ const idleMs = this.cfg.idleMs ?? IDLE_TIMEOUT_MS;
85
+ const overall = AbortSignal.timeout(overallMs);
86
+ const expectId = isJsonRpcId(message.id) ? message.id : undefined;
87
+ const body = JSON.stringify(message);
88
+ const cancelled = () => opts.signal?.aborted === true;
89
+ const giveUp = (code, text) => new ApiError(0, code, this.redact(text));
90
+ const retryWait = async (attempt, retryAfter, what) => {
91
+ const delay = retryDelayMs(attempt, retryAfter, rt.random);
92
+ this.cfg.log(`${what}; retrying in ${Math.ceil(delay / 1000)}s.`);
93
+ const signals = [overall, ...(opts.signal ? [opts.signal] : [])];
94
+ try {
95
+ await abortableSleep(rt, delay, AbortSignal.any(signals));
96
+ }
97
+ catch (err) {
98
+ if (cancelled())
99
+ throw new RequestCancelled();
100
+ if (overall.aborted)
101
+ throw giveUp("UPSTREAM_TIMEOUT", `No answer from ${this.url} within ${overallMs / 1000}s.`);
102
+ throw err;
103
+ }
104
+ };
105
+ for (let attempt = 0;; attempt++) {
106
+ const idle = new AbortController();
107
+ let idleTimer;
108
+ const touch = () => {
109
+ if (idleTimer)
110
+ clearTimeout(idleTimer);
111
+ idleTimer = setTimeout(() => idle.abort(), idleMs);
112
+ idleTimer.unref?.();
113
+ };
114
+ const signals = [overall, idle.signal, ...(opts.signal ? [opts.signal] : [])];
115
+ const signal = AbortSignal.any(signals);
116
+ touch();
117
+ const transportError = (err) => {
118
+ if (cancelled())
119
+ return new RequestCancelled();
120
+ if (overall.aborted)
121
+ return giveUp("UPSTREAM_TIMEOUT", `No answer from ${this.url} within ${overallMs / 1000}s.`);
122
+ if (idle.signal.aborted)
123
+ return giveUp("UPSTREAM_TIMEOUT", `${this.url} sent nothing for ${idleMs / 1000}s.`);
124
+ const reason = err instanceof Error ? err.message : String(err);
125
+ return giveUp("NETWORK_ERROR", `Could not reach ${this.url}: ${reason}`);
126
+ };
127
+ try {
128
+ let response;
129
+ try {
130
+ response = await rt.fetch(this.url, { method: "POST", headers: this.headers(), body, signal, redirect: "error" });
131
+ }
132
+ catch (err) {
133
+ const failure = transportError(err);
134
+ // Network errors and idle timeouts are retried for idempotent requests; never
135
+ // a cancellation or the overall deadline.
136
+ if (failure instanceof ApiError && !overall.aborted && opts.idempotent && attempt < maxRetries) {
137
+ await retryWait(attempt, undefined, `Network error (${failure.message})`);
138
+ continue;
139
+ }
140
+ throw failure;
141
+ }
142
+ if (!response.ok) {
143
+ let text = "";
144
+ try {
145
+ text = await readCapped(response, signal, touch);
146
+ }
147
+ catch {
148
+ /* keep the status alone */
149
+ }
150
+ let parsed = null;
151
+ try {
152
+ parsed = text ? JSON.parse(text) : null;
153
+ }
154
+ catch {
155
+ parsed = { detail: text.slice(0, 500) };
156
+ }
157
+ const retryAfter = parseRetryAfter(response.headers.get("retry-after"), rt.now());
158
+ const error = errorFromBody(response.status, parsed, retryAfter, this.cfg.apiKey);
159
+ const beforeHandler = response.status === 429 || (response.status === 503 && error.code === "RATE_LIMIT_UNAVAILABLE");
160
+ const retryable = beforeHandler || (opts.idempotent && RETRY_STATUSES.has(response.status));
161
+ if (!retryable || attempt >= maxRetries)
162
+ throw error;
163
+ await retryWait(attempt, error.retryAfterSec, `HTTP ${response.status} ${error.code}`);
164
+ continue;
165
+ }
166
+ if (expectId === undefined) {
167
+ // A notification: 202 Accepted, body ignored.
168
+ await response.body?.cancel().catch(() => { });
169
+ return null;
170
+ }
171
+ const type = (response.headers.get("content-type") ?? "").toLowerCase();
172
+ try {
173
+ if (type.includes("text/event-stream")) {
174
+ return await this.readSse(response, expectId, signal, touch, opts.onNotification);
175
+ }
176
+ return this.pickResponse(await readCapped(response, signal, touch), expectId);
177
+ }
178
+ catch (err) {
179
+ if (err instanceof ReadFailure) {
180
+ if (signal.aborted)
181
+ throw transportError(err);
182
+ if (err.code === "UPSTREAM_CLOSED" && opts.idempotent && attempt < maxRetries) {
183
+ await retryWait(attempt, undefined, err.message);
184
+ continue;
185
+ }
186
+ throw giveUp(err.code, err.message);
187
+ }
188
+ throw transportError(err);
189
+ }
190
+ }
191
+ finally {
192
+ if (idleTimer)
193
+ clearTimeout(idleTimer);
194
+ }
195
+ }
196
+ }
197
+ pickResponse(text, id) {
198
+ let parsed;
199
+ try {
200
+ parsed = JSON.parse(text);
201
+ }
202
+ catch {
203
+ throw new ReadFailure("UPSTREAM_BAD_REPLY", `${this.url} answered with something that is not JSON.`);
204
+ }
205
+ for (const candidate of Array.isArray(parsed) ? parsed : [parsed]) {
206
+ if (isRecord(candidate) && isResponse(candidate) && candidate.id === id)
207
+ return candidate;
208
+ }
209
+ throw new ReadFailure("UPSTREAM_BAD_REPLY", `${this.url} answered without a response for this request.`);
210
+ }
211
+ async readSse(response, id, signal, touch, onNotification) {
212
+ const reader = response.body?.getReader();
213
+ if (!reader)
214
+ throw new ReadFailure("UPSTREAM_CLOSED", `${this.url} closed the stream without a response.`);
215
+ const onAbort = () => void reader.cancel().catch(() => { });
216
+ signal.addEventListener("abort", onAbort, { once: true });
217
+ const decoder = new TextDecoder();
218
+ let total = 0;
219
+ let pending = "";
220
+ let data = [];
221
+ let found;
222
+ const dispatch = () => {
223
+ if (data.length === 0)
224
+ return;
225
+ const text = data.join("\n");
226
+ data = [];
227
+ let message;
228
+ try {
229
+ message = JSON.parse(text);
230
+ }
231
+ catch {
232
+ this.cfg.log("Ignored an SSE event that is not JSON.");
233
+ return;
234
+ }
235
+ if (!isRecord(message))
236
+ return;
237
+ if (isResponse(message)) {
238
+ if (message.id === id)
239
+ found = message;
240
+ else
241
+ this.cfg.log("Ignored an upstream response for another request.");
242
+ return;
243
+ }
244
+ if (typeof message.method !== "string")
245
+ return;
246
+ if ("id" in message) {
247
+ // A server-to-client request: never answered, never passed to the host.
248
+ this.cfg.log(`Dropped an upstream request (${safeMethod(message.method)}); this proxy does not answer server requests.`);
249
+ return;
250
+ }
251
+ if (FORWARDED_NOTIFICATIONS.has(message.method))
252
+ onNotification?.(message);
253
+ else
254
+ this.cfg.log(`Dropped an upstream notification (${safeMethod(message.method)}).`);
255
+ };
256
+ const line = (raw) => {
257
+ const text = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
258
+ if (text.length > MAX_LINE_CHARS)
259
+ throw new ReadFailure("UPSTREAM_TOO_LARGE", "An upstream line is longer than 1 MB.");
260
+ if (text === "")
261
+ return dispatch();
262
+ if (text.startsWith(":"))
263
+ return;
264
+ const colon = text.indexOf(":");
265
+ const field = colon < 0 ? text : text.slice(0, colon);
266
+ if (field !== "data")
267
+ return;
268
+ let value = colon < 0 ? "" : text.slice(colon + 1);
269
+ if (value.startsWith(" "))
270
+ value = value.slice(1);
271
+ data.push(value);
272
+ };
273
+ try {
274
+ for (;;) {
275
+ const { done, value } = await reader.read();
276
+ if (done)
277
+ break;
278
+ touch();
279
+ total += value.byteLength;
280
+ if (total > MAX_RESPONSE_BYTES)
281
+ throw new ReadFailure("UPSTREAM_TOO_LARGE", "The upstream reply is larger than 8 MB.");
282
+ pending += decoder.decode(value, { stream: true });
283
+ let start = 0;
284
+ for (;;) {
285
+ const nl = pending.indexOf("\n", start);
286
+ if (nl < 0)
287
+ break;
288
+ line(pending.slice(start, nl));
289
+ start = nl + 1;
290
+ if (found)
291
+ break;
292
+ }
293
+ pending = pending.slice(start);
294
+ if (found)
295
+ break;
296
+ if (pending.length > MAX_LINE_CHARS)
297
+ throw new ReadFailure("UPSTREAM_TOO_LARGE", "An upstream line is longer than 1 MB.");
298
+ }
299
+ if (!found) {
300
+ pending += decoder.decode();
301
+ if (pending)
302
+ line(pending);
303
+ dispatch();
304
+ }
305
+ }
306
+ finally {
307
+ signal.removeEventListener("abort", onAbort);
308
+ reader.cancel().catch(() => { });
309
+ }
310
+ if (found)
311
+ return found;
312
+ throw new ReadFailure("UPSTREAM_CLOSED", `${this.url} closed the stream without a response.`);
313
+ }
314
+ }
315
+ function safeMethod(method) {
316
+ return method.replace(/[^A-Za-z0-9/_.-]/g, "").slice(0, 64);
317
+ }
318
+ /** The body as text, at most ``MAX_RESPONSE_BYTES``. */
319
+ async function readCapped(response, signal, touch) {
320
+ const reader = response.body?.getReader();
321
+ if (!reader)
322
+ return "";
323
+ const onAbort = () => void reader.cancel().catch(() => { });
324
+ signal.addEventListener("abort", onAbort, { once: true });
325
+ const decoder = new TextDecoder();
326
+ let total = 0;
327
+ let text = "";
328
+ try {
329
+ for (;;) {
330
+ const { done, value } = await reader.read();
331
+ if (done)
332
+ break;
333
+ touch();
334
+ total += value.byteLength;
335
+ if (total > MAX_RESPONSE_BYTES)
336
+ throw new ReadFailure("UPSTREAM_TOO_LARGE", "The upstream reply is larger than 8 MB.");
337
+ text += decoder.decode(value, { stream: true });
338
+ }
339
+ text += decoder.decode();
340
+ }
341
+ finally {
342
+ signal.removeEventListener("abort", onAbort);
343
+ }
344
+ if (signal.aborted)
345
+ throw new ReadFailure("UPSTREAM_CLOSED", "aborted");
346
+ return text;
347
+ }
package/dist/plan.js CHANGED
@@ -10,7 +10,9 @@ export const ENVIRONMENT_CODES = new Set([
10
10
  "interrupted",
11
11
  "start_failed",
12
12
  "install_failed",
13
+ "device_minutes_exhausted",
13
14
  "NO_DEVICE_ONLINE",
15
+ "DEVICE_MINUTES_EXCEEDED",
14
16
  ]);
15
17
  export function isTerminal(plan) {
16
18
  return TERMINAL_PLAN_STATUSES.has(String(plan.status));
package/dist/version.js CHANGED
@@ -1,4 +1,6 @@
1
- /** Kept in step with package.json "version" (test/version.test.ts checks it). */
2
- export const VERSION = "0.1.0";
1
+ /** Kept in step with package.json "version" (test/packaging.test.ts checks it). */
2
+ export const VERSION = "0.2.0";
3
3
  /** Sent as X-Caiot-Client so the server records the CLI channel and client name. */
4
4
  export const CLIENT_HEADER_VALUE = `coreautomata-cli/${VERSION}`;
5
+ /** X-Caiot-Client for requests made by `coreautomata mcp` (the stdio proxy and its upload_build tool). */
6
+ export const MCP_CLIENT_HEADER_VALUE = `${CLIENT_HEADER_VALUE} mcp`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coreautomata/cli",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "CoreAutomata command line: upload Android and iOS builds, run test cases on real devices, and gate CI on the result.",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -12,7 +12,7 @@
12
12
  "dist"
13
13
  ],
14
14
  "engines": {
15
- "node": ">=20"
15
+ "node": ">=20.3"
16
16
  },
17
17
  "publishConfig": {
18
18
  "access": "public"