@defrex/autobuild 1.16.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +91 -7
  3. package/docs/answering-blocked-builds.md +34 -1
  4. package/docs/architecture.md +15 -1
  5. package/docs/configuration.md +33 -4
  6. package/docs/operator-api.md +15 -5
  7. package/docs/plugin-authoring.md +1 -0
  8. package/docs/remote-store-protocol.md +13 -3
  9. package/docs/remote-ticket-protocol.md +3 -1
  10. package/docs/restacking.md +41 -1
  11. package/docs/setup.md +15 -6
  12. package/docs/troubleshooting.md +39 -2
  13. package/docs/workspaces.md +2 -0
  14. package/package.json +3 -3
  15. package/packages/core/src/cli/accounts.ts +3 -0
  16. package/packages/core/src/cli/binary-direct.ts +14 -1
  17. package/packages/core/src/cli/binary.ts +10 -7
  18. package/packages/core/src/cli/dispatch.ts +503 -334
  19. package/packages/core/src/cli/secrets.ts +2 -0
  20. package/packages/core/src/config/schema.ts +15 -2
  21. package/packages/core/src/events/payloads.ts +8 -5
  22. package/packages/core/src/kernel/engine.ts +118 -0
  23. package/packages/core/src/kernel/reconcile-restack.ts +72 -9
  24. package/packages/core/src/kernel/tracked-dirt.ts +173 -0
  25. package/packages/core/src/ontology.ts +1 -0
  26. package/packages/core/src/operator/index.ts +10 -0
  27. package/packages/core/src/operator/merged-builds.ts +51 -0
  28. package/packages/core/src/operator/registry.ts +190 -101
  29. package/packages/core/src/operator/repo-argument.ts +43 -0
  30. package/packages/core/src/ports/tickets/grants.ts +2 -0
  31. package/packages/core/src/ports/tickets/remote.ts +2 -0
  32. package/packages/core/src/ports/types.ts +15 -0
  33. package/packages/core/src/ports/workspace/vercel-command-diagnostics.ts +144 -0
  34. package/packages/core/src/ports/workspace/vercel-sandbox.ts +576 -140
  35. package/packages/core/src/processes/build-child.ts +15 -1
  36. package/packages/core/src/processes/build-runner.ts +349 -20
  37. package/packages/core/src/processes/dispatcher.ts +28 -7
  38. package/packages/core/src/processes/harvest-child.ts +21 -1
  39. package/packages/core/src/processes/harvest-runner.ts +82 -35
  40. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  41. package/packages/core/src/processes/provisioning-progress.ts +23 -0
  42. package/packages/core/src/processes/repo-view.ts +25 -4
  43. package/packages/core/src/processes/workspace-preparation.ts +1 -0
  44. package/packages/core/src/store/adapter.ts +34 -5
  45. package/packages/core/src/store/build-feed.ts +148 -22
  46. package/packages/core/src/store/build-scope.ts +12 -3
  47. package/packages/core/src/store/caller-attribution.ts +170 -0
  48. package/packages/core/src/store/contract.ts +1038 -165
  49. package/packages/core/src/store/local/schema.ts +12 -1
  50. package/packages/core/src/store/local/store.ts +260 -25
  51. package/packages/core/src/store/memory.ts +156 -9
  52. package/packages/core/src/store/phase-session.ts +23 -3
  53. package/packages/core/src/store/reducer-value-shapes.json +3184 -3175
  54. package/packages/core/src/store/remote/client.ts +90 -11
  55. package/packages/core/src/store/remote/credentials.ts +2 -0
  56. package/packages/core/src/store/remote/index.ts +31 -5
  57. package/packages/core/src/store/remote/protocol.ts +45 -8
  58. package/packages/core/src/store/remote/released-clients.json +11 -0
  59. package/packages/core/src/store/remote/released-reducer-values/1.17.0.json +36367 -0
  60. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  61. package/packages/core/src/store/session-handle.ts +12 -3
  62. package/packages/core/src/store/types.ts +48 -3
  63. package/packages/core/src/testing/reduced-read-budget.ts +222 -4
  64. package/skills/guide/SKILL.md +46 -8
  65. package/skills/guide/references/operator-api.md +15 -5
  66. package/skills/guide/references/plugin-authoring.md +1 -0
  67. package/skills/guide/references/remote-store-protocol.md +13 -3
  68. package/skills/guide/references/remote-ticket-protocol.md +3 -1
  69. package/skills/guide/references/restacking.md +41 -1
  70. package/skills/guide/references/setup.md +15 -6
  71. package/skills/operate/SKILL.md +24 -3
  72. 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,
@@ -849,6 +1132,13 @@ async function bootstrapRuntimes(
849
1132
  references: readonly RuntimeReferenceGroup[],
850
1133
  install: boolean,
851
1134
  signal?: AbortSignal,
1135
+ opts: {
1136
+ /** Bound for each install and preflight; its stage label is replaced by
1137
+ * `runtime bootstrap <runtime> <install|preflight>`. */
1138
+ bound?: CommandBound
1139
+ /** Reports `<runtime> install` / `<runtime> preflight` before each. */
1140
+ onStage?: (step: string) => void
1141
+ } = {},
852
1142
  ): Promise<void> {
853
1143
  for (const group of [...references].sort((left, right) =>
854
1144
  left.runtime < right.runtime ? -1 : left.runtime > right.runtime ? 1 : 0,
@@ -860,6 +1150,8 @@ async function bootstrapRuntimes(
860
1150
  )
861
1151
  }
862
1152
  for (const stage of install ? (['install', 'preflight'] as const) : (['preflight'] as const)) {
1153
+ const step = `${group.runtime} ${stage}`
1154
+ opts.onStage?.(step)
863
1155
  try {
864
1156
  await readableCommand(sandbox, {
865
1157
  cmd: 'sh',
@@ -867,8 +1159,12 @@ async function bootstrapRuntimes(
867
1159
  cwd: VERCEL_WORKSPACE_PATH,
868
1160
  env,
869
1161
  ...(signal === undefined ? {} : { signal }),
1162
+ ...(opts.bound === undefined
1163
+ ? {}
1164
+ : { ...opts.bound, stage: `runtime bootstrap ${step}` }),
870
1165
  })
871
1166
  } catch (error) {
1167
+ if (signal?.aborted) throw error
872
1168
  throw new Error(
873
1169
  `runtime ${displayName(group.runtime)} ${stage} failed (selected by ${group.references.join(', ')}); fix workspace.config.runtimeProvisioning.${group.runtime}.${stage}: ${redactRuntimeError(error, env)}`,
874
1170
  )
@@ -881,39 +1177,50 @@ async function runSystemProvisioning(
881
1177
  sandbox: VercelSandboxHandle,
882
1178
  steps: readonly VercelProvisioningStep[],
883
1179
  signal?: AbortSignal,
1180
+ bound?: CommandBound,
884
1181
  ): Promise<string[]> {
885
1182
  const completed: string[] = []
886
1183
  for (const step of steps) {
887
- await runSystemProvisioningStep(sandbox, step, signal)
1184
+ await runSystemProvisioningStep(sandbox, step, signal, bound)
888
1185
  completed.push(step.name)
889
1186
  }
890
1187
  return completed
891
1188
  }
892
1189
 
1190
+ /** Run one declared system provisioning step under its own timeout:
1191
+ * `timeoutSeconds` when declared, else `bound.timeoutMs`, else the default. */
893
1192
  async function runSystemProvisioningStep(
894
1193
  sandbox: VercelSandboxHandle,
895
1194
  step: VercelProvisioningStep,
896
1195
  signal?: AbortSignal,
1196
+ bound?: CommandBound,
897
1197
  ): 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
- ])
1198
+ const timeoutMs =
1199
+ step.timeoutSeconds !== undefined
1200
+ ? step.timeoutSeconds * 1000
1201
+ : (bound?.timeoutMs ?? VERCEL_PROVISIONING_STEP_TIMEOUT_DEFAULT_SECONDS * 1000)
1202
+ try {
1203
+ await commandOrThrow(sandbox, {
1204
+ cmd: 'sh',
1205
+ args: ['-c', step.command],
1206
+ cwd: VERCEL_WORKSPACE_PATH,
1207
+ sudo: true,
1208
+ ...(signal === undefined ? {} : { signal }),
1209
+ ...bound,
1210
+ timeoutMs,
1211
+ stage: `system provisioning step ${step.name}`,
1212
+ })
1213
+ } catch (error) {
1214
+ if (signal?.aborted) throw error
1215
+ const detail = error instanceof Error ? error.message : String(error)
1216
+ const timedOut = /^sandbox command \S+ exceeded its /.test(detail)
910
1217
  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',
1218
+ `system provisioning step ${JSON.stringify(step.name)} failed\n${detail}\n` +
1219
+ 'remediation: fix [workspace.config].provisioning and rerun ab init --validate' +
1220
+ (timedOut
1221
+ ? `; 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})`
1222
+ : ''),
1223
+ { cause: error },
917
1224
  )
918
1225
  }
919
1226
  }
@@ -927,12 +1234,14 @@ async function ensurePinnedBun(
927
1234
  sandbox: VercelSandboxHandle,
928
1235
  image: string,
929
1236
  signal?: AbortSignal,
1237
+ bound?: CommandBound,
930
1238
  ): Promise<void> {
931
- const reported = await reportedBunVersion(sandbox, signal)
1239
+ const reported = await reportedBunVersion(sandbox, signal, bound)
932
1240
  if (reported === VERCEL_BUN_VERSION) return
933
1241
  try {
934
- await provisionBun(sandbox, image, signal)
1242
+ await provisionBun(sandbox, image, signal, bound)
935
1243
  } catch (error) {
1244
+ if (signal?.aborted) throw error
936
1245
  const cause = error instanceof Error && error.cause instanceof Error ? error.cause : error
937
1246
  throw new Error(
938
1247
  `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 +1282,9 @@ export interface VercelReadinessResult {
973
1282
 
974
1283
  async function readableCommand(
975
1284
  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
- },
1285
+ params: Omit<SandboxCommandParams, 'readStdout'>,
984
1286
  ): 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
1287
+ return (await runSandboxCommand(sandbox, { ...params, readStdout: true })).stdout
998
1288
  }
999
1289
 
1000
1290
  /** The commit the guest checkout is actually on: HEAD and the build branch
@@ -1064,6 +1354,7 @@ async function writeProvisionCheckpoint(
1064
1354
  key: string,
1065
1355
  fingerprint: string,
1066
1356
  signal?: AbortSignal,
1357
+ bound?: CommandBound,
1067
1358
  ): Promise<void> {
1068
1359
  await commandOrThrow(sandbox, {
1069
1360
  cmd: 'sh',
@@ -1076,6 +1367,7 @@ async function writeProvisionCheckpoint(
1076
1367
  fingerprint,
1077
1368
  ],
1078
1369
  ...(signal === undefined ? {} : { signal }),
1370
+ ...bound,
1079
1371
  })
1080
1372
  }
1081
1373
 
@@ -1083,6 +1375,7 @@ async function writeProvisionCheckpoint(
1083
1375
  async function readProvisionCheckpoints(
1084
1376
  sandbox: VercelSandboxHandle,
1085
1377
  signal?: AbortSignal,
1378
+ bound?: CommandBound,
1086
1379
  ): Promise<Map<string, string>> {
1087
1380
  const stdout = await readableCommand(sandbox, {
1088
1381
  cmd: 'sh',
@@ -1093,6 +1386,7 @@ async function readProvisionCheckpoints(
1093
1386
  VERCEL_PROVISION_CHECKPOINT_DIR,
1094
1387
  ],
1095
1388
  ...(signal === undefined ? {} : { signal }),
1389
+ ...bound,
1096
1390
  })
1097
1391
  const checkpoints = new Map<string, string>()
1098
1392
  for (const line of stdout.split('\n')) {
@@ -1113,6 +1407,7 @@ async function clearProvisionCheckpoints(
1113
1407
  sandbox: VercelSandboxHandle,
1114
1408
  keys: readonly string[],
1115
1409
  signal?: AbortSignal,
1410
+ bound?: CommandBound,
1116
1411
  ): Promise<void> {
1117
1412
  if (keys.length === 0) return
1118
1413
  for (const key of keys) {
@@ -1129,6 +1424,7 @@ async function clearProvisionCheckpoints(
1129
1424
  ...keys,
1130
1425
  ],
1131
1426
  ...(signal === undefined ? {} : { signal }),
1427
+ ...bound,
1132
1428
  })
1133
1429
  }
1134
1430
 
@@ -1378,33 +1674,45 @@ async function installDistribution(
1378
1674
  archive: Uint8Array,
1379
1675
  identity: string,
1380
1676
  signal?: AbortSignal,
1677
+ opts: {
1678
+ /** Bound for each guest command. */
1679
+ bound?: CommandBound
1680
+ /** The archive upload's signal; defaults to `signal`. */
1681
+ writeSignal?: AbortSignal
1682
+ } = {},
1381
1683
  ): Promise<void> {
1382
- await sandbox.writeFiles([{ path: '/tmp/autobuild.tgz', content: archive }], {
1684
+ const writeSignal = opts.writeSignal ?? signal
1685
+ const guest = {
1383
1686
  ...(signal === undefined ? {} : { signal }),
1687
+ ...opts.bound,
1688
+ }
1689
+ await sandbox.writeFiles([{ path: '/tmp/autobuild.tgz', content: archive }], {
1690
+ ...(writeSignal === undefined ? {} : { signal: writeSignal }),
1384
1691
  })
1385
1692
  await commandOrThrow(sandbox, {
1386
1693
  cmd: 'mkdir',
1387
1694
  args: ['-p', VERCEL_AUTOBUILD_PATH],
1388
- ...(signal === undefined ? {} : { signal }),
1695
+ ...guest,
1389
1696
  })
1390
1697
  await commandOrThrow(sandbox, {
1391
1698
  cmd: 'tar',
1392
1699
  args: ['-xzf', '/tmp/autobuild.tgz', '--strip-components=1', '-C', VERCEL_AUTOBUILD_PATH],
1393
- ...(signal === undefined ? {} : { signal }),
1700
+ ...guest,
1394
1701
  })
1395
1702
  await commandOrThrow(sandbox, {
1396
1703
  cmd: VERCEL_BUN_EXECUTABLE,
1397
1704
  args: ['install', '--production', '--ignore-scripts'],
1398
1705
  cwd: VERCEL_AUTOBUILD_PATH,
1399
- ...(signal === undefined ? {} : { signal }),
1706
+ ...guest,
1400
1707
  })
1401
- await writeDistributionVersionMarker(sandbox, identity, signal)
1708
+ await writeDistributionVersionMarker(sandbox, identity, signal, opts.bound)
1402
1709
  }
1403
1710
 
1404
1711
  async function writeDistributionVersionMarker(
1405
1712
  sandbox: VercelSandboxHandle,
1406
1713
  identity: string,
1407
1714
  signal?: AbortSignal,
1715
+ bound?: CommandBound,
1408
1716
  ): Promise<void> {
1409
1717
  await commandOrThrow(sandbox, {
1410
1718
  cmd: 'sh',
@@ -1416,11 +1724,13 @@ async function writeDistributionVersionMarker(
1416
1724
  VERCEL_DISTRIBUTION_VERSION_MARKER,
1417
1725
  ],
1418
1726
  ...(signal === undefined ? {} : { signal }),
1727
+ ...bound,
1419
1728
  })
1420
1729
  const readback = await readableCommand(sandbox, {
1421
1730
  cmd: 'cat',
1422
1731
  args: [VERCEL_DISTRIBUTION_VERSION_MARKER],
1423
1732
  ...(signal === undefined ? {} : { signal }),
1733
+ ...bound,
1424
1734
  })
1425
1735
  if (readback.trim() !== identity) {
1426
1736
  throw new Error(
@@ -1432,10 +1742,12 @@ async function writeDistributionVersionMarker(
1432
1742
 
1433
1743
  /** The installed distribution's identity stamp, or `undefined` when the marker
1434
1744
  * is unreadable — which includes every guest provisioned before the marker
1435
- * existed and is treated as a mismatch by the reuse and restart paths. */
1745
+ * existed and is treated as a mismatch by the reuse and restart paths. An
1746
+ * abort of `cancel` is never read as an unreadable marker: it rethrows. */
1436
1747
  async function readDistributionVersionMarker(
1437
1748
  sandbox: VercelSandboxHandle,
1438
1749
  signal?: AbortSignal,
1750
+ cancel?: AbortSignal,
1439
1751
  ): Promise<string | undefined> {
1440
1752
  try {
1441
1753
  const content = await readableCommand(sandbox, {
@@ -1445,7 +1757,8 @@ async function readDistributionVersionMarker(
1445
1757
  })
1446
1758
  const trimmed = content.trim()
1447
1759
  return trimmed === '' ? undefined : trimmed
1448
- } catch {
1760
+ } catch (error) {
1761
+ if (cancel?.aborted) throw error
1449
1762
  return undefined
1450
1763
  }
1451
1764
  }
@@ -1700,6 +2013,10 @@ export interface VercelSandboxProviderOptions {
1700
2013
  /** Test seam: the expected wall time of one `provision`. Defaults to
1701
2014
  * `VERCEL_PROVISION_ESTIMATE_MS`. */
1702
2015
  provisionEstimateMs?: number
2016
+ /** Composition and test seam, never configuration: per-stage provisioning
2017
+ * command bounds in milliseconds over the `VERCEL_*_TIMEOUT_MS` defaults. A
2018
+ * declared step's `timeoutSeconds` still beats `step`. */
2019
+ provisioningTimeouts?: Partial<VercelProvisioningTimeouts>
1703
2020
  /** Test seam: the expected wall time of one stopped-sandbox recovery, used
1704
2021
  * to admit it in a bounded invocation. Defaults to
1705
2022
  * `VERCEL_RECOVERY_ESTIMATE_MS`; `recoveryTimeoutMs` stays the ceiling. */
@@ -2004,7 +2321,19 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2004
2321
  restorationArchives?: 'local' | 'remote'
2005
2322
  restoreStored?: Parameters<WorkspaceProvider['provision']>[0]['restoreStored']
2006
2323
  adoptAbandoned?: boolean
2324
+ signal?: AbortSignal
2325
+ onProgress?: (progress: WorkspaceProvisionProgress) => void
2007
2326
  }): Promise<WorkspaceProvisionResult> {
2327
+ const invocation = opts.signal
2328
+ const report = (stage: string, step?: string): void => {
2329
+ try {
2330
+ opts.onProgress?.(step === undefined ? { stage } : { stage, step })
2331
+ } catch {
2332
+ // An observer never fails provisioning.
2333
+ }
2334
+ }
2335
+ const timeouts = resolveProvisioningTimeouts(this.options.provisioningTimeouts)
2336
+ const small = commandBound(timeouts, timeouts.command)
2008
2337
  const scopedToken = await (this.options.delegateCredential ?? delegateCredential)(
2009
2338
  this.options.storeRef,
2010
2339
  this.options.storeToken,
@@ -2047,9 +2376,12 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2047
2376
 
2048
2377
  let checkedOut = base
2049
2378
  if (sandbox !== null) {
2050
- const marker = await sandbox.runCommand({
2379
+ const marker = await runSandboxCommand(sandbox, {
2051
2380
  cmd: 'test',
2052
2381
  args: ['-f', VERCEL_PROVISIONED_MARKER],
2382
+ accept: () => true,
2383
+ ...(invocation === undefined ? {} : { signal: invocation }),
2384
+ ...small,
2053
2385
  })
2054
2386
  if (marker.exitCode === 0) {
2055
2387
  // A completed sandbox from an attempt that recorded nothing keeps the
@@ -2057,7 +2389,11 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2057
2389
  // since. Read it before any stop: a command after stop would resume
2058
2390
  // the persistent guest.
2059
2391
  try {
2060
- checkedOut = await checkedOutBranchHead(sandbox, opts.branch, this.operationSignal())
2392
+ checkedOut = await checkedOutBranchHead(
2393
+ sandbox,
2394
+ opts.branch,
2395
+ this.stageSignal(invocation),
2396
+ )
2061
2397
  } catch (error) {
2062
2398
  throw new WorkspaceCleanupRequired(
2063
2399
  {
@@ -2070,23 +2406,31 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2070
2406
  error,
2071
2407
  )
2072
2408
  }
2073
- const installed = await readDistributionVersionMarker(sandbox, this.operationSignal())
2409
+ const installed = await readDistributionVersionMarker(
2410
+ sandbox,
2411
+ this.stageSignal(invocation),
2412
+ invocation,
2413
+ )
2074
2414
  if (installed === distributionIdentity) {
2075
- await sandbox.stop({ signal: this.operationSignal() })
2415
+ await sandbox.stop({ signal: this.stageSignal(invocation) })
2076
2416
  } else {
2077
2417
  // A completed sandbox whose installed distribution disagrees with
2078
2418
  // what the current system would deliver — including legacy guests
2079
2419
  // without a marker — is refreshed in place. Any refresh failure
2080
2420
  // deletes the sandbox so the next pass rematerializes cleanly.
2421
+ report('distribution refresh')
2081
2422
  try {
2082
- await ensurePinnedBun(sandbox, this.options.config.image, this.operationSignal())
2083
- const archive = await this.archiveBytes()
2084
- await installDistribution(
2423
+ await ensurePinnedBun(
2085
2424
  sandbox,
2086
- archive,
2087
- distributionIdentity,
2088
- this.operationSignal(),
2425
+ this.options.config.image,
2426
+ invocation,
2427
+ commandBound(timeouts, timeouts.bun, 'bun install'),
2089
2428
  )
2429
+ const archive = await this.archiveBytes()
2430
+ await installDistribution(sandbox, archive, distributionIdentity, invocation, {
2431
+ bound: commandBound(timeouts, timeouts.distribution, 'distribution install'),
2432
+ writeSignal: this.stageSignal(invocation),
2433
+ })
2090
2434
  } catch (error) {
2091
2435
  throw new WorkspaceCleanupRequired(
2092
2436
  {
@@ -2099,7 +2443,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2099
2443
  error,
2100
2444
  )
2101
2445
  }
2102
- await sandbox.stop({ signal: this.operationSignal() })
2446
+ await sandbox.stop({ signal: this.stageSignal(invocation) })
2103
2447
  }
2104
2448
  } else if (!opts.adoptAbandoned) {
2105
2449
  // A named VM without the marker is a crashed/legacy provisioning
@@ -2119,13 +2463,17 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2119
2463
  // its own teardown, and its lease is gone. Finish the same sandbox in
2120
2464
  // place at the commit it cloned, resuming after its last completed
2121
2465
  // stage, but only after verification; any doubt still reaps it.
2466
+ report('adopt')
2122
2467
  try {
2123
2468
  // Quiesce first: stopping ends any command the dead invocation left
2124
2469
  // running, and the persistent guest resumes on the next command.
2125
- await sandbox.stop({ signal: this.operationSignal() })
2126
- const checkout = await sandbox.runCommand({
2470
+ await sandbox.stop({ signal: this.stageSignal(invocation) })
2471
+ const checkout = await runSandboxCommand(sandbox, {
2127
2472
  cmd: 'test',
2128
2473
  args: ['-e', `${VERCEL_WORKSPACE_PATH}/.git`],
2474
+ accept: () => true,
2475
+ ...(invocation === undefined ? {} : { signal: invocation }),
2476
+ ...small,
2129
2477
  })
2130
2478
  if (checkout.exitCode !== 0)
2131
2479
  throw new Error('abandoned provisioning left no checkout to finish')
@@ -2136,6 +2484,9 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2136
2484
  distributionIdentity,
2137
2485
  scopedToken,
2138
2486
  resume: true,
2487
+ ...(invocation === undefined ? {} : { signal: invocation }),
2488
+ report,
2489
+ timeouts,
2139
2490
  })
2140
2491
  } catch (error) {
2141
2492
  throw new WorkspaceCleanupRequired(
@@ -2165,6 +2516,9 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2165
2516
  password === undefined
2166
2517
  ? undefined
2167
2518
  : `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`
2519
+ // Create stays on its own acknowledgement bound: aborting it mid-flight
2520
+ // would leave a half-created VM nothing addresses.
2521
+ report('create')
2168
2522
  sandbox = await this.facade.create({
2169
2523
  name,
2170
2524
  source: {
@@ -2189,13 +2543,17 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2189
2543
  signal: this.operationSignal(),
2190
2544
  })
2191
2545
  try {
2192
- await relocateCheckout(sandbox, origin.directory)
2546
+ report('relocate')
2547
+ await relocateCheckout(sandbox, origin.directory, invocation, small)
2193
2548
  checkedOut = await this.completeProvisioning(sandbox, {
2194
2549
  origin,
2195
2550
  branch: opts.branch,
2196
2551
  base,
2197
2552
  distributionIdentity,
2198
2553
  scopedToken,
2554
+ ...(invocation === undefined ? {} : { signal: invocation }),
2555
+ report,
2556
+ timeouts,
2199
2557
  })
2200
2558
  } catch (error) {
2201
2559
  throw new WorkspaceCleanupRequired(
@@ -2213,31 +2571,38 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2213
2571
  let provisionHead = checkedOut
2214
2572
  let restorationSkipped: import('../types').RestorationSkip[] = []
2215
2573
  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
- })
2574
+ report('restoration')
2575
+ provisionHead = await this.withTrustedGit(
2576
+ sandbox,
2577
+ name,
2578
+ undefined,
2579
+ async (exec) => {
2580
+ restorationSkipped = (
2581
+ await restoreGitCommits({
2582
+ exec,
2583
+ workspacePath: VERCEL_WORKSPACE_PATH,
2584
+ branch: opts.branch,
2585
+ heads: opts.restoration!,
2586
+ replaced: opts.restorationReplaced,
2587
+ // Store copies are read host-side and applied over the trusted
2588
+ // transport; the guest never holds store credentials.
2589
+ ...(opts.restoreStored
2590
+ ? {
2591
+ restoreStored: (sha: string) =>
2592
+ opts.restoreStored!({ exec, workspacePath: VERCEL_WORKSPACE_PATH, sha }),
2593
+ }
2594
+ : {}),
2595
+ })
2596
+ ).skipped
2597
+ const result = await exec(
2598
+ ['git', 'rev-parse', '--verify', `refs/heads/${opts.branch}^{commit}`],
2599
+ { cwd: VERCEL_WORKSPACE_PATH },
2600
+ )
2601
+ if (result.exitCode !== 0) throw new Error('cannot confirm restored workspace branch')
2602
+ return result.stdout.trim()
2603
+ },
2604
+ invocation,
2605
+ )
2241
2606
  }
2242
2607
  this.origins.set(name, origin)
2243
2608
  this.sessions.set(name, sandbox)
@@ -2277,19 +2642,28 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2277
2642
  /** Finish an abandoned attempt: keep the cloned commit, skip completed
2278
2643
  * stages, and require no tracked modifications. */
2279
2644
  resume?: boolean
2645
+ /** The invocation's teardown signal: every guest command stops on it. */
2646
+ signal?: AbortSignal
2647
+ /** Reports the stage (and step) about to run. */
2648
+ report: (stage: string, step?: string) => void
2649
+ timeouts: VercelProvisioningTimeouts
2280
2650
  },
2281
2651
  ): Promise<string> {
2282
- const { origin, branch, distributionIdentity, scopedToken } = input
2652
+ const { origin, branch, distributionIdentity, scopedToken, report, timeouts } = input
2283
2653
  const resume = input.resume === true
2284
- const head = resume ? await guestHeadCommit(sandbox, this.operationSignal()) : input.base
2654
+ const invocation = input.signal
2655
+ const cancel = invocation === undefined ? {} : { signal: invocation }
2656
+ const small = commandBound(timeouts, timeouts.command)
2657
+ const head = resume ? await guestHeadCommit(sandbox, this.stageSignal(invocation)) : input.base
2285
2658
  const checkpoints = resume
2286
- ? await readProvisionCheckpoints(sandbox, this.operationSignal())
2659
+ ? await readProvisionCheckpoints(sandbox, invocation, small)
2287
2660
  : new Map<string, string>()
2288
2661
  let previous = ''
2289
2662
  let executing = !resume
2290
2663
  const kept = new Set<string>()
2291
2664
  const stage = async (
2292
2665
  key: string,
2666
+ label: { stage: string; step?: string },
2293
2667
  inputs: unknown,
2294
2668
  run: () => Promise<void>,
2295
2669
  skipped?: () => Promise<void>,
@@ -2306,49 +2680,59 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2306
2680
  await clearProvisionCheckpoints(
2307
2681
  sandbox,
2308
2682
  [...checkpoints.keys()].filter((existing) => !kept.has(existing)),
2309
- this.operationSignal(),
2683
+ invocation,
2684
+ small,
2310
2685
  )
2311
2686
  executing = true
2312
2687
  }
2688
+ report(label.stage, label.step)
2313
2689
  await run()
2314
- await writeProvisionCheckpoint(sandbox, key, fingerprint, this.operationSignal())
2690
+ await writeProvisionCheckpoint(sandbox, key, fingerprint, invocation, small)
2315
2691
  }
2316
2692
  previous = fingerprint
2317
2693
  }
2318
2694
 
2695
+ const checkout = commandBound(timeouts, timeouts.command, 'checkout')
2319
2696
  await stage(
2320
2697
  '01-checkout',
2698
+ { stage: 'checkout' },
2321
2699
  { branch, origin: origin.url, head },
2322
2700
  async () => {
2323
2701
  await commandOrThrow(sandbox, {
2324
2702
  cmd: 'git',
2325
2703
  args: ['checkout', '-B', branch, head],
2326
2704
  cwd: VERCEL_WORKSPACE_PATH,
2705
+ ...cancel,
2706
+ ...checkout,
2327
2707
  })
2328
- const checked = await checkedOutBranchHead(sandbox, branch, this.operationSignal())
2708
+ const checked = await checkedOutBranchHead(sandbox, branch, this.stageSignal(invocation))
2329
2709
  if (checked !== head)
2330
2710
  throw new Error(`checked out ${branch} at ${checked}, expected selected base ${head}`)
2331
2711
  await commandOrThrow(sandbox, {
2332
2712
  cmd: 'git',
2333
2713
  args: ['remote', 'set-url', 'origin', origin.url],
2334
2714
  cwd: VERCEL_WORKSPACE_PATH,
2715
+ ...cancel,
2716
+ ...checkout,
2335
2717
  })
2336
2718
  for (const key of [
2337
2719
  'credential.helper',
2338
2720
  'http.extraheader',
2339
2721
  `http.${origin.url}.extraheader`,
2340
2722
  ]) {
2341
- const result = await sandbox.runCommand({
2723
+ // Exit 5: the key was not set.
2724
+ await commandOrThrow(sandbox, {
2342
2725
  cmd: 'git',
2343
2726
  args: ['config', '--local', '--unset-all', key],
2344
2727
  cwd: VERCEL_WORKSPACE_PATH,
2728
+ accept: (code) => code === 0 || code === 5,
2729
+ ...cancel,
2730
+ ...checkout,
2345
2731
  })
2346
- if (result.exitCode !== 0 && result.exitCode !== 5)
2347
- throw new Error(`failed to scrub git config ${key}`)
2348
2732
  }
2349
2733
  },
2350
2734
  async () => {
2351
- const checked = await checkedOutBranchHead(sandbox, branch, this.operationSignal())
2735
+ const checked = await checkedOutBranchHead(sandbox, branch, this.stageSignal(invocation))
2352
2736
  if (checked !== head)
2353
2737
  throw new Error(`checked out ${branch} at ${checked}, expected cloned head ${head}`)
2354
2738
  },
@@ -2356,40 +2740,69 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2356
2740
  if (resume) {
2357
2741
  // A finished abandoned attempt must not expose tracked edits the dead
2358
2742
  // invocation may have left behind.
2359
- const diff = await sandbox.runCommand({
2743
+ const diff = await runSandboxCommand(sandbox, {
2360
2744
  cmd: 'git',
2361
2745
  args: ['diff', '--quiet', 'HEAD', '--'],
2362
2746
  cwd: VERCEL_WORKSPACE_PATH,
2747
+ accept: () => true,
2748
+ ...cancel,
2749
+ ...small,
2363
2750
  })
2364
2751
  if (diff.exitCode !== 0) throw new Error('abandoned provisioning left tracked modifications')
2365
2752
  }
2366
2753
  const image = this.options.config.image
2367
- await stage('02-bun', { version: VERCEL_BUN_VERSION, image }, () =>
2368
- provisionBun(sandbox, image),
2754
+ await stage('02-bun', { stage: 'bun install' }, { version: VERCEL_BUN_VERSION, image }, () =>
2755
+ provisionBun(sandbox, image, invocation, commandBound(timeouts, timeouts.bun, 'bun install')),
2369
2756
  )
2370
2757
  const steps = this.options.config.provisioning ?? []
2371
2758
  for (const [index, step] of steps.entries()) {
2372
- await stage(`03-step-${index}`, { name: step.name, command: step.command }, () =>
2373
- runSystemProvisioningStep(sandbox, step),
2759
+ // The fingerprint deliberately omits `timeoutSeconds`: a bound change
2760
+ // never reruns a completed step.
2761
+ await stage(
2762
+ `03-step-${index}`,
2763
+ { stage: 'system provisioning step', step: step.name },
2764
+ { name: step.name, command: step.command },
2765
+ () =>
2766
+ runSystemProvisioningStep(
2767
+ sandbox,
2768
+ step,
2769
+ invocation,
2770
+ commandBound(timeouts, timeouts.step),
2771
+ ),
2374
2772
  )
2375
2773
  }
2376
- await stage('04-distribution', { identity: distributionIdentity }, async () => {
2377
- const archive = await this.archiveBytes()
2378
- await installDistribution(sandbox, archive, distributionIdentity, this.operationSignal())
2379
- })
2774
+ await stage(
2775
+ '04-distribution',
2776
+ { stage: 'distribution install' },
2777
+ { identity: distributionIdentity },
2778
+ async () => {
2779
+ const archive = await this.archiveBytes()
2780
+ await installDistribution(sandbox, archive, distributionIdentity, invocation, {
2781
+ bound: commandBound(timeouts, timeouts.distribution, 'distribution install'),
2782
+ writeSignal: this.stageSignal(invocation),
2783
+ })
2784
+ },
2785
+ )
2380
2786
  // Repository dependencies precede branch-owned package plugin loading.
2381
2787
  // The fixed bootstrap supports the consuming repository's lockfile; its
2382
2788
  // 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
- }),
2789
+ await stage(
2790
+ '05-dependencies',
2791
+ { stage: 'dependency install' },
2792
+ { command: DEPENDENCY_INSTALL_COMMAND },
2793
+ () =>
2794
+ commandOrThrow(sandbox, {
2795
+ cmd: 'sh',
2796
+ args: ['-c', DEPENDENCY_INSTALL_COMMAND],
2797
+ cwd: VERCEL_WORKSPACE_PATH,
2798
+ ...cancel,
2799
+ ...commandBound(timeouts, timeouts.dependencies, 'dependency install'),
2800
+ }),
2389
2801
  )
2390
2802
  const references = currentRuntimeReferences(this.options.runtimeReferences)
2391
2803
  await stage(
2392
2804
  '06-runtimes',
2805
+ { stage: 'runtime bootstrap' },
2393
2806
  [...references]
2394
2807
  .sort((left, right) =>
2395
2808
  left.runtime < right.runtime ? -1 : left.runtime > right.runtime ? 1 : 0,
@@ -2410,13 +2823,21 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2410
2823
  { ...this.guestEnvironment(), AB_TOKEN: scopedToken },
2411
2824
  references,
2412
2825
  true,
2826
+ invocation,
2827
+ {
2828
+ bound: commandBound(timeouts, timeouts.runtime),
2829
+ onStage: (step) => report('runtime bootstrap', step),
2830
+ },
2413
2831
  ),
2414
2832
  )
2833
+ report('finalize')
2415
2834
  await commandOrThrow(sandbox, {
2416
2835
  cmd: 'touch',
2417
2836
  args: [VERCEL_PROVISIONED_MARKER],
2837
+ ...cancel,
2838
+ ...commandBound(timeouts, timeouts.command, 'finalize'),
2418
2839
  })
2419
- await sandbox.stop({ signal: this.operationSignal() })
2840
+ await sandbox.stop({ signal: this.stageSignal(invocation) })
2420
2841
  return head
2421
2842
  }
2422
2843
 
@@ -2429,6 +2850,14 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2429
2850
  return AbortSignal.timeout(this.operationTimeoutMs())
2430
2851
  }
2431
2852
 
2853
+ /** A metadata call inside provisioning: its own acknowledgement bound, and
2854
+ * stopped by the invocation's teardown signal. */
2855
+ private stageSignal(invocation?: AbortSignal): AbortSignal {
2856
+ return invocation === undefined
2857
+ ? this.operationSignal()
2858
+ : AbortSignal.any([this.operationSignal(), invocation])
2859
+ }
2860
+
2432
2861
  private operationTimeoutMs(): number {
2433
2862
  return this.options.config.operationTimeoutMs ?? 30_000
2434
2863
  }
@@ -4891,6 +5320,9 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4891
5320
  ref: string,
4892
5321
  signal: AbortSignal | undefined,
4893
5322
  effect: (exec: Exec) => Promise<T>,
5323
+ /** Also stops each guest command (provisioning restore at teardown);
5324
+ * each keeps its own acknowledgement cap. */
5325
+ cancel?: AbortSignal,
4894
5326
  ): Promise<T> {
4895
5327
  const { origin } = await this.normalNetworkPolicy(ref)
4896
5328
  const token = this.options.env.GITHUB_TOKEN || this.options.env.GH_TOKEN
@@ -4927,7 +5359,11 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4927
5359
  { signal: this.recoveryMetadataSignal() },
4928
5360
  )
4929
5361
  return await effect(async (cmd) => {
4930
- const bound = signal ?? this.operationSignal()
5362
+ const bound =
5363
+ signal ??
5364
+ (cancel === undefined
5365
+ ? this.operationSignal()
5366
+ : AbortSignal.any([this.operationSignal(), cancel]))
4931
5367
  const result = await sandbox.runCommand({
4932
5368
  cmd: cmd[0]!,
4933
5369
  args: cmd.slice(1),