@testsprite/testsprite-cli 0.15.0 → 0.17.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 (207) hide show
  1. package/README.md +53 -141
  2. package/dist/commands/agent.d.ts +12 -4
  3. package/dist/commands/agent.js +55 -65
  4. package/dist/commands/auth.d.ts +6 -10
  5. package/dist/commands/auth.js +44 -56
  6. package/dist/commands/ci.d.ts +23 -100
  7. package/dist/commands/ci.js +297 -489
  8. package/dist/commands/completion.js +2 -1
  9. package/dist/commands/conversation.d.ts +27 -0
  10. package/dist/commands/conversation.js +702 -0
  11. package/dist/commands/doctor.d.ts +5 -1
  12. package/dist/commands/doctor.js +130 -34
  13. package/dist/commands/init.d.ts +4 -45
  14. package/dist/commands/init.js +116 -68
  15. package/dist/commands/project-env.d.ts +62 -2
  16. package/dist/commands/project-env.js +426 -53
  17. package/dist/commands/project-sign-in.d.ts +0 -48
  18. package/dist/commands/project-sign-in.js +1 -224
  19. package/dist/commands/project.d.ts +15 -186
  20. package/dist/commands/project.js +93 -921
  21. package/dist/commands/result.d.ts +10 -0
  22. package/dist/commands/result.js +215 -0
  23. package/dist/commands/schedule.d.ts +0 -29
  24. package/dist/commands/schedule.js +47 -97
  25. package/dist/commands/test.d.ts +315 -1824
  26. package/dist/commands/test.js +1962 -13733
  27. package/dist/commands/testlist.d.ts +128 -5
  28. package/dist/commands/testlist.js +269 -329
  29. package/dist/commands/tunnel.d.ts +2 -2
  30. package/dist/commands/tunnel.js +43 -41
  31. package/dist/commands/usage.d.ts +12 -45
  32. package/dist/commands/usage.js +51 -131
  33. package/dist/index.js +189 -108
  34. package/dist/lib/agent-detect.js +9 -5
  35. package/dist/lib/agent-targets.d.ts +21 -2
  36. package/dist/lib/agent-targets.js +88 -11
  37. package/dist/lib/args.d.ts +13 -0
  38. package/dist/lib/args.js +49 -0
  39. package/dist/lib/basic-auth.d.ts +3 -0
  40. package/dist/lib/basic-auth.js +15 -0
  41. package/dist/lib/billing-refusal.js +4 -3
  42. package/dist/lib/ci-linkage.d.ts +4 -82
  43. package/dist/lib/ci-linkage.js +4 -157
  44. package/dist/lib/ci-run.js +1 -1
  45. package/dist/lib/client-factory.d.ts +10 -2
  46. package/dist/lib/client-factory.js +38 -26
  47. package/dist/lib/commit-signal.d.ts +65 -0
  48. package/dist/lib/commit-signal.js +305 -0
  49. package/dist/lib/concurrency-limiter.d.ts +6 -0
  50. package/dist/lib/concurrency-limiter.js +29 -0
  51. package/dist/lib/config.js +10 -5
  52. package/dist/lib/conflict-reason.d.ts +31 -4
  53. package/dist/lib/conflict-reason.js +38 -4
  54. package/dist/lib/conversation/answers.d.ts +9 -0
  55. package/dist/lib/conversation/answers.js +49 -0
  56. package/dist/lib/conversation/api.d.ts +71 -0
  57. package/dist/lib/conversation/api.js +150 -0
  58. package/dist/lib/conversation/change.d.ts +31 -0
  59. package/dist/lib/conversation/change.js +124 -0
  60. package/dist/lib/conversation/context.d.ts +19 -0
  61. package/dist/lib/conversation/context.js +70 -0
  62. package/dist/lib/conversation/environment.d.ts +15 -0
  63. package/dist/lib/conversation/environment.js +33 -0
  64. package/dist/lib/conversation/follow.d.ts +24 -0
  65. package/dist/lib/conversation/follow.js +42 -0
  66. package/dist/lib/conversation/render.d.ts +33 -0
  67. package/dist/lib/conversation/render.js +315 -0
  68. package/dist/lib/conversation/title.d.ts +2 -0
  69. package/dist/lib/conversation/title.js +18 -0
  70. package/dist/lib/conversation/types.d.ts +156 -0
  71. package/dist/lib/conversation/types.js +6 -0
  72. package/dist/lib/credentials.js +67 -11
  73. package/dist/lib/cron.d.ts +1 -1
  74. package/dist/lib/cron.js +2 -2
  75. package/dist/lib/dispatch-stop.d.ts +20 -0
  76. package/dist/lib/dispatch-stop.js +30 -0
  77. package/dist/lib/download.d.ts +71 -0
  78. package/dist/lib/download.js +274 -0
  79. package/dist/lib/dry-run/fetch.d.ts +10 -0
  80. package/dist/lib/dry-run/fetch.js +20 -0
  81. package/dist/lib/dry-run/samples.d.ts +6 -34
  82. package/dist/lib/dry-run/samples.js +389 -751
  83. package/dist/lib/environment-tunnel.d.ts +16 -26
  84. package/dist/lib/environment-tunnel.js +161 -157
  85. package/dist/lib/errors.d.ts +20 -4
  86. package/dist/lib/errors.js +36 -16
  87. package/dist/lib/facade.d.ts +7 -29
  88. package/dist/lib/facade.js +7 -36
  89. package/dist/lib/failing-fe-resolver.d.ts +13 -58
  90. package/dist/lib/failing-fe-resolver.js +47 -132
  91. package/dist/lib/first-suite-hint.d.ts +16 -22
  92. package/dist/lib/first-suite-hint.js +38 -47
  93. package/dist/lib/gh-output.d.ts +76 -21
  94. package/dist/lib/gh-output.js +171 -90
  95. package/dist/lib/git-utils.d.ts +56 -0
  96. package/dist/lib/git-utils.js +212 -0
  97. package/dist/lib/github-context.d.ts +2 -0
  98. package/dist/lib/github-context.js +40 -8
  99. package/dist/lib/history-retention.d.ts +6 -2
  100. package/dist/lib/history-retention.js +10 -7
  101. package/dist/lib/http.d.ts +58 -134
  102. package/dist/lib/http.js +352 -271
  103. package/dist/lib/interrupt.d.ts +14 -8
  104. package/dist/lib/interrupt.js +28 -10
  105. package/dist/lib/junit-report.d.ts +60 -4
  106. package/dist/lib/junit-report.js +209 -32
  107. package/dist/lib/local-target.d.ts +3 -3
  108. package/dist/lib/local-target.js +3 -3
  109. package/dist/lib/output.d.ts +0 -29
  110. package/dist/lib/output.js +10 -33
  111. package/dist/lib/pagination.d.ts +2 -5
  112. package/dist/lib/pagination.js +2 -5
  113. package/dist/lib/presigned-url.d.ts +22 -0
  114. package/dist/lib/presigned-url.js +90 -0
  115. package/dist/lib/prompt.js +36 -2
  116. package/dist/lib/proxy.js +2 -1
  117. package/dist/lib/redact.d.ts +2 -2
  118. package/dist/lib/redact.js +3 -4
  119. package/dist/lib/removed-commands.d.ts +18 -0
  120. package/dist/lib/removed-commands.js +154 -0
  121. package/dist/lib/render-error.d.ts +31 -6
  122. package/dist/lib/render-error.js +88 -25
  123. package/dist/lib/response-schemas.d.ts +38 -30
  124. package/dist/lib/response-schemas.js +210 -207
  125. package/dist/lib/result/api.d.ts +24 -0
  126. package/dist/lib/result/api.js +28 -0
  127. package/dist/lib/result/evidence.d.ts +71 -0
  128. package/dist/lib/result/evidence.js +420 -0
  129. package/dist/lib/result/render.d.ts +20 -0
  130. package/dist/lib/result/render.js +194 -0
  131. package/dist/lib/result/types.d.ts +122 -0
  132. package/dist/lib/result/types.js +19 -0
  133. package/dist/lib/run-output.d.ts +275 -0
  134. package/dist/lib/run-output.js +227 -0
  135. package/dist/lib/run-render.d.ts +101 -0
  136. package/dist/lib/run-render.js +183 -0
  137. package/dist/lib/run-wait.d.ts +192 -0
  138. package/dist/lib/run-wait.js +452 -0
  139. package/dist/lib/runs.types.d.ts +134 -367
  140. package/dist/lib/runs.types.js +0 -14
  141. package/dist/lib/secret-file.d.ts +1 -1
  142. package/dist/lib/secret-file.js +11 -2
  143. package/dist/lib/skill-nudge.d.ts +7 -27
  144. package/dist/lib/skill-nudge.js +9 -37
  145. package/dist/lib/target-path.d.ts +15 -0
  146. package/dist/lib/target-path.js +35 -0
  147. package/dist/lib/target-url-advisory.d.ts +19 -0
  148. package/dist/lib/target-url-advisory.js +31 -0
  149. package/dist/lib/target-url-preflight.d.ts +9 -0
  150. package/dist/lib/target-url-preflight.js +214 -106
  151. package/dist/lib/target-url.d.ts +1 -1
  152. package/dist/lib/target-url.js +6 -16
  153. package/dist/lib/telemetry.d.ts +32 -12
  154. package/dist/lib/telemetry.js +39 -8
  155. package/dist/lib/terminal-text.d.ts +41 -0
  156. package/dist/lib/terminal-text.js +127 -0
  157. package/dist/lib/testlist.types.d.ts +16 -8
  158. package/dist/lib/testlist.types.js +1 -1
  159. package/dist/lib/text-equality.d.ts +2 -0
  160. package/dist/lib/text-equality.js +5 -0
  161. package/dist/lib/text-file.d.ts +16 -0
  162. package/dist/lib/text-file.js +41 -0
  163. package/dist/lib/text-table.d.ts +46 -0
  164. package/dist/lib/text-table.js +72 -4
  165. package/dist/lib/ticker.d.ts +9 -2
  166. package/dist/lib/ticker.js +16 -3
  167. package/dist/lib/transport-failure.d.ts +22 -0
  168. package/dist/lib/transport-failure.js +126 -0
  169. package/dist/lib/tunnel-session.d.ts +7 -1
  170. package/dist/lib/tunnel-session.js +22 -9
  171. package/dist/lib/update-check.js +3 -2
  172. package/dist/lib/url-template.d.ts +43 -0
  173. package/dist/lib/url-template.js +151 -0
  174. package/dist/lib/validate.d.ts +0 -64
  175. package/dist/lib/validate.js +2 -131
  176. package/dist/lib/version-notice.js +4 -3
  177. package/dist/lib/wait-exit.d.ts +37 -2
  178. package/dist/lib/wait-exit.js +88 -30
  179. package/dist/lib/workspace-status.js +10 -2
  180. package/dist/version.d.ts +1 -1
  181. package/dist/version.js +1 -1
  182. package/package.json +3 -4
  183. package/skills/testsprite-ci.skill.md +48 -18
  184. package/skills/testsprite-onboard.skill.md +66 -151
  185. package/skills/testsprite-verify.codex.md +54 -56
  186. package/skills/testsprite-verify.skill.md +194 -358
  187. package/dist/lib/browser.d.ts +0 -6
  188. package/dist/lib/browser.js +0 -54
  189. package/dist/lib/bundle.d.ts +0 -234
  190. package/dist/lib/bundle.js +0 -781
  191. package/dist/lib/deprecate.d.ts +0 -10
  192. package/dist/lib/deprecate.js +0 -13
  193. package/dist/lib/flaky.d.ts +0 -91
  194. package/dist/lib/flaky.js +0 -71
  195. package/dist/lib/plan-poll.d.ts +0 -171
  196. package/dist/lib/plan-poll.js +0 -441
  197. package/dist/lib/plans.types.d.ts +0 -130
  198. package/dist/lib/plans.types.js +0 -31
  199. package/dist/lib/poll.d.ts +0 -100
  200. package/dist/lib/poll.js +0 -290
  201. package/dist/lib/rate-throttle.d.ts +0 -49
  202. package/dist/lib/rate-throttle.js +0 -75
  203. package/dist/lib/run-progress.d.ts +0 -41
  204. package/dist/lib/run-progress.js +0 -56
  205. package/dist/lib/v3-advisory.d.ts +0 -55
  206. package/dist/lib/v3-advisory.js +0 -74
  207. package/schemas/plan.schema.json +0 -61
@@ -16,10 +16,11 @@
16
16
  */
17
17
  import { ApiError, insufficientCreditsNextAction } from './errors.js';
18
18
  import { classifyBillingRefusal, isPausedReason } from './billing-refusal.js';
19
+ import { runLabel } from './run-render.js';
19
20
  /**
20
21
  * Short human label for a conflict's cause — the reason a case did NOT dispatch.
21
22
  * Absent reason renders as the legacy "already in flight" so an old backend's
22
- * bare `{testId, currentRunId?}` conflicts read exactly as they did before.
23
+ * bare `{testId, currentResultId?}` conflicts read exactly as they did before.
23
24
  */
24
25
  export function describeConflict(c) {
25
26
  switch (c.reason) {
@@ -34,11 +35,17 @@ export function describeConflict(c) {
34
35
  case 'paused':
35
36
  case 'billing_hold':
36
37
  return c.message || 'workspace paused';
38
+ case 'no_producer':
39
+ return c.message || 'no test case captures a variable it needs';
40
+ case 'producer_in_flight':
41
+ return c.message || 'its producer is running in another run';
37
42
  case 'error':
38
43
  return c.message || 'dispatch failed';
39
44
  case 'in_flight':
40
45
  default:
41
- return c.currentRunId ? `already in flight (run ${c.currentRunId})` : 'already in flight';
46
+ return c.currentResultId
47
+ ? `already in flight (${runLabel({ resultId: c.currentResultId, runId: c.currentRunId }, 'lower')})`
48
+ : 'already in flight';
42
49
  }
43
50
  }
44
51
  const CONFLICT_LABELS = {
@@ -49,6 +56,8 @@ const CONFLICT_LABELS = {
49
56
  insufficient_credits: 'insufficient credits',
50
57
  paused: 'workspace paused',
51
58
  billing_hold: 'workspace paused',
59
+ no_producer: 'no producer for its variables',
60
+ producer_in_flight: 'producer running in another run',
52
61
  error: 'dispatch error',
53
62
  };
54
63
  /**
@@ -71,6 +80,30 @@ function countByReason(conflicts) {
71
80
  }
72
81
  return counts;
73
82
  }
83
+ /**
84
+ * A backend consumer blocked before dispatch on a missing or busy producer.
85
+ * The CLI reports it as a refusal (exit 6), as a single `run` does,
86
+ * rather than polling the result the server seeded for it.
87
+ */
88
+ export function isProducerBlock(c) {
89
+ return c.reason === 'no_producer' || c.reason === 'producer_in_flight';
90
+ }
91
+ /**
92
+ * The retry advice for a set of refused test cases. A `no_producer` test case
93
+ * needs a producer, not a wait, so it gets its own line; every other reason
94
+ * keeps the caller's wait hint, given the ids it applies to.
95
+ */
96
+ export function conflictNextAction(conflicts, waitHint) {
97
+ const missing = conflicts.filter(c => c.reason === 'no_producer').map(c => c.testId);
98
+ const waiting = conflicts.filter(c => c.reason !== 'no_producer').map(c => c.testId);
99
+ const lines = [
100
+ waiting.length > 0 ? waitHint(waiting) : '',
101
+ missing.length > 0
102
+ ? `Add or accept a test case that captures the missing variable (or supply it from the environment), then retry: ${missing.join(' ')}`
103
+ : '',
104
+ ];
105
+ return lines.filter(Boolean).join('\n');
106
+ }
74
107
  /**
75
108
  * One-line summary of a conflict set grouped by reason, e.g.
76
109
  * `2 already in flight, 1 environment not runnable`. Used where a single line
@@ -78,9 +111,10 @@ function countByReason(conflicts) {
78
111
  */
79
112
  export function summarizeConflicts(conflicts) {
80
113
  // A future/unknown reason the loose wire schema admits (describeConflict covers
81
- // it via its default arm) must not render as "N undefined" here.
114
+ // it via its default arm) must not render as "N undefined" here. Callers wrap
115
+ // this in "not dispatched (…)", so the fallback must not say that again.
82
116
  return [...countByReason(conflicts).entries()]
83
- .map(([reason, n]) => `${n} ${CONFLICT_LABELS[reason] ?? 'not dispatched'}`)
117
+ .map(([reason, n]) => `${n} ${CONFLICT_LABELS[reason] ?? 'other'}`)
84
118
  .join(', ');
85
119
  }
86
120
  /**
@@ -0,0 +1,9 @@
1
+ import type { Question } from './types.js';
2
+ export declare const optionLetter: (index: number) => string;
3
+ /**
4
+ * The answers `apply --answer <n>=<choice>` gives a question card, keyed by
5
+ * each question's text as the portal's card sends them: an option's label,
6
+ * several labels joined by ", " when the question takes several, or the
7
+ * user's own words. Every question needs an answer, or the card keeps waiting.
8
+ */
9
+ export declare function answersFor(questions: Question[], given: string[]): Record<string, string>;
@@ -0,0 +1,49 @@
1
+ import { CLIError } from '../errors.js';
2
+ const LETTERS = 'abcdefghijklmnopqrstuvwxyz';
3
+ const LETTER_LIST = /^[a-z](\s*,\s*[a-z])*$/i;
4
+ export const optionLetter = (index) => LETTERS[index] ?? String(index + 1);
5
+ const invalid = (message) => new CLIError(message, 5, 'VALIDATION_ERROR');
6
+ /**
7
+ * The answers `apply --answer <n>=<choice>` gives a question card, keyed by
8
+ * each question's text as the portal's card sends them: an option's label,
9
+ * several labels joined by ", " when the question takes several, or the
10
+ * user's own words. Every question needs an answer, or the card keeps waiting.
11
+ */
12
+ export function answersFor(questions, given) {
13
+ const answers = new Map();
14
+ for (const raw of given) {
15
+ const at = raw.indexOf('=');
16
+ const index = at > 0 ? Number(raw.slice(0, at).trim()) : NaN;
17
+ const choice = at > 0 ? raw.slice(at + 1).trim() : '';
18
+ if (!Number.isInteger(index) || index < 1 || index > questions.length) {
19
+ throw invalid(`--answer ${raw}: questions are numbered 1 to ${questions.length}, as \`testsprite apply --answer <n>=<choice>\`.`);
20
+ }
21
+ if (!choice)
22
+ throw invalid(`--answer ${raw}: give an option's letter or your own words.`);
23
+ if (answers.has(index))
24
+ throw invalid(`--answer ${raw}: question ${index} is answered twice.`);
25
+ answers.set(index, answerTo(questions[index - 1], index, choice, raw));
26
+ }
27
+ const unanswered = questions.map((_, i) => i + 1).filter(n => !answers.has(n));
28
+ if (unanswered.length) {
29
+ throw invalid(`Answer ${unanswered.length === 1 ? 'question' : 'questions'} ${unanswered.join(', ')} too: \`testsprite apply ${questions.map((_, i) => `--answer ${i + 1}=<choice>`).join(' ')}\`. The card keeps waiting.`);
30
+ }
31
+ return Object.fromEntries(questions.map((q, i) => [q.question, answers.get(i + 1)]));
32
+ }
33
+ function answerTo(question, index, choice, raw) {
34
+ if (!LETTER_LIST.test(choice))
35
+ return choice;
36
+ const letters = choice.split(',').map(l => l.trim().toLowerCase());
37
+ const last = optionLetter(question.options.length - 1);
38
+ const labels = letters.map(letter => {
39
+ const option = question.options[LETTERS.indexOf(letter)];
40
+ if (!option)
41
+ throw invalid(`--answer ${raw}: question ${index} has options a to ${last}.`);
42
+ return option.label;
43
+ });
44
+ if (labels.length > 1 && !question.multiSelect) {
45
+ throw invalid(`--answer ${raw}: question ${index} takes one option.`);
46
+ }
47
+ return [...new Set(labels)].join(', ');
48
+ }
49
+ //# sourceMappingURL=answers.js.map
@@ -0,0 +1,71 @@
1
+ import type { FetchImpl, HttpClient } from '../http.js';
2
+ import { type ShutdownHandle } from '../interrupt.js';
3
+ import type { ApplyResult, Brief, Conversation, ConversationSummary } from './types.js';
4
+ import type { PlanEnvironment } from './environment.js';
5
+ /** The longest a follow request may be held by the server, in seconds. */
6
+ export declare const MAX_WAIT_SECONDS = 25;
7
+ export interface ConversationApi {
8
+ environments(projectId: string): Promise<PlanEnvironment[]>;
9
+ start(projectId: string, options: {
10
+ model?: string;
11
+ title?: string;
12
+ }): Promise<{
13
+ id: string;
14
+ url: string;
15
+ model: string;
16
+ }>;
17
+ list(projectId: string, limit?: number): Promise<ConversationSummary[]>;
18
+ get(projectId: string, id: string, follow?: {
19
+ afterSeq: number;
20
+ waitSeconds: number;
21
+ signal?: AbortSignal;
22
+ }): Promise<Conversation>;
23
+ upload(projectId: string, id: string, file: {
24
+ name: string;
25
+ contentType: string;
26
+ bytes: Uint8Array;
27
+ }): Promise<string>;
28
+ send(projectId: string, id: string, message: {
29
+ text: string;
30
+ files?: string[];
31
+ brief?: Brief;
32
+ }): Promise<void>;
33
+ /** Decides the card named, never whichever waits now; 409 when it was decided meanwhile. */
34
+ apply(projectId: string, id: string, choice: {
35
+ card: string;
36
+ only?: string[];
37
+ exclude?: string[];
38
+ /** For a secret card: what a person typed. Never a flag, never stored by the CLI. */
39
+ secrets?: {
40
+ value: string;
41
+ };
42
+ /** For a question card: the answer to each question, by the question's text. */
43
+ answers?: Record<string, string>;
44
+ /** For a run card: run on this environment instead of the one the card names, by name. */
45
+ environment?: string;
46
+ }): Promise<ApplyResult>;
47
+ reject(projectId: string, id: string, card: string, reason?: string): Promise<{
48
+ rejected: string;
49
+ }>;
50
+ /** `stopped` is false when the agent was not at work; older servers leave it out. */
51
+ stop(projectId: string, id: string): Promise<{
52
+ stopped?: boolean;
53
+ }>;
54
+ /** Stop the agent, turn down a waiting card, and put back what it changed and never saved. */
55
+ discard(projectId: string, id: string): Promise<{
56
+ discarded: string;
57
+ released: string[];
58
+ }>;
59
+ }
60
+ /**
61
+ * What a file's PUT to storage needs from the caller. That request goes around
62
+ * HttpClient, so it gets none of the client's deadline or Ctrl-C handling
63
+ * unless it is handed the same two things.
64
+ */
65
+ export interface StorageUploadOptions {
66
+ /** The longest one file's PUT may take: the per-request timeout the API calls run under. */
67
+ requestTimeoutMs: number;
68
+ /** Where Ctrl-C arrives. The process-wide one unless a test hands in its own. */
69
+ shutdown?: Pick<ShutdownHandle, 'signal' | 'arm'>;
70
+ }
71
+ export declare function conversationApi(client: HttpClient, fetchImpl: FetchImpl, storage: StorageUploadOptions): ConversationApi;
@@ -0,0 +1,150 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { ApiError, InterruptError, RequestTimeoutError } from '../errors.js';
3
+ import { globalShutdown } from '../interrupt.js';
4
+ import { assertSafePresignedUploadUrl } from '../presigned-url.js';
5
+ /** The longest a follow request may be held by the server, in seconds. */
6
+ export const MAX_WAIT_SECONDS = 25;
7
+ const base = (projectId) => `/projects/${encodeURIComponent(projectId)}/conversations`;
8
+ const one = (projectId, id) => `${base(projectId)}/${encodeURIComponent(id)}`;
9
+ const idempotent = () => ({ 'idempotency-key': randomUUID() });
10
+ export function conversationApi(client, fetchImpl, storage) {
11
+ return {
12
+ environments: async (projectId) => (await client.get(`/projects/${encodeURIComponent(projectId)}/env`)).environments,
13
+ start: (projectId, { model, title }) => client.post(base(projectId), {
14
+ body: {
15
+ ...(model ? { model } : {}),
16
+ ...(title ? { title } : {}),
17
+ },
18
+ headers: idempotent(),
19
+ }),
20
+ list: async (projectId, limit = 20) => (await client.get(base(projectId), {
21
+ query: { limit },
22
+ })).conversations,
23
+ get: (projectId, id, follow) => client.get(one(projectId, id), {
24
+ query: follow
25
+ ? { afterSeq: follow.afterSeq, waitSeconds: follow.waitSeconds || undefined }
26
+ : {},
27
+ signal: follow?.signal,
28
+ }),
29
+ async upload(projectId, id, file) {
30
+ // The mint only signs a URL for a path fixed by the conversation and the
31
+ // file name, and stores nothing, so asking again after a server error is
32
+ // harmless.
33
+ const minted = await client.post(`${one(projectId, id)}/files`, { body: { fileName: file.name, contentType: file.contentType }, replaySafe: true });
34
+ assertSafePresignedUploadUrl(minted.uploadUrl, client.resolvedBaseUrl);
35
+ await putToStorage(fetchImpl, minted.uploadUrl, file, storage);
36
+ return minted.name;
37
+ },
38
+ async send(projectId, id, message) {
39
+ await client.post(`${one(projectId, id)}/messages`, {
40
+ body: message,
41
+ headers: idempotent(),
42
+ retryOnConflict: false,
43
+ });
44
+ },
45
+ apply: (projectId, id, choice) => client.post(`${one(projectId, id)}/apply`, {
46
+ body: choice,
47
+ headers: idempotent(),
48
+ retryOnConflict: false,
49
+ }),
50
+ reject: (projectId, id, card, reason) => client.post(`${one(projectId, id)}/reject`, {
51
+ body: { card, ...(reason ? { reason } : {}) },
52
+ headers: idempotent(),
53
+ retryOnConflict: false,
54
+ }),
55
+ async stop(projectId, id) {
56
+ // A second stop finds the agent already stopped and nothing left waiting,
57
+ // so a server error is retried instead of failing the command, whose
58
+ // exit 1 would read as "the agent stopped".
59
+ const { stopped } = await client.post(`${one(projectId, id)}/stop`, {
60
+ body: {},
61
+ replaySafe: true,
62
+ });
63
+ return typeof stopped === 'boolean' ? { stopped } : {};
64
+ },
65
+ // Safe to send again after a server error: a second discard finds the card
66
+ // already turned down and the files already put back, and finishes whatever
67
+ // the first one left undone.
68
+ discard: (projectId, id) => client.post(`${one(projectId, id)}/discard`, {
69
+ body: {},
70
+ retryOnConflict: false,
71
+ replaySafe: true,
72
+ }),
73
+ };
74
+ }
75
+ function storageUnavailable(fileName, why) {
76
+ return new ApiError({
77
+ code: 'UNAVAILABLE',
78
+ message: `Uploading ${fileName} failed: ${why}.`,
79
+ nextAction: 'Nothing was sent to the agent. Run the command again.',
80
+ requestId: 'local',
81
+ details: { reason: 'presigned_put_failed', file: fileName },
82
+ });
83
+ }
84
+ /**
85
+ * PUT one file's bytes to the URL the server minted. Straight to storage,
86
+ * never through HttpClient, so the API key isn't sent there. Going around the
87
+ * client also means nothing else bounds this request: storage that stops
88
+ * answering would hold the command for as long as the connection stays open.
89
+ * So it gets the same per-request deadline as an API call (exit 7), and Ctrl-C
90
+ * aborts it (exit 130/143).
91
+ */
92
+ async function putToStorage(fetchImpl, uploadUrl, file, { requestTimeoutMs, shutdown = globalShutdown }) {
93
+ const controller = new AbortController();
94
+ const timer = setTimeout(() => controller.abort(), requestTimeoutMs);
95
+ const shutdownSignal = shutdown.signal;
96
+ const onShutdownAbort = () => controller.abort(shutdownSignal.reason);
97
+ // Armed for as long as the PUT runs: the signal handler does not track this
98
+ // request, and outside an armed scope it would end the process on the first
99
+ // Ctrl-C without letting the command unwind.
100
+ const disarm = shutdown.arm();
101
+ if (shutdownSignal.aborted)
102
+ onShutdownAbort();
103
+ else
104
+ shutdownSignal.addEventListener('abort', onShutdownAbort, { once: true });
105
+ try {
106
+ const response = await fetchImpl(uploadUrl, {
107
+ method: 'PUT',
108
+ headers: { 'content-type': file.contentType },
109
+ body: file.bytes,
110
+ // Only the minted URL was checked. Following a redirect would send the
111
+ // file to an address nothing looked at.
112
+ redirect: 'error',
113
+ signal: controller.signal,
114
+ });
115
+ // Only the status is used. Let go of the body without waiting for it, so
116
+ // storage that stalls after its headers can't keep the connection, and
117
+ // with it the process, open.
118
+ void response.body?.cancel().catch(() => undefined);
119
+ if (!response.ok) {
120
+ throw storageUnavailable(file.name, `storage answered HTTP ${response.status}`);
121
+ }
122
+ }
123
+ catch (cause) {
124
+ // Ctrl-C outranks the deadline: both abort the same request, and an
125
+ // interrupted upload must not be reported as a timeout.
126
+ if (cause instanceof InterruptError)
127
+ throw cause;
128
+ if (shutdownSignal.aborted)
129
+ throw shutdownSignal.reason;
130
+ if (cause instanceof ApiError)
131
+ throw cause;
132
+ // Past the Ctrl-C checks, only the deadline can have aborted the request.
133
+ if (controller.signal.aborted) {
134
+ const timedOut = new RequestTimeoutError(requestTimeoutMs);
135
+ timedOut.message = `Uploading ${file.name} timed out; nothing was sent to the agent. ${timedOut.message}`;
136
+ throw timedOut;
137
+ }
138
+ // A connection that failed, or a redirect refused above, is storage being
139
+ // unreachable, as a refusal is. Left raw it would end the command with
140
+ // exit 1, which these commands use to mean "the agent stopped".
141
+ const reason = cause instanceof Error ? cause.message : String(cause);
142
+ throw storageUnavailable(file.name, `network error before storage answered: ${reason}`);
143
+ }
144
+ finally {
145
+ clearTimeout(timer);
146
+ shutdownSignal.removeEventListener('abort', onShutdownAbort);
147
+ disarm();
148
+ }
149
+ }
150
+ //# sourceMappingURL=api.js.map
@@ -0,0 +1,31 @@
1
+ export type Git = (args: string[], cwd: string) => {
2
+ ok: boolean;
3
+ stdout: string;
4
+ };
5
+ export declare const runGit: Git;
6
+ export interface Repository {
7
+ root: string;
8
+ name?: string;
9
+ branch?: string;
10
+ commit?: string;
11
+ }
12
+ /** The git repository the CLI runs in, or null outside one. */
13
+ export declare function readRepository(cwd: string, git?: Git): Repository | null;
14
+ /** The most the change may weigh; past it, a closer base names a smaller change. */
15
+ export declare const MAX_CHANGE_BYTES: number;
16
+ export interface Change {
17
+ /** What the patch is taken against: a commit, or HEAD for uncommitted work only. */
18
+ base: string;
19
+ patch: string;
20
+ files: string[];
21
+ /** Files left out: they may hold secrets, are binary, or are too large to be source. */
22
+ left: string[];
23
+ }
24
+ /**
25
+ * The change being worked on, as one patch: everything since `base`
26
+ * (default: where this branch left the remote's default branch), committed or
27
+ * not, with new untracked files; minus files that may hold secrets, and with
28
+ * known credential formats blanked.
29
+ */
30
+ export declare function readChange(repo: Repository, base: string | undefined, git?: Git): Change;
31
+ export declare function blankSecrets(text: string): string;
@@ -0,0 +1,124 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { readFileSync, statSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { parseRepoSlug } from '../ci-linkage.js';
5
+ import { CLIError } from '../errors.js';
6
+ import { REDACTED } from '../redact.js';
7
+ export const runGit = (args, cwd) => {
8
+ const result = spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
9
+ return { ok: result.status === 0, stdout: result.stdout ?? '' };
10
+ };
11
+ /** The git repository the CLI runs in, or null outside one. */
12
+ export function readRepository(cwd, git = runGit) {
13
+ const root = git(['rev-parse', '--show-toplevel'], cwd);
14
+ if (!root.ok)
15
+ return null;
16
+ const at = root.stdout.trim();
17
+ const remote = git(['remote', 'get-url', 'origin'], at);
18
+ const branch = git(['rev-parse', '--abbrev-ref', 'HEAD'], at);
19
+ const commit = git(['rev-parse', '--short', 'HEAD'], at);
20
+ const name = remote.ok ? (parseRepoSlug(remote.stdout) ?? undefined) : undefined;
21
+ return {
22
+ root: at,
23
+ ...(name ? { name } : {}),
24
+ ...(branch.ok && branch.stdout.trim() !== 'HEAD' ? { branch: branch.stdout.trim() } : {}),
25
+ ...(commit.ok ? { commit: commit.stdout.trim() } : {}),
26
+ };
27
+ }
28
+ /** Files never sent, whatever the change: where keys and passwords are kept. */
29
+ const SECRET_FILE = /(^|\/)(\.env(\..*)?|.*\.(pem|key|p12|pfx|keystore|jks|secret)|id_(rsa|ed25519|ecdsa)(\.pub)?|\.npmrc|\.netrc|\.pypirc|(credentials|secrets)\.(json|ya?ml|toml)|service-account.*\.json)$/i;
30
+ /** Well-known credential formats, blanked wherever they appear in the change. */
31
+ const SECRET_VALUE = [
32
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
33
+ /\bAKIA[0-9A-Z]{16}\b/g,
34
+ /\bgh[pousr]_[A-Za-z0-9]{36,}\b/g,
35
+ /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g,
36
+ /\b[sr]k_live_[A-Za-z0-9]{16,}\b/g,
37
+ /\bsk-[A-Za-z0-9_-]{20,}\b/g,
38
+ /\bAIza[0-9A-Za-z_-]{35}\b/g,
39
+ ];
40
+ /** Untracked files larger than this are left out: a new feature is source, not data. */
41
+ const MAX_NEW_FILE_BYTES = 256 * 1024;
42
+ /** The most the change may weigh; past it, a closer base names a smaller change. */
43
+ export const MAX_CHANGE_BYTES = 5 * 1024 * 1024;
44
+ /**
45
+ * The change being worked on, as one patch: everything since `base`
46
+ * (default: where this branch left the remote's default branch), committed or
47
+ * not, with new untracked files; minus files that may hold secrets, and with
48
+ * known credential formats blanked.
49
+ */
50
+ export function readChange(repo, base, git = runGit) {
51
+ const from = base ?? defaultBase(repo.root, git);
52
+ const tracked = git(['diff', '--name-only', from, '--'], repo.root);
53
+ if (!tracked.ok) {
54
+ throw new CLIError(`Can't diff against ${from}: no such commit or branch here.`, 5, 'VALIDATION_ERROR');
55
+ }
56
+ const left = [];
57
+ const allowed = (path) => {
58
+ if (!SECRET_FILE.test(path))
59
+ return true;
60
+ left.push(path);
61
+ return false;
62
+ };
63
+ const trackedFiles = lines(tracked.stdout).filter(allowed);
64
+ const parts = [];
65
+ if (trackedFiles.length) {
66
+ const diff = git(['diff', '--no-color', '--no-ext-diff', from, '--', ...trackedFiles], repo.root);
67
+ if (diff.ok)
68
+ parts.push(diff.stdout);
69
+ }
70
+ const newFiles = [];
71
+ const untracked = git(['ls-files', '--others', '--exclude-standard'], repo.root);
72
+ for (const path of lines(untracked.stdout).filter(allowed)) {
73
+ const section = newFileSection(repo.root, path);
74
+ if (section === null)
75
+ left.push(path);
76
+ else {
77
+ parts.push(section);
78
+ newFiles.push(path);
79
+ }
80
+ }
81
+ const patch = blankSecrets(parts.join(''));
82
+ if (Buffer.byteLength(patch) > MAX_CHANGE_BYTES) {
83
+ throw new CLIError(`The change since ${from} is over ${MAX_CHANGE_BYTES / 1024 / 1024} MB. Name a closer base with --diff <commit>.`, 5, 'VALIDATION_ERROR');
84
+ }
85
+ return { base: from, patch, files: [...trackedFiles, ...newFiles], left };
86
+ }
87
+ /** A new file as a patch section, the way `git diff` shows one; null for a binary or large file. */
88
+ function newFileSection(root, path) {
89
+ const full = join(root, path);
90
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- an untracked file git lists in the user's own repository, read to attach it with the change.
91
+ if (statSync(full).size > MAX_NEW_FILE_BYTES)
92
+ return null;
93
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- an untracked file git lists in the user's own repository, read to attach it with the change.
94
+ const bytes = readFileSync(full);
95
+ if (bytes.includes(0))
96
+ return null;
97
+ const body = bytes.toString('utf8');
98
+ const content = body.endsWith('\n') ? body.slice(0, -1) : body;
99
+ const added = content === '' ? [] : content.split('\n');
100
+ return [
101
+ `diff --git a/${path} b/${path}`,
102
+ 'new file mode 100644',
103
+ '--- /dev/null',
104
+ `+++ b/${path}`,
105
+ ...(added.length ? [`@@ -0,0 +1,${added.length} @@`, ...added.map(l => `+${l}`)] : []),
106
+ '',
107
+ ].join('\n');
108
+ }
109
+ export function blankSecrets(text) {
110
+ return SECRET_VALUE.reduce((out, pattern) => out.replace(pattern, REDACTED), text);
111
+ }
112
+ function defaultBase(root, git) {
113
+ for (const remoteHead of ['origin/HEAD', 'origin/main', 'origin/master']) {
114
+ const forkPoint = git(['merge-base', 'HEAD', remoteHead], root);
115
+ if (forkPoint.ok && forkPoint.stdout.trim())
116
+ return forkPoint.stdout.trim();
117
+ }
118
+ return 'HEAD';
119
+ }
120
+ const lines = (text) => text
121
+ .split('\n')
122
+ .map(l => l.trim())
123
+ .filter(Boolean);
124
+ //# sourceMappingURL=change.js.map
@@ -0,0 +1,19 @@
1
+ export interface ContextDeps {
2
+ env?: NodeJS.ProcessEnv;
3
+ /** The folder the state lives in: the repository root, else the working directory. */
4
+ root: string;
5
+ }
6
+ /** `--project`, else `TESTSPRITE_PROJECT_ID`, else the project last worked on in this folder. */
7
+ export declare function resolveProjectId(flag: string | undefined, deps: ContextDeps): string;
8
+ /** Remember the project and its conversation for the next command run in this folder. */
9
+ export declare function rememberConversation(root: string, projectId: string, conversationId: string): void;
10
+ /**
11
+ * `--conversation`, else the one last started from this folder on the
12
+ * project. Never a guess: a conversation someone else is having, in the
13
+ * portal or another folder, is only ever reached by its id.
14
+ */
15
+ export declare function resolveConversationId(flag: string | undefined, projectId: string, deps: ContextDeps): string;
16
+ /** Remember the card a conversation showed here, so `apply` and `reject` decide that one. */
17
+ export declare function rememberCard(root: string, conversationId: string, cardId: string): void;
18
+ /** The card this folder last showed for a conversation, if any. */
19
+ export declare function shownCard(root: string, conversationId: string): string | undefined;
@@ -0,0 +1,70 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { ensureStateGitignore } from '../git-utils.js';
4
+ import { CLIError } from '../errors.js';
5
+ const STATE_DIR = '.testsprite';
6
+ const STATE_FILE = 'agent.json';
7
+ function readState(root) {
8
+ try {
9
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the CLI's own state under the folder it runs in, never a path from input.
10
+ const parsed = JSON.parse(readFileSync(join(root, STATE_DIR, STATE_FILE), 'utf8'));
11
+ return parsed && typeof parsed === 'object' ? parsed : {};
12
+ }
13
+ catch {
14
+ return {};
15
+ }
16
+ }
17
+ function writeState(root, state) {
18
+ const dir = join(root, STATE_DIR);
19
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the CLI's own state under the folder it runs in, never a path from input.
20
+ mkdirSync(dir, { recursive: true });
21
+ ensureStateGitignore(dir);
22
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the CLI's own state under the folder it runs in, never a path from input.
23
+ writeFileSync(join(dir, STATE_FILE), `${JSON.stringify(state, null, 2)}\n`);
24
+ }
25
+ /** `--project`, else `TESTSPRITE_PROJECT_ID`, else the project last worked on in this folder. */
26
+ export function resolveProjectId(flag, deps) {
27
+ const projectId = flag?.trim() ||
28
+ (deps.env ?? process.env).TESTSPRITE_PROJECT_ID?.trim() ||
29
+ readState(deps.root).projectId;
30
+ if (!projectId) {
31
+ throw new CLIError('No project. Pass --project <id> (see `testsprite project list`) or set TESTSPRITE_PROJECT_ID; ' +
32
+ 'this folder remembers it after that.', 5, 'VALIDATION_ERROR');
33
+ }
34
+ return projectId;
35
+ }
36
+ /** Remember the project and its conversation for the next command run in this folder. */
37
+ export function rememberConversation(root, projectId, conversationId) {
38
+ const state = readState(root);
39
+ writeState(root, {
40
+ ...state,
41
+ projectId,
42
+ conversations: { ...state.conversations, [projectId]: conversationId },
43
+ });
44
+ }
45
+ /**
46
+ * `--conversation`, else the one last started from this folder on the
47
+ * project. Never a guess: a conversation someone else is having, in the
48
+ * portal or another folder, is only ever reached by its id.
49
+ */
50
+ export function resolveConversationId(flag, projectId, deps) {
51
+ const id = flag?.trim() || readState(deps.root).conversations?.[projectId];
52
+ if (!id) {
53
+ throw new CLIError('No conversation was started from this folder on this project. Start one with ' +
54
+ '`testsprite plan "<what to test>"`, or name one with --conversation <id> ' +
55
+ '(`testsprite status --list` shows yours).', 5, 'VALIDATION_ERROR');
56
+ }
57
+ return id;
58
+ }
59
+ /** Remember the card a conversation showed here, so `apply` and `reject` decide that one. */
60
+ export function rememberCard(root, conversationId, cardId) {
61
+ const state = readState(root);
62
+ if (state.cards?.[conversationId] === cardId)
63
+ return;
64
+ writeState(root, { ...state, cards: { ...state.cards, [conversationId]: cardId } });
65
+ }
66
+ /** The card this folder last showed for a conversation, if any. */
67
+ export function shownCard(root, conversationId) {
68
+ return readState(root).cards?.[conversationId];
69
+ }
70
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1,15 @@
1
+ /** An environment as `GET /projects/{id}/env` lists it, as far as a plan needs it. */
2
+ export interface PlanEnvironment {
3
+ id?: string;
4
+ name: string;
5
+ url: string;
6
+ isDefault: boolean;
7
+ authMode: string;
8
+ hasCredentials: boolean;
9
+ }
10
+ /**
11
+ * What the caller should know before the agent starts on this environment:
12
+ * what its browser can't reach and what only a person can do there. Said up
13
+ * front so nobody learns it from a run that went half way.
14
+ */
15
+ export declare function environmentNotes(environment: PlanEnvironment): string[];
@@ -0,0 +1,33 @@
1
+ import { loopbackHost } from '../local-target.js';
2
+ import { terminalSafeLine } from '../terminal-text.js';
3
+ /**
4
+ * What the caller should know before the agent starts on this environment:
5
+ * what its browser can't reach and what only a person can do there. Said up
6
+ * front so nobody learns it from a run that went half way.
7
+ */
8
+ export function environmentNotes(environment) {
9
+ // Each note is one line naming the server's name and URL: each stays on it,
10
+ // so neither can start a line or take the words between them.
11
+ const name = terminalSafeLine(environment.name);
12
+ const notes = [];
13
+ let local = null;
14
+ try {
15
+ const url = new URL(environment.url);
16
+ if (loopbackHost(url.hostname) !== undefined)
17
+ local = { port: url.port };
18
+ }
19
+ catch {
20
+ local = null;
21
+ }
22
+ if (local) {
23
+ notes.push(`The "${name}" environment is on this machine (${terminalSafeLine(environment.url)}), which the agent's browser can't open: it works from your change and the project's files. Run what it saves here with \`testsprite run <test-id...> --local ${local.port || '<port>'}\`.`);
24
+ }
25
+ if (environment.authMode === 'manual') {
26
+ notes.push(`The "${name}" environment signs in by hand (single sign-on). The agent can't reuse that sign-in yet: it covers what it reaches without signing in, and a person can sign in once in the conversation's live browser.`);
27
+ }
28
+ else if (environment.authMode === 'account' && !environment.hasCredentials) {
29
+ notes.push(`The "${name}" environment has no test account stored, so the agent may only reach what needs no sign-in. A person adds one in the Portal (project → Settings → Environments → ${name}).`);
30
+ }
31
+ return notes;
32
+ }
33
+ //# sourceMappingURL=environment.js.map