@testsprite/testsprite-cli 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Which coding agents does this repo use?
3
+ *
4
+ * Two signal classes, kept apart because they answer different questions: `env`
5
+ * is who is invoking the CLI now, `trace` is who has been used here. Only two
6
+ * targets publish a usable env var, so traces cover the rest.
7
+ */
8
+ import { join } from 'node:path';
9
+ import { existsSync as nodeExistsSync, readFileSync as nodeReadFileSync, readdirSync as nodeReaddirSync, statSync as nodeStatSync, } from 'node:fs';
10
+ import { DEFAULT_SKILLS, TARGETS, pathFor } from './agent-targets.js';
11
+ /**
12
+ * Environment variables that identify the invoking agent.
13
+ *
14
+ * Only add a variable that is observed or vendor-documented: a guessed name
15
+ * never matches, so it degrades to the fallback instead of failing loudly.
16
+ * The other six targets publish nothing usable — VSCODE_* and TERM_PROGRAM
17
+ * name the editor, not the agent, and cannot separate cursor from windsurf.
18
+ *
19
+ * Presence is the signal, so a CI job that exports one of these is read as that
20
+ * agent calling. The cost is bounded and one-directional: an extra skill file
21
+ * installed, and `detected` rather than `fallback` in the summary. Pass
22
+ * `--agent` to decide it explicitly, or `--no-agent` to install nothing.
23
+ */
24
+ const ENV_SIGNALS = {
25
+ claude: ['CLAUDECODE'],
26
+ cursor: ['CURSOR_AGENT'],
27
+ };
28
+ /**
29
+ * Repo paths that show an agent has been used here.
30
+ *
31
+ * Each is the config root the agent itself owns, which is also where our skill
32
+ * lands — so presence alone is not enough (see `hasForeignContent`).
33
+ */
34
+ const TRACE_PATHS = {
35
+ claude: '.claude',
36
+ antigravity: '.agents',
37
+ cursor: '.cursor',
38
+ cline: '.clinerules',
39
+ kiro: '.kiro',
40
+ windsurf: '.windsurf',
41
+ copilot: '.github/instructions',
42
+ codex: 'AGENTS.md',
43
+ };
44
+ const MAX_TRACE_DEPTH = 4;
45
+ function truthy(value) {
46
+ if (value === undefined)
47
+ return false;
48
+ const v = value.trim().toLowerCase();
49
+ return v !== '' && v !== '0' && v !== 'false';
50
+ }
51
+ /**
52
+ * Every relative path this CLI writes for a target, across all default skills.
53
+ *
54
+ * Includes the `.bak` sibling `agent install --force` leaves behind. Without
55
+ * it one forced reinstall makes that target permanently "detected" from its
56
+ * own backup — the self-reinforcement `hasForeignContent` exists to prevent,
57
+ * just one file over.
58
+ */
59
+ function ownPaths(target) {
60
+ return DEFAULT_SKILLS.flatMap(skill => {
61
+ const p = pathFor(target, skill).replace(/\\/g, '/');
62
+ return [p, `${p}.bak`];
63
+ });
64
+ }
65
+ /**
66
+ * True when the trace holds something this CLI did not put there.
67
+ *
68
+ * Without this the fallback is self-reinforcing: a repo where nothing was
69
+ * detected gets our own skill files written, and the next run reads those back
70
+ * as evidence of the agent we guessed.
71
+ */
72
+ function hasForeignContent(dir, target, relRoot, deps) {
73
+ const mine = new Set(ownPaths(target));
74
+ const walk = (rel, depth) => {
75
+ if (depth > MAX_TRACE_DEPTH)
76
+ return true; // too deep to be only ours
77
+ let entries;
78
+ try {
79
+ entries = deps.readdirSync(join(dir, rel));
80
+ }
81
+ catch {
82
+ return false; // unreadable → claim nothing
83
+ }
84
+ for (const entry of entries) {
85
+ const childRel = `${rel}/${entry}`;
86
+ if (mine.has(childRel))
87
+ continue;
88
+ // A directory on the way to one of our files is not itself evidence.
89
+ const isPrefix = [...mine].some(p => p.startsWith(`${childRel}/`));
90
+ if (!isPrefix)
91
+ return true;
92
+ if (deps.isDirectory(join(dir, childRel)) && walk(childRel, depth + 1))
93
+ return true;
94
+ }
95
+ return false;
96
+ };
97
+ return walk(relRoot, 1);
98
+ }
99
+ /**
100
+ * `AGENTS.md` is a cross-agent convention file, and this CLI creates it when
101
+ * absent — so it counts as a codex trace only when it carries content beyond
102
+ * our own managed section.
103
+ */
104
+ function agentsFileHasForeignContent(content) {
105
+ const withoutSection = content.replace(/<!--\s*BEGIN TESTSPRITE AGENT SECTION[\s\S]*?END TESTSPRITE AGENT SECTION\s*-->/g, '');
106
+ return withoutSection.trim().length > 0;
107
+ }
108
+ /**
109
+ * Who is invoking the CLI right now, from the environment alone — no fs, no
110
+ * repo history. This is the only signal that identifies the CALLER; a repo
111
+ * trace only shows an agent was used here at some point.
112
+ */
113
+ export function detectCallerFromEnv(env = process.env) {
114
+ const out = [];
115
+ for (const [target, vars] of Object.entries(ENV_SIGNALS)) {
116
+ const hit = vars.find(name => truthy(env[name]));
117
+ if (hit)
118
+ out.push({ target, source: 'env', signal: hit });
119
+ }
120
+ return out;
121
+ }
122
+ /**
123
+ * Targets detected in `dir`, env signals first.
124
+ *
125
+ * Order is significant: `setup` reports these in order, so the strongest
126
+ * evidence is named first. A target found by both appears once, as `env`.
127
+ */
128
+ export function detectAgentTargets(dir, deps = {}) {
129
+ const env = deps.env ?? process.env;
130
+ const exists = deps.existsSync ?? nodeExistsSync;
131
+ const readdir = deps.readdirSync ??
132
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- path comes from this module's own TRACE_PATHS table joined to the caller's dir, never from user input.
133
+ ((p) => nodeReaddirSync(p));
134
+ const isDir = deps.isDirectory ??
135
+ ((p) => {
136
+ try {
137
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- as above.
138
+ return nodeStatSync(p).isDirectory();
139
+ }
140
+ catch {
141
+ return false;
142
+ }
143
+ });
144
+ const readFile = deps.readFileSync ??
145
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- as above.
146
+ ((p) => nodeReadFileSync(p, 'utf8'));
147
+ const out = detectCallerFromEnv(env);
148
+ const seen = new Set(out.map(d => d.target));
149
+ for (const target of Object.keys(TARGETS)) {
150
+ if (seen.has(target))
151
+ continue;
152
+ const rel = TRACE_PATHS[target];
153
+ const full = join(dir, rel);
154
+ if (!exists(full))
155
+ continue;
156
+ if (TARGETS[target].mode === 'managed-section') {
157
+ let content;
158
+ try {
159
+ content = readFile(full);
160
+ }
161
+ catch {
162
+ continue; // unreadable → claim nothing
163
+ }
164
+ if (!agentsFileHasForeignContent(content))
165
+ continue;
166
+ }
167
+ else if (!hasForeignContent(dir, target, rel, { readdirSync: readdir, isDirectory: isDir })) {
168
+ continue;
169
+ }
170
+ out.push({ target, source: 'trace', signal: rel });
171
+ seen.add(target);
172
+ }
173
+ return out;
174
+ }
175
+ /** Just the targets, for callers that do not report the evidence. */
176
+ export function detectedTargets(dir, deps = {}) {
177
+ return detectAgentTargets(dir, deps).map(d => d.target);
178
+ }
179
+ /** Installed when nothing is detected and the caller named no target. */
180
+ export const FALLBACK_TARGET = 'claude';
181
+ /**
182
+ * Which targets an install should cover: an explicit choice, else every agent
183
+ * detected in `dir`, else {@link FALLBACK_TARGET}.
184
+ */
185
+ export function resolveAgentTargets(explicit, dir, deps = {}) {
186
+ if (explicit)
187
+ return { targets: [explicit], source: 'flag', detections: [] };
188
+ const detections = detectAgentTargets(dir, deps);
189
+ if (detections.length === 0) {
190
+ return { targets: [FALLBACK_TARGET], source: 'fallback', detections };
191
+ }
192
+ return {
193
+ targets: detections.map(d => d.target),
194
+ source: detections.some(d => d.source === 'env') ? 'env' : 'trace',
195
+ detections,
196
+ };
197
+ }
198
+ //# sourceMappingURL=agent-detect.js.map
@@ -165,6 +165,15 @@ export interface RequestOptions<T = unknown> {
165
165
  * other callers.
166
166
  */
167
167
  retryOnRateLimit?: boolean;
168
+ /**
169
+ * Disable every automatic retry for a read whose caller owns its cadence.
170
+ *
171
+ * The borrowed-tunnel liveness probe is one such read: a failed observation
172
+ * is "unknown", and its next attempt belongs to the 15-second wall-clock
173
+ * schedule rather than an HTTP-layer retry burst. Defaults to `true` so all
174
+ * existing request paths retain their retry behaviour.
175
+ */
176
+ retry?: boolean;
168
177
  }
169
178
  /**
170
179
  * Result of a successful HTTP request, including the parsed body and the
@@ -348,6 +357,7 @@ export declare class HttpClient {
348
357
  */
349
358
  getTunnelStatus(clientId: string, options?: {
350
359
  signal?: AbortSignal;
360
+ retry?: boolean;
351
361
  }): Promise<TunnelStatusResponse>;
352
362
  /**
353
363
  * DELETE /api/cli/v1/tunnel/{clientId} — destroy a binding. 204, idempotent.
package/dist/lib/http.js CHANGED
@@ -334,6 +334,7 @@ export class HttpClient {
334
334
  async getTunnelStatus(clientId, options = {}) {
335
335
  return this.get(`/tunnel/${encodeURIComponent(clientId)}`, {
336
336
  signal: options.signal,
337
+ retry: options.retry,
337
338
  schema: TUNNEL_STATUS_RESPONSE_SCHEMA,
338
339
  });
339
340
  }
@@ -451,7 +452,8 @@ export class HttpClient {
451
452
  throw ApiError.authRequired();
452
453
  const url = buildUrl(this.baseUrl, path, options.query);
453
454
  const requestId = options.requestId ?? newRequestId();
454
- const allowTransportRetry = canRetryTransport(method, options);
455
+ const allowRetry = options.retry !== false;
456
+ const allowTransportRetry = allowRetry && canRetryTransport(method, options);
455
457
  let attempt = 0;
456
458
  while (true) {
457
459
  // Bail before issuing (or re-issuing after a retry sleep) a request the
@@ -698,7 +700,9 @@ export class HttpClient {
698
700
  });
699
701
  const retryOnConflict = options.retryOnConflict !== false;
700
702
  const retryOnRateLimit = options.retryOnRateLimit !== false;
701
- const decision = apiRetryDecision(apiError.code, attempt, retryAfterSec, this.random, retryOnConflict, retryOnRateLimit);
703
+ const decision = allowRetry
704
+ ? apiRetryDecision(apiError.code, attempt, retryAfterSec, this.random, retryOnConflict, retryOnRateLimit)
705
+ : { retry: false, delayMs: 0 };
702
706
  if (!decision.retry)
703
707
  throw apiError;
704
708
  const delaySec = Math.round(decision.delayMs / 1000);
@@ -142,6 +142,12 @@ export const TRIGGER_RUN_RESPONSE_SCHEMA = v.looseObject({
142
142
  enqueuedAt: v.string(),
143
143
  codeVersion: v.string(),
144
144
  targetUrl: v.string(),
145
+ // Server-built portal links (backend ≥ the run-links change). Optional
146
+ // with no default (rule 3): an older backend omits them, and a V3 run
147
+ // the server could not link stays ABSENT — the renderer prints a
148
+ // `dashboard` line only when the key is present.
149
+ dashboardUrl: v.optional(v.string()),
150
+ executionUrl: v.optional(v.string()),
145
151
  });
146
152
  // ---------------------------------------------------------------------------
147
153
  // POST /tests/{testId}/runs/rerun
@@ -185,6 +191,9 @@ export const RERUN_RESPONSE_SCHEMA = v.looseObject({
185
191
  // survives validation byte-identically). Older backends that predate the
186
192
  // field simply omit it — never fails validation.
187
193
  advisories: v.optional(v.array(RERUN_ADVISORY_SCHEMA)),
194
+ // Same present-or-absent portal links as TRIGGER_RUN_RESPONSE_SCHEMA.
195
+ dashboardUrl: v.optional(v.string()),
196
+ executionUrl: v.optional(v.string()),
188
197
  });
189
198
  // ---------------------------------------------------------------------------
190
199
  // POST /tests/batch/rerun
@@ -236,6 +245,11 @@ export const BATCH_RUN_FRESH_RESPONSE_SCHEMA = v.looseObject({
236
245
  deferred: v.array(v.looseObject({ testId: v.string() })),
237
246
  skippedFrontend: v.array(v.string()),
238
247
  skippedIntegration: v.array(v.looseObject({ testId: v.string() })),
248
+ // Project-level closing link. Absent-key-preserving like `RUN_RESPONSE_SCHEMA`'s
249
+ // `dashboardUrl` (see the note there): omitted stays ABSENT so the client
250
+ // keeps computing its legacy template for an older backend / the V2 engine;
251
+ // `null` passes through as a present key meaning "no correct page".
252
+ dashboardUrl: v.nullish(v.string(), undefined),
239
253
  });
240
254
  /**
241
255
  * `POST /api/cli/v1/testlist/{listId}/run`. Mirrors the batch-run-fresh shape so
@@ -89,6 +89,10 @@ export interface RerunResponse {
89
89
  * on every other response, including older backends that predate the field.
90
90
  */
91
91
  advisories?: RerunAdvisory[];
92
+ /** See `TriggerRunResponse.dashboardUrl` — same present-or-absent contract. */
93
+ dashboardUrl?: string;
94
+ /** See `TriggerRunResponse.executionUrl` — same present-or-absent contract. */
95
+ executionUrl?: string;
92
96
  }
93
97
  /**
94
98
  * Body sent to `POST /api/cli/v1/tests/batch/rerun`.
@@ -162,6 +166,18 @@ export interface TriggerRunResponse {
162
166
  codeVersion: string;
163
167
  /** Resolved target URL (project default when --target-url absent). */
164
168
  targetUrl: string;
169
+ /**
170
+ * Portal deep link for the run's test, built by the server for the store
171
+ * that dispatched it. Present-or-absent (never null): an older backend, a
172
+ * V3 run while the server's org-link flag is off, or one with no resolvable
173
+ * workspace all OMIT it, and the CLI prints nothing rather than guessing.
174
+ */
175
+ dashboardUrl?: string;
176
+ /**
177
+ * Portal deep link to THIS run's result page — V3-served runs only (a V2
178
+ * run has no execution page). Same present-or-absent contract.
179
+ */
180
+ executionUrl?: string;
165
181
  }
166
182
  /**
167
183
  * Public run-status values.
@@ -424,4 +440,14 @@ export interface BatchRunFreshResponse {
424
440
  skippedIntegration: Array<{
425
441
  testId: string;
426
442
  }>;
443
+ /**
444
+ * Project-level portal link the batch closes with ("watch it here"). Same
445
+ * absent-vs-present contract as the per-run `dashboardUrl`: ABSENT ⇒ an older
446
+ * backend (or the V2 engine, whose live page is the CLI's own
447
+ * `/dashboard/tests/{projectId}` template) — compute the legacy link
448
+ * client-side; a string ⇒ print it verbatim; `null` ⇒ the server knows no
449
+ * correct page exists (several sibling projects, no owning org) — print
450
+ * nothing rather than a dead link.
451
+ */
452
+ dashboardUrl?: string | null;
427
453
  }
@@ -1,3 +1,4 @@
1
+ import { type AgentTarget } from './agent-targets.js';
1
2
  import type { OutputMode } from './output.js';
2
3
  /**
3
4
  * Full command paths (group + leaf) that signal the caller is actively driving
@@ -41,13 +42,20 @@ export declare function isPlanTemplateInvocation(commandPath: string, planTempla
41
42
  export interface SkillPresenceDeps {
42
43
  existsSync?: (p: string) => boolean;
43
44
  readFileSync?: (p: string) => string;
45
+ /**
46
+ * Narrow the check to specific agents. Pass the agents actually calling: a
47
+ * skill installed for some OTHER agent is not one this caller can read, and
48
+ * treating it as installed is what makes the miss silent. Empty or omitted
49
+ * keeps the any-target answer, which is all an unidentified caller supports.
50
+ */
51
+ requiredTargets?: readonly AgentTarget[];
44
52
  }
45
53
  /**
46
- * True if the `testsprite-verify` skill is installed for ANY supported agent in
47
- * `dir`. own-file targets (claude/cursor/cline/antigravity): the landing file
48
- * exists. managed-section target (codex / AGENTS.md): the file exists AND
49
- * carries one complete managed section — a user-authored AGENTS.md without the
50
- * sentinels, or with a truncated section, does NOT count as our skill.
54
+ * True if the `testsprite-verify` skill is installed in `dir` — for any
55
+ * supported agent, or only for `deps.requiredTargets` when given. own-file
56
+ * targets: the landing file exists. managed-section target (codex / AGENTS.md):
57
+ * the file exists AND carries one complete managed section — a user-authored
58
+ * AGENTS.md without the sentinels, or with a truncated section, does NOT count.
51
59
  *
52
60
  * The TARGETS table is the single source of truth for landing paths, so this
53
61
  * stays in lockstep with `agent install` without re-listing paths. Best-effort:
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { MANAGED_SECTION_BEGIN, MANAGED_SECTION_END, TARGETS } from './agent-targets.js';
3
+ import { MANAGED_SECTION_BEGIN, MANAGED_SECTION_END, TARGETS, } from './agent-targets.js';
4
+ import { detectCallerFromEnv } from './agent-detect.js';
4
5
  import { defaultCredentialsPath, readProfile } from './credentials.js';
5
6
  /**
6
7
  * Full command paths (group + leaf) that signal the caller is actively driving
@@ -51,11 +52,11 @@ export function isPlanTemplateInvocation(commandPath, planTemplate) {
51
52
  return commandPath === 'test create' && planTemplate === true;
52
53
  }
53
54
  /**
54
- * True if the `testsprite-verify` skill is installed for ANY supported agent in
55
- * `dir`. own-file targets (claude/cursor/cline/antigravity): the landing file
56
- * exists. managed-section target (codex / AGENTS.md): the file exists AND
57
- * carries one complete managed section — a user-authored AGENTS.md without the
58
- * sentinels, or with a truncated section, does NOT count as our skill.
55
+ * True if the `testsprite-verify` skill is installed in `dir` — for any
56
+ * supported agent, or only for `deps.requiredTargets` when given. own-file
57
+ * targets: the landing file exists. managed-section target (codex / AGENTS.md):
58
+ * the file exists AND carries one complete managed section — a user-authored
59
+ * AGENTS.md without the sentinels, or with a truncated section, does NOT count.
59
60
  *
60
61
  * The TARGETS table is the single source of truth for landing paths, so this
61
62
  * stays in lockstep with `agent install` without re-listing paths. Best-effort:
@@ -64,7 +65,11 @@ export function isPlanTemplateInvocation(commandPath, planTemplate) {
64
65
  export function isVerifySkillInstalled(dir, deps = {}) {
65
66
  const exists = deps.existsSync ?? existsSync;
66
67
  const read = deps.readFileSync ?? ((p) => readFileSync(p, 'utf8'));
67
- for (const spec of Object.values(TARGETS)) {
68
+ const wanted = new Set(deps.requiredTargets ?? []);
69
+ const specs = Object.entries(TARGETS)
70
+ .filter(([target]) => wanted.size === 0 || wanted.has(target))
71
+ .map(([, spec]) => spec);
72
+ for (const spec of specs) {
68
73
  const full = join(dir, spec.path);
69
74
  if (!exists(full))
70
75
  continue;
@@ -117,16 +122,37 @@ export function maybeEmitSkillNudge(ctx) {
117
122
  const profile = lookup(ctx.profile, { path: credsPath });
118
123
  if (!profile?.apiKey)
119
124
  return;
120
- if (isVerifySkillInstalled(ctx.cwd, {
121
- existsSync: ctx.existsSync,
122
- readFileSync: ctx.readFileSync,
123
- })) {
125
+ const presence = { existsSync: ctx.existsSync, readFileSync: ctx.readFileSync };
126
+ // When the environment names the calling agent, only that agent's skill
127
+ // counts — an install for a different agent is one this caller cannot read.
128
+ //
129
+ // Checked PER caller and ANDed, never as one set. `isVerifySkillInstalled`
130
+ // answers "any of these targets", so handing it the whole set lets one
131
+ // satisfied caller hide another's miss: with both CLAUDECODE and
132
+ // CURSOR_AGENT present — a nested shell that still carries the outer
133
+ // agent's variable — a project wired only for claude would fall silent for
134
+ // cursor, which is the exact silent miss this check exists to remove.
135
+ const callers = detectCallerFromEnv(ctx.env).map(d => d.target);
136
+ const missing = callers.filter(target => !isVerifySkillInstalled(ctx.cwd, { ...presence, requiredTargets: [target] }));
137
+ if (callers.length > 0) {
138
+ if (missing.length === 0)
139
+ return;
140
+ }
141
+ else if (isVerifySkillInstalled(ctx.cwd, presence)) {
142
+ // No identified caller: the any-target answer is all this can support.
124
143
  return;
125
144
  }
126
145
  const write = ctx.stderr ?? ((line) => process.stderr.write(`${line}\n`));
127
- write('[warn] No TestSprite verification skill is installed in this project — your coding ' +
128
- 'agent will not verify its changes against TestSprite. Run `testsprite setup` (or ' +
129
- `\`testsprite agent install\`) to set it up. Silence: ${SKILL_NUDGE_OPT_OUT_ENV}=1`);
146
+ // Names the callers actually missing a skill, not every caller detected —
147
+ // with one of two satisfied, "not for cursor" is the actionable half and
148
+ // "not for claude or cursor" would be wrong about claude.
149
+ const forOtherAgent = missing.length > 0 && isVerifySkillInstalled(ctx.cwd, presence);
150
+ const subject = forOtherAgent
151
+ ? `The TestSprite verification skill is installed, but not for ${missing.join(' or ')}`
152
+ : 'No TestSprite verification skill is installed in this project';
153
+ write(`[warn] ${subject} — your coding agent will not verify its changes against ` +
154
+ 'TestSprite. Run `testsprite setup` (or `testsprite agent install`) to set it up. ' +
155
+ `Silence: ${SKILL_NUDGE_OPT_OUT_ENV}=1`);
130
156
  }
131
157
  catch {
132
158
  // A nudge must never break, delay, or alter the exit status of a real
@@ -24,6 +24,14 @@
24
24
  * - Reject IPv6 link-local (`fe80::/10`), unique-local (`fc00::/7`), and
25
25
  * deprecated site-local (`fec0::/10`)
26
26
  */
27
+ type TargetUrlHintContext = 'runtime' | 'bootstrap';
28
+ export interface TargetUrlCaller {
29
+ /** CLI flag name without the leading `--`, used in the error envelope. */
30
+ field: string;
31
+ /** Command prefix without `--help`, for example `testsprite project create`. */
32
+ helpCommand: string;
33
+ hintContext?: TargetUrlHintContext;
34
+ }
27
35
  /**
28
36
  * Throws a local `VALIDATION_ERROR` (exit 5) when `rawUrl` is a
29
37
  * disallowed target — localhost or a private/reserved literal IP. Also rejects
@@ -31,7 +39,7 @@
31
39
  *
32
40
  * Silently returns on allowed URLs.
33
41
  */
34
- export declare function assertNotLocal(rawUrl: string): void;
42
+ export declare function assertNotLocal(rawUrl: string, caller?: TargetUrlCaller): void;
35
43
  /**
36
44
  * One disallowed-address classification: the human-readable reason (used
37
45
  * verbatim in the rejection message — unchanged wording, not a new
@@ -77,3 +85,4 @@ export interface DisallowedIpClassification {
77
85
  * range list, not two drifting copies of it.
78
86
  */
79
87
  export declare function disallowedIpReason(host: string): DisallowedIpClassification | undefined;
88
+ export {};
@@ -33,7 +33,20 @@ import { ApiError } from './errors.js';
33
33
  // on `127.0.0.1`/`::1`, so `--local`'s default dial reaches it) — NOT for
34
34
  // the rest of `127.0.0.0/8`, which `--local` cannot dial by name at all. See
35
35
  // `'loopback-other'` below for that distinction.
36
- const LOCAL_DEV_HINT = "This looks like a local-dev target. Run it with `testsprite test run <test-id> --local <port>` instead — it tunnels this machine's loopback address to the test runner (frontend tests only; requires an API key with the `run:tunnel` scope).";
36
+ const LOCAL_DEV_RUNTIME_HINT = "This looks like a local-dev target. Run it with `testsprite test run <test-id> --local <port>` instead — it tunnels this machine's loopback address to the test runner (frontend tests only; requires an API key with the `run:tunnel` scope).";
37
+ // Project/test creation happens before the caller necessarily has a test id
38
+ // (and project create happens before they have a project at all). Lead those
39
+ // callers through the required public project URL first, then name the per-run
40
+ // loopback tunnel only after the test exists.
41
+ const LOCAL_DEV_BOOTSTRAP_HINT = "TestSprite executes tests from the cloud, so a project's URL must be an internet-reachable address the runner can use. " +
42
+ 'Set the project to its deployed or staging URL. ' +
43
+ 'After a test exists, target an app on this machine for an individual run with ' +
44
+ "`testsprite test run <test-id> --local <port>`; that tunnel is per-run and does not make localhost the project's URL.";
45
+ const DEFAULT_TARGET_URL_CALLER = {
46
+ field: 'target-url',
47
+ helpCommand: 'testsprite test run',
48
+ hintContext: 'runtime',
49
+ };
37
50
  // Private, reserved, link-local, and metadata addresses are network-reachable from
38
51
  // the caller's own machine in general (a LAN or VPN address usually answers)
39
52
  // — what is actually true, and all this hint claims, is that TestSprite's
@@ -51,17 +64,18 @@ const PRIVATE_NETWORK_HINT = 'This is a private/reserved network address (privat
51
64
  *
52
65
  * Silently returns on allowed URLs.
53
66
  */
54
- export function assertNotLocal(rawUrl) {
67
+ export function assertNotLocal(rawUrl, caller = DEFAULT_TARGET_URL_CALLER) {
68
+ const { field, helpCommand, hintContext = 'runtime' } = caller;
55
69
  let parsed;
56
70
  try {
57
71
  parsed = new URL(rawUrl);
58
72
  }
59
73
  catch {
60
- throw localTargetError('target-url', 'must be a valid URL');
74
+ throw localTargetError(field, 'must be a valid URL', helpCommand);
61
75
  }
62
76
  // Scheme check.
63
77
  if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
64
- throw localTargetError('target-url', 'must use http or https scheme');
78
+ throw localTargetError(field, 'must use http or https scheme', helpCommand);
65
79
  }
66
80
  // Normalize a single trailing dot in the hostname. `localhost.` is the
67
81
  // fully-qualified form of `localhost` (RFC 6761 reserves both to resolve to
@@ -75,13 +89,16 @@ export function assertNotLocal(rawUrl) {
75
89
  // `disallowedIpReason` below (which classifies IPv4/IPv6 address forms).
76
90
  // It is also always loopback — the same class `--local` can reach.
77
91
  if (host === 'localhost') {
78
- throw localTargetError('target-url', 'localhost targets are not allowed', LOCAL_DEV_HINT);
92
+ throw localTargetError(field, 'localhost targets are not allowed', helpCommand, localDevHintFor(hintContext));
79
93
  }
80
94
  const disallowed = disallowedIpReason(host);
81
95
  if (disallowed !== undefined) {
82
- throw localTargetError('target-url', disallowed.reason, hintFor(disallowed.hintKind));
96
+ throw localTargetError(field, disallowed.reason, helpCommand, hintFor(disallowed.hintKind, hintContext));
83
97
  }
84
98
  }
99
+ function localDevHintFor(hintContext) {
100
+ return hintContext === 'bootstrap' ? LOCAL_DEV_BOOTSTRAP_HINT : LOCAL_DEV_RUNTIME_HINT;
101
+ }
85
102
  /**
86
103
  * Map a classification's `hintKind` to the hint text `assertNotLocal` attaches
87
104
  * to the rejection — or no hint at all for `'loopback-other'`/`'undecided'`.
@@ -89,10 +106,10 @@ export function assertNotLocal(rawUrl) {
89
106
  * spot rather than a nested ternary repeated wherever a classification is
90
107
  * consumed.
91
108
  */
92
- function hintFor(hintKind) {
109
+ function hintFor(hintKind, hintContext) {
93
110
  switch (hintKind) {
94
111
  case 'loopback':
95
- return LOCAL_DEV_HINT;
112
+ return localDevHintFor(hintContext);
96
113
  case 'loopback-other':
97
114
  return undefined;
98
115
  case 'private':
@@ -339,14 +356,14 @@ function disallowedIpv6Reason(inner) {
339
356
  }
340
357
  return undefined;
341
358
  }
342
- function localTargetError(field, reason, hint) {
359
+ function localTargetError(field, reason, helpCommand, hint) {
343
360
  return ApiError.fromEnvelope({
344
361
  error: {
345
362
  code: 'VALIDATION_ERROR',
346
363
  message: `Field \`${field}\` is invalid: ${reason}.`,
347
364
  nextAction: hint
348
- ? hint + ' See `testsprite test run --help` for accepted values.'
349
- : `See \`testsprite test run --help\` for accepted values.`,
365
+ ? hint + ` See \`${helpCommand} --help\` for accepted values.`
366
+ : `See \`${helpCommand} --help\` for accepted values.`,
350
367
  requestId: 'local',
351
368
  details: { field, reason, ...(hint ? { hint } : {}) },
352
369
  },
@@ -54,7 +54,15 @@ export declare const DEFAULT_TUNNEL_CONNECT_TIMEOUT_MS = 20000;
54
54
  /** Maximum time teardown lets a wedged client delay credential deletion. */
55
55
  export declare const TUNNEL_CLIENT_STOP_TIMEOUT_MS = 2000;
56
56
  /** Why a tunnel stopped being usable for the run that was attached to it. */
57
- export type TunnelFatalReason = 'auth-failed';
57
+ export type TunnelFatalReason =
58
+ /** The server refused or dropped a client WE minted and connected. */
59
+ 'auth-failed'
60
+ /**
61
+ * A BORROWED client (`--tunnel-client`) is no longer registered. Different
62
+ * cause and different remedy from `auth-failed`: nobody disconnected us,
63
+ * the process that minted the tunnel stopped owning it.
64
+ */
65
+ | 'owner-gone';
58
66
  export interface TunnelSession {
59
67
  readonly clientId: string;
60
68
  readonly expiresAt: string;
@@ -110,8 +118,9 @@ export interface TunnelSessionDeps {
110
118
  }
111
119
  /**
112
120
  * Thrown when the tunnel a run depends on dies mid-run. `UNAVAILABLE` (exit
113
- * 10, "retry the command") rather than a run failure: the test did not fail,
114
- * the transport under it did, and re-running is the right next action.
121
+ * 10 rather than a run failure: the test did not fail, the transport under it
122
+ * did. An owned run can retry with a fresh tunnel; a borrowed run must inspect
123
+ * the already-started server-side run before deciding whether to retry.
115
124
  */
116
125
  export declare class TunnelLostError extends ApiError {
117
126
  constructor(reason: TunnelFatalReason, runId: string);
@@ -55,17 +55,34 @@ export const TUNNEL_CLIENT_STOP_TIMEOUT_MS = 2_000;
55
55
  const TUNNEL_SECRET_REDACTION = '[REDACTED]';
56
56
  /**
57
57
  * Thrown when the tunnel a run depends on dies mid-run. `UNAVAILABLE` (exit
58
- * 10, "retry the command") rather than a run failure: the test did not fail,
59
- * the transport under it did, and re-running is the right next action.
58
+ * 10 rather than a run failure: the test did not fail, the transport under it
59
+ * did. An owned run can retry with a fresh tunnel; a borrowed run must inspect
60
+ * the already-started server-side run before deciding whether to retry.
60
61
  */
61
62
  export class TunnelLostError extends ApiError {
62
63
  constructor(reason, runId) {
64
+ // Two different things go wrong here and they do NOT share a remedy.
65
+ // Telling a borrower to "run again" both hides the already-started billed
66
+ // run and is false about the tunnel — `--tunnel-client <id>` re-attaches
67
+ // to the same dead id and mints nothing. Naming the wrong cause is the
68
+ // failure mode this whole area keeps repeating, so each reason carries its
69
+ // own copy.
70
+ const ownerGone = reason === 'owner-gone';
63
71
  super({
64
72
  code: 'UNAVAILABLE',
65
- message: `The tunnel carrying run ${runId} was disconnected by the server and cannot be ` +
66
- `restored for this run (${reason}).`,
67
- nextAction: 'This usually means the tunnel service was redeployed mid-run. Start the run again: ' +
68
- 'the retry mints a fresh tunnel.',
73
+ message: ownerGone
74
+ ? `The borrowed tunnel for run ${runId} is no longer registered. It was minted by ` +
75
+ `another process (\`testsprite tunnel start\`), and that process has stopped or its ` +
76
+ `credential expired. Run ${runId} was left executing server-side and may still ` +
77
+ `finish; if it is cancelled, its verdict is discarded.`
78
+ : `The tunnel carrying run ${runId} was disconnected by the server and cannot be ` +
79
+ `restored for this run (${reason}).`,
80
+ nextAction: ownerGone
81
+ ? `Run ${runId} has lost its tunnel and cannot reach your app any more. Stop it now ` +
82
+ `with: testsprite test cancel ${runId} (idempotent). To watch it instead: ` +
83
+ `testsprite test wait ${runId} --timeout <s>.`
84
+ : 'This usually means the tunnel service was redeployed mid-run. Start the run again: ' +
85
+ 'the retry mints a fresh tunnel.',
69
86
  requestId: 'local',
70
87
  details: { reason, runId },
71
88
  });