@testsprite/testsprite-cli 0.2.0 → 0.3.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 (55) hide show
  1. package/README.md +34 -26
  2. package/dist/commands/agent.d.ts +43 -0
  3. package/dist/commands/agent.js +200 -18
  4. package/dist/commands/auth.js +29 -27
  5. package/dist/commands/doctor.d.ts +49 -0
  6. package/dist/commands/doctor.js +211 -0
  7. package/dist/commands/init.d.ts +1 -1
  8. package/dist/commands/init.js +24 -14
  9. package/dist/commands/project.d.ts +50 -1
  10. package/dist/commands/project.js +252 -43
  11. package/dist/commands/test.d.ts +188 -1
  12. package/dist/commands/test.js +1088 -81
  13. package/dist/commands/usage.js +13 -12
  14. package/dist/index.js +33 -2
  15. package/dist/lib/agent-targets.d.ts +72 -6
  16. package/dist/lib/agent-targets.js +188 -6
  17. package/dist/lib/bundle.d.ts +34 -0
  18. package/dist/lib/bundle.js +44 -10
  19. package/dist/lib/client-factory.d.ts +25 -0
  20. package/dist/lib/client-factory.js +47 -0
  21. package/dist/lib/config.d.ts +2 -0
  22. package/dist/lib/config.js +11 -2
  23. package/dist/lib/credentials.js +10 -1
  24. package/dist/lib/dry-run/samples.d.ts +5 -0
  25. package/dist/lib/dry-run/samples.js +28 -0
  26. package/dist/lib/flaky.d.ts +80 -0
  27. package/dist/lib/flaky.js +76 -0
  28. package/dist/lib/http.d.ts +20 -0
  29. package/dist/lib/http.js +216 -132
  30. package/dist/lib/interrupt.d.ts +61 -0
  31. package/dist/lib/interrupt.js +97 -0
  32. package/dist/lib/junit-report.d.ts +58 -0
  33. package/dist/lib/junit-report.js +210 -0
  34. package/dist/lib/output.d.ts +16 -1
  35. package/dist/lib/output.js +24 -2
  36. package/dist/lib/pagination.d.ts +4 -3
  37. package/dist/lib/pagination.js +34 -6
  38. package/dist/lib/prompt.js +52 -8
  39. package/dist/lib/proxy.d.ts +29 -0
  40. package/dist/lib/proxy.js +30 -0
  41. package/dist/lib/render-error.js +3 -1
  42. package/dist/lib/skill-nudge.d.ts +2 -2
  43. package/dist/lib/skill-nudge.js +13 -4
  44. package/dist/lib/target-url.js +8 -1
  45. package/dist/lib/ticker.d.ts +11 -1
  46. package/dist/lib/ticker.js +33 -1
  47. package/dist/lib/update-check.d.ts +67 -0
  48. package/dist/lib/update-check.js +246 -0
  49. package/dist/version-guard.d.ts +33 -0
  50. package/dist/version-guard.js +39 -0
  51. package/dist/version.d.ts +1 -1
  52. package/dist/version.js +1 -1
  53. package/package.json +3 -2
  54. package/skills/testsprite-onboard.skill.md +21 -0
  55. package/skills/testsprite-verify.skill.md +33 -0
@@ -0,0 +1,210 @@
1
+ import { createWriteStream } from 'node:fs';
2
+ import { rename, stat, unlink } from 'node:fs/promises';
3
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { localValidationError, TransportError } from './errors.js';
6
+ const XML_DECL = '<?xml version="1.0" encoding="UTF-8"?>';
7
+ /**
8
+ * Parse `--report <format>`. Only `junit` is accepted in v1.
9
+ */
10
+ export function parseJUnitReportFormat(raw) {
11
+ if (raw === undefined || raw === '')
12
+ return undefined;
13
+ if (raw === 'junit')
14
+ return 'junit';
15
+ throw localValidationError('report', `unsupported report format "${raw}" — accepted: junit`);
16
+ }
17
+ /**
18
+ * Validate `--report` / `--report-file` / `--report-suite-name` combinations.
19
+ * Report export is a sidecar artifact for batch `--wait` runs only.
20
+ */
21
+ export function assertJUnitReportOptions(opts) {
22
+ if (opts.report === undefined) {
23
+ if (opts.reportFile !== undefined && opts.reportFile !== '') {
24
+ throw localValidationError('report-file', '--report-file requires --report junit');
25
+ }
26
+ if (opts.reportSuiteName !== undefined && opts.reportSuiteName !== '') {
27
+ throw localValidationError('report-suite-name', '--report-suite-name requires --report junit');
28
+ }
29
+ return;
30
+ }
31
+ if (!opts.batchPath) {
32
+ throw localValidationError('report', '--report junit only applies to batch --wait runs (test run --all, or test rerun --all / multiple test ids)');
33
+ }
34
+ if (!opts.wait) {
35
+ throw localValidationError('report', '--report junit requires --wait (the report is written after batch polling completes)');
36
+ }
37
+ if (opts.reportFile === undefined || opts.reportFile === '') {
38
+ throw localValidationError('report-file', '--report junit requires --report-file <path>');
39
+ }
40
+ }
41
+ /**
42
+ * Resolve the project id used for JUnit classname / default suite naming.
43
+ * Prefer explicit `--project`, then ids observed on polled run rows.
44
+ */
45
+ export function resolveBatchReportProjectId(opts, results) {
46
+ if (opts.projectId)
47
+ return opts.projectId;
48
+ const fromPoll = results.map(r => r.projectId).find((id) => !!id);
49
+ if (fromPoll)
50
+ return fromPoll;
51
+ throw localValidationError('project', '--report junit requires --project <id> when the project cannot be inferred from run results');
52
+ }
53
+ /**
54
+ * Escape text for inclusion in XML element bodies and double-quoted attributes.
55
+ */
56
+ export function escapeXml(text) {
57
+ return text
58
+ .replace(/&/g, '&amp;')
59
+ .replace(/</g, '&lt;')
60
+ .replace(/>/g, '&gt;')
61
+ .replace(/"/g, '&quot;')
62
+ .replace(/'/g, '&apos;');
63
+ }
64
+ function classifyJUnitOutcome(status, error) {
65
+ if (status === 'passed')
66
+ return 'passed';
67
+ if (status === 'skipped')
68
+ return 'skipped';
69
+ if (status === 'error' || error?.exitCode === 3)
70
+ return 'error';
71
+ return 'failure';
72
+ }
73
+ function failureMessage(result) {
74
+ if (result.error?.message)
75
+ return result.error.message;
76
+ if (result.error?.code)
77
+ return result.error.code;
78
+ return result.status;
79
+ }
80
+ function renderTestcase(result, classname) {
81
+ const outcome = classifyJUnitOutcome(result.status, result.error);
82
+ const name = escapeXml(result.testId);
83
+ const cls = escapeXml(classname);
84
+ const lines = [` <testcase classname="${cls}" name="${name}" time="0">`];
85
+ if (outcome === 'failure') {
86
+ const message = escapeXml(failureMessage(result));
87
+ const type = escapeXml(result.status);
88
+ const body = escapeXml([
89
+ `status: ${result.status}`,
90
+ result.runId ? `runId: ${result.runId}` : undefined,
91
+ result.error?.code ? `code: ${result.error.code}` : undefined,
92
+ result.error?.message ? `message: ${result.error.message}` : undefined,
93
+ ]
94
+ .filter(Boolean)
95
+ .join('\n'));
96
+ lines.push(` <failure message="${message}" type="${type}">${body}</failure>`);
97
+ }
98
+ else if (outcome === 'error') {
99
+ const message = escapeXml(failureMessage(result));
100
+ const type = escapeXml(result.error?.code ?? result.status);
101
+ const body = escapeXml([
102
+ result.error?.code ? `code: ${result.error.code}` : undefined,
103
+ result.error?.message ? `message: ${result.error.message}` : undefined,
104
+ result.runId ? `runId: ${result.runId}` : undefined,
105
+ ]
106
+ .filter(Boolean)
107
+ .join('\n'));
108
+ lines.push(` <error message="${message}" type="${type}">${body}</error>`);
109
+ }
110
+ else if (outcome === 'skipped') {
111
+ lines.push(` <skipped/>`);
112
+ }
113
+ lines.push(' </testcase>');
114
+ return lines.join('\n');
115
+ }
116
+ /**
117
+ * Build a JUnit XML document from batch poll results. Duration is `0` in v1
118
+ * because batch poll envelopes do not carry per-run timing.
119
+ */
120
+ export function buildJUnitReport(opts) {
121
+ const results = opts.results;
122
+ let failures = 0;
123
+ let errors = 0;
124
+ let skipped = 0;
125
+ for (const result of results) {
126
+ const outcome = classifyJUnitOutcome(result.status, result.error);
127
+ if (outcome === 'failure')
128
+ failures++;
129
+ else if (outcome === 'error')
130
+ errors++;
131
+ else if (outcome === 'skipped')
132
+ skipped++;
133
+ }
134
+ const suiteName = escapeXml(opts.suiteName);
135
+ const testcases = results.map(r => renderTestcase(r, opts.classname)).join('\n');
136
+ return [
137
+ XML_DECL,
138
+ '<testsuites>',
139
+ ` <testsuite name="${suiteName}" tests="${results.length}" failures="${failures}" errors="${errors}" skipped="${skipped}" time="0">`,
140
+ testcases,
141
+ ' </testsuite>',
142
+ '</testsuites>',
143
+ '',
144
+ ].join('\n');
145
+ }
146
+ async function assertReportFileParent(rawPath) {
147
+ if (typeof rawPath !== 'string' || rawPath.length === 0) {
148
+ throw localValidationError('report-file', 'must be a non-empty file path');
149
+ }
150
+ const resolved = isAbsolute(rawPath) ? rawPath : resolve(process.cwd(), rawPath);
151
+ if (resolved.endsWith('/') || resolved.endsWith('\\')) {
152
+ throw localValidationError('report-file', 'must point to a file, not a directory');
153
+ }
154
+ const parent = dirname(resolved);
155
+ let parentStat;
156
+ try {
157
+ parentStat = await stat(parent);
158
+ }
159
+ catch {
160
+ throw localValidationError('report-file', `parent directory does not exist: ${parent}`);
161
+ }
162
+ if (!parentStat.isDirectory()) {
163
+ throw localValidationError('report-file', `parent path is not a directory: ${parent}`);
164
+ }
165
+ let targetStat;
166
+ try {
167
+ targetStat = await stat(resolved);
168
+ }
169
+ catch {
170
+ return resolved;
171
+ }
172
+ if (targetStat.isDirectory()) {
173
+ throw localValidationError('report-file', `must point to a file, not a directory: ${resolved}`);
174
+ }
175
+ return resolved;
176
+ }
177
+ /**
178
+ * Atomically write JUnit XML to `--report-file` (temp sibling + rename).
179
+ */
180
+ export async function writeJUnitReportFile(rawPath, xml) {
181
+ const resolved = await assertReportFileParent(rawPath);
182
+ const parent = dirname(resolved);
183
+ const tmpPath = join(parent, `.${basename(resolved)}.tmp-${randomUUID()}`);
184
+ await new Promise((resolvePromise, reject) => {
185
+ const stream = createWriteStream(tmpPath, { encoding: 'utf8' });
186
+ let streamError = null;
187
+ stream.on('error', err => {
188
+ streamError = err instanceof Error ? err : new Error(String(err));
189
+ });
190
+ stream.write(xml, err => {
191
+ if (err) {
192
+ streamError = err instanceof Error ? err : new Error(String(err));
193
+ }
194
+ stream.end(() => {
195
+ if (streamError) {
196
+ unlink(tmpPath).catch(() => undefined);
197
+ reject(new TransportError(`Failed to write --report-file ${resolved}: ${streamError.message}`));
198
+ return;
199
+ }
200
+ rename(tmpPath, resolved)
201
+ .then(() => resolvePromise())
202
+ .catch(renameErr => {
203
+ unlink(tmpPath).catch(() => undefined);
204
+ reject(new TransportError(`Failed to write --report-file ${resolved}: ${renameErr instanceof Error ? renameErr.message : String(renameErr)}`));
205
+ });
206
+ });
207
+ });
208
+ });
209
+ }
210
+ //# sourceMappingURL=junit-report.js.map
@@ -2,10 +2,25 @@ export type OutputMode = 'json' | 'text';
2
2
  /**
3
3
  * Help-text footer pointing at the global options surface so users
4
4
  * looking at any subcommand `--help` don't miss `--dry-run`, `--output`,
5
- * `--profile`, `--endpoint-url`, `--debug`.
5
+ * `--profile`, `--endpoint-url`, `--request-timeout`, `--debug`.
6
6
  */
7
7
  export declare const GLOBAL_OPTS_HINT: string;
8
8
  export declare function isOutputMode(value: unknown): value is OutputMode;
9
+ /**
10
+ * Resolve a raw `--output` flag value to a concrete {@link OutputMode}.
11
+ *
12
+ * `undefined` (flag omitted) resolves to the default `'text'`. Any other
13
+ * value that is not `'json'` or `'text'` throws a typed VALIDATION_ERROR
14
+ * (exit 5) with an actionable message.
15
+ *
16
+ * The alternative — silently falling back to `'text'` — is a footgun for the
17
+ * CLI's primary consumer (coding agents): a caller that asks for
18
+ * `--output json` but mistypes it (`--output josn`) would otherwise receive a
19
+ * human-readable text payload and fail to parse it as JSON, with no signal as
20
+ * to why. Every command group routes its global-option resolution through this
21
+ * helper so the validation is uniform.
22
+ */
23
+ export declare function resolveOutputMode(raw: unknown): OutputMode;
9
24
  export interface OutputStreams {
10
25
  /**
11
26
  * Line-oriented stdout writer. Each call is one logical line; the
@@ -1,13 +1,35 @@
1
+ import { localValidationError } from './errors.js';
1
2
  /**
2
3
  * Help-text footer pointing at the global options surface so users
3
4
  * looking at any subcommand `--help` don't miss `--dry-run`, `--output`,
4
- * `--profile`, `--endpoint-url`, `--debug`.
5
+ * `--profile`, `--endpoint-url`, `--request-timeout`, `--debug`.
5
6
  */
6
- export const GLOBAL_OPTS_HINT = '\nGlobal options (--dry-run, --output, --profile, --endpoint-url, --verbose, --debug):' +
7
+ export const GLOBAL_OPTS_HINT = '\nGlobal options (--dry-run, --output, --profile, --endpoint-url, --request-timeout, --verbose, --debug):' +
7
8
  '\n testsprite --help';
8
9
  export function isOutputMode(value) {
9
10
  return value === 'json' || value === 'text';
10
11
  }
12
+ /**
13
+ * Resolve a raw `--output` flag value to a concrete {@link OutputMode}.
14
+ *
15
+ * `undefined` (flag omitted) resolves to the default `'text'`. Any other
16
+ * value that is not `'json'` or `'text'` throws a typed VALIDATION_ERROR
17
+ * (exit 5) with an actionable message.
18
+ *
19
+ * The alternative — silently falling back to `'text'` — is a footgun for the
20
+ * CLI's primary consumer (coding agents): a caller that asks for
21
+ * `--output json` but mistypes it (`--output josn`) would otherwise receive a
22
+ * human-readable text payload and fail to parse it as JSON, with no signal as
23
+ * to why. Every command group routes its global-option resolution through this
24
+ * helper so the validation is uniform.
25
+ */
26
+ export function resolveOutputMode(raw) {
27
+ if (raw === undefined)
28
+ return 'text';
29
+ if (isOutputMode(raw))
30
+ return raw;
31
+ throw localValidationError('output', 'must be one of: json, text', ['json', 'text']);
32
+ }
11
33
  export class Output {
12
34
  mode;
13
35
  stdoutWrite;
@@ -16,13 +16,14 @@ export interface PaginationFlags {
16
16
  /** Client-side cap on total items returned across pages. */
17
17
  maxItems?: number;
18
18
  }
19
+ export declare const MAX_AUTO_PAGES = 1000;
19
20
  /**
20
21
  * Validates and normalizes pagination flags. Per the CLI OpenAPI spec
21
22
  * §components.parameters.PageSize the hard cap is 100. Values above the
22
23
  * cap are now rejected with exit 5 rather than silently clamped, giving
23
- * callers fast feedback that their flag value is out of range. Sub-1 /
24
- * NaN values also throw. `maxItems` is validated but not capped (it is a
25
- * client-side cursor, not a server parameter).
24
+ * callers fast feedback that their flag value is out of range. Fractional,
25
+ * sub-1, and NaN values also throw. `maxItems` is validated but not capped
26
+ * (it is a client-side cursor, not a server parameter).
26
27
  *
27
28
  * NOTE: `runResultHistory` previously did its own silent clamp via
28
29
  * `Math.min(Math.max(1, n), 100)` — that was unified to this path by the
@@ -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
@@ -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
  };
@@ -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);