@firstdraft.com/cli 0.8.1 → 0.8.2

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.
package/README.md CHANGED
@@ -18,7 +18,7 @@ requires `--github`.
18
18
  - conditional whole-document push and conflict reporting;
19
19
  - analysis polling and complete GapSet output;
20
20
  - direct Compile-and-materialize and private publish orchestration;
21
- - retained Compilation inspection and artifact download;
21
+ - retained Compilation inspection, cancellation, and artifact download;
22
22
  - terminal output, exit status, and recovery contracts;
23
23
  - the dependency-free npm package; and
24
24
  - package provenance and publication.
@@ -42,13 +42,13 @@ Run firstdraft --help or a command group's --help for concise terminal syntax.
42
42
 
43
43
  ## Repository layout
44
44
 
45
- | Path | Responsibility |
46
- | -------- | --------------------------------------------------------------------------- |
47
- | bin/ | Published executable entrypoint |
48
- | src/ | Commands, API client, local Plan state, and output contracts |
49
- | test/ | Command, protocol, recovery, and package tests |
50
- | scripts/ | Test runner, package checks, and version sync |
51
- | docs/ | Documentation map, command and error references, and frozen release history |
45
+ | Path | Responsibility |
46
+ | -------- | ------------------------------------------------------------ |
47
+ | bin/ | Published executable entrypoint |
48
+ | src/ | Commands, API client, local Plan state, and output contracts |
49
+ | test/ | Command, protocol, recovery, and package tests |
50
+ | scripts/ | Test runner, package checks, and version sync |
51
+ | docs/ | Documentation map and command and error references |
52
52
 
53
53
  ## Development
54
54
 
@@ -102,6 +102,5 @@ The published package:
102
102
  - carries npm provenance linking registry bytes to its GitHub workflow and commit.
103
103
 
104
104
  The package includes this README, the documentation map, the command and error references, and the security
105
- policy. Repository files for maintainers stay out of it: `AGENTS.md`, the release runbook, the changelog, the
106
- release history, and the source-only `release/compatibility.json`. Inspect the packed file list whenever a source or
107
- documentation path moves.
105
+ policy. Repository files for maintainers stay out of it: `AGENTS.md`, the release runbook, the changelog, and the
106
+ source-only `release/compatibility.json`. Inspect the packed file list whenever a source or documentation path moves.
package/docs/README.md CHANGED
@@ -30,13 +30,6 @@ evidence for implemented behavior; if they contradict a document, surface the co
30
30
  Start here, then load the one owning document for the task. Follow a cross-link only when the task crosses an
31
31
  authority boundary. Create another page only for a distinct audience, task, or authority.
32
32
 
33
- The documentation tests cap `AGENTS.md` at 2 KiB, the root README at 6 KiB, and this map at 4 KiB. They also
34
- require every public topic to be reachable from this map or the root README. They check relative links, links to
35
- this repository's `main` on GitHub, and their fragments. Outside the changelog and release history, they reject
36
- retired version identities and release-status labels on the current version. They also reject status labels in
37
- changelog headings. The package check verifies that relative links in packaged Markdown resolve inside the package;
38
- packaged pages link other files on GitHub.
39
-
40
33
  ## Work on the repository
41
34
 
42
35
  Development uses Node.js 24.18.0 and npm 11.16.0, pinned in `.tool-versions`. From a fresh checkout:
package/docs/commands.md CHANGED
@@ -5,8 +5,8 @@ group's `--help` for concise executable syntax. See [Errors and recovery](errors
5
5
 
6
6
  The current `0.8.x` source line contains the auditable command shell, browser and device login, local Foundation Plan initialization, local
7
7
  application-key and UUID generation, conditional whole-document push, whole-graph analysis status polling, direct
8
- Compile-and-materialize and private publish orchestration, and retained-Compilation inspection. CLI `0.8.x`
9
- requires the service's `0.7.x` API contract. The
8
+ Compile-and-materialize and private publish orchestration, and retained-Compilation inspection and cancellation.
9
+ CLI `0.8.x` requires the service's `0.7.x` API contract. The
10
10
  [changelog](https://github.com/firstdraft/cli/blob/main/CHANGELOG.md) describes each version.
11
11
 
12
12
  ## Command map
@@ -24,6 +24,7 @@ requires the service's `0.7.x` API contract. The
24
24
  | `firstdraft plan compile --github` | Yes | Push and analyze, then publish to private GitHub |
25
25
  | `firstdraft compilation status` | Yes | Inspect a retained Compilation by ID |
26
26
  | `firstdraft compilation download` | Yes | Verify and materialize a successful retained Compilation |
27
+ | `firstdraft compilation cancel` | Yes | Cancel a queued or running Compilation by ID |
27
28
 
28
29
  ## Select an environment and authenticate
29
30
 
@@ -113,8 +114,8 @@ the existing Project's private state to redirect it.
113
114
  `FIRSTDRAFT_API_URL` remains available for an initial custom HTTPS origin or loopback HTTP development server, and
114
115
  it also selects the origin for `login` and `logout`, for example `FIRSTDRAFT_API_URL=http://127.0.0.1:3000
115
116
  firstdraft login`. `--staging` together with a different URL is an error; the equivalent normalized staging URL is
116
- allowed. Later pushes and compilation reject an override that differs from the pin. Read-only status and retained
117
- download commands use the pin and ignore `FIRSTDRAFT_API_URL` unless checking its conflict with an explicit
117
+ allowed. Later pushes and compilation reject an override that differs from the pin. Status, retained download, and
118
+ cancel commands use the pin and ignore `FIRSTDRAFT_API_URL` unless checking its conflict with an explicit
118
119
  `--staging`.
119
120
 
120
121
  Every remote command selects credentials from its effective origin. First it uses the environment: the exact
@@ -464,6 +465,38 @@ POSIX, directories use mode `0755` and files use artifact-declared `0644` or `07
464
465
  contents, and digests without claiming POSIX mode bits. The declared and streamed artifact envelope is bounded at
465
466
  128 MiB.
466
467
 
468
+ ## Cancel a stuck Compilation
469
+
470
+ A Project allows one active Compilation. While it is queued or running, First Draft refuses to replace the Plan or
471
+ start another Compilation with `409 compilation_active`, so `plan push` and `plan compile` fail. If that Compilation
472
+ will not finish, for example because its worker process died, cancel it from the Project's directory:
473
+
474
+ ```sh
475
+ firstdraft compilation cancel 01900000-0000-7000-8000-000000000001
476
+ ```
477
+
478
+ The `compilation_active` problem names the active Compilation's ID in its `response.detail`, and a `plan compile`
479
+ failure after a validated start carries it as `current.compilation.id`. Read the Compilation with
480
+ `compilation status` first. Cancelling one that is still making progress throws away its work, and the next
481
+ `plan compile` starts over.
482
+
483
+ The command validates the UUID before network access and makes one `POST` to the origin pinned for the Project, with
484
+ that origin's credential. It sends no Plan bytes or precondition header and changes no local state. Success prints
485
+ the validated cancelled Compilation in the same shape as `compilation status`, with `compilation.status` set to
486
+ `cancelled`. First Draft clears the Project's active Compilation, so the next `plan push` or `plan compile` can
487
+ proceed. A worker that finishes later cannot attach an artifact to a cancelled Compilation; stopping that worker is
488
+ best effort.
489
+
490
+ Cancel is idempotent for queued, running, and cancelled Compilations, so repeating it prints the same cancelled
491
+ Compilation. First Draft never changes a succeeded or failed Compilation: it answers
492
+ `409 compilation_not_cancellable`, which the CLI reports as `compilation_cancel_rejected`. Because a repeat is
493
+ safe, an outcome the CLI cannot confirm is `compilation_cancel_unavailable` rather than `request_outcome_unknown`.
494
+ See [stuck Compilation recovery](errors.md#stuck-compilation-recovery).
495
+
496
+ If the Compilation was started by `plan compile --github`, Cancel also cancels the Project's Publication. The
497
+ Publication is a Project singleton in this release, so `plan compile --github` cannot start another one for that
498
+ Project.
499
+
467
500
  ## Service endpoints
468
501
 
469
502
  The CLI calls these Service API routes. The `/v1` routes go to the origin pinned for the Project and send the
@@ -479,6 +512,7 @@ timeout. Each request takes its method and path from one
479
512
  | `GET` | `/v1/projects/{project_id}/analysis` | Read the Head's current analysis |
480
513
  | `POST` | `/v1/projects/{project_id}/compilations` | Start a Compilation of the Head |
481
514
  | `GET` | `/v1/projects/{project_id}/compilations/{compilation_id}` | Read one retained Compilation |
515
+ | `POST` | `/v1/projects/{project_id}/compilations/{compilation_id}/cancel` | Cancel that Compilation |
482
516
  | `GET` | `/v1/projects/{project_id}/compilations/{compilation_id}/artifact` | Download that Compilation's artifact |
483
517
  | `PUT` | `/v1/projects/{project_id}/github-publication` | Start or rejoin the Publication |
484
518
  | `GET` | `/v1/projects/{project_id}/github-publication` | Poll or reconcile the Publication |
@@ -489,12 +523,13 @@ timeout. Each request takes its method and path from one
489
523
  `plan push` sends the Plan `PUT`, and `plan status` reads the analysis. `plan compile` does both. It then starts a
490
524
  Compilation, polls it, and downloads its artifact. With `--github`, it starts and polls the Publication instead.
491
525
  `compilation status` reads one retained Compilation. `compilation download` reads it and downloads its artifact.
526
+ `compilation cancel` cancels it.
492
527
  `login` exchanges its authorization code at `/oauth/token`. With `--interactive`, it starts at
493
528
  `/oauth/device_authorization` and then polls `/oauth/token`. `logout` calls `/oauth/revoke`. The browser, not the
494
529
  CLI, opens `/oauth/authorize` and `/device`, so they have no rows.
495
530
 
496
- The first push sends `If-None-Match: *`. Later pushes, the Compilation `POST`, and the Publication `PUT` send the
497
- saved Head ETag in `If-Match`. The Service also has a Compilation cancel route, which the CLI does not call.
531
+ The first push sends `If-None-Match: *`. Later pushes, the Compilation start `POST`, and the Publication `PUT` send
532
+ the saved Head ETag in `If-Match`. The cancel `POST` sends no precondition header.
498
533
 
499
534
  The `/v1` routes belong to the API-contract range that `release/compatibility.json` accepts. The CLI does not read the
500
535
  Service's `FirstDraft-API-Contract` response header. Instead, the Service's release compatibility check compares the
@@ -550,8 +585,7 @@ Use this checklist when a change adds a command or subcommand. Each step names t
550
585
  5. **Document it.**
551
586
  - In this page, add a row to the [command map](#command-map) and a section for the command. Add a row to
552
587
  [Service endpoints](#service-endpoints) for each new route, and name the command in the paragraph below the
553
- table. If the command calls a route that section says the CLI does not call, such as Compilation cancel,
554
- rewrite that sentence.
588
+ table.
555
589
  - In [errors.md](errors.md#error-index), add an Error index row for each new `error` value. Add recovery guidance
556
590
  when retrying the command is safe in a different way than for the existing commands.
557
591
  - When the Skill will call the command, update the Skill's CLI references and contract checks in
package/docs/errors.md CHANGED
@@ -20,9 +20,9 @@ remain human-readable text on standard error with exit 2. Unexpected programming
20
20
  `invalid_configuration` stops before a request when `--staging` conflicts with `FIRSTDRAFT_API_URL` or a Project's
21
21
  saved origin. Push and Compile also reject any URL override that differs from that pin. Unset the conflicting
22
22
  override or use a separate initialized project directory for the other environment; do not redirect existing
23
- private Project state. Status and retained download commands continue using their pin.
23
+ private Project state. Status, retained download, and cancel commands continue using their pin.
24
24
 
25
- `authentication_required` means the selected environment's token is missing or rejected. Staging uses
25
+ `authentication_required` means the selected environment's token is missing or rejected with `401`. Staging uses
26
26
  `FIRSTDRAFT_STAGING_API_TOKEN`, including old staging Projects with no flag. Production and custom origins use
27
27
  `FIRSTDRAFT_API_TOKEN`. When that variable is unset, the token saved by `firstdraft login` for the exact origin is
28
28
  used. The CLI never substitutes one environment's credential for another's. Run `firstdraft login` for the same
@@ -130,10 +130,37 @@ operation is safe to remove. After successful adoption, run retained status and
130
130
 
131
131
  After `compilation_wait_timed_out`, retained work may still continue. Use
132
132
  `firstdraft compilation status <current.compilation.id>` for one read-only status check; do not rerun
133
- `plan compile`. `compilation_failed`, `compilation_cancelled`, and `compilation_changed` already carry the
133
+ `plan compile`. If it stays `queued` or `running`, follow [stuck Compilation recovery](#stuck-compilation-recovery).
134
+ `compilation_failed`, `compilation_cancelled`, and `compilation_changed` already carry the
134
135
  validated `current` projection appropriate to their stopping boundary. Authentication recovery may refresh the
135
136
  credential, but it must continue from the retained ID rather than starting another Compilation.
136
137
 
138
+ ## Stuck Compilation recovery
139
+
140
+ A Project allows one active Compilation. While one is queued or running, `plan push` and `plan compile` report
141
+ `server_rejected` with First Draft's `409 compilation_active` problem in `response`, because the Plan cannot be
142
+ replaced. `plan compile` can also meet it at the Compilation start, as `compilation_start_rejected`. Either problem's
143
+ `response.detail` names the active Compilation's ID.
144
+
145
+ 1. Read that Compilation once with `firstdraft compilation status <id>`. One that has reached `succeeded`, `failed`,
146
+ or `cancelled` no longer blocks; rerun `plan compile`.
147
+ 2. If it is still `queued` or `running` well after a Compilation normally finishes, for example after a
148
+ `plan compile` wait timed out, cancel it with `firstdraft compilation cancel <id>`. Cancelling throws away any
149
+ work it is still doing.
150
+ 3. After the cancel succeeds, rerun `plan compile`.
151
+
152
+ Cancel never changes a succeeded or failed Compilation, and repeating it is safe:
153
+
154
+ - `compilation_cancel_rejected` means First Draft refused and nothing was cancelled; `response.code` says why.
155
+ `409 compilation_not_cancellable` means the Compilation already succeeded or failed, so it no longer blocks; check
156
+ it with `compilation status`. `404 compilation_not_found` or `404 project_not_found` means First Draft found no
157
+ such Compilation for this Project and account. Check the ID, the directory, and that the environment and login
158
+ match the ones that started it.
159
+ - `compilation_cancel_unavailable` means a network failure, timeout, or server error left the outcome unconfirmed.
160
+ Rerun `compilation cancel`, or check the result with `compilation status`.
161
+ - `invalid_compilation_status` means the response violated the Compilation contract, so the cancellation may or may
162
+ not have happened. Check with `compilation status` rather than repeating the unchanged request.
163
+
137
164
  ## Publication recovery
138
165
 
139
166
  The Publication is a Project singleton. If its initial conditional `PUT` is ambiguous, the CLI attempts one
@@ -178,6 +205,9 @@ stopped without following the replacement.
178
205
  | `compilation status`, `compilation download` | `compilation_status_unavailable`, `invalid_compilation_status` | 1 | The retained status could not be read or violated its exact contract. |
179
206
  | `compilation status --wait` | `compilation_changed`, `compilation_wait_timed_out` | 1 | Retained identity/provenance changed or the wait ended. |
180
207
  | `compilation download` | `compilation_not_succeeded` | 1 | Status was not `succeeded`; no artifact request was made. |
208
+ | `compilation cancel` | `compilation_cancel_rejected` | 1 | Nothing was cancelled; `response.code` says why ([recovery](#stuck-compilation-recovery)). |
209
+ | `compilation cancel` | `compilation_cancel_unavailable` | 1 | The cancellation could not be confirmed; repeating it is safe. |
210
+ | `compilation cancel` | `invalid_compilation_status` | 1 | The response violated the Compilation contract; check status before repeating. |
181
211
  | Download commands | `artifact_unavailable`, `invalid_artifact` | 1 | Artifact transport or integrity validation failed; direct Compile post-start errors include `current`. |
182
212
  | Download commands | `invalid_output_path` | 2 | The absent destination or root-adoption preconditions failed; `reason` identifies the stable refusal. |
183
213
  | Download commands | `materialization_failed` | 1 | The output changed or its transaction failed; `reason` identifies incomplete rollback when applicable. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firstdraft.com/cli",
3
- "version": "0.8.1",
3
+ "version": "0.8.2",
4
4
  "description": "Command-line interface for First Draft",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -43,6 +43,10 @@ export const SERVICE_ROUTES = {
43
43
  method: "GET",
44
44
  path: "/v1/projects/{project_id}/compilations/{compilation_id}",
45
45
  },
46
+ cancelCompilation: {
47
+ method: "POST",
48
+ path: "/v1/projects/{project_id}/compilations/{compilation_id}/cancel",
49
+ },
46
50
  downloadArtifact: {
47
51
  method: "GET",
48
52
  path: "/v1/projects/{project_id}/compilations/{compilation_id}/artifact",
package/src/cli.js CHANGED
@@ -17,6 +17,8 @@ import {
17
17
  CompilationArtifactInvalidError,
18
18
  CompilationArtifactResponseInvalidError,
19
19
  CompilationArtifactUnavailableError,
20
+ CompilationCancelRejectedError,
21
+ CompilationCancelUnavailableError,
20
22
  CompilationCancelledError,
21
23
  CompilationChangedError,
22
24
  CompilationFailedError,
@@ -32,6 +34,7 @@ import {
32
34
  CompilationStatusInvalidError,
33
35
  CompilationStatusUnavailableError,
34
36
  CompilationTimeoutError,
37
+ cancelCompilation,
35
38
  downloadCompilation,
36
39
  readCompilation,
37
40
  } from "./commands/compilation.js";
@@ -94,7 +97,7 @@ Usage:
94
97
  firstdraft [options]
95
98
 
96
99
  Commands:
97
- compilation Inspect and download Compilations
100
+ compilation Inspect, download, and cancel Compilations
98
101
  generate Generate local values
99
102
  login Log in to First Draft and save a token
100
103
  logout Revoke and remove the saved token
@@ -230,6 +233,7 @@ Usage:
230
233
  Commands:
231
234
  status Read one retained Compilation
232
235
  download Download one successful Compilation artifact
236
+ cancel Cancel one queued or running Compilation
233
237
 
234
238
  Options:
235
239
  -h, --help Show help
@@ -274,6 +278,25 @@ materializes it into an absent output path or adopts the current directory
274
278
  while preserving existing material under .firstdraft/design. It never starts work.
275
279
  `;
276
280
 
281
+ const COMPILATION_CANCEL_HELP = `First Draft CLI
282
+
283
+ Usage:
284
+ firstdraft compilation cancel <compilation-id>
285
+
286
+ Options:
287
+ --staging Use staging; reject a different saved origin
288
+ -h, --help Show help
289
+
290
+ Environment:
291
+ FIRSTDRAFT_API_TOKEN Authenticate production or custom API origins
292
+ FIRSTDRAFT_STAGING_API_TOKEN Authenticate staging.firstdraft.com
293
+
294
+ The command asks First Draft once to cancel a queued or running Compilation of
295
+ the local Project and prints the cancelled Compilation. Cancelling it again
296
+ prints the same result; a succeeded or failed Compilation is not changed.
297
+ Once cancelled, it no longer blocks plan push or plan compile.
298
+ `;
299
+
277
300
  const PLAN_INIT_HELP = `First Draft CLI
278
301
 
279
302
  Usage:
@@ -446,6 +469,8 @@ const COMPILATION_STATUS_INVALID_ARGUMENTS_DETAIL =
446
469
  "Invalid arguments. Run 'firstdraft compilation status --help' for usage.";
447
470
  const COMPILATION_DOWNLOAD_INVALID_ARGUMENTS_DETAIL =
448
471
  "Invalid arguments. Run 'firstdraft compilation download --help' for usage.";
472
+ const COMPILATION_CANCEL_INVALID_ARGUMENTS_DETAIL =
473
+ "Invalid arguments. Run 'firstdraft compilation cancel --help' for usage.";
449
474
  const COMPILATION_LOCAL_INPUT_UNREADABLE_DETAIL =
450
475
  "Could not read valid local First Draft state. No network request was made.";
451
476
  const COMPILATION_NOT_PUSHED_DETAIL =
@@ -460,6 +485,12 @@ const COMPILATION_TIMEOUT_DETAIL =
460
485
  "The retained Compilation is still processing after the bounded ten-minute wait.";
461
486
  const COMPILATION_NOT_SUCCEEDED_DETAIL =
462
487
  "The requested Compilation has not succeeded, so no artifact was downloaded.";
488
+ const COMPILATION_CANCEL_REJECTED_DETAIL =
489
+ "First Draft rejected the cancellation, so nothing was cancelled. response.code compilation_not_cancellable means the Compilation already succeeded or failed; compilation_not_found or project_not_found means First Draft found no such Compilation for this Project and account.";
490
+ const COMPILATION_CANCEL_UNAVAILABLE_DETAIL =
491
+ "Could not confirm the cancellation. Cancelling again is safe: rerun 'firstdraft compilation cancel', or check the Compilation with 'firstdraft compilation status'.";
492
+ const COMPILATION_CANCEL_INVALID_DETAIL =
493
+ "First Draft returned an invalid response to the cancellation, so its outcome is unconfirmed. Check the Compilation with 'firstdraft compilation status'; retrying unchanged will not repair this protocol mismatch.";
463
494
  const COMPILATION_ARTIFACT_UNAVAILABLE_DETAIL =
464
495
  "Could not download the requested Compilation artifact. No files were materialized.";
465
496
  const COMPILATION_ARTIFACT_INVALID_DETAIL =
@@ -939,6 +970,23 @@ async function runCompilation({
939
970
  });
940
971
  }
941
972
 
973
+ if (argv[0] === "cancel") {
974
+ return runCompilationCancel({
975
+ argv: argv.slice(1),
976
+ stdout,
977
+ stderr,
978
+ cwd: cwd ?? getCwd(),
979
+ fetchFunction,
980
+ planPushFileSystem,
981
+ createRequestSignal,
982
+ apiUrl,
983
+ apiToken,
984
+ stagingApiToken,
985
+ staging,
986
+ credentials,
987
+ });
988
+ }
989
+
942
990
  const parsed = parseArguments(() =>
943
991
  parseArgs({
944
992
  args: [...argv],
@@ -1204,6 +1252,120 @@ async function runCompilationDownload({
1204
1252
  }
1205
1253
  }
1206
1254
 
1255
+ /**
1256
+ * @param {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "cwd" | "fetchFunction" | "planPushFileSystem" | "createRequestSignal" | "apiUrl" | "apiToken" | "stagingApiToken" | "staging" | "credentials">} options
1257
+ */
1258
+ async function runCompilationCancel({
1259
+ argv,
1260
+ stdout,
1261
+ stderr,
1262
+ cwd,
1263
+ fetchFunction,
1264
+ planPushFileSystem,
1265
+ createRequestSignal,
1266
+ apiUrl,
1267
+ apiToken,
1268
+ stagingApiToken,
1269
+ staging,
1270
+ credentials,
1271
+ }) {
1272
+ const parsed = parseArguments(() =>
1273
+ parseArgs({
1274
+ args: [...argv],
1275
+ options: {
1276
+ staging: { type: "boolean" },
1277
+ help: { type: "boolean", short: "h" },
1278
+ },
1279
+ allowPositionals: true,
1280
+ strict: true,
1281
+ tokens: true,
1282
+ }),
1283
+ );
1284
+
1285
+ if (!parsed || repeatedValueOption(parsed.tokens)) {
1286
+ writeCompilationInvalidArguments(
1287
+ stderr,
1288
+ COMPILATION_CANCEL_INVALID_ARGUMENTS_DETAIL,
1289
+ );
1290
+ return 2;
1291
+ }
1292
+
1293
+ if (parsed.values.help) {
1294
+ stdout.write(COMPILATION_CANCEL_HELP);
1295
+ return 0;
1296
+ }
1297
+
1298
+ const [compilationId] = parsed.positionals;
1299
+ if (parsed.positionals.length !== 1 || !isUuidV7(compilationId)) {
1300
+ writeCompilationInvalidArguments(
1301
+ stderr,
1302
+ COMPILATION_CANCEL_INVALID_ARGUMENTS_DETAIL,
1303
+ );
1304
+ return 2;
1305
+ }
1306
+
1307
+ try {
1308
+ const authentication = authenticateApiCommand({
1309
+ fetchFunction,
1310
+ apiUrl,
1311
+ apiToken,
1312
+ stagingApiToken,
1313
+ staging: staging || parsed.values.staging,
1314
+ readStoredTokens: storedTokenReader(credentials),
1315
+ });
1316
+ if (authentication === null) {
1317
+ writeAuthenticationRequired(stderr);
1318
+ return 1;
1319
+ }
1320
+ const result = await cancelCompilation({
1321
+ cwd,
1322
+ compilationId,
1323
+ fetchFunction: authentication.fetchFunction,
1324
+ fileSystem: planPushFileSystem,
1325
+ createRequestSignal,
1326
+ });
1327
+ writeJson(stdout, result);
1328
+ return 0;
1329
+ } catch (error) {
1330
+ if (error instanceof CompilationCancelRejectedError) {
1331
+ if (isAuthenticationProblem(error.status, error.response)) {
1332
+ writeAuthenticationRequired(stderr, error.status, error.response);
1333
+ return 1;
1334
+ }
1335
+ writeJson(stderr, {
1336
+ error: "compilation_cancel_rejected",
1337
+ detail: COMPILATION_CANCEL_REJECTED_DETAIL,
1338
+ status: error.status,
1339
+ response: error.response,
1340
+ });
1341
+ return 1;
1342
+ }
1343
+
1344
+ if (error instanceof CompilationCancelUnavailableError) {
1345
+ writeJson(stderr, {
1346
+ error: "compilation_cancel_unavailable",
1347
+ detail: COMPILATION_CANCEL_UNAVAILABLE_DETAIL,
1348
+ ...(typeof error.status === "number" ? { status: error.status } : {}),
1349
+ ...(error.response ? { response: error.response } : {}),
1350
+ });
1351
+ return 1;
1352
+ }
1353
+
1354
+ if (error instanceof CompilationStatusInvalidError) {
1355
+ writeJson(stderr, {
1356
+ error: "invalid_compilation_status",
1357
+ detail: COMPILATION_CANCEL_INVALID_DETAIL,
1358
+ status: error.status,
1359
+ });
1360
+ return 1;
1361
+ }
1362
+
1363
+ const status = writeCompilationReadError(stderr, error, false);
1364
+ if (status !== null) return status;
1365
+ throw error;
1366
+ }
1367
+ }
1368
+
1207
1369
  /** @param {Writer} writer @param {string} detail */
1208
1370
  function writeCompilationInvalidArguments(writer, detail) {
1209
1371
  writeJson(writer, { error: "invalid_arguments", detail });
@@ -131,6 +131,30 @@ export class CompilationStatusInvalidError extends Error {
131
131
  }
132
132
  }
133
133
 
134
+ export class CompilationCancelRejectedError extends Error {
135
+ /**
136
+ * @param {number} status
137
+ * @param {Record<string, unknown>} response
138
+ */
139
+ constructor(status, response) {
140
+ super("First Draft rejected the cancellation.");
141
+ this.status = status;
142
+ this.response = response;
143
+ }
144
+ }
145
+
146
+ export class CompilationCancelUnavailableError extends Error {
147
+ /**
148
+ * @param {number | undefined} status
149
+ * @param {Record<string, unknown> | null} [response]
150
+ */
151
+ constructor(status, response = null) {
152
+ super("The cancellation could not be confirmed.");
153
+ this.status = status;
154
+ this.response = response;
155
+ }
156
+ }
157
+
134
158
  export class CompilationChangedError extends Error {
135
159
  /** @param {CompilationResponse} current */
136
160
  constructor(current) {
@@ -361,6 +385,82 @@ export async function downloadCompilation({
361
385
  }
362
386
  }
363
387
 
388
+ /**
389
+ * @typedef {object} CompilationCancelOptions
390
+ * @property {string} cwd
391
+ * @property {string} compilationId
392
+ * @property {typeof globalThis.fetch} [fetchFunction]
393
+ * @property {import("../plan-state.js").PlanStateFileSystem} [fileSystem]
394
+ * @property {(timeoutMs: number) => AbortSignal} [createRequestSignal]
395
+ */
396
+
397
+ /**
398
+ * Cancel one queued or running Compilation of the local Project. The Service
399
+ * answers a repeated cancel with the same cancelled Compilation and refuses a
400
+ * succeeded or failed one without changing it, so an unconfirmed outcome is
401
+ * safe to repeat rather than an ambiguous mutation.
402
+ *
403
+ * @param {CompilationCancelOptions} options
404
+ * @returns {Promise<CompilationResponse>}
405
+ */
406
+ export async function cancelCompilation({
407
+ cwd,
408
+ compilationId,
409
+ fetchFunction = globalThis.fetch,
410
+ fileSystem,
411
+ createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs),
412
+ }) {
413
+ const { apiUrl, projectId } = readContext({ cwd, compilationId, fileSystem });
414
+ const endpoint = serviceEndpoint(SERVICE_ROUTES.cancelCompilation, apiUrl, {
415
+ project_id: projectId,
416
+ compilation_id: compilationId,
417
+ });
418
+ let response;
419
+ let body;
420
+ try {
421
+ response = await sendRequest(fetchFunction, endpoint, {
422
+ headers: { Accept: "application/json, application/problem+json" },
423
+ redirect: "error",
424
+ signal: createRequestSignal(REQUEST_TIMEOUT_MS),
425
+ });
426
+ body = await readResponseBody(response);
427
+ } catch (error) {
428
+ if (error instanceof FirstDraftNetworkError) {
429
+ throw new CompilationCancelUnavailableError(error.status);
430
+ }
431
+ // An oversized error body leaves the outcome as unconfirmed as any other
432
+ // failed response; only an oversized success breaks the contract.
433
+ if (error instanceof FirstDraftProtocolError) {
434
+ throw error.status >= 200 && error.status < 300
435
+ ? new CompilationStatusInvalidError(error.status)
436
+ : new CompilationCancelUnavailableError(error.status);
437
+ }
438
+
439
+ throw error;
440
+ }
441
+
442
+ if (response.status !== 200) {
443
+ if (response.ok) throw new CompilationStatusInvalidError(response.status);
444
+
445
+ const problem = safeProblem(response, body);
446
+ if (problem !== null && response.status !== 408 && response.status < 500) {
447
+ throw new CompilationCancelRejectedError(response.status, problem);
448
+ }
449
+ throw new CompilationCancelUnavailableError(response.status, problem);
450
+ }
451
+
452
+ const parsed = parseCompilationResponse(body, projectId, compilationId);
453
+ if (
454
+ responseMediaType(response) !== "application/json" ||
455
+ parsed === null ||
456
+ parsed.compilation.status !== "cancelled"
457
+ ) {
458
+ throw new CompilationStatusInvalidError(response.status);
459
+ }
460
+
461
+ return parsed;
462
+ }
463
+
364
464
  /**
365
465
  * @typedef {object} CurrentCompilationIdentity
366
466
  * @property {string} projectId