@testsprite/testsprite-cli 0.2.0 → 0.4.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.
Files changed (68) hide show
  1. package/README.md +35 -26
  2. package/dist/commands/agent.d.ts +43 -0
  3. package/dist/commands/agent.js +200 -18
  4. package/dist/commands/auth.d.ts +5 -0
  5. package/dist/commands/auth.js +38 -27
  6. package/dist/commands/doctor.d.ts +49 -0
  7. package/dist/commands/doctor.js +233 -0
  8. package/dist/commands/init.d.ts +1 -1
  9. package/dist/commands/init.js +24 -14
  10. package/dist/commands/project.d.ts +75 -2
  11. package/dist/commands/project.js +326 -47
  12. package/dist/commands/test.d.ts +281 -2
  13. package/dist/commands/test.js +1658 -177
  14. package/dist/commands/usage.js +13 -12
  15. package/dist/index.js +71 -3
  16. package/dist/lib/agent-targets.d.ts +72 -6
  17. package/dist/lib/agent-targets.js +188 -6
  18. package/dist/lib/bundle.d.ts +34 -0
  19. package/dist/lib/bundle.js +63 -11
  20. package/dist/lib/client-factory.d.ts +31 -0
  21. package/dist/lib/client-factory.js +63 -0
  22. package/dist/lib/config.d.ts +2 -0
  23. package/dist/lib/config.js +11 -2
  24. package/dist/lib/credentials.js +10 -1
  25. package/dist/lib/dry-run/samples.d.ts +5 -0
  26. package/dist/lib/dry-run/samples.js +64 -0
  27. package/dist/lib/errors.d.ts +28 -1
  28. package/dist/lib/errors.js +40 -0
  29. package/dist/lib/failing-fe-resolver.d.ts +15 -0
  30. package/dist/lib/failing-fe-resolver.js +49 -1
  31. package/dist/lib/flaky.d.ts +80 -0
  32. package/dist/lib/flaky.js +76 -0
  33. package/dist/lib/http.d.ts +73 -1
  34. package/dist/lib/http.js +327 -135
  35. package/dist/lib/interrupt.d.ts +116 -0
  36. package/dist/lib/interrupt.js +182 -0
  37. package/dist/lib/junit-report.d.ts +58 -0
  38. package/dist/lib/junit-report.js +210 -0
  39. package/dist/lib/output.d.ts +16 -1
  40. package/dist/lib/output.js +24 -2
  41. package/dist/lib/pagination.d.ts +4 -3
  42. package/dist/lib/pagination.js +34 -6
  43. package/dist/lib/poll.d.ts +11 -0
  44. package/dist/lib/poll.js +70 -5
  45. package/dist/lib/prompt.js +52 -8
  46. package/dist/lib/proxy.d.ts +29 -0
  47. package/dist/lib/proxy.js +30 -0
  48. package/dist/lib/render-error.js +3 -1
  49. package/dist/lib/runs.types.d.ts +9 -0
  50. package/dist/lib/skill-nudge.d.ts +2 -2
  51. package/dist/lib/skill-nudge.js +13 -4
  52. package/dist/lib/target-url.js +8 -1
  53. package/dist/lib/ticker.d.ts +11 -1
  54. package/dist/lib/ticker.js +33 -1
  55. package/dist/lib/update-check.d.ts +67 -0
  56. package/dist/lib/update-check.js +246 -0
  57. package/dist/lib/v3-advisory.d.ts +13 -0
  58. package/dist/lib/v3-advisory.js +24 -0
  59. package/dist/lib/version-notice.d.ts +37 -0
  60. package/dist/lib/version-notice.js +87 -0
  61. package/dist/version-guard.d.ts +33 -0
  62. package/dist/version-guard.js +39 -0
  63. package/dist/version.d.ts +1 -1
  64. package/dist/version.js +1 -1
  65. package/package.json +3 -2
  66. package/skills/testsprite-onboard.skill.md +21 -0
  67. package/skills/testsprite-verify.codex.md +6 -0
  68. package/skills/testsprite-verify.skill.md +48 -4
@@ -1,13 +1,14 @@
1
- import { localValidationError } from './errors.js';
1
+ import { ApiError, localValidationError } from './errors.js';
2
2
  const HARD_PAGE_SIZE_CAP = 100;
3
3
  const DEFAULT_PAGE_SIZE = 25;
4
+ export const MAX_AUTO_PAGES = 1000;
4
5
  /**
5
6
  * Validates and normalizes pagination flags. Per the CLI OpenAPI spec
6
7
  * §components.parameters.PageSize the hard cap is 100. Values above the
7
8
  * cap are now rejected with exit 5 rather than silently clamped, giving
8
- * callers fast feedback that their flag value is out of range. Sub-1 /
9
- * NaN values also throw. `maxItems` is validated but not capped (it is a
10
- * client-side cursor, not a server parameter).
9
+ * callers fast feedback that their flag value is out of range. Fractional,
10
+ * sub-1, and NaN values also throw. `maxItems` is validated but not capped
11
+ * (it is a client-side cursor, not a server parameter).
11
12
  *
12
13
  * NOTE: `runResultHistory` previously did its own silent clamp via
13
14
  * `Math.min(Math.max(1, n), 100)` — that was unified to this path by the
@@ -16,7 +17,7 @@ const DEFAULT_PAGE_SIZE = 25;
16
17
  export function validatePaginationFlags(flags) {
17
18
  const out = { ...flags };
18
19
  if (out.pageSize !== undefined) {
19
- if (!Number.isFinite(out.pageSize) || out.pageSize < 1) {
20
+ if (!Number.isFinite(out.pageSize) || !Number.isInteger(out.pageSize) || out.pageSize < 1) {
20
21
  throw localValidationError('page-size', `must be a positive integer between 1 and ${HARD_PAGE_SIZE_CAP}`);
21
22
  }
22
23
  if (out.pageSize > HARD_PAGE_SIZE_CAP) {
@@ -24,7 +25,7 @@ export function validatePaginationFlags(flags) {
24
25
  }
25
26
  }
26
27
  if (out.maxItems !== undefined) {
27
- if (!Number.isFinite(out.maxItems) || out.maxItems < 1) {
28
+ if (!Number.isFinite(out.maxItems) || !Number.isInteger(out.maxItems) || out.maxItems < 1) {
28
29
  throw localValidationError('maxItems', 'must be a positive integer');
29
30
  }
30
31
  }
@@ -50,12 +51,23 @@ export async function paginate(fetchPage, flags = {}) {
50
51
  const items = [];
51
52
  let cursor = flags.startingToken;
52
53
  let lastNextToken = null;
54
+ let pagesFetched = 0;
55
+ const seenNextTokens = new Set();
56
+ if (cursor !== undefined)
57
+ seenNextTokens.add(cursor);
53
58
  while (true) {
54
59
  const remaining = maxItems !== undefined ? maxItems - items.length : Infinity;
55
60
  if (remaining <= 0)
56
61
  break;
62
+ if (pagesFetched >= MAX_AUTO_PAGES) {
63
+ throw paginationSafetyError('max_pages_exceeded', {
64
+ maxPages: MAX_AUTO_PAGES,
65
+ lastCursor: cursor ?? null,
66
+ });
67
+ }
57
68
  const callPageSize = Number.isFinite(remaining) ? Math.min(pageSize, remaining) : pageSize;
58
69
  const page = await fetchPage({ pageSize: callPageSize, cursor });
70
+ pagesFetched += 1;
59
71
  lastNextToken = page.nextToken;
60
72
  for (const item of page.items) {
61
73
  if (maxItems !== undefined && items.length >= maxItems)
@@ -64,10 +76,26 @@ export async function paginate(fetchPage, flags = {}) {
64
76
  }
65
77
  if (page.nextToken === null)
66
78
  break;
79
+ if (seenNextTokens.has(page.nextToken)) {
80
+ throw paginationSafetyError('repeated_next_token', {
81
+ cursor: page.nextToken,
82
+ pagesFetched,
83
+ });
84
+ }
85
+ seenNextTokens.add(page.nextToken);
67
86
  cursor = page.nextToken;
68
87
  }
69
88
  return { items, nextToken: lastNextToken };
70
89
  }
90
+ function paginationSafetyError(reason, details) {
91
+ return ApiError.fromEnvelope({
92
+ code: 'UNAVAILABLE',
93
+ message: 'Pagination did not make progress safely.',
94
+ nextAction: 'Retry later. If the problem continues, contact TestSprite support with the cursor details.',
95
+ requestId: 'local',
96
+ details: { reason, ...details },
97
+ });
98
+ }
71
99
  /**
72
100
  * Drop-in helper for commands that take a single page and surface
73
101
  * the cursor verbatim (no auto-follow). Used when the caller passed
@@ -20,6 +20,7 @@
20
20
  * 5xx → single retry honoring Retry-After, second 5xx throws (exit 9).
21
21
  * Deadline exceeded → throw `TimeoutError`.
22
22
  */
23
+ import type { ShutdownHandle } from './interrupt.js';
23
24
  import type { RunResponse } from './runs.types.js';
24
25
  /**
25
26
  * Minimal interface that `pollRunUntilTerminal` requires from the HTTP client.
@@ -75,6 +76,16 @@ export interface PollOptions {
75
76
  * user's deadline (the per-request HTTP timeout is much larger).
76
77
  */
77
78
  resolveAlternate?: (run: RunResponse, elapsedMs: number, signal: AbortSignal) => Promise<RunResponse | null>;
79
+ /**
80
+ * Graceful-detach coordinator (DEV-331 piece 1). While the poll runs, the
81
+ * scope is armed: a SIGINT/SIGTERM aborts `shutdown.signal` with an
82
+ * `InterruptError` instead of killing the process, and this loop surfaces
83
+ * it immediately — the in-flight long-poll fetch aborts (composed into the
84
+ * per-iteration signal) and every backoff/retry sleep bails early. The
85
+ * caller's catch block renders the honest partial + re-attach hint.
86
+ * Absent (tests, non-wait callers): behavior is unchanged.
87
+ */
88
+ shutdown?: ShutdownHandle;
78
89
  }
79
90
  /**
80
91
  * Poll `GET /api/cli/v1/runs/{runId}` until the run reaches a terminal
package/dist/lib/poll.js CHANGED
@@ -20,7 +20,7 @@
20
20
  * 5xx → single retry honoring Retry-After, second 5xx throws (exit 9).
21
21
  * Deadline exceeded → throw `TimeoutError`.
22
22
  */
23
- import { ApiError } from './errors.js';
23
+ import { ApiError, InterruptError } from './errors.js';
24
24
  import { isTerminalStatus } from './runs.types.js';
25
25
  /** Thrown when the polling deadline is hit. */
26
26
  export class TimeoutError extends Error {
@@ -44,8 +44,25 @@ const BACKOFF_SCHEDULE_MS = [2000, 4000, 8000, 15000];
44
44
  * and unrecoverable server errors.
45
45
  */
46
46
  export async function pollRunUntilTerminal(client, runId, options) {
47
+ // Arm the graceful-detach scope for the duration of the poll (DEV-331):
48
+ // while armed, a termination signal aborts instead of hard-killing the
49
+ // process, and the wait-path catch blocks own the honest detach UX.
50
+ const disarm = options.shutdown?.arm();
51
+ try {
52
+ return await pollLoop(client, runId, options);
53
+ }
54
+ finally {
55
+ disarm?.();
56
+ }
57
+ }
58
+ async function pollLoop(client, runId, options) {
47
59
  const { timeoutSeconds, onTick, onTransition, resolveAlternate } = options;
48
- const sleep = options.sleep ?? defaultSleep;
60
+ const shutdownSignal = options.shutdown?.signal;
61
+ const rawSleep = options.sleep ?? defaultSleep;
62
+ // Every sleep site (retryAfterSeconds, backoff schedule, not_yet_visible,
63
+ // 5xx retry) bails immediately on interrupt — a Ctrl-C must not sit out a
64
+ // 15s backoff before it is noticed.
65
+ const sleep = (ms) => sleepUnlessInterrupted(rawSleep, ms, shutdownSignal);
49
66
  const startMs = Date.now();
50
67
  const deadlineMs = startMs + timeoutSeconds * 1000;
51
68
  // Track whether the server supports ?waitSeconds. Start optimistic.
@@ -55,6 +72,10 @@ export async function pollRunUntilTerminal(client, runId, options) {
55
72
  // 404 not_yet_visible retry budget (one soft retry per event).
56
73
  let notYetVisibleRetries = 0;
57
74
  while (true) {
75
+ // Interrupt outranks the deadline: a Ctrl-C that raced the timeout must
76
+ // surface as the honest detach, not as a generic TimeoutError.
77
+ if (shutdownSignal?.aborted)
78
+ throw shutdownSignal.reason;
58
79
  const now = Date.now();
59
80
  if (now >= deadlineMs) {
60
81
  throw new TimeoutError(runId, timeoutSeconds);
@@ -69,14 +90,21 @@ export async function pollRunUntilTerminal(client, runId, options) {
69
90
  const abortTimer = setTimeout(() => {
70
91
  abortController.abort();
71
92
  }, remainingMs + TRANSPORT_CUSHION_MS);
93
+ // Compose the interrupt into the per-iteration signal: a `--wait` can sit
94
+ // inside one <=25s long-poll fetch (and the auto-raised per-request
95
+ // timeout means even longer for slow backends) — checking the flag
96
+ // between iterations is not enough, the in-flight fetch must abort.
97
+ const iterationSignal = shutdownSignal != null
98
+ ? AbortSignal.any([abortController.signal, shutdownSignal])
99
+ : abortController.signal;
72
100
  let run;
73
101
  try {
74
102
  if (useBackoff) {
75
- run = await client.getRun(runId, { signal: abortController.signal });
103
+ run = await client.getRun(runId, { signal: iterationSignal });
76
104
  }
77
105
  else {
78
106
  const waitSeconds = Math.min(remainingSeconds, LONG_POLL_WAIT_SECONDS);
79
- run = await client.getRun(runId, { waitSeconds, signal: abortController.signal });
107
+ run = await client.getRun(runId, { waitSeconds, signal: iterationSignal });
80
108
  }
81
109
  // Successful GET resets the consecutive-error counter.
82
110
  consecutiveErrors = 0;
@@ -84,6 +112,13 @@ export async function pollRunUntilTerminal(client, runId, options) {
84
112
  }
85
113
  catch (err) {
86
114
  clearTimeout(abortTimer);
115
+ // Interrupt classification precedes the timeout mapping: the composed
116
+ // signal makes the fetch reject on Ctrl-C, and that abort must surface
117
+ // as the InterruptError — not as a spurious TimeoutError.
118
+ if (err instanceof InterruptError)
119
+ throw err;
120
+ if (shutdownSignal?.aborted)
121
+ throw shutdownSignal.reason;
87
122
  // An AbortError from our per-iteration controller means the deadline
88
123
  // passed while the fetch was in flight — surface as TimeoutError.
89
124
  if (isAbortError(err)) {
@@ -155,9 +190,15 @@ export async function pollRunUntilTerminal(client, runId, options) {
155
190
  }
156
191
  const altAbort = new AbortController();
157
192
  const altTimer = setTimeout(() => altAbort.abort(), altRemainingMs);
193
+ // The alternate lookup aborts on interrupt too; its errors are swallowed
194
+ // by the fallback (best-effort), so the loop-top interrupt check above
195
+ // surfaces the InterruptError on the next iteration.
196
+ const altSignal = shutdownSignal != null
197
+ ? AbortSignal.any([altAbort.signal, shutdownSignal])
198
+ : altAbort.signal;
158
199
  let alternate = null;
159
200
  try {
160
- alternate = await resolveAlternate(run, elapsedMs, altAbort.signal);
201
+ alternate = await resolveAlternate(run, elapsedMs, altSignal);
161
202
  }
162
203
  finally {
163
204
  clearTimeout(altTimer);
@@ -205,6 +246,30 @@ function backoffScheduleDelay(index) {
205
246
  function defaultSleep(ms) {
206
247
  return new Promise(resolve => setTimeout(resolve, ms));
207
248
  }
249
+ /**
250
+ * Race a sleep against the shutdown signal: rejects with the signal's
251
+ * `InterruptError` reason the moment it fires, so no backoff/retry wait can
252
+ * delay the honest-detach UX. Wraps the injected `sleep` (tests keep their
253
+ * deterministic fakes); the underlying timer is left to fire harmlessly —
254
+ * the interrupt path exits the process long before it matters.
255
+ */
256
+ function sleepUnlessInterrupted(sleep, ms, signal) {
257
+ if (signal == null)
258
+ return sleep(ms);
259
+ if (signal.aborted)
260
+ return Promise.reject(signal.reason);
261
+ return new Promise((resolve, reject) => {
262
+ const onAbort = () => reject(signal.reason);
263
+ signal.addEventListener('abort', onAbort, { once: true });
264
+ sleep(ms).then(() => {
265
+ signal.removeEventListener('abort', onAbort);
266
+ resolve();
267
+ }, err => {
268
+ signal.removeEventListener('abort', onAbort);
269
+ reject(err instanceof Error ? err : new Error(String(err)));
270
+ });
271
+ });
272
+ }
208
273
  /**
209
274
  * Detects an AbortError thrown when an AbortSignal fires.
210
275
  * Works for native fetch AbortErrors as well as `AbortController.abort()`
@@ -1,12 +1,19 @@
1
+ const pendingPromptInput = new WeakMap();
1
2
  export async function promptText(question, streams = {}) {
2
3
  const input = streams.input ?? process.stdin;
3
- const output = streams.output ?? process.stdout;
4
+ // Prompts are interactive UI, not data — write the question (and any echo)
5
+ // to stderr so stdout carries only the command's result. This keeps
6
+ // `--output json` stdout a single pure JSON document even on the interactive
7
+ // setup / configure path (§8.1 stdout purity). stderr is still the user's
8
+ // TTY, so the prompt remains visible.
9
+ const output = streams.output ?? process.stderr;
4
10
  output.write(question);
5
11
  return readLine(input, output, false);
6
12
  }
7
13
  export async function promptSecret(question, streams = {}) {
8
14
  const input = streams.input ?? process.stdin;
9
- const output = streams.output ?? process.stdout;
15
+ // See promptText: interactive prompt + masking go to stderr, not stdout.
16
+ const output = streams.output ?? process.stderr;
10
17
  output.write(question);
11
18
  const inputAsTTY = input;
12
19
  const useRawMode = inputAsTTY.isTTY === true && typeof inputAsTTY.setRawMode === 'function';
@@ -24,17 +31,27 @@ function readLine(input, output, mask) {
24
31
  return new Promise((resolve, reject) => {
25
32
  let buffer = '';
26
33
  let resolved = false;
34
+ let listening = false;
27
35
  const onData = (chunk) => {
28
36
  const str = typeof chunk === 'string' ? chunk : chunk.toString('utf-8');
29
- for (const ch of str) {
30
- const code = ch.charCodeAt(0);
37
+ processText(str);
38
+ };
39
+ const processText = (str) => {
40
+ for (let i = 0; i < str.length; i += 1) {
41
+ const code = str.charCodeAt(i);
31
42
  // Enter (CR or LF)
32
43
  if (code === 13 || code === 10) {
44
+ let nextIndex = i + 1;
45
+ if (code === 13 && str.charCodeAt(nextIndex) === 10) {
46
+ nextIndex += 1;
47
+ }
48
+ savePendingInput(str.slice(nextIndex));
33
49
  finish();
34
50
  return;
35
51
  }
36
52
  // Ctrl-C
37
53
  if (code === 3) {
54
+ savePendingInput('');
38
55
  cleanup();
39
56
  output.write('\n');
40
57
  if (!resolved) {
@@ -55,7 +72,7 @@ function readLine(input, output, mask) {
55
72
  // Drop other control chars
56
73
  if (code < 32)
57
74
  continue;
58
- buffer += ch;
75
+ buffer += str[i];
59
76
  if (mask)
60
77
  output.write('*');
61
78
  }
@@ -71,9 +88,12 @@ function readLine(input, output, mask) {
71
88
  }
72
89
  };
73
90
  const cleanup = () => {
74
- input.off('data', onData);
75
- input.off('end', onEnd);
76
- input.off('error', onError);
91
+ if (listening) {
92
+ input.off('data', onData);
93
+ input.off('end', onEnd);
94
+ input.off('error', onError);
95
+ listening = false;
96
+ }
77
97
  const pausable = input;
78
98
  if (typeof pausable.pause === 'function')
79
99
  pausable.pause();
@@ -86,12 +106,36 @@ function readLine(input, output, mask) {
86
106
  resolve(buffer);
87
107
  }
88
108
  };
109
+ const savePendingInput = (text) => {
110
+ if (text.length > 0) {
111
+ pendingPromptInput.set(input, text);
112
+ }
113
+ else {
114
+ pendingPromptInput.delete(input);
115
+ }
116
+ };
117
+ const pending = pendingPromptInput.get(input);
118
+ if (pending !== undefined) {
119
+ pendingPromptInput.delete(input);
120
+ processText(pending);
121
+ if (resolved)
122
+ return;
123
+ if (isInputEnded(input)) {
124
+ finish();
125
+ return;
126
+ }
127
+ }
89
128
  input.on('data', onData);
90
129
  input.on('end', onEnd);
91
130
  input.on('error', onError);
131
+ listening = true;
92
132
  const resumable = input;
93
133
  if (typeof resumable.resume === 'function')
94
134
  resumable.resume();
95
135
  });
96
136
  }
137
+ function isInputEnded(input) {
138
+ const state = input;
139
+ return state.readableEnded === true || state.destroyed === true || state.closed === true;
140
+ }
97
141
  //# sourceMappingURL=prompt.js.map
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Proxy support (issue #119): honor HTTPS_PROXY / HTTP_PROXY / NO_PROXY.
3
+ *
4
+ * Node's built-in fetch (undici) deliberately ignores the proxy environment
5
+ * variables, so behind a corporate or CI proxy every request dies with
6
+ * `fetch failed` after a full retry cycle. Installing undici's
7
+ * `EnvHttpProxyAgent` as the global dispatcher restores the conventional
8
+ * behavior (including NO_PROXY exemptions) for every fetch the CLI makes.
9
+ *
10
+ * Only active when a proxy env var is actually present, so the default path
11
+ * stays byte-identical and pays zero startup cost. Dependency note for
12
+ * reviewers: this adds `undici` as an explicit runtime dependency (the same
13
+ * engine Node already bundles); the alternative, a hand-rolled CONNECT
14
+ * tunnel, would re-implement what undici ships and maintains.
15
+ */
16
+ import type { Dispatcher } from 'undici';
17
+ export interface ProxyDeps {
18
+ env?: NodeJS.ProcessEnv;
19
+ /** Dispatcher installer. Defaults to undici's setGlobalDispatcher. */
20
+ install?: (agent: Dispatcher) => void;
21
+ /** Warning sink. Defaults to `process.stderr`. */
22
+ stderr?: (line: string) => void;
23
+ }
24
+ /**
25
+ * Install the env-driven proxy dispatcher when any proxy variable is set
26
+ * (both canonical upper-case and conventional lower-case spellings).
27
+ * Returns whether an agent was installed (observable for tests/debugging).
28
+ */
29
+ export declare function maybeInstallProxyAgent(deps?: ProxyDeps): boolean;
@@ -0,0 +1,30 @@
1
+ import { EnvHttpProxyAgent, setGlobalDispatcher } from 'undici';
2
+ /**
3
+ * Install the env-driven proxy dispatcher when any proxy variable is set
4
+ * (both canonical upper-case and conventional lower-case spellings).
5
+ * Returns whether an agent was installed (observable for tests/debugging).
6
+ */
7
+ export function maybeInstallProxyAgent(deps = {}) {
8
+ const env = deps.env ?? process.env;
9
+ const hasProxy = [env.HTTPS_PROXY, env.https_proxy, env.HTTP_PROXY, env.http_proxy].some(value => typeof value === 'string' && value.length > 0);
10
+ if (!hasProxy)
11
+ return false;
12
+ const install = deps.install ?? setGlobalDispatcher;
13
+ // EnvHttpProxyAgent reads HTTPS_PROXY/HTTP_PROXY/NO_PROXY itself, per
14
+ // request, so NO_PROXY exemptions apply without extra plumbing here.
15
+ //
16
+ // A malformed or unsupported proxy value (e.g. `socks5://...`) makes the
17
+ // agent throw. Because this runs at startup, an unguarded throw would abort
18
+ // every command before the CLI's own error handling — so fall back to the
19
+ // default (proxy-less) dispatcher and warn instead of crashing.
20
+ try {
21
+ install(new EnvHttpProxyAgent());
22
+ return true;
23
+ }
24
+ catch (error) {
25
+ const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
26
+ stderr(`warning: ignoring proxy environment (could not initialize proxy agent): ${error instanceof Error ? error.message : String(error)}`);
27
+ return false;
28
+ }
29
+ }
30
+ //# sourceMappingURL=proxy.js.map
@@ -3,13 +3,15 @@
3
3
  *
4
4
  * `boolean` flags (--dry-run, --debug, --verbose) take no value; emit
5
5
  * example without a placeholder. `value` flags (--output, --profile,
6
- * --endpoint-url) take a single argument; emit example with `<value>`.
6
+ * --endpoint-url, --request-timeout) take a single argument; emit example
7
+ * with `<value>`.
7
8
  */
8
9
  const GLOBAL_FLAG_ARITY = {
9
10
  'dry-run': 'boolean',
10
11
  output: 'value',
11
12
  profile: 'value',
12
13
  'endpoint-url': 'value',
14
+ 'request-timeout': 'value',
13
15
  debug: 'boolean',
14
16
  verbose: 'boolean',
15
17
  };
@@ -203,6 +203,15 @@ export interface RunResponse {
203
203
  */
204
204
  steps?: RunStepDto[] | null;
205
205
  }
206
+ /**
207
+ * Response from `POST /api/cli/v1/runs/{runId}/cancel`.
208
+ * Same shape as `GET /runs/{runId}` (`status: "cancelled"`, verdict
209
+ * untouched) plus `alreadyCancelled` distinguishing a fresh cancel
210
+ * (naturally idempotent) from a no-op re-cancel.
211
+ */
212
+ export interface CancelRunResponse extends RunResponse {
213
+ alreadyCancelled: boolean;
214
+ }
206
215
  /** Terminal states from the RunStatus union. */
207
216
  export declare const TERMINAL_RUN_STATUSES: ReadonlySet<RunStatus>;
208
217
  export declare function isTerminalStatus(status: RunStatus): boolean;
@@ -29,8 +29,8 @@ export interface SkillPresenceDeps {
29
29
  * True if the `testsprite-verify` skill is installed for ANY supported agent in
30
30
  * `dir`. own-file targets (claude/cursor/cline/antigravity): the landing file
31
31
  * exists. managed-section target (codex / AGENTS.md): the file exists AND
32
- * carries our BEGIN sentinel — a user-authored AGENTS.md without the sentinel
33
- * does NOT count as our skill.
32
+ * carries one complete managed section — a user-authored AGENTS.md without the
33
+ * sentinels, or with a truncated section, does NOT count as our skill.
34
34
  *
35
35
  * The TARGETS table is the single source of truth for landing paths, so this
36
36
  * stays in lockstep with `agent install` without re-listing paths. Best-effort:
@@ -1,6 +1,6 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { MANAGED_SECTION_BEGIN, TARGETS } from './agent-targets.js';
3
+ import { MANAGED_SECTION_BEGIN, MANAGED_SECTION_END, TARGETS } from './agent-targets.js';
4
4
  import { defaultCredentialsPath, readProfile } from './credentials.js';
5
5
  /**
6
6
  * Full command paths (group + leaf) that signal the caller is actively driving
@@ -35,8 +35,8 @@ export const SKILL_NUDGE_OPT_OUT_ENV = 'TESTSPRITE_NO_SKILL_WARNING';
35
35
  * True if the `testsprite-verify` skill is installed for ANY supported agent in
36
36
  * `dir`. own-file targets (claude/cursor/cline/antigravity): the landing file
37
37
  * exists. managed-section target (codex / AGENTS.md): the file exists AND
38
- * carries our BEGIN sentinel — a user-authored AGENTS.md without the sentinel
39
- * does NOT count as our skill.
38
+ * carries one complete managed section — a user-authored AGENTS.md without the
39
+ * sentinels, or with a truncated section, does NOT count as our skill.
40
40
  *
41
41
  * The TARGETS table is the single source of truth for landing paths, so this
42
42
  * stays in lockstep with `agent install` without re-listing paths. Best-effort:
@@ -51,7 +51,7 @@ export function isVerifySkillInstalled(dir, deps = {}) {
51
51
  continue;
52
52
  if (spec.mode === 'managed-section') {
53
53
  try {
54
- if (read(full).includes(MANAGED_SECTION_BEGIN))
54
+ if (hasCompleteManagedSection(read(full)))
55
55
  return true;
56
56
  }
57
57
  catch {
@@ -63,6 +63,14 @@ export function isVerifySkillInstalled(dir, deps = {}) {
63
63
  }
64
64
  return false;
65
65
  }
66
+ /** True when a managed-section file contains an ordered TestSprite BEGIN/END pair. */
67
+ function hasCompleteManagedSection(content) {
68
+ const begin = content.indexOf(MANAGED_SECTION_BEGIN);
69
+ if (begin === -1)
70
+ return false;
71
+ const end = content.indexOf(MANAGED_SECTION_END, begin + MANAGED_SECTION_BEGIN.length);
72
+ return end !== -1;
73
+ }
66
74
  /**
67
75
  * Best-effort onboarding warning. When a configured caller drives a verify-loop
68
76
  * command in a project that has NO installed skill, print a one-line `[warn]`
@@ -106,6 +114,7 @@ export function maybeEmitSkillNudge(ctx) {
106
114
  // command. Swallow everything (missing creds file, fs races, etc.).
107
115
  }
108
116
  }
117
+ /** Interpret common env-var spellings for an enabled opt-out flag. */
109
118
  function isTruthyEnv(v) {
110
119
  if (v === undefined)
111
120
  return false;
@@ -36,7 +36,14 @@ export function assertNotLocal(rawUrl) {
36
36
  if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
37
37
  throw localTargetError('target-url', 'must use http or https scheme');
38
38
  }
39
- const host = parsed.hostname.toLowerCase();
39
+ // Normalize a single trailing dot in the hostname. `localhost.` is the
40
+ // fully-qualified form of `localhost` (RFC 6761 reserves both to resolve to
41
+ // loopback), so `http://localhost.` must be rejected just like
42
+ // `http://localhost`. Without this strip, the trailing-dot form (also
43
+ // reachable via `localhost%2e`) slips past the `host === 'localhost'` check.
44
+ // IP literals are already dot-normalized by the WHATWG URL parser, so this
45
+ // only affects named hosts.
46
+ const host = parsed.hostname.toLowerCase().replace(/\.$/, '');
40
47
  // Loopback / unspecified.
41
48
  if (host === 'localhost' || host === '0.0.0.0') {
42
49
  throw localTargetError('target-url', 'localhost targets are not allowed', LOCAL_DEV_HINT);
@@ -8,6 +8,9 @@
8
8
  * - Uses `\r` + ANSI clear-line to overwrite in place on TTY
9
9
  * - On terminal, emits one final line + newline then prints the result
10
10
  * - `--output json` disables the ticker (caller doesn't create one)
11
+ * - Respects the NO_COLOR env var (https://no-color.org/): when set,
12
+ * ANSI escape sequences are suppressed and updates are emitted as
13
+ * plain lines instead of in-place overwrites.
11
14
  *
12
15
  * Overhead: <2ms per update (no syscalls beyond a single write).
13
16
  *
@@ -23,6 +26,11 @@ export interface Ticker {
23
26
  */
24
27
  finalize(line?: string): void;
25
28
  }
29
+ /**
30
+ * Returns true when NO_COLOR is present in the environment and is not
31
+ * an empty string, per https://no-color.org/.
32
+ */
33
+ export declare function isNoColor(env?: NodeJS.ProcessEnv): boolean;
26
34
  /**
27
35
  * Create a ticker bound to the given stderr writer. Respects
28
36
  * `isTTY` to silently no-op in CI environments.
@@ -33,5 +41,7 @@ export interface Ticker {
33
41
  * @param stderrRaw - optional raw writer (no \n appended); used for
34
42
  * the carriage-return + clear-line trick. Defaults to
35
43
  * `process.stderr.write.bind(process.stderr)`.
44
+ * @param noColor - whether to suppress ANSI escape sequences.
45
+ * Defaults to checking `NO_COLOR` env var per https://no-color.org/.
36
46
  */
37
- export declare function createTicker(stderrWrite: (line: string) => void, isTTY?: boolean, stderrRaw?: (text: string) => void): Ticker;
47
+ export declare function createTicker(stderrWrite: (line: string) => void, isTTY?: boolean, stderrRaw?: (text: string) => void, noColor?: boolean): Ticker;
@@ -8,12 +8,23 @@
8
8
  * - Uses `\r` + ANSI clear-line to overwrite in place on TTY
9
9
  * - On terminal, emits one final line + newline then prints the result
10
10
  * - `--output json` disables the ticker (caller doesn't create one)
11
+ * - Respects the NO_COLOR env var (https://no-color.org/): when set,
12
+ * ANSI escape sequences are suppressed and updates are emitted as
13
+ * plain lines instead of in-place overwrites.
11
14
  *
12
15
  * Overhead: <2ms per update (no syscalls beyond a single write).
13
16
  *
14
17
  * Timestamps: each tick prefixes an ISO 8601 timestamp so engineers
15
18
  * can correlate spinner output with --debug logs (dogfood item 2).
16
19
  */
20
+ /**
21
+ * Returns true when NO_COLOR is present in the environment and is not
22
+ * an empty string, per https://no-color.org/.
23
+ */
24
+ export function isNoColor(env = process.env) {
25
+ const value = env.NO_COLOR;
26
+ return typeof value === 'string' && value.length > 0;
27
+ }
17
28
  /**
18
29
  * Create a ticker bound to the given stderr writer. Respects
19
30
  * `isTTY` to silently no-op in CI environments.
@@ -24,13 +35,16 @@
24
35
  * @param stderrRaw - optional raw writer (no \n appended); used for
25
36
  * the carriage-return + clear-line trick. Defaults to
26
37
  * `process.stderr.write.bind(process.stderr)`.
38
+ * @param noColor - whether to suppress ANSI escape sequences.
39
+ * Defaults to checking `NO_COLOR` env var per https://no-color.org/.
27
40
  */
28
- export function createTicker(stderrWrite, isTTY, stderrRaw) {
41
+ export function createTicker(stderrWrite, isTTY, stderrRaw, noColor) {
29
42
  const tty = isTTY ?? (typeof process !== 'undefined' ? process.stderr.isTTY === true : false);
30
43
  const rawWrite = stderrRaw ??
31
44
  (typeof process !== 'undefined'
32
45
  ? (text) => process.stderr.write(text)
33
46
  : (_text) => undefined);
47
+ const suppressAnsi = noColor ?? isNoColor();
34
48
  let lastLength = 0;
35
49
  if (!tty) {
36
50
  // Non-TTY: completely silent.
@@ -39,6 +53,24 @@ export function createTicker(stderrWrite, isTTY, stderrRaw) {
39
53
  finalize: () => undefined,
40
54
  };
41
55
  }
56
+ if (suppressAnsi) {
57
+ // TTY but NO_COLOR: emit plain-text lines without ANSI escape sequences.
58
+ return {
59
+ update(line) {
60
+ const stamped = `${new Date().toISOString()} ${line}`;
61
+ stderrWrite(stamped);
62
+ lastLength = stamped.length;
63
+ },
64
+ finalize(line) {
65
+ if (line !== undefined) {
66
+ const stamped = `${new Date().toISOString()} ${line}`;
67
+ stderrWrite(stamped);
68
+ lastLength = stamped.length;
69
+ }
70
+ void stderrWrite;
71
+ },
72
+ };
73
+ }
42
74
  return {
43
75
  update(line) {
44
76
  // ANSI ESC[2K clears the entire line; \r moves to column 0.