@defrex/autobuild 1.16.0 → 1.18.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 (97) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +132 -9
  3. package/docs/answering-blocked-builds.md +34 -1
  4. package/docs/architecture.md +42 -3
  5. package/docs/configuration.md +44 -7
  6. package/docs/dispatcher-hosting.md +5 -3
  7. package/docs/operator-api.md +29 -6
  8. package/docs/plugin-authoring.md +30 -1
  9. package/docs/remote-store-protocol.md +13 -3
  10. package/docs/remote-ticket-protocol.md +37 -2
  11. package/docs/restacking.md +46 -1
  12. package/docs/setup.md +24 -9
  13. package/docs/ticket-sources.md +28 -1
  14. package/docs/troubleshooting.md +54 -2
  15. package/docs/workspaces.md +3 -1
  16. package/package.json +4 -4
  17. package/packages/core/src/cli/accounts.ts +3 -0
  18. package/packages/core/src/cli/binary-direct.ts +14 -1
  19. package/packages/core/src/cli/binary.ts +10 -7
  20. package/packages/core/src/cli/dashboard/refresh.ts +8 -0
  21. package/packages/core/src/cli/dispatch.ts +503 -334
  22. package/packages/core/src/cli/secrets.ts +2 -0
  23. package/packages/core/src/config/schema.ts +17 -3
  24. package/packages/core/src/events/payloads.ts +8 -5
  25. package/packages/core/src/events/repository.ts +37 -1
  26. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/d41044cb2e54809c.json +194 -0
  27. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e0f89f52e48cbf62.json +197 -0
  28. package/packages/core/src/kernel/engine.ts +118 -0
  29. package/packages/core/src/kernel/reconcile-restack.ts +72 -9
  30. package/packages/core/src/kernel/reducer-revisions.ts +5 -0
  31. package/packages/core/src/kernel/repository-read-facts.ts +9 -2
  32. package/packages/core/src/kernel/ticket-preparation.ts +10 -0
  33. package/packages/core/src/kernel/tracked-dirt.ts +173 -0
  34. package/packages/core/src/ontology.ts +1 -0
  35. package/packages/core/src/operator/index.ts +10 -0
  36. package/packages/core/src/operator/merged-builds.ts +51 -0
  37. package/packages/core/src/operator/registry.ts +254 -110
  38. package/packages/core/src/operator/repo-argument.ts +43 -0
  39. package/packages/core/src/operator/tickets.ts +139 -25
  40. package/packages/core/src/plugin-sdk/index.ts +4 -0
  41. package/packages/core/src/plugins/manifest.ts +1 -1
  42. package/packages/core/src/ports/tickets/completion.ts +71 -0
  43. package/packages/core/src/ports/tickets/contract.ts +73 -0
  44. package/packages/core/src/ports/tickets/github-fake.ts +8 -0
  45. package/packages/core/src/ports/tickets/github-issues.ts +1 -0
  46. package/packages/core/src/ports/tickets/github.ts +18 -6
  47. package/packages/core/src/ports/tickets/grants.ts +2 -0
  48. package/packages/core/src/ports/tickets/hosted-index.ts +8 -0
  49. package/packages/core/src/ports/tickets/linear.ts +18 -2
  50. package/packages/core/src/ports/tickets/remote-protocol.ts +37 -8
  51. package/packages/core/src/ports/tickets/remote.ts +43 -3
  52. package/packages/core/src/ports/tickets/tree.ts +11 -1
  53. package/packages/core/src/ports/types.ts +47 -4
  54. package/packages/core/src/ports/workspace/vercel-command-diagnostics.ts +144 -0
  55. package/packages/core/src/ports/workspace/vercel-sandbox.ts +649 -160
  56. package/packages/core/src/processes/build-child.ts +15 -1
  57. package/packages/core/src/processes/build-runner.ts +349 -20
  58. package/packages/core/src/processes/dispatcher.ts +880 -283
  59. package/packages/core/src/processes/harvest-child.ts +21 -1
  60. package/packages/core/src/processes/harvest-runner.ts +82 -35
  61. package/packages/core/src/processes/pass-stages.ts +32 -6
  62. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  63. package/packages/core/src/processes/provisioning-progress.ts +23 -0
  64. package/packages/core/src/processes/repo-view.ts +25 -4
  65. package/packages/core/src/processes/workspace-preparation.ts +1 -0
  66. package/packages/core/src/store/adapter.ts +34 -5
  67. package/packages/core/src/store/build-feed.ts +148 -22
  68. package/packages/core/src/store/build-scope.ts +12 -3
  69. package/packages/core/src/store/caller-attribution.ts +170 -0
  70. package/packages/core/src/store/contract.ts +1038 -165
  71. package/packages/core/src/store/local/schema.ts +12 -1
  72. package/packages/core/src/store/local/store.ts +260 -25
  73. package/packages/core/src/store/memory.ts +156 -9
  74. package/packages/core/src/store/phase-session.ts +23 -3
  75. package/packages/core/src/store/reducer-value-shapes.json +8196 -8118
  76. package/packages/core/src/store/remote/client.ts +90 -11
  77. package/packages/core/src/store/remote/credentials.ts +2 -0
  78. package/packages/core/src/store/remote/index.ts +31 -5
  79. package/packages/core/src/store/remote/protocol.ts +45 -8
  80. package/packages/core/src/store/remote/released-clients.json +22 -0
  81. package/packages/core/src/store/remote/released-reducer-values/1.17.0.json +36367 -0
  82. package/packages/core/src/store/remote/released-reducer-values/1.18.0.json +36436 -0
  83. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  84. package/packages/core/src/store/session-handle.ts +12 -3
  85. package/packages/core/src/store/types.ts +48 -3
  86. package/packages/core/src/testing/dispatch-read-budget.ts +143 -16
  87. package/packages/core/src/testing/index.ts +2 -0
  88. package/packages/core/src/testing/reduced-read-budget.ts +420 -6
  89. package/skills/guide/SKILL.md +67 -13
  90. package/skills/guide/references/operator-api.md +29 -6
  91. package/skills/guide/references/plugin-authoring.md +30 -1
  92. package/skills/guide/references/remote-store-protocol.md +13 -3
  93. package/skills/guide/references/remote-ticket-protocol.md +37 -2
  94. package/skills/guide/references/restacking.md +46 -1
  95. package/skills/guide/references/setup.md +24 -9
  96. package/skills/operate/SKILL.md +42 -4
  97. package/templates/hosted-service/package.json +2 -2
@@ -26,13 +26,21 @@ import { displayName, tomlKey, type RuntimeReferenceGroup } from '../../config/r
26
26
  import {
27
27
  type VercelProvisioningStep,
28
28
  type VercelSandboxConfig,
29
+ VERCEL_PROVISIONING_STEP_TIMEOUT_DEFAULT_SECONDS,
30
+ VERCEL_PROVISIONING_STEP_TIMEOUT_MAX_SECONDS,
29
31
  vercelSandboxConfigSchema,
30
32
  } from '../../config/schema'
31
33
  import { distributionStampFor, resolveDistributionArchive } from './distribution-archive'
34
+ import {
35
+ formatSandboxCommandFailure,
36
+ type SandboxCommandFailure,
37
+ type SandboxCommandOutcome,
38
+ } from './vercel-command-diagnostics'
32
39
  import type {
33
40
  ForgeRewrite,
34
41
  WorkspaceHandle,
35
42
  WorkspaceProvider,
43
+ WorkspaceProvisionProgress,
36
44
  WorkspaceProvisionResult,
37
45
  WorkspacePublication,
38
46
  WorkspaceReapOutcome,
@@ -198,6 +206,9 @@ export interface VercelSandboxHandle {
198
206
  detached?: true
199
207
  sudo?: boolean
200
208
  signal?: AbortSignal
209
+ /** Server-side kill bound (SDK `timeoutMs`): the sandbox SIGKILLs the
210
+ * command when it elapses, whether or not the request is still awaited. */
211
+ timeoutMs?: number
201
212
  }): Promise<VercelCommand | { exitCode: number }>
202
213
  writeFiles(
203
214
  files: { path: string; content: Uint8Array }[],
@@ -272,6 +283,83 @@ export const VERCEL_OBSERVE_WAIT_MS = 5_000
272
283
  * finishes. */
273
284
  export const VERCEL_PROVISION_ESTIMATE_MS = 150_000
274
285
 
286
+ // Provisioning command bounds (#1400). Each is passed to the SDK as the
287
+ // server-side kill (`timeoutMs`) and backed by a host timer `grace` later.
288
+ // Every bound stays under the ~15-minute request timeout Bun's native fetch
289
+ // puts on the SDK's `wait=true` command request (see `waitForCommandExit`).
290
+
291
+ /** Small provisioning commands: checkout, remote and config scrub, mkdir,
292
+ * checkpoints, the completion marker, relocation, and adoption probes. */
293
+ export const VERCEL_PROVISION_COMMAND_TIMEOUT_MS = 120_000
294
+ /** `npm install bun@<pin>` and its version check. */
295
+ export const VERCEL_BUN_INSTALL_TIMEOUT_MS = 300_000
296
+ /** Each distribution install command: extraction, production install, and
297
+ * the identity marker write and readback. */
298
+ export const VERCEL_DISTRIBUTION_INSTALL_TIMEOUT_MS = 300_000
299
+ /** The repository's lockfile dependency install. */
300
+ export const VERCEL_DEPENDENCY_INSTALL_TIMEOUT_MS = 600_000
301
+ /** Each runtime install and each runtime preflight. */
302
+ export const VERCEL_RUNTIME_BOOTSTRAP_TIMEOUT_MS = 600_000
303
+ /** How long past the server-side kill the host waits for the response. */
304
+ export const VERCEL_COMMAND_TIMEOUT_GRACE_MS = 15_000
305
+ /** Bound on every command output read: a read opens its own log stream that
306
+ * inherits neither the command's signal nor its server-side timeout. */
307
+ export const VERCEL_COMMAND_OUTPUT_READ_MS = 30_000
308
+
309
+ /** Per-stage provisioning command bounds in milliseconds. A composition and
310
+ * test seam, not configuration: a declared step's `timeoutSeconds` beats
311
+ * `step`, which beats the default. */
312
+ export interface VercelProvisioningTimeouts {
313
+ command: number
314
+ bun: number
315
+ step: number
316
+ distribution: number
317
+ dependencies: number
318
+ runtime: number
319
+ grace: number
320
+ outputRead: number
321
+ }
322
+
323
+ function resolveProvisioningTimeouts(
324
+ overrides: Partial<VercelProvisioningTimeouts> = {},
325
+ ): VercelProvisioningTimeouts {
326
+ return {
327
+ command: VERCEL_PROVISION_COMMAND_TIMEOUT_MS,
328
+ bun: VERCEL_BUN_INSTALL_TIMEOUT_MS,
329
+ step: VERCEL_PROVISIONING_STEP_TIMEOUT_DEFAULT_SECONDS * 1000,
330
+ distribution: VERCEL_DISTRIBUTION_INSTALL_TIMEOUT_MS,
331
+ dependencies: VERCEL_DEPENDENCY_INSTALL_TIMEOUT_MS,
332
+ runtime: VERCEL_RUNTIME_BOOTSTRAP_TIMEOUT_MS,
333
+ grace: VERCEL_COMMAND_TIMEOUT_GRACE_MS,
334
+ outputRead: VERCEL_COMMAND_OUTPUT_READ_MS,
335
+ ...overrides,
336
+ }
337
+ }
338
+
339
+ /** How one guest command is bounded and labelled for diagnostics. */
340
+ interface CommandBound {
341
+ /** Server-side kill and timeout classification; absent leaves the command
342
+ * bounded only by its signal. */
343
+ timeoutMs?: number
344
+ graceMs?: number
345
+ outputReadMs?: number
346
+ /** Provisioning stage named in a failure. */
347
+ stage?: string
348
+ }
349
+
350
+ function commandBound(
351
+ timeouts: VercelProvisioningTimeouts,
352
+ timeoutMs: number,
353
+ stage?: string,
354
+ ): CommandBound {
355
+ return {
356
+ timeoutMs,
357
+ graceMs: timeouts.grace,
358
+ outputReadMs: timeouts.outputRead,
359
+ ...(stage === undefined ? {} : { stage }),
360
+ }
361
+ }
362
+
275
363
  /** Default ceiling for one stopped-sandbox recovery: an explicit cold resume
276
364
  * plus the guest git work that follows it (`recoveryTimeoutMs`). A bounded
277
365
  * invocation admits a recovery on `VERCEL_RECOVERY_ESTIMATE_MS`, not on this
@@ -692,6 +780,7 @@ async function relocateCheckout(
692
780
  sandbox: VercelSandboxHandle,
693
781
  directory: string,
694
782
  signal?: AbortSignal,
783
+ bound?: CommandBound,
695
784
  ): Promise<void> {
696
785
  const sourcePath = sourceCheckoutPath(sandbox, directory)
697
786
  try {
@@ -705,6 +794,7 @@ async function relocateCheckout(
705
794
  VERCEL_WORKSPACE_PATH,
706
795
  ],
707
796
  ...(signal === undefined ? {} : { signal }),
797
+ ...bound,
708
798
  })
709
799
  } catch (error) {
710
800
  throw new Error(
@@ -740,47 +830,229 @@ async function guestCloneCheckout(
740
830
  })
741
831
  }
742
832
 
833
+ type SandboxCommandParams = {
834
+ cmd: string
835
+ args?: string[]
836
+ cwd?: string
837
+ env?: Record<string, string>
838
+ sudo?: boolean
839
+ /** The caller's cancellation: an abort rethrows promptly, unformatted, and
840
+ * reads no output. */
841
+ signal?: AbortSignal
842
+ /** Values redacted from any failure text, besides every `env` value. */
843
+ secrets?: readonly string[]
844
+ /** Read and return stdout on success. */
845
+ readStdout?: boolean
846
+ /** Exit codes that count as success; default only 0. A timeout always
847
+ * fails. */
848
+ accept?: (exitCode: number) => boolean
849
+ } & CommandBound
850
+
851
+ function abortReason(signal: AbortSignal): unknown {
852
+ return signal.reason ?? new Error('aborted')
853
+ }
854
+
855
+ function anySignal(signals: Array<AbortSignal | undefined>): AbortSignal | undefined {
856
+ const present = signals.filter((signal): signal is AbortSignal => signal !== undefined)
857
+ if (present.length === 0) return undefined
858
+ return present.length === 1 ? present[0] : AbortSignal.any(present)
859
+ }
860
+
861
+ /** One output stream, bounded by `signal` even when the reader ignores it. */
862
+ function boundedRead(
863
+ read: ((opts?: { signal?: AbortSignal }) => Promise<string>) | undefined,
864
+ signal: AbortSignal,
865
+ ): Promise<string> {
866
+ if (read === undefined) return Promise.resolve('')
867
+ if (signal.aborted) return Promise.reject(abortReason(signal))
868
+ return new Promise<string>((resolve, reject) => {
869
+ const onAbort = () => reject(abortReason(signal))
870
+ signal.addEventListener('abort', onAbort, { once: true })
871
+ read({ signal }).then(
872
+ (output) => {
873
+ signal.removeEventListener('abort', onAbort)
874
+ resolve(output)
875
+ },
876
+ (error: unknown) => {
877
+ signal.removeEventListener('abort', onAbort)
878
+ reject(error)
879
+ },
880
+ )
881
+ })
882
+ }
883
+
884
+ /** The one guest-command runner behind `commandOrThrow` and
885
+ * `readableCommand`. Failures (non-zero exit, missing status, timeout, request
886
+ * failure) throw a diagnostic naming the redacted argv, cwd, stage, and
887
+ * bounded stderr/stdout tails (#1399). With `timeoutMs`, the sandbox kills the
888
+ * command and a host backstop bounds the response (#1400): a result arriving
889
+ * at or past `timeoutMs` is a timeout whatever its exit code, because the SDK
890
+ * reads a killed command's missing exit code as 0. */
891
+ async function runSandboxCommand(
892
+ sandbox: VercelSandboxHandle,
893
+ params: SandboxCommandParams,
894
+ ): Promise<{ stdout: string; exitCode: number }> {
895
+ const {
896
+ signal,
897
+ secrets,
898
+ readStdout,
899
+ accept,
900
+ timeoutMs,
901
+ graceMs,
902
+ outputReadMs,
903
+ stage,
904
+ ...command
905
+ } = params
906
+ if (signal?.aborted) throw abortReason(signal)
907
+ const redact = [...(secrets ?? []), ...Object.values(command.env ?? {})]
908
+ const readMs = outputReadMs ?? VERCEL_COMMAND_OUTPUT_READ_MS
909
+ const fail = (
910
+ outcome: SandboxCommandOutcome,
911
+ output: Pick<SandboxCommandFailure, 'stdout' | 'stderr' | 'outputUnavailable'>,
912
+ cause?: unknown,
913
+ ): Error =>
914
+ new Error(
915
+ formatSandboxCommandFailure({
916
+ cmd: command.cmd,
917
+ ...(command.args === undefined ? {} : { args: command.args }),
918
+ ...(command.cwd === undefined ? {} : { cwd: command.cwd }),
919
+ ...(stage === undefined ? {} : { stage }),
920
+ secrets: redact,
921
+ outcome,
922
+ ...output,
923
+ }),
924
+ cause === undefined ? undefined : { cause },
925
+ )
926
+ const hostTimer =
927
+ timeoutMs === undefined
928
+ ? undefined
929
+ : AbortSignal.timeout(timeoutMs + (graceMs ?? VERCEL_COMMAND_TIMEOUT_GRACE_MS))
930
+ const combined = anySignal([signal, hostTimer])
931
+ const started = Date.now()
932
+ let result: VercelCommand | { exitCode: number }
933
+ try {
934
+ result = await sandbox.runCommand({
935
+ ...command,
936
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
937
+ ...(combined === undefined ? {} : { signal: combined }),
938
+ })
939
+ } catch (error) {
940
+ if (signal?.aborted) throw error
941
+ if (timeoutMs !== undefined && hostTimer?.aborted)
942
+ throw fail(
943
+ { kind: 'timeout', timeoutMs, elapsedMs: Date.now() - started },
944
+ { outputUnavailable: 'the command did not report back before the host backstop' },
945
+ error,
946
+ )
947
+ // Unbounded callers keep the provider's own error for classification.
948
+ if (timeoutMs === undefined) throw error
949
+ throw fail(
950
+ { kind: 'error', message: error instanceof Error ? error.message : String(error) },
951
+ { outputUnavailable: 'the command request failed' },
952
+ error,
953
+ )
954
+ }
955
+ const elapsedMs = Date.now() - started
956
+ const outputs = result as Partial<Pick<VercelCommand, 'stdout' | 'stderr'>>
957
+ const exitCode = result.exitCode as number | null | undefined
958
+ const timedOut = timeoutMs !== undefined && elapsedMs >= timeoutMs
959
+ const ok =
960
+ !timedOut &&
961
+ exitCode !== null &&
962
+ exitCode !== undefined &&
963
+ (accept ?? ((code) => code === 0))(exitCode)
964
+ if (ok) {
965
+ if (readStdout !== true) return { stdout: '', exitCode }
966
+ const outputSignal = anySignal([signal, AbortSignal.timeout(readMs)])!
967
+ try {
968
+ return { stdout: await boundedRead(outputs.stdout?.bind(result), outputSignal), exitCode }
969
+ } catch (error) {
970
+ if (signal?.aborted) throw error
971
+ if (!outputSignal.aborted) throw error
972
+ throw fail(
973
+ {
974
+ kind: 'error',
975
+ message: `command exited 0 but its output could not be read within ${Math.round(readMs / 1000)}s`,
976
+ },
977
+ { outputUnavailable: 'output read deadline' },
978
+ error,
979
+ )
980
+ }
981
+ }
982
+ const outputSignal = anySignal([signal, AbortSignal.timeout(readMs)])!
983
+ let output: Pick<SandboxCommandFailure, 'stdout' | 'stderr' | 'outputUnavailable'>
984
+ try {
985
+ const [stderr, stdout] = await Promise.all([
986
+ boundedRead(outputs.stderr?.bind(result), outputSignal),
987
+ boundedRead(outputs.stdout?.bind(result), outputSignal),
988
+ ])
989
+ output = { stderr, stdout }
990
+ } catch (error) {
991
+ if (signal?.aborted) throw signal.reason ?? error
992
+ output = {
993
+ outputUnavailable: outputSignal.aborted
994
+ ? `output could not be read within ${Math.round(readMs / 1000)}s`
995
+ : error instanceof Error
996
+ ? error.message
997
+ : String(error),
998
+ }
999
+ }
1000
+ throw fail(
1001
+ timedOut
1002
+ ? { kind: 'timeout', timeoutMs: timeoutMs!, elapsedMs }
1003
+ : exitCode === null || exitCode === undefined
1004
+ ? { kind: 'no-status' }
1005
+ : { kind: 'exit', code: exitCode },
1006
+ output,
1007
+ )
1008
+ }
1009
+
743
1010
  async function commandOrThrow(
744
1011
  sandbox: VercelSandboxHandle,
745
- params: {
746
- cmd: string
747
- args?: string[]
748
- cwd?: string
749
- env?: Record<string, string>
750
- sudo?: boolean
751
- signal?: AbortSignal
752
- },
1012
+ params: Omit<SandboxCommandParams, 'readStdout'>,
753
1013
  ): Promise<void> {
754
- const result = await sandbox.runCommand(params)
755
- if (result.exitCode === null || result.exitCode === undefined) {
756
- throw new Error(`sandbox command ${params.cmd} did not return an exit status`)
757
- }
758
- if (result.exitCode !== 0)
759
- throw new Error(`sandbox command ${params.cmd} exited ${result.exitCode}`)
1014
+ await runSandboxCommand(sandbox, params)
760
1015
  }
761
1016
 
1017
+ /** The cause's message rides on its own line: `WorkspaceCleanupRequired` and
1018
+ * `dispatch.failed` copy only the visible message, never `cause`. */
762
1019
  function bunProvisioningError(image: string, operation: string, error: unknown): Error {
763
1020
  return new Error(
764
- `vercel-sandbox could not ${operation} Bun ${VERCEL_BUN_VERSION} on image ${JSON.stringify(image)}; Autobuild supports the universal managed image with working Node/npm, shell, filesystem, and package-registry access`,
1021
+ `vercel-sandbox could not ${operation} Bun ${VERCEL_BUN_VERSION} on image ${JSON.stringify(image)}; Autobuild supports the universal managed image with working Node/npm, shell, filesystem, and package-registry access\n${
1022
+ error instanceof Error ? error.message : String(error)
1023
+ }`,
765
1024
  { cause: error },
766
1025
  )
767
1026
  }
768
1027
 
769
1028
  /** The trimmed `bun --version` output of the provisioned executable, or
770
- * undefined when it cannot run or prints nothing. */
1029
+ * undefined when it prints nothing. A command that fails or times out
1030
+ * rejects with the runner's diagnostics. */
1031
+ async function bunVersion(
1032
+ sandbox: VercelSandboxHandle,
1033
+ signal?: AbortSignal,
1034
+ bound?: CommandBound,
1035
+ ): Promise<string | undefined> {
1036
+ const version = (
1037
+ await readableCommand(sandbox, {
1038
+ cmd: VERCEL_BUN_EXECUTABLE,
1039
+ args: ['--version'],
1040
+ ...(signal === undefined ? {} : { signal }),
1041
+ ...bound,
1042
+ })
1043
+ ).trim()
1044
+ return version === '' ? undefined : version
1045
+ }
1046
+
1047
+ /** {@link bunVersion} for an optional preflight: undefined when the
1048
+ * executable cannot run, so the caller reinstalls at the pin. */
771
1049
  async function reportedBunVersion(
772
1050
  sandbox: VercelSandboxHandle,
773
1051
  signal?: AbortSignal,
1052
+ bound?: CommandBound,
774
1053
  ): Promise<string | undefined> {
775
1054
  try {
776
- const version = (
777
- await readableCommand(sandbox, {
778
- cmd: VERCEL_BUN_EXECUTABLE,
779
- args: ['--version'],
780
- ...(signal === undefined ? {} : { signal }),
781
- })
782
- ).trim()
783
- return version === '' ? undefined : version
1055
+ return await bunVersion(sandbox, signal, bound)
784
1056
  } catch (error) {
785
1057
  if (signal?.aborted) throw error
786
1058
  return undefined
@@ -795,17 +1067,28 @@ async function provisionBun(
795
1067
  sandbox: VercelSandboxHandle,
796
1068
  image: string,
797
1069
  signal?: AbortSignal,
1070
+ bound?: CommandBound,
798
1071
  ): Promise<void> {
799
1072
  try {
800
1073
  await commandOrThrow(sandbox, {
801
1074
  cmd: 'npm',
802
1075
  args: ['install', '--prefix', VERCEL_BUN_PREFIX, '--no-save', `bun@${VERCEL_BUN_VERSION}`],
803
1076
  ...(signal === undefined ? {} : { signal }),
1077
+ ...bound,
804
1078
  })
805
1079
  } catch (error) {
1080
+ if (signal?.aborted) throw error
806
1081
  throw bunProvisioningError(image, 'provision', error)
807
1082
  }
808
- const reported = await reportedBunVersion(sandbox, signal)
1083
+ // Verification after an install is mandatory: a failing or hung version
1084
+ // check keeps its command diagnostics instead of reading as "no version".
1085
+ let reported: string | undefined
1086
+ try {
1087
+ reported = await bunVersion(sandbox, signal, bound)
1088
+ } catch (error) {
1089
+ if (signal?.aborted) throw error
1090
+ throw bunProvisioningError(image, 'verify provisioned', error)
1091
+ }
809
1092
  if (reported !== VERCEL_BUN_VERSION) {
810
1093
  throw bunProvisioningError(
811
1094
  image,
@@ -841,14 +1124,33 @@ function redactRuntimeError(error: unknown, env: Record<string, string>): string
841
1124
  * callers decide which names a guest may see — the build and harvest paths
842
1125
  * forward `[workspace.config].environmentVariables`, while the operator
843
1126
  * sandbox passes its credential-free forwarded set only (build-workspace
844
- * variables never enter a sandbox). */
1127
+ * variables never enter a sandbox).
1128
+ *
1129
+ * `mode` selects the chain. `'install'` provisions a fresh workspace: every
1130
+ * group installs, then preflights. `'repair'` relaunches into an existing
1131
+ * workspace: every group preflights, and a group whose preflight fails installs
1132
+ * in place and preflights again, so a runtime a role change newly selected (or
1133
+ * a changed pin) reaches the workspace at its next launch. Only a failure after
1134
+ * that install fails a repair; a passing preflight is never reinstalled. */
845
1135
  async function bootstrapRuntimes(
846
1136
  sandbox: VercelSandboxHandle,
847
1137
  config: VercelSandboxConfig,
848
1138
  env: Record<string, string>,
849
1139
  references: readonly RuntimeReferenceGroup[],
850
- install: boolean,
1140
+ mode: 'install' | 'repair',
851
1141
  signal?: AbortSignal,
1142
+ opts: {
1143
+ /** Bound for each install and preflight; its stage label is replaced by
1144
+ * `runtime bootstrap <runtime> <install|preflight>`. In `'repair'` mode it
1145
+ * bounds only the first preflight. */
1146
+ bound?: CommandBound
1147
+ /** Bound for the install and second preflight a `'repair'` runs after a
1148
+ * failed preflight; its stage label is replaced by
1149
+ * `runtime repair <runtime> <install|preflight>`. */
1150
+ repairBound?: CommandBound
1151
+ /** Reports `<runtime> install` / `<runtime> preflight` before each. */
1152
+ onStage?: (step: string) => void
1153
+ } = {},
852
1154
  ): Promise<void> {
853
1155
  for (const group of [...references].sort((left, right) =>
854
1156
  left.runtime < right.runtime ? -1 : left.runtime > right.runtime ? 1 : 0,
@@ -859,20 +1161,55 @@ async function bootstrapRuntimes(
859
1161
  `runtime ${displayName(group.runtime)} selected by ${group.references.join(', ')} has no provisioning; add [workspace.config.runtimeProvisioning.${tomlKey(group.runtime)}] with install and preflight commands`,
860
1162
  )
861
1163
  }
862
- for (const stage of install ? (['install', 'preflight'] as const) : (['preflight'] as const)) {
863
- try {
864
- await readableCommand(sandbox, {
865
- cmd: 'sh',
866
- args: ['-c', provisioning[stage]],
867
- cwd: VERCEL_WORKSPACE_PATH,
868
- env,
869
- ...(signal === undefined ? {} : { signal }),
870
- })
871
- } catch (error) {
872
- throw new Error(
873
- `runtime ${displayName(group.runtime)} ${stage} failed (selected by ${group.references.join(', ')}); fix workspace.config.runtimeProvisioning.${group.runtime}.${stage}: ${redactRuntimeError(error, env)}`,
874
- )
1164
+ const selectedBy = group.references.join(', ')
1165
+ const run = async (
1166
+ stage: 'install' | 'preflight',
1167
+ bound: CommandBound | undefined,
1168
+ label: string,
1169
+ ): Promise<void> => {
1170
+ const step = `${group.runtime} ${stage}`
1171
+ opts.onStage?.(step)
1172
+ await readableCommand(sandbox, {
1173
+ cmd: 'sh',
1174
+ args: ['-c', provisioning[stage]],
1175
+ cwd: VERCEL_WORKSPACE_PATH,
1176
+ env,
1177
+ ...(signal === undefined ? {} : { signal }),
1178
+ ...(bound === undefined ? {} : { ...bound, stage: `${label} ${step}` }),
1179
+ })
1180
+ }
1181
+ const failure = (stage: 'install' | 'preflight', qualifier: string, error: unknown): Error =>
1182
+ new Error(
1183
+ `runtime ${displayName(group.runtime)} ${stage} failed${qualifier} (selected by ${selectedBy}); fix workspace.config.runtimeProvisioning.${group.runtime}.${stage}: ${redactRuntimeError(error, env)}`,
1184
+ )
1185
+ if (mode === 'install') {
1186
+ for (const stage of ['install', 'preflight'] as const) {
1187
+ try {
1188
+ await run(stage, opts.bound, 'runtime bootstrap')
1189
+ } catch (error) {
1190
+ if (signal?.aborted) throw error
1191
+ throw failure(stage, '', error)
1192
+ }
875
1193
  }
1194
+ continue
1195
+ }
1196
+ try {
1197
+ await run('preflight', opts.bound, 'runtime bootstrap')
1198
+ continue
1199
+ } catch (error) {
1200
+ if (signal?.aborted) throw error
1201
+ }
1202
+ try {
1203
+ await run('install', opts.repairBound, 'runtime repair')
1204
+ } catch (error) {
1205
+ if (signal?.aborted) throw error
1206
+ throw failure('install', ' after its preflight failed in an existing workspace', error)
1207
+ }
1208
+ try {
1209
+ await run('preflight', opts.repairBound, 'runtime repair')
1210
+ } catch (error) {
1211
+ if (signal?.aborted) throw error
1212
+ throw failure('preflight', ' after install', error)
876
1213
  }
877
1214
  }
878
1215
  }
@@ -881,39 +1218,50 @@ async function runSystemProvisioning(
881
1218
  sandbox: VercelSandboxHandle,
882
1219
  steps: readonly VercelProvisioningStep[],
883
1220
  signal?: AbortSignal,
1221
+ bound?: CommandBound,
884
1222
  ): Promise<string[]> {
885
1223
  const completed: string[] = []
886
1224
  for (const step of steps) {
887
- await runSystemProvisioningStep(sandbox, step, signal)
1225
+ await runSystemProvisioningStep(sandbox, step, signal, bound)
888
1226
  completed.push(step.name)
889
1227
  }
890
1228
  return completed
891
1229
  }
892
1230
 
1231
+ /** Run one declared system provisioning step under its own timeout:
1232
+ * `timeoutSeconds` when declared, else `bound.timeoutMs`, else the default. */
893
1233
  async function runSystemProvisioningStep(
894
1234
  sandbox: VercelSandboxHandle,
895
1235
  step: VercelProvisioningStep,
896
1236
  signal?: AbortSignal,
1237
+ bound?: CommandBound,
897
1238
  ): Promise<void> {
898
- const result = (await sandbox.runCommand({
899
- cmd: 'sh',
900
- args: ['-c', step.command],
901
- cwd: VERCEL_WORKSPACE_PATH,
902
- sudo: true,
903
- ...(signal === undefined ? {} : { signal }),
904
- })) as VercelCommand
905
- if (result.exitCode !== 0) {
906
- const [stdout, stderr] = await Promise.all([
907
- result.stdout?.() ?? Promise.resolve(''),
908
- result.stderr?.() ?? Promise.resolve(''),
909
- ])
1239
+ const timeoutMs =
1240
+ step.timeoutSeconds !== undefined
1241
+ ? step.timeoutSeconds * 1000
1242
+ : (bound?.timeoutMs ?? VERCEL_PROVISIONING_STEP_TIMEOUT_DEFAULT_SECONDS * 1000)
1243
+ try {
1244
+ await commandOrThrow(sandbox, {
1245
+ cmd: 'sh',
1246
+ args: ['-c', step.command],
1247
+ cwd: VERCEL_WORKSPACE_PATH,
1248
+ sudo: true,
1249
+ ...(signal === undefined ? {} : { signal }),
1250
+ ...bound,
1251
+ timeoutMs,
1252
+ stage: `system provisioning step ${step.name}`,
1253
+ })
1254
+ } catch (error) {
1255
+ if (signal?.aborted) throw error
1256
+ const detail = error instanceof Error ? error.message : String(error)
1257
+ const timedOut = /^sandbox command \S+ exceeded its /.test(detail)
910
1258
  throw new Error(
911
- `system provisioning step ${JSON.stringify(step.name)} failed\n` +
912
- `command: ${step.command}\n` +
913
- `exit status: ${result.exitCode ?? '(missing)'}\n` +
914
- `stdout:\n${stdout.trim() === '' ? '(empty)' : stdout}\n` +
915
- `stderr:\n${stderr.trim() === '' ? '(empty)' : stderr}\n` +
916
- 'remediation: fix [workspace.config].provisioning and rerun ab init --validate',
1259
+ `system provisioning step ${JSON.stringify(step.name)} failed\n${detail}\n` +
1260
+ 'remediation: fix [workspace.config].provisioning and rerun ab init --validate' +
1261
+ (timedOut
1262
+ ? `; if the step hangs on an upstream mirror, check that mirror or raise the step's timeoutSeconds (at most ${VERCEL_PROVISIONING_STEP_TIMEOUT_MAX_SECONDS})`
1263
+ : ''),
1264
+ { cause: error },
917
1265
  )
918
1266
  }
919
1267
  }
@@ -927,12 +1275,14 @@ async function ensurePinnedBun(
927
1275
  sandbox: VercelSandboxHandle,
928
1276
  image: string,
929
1277
  signal?: AbortSignal,
1278
+ bound?: CommandBound,
930
1279
  ): Promise<void> {
931
- const reported = await reportedBunVersion(sandbox, signal)
1280
+ const reported = await reportedBunVersion(sandbox, signal, bound)
932
1281
  if (reported === VERCEL_BUN_VERSION) return
933
1282
  try {
934
- await provisionBun(sandbox, image, signal)
1283
+ await provisionBun(sandbox, image, signal, bound)
935
1284
  } catch (error) {
1285
+ if (signal?.aborted) throw error
936
1286
  const cause = error instanceof Error && error.cause instanceof Error ? error.cause : error
937
1287
  throw new Error(
938
1288
  `vercel-sandbox Bun preflight on image ${JSON.stringify(image)} found ${describeBunVersion(reported)} (pin ${VERCEL_BUN_VERSION}) and could not bring it to the pin: ${
@@ -973,28 +1323,9 @@ export interface VercelReadinessResult {
973
1323
 
974
1324
  async function readableCommand(
975
1325
  sandbox: VercelSandboxHandle,
976
- params: {
977
- cmd: string
978
- args?: string[]
979
- cwd?: string
980
- env?: Record<string, string>
981
- sudo?: boolean
982
- signal?: AbortSignal
983
- },
1326
+ params: Omit<SandboxCommandParams, 'readStdout'>,
984
1327
  ): Promise<string> {
985
- const result = (await sandbox.runCommand(params)) as VercelCommand
986
- const output = params.signal === undefined ? undefined : { signal: params.signal }
987
- const stderr = result.stderr === undefined ? '' : await result.stderr(output)
988
- const stdout = result.stdout === undefined ? '' : await result.stdout(output)
989
- if (result.exitCode === null || result.exitCode === undefined) {
990
- throw new Error(`sandbox command ${params.cmd} did not return an exit status`)
991
- }
992
- if (result.exitCode !== 0) {
993
- throw new Error(
994
- `sandbox command ${params.cmd} exited ${result.exitCode}: ${stderr.trim() || stdout.trim() || '(no output)'}`,
995
- )
996
- }
997
- return stdout
1328
+ return (await runSandboxCommand(sandbox, { ...params, readStdout: true })).stdout
998
1329
  }
999
1330
 
1000
1331
  /** The commit the guest checkout is actually on: HEAD and the build branch
@@ -1064,6 +1395,7 @@ async function writeProvisionCheckpoint(
1064
1395
  key: string,
1065
1396
  fingerprint: string,
1066
1397
  signal?: AbortSignal,
1398
+ bound?: CommandBound,
1067
1399
  ): Promise<void> {
1068
1400
  await commandOrThrow(sandbox, {
1069
1401
  cmd: 'sh',
@@ -1076,6 +1408,7 @@ async function writeProvisionCheckpoint(
1076
1408
  fingerprint,
1077
1409
  ],
1078
1410
  ...(signal === undefined ? {} : { signal }),
1411
+ ...bound,
1079
1412
  })
1080
1413
  }
1081
1414
 
@@ -1083,6 +1416,7 @@ async function writeProvisionCheckpoint(
1083
1416
  async function readProvisionCheckpoints(
1084
1417
  sandbox: VercelSandboxHandle,
1085
1418
  signal?: AbortSignal,
1419
+ bound?: CommandBound,
1086
1420
  ): Promise<Map<string, string>> {
1087
1421
  const stdout = await readableCommand(sandbox, {
1088
1422
  cmd: 'sh',
@@ -1093,6 +1427,7 @@ async function readProvisionCheckpoints(
1093
1427
  VERCEL_PROVISION_CHECKPOINT_DIR,
1094
1428
  ],
1095
1429
  ...(signal === undefined ? {} : { signal }),
1430
+ ...bound,
1096
1431
  })
1097
1432
  const checkpoints = new Map<string, string>()
1098
1433
  for (const line of stdout.split('\n')) {
@@ -1113,6 +1448,7 @@ async function clearProvisionCheckpoints(
1113
1448
  sandbox: VercelSandboxHandle,
1114
1449
  keys: readonly string[],
1115
1450
  signal?: AbortSignal,
1451
+ bound?: CommandBound,
1116
1452
  ): Promise<void> {
1117
1453
  if (keys.length === 0) return
1118
1454
  for (const key of keys) {
@@ -1129,6 +1465,7 @@ async function clearProvisionCheckpoints(
1129
1465
  ...keys,
1130
1466
  ],
1131
1467
  ...(signal === undefined ? {} : { signal }),
1468
+ ...bound,
1132
1469
  })
1133
1470
  }
1134
1471
 
@@ -1279,7 +1616,7 @@ export async function validateVercelSandbox(
1279
1616
  options.env,
1280
1617
  ),
1281
1618
  options.runtimeReferences ?? [],
1282
- true,
1619
+ 'install',
1283
1620
  options.signal,
1284
1621
  )
1285
1622
  const setup = await readableCommand(
@@ -1378,33 +1715,45 @@ async function installDistribution(
1378
1715
  archive: Uint8Array,
1379
1716
  identity: string,
1380
1717
  signal?: AbortSignal,
1718
+ opts: {
1719
+ /** Bound for each guest command. */
1720
+ bound?: CommandBound
1721
+ /** The archive upload's signal; defaults to `signal`. */
1722
+ writeSignal?: AbortSignal
1723
+ } = {},
1381
1724
  ): Promise<void> {
1382
- await sandbox.writeFiles([{ path: '/tmp/autobuild.tgz', content: archive }], {
1725
+ const writeSignal = opts.writeSignal ?? signal
1726
+ const guest = {
1383
1727
  ...(signal === undefined ? {} : { signal }),
1728
+ ...opts.bound,
1729
+ }
1730
+ await sandbox.writeFiles([{ path: '/tmp/autobuild.tgz', content: archive }], {
1731
+ ...(writeSignal === undefined ? {} : { signal: writeSignal }),
1384
1732
  })
1385
1733
  await commandOrThrow(sandbox, {
1386
1734
  cmd: 'mkdir',
1387
1735
  args: ['-p', VERCEL_AUTOBUILD_PATH],
1388
- ...(signal === undefined ? {} : { signal }),
1736
+ ...guest,
1389
1737
  })
1390
1738
  await commandOrThrow(sandbox, {
1391
1739
  cmd: 'tar',
1392
1740
  args: ['-xzf', '/tmp/autobuild.tgz', '--strip-components=1', '-C', VERCEL_AUTOBUILD_PATH],
1393
- ...(signal === undefined ? {} : { signal }),
1741
+ ...guest,
1394
1742
  })
1395
1743
  await commandOrThrow(sandbox, {
1396
1744
  cmd: VERCEL_BUN_EXECUTABLE,
1397
1745
  args: ['install', '--production', '--ignore-scripts'],
1398
1746
  cwd: VERCEL_AUTOBUILD_PATH,
1399
- ...(signal === undefined ? {} : { signal }),
1747
+ ...guest,
1400
1748
  })
1401
- await writeDistributionVersionMarker(sandbox, identity, signal)
1749
+ await writeDistributionVersionMarker(sandbox, identity, signal, opts.bound)
1402
1750
  }
1403
1751
 
1404
1752
  async function writeDistributionVersionMarker(
1405
1753
  sandbox: VercelSandboxHandle,
1406
1754
  identity: string,
1407
1755
  signal?: AbortSignal,
1756
+ bound?: CommandBound,
1408
1757
  ): Promise<void> {
1409
1758
  await commandOrThrow(sandbox, {
1410
1759
  cmd: 'sh',
@@ -1416,11 +1765,13 @@ async function writeDistributionVersionMarker(
1416
1765
  VERCEL_DISTRIBUTION_VERSION_MARKER,
1417
1766
  ],
1418
1767
  ...(signal === undefined ? {} : { signal }),
1768
+ ...bound,
1419
1769
  })
1420
1770
  const readback = await readableCommand(sandbox, {
1421
1771
  cmd: 'cat',
1422
1772
  args: [VERCEL_DISTRIBUTION_VERSION_MARKER],
1423
1773
  ...(signal === undefined ? {} : { signal }),
1774
+ ...bound,
1424
1775
  })
1425
1776
  if (readback.trim() !== identity) {
1426
1777
  throw new Error(
@@ -1432,10 +1783,12 @@ async function writeDistributionVersionMarker(
1432
1783
 
1433
1784
  /** The installed distribution's identity stamp, or `undefined` when the marker
1434
1785
  * is unreadable — which includes every guest provisioned before the marker
1435
- * existed and is treated as a mismatch by the reuse and restart paths. */
1786
+ * existed and is treated as a mismatch by the reuse and restart paths. An
1787
+ * abort of `cancel` is never read as an unreadable marker: it rethrows. */
1436
1788
  async function readDistributionVersionMarker(
1437
1789
  sandbox: VercelSandboxHandle,
1438
1790
  signal?: AbortSignal,
1791
+ cancel?: AbortSignal,
1439
1792
  ): Promise<string | undefined> {
1440
1793
  try {
1441
1794
  const content = await readableCommand(sandbox, {
@@ -1445,7 +1798,8 @@ async function readDistributionVersionMarker(
1445
1798
  })
1446
1799
  const trimmed = content.trim()
1447
1800
  return trimmed === '' ? undefined : trimmed
1448
- } catch {
1801
+ } catch (error) {
1802
+ if (cancel?.aborted) throw error
1449
1803
  return undefined
1450
1804
  }
1451
1805
  }
@@ -1700,6 +2054,10 @@ export interface VercelSandboxProviderOptions {
1700
2054
  /** Test seam: the expected wall time of one `provision`. Defaults to
1701
2055
  * `VERCEL_PROVISION_ESTIMATE_MS`. */
1702
2056
  provisionEstimateMs?: number
2057
+ /** Composition and test seam, never configuration: per-stage provisioning
2058
+ * command bounds in milliseconds over the `VERCEL_*_TIMEOUT_MS` defaults. A
2059
+ * declared step's `timeoutSeconds` still beats `step`. */
2060
+ provisioningTimeouts?: Partial<VercelProvisioningTimeouts>
1703
2061
  /** Test seam: the expected wall time of one stopped-sandbox recovery, used
1704
2062
  * to admit it in a bounded invocation. Defaults to
1705
2063
  * `VERCEL_RECOVERY_ESTIMATE_MS`; `recoveryTimeoutMs` stays the ceiling. */
@@ -2004,7 +2362,19 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2004
2362
  restorationArchives?: 'local' | 'remote'
2005
2363
  restoreStored?: Parameters<WorkspaceProvider['provision']>[0]['restoreStored']
2006
2364
  adoptAbandoned?: boolean
2365
+ signal?: AbortSignal
2366
+ onProgress?: (progress: WorkspaceProvisionProgress) => void
2007
2367
  }): Promise<WorkspaceProvisionResult> {
2368
+ const invocation = opts.signal
2369
+ const report = (stage: string, step?: string): void => {
2370
+ try {
2371
+ opts.onProgress?.(step === undefined ? { stage } : { stage, step })
2372
+ } catch {
2373
+ // An observer never fails provisioning.
2374
+ }
2375
+ }
2376
+ const timeouts = resolveProvisioningTimeouts(this.options.provisioningTimeouts)
2377
+ const small = commandBound(timeouts, timeouts.command)
2008
2378
  const scopedToken = await (this.options.delegateCredential ?? delegateCredential)(
2009
2379
  this.options.storeRef,
2010
2380
  this.options.storeToken,
@@ -2047,9 +2417,12 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2047
2417
 
2048
2418
  let checkedOut = base
2049
2419
  if (sandbox !== null) {
2050
- const marker = await sandbox.runCommand({
2420
+ const marker = await runSandboxCommand(sandbox, {
2051
2421
  cmd: 'test',
2052
2422
  args: ['-f', VERCEL_PROVISIONED_MARKER],
2423
+ accept: () => true,
2424
+ ...(invocation === undefined ? {} : { signal: invocation }),
2425
+ ...small,
2053
2426
  })
2054
2427
  if (marker.exitCode === 0) {
2055
2428
  // A completed sandbox from an attempt that recorded nothing keeps the
@@ -2057,7 +2430,11 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2057
2430
  // since. Read it before any stop: a command after stop would resume
2058
2431
  // the persistent guest.
2059
2432
  try {
2060
- checkedOut = await checkedOutBranchHead(sandbox, opts.branch, this.operationSignal())
2433
+ checkedOut = await checkedOutBranchHead(
2434
+ sandbox,
2435
+ opts.branch,
2436
+ this.stageSignal(invocation),
2437
+ )
2061
2438
  } catch (error) {
2062
2439
  throw new WorkspaceCleanupRequired(
2063
2440
  {
@@ -2070,23 +2447,31 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2070
2447
  error,
2071
2448
  )
2072
2449
  }
2073
- const installed = await readDistributionVersionMarker(sandbox, this.operationSignal())
2450
+ const installed = await readDistributionVersionMarker(
2451
+ sandbox,
2452
+ this.stageSignal(invocation),
2453
+ invocation,
2454
+ )
2074
2455
  if (installed === distributionIdentity) {
2075
- await sandbox.stop({ signal: this.operationSignal() })
2456
+ await sandbox.stop({ signal: this.stageSignal(invocation) })
2076
2457
  } else {
2077
2458
  // A completed sandbox whose installed distribution disagrees with
2078
2459
  // what the current system would deliver — including legacy guests
2079
2460
  // without a marker — is refreshed in place. Any refresh failure
2080
2461
  // deletes the sandbox so the next pass rematerializes cleanly.
2462
+ report('distribution refresh')
2081
2463
  try {
2082
- await ensurePinnedBun(sandbox, this.options.config.image, this.operationSignal())
2083
- const archive = await this.archiveBytes()
2084
- await installDistribution(
2464
+ await ensurePinnedBun(
2085
2465
  sandbox,
2086
- archive,
2087
- distributionIdentity,
2088
- this.operationSignal(),
2466
+ this.options.config.image,
2467
+ invocation,
2468
+ commandBound(timeouts, timeouts.bun, 'bun install'),
2089
2469
  )
2470
+ const archive = await this.archiveBytes()
2471
+ await installDistribution(sandbox, archive, distributionIdentity, invocation, {
2472
+ bound: commandBound(timeouts, timeouts.distribution, 'distribution install'),
2473
+ writeSignal: this.stageSignal(invocation),
2474
+ })
2090
2475
  } catch (error) {
2091
2476
  throw new WorkspaceCleanupRequired(
2092
2477
  {
@@ -2099,7 +2484,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2099
2484
  error,
2100
2485
  )
2101
2486
  }
2102
- await sandbox.stop({ signal: this.operationSignal() })
2487
+ await sandbox.stop({ signal: this.stageSignal(invocation) })
2103
2488
  }
2104
2489
  } else if (!opts.adoptAbandoned) {
2105
2490
  // A named VM without the marker is a crashed/legacy provisioning
@@ -2119,13 +2504,17 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2119
2504
  // its own teardown, and its lease is gone. Finish the same sandbox in
2120
2505
  // place at the commit it cloned, resuming after its last completed
2121
2506
  // stage, but only after verification; any doubt still reaps it.
2507
+ report('adopt')
2122
2508
  try {
2123
2509
  // Quiesce first: stopping ends any command the dead invocation left
2124
2510
  // running, and the persistent guest resumes on the next command.
2125
- await sandbox.stop({ signal: this.operationSignal() })
2126
- const checkout = await sandbox.runCommand({
2511
+ await sandbox.stop({ signal: this.stageSignal(invocation) })
2512
+ const checkout = await runSandboxCommand(sandbox, {
2127
2513
  cmd: 'test',
2128
2514
  args: ['-e', `${VERCEL_WORKSPACE_PATH}/.git`],
2515
+ accept: () => true,
2516
+ ...(invocation === undefined ? {} : { signal: invocation }),
2517
+ ...small,
2129
2518
  })
2130
2519
  if (checkout.exitCode !== 0)
2131
2520
  throw new Error('abandoned provisioning left no checkout to finish')
@@ -2136,6 +2525,9 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2136
2525
  distributionIdentity,
2137
2526
  scopedToken,
2138
2527
  resume: true,
2528
+ ...(invocation === undefined ? {} : { signal: invocation }),
2529
+ report,
2530
+ timeouts,
2139
2531
  })
2140
2532
  } catch (error) {
2141
2533
  throw new WorkspaceCleanupRequired(
@@ -2165,6 +2557,9 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2165
2557
  password === undefined
2166
2558
  ? undefined
2167
2559
  : `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`
2560
+ // Create stays on its own acknowledgement bound: aborting it mid-flight
2561
+ // would leave a half-created VM nothing addresses.
2562
+ report('create')
2168
2563
  sandbox = await this.facade.create({
2169
2564
  name,
2170
2565
  source: {
@@ -2189,13 +2584,17 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2189
2584
  signal: this.operationSignal(),
2190
2585
  })
2191
2586
  try {
2192
- await relocateCheckout(sandbox, origin.directory)
2587
+ report('relocate')
2588
+ await relocateCheckout(sandbox, origin.directory, invocation, small)
2193
2589
  checkedOut = await this.completeProvisioning(sandbox, {
2194
2590
  origin,
2195
2591
  branch: opts.branch,
2196
2592
  base,
2197
2593
  distributionIdentity,
2198
2594
  scopedToken,
2595
+ ...(invocation === undefined ? {} : { signal: invocation }),
2596
+ report,
2597
+ timeouts,
2199
2598
  })
2200
2599
  } catch (error) {
2201
2600
  throw new WorkspaceCleanupRequired(
@@ -2213,31 +2612,38 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2213
2612
  let provisionHead = checkedOut
2214
2613
  let restorationSkipped: import('../types').RestorationSkip[] = []
2215
2614
  if (opts.restoration?.length) {
2216
- provisionHead = await this.withTrustedGit(sandbox, name, undefined, async (exec) => {
2217
- restorationSkipped = (
2218
- await restoreGitCommits({
2219
- exec,
2220
- workspacePath: VERCEL_WORKSPACE_PATH,
2221
- branch: opts.branch,
2222
- heads: opts.restoration!,
2223
- replaced: opts.restorationReplaced,
2224
- // Store copies are read host-side and applied over the trusted
2225
- // transport; the guest never holds store credentials.
2226
- ...(opts.restoreStored
2227
- ? {
2228
- restoreStored: (sha: string) =>
2229
- opts.restoreStored!({ exec, workspacePath: VERCEL_WORKSPACE_PATH, sha }),
2230
- }
2231
- : {}),
2232
- })
2233
- ).skipped
2234
- const result = await exec(
2235
- ['git', 'rev-parse', '--verify', `refs/heads/${opts.branch}^{commit}`],
2236
- { cwd: VERCEL_WORKSPACE_PATH },
2237
- )
2238
- if (result.exitCode !== 0) throw new Error('cannot confirm restored workspace branch')
2239
- return result.stdout.trim()
2240
- })
2615
+ report('restoration')
2616
+ provisionHead = await this.withTrustedGit(
2617
+ sandbox,
2618
+ name,
2619
+ undefined,
2620
+ async (exec) => {
2621
+ restorationSkipped = (
2622
+ await restoreGitCommits({
2623
+ exec,
2624
+ workspacePath: VERCEL_WORKSPACE_PATH,
2625
+ branch: opts.branch,
2626
+ heads: opts.restoration!,
2627
+ replaced: opts.restorationReplaced,
2628
+ // Store copies are read host-side and applied over the trusted
2629
+ // transport; the guest never holds store credentials.
2630
+ ...(opts.restoreStored
2631
+ ? {
2632
+ restoreStored: (sha: string) =>
2633
+ opts.restoreStored!({ exec, workspacePath: VERCEL_WORKSPACE_PATH, sha }),
2634
+ }
2635
+ : {}),
2636
+ })
2637
+ ).skipped
2638
+ const result = await exec(
2639
+ ['git', 'rev-parse', '--verify', `refs/heads/${opts.branch}^{commit}`],
2640
+ { cwd: VERCEL_WORKSPACE_PATH },
2641
+ )
2642
+ if (result.exitCode !== 0) throw new Error('cannot confirm restored workspace branch')
2643
+ return result.stdout.trim()
2644
+ },
2645
+ invocation,
2646
+ )
2241
2647
  }
2242
2648
  this.origins.set(name, origin)
2243
2649
  this.sessions.set(name, sandbox)
@@ -2277,19 +2683,28 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2277
2683
  /** Finish an abandoned attempt: keep the cloned commit, skip completed
2278
2684
  * stages, and require no tracked modifications. */
2279
2685
  resume?: boolean
2686
+ /** The invocation's teardown signal: every guest command stops on it. */
2687
+ signal?: AbortSignal
2688
+ /** Reports the stage (and step) about to run. */
2689
+ report: (stage: string, step?: string) => void
2690
+ timeouts: VercelProvisioningTimeouts
2280
2691
  },
2281
2692
  ): Promise<string> {
2282
- const { origin, branch, distributionIdentity, scopedToken } = input
2693
+ const { origin, branch, distributionIdentity, scopedToken, report, timeouts } = input
2283
2694
  const resume = input.resume === true
2284
- const head = resume ? await guestHeadCommit(sandbox, this.operationSignal()) : input.base
2695
+ const invocation = input.signal
2696
+ const cancel = invocation === undefined ? {} : { signal: invocation }
2697
+ const small = commandBound(timeouts, timeouts.command)
2698
+ const head = resume ? await guestHeadCommit(sandbox, this.stageSignal(invocation)) : input.base
2285
2699
  const checkpoints = resume
2286
- ? await readProvisionCheckpoints(sandbox, this.operationSignal())
2700
+ ? await readProvisionCheckpoints(sandbox, invocation, small)
2287
2701
  : new Map<string, string>()
2288
2702
  let previous = ''
2289
2703
  let executing = !resume
2290
2704
  const kept = new Set<string>()
2291
2705
  const stage = async (
2292
2706
  key: string,
2707
+ label: { stage: string; step?: string },
2293
2708
  inputs: unknown,
2294
2709
  run: () => Promise<void>,
2295
2710
  skipped?: () => Promise<void>,
@@ -2306,49 +2721,59 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2306
2721
  await clearProvisionCheckpoints(
2307
2722
  sandbox,
2308
2723
  [...checkpoints.keys()].filter((existing) => !kept.has(existing)),
2309
- this.operationSignal(),
2724
+ invocation,
2725
+ small,
2310
2726
  )
2311
2727
  executing = true
2312
2728
  }
2729
+ report(label.stage, label.step)
2313
2730
  await run()
2314
- await writeProvisionCheckpoint(sandbox, key, fingerprint, this.operationSignal())
2731
+ await writeProvisionCheckpoint(sandbox, key, fingerprint, invocation, small)
2315
2732
  }
2316
2733
  previous = fingerprint
2317
2734
  }
2318
2735
 
2736
+ const checkout = commandBound(timeouts, timeouts.command, 'checkout')
2319
2737
  await stage(
2320
2738
  '01-checkout',
2739
+ { stage: 'checkout' },
2321
2740
  { branch, origin: origin.url, head },
2322
2741
  async () => {
2323
2742
  await commandOrThrow(sandbox, {
2324
2743
  cmd: 'git',
2325
2744
  args: ['checkout', '-B', branch, head],
2326
2745
  cwd: VERCEL_WORKSPACE_PATH,
2746
+ ...cancel,
2747
+ ...checkout,
2327
2748
  })
2328
- const checked = await checkedOutBranchHead(sandbox, branch, this.operationSignal())
2749
+ const checked = await checkedOutBranchHead(sandbox, branch, this.stageSignal(invocation))
2329
2750
  if (checked !== head)
2330
2751
  throw new Error(`checked out ${branch} at ${checked}, expected selected base ${head}`)
2331
2752
  await commandOrThrow(sandbox, {
2332
2753
  cmd: 'git',
2333
2754
  args: ['remote', 'set-url', 'origin', origin.url],
2334
2755
  cwd: VERCEL_WORKSPACE_PATH,
2756
+ ...cancel,
2757
+ ...checkout,
2335
2758
  })
2336
2759
  for (const key of [
2337
2760
  'credential.helper',
2338
2761
  'http.extraheader',
2339
2762
  `http.${origin.url}.extraheader`,
2340
2763
  ]) {
2341
- const result = await sandbox.runCommand({
2764
+ // Exit 5: the key was not set.
2765
+ await commandOrThrow(sandbox, {
2342
2766
  cmd: 'git',
2343
2767
  args: ['config', '--local', '--unset-all', key],
2344
2768
  cwd: VERCEL_WORKSPACE_PATH,
2769
+ accept: (code) => code === 0 || code === 5,
2770
+ ...cancel,
2771
+ ...checkout,
2345
2772
  })
2346
- if (result.exitCode !== 0 && result.exitCode !== 5)
2347
- throw new Error(`failed to scrub git config ${key}`)
2348
2773
  }
2349
2774
  },
2350
2775
  async () => {
2351
- const checked = await checkedOutBranchHead(sandbox, branch, this.operationSignal())
2776
+ const checked = await checkedOutBranchHead(sandbox, branch, this.stageSignal(invocation))
2352
2777
  if (checked !== head)
2353
2778
  throw new Error(`checked out ${branch} at ${checked}, expected cloned head ${head}`)
2354
2779
  },
@@ -2356,40 +2781,69 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2356
2781
  if (resume) {
2357
2782
  // A finished abandoned attempt must not expose tracked edits the dead
2358
2783
  // invocation may have left behind.
2359
- const diff = await sandbox.runCommand({
2784
+ const diff = await runSandboxCommand(sandbox, {
2360
2785
  cmd: 'git',
2361
2786
  args: ['diff', '--quiet', 'HEAD', '--'],
2362
2787
  cwd: VERCEL_WORKSPACE_PATH,
2788
+ accept: () => true,
2789
+ ...cancel,
2790
+ ...small,
2363
2791
  })
2364
2792
  if (diff.exitCode !== 0) throw new Error('abandoned provisioning left tracked modifications')
2365
2793
  }
2366
2794
  const image = this.options.config.image
2367
- await stage('02-bun', { version: VERCEL_BUN_VERSION, image }, () =>
2368
- provisionBun(sandbox, image),
2795
+ await stage('02-bun', { stage: 'bun install' }, { version: VERCEL_BUN_VERSION, image }, () =>
2796
+ provisionBun(sandbox, image, invocation, commandBound(timeouts, timeouts.bun, 'bun install')),
2369
2797
  )
2370
2798
  const steps = this.options.config.provisioning ?? []
2371
2799
  for (const [index, step] of steps.entries()) {
2372
- await stage(`03-step-${index}`, { name: step.name, command: step.command }, () =>
2373
- runSystemProvisioningStep(sandbox, step),
2800
+ // The fingerprint deliberately omits `timeoutSeconds`: a bound change
2801
+ // never reruns a completed step.
2802
+ await stage(
2803
+ `03-step-${index}`,
2804
+ { stage: 'system provisioning step', step: step.name },
2805
+ { name: step.name, command: step.command },
2806
+ () =>
2807
+ runSystemProvisioningStep(
2808
+ sandbox,
2809
+ step,
2810
+ invocation,
2811
+ commandBound(timeouts, timeouts.step),
2812
+ ),
2374
2813
  )
2375
2814
  }
2376
- await stage('04-distribution', { identity: distributionIdentity }, async () => {
2377
- const archive = await this.archiveBytes()
2378
- await installDistribution(sandbox, archive, distributionIdentity, this.operationSignal())
2379
- })
2815
+ await stage(
2816
+ '04-distribution',
2817
+ { stage: 'distribution install' },
2818
+ { identity: distributionIdentity },
2819
+ async () => {
2820
+ const archive = await this.archiveBytes()
2821
+ await installDistribution(sandbox, archive, distributionIdentity, invocation, {
2822
+ bound: commandBound(timeouts, timeouts.distribution, 'distribution install'),
2823
+ writeSignal: this.stageSignal(invocation),
2824
+ })
2825
+ },
2826
+ )
2380
2827
  // Repository dependencies precede branch-owned package plugin loading.
2381
2828
  // The fixed bootstrap supports the consuming repository's lockfile; its
2382
2829
  // configured setup command still runs at every runner attachment.
2383
- await stage('05-dependencies', { command: DEPENDENCY_INSTALL_COMMAND }, () =>
2384
- commandOrThrow(sandbox, {
2385
- cmd: 'sh',
2386
- args: ['-c', DEPENDENCY_INSTALL_COMMAND],
2387
- cwd: VERCEL_WORKSPACE_PATH,
2388
- }),
2830
+ await stage(
2831
+ '05-dependencies',
2832
+ { stage: 'dependency install' },
2833
+ { command: DEPENDENCY_INSTALL_COMMAND },
2834
+ () =>
2835
+ commandOrThrow(sandbox, {
2836
+ cmd: 'sh',
2837
+ args: ['-c', DEPENDENCY_INSTALL_COMMAND],
2838
+ cwd: VERCEL_WORKSPACE_PATH,
2839
+ ...cancel,
2840
+ ...commandBound(timeouts, timeouts.dependencies, 'dependency install'),
2841
+ }),
2389
2842
  )
2390
2843
  const references = currentRuntimeReferences(this.options.runtimeReferences)
2391
2844
  await stage(
2392
2845
  '06-runtimes',
2846
+ { stage: 'runtime bootstrap' },
2393
2847
  [...references]
2394
2848
  .sort((left, right) =>
2395
2849
  left.runtime < right.runtime ? -1 : left.runtime > right.runtime ? 1 : 0,
@@ -2409,14 +2863,22 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2409
2863
  this.options.config,
2410
2864
  { ...this.guestEnvironment(), AB_TOKEN: scopedToken },
2411
2865
  references,
2412
- true,
2866
+ 'install',
2867
+ invocation,
2868
+ {
2869
+ bound: commandBound(timeouts, timeouts.runtime),
2870
+ onStage: (step) => report('runtime bootstrap', step),
2871
+ },
2413
2872
  ),
2414
2873
  )
2874
+ report('finalize')
2415
2875
  await commandOrThrow(sandbox, {
2416
2876
  cmd: 'touch',
2417
2877
  args: [VERCEL_PROVISIONED_MARKER],
2878
+ ...cancel,
2879
+ ...commandBound(timeouts, timeouts.command, 'finalize'),
2418
2880
  })
2419
- await sandbox.stop({ signal: this.operationSignal() })
2881
+ await sandbox.stop({ signal: this.stageSignal(invocation) })
2420
2882
  return head
2421
2883
  }
2422
2884
 
@@ -2429,6 +2891,14 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2429
2891
  return AbortSignal.timeout(this.operationTimeoutMs())
2430
2892
  }
2431
2893
 
2894
+ /** A metadata call inside provisioning: its own acknowledgement bound, and
2895
+ * stopped by the invocation's teardown signal. */
2896
+ private stageSignal(invocation?: AbortSignal): AbortSignal {
2897
+ return invocation === undefined
2898
+ ? this.operationSignal()
2899
+ : AbortSignal.any([this.operationSignal(), invocation])
2900
+ }
2901
+
2432
2902
  private operationTimeoutMs(): number {
2433
2903
  return this.options.config.operationTimeoutMs ?? 30_000
2434
2904
  }
@@ -2829,12 +3299,19 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2829
3299
  )
2830
3300
  }
2831
3301
  }
3302
+ // Every selected runtime preflights before the runner starts. A runtime
3303
+ // whose preflight fails — one a role change newly selected, or a changed
3304
+ // pin — is installed in place and preflighted again, so the change reaches
3305
+ // this existing workspace now instead of failing every relaunch.
3306
+ const repairTimeouts = resolveProvisioningTimeouts(this.options.provisioningTimeouts)
2832
3307
  await bootstrapRuntimes(
2833
3308
  sandbox,
2834
3309
  this.options.config,
2835
3310
  { ...this.guestEnvironment(), AB_TOKEN: scopedToken },
2836
3311
  currentRuntimeReferences(this.options.runtimeReferences),
2837
- false,
3312
+ 'repair',
3313
+ undefined,
3314
+ { repairBound: commandBound(repairTimeouts, repairTimeouts.runtime) },
2838
3315
  )
2839
3316
  this.sessions.set(ref, sandbox)
2840
3317
  const env: Record<string, string> = {
@@ -3105,7 +3582,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
3105
3582
  this.options.config,
3106
3583
  { ...this.guestEnvironment(), AB_TOKEN: scopedToken },
3107
3584
  currentRuntimeReferences(this.options.runtimeReferences),
3108
- true,
3585
+ 'install',
3109
3586
  )
3110
3587
  await commandOrThrow(sandbox, {
3111
3588
  cmd: 'touch',
@@ -3151,12 +3628,17 @@ export class VercelSandboxProvider implements WorkspaceProvider {
3151
3628
  }
3152
3629
  throw error
3153
3630
  }
3631
+ // A reused harvest sandbox installs a newly selected runtime in place,
3632
+ // exactly as a build relaunch does.
3633
+ const repairTimeouts = resolveProvisioningTimeouts(this.options.provisioningTimeouts)
3154
3634
  await bootstrapRuntimes(
3155
3635
  sandbox,
3156
3636
  this.options.config,
3157
3637
  { ...this.guestEnvironment(), AB_TOKEN: scopedToken },
3158
3638
  currentRuntimeReferences(this.options.runtimeReferences),
3159
- false,
3639
+ 'repair',
3640
+ undefined,
3641
+ { repairBound: commandBound(repairTimeouts, repairTimeouts.runtime) },
3160
3642
  )
3161
3643
  this.sessions.set(name, sandbox)
3162
3644
  const sessionId = sandbox.currentSession?.().sessionId
@@ -4891,6 +5373,9 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4891
5373
  ref: string,
4892
5374
  signal: AbortSignal | undefined,
4893
5375
  effect: (exec: Exec) => Promise<T>,
5376
+ /** Also stops each guest command (provisioning restore at teardown);
5377
+ * each keeps its own acknowledgement cap. */
5378
+ cancel?: AbortSignal,
4894
5379
  ): Promise<T> {
4895
5380
  const { origin } = await this.normalNetworkPolicy(ref)
4896
5381
  const token = this.options.env.GITHUB_TOKEN || this.options.env.GH_TOKEN
@@ -4927,7 +5412,11 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4927
5412
  { signal: this.recoveryMetadataSignal() },
4928
5413
  )
4929
5414
  return await effect(async (cmd) => {
4930
- const bound = signal ?? this.operationSignal()
5415
+ const bound =
5416
+ signal ??
5417
+ (cancel === undefined
5418
+ ? this.operationSignal()
5419
+ : AbortSignal.any([this.operationSignal(), cancel]))
4931
5420
  const result = await sandbox.runCommand({
4932
5421
  cmd: cmd[0]!,
4933
5422
  args: cmd.slice(1),