@testsprite/testsprite-cli 0.1.2 → 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 (58) hide show
  1. package/README.md +34 -26
  2. package/dist/commands/agent.d.ts +52 -0
  3. package/dist/commands/agent.js +341 -93
  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 +7 -1
  8. package/dist/commands/init.js +66 -26
  9. package/dist/commands/project.d.ts +50 -1
  10. package/dist/commands/project.js +257 -43
  11. package/dist/commands/test.d.ts +214 -12
  12. package/dist/commands/test.js +1310 -174
  13. package/dist/commands/usage.js +13 -12
  14. package/dist/index.js +71 -18
  15. package/dist/lib/agent-targets.d.ts +169 -22
  16. package/dist/lib/agent-targets.js +335 -34
  17. package/dist/lib/bundle.d.ts +51 -1
  18. package/dist/lib/bundle.js +146 -55
  19. package/dist/lib/client-factory.d.ts +43 -0
  20. package/dist/lib/client-factory.js +89 -2
  21. package/dist/lib/config.d.ts +2 -0
  22. package/dist/lib/config.js +11 -2
  23. package/dist/lib/credentials.d.ts +7 -0
  24. package/dist/lib/credentials.js +40 -1
  25. package/dist/lib/dry-run/samples.d.ts +5 -0
  26. package/dist/lib/dry-run/samples.js +54 -9
  27. package/dist/lib/flaky.d.ts +80 -0
  28. package/dist/lib/flaky.js +76 -0
  29. package/dist/lib/http.d.ts +20 -0
  30. package/dist/lib/http.js +216 -132
  31. package/dist/lib/interrupt.d.ts +61 -0
  32. package/dist/lib/interrupt.js +97 -0
  33. package/dist/lib/junit-report.d.ts +58 -0
  34. package/dist/lib/junit-report.js +210 -0
  35. package/dist/lib/output.d.ts +16 -1
  36. package/dist/lib/output.js +24 -2
  37. package/dist/lib/pagination.d.ts +4 -3
  38. package/dist/lib/pagination.js +34 -6
  39. package/dist/lib/prompt.js +52 -8
  40. package/dist/lib/proxy.d.ts +29 -0
  41. package/dist/lib/proxy.js +30 -0
  42. package/dist/lib/render-error.d.ts +13 -0
  43. package/dist/lib/render-error.js +30 -7
  44. package/dist/lib/skill-nudge.d.ts +2 -2
  45. package/dist/lib/skill-nudge.js +13 -4
  46. package/dist/lib/target-url.js +8 -1
  47. package/dist/lib/ticker.d.ts +11 -1
  48. package/dist/lib/ticker.js +33 -1
  49. package/dist/lib/update-check.d.ts +67 -0
  50. package/dist/lib/update-check.js +246 -0
  51. package/dist/version-guard.d.ts +33 -0
  52. package/dist/version-guard.js +39 -0
  53. package/dist/version.d.ts +1 -1
  54. package/dist/version.js +1 -1
  55. package/package.json +3 -2
  56. package/skills/testsprite-onboard.skill.md +183 -0
  57. package/skills/testsprite-verify.codex.md +2 -0
  58. package/skills/testsprite-verify.skill.md +52 -1
@@ -1,12 +1,12 @@
1
1
  import { Command } from 'commander';
2
- import { emitDryRunBanner, makeHttpClient, } from '../lib/client-factory.js';
2
+ import { assertValidEndpointUrl, emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
3
3
  import { ApiError, CLIError } from '../lib/errors.js';
4
4
  import { facadeBaseUrl } from '../lib/facade.js';
5
5
  import { HttpClient } from '../lib/http.js';
6
6
  import { defaultCredentialsPath, deleteProfile, readProfile, writeProfile, } from '../lib/credentials.js';
7
- import { loadConfig } from '../lib/config.js';
7
+ import { loadConfig, normalizeEnvVar } from '../lib/config.js';
8
8
  import { emitDeprecationNotice } from '../lib/deprecate.js';
9
- import { GLOBAL_OPTS_HINT, Output } from '../lib/output.js';
9
+ import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
10
10
  import { promptSecret } from '../lib/prompt.js';
11
11
  const DEFAULT_API_URL = 'https://api.testsprite.com';
12
12
  const FROM_ENV_MISSING_KEY = 'TESTSPRITE_API_KEY is not set in the environment. Set it and re-run with --from-env, or omit --from-env to enter the key interactively.';
@@ -14,19 +14,23 @@ export async function runConfigure(opts, deps = {}) {
14
14
  const env = deps.env ?? process.env;
15
15
  const credentialsPath = deps.credentialsPath ?? defaultCredentialsPath();
16
16
  const out = makeOutput(opts.output, deps);
17
- const prelude = deps.preludeWrite ?? ((chunk) => process.stdout.write(chunk));
17
+ // The "Configuring profile …" prelude is informational, not result data, so
18
+ // it defaults to stderr — stdout stays a pure result stream (the configured
19
+ // JSON/text), which matters under `--output json` (§8.1 stdout purity).
20
+ const prelude = deps.preludeWrite ?? ((chunk) => process.stderr.write(chunk));
18
21
  const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
19
22
  // Normalize the env endpoint: an empty / whitespace-only TESTSPRITE_API_URL is
20
23
  // treated as unset. Without this, `''` (e.g. `export TESTSPRITE_API_URL=` in a
21
24
  // shell profile) is non-nullish and would short-circuit the `??` chains below to
22
25
  // an empty endpoint instead of falling through to the profile / prod default.
23
- const envApiUrl = env.TESTSPRITE_API_URL?.trim() || undefined;
26
+ const envApiUrl = normalizeEnvVar(env.TESTSPRITE_API_URL);
24
27
  // Dry-run: do not prompt, do not read env, do not write credentials.
25
28
  // Print the canned success shape so an agent sees exactly the JSON it
26
29
  // would get on a real configure (modulo the endpoint string).
27
30
  if (opts.dryRun) {
28
- emitDryRunBanner(stderr);
29
31
  const apiUrl = opts.endpointUrl ?? envApiUrl ?? DEFAULT_API_URL;
32
+ assertValidEndpointUrl(apiUrl);
33
+ emitDryRunBanner(stderr);
30
34
  stderr(`[dry-run] would write credentials for profile="${opts.profile}" to ${credentialsPath}`);
31
35
  out.print({ profile: opts.profile, apiUrl, status: 'configured' }, data => {
32
36
  const d = data;
@@ -49,6 +53,7 @@ export async function runConfigure(opts, deps = {}) {
49
53
  // api_url doesn't silently validate a new key against the default endpoint.
50
54
  const resolvedFromProfile = existingProfile?.apiUrl;
51
55
  const apiUrl = opts.endpointUrl ?? envApiUrl ?? resolvedFromProfile ?? DEFAULT_API_URL;
56
+ assertValidEndpointUrl(apiUrl);
52
57
  if (opts.fromEnv) {
53
58
  apiKey = env.TESTSPRITE_API_KEY?.trim();
54
59
  if (!apiKey)
@@ -79,6 +84,7 @@ export async function runConfigure(opts, deps = {}) {
79
84
  baseUrl: facadeBaseUrl(apiUrl),
80
85
  apiKey,
81
86
  fetchImpl: deps.fetchImpl,
87
+ requestTimeoutMs: opts.requestTimeoutMs,
82
88
  });
83
89
  try {
84
90
  // Tag the validation call with the originating command (when provided) so
@@ -90,11 +96,20 @@ export async function runConfigure(opts, deps = {}) {
90
96
  catch (err) {
91
97
  const message = err instanceof Error ? err.message : String(err);
92
98
  stderr(`API key rejected by ${apiUrl}: ${message} — profile NOT updated`);
93
- const exitCode = err instanceof ApiError ? err.exitCode : 3;
94
- // Include the resolved endpoint in the thrown message so the user knows
95
- // which host rejected the key. This prevents the "invalid or revoked"
96
- // message from being ambiguous when the key is valid for a different env.
97
- throw new CLIError(`API key rejected by ${apiUrl}: ${message} — did you mean to set TESTSPRITE_API_URL?`, exitCode);
99
+ // When the verification call returned a typed API error (AUTH_INVALID,
100
+ // AUTH_FORBIDDEN, etc.), re-throw it directly so `index.ts` renders the
101
+ // full typed envelope under `--output json` (code, nextAction, requestId,
102
+ // details). Previously wrapping it in CLIError discarded those fields and
103
+ // emitted a bare `{"error":"...string..."}` — violating the JSON contract.
104
+ // Augment the message with the endpoint context so text-mode users still
105
+ // see which host rejected the key.
106
+ if (err instanceof ApiError) {
107
+ err.message = `API key rejected by ${apiUrl}: ${message} — did you mean to set TESTSPRITE_API_URL?`;
108
+ throw err;
109
+ }
110
+ // Non-ApiError (truly unexpected throws like a TypeError from a
111
+ // misconfigured fetchImpl). Exit 3 (auth family).
112
+ throw new CLIError(`API key rejected by ${apiUrl}: ${message} — did you mean to set TESTSPRITE_API_URL?`, 3);
98
113
  }
99
114
  writeProfile(opts.profile, { apiKey, apiUrl }, { path: credentialsPath });
100
115
  out.print({ profile: opts.profile, apiUrl, status: 'configured' }, data => {
@@ -115,7 +130,8 @@ export async function runWhoami(opts, deps = {}) {
115
130
  // displayed URL always matches where requests actually go (dogfood L1788).
116
131
  let resolvedEndpoint;
117
132
  if (opts.dryRun) {
118
- resolvedEndpoint = opts.endpointUrl ?? env.TESTSPRITE_API_URL ?? 'https://api.testsprite.com';
133
+ resolvedEndpoint =
134
+ opts.endpointUrl ?? normalizeEnvVar(env.TESTSPRITE_API_URL) ?? 'https://api.testsprite.com';
119
135
  }
120
136
  else {
121
137
  const credentialsPath = deps.credentialsPath ?? defaultCredentialsPath();
@@ -222,7 +238,7 @@ function resolveCommonOptions(command) {
222
238
  const globals = command.optsWithGlobals();
223
239
  return {
224
240
  profile: globals.profile ?? 'default',
225
- output: globals.output ?? 'text',
241
+ output: resolveOutputMode(globals.output),
226
242
  endpointUrl: globals.endpointUrl,
227
243
  debug: globals.debug ?? false,
228
244
  verbose: globals.verbose ?? false,
@@ -230,20 +246,6 @@ function resolveCommonOptions(command) {
230
246
  requestTimeoutMs: parseRequestTimeoutFlag(globals.requestTimeout),
231
247
  };
232
248
  }
233
- /**
234
- * Parse the `--request-timeout <seconds>` flag value into milliseconds.
235
- * Returns `undefined` when the flag was not supplied (factory falls back to
236
- * the env var / default). Silently clamps out-of-range values — the
237
- * factory applies the same clamp so there is no double-clamp risk.
238
- */
239
- function parseRequestTimeoutFlag(raw) {
240
- if (raw === undefined)
241
- return undefined;
242
- const n = Number(raw);
243
- if (!Number.isFinite(n) || n <= 0)
244
- return undefined;
245
- return Math.round(n * 1000); // seconds → milliseconds
246
- }
247
249
  function makeOutput(mode, deps) {
248
250
  return new Output(mode, { stdout: deps.stdout, stderr: deps.stderr });
249
251
  }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * `testsprite doctor` — one-shot environment diagnostic.
3
+ *
4
+ * Runs a fixed checklist (CLI version, Node.js runtime, active profile, API
5
+ * endpoint, credentials, live connectivity + key validity, and whether the
6
+ * verify skill is installed in the current project) and prints an OK/WARN/FAIL
7
+ * report. Exits non-zero when any check FAILS so it can gate a CI step or an
8
+ * agent preflight (`testsprite doctor && testsprite test run ...`). Warnings
9
+ * (e.g. skill not installed) do not fail the process.
10
+ *
11
+ * Every check is reused from the same helpers the real commands use, so the
12
+ * report reflects exactly what a subsequent command would resolve: `loadConfig`
13
+ * for profile/endpoint/key, `assertValidEndpointUrl` for the endpoint gate,
14
+ * `makeHttpClient` + `GET /me` for connectivity, and `isVerifySkillInstalled`
15
+ * for the skill check.
16
+ */
17
+ import { Command } from 'commander';
18
+ import { type CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
19
+ import type { FetchImpl } from '../lib/http.js';
20
+ export type DoctorStatus = 'ok' | 'warn' | 'fail';
21
+ export interface DoctorCheck {
22
+ /** Short, stable label (also the JSON key-ish name). */
23
+ name: string;
24
+ status: DoctorStatus;
25
+ /** Human-readable one-line result. Never contains the API key. */
26
+ detail: string;
27
+ }
28
+ export interface DoctorReport {
29
+ checks: DoctorCheck[];
30
+ failures: number;
31
+ warnings: number;
32
+ }
33
+ export interface DoctorDeps {
34
+ env?: NodeJS.ProcessEnv;
35
+ credentialsPath?: string;
36
+ fetchImpl?: FetchImpl;
37
+ stdout?: (line: string) => void;
38
+ stderr?: (line: string) => void;
39
+ /** Project dir for the skill check. Defaults to `process.cwd()`. */
40
+ cwd?: string;
41
+ /** Runtime version string (e.g. "22.9.0"). Defaults to `process.versions.node`. */
42
+ nodeVersion?: string;
43
+ existsSync?: (p: string) => boolean;
44
+ readFileSync?: (p: string) => string;
45
+ }
46
+ type CommonOptions = FactoryCommonOptions;
47
+ export declare function runDoctor(opts: CommonOptions, deps?: DoctorDeps): Promise<DoctorReport>;
48
+ export declare function createDoctorCommand(deps?: DoctorDeps): Command;
49
+ export {};
@@ -0,0 +1,211 @@
1
+ /**
2
+ * `testsprite doctor` — one-shot environment diagnostic.
3
+ *
4
+ * Runs a fixed checklist (CLI version, Node.js runtime, active profile, API
5
+ * endpoint, credentials, live connectivity + key validity, and whether the
6
+ * verify skill is installed in the current project) and prints an OK/WARN/FAIL
7
+ * report. Exits non-zero when any check FAILS so it can gate a CI step or an
8
+ * agent preflight (`testsprite doctor && testsprite test run ...`). Warnings
9
+ * (e.g. skill not installed) do not fail the process.
10
+ *
11
+ * Every check is reused from the same helpers the real commands use, so the
12
+ * report reflects exactly what a subsequent command would resolve: `loadConfig`
13
+ * for profile/endpoint/key, `assertValidEndpointUrl` for the endpoint gate,
14
+ * `makeHttpClient` + `GET /me` for connectivity, and `isVerifySkillInstalled`
15
+ * for the skill check.
16
+ */
17
+ import { Command } from 'commander';
18
+ import { assertValidEndpointUrl, makeHttpClient, } from '../lib/client-factory.js';
19
+ import { loadConfig } from '../lib/config.js';
20
+ import { ApiError, CLIError, localValidationError } from '../lib/errors.js';
21
+ import { GLOBAL_OPTS_HINT, Output } from '../lib/output.js';
22
+ import { isVerifySkillInstalled } from '../lib/skill-nudge.js';
23
+ import { VERSION } from '../version.js';
24
+ import { MIN_SUPPORTED_NODE_MAJOR, shouldRejectNodeVersion } from '../version-guard.js';
25
+ export async function runDoctor(opts, deps = {}) {
26
+ const out = makeOutput(opts.output, deps);
27
+ const env = deps.env ?? process.env;
28
+ const cwd = deps.cwd ?? process.cwd();
29
+ const nodeVersion = deps.nodeVersion ?? process.versions.node;
30
+ const config = loadConfig({
31
+ profile: opts.profile,
32
+ endpointUrl: opts.endpointUrl,
33
+ env,
34
+ credentialsPath: deps.credentialsPath,
35
+ });
36
+ const endpointCheck = checkEndpoint(config.apiUrl);
37
+ const hasKey = Boolean(config.apiKey);
38
+ const checks = [
39
+ { name: 'CLI version', status: 'ok', detail: VERSION },
40
+ checkNodeVersion(nodeVersion),
41
+ { name: 'Profile', status: 'ok', detail: config.profile },
42
+ endpointCheck,
43
+ checkCredentials(hasKey, config.profile, opts.dryRun ?? false),
44
+ await checkConnectivity(opts, deps, {
45
+ hasKey,
46
+ endpointOk: endpointCheck.status === 'ok',
47
+ }),
48
+ checkSkill(cwd, deps),
49
+ ];
50
+ const failures = checks.filter(check => check.status === 'fail').length;
51
+ const warnings = checks.filter(check => check.status === 'warn').length;
52
+ const report = { checks, failures, warnings };
53
+ out.print(report, () => renderDoctor(report));
54
+ if (failures > 0) {
55
+ // Non-zero exit so `testsprite doctor && ...` gates a CI step or an agent
56
+ // preflight. The full report already printed above; this line is the stderr
57
+ // summary index.ts renders before exiting 1.
58
+ throw new CLIError(`doctor: ${failures} check(s) failed, ${warnings} warning(s)`, 1);
59
+ }
60
+ return report;
61
+ }
62
+ function checkNodeVersion(nodeVersion) {
63
+ // Reuse the CLI's own runtime guard so the verdict matches exactly what the
64
+ // entrypoint enforces at startup, rather than a divergent hardcoded check.
65
+ // The precise engines floor (20.19+/22.13+/24+) is enforced by npm at install
66
+ // time via .npmrc engine-strict. sourceRef: src/version-guard.ts.
67
+ const rejected = shouldRejectNodeVersion(nodeVersion);
68
+ return {
69
+ name: 'Node.js',
70
+ status: rejected ? 'fail' : 'ok',
71
+ detail: rejected
72
+ ? `v${nodeVersion} is below the required Node ${MIN_SUPPORTED_NODE_MAJOR}; upgrade Node.js`
73
+ : `v${nodeVersion} (>=${MIN_SUPPORTED_NODE_MAJOR} required)`,
74
+ };
75
+ }
76
+ function checkEndpoint(apiUrl) {
77
+ try {
78
+ assertValidEndpointUrl(apiUrl);
79
+ return { name: 'API endpoint', status: 'ok', detail: apiUrl };
80
+ }
81
+ catch {
82
+ return {
83
+ name: 'API endpoint',
84
+ status: 'fail',
85
+ detail: `"${apiUrl}" is not a valid http(s) URL`,
86
+ };
87
+ }
88
+ }
89
+ function checkCredentials(hasKey, profile, dryRun) {
90
+ if (hasKey) {
91
+ // Never print any part of the key (security). Confirm presence only.
92
+ return {
93
+ name: 'Credentials',
94
+ status: 'ok',
95
+ detail: `API key configured (profile "${profile}")`,
96
+ };
97
+ }
98
+ // Under --dry-run no key is expected, so a missing key is not a failure.
99
+ return {
100
+ name: 'Credentials',
101
+ status: dryRun ? 'warn' : 'fail',
102
+ detail: dryRun
103
+ ? 'no API key (not needed under --dry-run)'
104
+ : 'no API key found; run `testsprite setup` (or set TESTSPRITE_API_KEY)',
105
+ };
106
+ }
107
+ function checkSkill(cwd, deps) {
108
+ const installed = isVerifySkillInstalled(cwd, {
109
+ existsSync: deps.existsSync,
110
+ readFileSync: deps.readFileSync,
111
+ });
112
+ return {
113
+ name: 'Verify skill',
114
+ status: installed ? 'ok' : 'warn',
115
+ detail: installed
116
+ ? 'installed in this project'
117
+ : 'not installed here; run `testsprite setup` so your agent verifies its changes',
118
+ };
119
+ }
120
+ async function checkConnectivity(opts, deps, ctx) {
121
+ const name = 'Connectivity';
122
+ if (opts.dryRun)
123
+ return { name, status: 'warn', detail: 'skipped under --dry-run' };
124
+ if (!ctx.hasKey)
125
+ return { name, status: 'warn', detail: 'skipped; no API key to test with' };
126
+ if (!ctx.endpointOk)
127
+ return { name, status: 'warn', detail: 'skipped; endpoint URL is invalid' };
128
+ try {
129
+ const client = makeHttpClient(opts, {
130
+ env: deps.env,
131
+ credentialsPath: deps.credentialsPath,
132
+ fetchImpl: deps.fetchImpl,
133
+ stderr: deps.stderr,
134
+ });
135
+ const me = await client.get('/me');
136
+ const who = me.userId ? ` (userId ${me.userId})` : '';
137
+ return { name, status: 'ok', detail: `reached GET /me, API key accepted${who}` };
138
+ }
139
+ catch (error) {
140
+ if (error instanceof ApiError) {
141
+ if (error.code === 'AUTH_REQUIRED' ||
142
+ error.code === 'AUTH_INVALID' ||
143
+ error.code === 'AUTH_FORBIDDEN') {
144
+ return { name, status: 'fail', detail: `API key rejected (${error.code})` };
145
+ }
146
+ return { name, status: 'fail', detail: `GET /me failed (${error.code})` };
147
+ }
148
+ return {
149
+ name,
150
+ status: 'fail',
151
+ detail: `GET /me failed (${error instanceof Error ? error.message : String(error)})`,
152
+ };
153
+ }
154
+ }
155
+ const STATUS_LABEL = {
156
+ ok: '[OK] ',
157
+ warn: '[WARN]',
158
+ fail: '[FAIL]',
159
+ };
160
+ function renderDoctor(report) {
161
+ const nameWidth = Math.max(...report.checks.map(check => check.name.length));
162
+ const lines = ['TestSprite doctor', ''];
163
+ for (const check of report.checks) {
164
+ lines.push(` ${STATUS_LABEL[check.status]} ${check.name.padEnd(nameWidth)} ${check.detail}`);
165
+ }
166
+ lines.push('');
167
+ lines.push(report.failures === 0 && report.warnings === 0
168
+ ? 'All checks passed.'
169
+ : `${report.failures} failure(s), ${report.warnings} warning(s).`);
170
+ return lines.join('\n');
171
+ }
172
+ export function createDoctorCommand(deps = {}) {
173
+ const cmd = new Command('doctor')
174
+ .description('Diagnose CLI setup: version, Node, profile, endpoint, credentials, connectivity, skill')
175
+ .addHelpText('after', GLOBAL_OPTS_HINT)
176
+ .addHelpText('after', '\nExamples:\n' +
177
+ ' testsprite doctor # run all checks (exit 1 if any fails)\n' +
178
+ ' testsprite doctor --output json # machine-readable report\n' +
179
+ ' testsprite doctor && testsprite test run <id> # gate a command on a healthy setup')
180
+ .action(async (_cmdOpts, command) => {
181
+ await runDoctor(resolveCommonOptions(command), deps);
182
+ });
183
+ return cmd;
184
+ }
185
+ function resolveCommonOptions(command) {
186
+ const globals = command.optsWithGlobals();
187
+ return {
188
+ profile: globals.profile ?? 'default',
189
+ output: globals.output ?? 'text',
190
+ endpointUrl: globals.endpointUrl,
191
+ debug: globals.debug ?? false,
192
+ verbose: globals.verbose ?? false,
193
+ dryRun: globals.dryRun ?? false,
194
+ requestTimeoutMs: parseRequestTimeoutFlag(globals.requestTimeout),
195
+ };
196
+ }
197
+ function parseRequestTimeoutFlag(raw) {
198
+ if (raw === undefined)
199
+ return undefined;
200
+ const seconds = Number(raw);
201
+ if (!Number.isFinite(seconds) || seconds <= 0) {
202
+ // Match the other commands: a malformed --request-timeout is a validation
203
+ // error, not a silently-ignored default.
204
+ throw localValidationError('request-timeout', `must be a positive number of seconds (got "${raw}")`);
205
+ }
206
+ return Math.round(seconds * 1000);
207
+ }
208
+ function makeOutput(mode, deps) {
209
+ return new Output(mode, { stdout: deps.stdout, stderr: deps.stderr });
210
+ }
211
+ //# sourceMappingURL=doctor.js.map
@@ -10,7 +10,7 @@
10
10
  * Hard constraint: orchestrate existing exported primitives; never fork them.
11
11
  */
12
12
  import { Command } from 'commander';
13
- import type { CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
13
+ import { type CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
14
14
  import type { AuthDeps } from './auth.js';
15
15
  import type { AgentFs } from './agent.js';
16
16
  import type { FetchImpl } from '../lib/http.js';
@@ -52,9 +52,15 @@ export interface InitSummary {
52
52
  env: string;
53
53
  email?: string;
54
54
  scopes: string[];
55
+ /**
56
+ * Agent skill install outcome. `action` is an AGGREGATE across the installed
57
+ * skills (setup installs {@link DEFAULT_SKILLS}); `skills` lists which skills
58
+ * landed. `null` when --no-agent.
59
+ */
55
60
  agent: {
56
61
  target: string;
57
62
  action: string;
63
+ skills?: string[];
58
64
  } | null;
59
65
  status: 'initialized';
60
66
  }
@@ -10,12 +10,14 @@
10
10
  * Hard constraint: orchestrate existing exported primitives; never fork them.
11
11
  */
12
12
  import { Command } from 'commander';
13
+ import { parseRequestTimeoutFlag, } from '../lib/client-factory.js';
14
+ import { normalizeEnvVar } from '../lib/config.js';
13
15
  import { emitDeprecationNotice } from '../lib/deprecate.js';
14
16
  import { CLIError } from '../lib/errors.js';
15
- import { GLOBAL_OPTS_HINT, Output } from '../lib/output.js';
17
+ import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
16
18
  import { runConfigure, runWhoami } from './auth.js';
17
19
  import { runInstall } from './agent.js';
18
- import { TARGETS } from '../lib/agent-targets.js';
20
+ import { TARGETS, DEFAULT_SKILLS } from '../lib/agent-targets.js';
19
21
  import { readProfile } from '../lib/credentials.js';
20
22
  /** Mirrors auth.ts's DEFAULT_API_URL (kept in sync; auth.ts owns the canonical value). */
21
23
  const DEFAULT_API_URL = 'https://api.testsprite.com';
@@ -29,7 +31,7 @@ const DEFAULT_API_URL = 'https://api.testsprite.com';
29
31
  */
30
32
  function resolveReportedEndpoint(opts, deps) {
31
33
  const env = deps.env ?? process.env;
32
- const envApiUrl = env.TESTSPRITE_API_URL?.trim() || undefined;
34
+ const envApiUrl = normalizeEnvVar(env.TESTSPRITE_API_URL);
33
35
  let existing;
34
36
  try {
35
37
  existing = readProfile(opts.profile, { path: deps.credentialsPath })?.apiUrl;
@@ -39,6 +41,20 @@ function resolveReportedEndpoint(opts, deps) {
39
41
  }
40
42
  return opts.endpointUrl ?? envApiUrl ?? existing ?? DEFAULT_API_URL;
41
43
  }
44
+ /**
45
+ * Collapse the per-skill install actions into one representative action for the
46
+ * init summary. Precedence: a real change (updated) outranks a fresh install,
47
+ * which outranks a no-op. `blocked` never reaches here — runInstall throws first.
48
+ */
49
+ function aggregateInstallAction(actions) {
50
+ if (actions.some(a => a === 'updated' || a === 'section-updated'))
51
+ return 'updated';
52
+ if (actions.some(a => a === 'written' || a === 'section-installed'))
53
+ return 'installed';
54
+ if (actions.some(a => a === 'dry-run'))
55
+ return 'dry-run';
56
+ return 'skipped'; // all skipped / section-unchanged
57
+ }
42
58
  // ---------------------------------------------------------------------------
43
59
  // Helpers to split deps into the two primitive shapes
44
60
  // ---------------------------------------------------------------------------
@@ -140,7 +156,9 @@ export async function runInit(opts, deps = {}) {
140
156
  apiUrl: resolveReportedEndpoint(opts, deps),
141
157
  env: 'development',
142
158
  scopes: [],
143
- agent: agentTarget ? { target: agentTarget, action: 'dry-run' } : null,
159
+ agent: agentTarget
160
+ ? { target: agentTarget, action: 'dry-run', skills: [...DEFAULT_SKILLS] }
161
+ : null,
144
162
  status: 'initialized',
145
163
  };
146
164
  out.print(summary, renderInitText);
@@ -187,16 +205,19 @@ export async function runInit(opts, deps = {}) {
187
205
  // -------------------------------------------------------------------------
188
206
  let installedTarget = null;
189
207
  let installedAction = null;
208
+ let installedSkills = [];
190
209
  if (!opts.noAgent) {
191
- // Run install in JSON mode internally so we can reliably parse the action
210
+ // Run install in JSON mode internally so we can reliably parse the result
192
211
  // regardless of the outer --output flag. The stdout is captured here and
193
- // NOT forwarded — runInit owns the output surface.
194
- let capturedInstallResult = null;
212
+ // NOT forwarded — runInit owns the output surface. setup installs the full
213
+ // DEFAULT_SKILLS set (runInstall's default), so several InstallResults come
214
+ // back (one per own-file skill; one aggregate for codex).
215
+ let capturedInstallResults = [];
195
216
  const captureStdout = (line) => {
196
217
  try {
197
218
  const parsed = JSON.parse(line);
198
- if (Array.isArray(parsed) && parsed.length > 0 && parsed[0]) {
199
- capturedInstallResult = parsed[0];
219
+ if (Array.isArray(parsed) && parsed.length > 0) {
220
+ capturedInstallResults = parsed;
200
221
  }
201
222
  }
202
223
  catch {
@@ -208,13 +229,17 @@ export async function runInit(opts, deps = {}) {
208
229
  ...opts,
209
230
  output: 'json', // parse the result; final summary is ours to print
210
231
  target: [opts.agent],
232
+ // skills omitted → runInstall installs DEFAULT_SKILLS (verify + onboard)
211
233
  force: opts.force,
212
234
  dir: opts.dir,
213
235
  }, toAgentDeps(deps, captureStdout));
214
236
  installedTarget = opts.agent;
215
- installedAction = capturedInstallResult
216
- ? capturedInstallResult.action
217
- : 'installed';
237
+ installedAction =
238
+ capturedInstallResults.length > 0
239
+ ? aggregateInstallAction(capturedInstallResults.map(r => r.action))
240
+ : 'installed';
241
+ // De-dupe skills across results, preserving first-seen order.
242
+ installedSkills = [...new Set(capturedInstallResults.flatMap(r => r.skills ?? []))];
218
243
  }
219
244
  catch (installErr) {
220
245
  // Fix 6: credentials were already saved (Step 1+2 above succeeded).
@@ -230,7 +255,11 @@ export async function runInit(opts, deps = {}) {
230
255
  // -------------------------------------------------------------------------
231
256
  const agentSummary = opts.noAgent || installedTarget === null
232
257
  ? null
233
- : { target: installedTarget, action: installedAction ?? 'installed' };
258
+ : {
259
+ target: installedTarget,
260
+ action: installedAction ?? 'installed',
261
+ skills: installedSkills.length > 0 ? installedSkills : [...DEFAULT_SKILLS],
262
+ };
234
263
  const summary = {
235
264
  profile: opts.profile,
236
265
  // Resolved AFTER configure persists the profile → reflects the real endpoint
@@ -262,16 +291,35 @@ function renderInitText(data) {
262
291
  lines.push('');
263
292
  if (s.agent) {
264
293
  lines.push(` agent: ${s.agent.target} (${s.agent.action})`);
294
+ if (s.agent.skills && s.agent.skills.length > 0) {
295
+ lines.push(` skills: ${s.agent.skills.join(', ')}`);
296
+ }
265
297
  }
266
298
  else {
267
299
  lines.push(' agent: skipped (--no-agent)');
268
300
  }
269
301
  lines.push('');
270
302
  lines.push('Next steps:');
271
- lines.push(' testsprite test list # list tests in the current project');
272
- lines.push(' testsprite agent list # check installed agent targets');
303
+ lines.push(' # 1. Create your first project (frontend example) — prints a projectId');
304
+ lines.push(' testsprite project create --type frontend --name "My App" --url https://your-app.com');
305
+ lines.push('');
273
306
  if (s.agent) {
274
- lines.push(' testsprite agent install --target=<t> # re-install or install additional targets');
307
+ lines.push(' # 2. Generate tests: ask your coding agent (the testsprite-onboard skill is installed),');
308
+ lines.push(' # or create one yourself, then run them (use the projectId from step 1):');
309
+ lines.push(' testsprite test run --all --project <projectId>');
310
+ lines.push('');
311
+ lines.push(' # Manage installed agent skills');
312
+ lines.push(' testsprite agent list');
313
+ lines.push(' testsprite agent install --target=<t> # re-install or install additional targets');
314
+ }
315
+ else {
316
+ lines.push(' # 2. Create a test, then run it (use the projectId from step 1):');
317
+ lines.push(' testsprite test create --project <projectId> ...');
318
+ lines.push(' testsprite test run --all --project <projectId>');
319
+ lines.push(' # Tip: `testsprite agent install` sets up the onboarding skill for your coding agent');
320
+ lines.push('');
321
+ lines.push(' # Manage installed agent skills');
322
+ lines.push(' testsprite agent list');
275
323
  }
276
324
  return lines.join('\n');
277
325
  }
@@ -282,7 +330,7 @@ function resolveCommonOptions(command) {
282
330
  const globals = command.optsWithGlobals();
283
331
  return {
284
332
  profile: globals.profile ?? 'default',
285
- output: globals.output ?? 'text',
333
+ output: resolveOutputMode(globals.output),
286
334
  endpointUrl: globals.endpointUrl,
287
335
  debug: globals.debug ?? false,
288
336
  verbose: globals.verbose ?? false,
@@ -290,15 +338,7 @@ function resolveCommonOptions(command) {
290
338
  requestTimeoutMs: parseRequestTimeoutFlag(globals.requestTimeout),
291
339
  };
292
340
  }
293
- function parseRequestTimeoutFlag(raw) {
294
- if (raw === undefined)
295
- return undefined;
296
- const n = Number(raw);
297
- if (!Number.isFinite(n) || n <= 0)
298
- return undefined;
299
- return Math.round(n * 1000);
300
- }
301
- const SETUP_DESCRIPTION = 'Set up TestSprite: configure your API key and install the verification skill for your coding agent';
341
+ const SETUP_DESCRIPTION = 'Set up TestSprite: configure your API key and install the TestSprite agent skills for your coding agent';
302
342
  /** Attach the onboarding flags shared by `setup` and the `init` alias. */
303
343
  function addSetupOptions(cmd, validTargets, defaultAgent) {
304
344
  return cmd
@@ -63,10 +63,59 @@ interface UpdateOptions extends CommonOptions {
63
63
  username?: string;
64
64
  password?: string;
65
65
  passwordFile?: string;
66
- description?: string;
67
66
  instruction?: string;
68
67
  idempotencyKey?: string;
69
68
  }
70
69
  export declare function runUpdate(opts: UpdateOptions, deps?: ProjectDeps): Promise<CliUpdateProjectResponse>;
70
+ export interface CliProjectCredentialResponse {
71
+ projectId: string;
72
+ authType: string;
73
+ rewroteCount: number;
74
+ }
75
+ interface CredentialOptions extends CommonOptions {
76
+ projectId: string;
77
+ authType: string;
78
+ credential?: string;
79
+ credentialFile?: string;
80
+ idempotencyKey?: string;
81
+ }
82
+ export declare function runCredential(opts: CredentialOptions, deps?: ProjectDeps): Promise<CliProjectCredentialResponse>;
83
+ export interface CliProjectAutoAuthResponse {
84
+ projectId: string;
85
+ enabled: boolean;
86
+ method: string;
87
+ inject: string;
88
+ /**
89
+ * Present when the server's trial refresh failed: `enabled` is then `false`
90
+ * and this carries the reason (e.g. a bad refresh token). The config is still
91
+ * stored, but auto-auth won't run until the login succeeds.
92
+ */
93
+ lastRefreshError?: string;
94
+ }
95
+ interface AutoAuthOptions extends CommonOptions {
96
+ projectId: string;
97
+ disable?: boolean;
98
+ method: string;
99
+ inject: string;
100
+ injectKey?: string;
101
+ loginUrl?: string;
102
+ loginMethod?: string;
103
+ loginContentType?: string;
104
+ loginBodyTemplate?: string;
105
+ username?: string;
106
+ password?: string;
107
+ passwordFile?: string;
108
+ tokenPath?: string;
109
+ tokenEndpoint?: string;
110
+ clientId?: string;
111
+ clientSecret?: string;
112
+ clientSecretFile?: string;
113
+ refreshToken?: string;
114
+ refreshTokenFile?: string;
115
+ scope?: string;
116
+ region?: string;
117
+ idempotencyKey?: string;
118
+ }
119
+ export declare function runAutoAuth(opts: AutoAuthOptions, deps?: ProjectDeps): Promise<CliProjectAutoAuthResponse>;
71
120
  export declare function createProjectCommand(deps?: ProjectDeps): Command;
72
121
  export {};