@testsprite/testsprite-cli 0.7.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.
Files changed (74) hide show
  1. package/README.md +62 -45
  2. package/dist/commands/agent.d.ts +3 -0
  3. package/dist/commands/agent.js +79 -10
  4. package/dist/commands/ci.d.ts +88 -0
  5. package/dist/commands/ci.js +432 -0
  6. package/dist/commands/doctor.js +100 -1
  7. package/dist/commands/init.d.ts +45 -2
  8. package/dist/commands/init.js +198 -29
  9. package/dist/commands/project.d.ts +78 -0
  10. package/dist/commands/project.js +439 -5
  11. package/dist/commands/test.d.ts +193 -4
  12. package/dist/commands/test.js +1948 -398
  13. package/dist/commands/testlist.js +15 -9
  14. package/dist/commands/tunnel.d.ts +72 -0
  15. package/dist/commands/tunnel.js +367 -0
  16. package/dist/index.js +107 -38
  17. package/dist/lib/agent-detect.d.ts +53 -0
  18. package/dist/lib/agent-detect.js +198 -0
  19. package/dist/lib/dry-run/samples.d.ts +9 -0
  20. package/dist/lib/dry-run/samples.js +116 -0
  21. package/dist/lib/gh-output.d.ts +7 -0
  22. package/dist/lib/gh-output.js +50 -7
  23. package/dist/lib/http.d.ts +104 -0
  24. package/dist/lib/http.js +126 -7
  25. package/dist/lib/interrupt.d.ts +38 -13
  26. package/dist/lib/interrupt.js +130 -15
  27. package/dist/lib/local-target.d.ts +95 -0
  28. package/dist/lib/local-target.js +184 -0
  29. package/dist/lib/plan-poll.d.ts +171 -0
  30. package/dist/lib/plan-poll.js +442 -0
  31. package/dist/lib/plans.types.d.ts +130 -0
  32. package/dist/lib/plans.types.js +31 -0
  33. package/dist/lib/poll-support.d.ts +26 -0
  34. package/dist/lib/poll-support.js +65 -0
  35. package/dist/lib/poll.d.ts +1 -0
  36. package/dist/lib/poll.js +2 -40
  37. package/dist/lib/response-schemas.d.ts +13 -0
  38. package/dist/lib/response-schemas.js +46 -0
  39. package/dist/lib/run-progress.d.ts +41 -0
  40. package/dist/lib/run-progress.js +56 -0
  41. package/dist/lib/runs.types.d.ts +50 -0
  42. package/dist/lib/skill-nudge.d.ts +13 -5
  43. package/dist/lib/skill-nudge.js +40 -14
  44. package/dist/lib/target-url-preflight.js +3 -3
  45. package/dist/lib/target-url.d.ts +54 -8
  46. package/dist/lib/target-url.js +274 -68
  47. package/dist/lib/telemetry.d.ts +11 -0
  48. package/dist/lib/telemetry.js +1 -0
  49. package/dist/lib/ticker.d.ts +8 -0
  50. package/dist/lib/ticker.js +3 -0
  51. package/dist/lib/tunnel-session.d.ts +138 -0
  52. package/dist/lib/tunnel-session.js +249 -0
  53. package/dist/lib/tunnel.types.d.ts +54 -0
  54. package/dist/lib/tunnel.types.js +8 -0
  55. package/dist/vendor/tunnel-client/client.d.ts +82 -0
  56. package/dist/vendor/tunnel-client/client.js +924 -0
  57. package/dist/vendor/tunnel-client/config.d.ts +49 -0
  58. package/dist/vendor/tunnel-client/config.js +50 -0
  59. package/dist/vendor/tunnel-client/index.d.ts +9 -0
  60. package/dist/vendor/tunnel-client/index.js +9 -0
  61. package/dist/vendor/tunnel-client/lodash-lite.d.ts +14 -0
  62. package/dist/vendor/tunnel-client/lodash-lite.js +24 -0
  63. package/dist/vendor/tunnel-client/protocol.d.ts +60 -0
  64. package/dist/vendor/tunnel-client/protocol.js +143 -0
  65. package/dist/vendor/tunnel-client/types.d.ts +101 -0
  66. package/dist/vendor/tunnel-client/types.js +10 -0
  67. package/dist/vendor/tunnel-client/ws-compat.d.ts +206 -0
  68. package/dist/vendor/tunnel-client/ws-compat.js +316 -0
  69. package/dist/version.d.ts +1 -1
  70. package/dist/version.js +1 -1
  71. package/package.json +2 -1
  72. package/skills/testsprite-onboard.skill.md +60 -4
  73. package/skills/testsprite-verify.codex.md +22 -16
  74. package/skills/testsprite-verify.skill.md +27 -18
@@ -2,6 +2,8 @@
2
2
  * `testsprite init` — one-shot onboarding orchestrator.
3
3
  *
4
4
  * Chains, in order:
5
+ * 0. Agent-target resolution + confirmation prompt — the chosen install
6
+ * targets are settled here, before anything is written
5
7
  * 1. runConfigure — writes the API-key profile (validates via GET /me first)
6
8
  * 2. runWhoami — fetches identity for the post-configure banner
7
9
  * 3. runInstall — installs the TestSprite verification-loop skill (unless --no-agent)
@@ -13,11 +15,13 @@ import { Command } from 'commander';
13
15
  import { parseRequestTimeoutFlag, } from '../lib/client-factory.js';
14
16
  import { normalizeEnvVar } from '../lib/config.js';
15
17
  import { emitDeprecationNotice } from '../lib/deprecate.js';
16
- import { CLIError } from '../lib/errors.js';
18
+ import { CLIError, localValidationError } from '../lib/errors.js';
17
19
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
18
20
  import { runConfigure, runWhoami } from './auth.js';
19
21
  import { runInstall } from './agent.js';
20
22
  import { TARGETS, DEFAULT_SKILLS } from '../lib/agent-targets.js';
23
+ import { FALLBACK_TARGET, resolveAgentTargets, } from '../lib/agent-detect.js';
24
+ import { promptText } from '../lib/prompt.js';
21
25
  import { readProfile } from '../lib/credentials.js';
22
26
  /** Mirrors auth.ts's DEFAULT_API_URL (kept in sync; auth.ts owns the canonical value). */
23
27
  const DEFAULT_API_URL = 'https://api.testsprite.com';
@@ -41,6 +45,22 @@ function resolveReportedEndpoint(opts, deps) {
41
45
  }
42
46
  return opts.endpointUrl ?? envApiUrl ?? existing ?? DEFAULT_API_URL;
43
47
  }
48
+ /**
49
+ * Provenance for the summary. `env` and `trace` both collapse to `detected`
50
+ * because resolution is a union of the two signals — one word cannot honestly
51
+ * label a set whose members came from different ones. The split is carried
52
+ * per target in `detections`.
53
+ */
54
+ function agentProvenance(r) {
55
+ return {
56
+ detectedBy: r.source === 'flag' || r.source === 'fallback' ? r.source : 'detected',
57
+ detections: r.detections.map(d => ({
58
+ target: d.target,
59
+ source: d.source,
60
+ signal: d.signal,
61
+ })),
62
+ };
63
+ }
44
64
  /**
45
65
  * Collapse the per-skill install actions into one representative action for the
46
66
  * init summary. Precedence: a real change (updated) outranks a fresh install,
@@ -103,17 +123,119 @@ function toAgentDeps(deps, captureStdout) {
103
123
  function _suppressedStdout(_line) {
104
124
  // intentionally empty
105
125
  }
126
+ /**
127
+ * Say which agents the install covers and why. Silent when `--agent` named one
128
+ * (the caller already knows), and always says the fallback out loud — an
129
+ * unannounced fallback is how skills land where the calling agent cannot read
130
+ * them while the command still reports success.
131
+ */
132
+ function emitAgentResolutionNotice(resolution, stderrFn, willPrompt = false) {
133
+ if (resolution.source === 'flag')
134
+ return;
135
+ if (resolution.source === 'fallback') {
136
+ stderrFn(`[info] no coding agent detected in this project; installing for ${FALLBACK_TARGET}. ` +
137
+ `Pass --agent <target> to choose (${Object.keys(TARGETS).join(', ')}).`);
138
+ return;
139
+ }
140
+ const evidence = resolution.detections.map(d => `${d.target} (${d.signal})`).join(', ');
141
+ // When a prompt follows, the install set is not decided yet — saying
142
+ // "installing for X" here would read as a decision already taken.
143
+ if (willPrompt) {
144
+ stderrFn(`[info] detected ${evidence}`);
145
+ return;
146
+ }
147
+ stderrFn(`[info] detected ${evidence}; installing skills for ${resolution.targets.join(', ')}`);
148
+ }
149
+ /** Whether `confirmDetectedTargets` will actually ask. */
150
+ function shouldConfirmTargets(resolution, opts, isTTY) {
151
+ const fromDetection = resolution.source === 'env' || resolution.source === 'trace';
152
+ return fromDetection && isTTY && !opts.yes && !opts.dryRun && opts.output !== 'json';
153
+ }
154
+ const CONFIRM_TARGETS_MAX_ATTEMPTS = 3;
155
+ /**
156
+ * Let an operator see and edit the detected set before anything is written.
157
+ *
158
+ * Detection is a UNION of env and repo signals, so an ordinary repo carrying
159
+ * `AGENTS.md` plus a couple of agent config roots resolves to five targets and
160
+ * nine files — two of them shared, always-on rule files. `agent install`
161
+ * already asks when it has to choose; setup asking too keeps the two commands
162
+ * telling the same story.
163
+ *
164
+ * Returns the set to install, or `null` when the answer was `none` — the
165
+ * prompt's equivalent of `--no-agent`. Asks nothing when `--agent` named it
166
+ * (already explicit), on the fallback (one target, and the notice says so),
167
+ * under `--yes`, under `--dry-run` (nothing is written), off a TTY, or in JSON
168
+ * mode — a prompt there would corrupt the single-object stdout contract, the
169
+ * same reason the API-key prompt is refused in that mode.
170
+ *
171
+ * An unrecognised name is refused here and asked again, a bounded number of
172
+ * times. This runs before credentials are written, so a typo costs a retry
173
+ * rather than a half-finished setup that exits 5 after the key was saved.
174
+ */
175
+ async function confirmDetectedTargets(resolution, opts, isTTY, stderrFn, promptFn) {
176
+ if (!shouldConfirmTargets(resolution, opts, isTTY)) {
177
+ return [...resolution.targets];
178
+ }
179
+ const suggestion = resolution.targets.join(',');
180
+ const validTargets = Object.keys(TARGETS);
181
+ const ask = promptFn ?? ((q) => promptText(q));
182
+ for (let attempt = 1; attempt <= CONFIRM_TARGETS_MAX_ATTEMPTS; attempt++) {
183
+ const answer = (await ask(`Install skills for (comma-separated, or "none" to skip) [${suggestion}]: `)).trim();
184
+ if (answer.toLowerCase() === 'none')
185
+ return null;
186
+ // Lower-cased for the same reason `none` is: every target name is lower
187
+ // case, so `Claude` is a typo only in the sense that the shift key was
188
+ // down. Refusing it while accepting `NONE` would be an inconsistency the
189
+ // user has no way to predict.
190
+ const chosen = (answer || suggestion)
191
+ .split(',')
192
+ .map((s) => s.trim().toLowerCase())
193
+ .filter(Boolean);
194
+ // An answer of only separators ("," / ", ,") parses to nothing. Treat it as
195
+ // the empty answer it effectively is rather than installing for no target.
196
+ if (chosen.length === 0)
197
+ return [...resolution.targets];
198
+ const unknown = chosen.filter(t => !validTargets.includes(t));
199
+ if (unknown.length === 0)
200
+ return [...new Set(chosen)];
201
+ stderrFn(`[warn] unknown target ${unknown.map(t => `"${t}"`).join(', ')}; ` +
202
+ `supported: ${validTargets.join(', ')} (or "none" to skip)`);
203
+ }
204
+ throw new CLIError(`No recognised agent target after ${CONFIRM_TARGETS_MAX_ATTEMPTS} attempts. ` +
205
+ `Re-run with --agent <target> (${validTargets.join(', ')}) or --no-agent.`, 5);
206
+ }
106
207
  // ---------------------------------------------------------------------------
107
208
  // runInit
108
209
  // ---------------------------------------------------------------------------
109
210
  export async function runInit(opts, deps = {}) {
110
211
  const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
111
212
  const out = new Output(opts.output, { stdout: deps.stdout, stderr: deps.stderr });
213
+ // An unknown --agent is refused here, before credentials are written. Left
214
+ // to runInstall it surfaced as a `--target` error — a flag this command does
215
+ // not have — after the key was already saved, with a hint echoing the bad
216
+ // value back.
217
+ const validTargets = Object.keys(TARGETS);
218
+ if (opts.agent !== undefined && !opts.noAgent && !validTargets.includes(opts.agent)) {
219
+ throw localValidationError('agent', `unknown target "${opts.agent}"; supported: ${validTargets.join(', ')}`);
220
+ }
221
+ // -------------------------------------------------------------------------
222
+ // Which agents to install for: an explicit --agent, else whatever this repo
223
+ // shows, else the fallback. Resolved before any output so every branch below
224
+ // (conflict warning, dry-run preview, real install) reports the same set.
225
+ // -------------------------------------------------------------------------
226
+ let resolution = opts.noAgent
227
+ ? null
228
+ : resolveAgentTargets(opts.agent, opts.dir ?? deps.cwd ?? process.cwd(), {
229
+ env: deps.env,
230
+ ...deps.detect,
231
+ });
112
232
  // -------------------------------------------------------------------------
113
233
  // Fix 5: emit conflict warning when both --agent and --no-agent were given
114
234
  // -------------------------------------------------------------------------
115
235
  if (opts.rawArgConflict) {
116
- const effectiveLabel = opts.noAgent ? '--no-agent' : `--agent ${opts.agent}`;
236
+ const effectiveLabel = opts.noAgent
237
+ ? '--no-agent'
238
+ : `--agent ${opts.agent ?? resolution?.targets.join(',')}`;
117
239
  stderrFn(`[warn] both --no-agent and --agent supplied; using ${effectiveLabel} (last flag wins)`);
118
240
  }
119
241
  // -------------------------------------------------------------------------
@@ -141,6 +263,28 @@ export async function runInit(opts, deps = {}) {
141
263
  throw new CLIError('Interactive API-key prompt is unavailable in --output json mode (it would corrupt JSON stdout). ' +
142
264
  'Pass --api-key <key> or --from-env.', 5);
143
265
  }
266
+ // Announced only once the guards above have passed — otherwise a `--yes` with
267
+ // no key source printed "detected …" and then exited 5, describing an install
268
+ // that was never going to happen.
269
+ let agentSkippedBy = opts.noAgent ? 'flag' : undefined;
270
+ if (resolution) {
271
+ const willPrompt = shouldConfirmTargets(resolution, opts, isTTY);
272
+ emitAgentResolutionNotice(resolution, stderrFn, willPrompt);
273
+ // A detected set is confirmable before it lands; every other case passes
274
+ // through untouched. Narrowed here so every downstream reader — the install
275
+ // call, the summary, the failure hint — sees the set actually chosen.
276
+ const confirmed = await confirmDetectedTargets(resolution, opts, isTTY, stderrFn, deps.agentPrompt);
277
+ if (confirmed === null) {
278
+ stderrFn('[info] skipping the agent skill install (answered "none")');
279
+ resolution = null;
280
+ agentSkippedBy = 'prompt';
281
+ }
282
+ else {
283
+ resolution = { ...resolution, targets: confirmed };
284
+ if (willPrompt)
285
+ stderrFn(`[info] installing skills for ${confirmed.join(', ')}`);
286
+ }
287
+ }
144
288
  // -------------------------------------------------------------------------
145
289
  // Dry-run: zero network + zero FS writes; print preview only
146
290
  // -------------------------------------------------------------------------
@@ -153,13 +297,12 @@ export async function runInit(opts, deps = {}) {
153
297
  : opts.skipIfConfigured
154
298
  ? 'skip-if-configured'
155
299
  : 'prompt'})`);
156
- const agentTarget = opts.noAgent ? null : opts.agent;
157
- if (!opts.noAgent) {
300
+ if (resolution) {
158
301
  // Delegate to runInstall's own dry-run for the file-listing preview.
159
302
  // runInstall prints the would-write lines itself under dryRun.
160
303
  await runInstall({
161
304
  ...opts,
162
- target: [agentTarget],
305
+ target: resolution.targets,
163
306
  force: opts.force,
164
307
  dir: opts.dir,
165
308
  }, toAgentDeps(deps));
@@ -169,8 +312,14 @@ export async function runInit(opts, deps = {}) {
169
312
  apiUrl: resolveReportedEndpoint(opts, deps),
170
313
  env: 'development',
171
314
  scopes: [],
172
- agent: agentTarget
173
- ? { target: agentTarget, action: 'dry-run', skills: [...DEFAULT_SKILLS] }
315
+ agent: resolution
316
+ ? {
317
+ target: resolution.targets[0],
318
+ targets: [...resolution.targets],
319
+ ...agentProvenance(resolution),
320
+ action: 'dry-run',
321
+ skills: [...DEFAULT_SKILLS],
322
+ }
174
323
  : null,
175
324
  status: 'initialized',
176
325
  };
@@ -225,10 +374,10 @@ export async function runInit(opts, deps = {}) {
225
374
  // -------------------------------------------------------------------------
226
375
  // Step 3: Agent skill install (unless --no-agent)
227
376
  // -------------------------------------------------------------------------
228
- let installedTarget = null;
377
+ let installedTargets = null;
229
378
  let installedAction = null;
230
379
  let installedSkills = [];
231
- if (!opts.noAgent) {
380
+ if (resolution) {
232
381
  // Run install in JSON mode internally so we can reliably parse the result
233
382
  // regardless of the outer --output flag. The stdout is captured here and
234
383
  // NOT forwarded — runInit owns the output surface. setup installs the full
@@ -250,12 +399,12 @@ export async function runInit(opts, deps = {}) {
250
399
  await runInstall({
251
400
  ...opts,
252
401
  output: 'json', // parse the result; final summary is ours to print
253
- target: [opts.agent],
402
+ target: resolution.targets,
254
403
  // skills omitted → runInstall installs DEFAULT_SKILLS (verify + onboard)
255
404
  force: opts.force,
256
405
  dir: opts.dir,
257
406
  }, toAgentDeps(deps, captureStdout));
258
- installedTarget = opts.agent;
407
+ installedTargets = [...resolution.targets];
259
408
  installedAction =
260
409
  capturedInstallResults.length > 0
261
410
  ? aggregateInstallAction(capturedInstallResults.map(r => r.action))
@@ -268,17 +417,19 @@ export async function runInit(opts, deps = {}) {
268
417
  // Emit a clear summary line BEFORE re-throwing so the user knows their
269
418
  // API key was persisted — only the agent skill step failed (Fix 6).
270
419
  stderrFn(`[info] credentials saved for profile "${opts.profile}"; only the agent skill install failed — ` +
271
- `re-run 'testsprite agent install --target ${opts.agent}' after fixing the path`);
420
+ `re-run 'testsprite agent install --target ${resolution.targets.join(',')}' after fixing the path`);
272
421
  throw installErr;
273
422
  }
274
423
  }
275
424
  // -------------------------------------------------------------------------
276
425
  // Step 4: Summary
277
426
  // -------------------------------------------------------------------------
278
- const agentSummary = opts.noAgent || installedTarget === null
427
+ const agentSummary = resolution === null || installedTargets === null
279
428
  ? null
280
429
  : {
281
- target: installedTarget,
430
+ target: installedTargets[0],
431
+ targets: installedTargets,
432
+ ...agentProvenance(resolution),
282
433
  action: installedAction ?? 'installed',
283
434
  skills: installedSkills.length > 0 ? installedSkills : [...DEFAULT_SKILLS],
284
435
  };
@@ -291,6 +442,7 @@ export async function runInit(opts, deps = {}) {
291
442
  email: me.email,
292
443
  scopes: me.scopes,
293
444
  agent: agentSummary,
445
+ ...(agentSummary === null && agentSkippedBy ? { agentSkippedBy } : {}),
294
446
  status: 'initialized',
295
447
  };
296
448
  out.print(summary, renderInitText);
@@ -312,15 +464,26 @@ function renderInitText(data) {
312
464
  lines.push(` scopes: ${s.scopes.join(', ')}`);
313
465
  lines.push('');
314
466
  if (s.agent) {
315
- lines.push(` agent: ${s.agent.target} (${s.agent.action})`);
467
+ const targets = s.agent.targets.length > 0 ? s.agent.targets : [s.agent.target];
468
+ lines.push(` agent: ${targets.join(', ')} (${s.agent.action})`);
316
469
  if (s.agent.skills && s.agent.skills.length > 0) {
317
470
  lines.push(` skills: ${s.agent.skills.join(', ')}`);
318
471
  }
319
472
  }
320
473
  else {
321
- lines.push(' agent: skipped (--no-agent)');
474
+ lines.push(s.agentSkippedBy === 'prompt'
475
+ ? ' agent: skipped (answered "none" at the prompt)'
476
+ : ' agent: skipped (--no-agent)');
322
477
  }
323
478
  lines.push('');
479
+ // DEV-279: an agent session already open when the skills landed won't re-read
480
+ // them. `agent install` emits the same line on stderr; setup owns its summary,
481
+ // so it goes here. Only when bytes actually changed — `aggregateInstallAction`
482
+ // reports 'installed'/'updated' for that, 'dry-run'/'skipped' otherwise.
483
+ if (s.agent && (s.agent.action === 'installed' || s.agent.action === 'updated')) {
484
+ lines.push(` [hint] Reopen (or restart) your coding agent (${s.agent.target}) so it picks up the newly installed TestSprite skill(s).`);
485
+ lines.push('');
486
+ }
324
487
  lines.push('Next steps:');
325
488
  lines.push(' # 1. Create your first project (frontend example) — prints a projectId');
326
489
  lines.push(' testsprite project create --type frontend --name "My App" --url https://your-app.com');
@@ -361,12 +524,18 @@ function resolveCommonOptions(command) {
361
524
  };
362
525
  }
363
526
  const SETUP_DESCRIPTION = 'Set up TestSprite: configure your API key and install the TestSprite agent skills for your coding agent';
364
- /** Attach the onboarding flags shared by `setup` and the `init`/`auth configure` aliases. */
527
+ /**
528
+ * Attach the onboarding flags shared by `setup` and the `init`/`auth configure`
529
+ * aliases. `--agent` deliberately carries NO default: its absence is the signal
530
+ * that setup should detect the agent, and a default value here is
531
+ * indistinguishable from the caller naming that same target.
532
+ */
365
533
  export function addSetupOptions(cmd, validTargets, defaultAgent) {
366
534
  return cmd
367
535
  .option('--api-key <key>', 'API key to configure (skips the interactive prompt)')
368
536
  .option('--from-env', 'Read TESTSPRITE_API_KEY from the environment instead of prompting', false)
369
- .option('--agent <target>', `Coding-agent target to install: ${validTargets.join(', ')} (default: ${defaultAgent})`, defaultAgent)
537
+ .option('--agent <target>', `Coding-agent target to install: ${validTargets.join(', ')} ` +
538
+ `(default: every agent detected in this project, or ${defaultAgent} if none)`)
370
539
  .option('--no-agent', 'Skip the agent skill install (configure credentials only)')
371
540
  .option('--force', 'Overwrite an existing skill file (a .bak backup is kept)')
372
541
  .option('--dir <path>', 'Project root for the skill install (default: current directory)')
@@ -374,13 +543,10 @@ export function addSetupOptions(cmd, validTargets, defaultAgent) {
374
543
  .option('--skip-if-configured', 'Skip the API key prompt when credentials already exist for this profile (CI-safe idempotent re-run)');
375
544
  }
376
545
  /** Build {@link InitOptions} from raw Commander opts + globals. */
377
- function buildSetupOptions(cmdOpts, command, defaultAgent) {
546
+ function buildSetupOptions(cmdOpts, command) {
378
547
  const common = resolveCommonOptions(command);
379
548
  // Commander sets `agent: false` (boolean) when `--no-agent` is passed,
380
- // because `--no-agent` is the negation of `--agent <target>`. Guard against
381
- // this: if agent is falsy (false or empty string) default to the CLI default
382
- // so runInstall never receives a non-string target.
383
- const resolvedAgent = cmdOpts.agent && typeof cmdOpts.agent === 'string' ? cmdOpts.agent : defaultAgent;
549
+ // because `--no-agent` is the negation of `--agent <target>`.
384
550
  const isNoAgent = cmdOpts.noAgent === true || cmdOpts.agent === false;
385
551
  // Detect conflict when both --no-agent and --agent <target> appear in the raw
386
552
  // args. Commander only populates `rawArgs` on the ROOT command passed to
@@ -394,11 +560,14 @@ function buildSetupOptions(cmdOpts, command, defaultAgent) {
394
560
  const rawArgs = root.rawArgs ?? process.argv;
395
561
  const rawArgConflict = rawArgs.some((a) => a === '--no-agent') &&
396
562
  rawArgs.some((a) => a === '--agent' || a.startsWith('--agent='));
563
+ // Only a real `--agent <target>` reaches runInit. Left undefined otherwise, so
564
+ // setup detects instead of installing for a target nobody asked for.
565
+ const chosenAgent = typeof cmdOpts.agent === 'string' && cmdOpts.agent ? cmdOpts.agent : undefined;
397
566
  return {
398
567
  ...common,
399
568
  apiKey: cmdOpts.apiKey,
400
569
  fromEnv: Boolean(cmdOpts.fromEnv),
401
- agent: resolvedAgent,
570
+ agent: chosenAgent,
402
571
  noAgent: isNoAgent,
403
572
  force: Boolean(cmdOpts.force),
404
573
  dir: cmdOpts.dir,
@@ -408,8 +577,8 @@ function buildSetupOptions(cmdOpts, command, defaultAgent) {
408
577
  };
409
578
  }
410
579
  /** Shared action for `setup` and the deprecated `init` alias. */
411
- async function runSetupAction(cmdOpts, command, deps, defaultAgent) {
412
- const opts = buildSetupOptions(cmdOpts, command, defaultAgent);
580
+ async function runSetupAction(cmdOpts, command, deps) {
581
+ const opts = buildSetupOptions(cmdOpts, command);
413
582
  // When --yes is supplied without a key source, force isTTY=false so runInit
414
583
  // emits exit 5 with a clear message rather than hanging on a prompt in a
415
584
  // headless CI environment where a TTY fd happens to be open.
@@ -426,7 +595,7 @@ export function createSetupCommand(deps = {}) {
426
595
  .description(SETUP_DESCRIPTION)
427
596
  .addHelpText('after', GLOBAL_OPTS_HINT)
428
597
  .action(async (cmdOpts, command) => {
429
- await runSetupAction(cmdOpts, command, deps, defaultAgent);
598
+ await runSetupAction(cmdOpts, command, deps);
430
599
  });
431
600
  }
432
601
  /**
@@ -442,7 +611,7 @@ export function createDeprecatedInitCommand(deps = {}) {
442
611
  .description('(deprecated) alias for `setup`')
443
612
  .action(async (cmdOpts, command) => {
444
613
  emitDeprecationNotice('init', 'setup', deps.stderr);
445
- await runSetupAction(cmdOpts, command, deps, defaultAgent);
614
+ await runSetupAction(cmdOpts, command, deps);
446
615
  });
447
616
  }
448
617
  /**
@@ -458,6 +627,6 @@ export function createDeprecatedInitCommand(deps = {}) {
458
627
  * `addSetupOptions` before wiring this action.
459
628
  */
460
629
  export async function runConfigureViaSetup(command, deps, cmdOpts) {
461
- await runSetupAction(cmdOpts, command, deps, 'claude');
630
+ await runSetupAction(cmdOpts, command, deps);
462
631
  }
463
632
  //# sourceMappingURL=init.js.map
@@ -1,6 +1,7 @@
1
1
  import { Command } from 'commander';
2
2
  import { type CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
3
3
  import type { FetchImpl } from '../lib/http.js';
4
+ import { type ShutdownHandle } from '../lib/interrupt.js';
4
5
  import { type Page } from '../lib/pagination.js';
5
6
  export interface CliProject {
6
7
  id: string;
@@ -48,6 +49,8 @@ export interface ProjectDeps {
48
49
  fetchImpl?: FetchImpl;
49
50
  stdout?: (line: string) => void;
50
51
  stderr?: (line: string) => void;
52
+ /** Graceful-detach coordinator (DEV-331); tests inject their own. */
53
+ shutdown?: ShutdownHandle;
51
54
  }
52
55
  type CommonOptions = FactoryCommonOptions;
53
56
  interface ListOptions extends CommonOptions {
@@ -215,5 +218,80 @@ interface AutoAuthOptions extends CommonOptions {
215
218
  idempotencyKey?: string;
216
219
  }
217
220
  export declare function runAutoAuth(opts: AutoAuthOptions, deps?: ProjectDeps): Promise<CliProjectAutoAuthResponse>;
221
+ /**
222
+ * CLI-facing role flags → wire enum. Default is `api-doc` (stated in help);
223
+ * no inference from project type in v1 (design §3.4).
224
+ */
225
+ declare const DOC_ROLES: {
226
+ readonly 'api-doc': "API_DOC";
227
+ readonly prd: "PRD";
228
+ };
229
+ type DocRoleFlag = keyof typeof DOC_ROLES;
230
+ type DocRoleWire = (typeof DOC_ROLES)[DocRoleFlag];
231
+ /** `POST /projects/{id}/docs/upload-url` response (V3-A facade). */
232
+ export interface CliDocsUploadUrlResponse {
233
+ uploadUrl: string;
234
+ s3Key: string;
235
+ expiresInSeconds: number;
236
+ }
237
+ /** `POST /projects/{id}/docs` (register) response (V3-A facade). */
238
+ export interface CliDocsRegisterResponse {
239
+ resourceId: string;
240
+ displayName: string;
241
+ docRole: DocRoleWire | null;
242
+ processStatus: string;
243
+ }
244
+ /** Success result — the JSON-mode stdout shape (piece V3-D scope item 3). */
245
+ export interface CliDocsUploadResult {
246
+ resourceId: string;
247
+ displayName: string;
248
+ role: DocRoleWire | null;
249
+ size: number;
250
+ processStatus: string;
251
+ }
252
+ /** Dry-run result: the would-be plan. Zero network, nothing read beyond a stat. */
253
+ export interface CliDocsUploadPlan {
254
+ dryRun: true;
255
+ projectId: string;
256
+ file: string;
257
+ fileName: string;
258
+ displayName: string;
259
+ role: DocRoleWire;
260
+ contentType: string;
261
+ size: number;
262
+ steps: string[];
263
+ }
264
+ interface DocsUploadOptions extends CommonOptions {
265
+ file: string;
266
+ projectId?: string;
267
+ role?: string;
268
+ name?: string;
269
+ idempotencyKey?: string;
270
+ }
271
+ /**
272
+ * `project docs upload <file>` — upload an API spec or PRD as a project
273
+ * source so plan generation has inputs to feed on (closes the API-project
274
+ * cold start at `no_processed_inputs`).
275
+ *
276
+ * Three-step flow against the V3-A facade routes:
277
+ *
278
+ * 1. `POST /projects/{id}/docs/upload-url` — mints a one-hour presigned
279
+ * S3 PUT URL plus the S3 key to register afterwards.
280
+ * 2. HTTP PUT of the file bytes to the presigned URL — **streamed**
281
+ * (`createReadStream` → web stream), never buffering the whole file.
282
+ * This request goes straight to S3: no facade base URL, no API key.
283
+ * 3. `POST /projects/{id}/docs` — registers the S3 object with its role
284
+ * and display name, which starts processing + embedding.
285
+ *
286
+ * Reading the local file as INPUT is allowed by DR-21 (the no-local-OUTPUTS
287
+ * rule); nothing is ever written back to disk.
288
+ *
289
+ * Failure modes are deliberately distinguished (design non-negotiable): a
290
+ * step-2 failure names the presigned PUT and the fix (re-running mints a
291
+ * fresh URL — they expire); a step-3 failure preserves the server envelope
292
+ * and says the upload already succeeded (re-running is safe: the server
293
+ * upserts the document by S3 key, so no duplicate is created).
294
+ */
295
+ export declare function runDocsUpload(opts: DocsUploadOptions, deps?: ProjectDeps): Promise<CliDocsUploadResult | CliDocsUploadPlan>;
218
296
  export declare function createProjectCommand(deps?: ProjectDeps): Command;
219
297
  export {};