@defrex/autobuild 1.10.0 → 1.11.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.
- package/README.md +1 -1
- package/SPEC.md +738 -68
- package/bin/ab-dispatch-generation.ts +3 -1
- package/docs/accounts.md +2 -1
- package/docs/answering-blocked-builds.md +20 -0
- package/docs/architecture.md +155 -25
- package/docs/build-store.md +10 -7
- package/docs/cli.md +33 -1
- package/docs/configuration-overview.md +4 -1
- package/docs/configuration.md +381 -29
- package/docs/dispatcher.md +63 -4
- package/docs/forges.md +7 -0
- package/docs/integration-tree.md +2 -2
- package/docs/operating.md +4 -2
- package/docs/operator-api.md +134 -6
- package/docs/operator-surfaces.md +85 -0
- package/docs/optimization-nodes.md +69 -11
- package/docs/plugin-authoring.md +37 -1
- package/docs/remote-store-protocol.md +94 -13
- package/docs/remote-ticket-protocol.md +40 -0
- package/docs/restacking.md +20 -4
- package/docs/setup.md +14 -2
- package/docs/ticket-dependencies.md +10 -3
- package/docs/ticket-sources.md +24 -2
- package/docs/tickets.md +7 -1
- package/docs/troubleshooting.md +8 -0
- package/docs/verification.md +4 -3
- package/docs/workspaces.md +3 -0
- package/package.json +9 -5
- package/packages/core/src/cli/accounts.ts +7 -2
- package/packages/core/src/cli/attention.ts +3 -1
- package/packages/core/src/cli/binary-direct.ts +2 -0
- package/packages/core/src/cli/binary-lifecycle.ts +2 -1
- package/packages/core/src/cli/build-control.ts +79 -1
- package/packages/core/src/cli/context.ts +4 -0
- package/packages/core/src/cli/dashboard/facts.ts +49 -53
- package/packages/core/src/cli/dashboard/header.ts +101 -0
- package/packages/core/src/cli/dashboard/model.ts +31 -39
- package/packages/core/src/cli/dashboard/objective-row.ts +46 -14
- package/packages/core/src/cli/dashboard/poll.ts +178 -76
- package/packages/core/src/cli/dashboard/render.ts +129 -230
- package/packages/core/src/cli/dashboard/row-text.ts +538 -0
- package/packages/core/src/cli/dashboard/timeline.ts +288 -0
- package/packages/core/src/cli/dashboard/vocabulary.ts +188 -0
- package/packages/core/src/cli/dispatch-args.ts +44 -1
- package/packages/core/src/cli/dispatch-frontend.ts +29 -38
- package/packages/core/src/cli/dispatch-launch-stop.ts +18 -0
- package/packages/core/src/cli/dispatch-launcher.ts +20 -7
- package/packages/core/src/cli/dispatch-web.ts +155 -0
- package/packages/core/src/cli/dispatch.ts +200 -34
- package/packages/core/src/cli/help.ts +87 -3
- package/packages/core/src/cli/init-validation.ts +3 -3
- package/packages/core/src/cli/main.ts +70 -6
- package/packages/core/src/cli/mcp.ts +35 -3
- package/packages/core/src/cli/objective.ts +1 -1
- package/packages/core/src/cli/operator-preference.ts +57 -0
- package/packages/core/src/cli/repo-lease.ts +2 -0
- package/packages/core/src/cli/repo-state.ts +56 -6
- package/packages/core/src/cli/repository-status.ts +97 -43
- package/packages/core/src/cli/status.ts +82 -1
- package/packages/core/src/cli/terminal-restore.ts +32 -7
- package/packages/core/src/cli/ticket.ts +98 -36
- package/packages/core/src/cli/wait.ts +14 -6
- package/packages/core/src/cli/watch.ts +20 -4
- package/packages/core/src/cli/web.ts +139 -0
- package/packages/core/src/config/live.ts +99 -14
- package/packages/core/src/config/load.ts +61 -20
- package/packages/core/src/config/local.ts +212 -0
- package/packages/core/src/config/pipeline-source.ts +2 -0
- package/packages/core/src/config/reference.ts +18 -0
- package/packages/core/src/config/schema.ts +45 -10
- package/packages/core/src/events/catalog.ts +4 -0
- package/packages/core/src/events/payloads.ts +97 -0
- package/packages/core/src/events/policy.ts +10 -0
- package/packages/core/src/events/repository.ts +46 -3
- package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +316 -0
- package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/017d8dd5bb6dd80b.json.gz +0 -0
- package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/178e12f1759b7552.json.gz +0 -0
- package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4932c70a2af97faf.json.gz +0 -0
- package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/536085773daf6b58.json.gz +0 -0
- package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6bd6275061aaffa5.json.gz +0 -0
- package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/89625654b02e9ac1.json.gz +0 -0
- package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a98af134be2da8a9.json.gz +0 -0
- package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d5d5ccca80a893d8.json.gz +0 -0
- package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f8155387eb5f375c.json.gz +0 -0
- package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3c27f918b194e3b3.json +465 -0
- package/packages/core/src/kernel/__snapshots__/reducer-identity-records/79f0e0f4ccd43ba2.json +455 -0
- package/packages/core/src/kernel/__snapshots__/reducer-identity-records/859c09edac738823.json +1086 -0
- package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a283c1f3462b1cc1.json +81 -0
- package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a6e570fb126991ff.json +36 -0
- package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a8acf22c968b6e3d.json +81 -0
- package/packages/core/src/kernel/__snapshots__/reducer-identity-records/ba7b85895bf6698e.json +1153 -0
- package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fc66408cde0b6b04.json +637 -0
- package/packages/core/src/kernel/build-roster.ts +230 -0
- package/packages/core/src/kernel/dispatch-capacity.ts +4 -2
- package/packages/core/src/kernel/engine.ts +43 -5
- package/packages/core/src/kernel/execution-intervals.ts +61 -0
- package/packages/core/src/kernel/generators/optimization-log.ts +101 -0
- package/packages/core/src/kernel/generators/repository-journals.ts +13 -0
- package/packages/core/src/kernel/leaf-restack-base.ts +33 -7
- package/packages/core/src/kernel/leaf-restack-state.ts +82 -3
- package/packages/core/src/kernel/log-index.ts +19 -0
- package/packages/core/src/kernel/optimization-admission.ts +244 -3
- package/packages/core/src/kernel/optimization.ts +183 -4
- package/packages/core/src/kernel/phase-failures.ts +121 -0
- package/packages/core/src/kernel/published-branch-head.ts +60 -0
- package/packages/core/src/kernel/reducer-registry.ts +27 -8
- package/packages/core/src/kernel/reducer-revisions.ts +25 -0
- package/packages/core/src/kernel/reducer.ts +63 -4
- package/packages/core/src/kernel/rollup.ts +61 -0
- package/packages/core/src/kernel/setup-streak.ts +38 -0
- package/packages/core/src/kernel/step-durations.ts +257 -0
- package/packages/core/src/kernel/target-observation.ts +6 -1
- package/packages/core/src/kernel/target-rewrite-recovery.ts +116 -0
- package/packages/core/src/kernel/verify-diff-base.ts +5 -0
- package/packages/core/src/kernel/verify-stages.ts +13 -3
- package/packages/core/src/ontology.ts +5 -0
- package/packages/core/src/operator/agent-context-serve.ts +631 -0
- package/packages/core/src/operator/annotations.ts +75 -5
- package/packages/core/src/operator/attention.ts +470 -0
- package/packages/core/src/operator/canonical-skills.ts +35 -0
- package/packages/core/src/operator/cli-equivalents.ts +270 -0
- package/packages/core/src/operator/context-prompts.ts +61 -0
- package/packages/core/src/operator/index.ts +49 -1
- package/packages/core/src/operator/landings.ts +28 -19
- package/packages/core/src/operator/optimization.ts +7 -0
- package/packages/core/src/operator/protocol.ts +3 -0
- package/packages/core/src/operator/query.ts +122 -72
- package/packages/core/src/operator/read-view.ts +5 -2
- package/packages/core/src/operator/registry.ts +406 -46
- package/packages/core/src/operator/requests.ts +20 -18
- package/packages/core/src/operator/sandbox-host.ts +107 -11
- package/packages/core/src/operator/sandbox-resolver.ts +253 -0
- package/packages/core/src/operator/sandbox.ts +778 -82
- package/packages/core/src/operator/ticket-asset-list.ts +77 -0
- package/packages/core/src/operator/ticket-assets.ts +167 -0
- package/packages/core/src/operator/tickets.ts +33 -2
- package/packages/core/src/plugin-sdk/index.ts +22 -0
- package/packages/core/src/plugins/manifest.ts +1 -1
- package/packages/core/src/ports/forge/fake.ts +92 -1
- package/packages/core/src/ports/forge/git-blob.ts +15 -0
- package/packages/core/src/ports/forge/github.ts +82 -0
- package/packages/core/src/ports/forge/local-git.ts +61 -1
- package/packages/core/src/ports/forge-failure.ts +24 -0
- package/packages/core/src/ports/runner/antigravity-test.fixture.ts +149 -0
- package/packages/core/src/ports/runner/claude-test.fixture.ts +71 -0
- package/packages/core/src/ports/runner/codex-test.fixture.ts +63 -0
- package/packages/core/src/ports/tickets/contract.ts +71 -0
- package/packages/core/src/ports/tickets/fake.ts +11 -0
- package/packages/core/src/ports/tickets/file.ts +18 -0
- package/packages/core/src/ports/tickets/github-fake.ts +136 -4
- package/packages/core/src/ports/tickets/github.ts +387 -30
- package/packages/core/src/ports/tickets/hosted-index.ts +10 -0
- package/packages/core/src/ports/tickets/linear.ts +130 -0
- package/packages/core/src/ports/tickets/priority.ts +9 -0
- package/packages/core/src/ports/tickets/remote-protocol.ts +34 -0
- package/packages/core/src/ports/tickets/remote.ts +70 -6
- package/packages/core/src/ports/tickets/search.ts +139 -0
- package/packages/core/src/ports/types.ts +104 -2
- package/packages/core/src/ports/workspace/builtin-capabilities.ts +9 -0
- package/packages/core/src/ports/workspace/create.ts +15 -1
- package/packages/core/src/ports/workspace/fake.ts +340 -12
- package/packages/core/src/ports/workspace/git-worktree.ts +833 -42
- package/packages/core/src/ports/workspace/operator-sandbox.ts +129 -12
- package/packages/core/src/ports/workspace/process-group.ts +48 -0
- package/packages/core/src/ports/workspace/vercel-sandbox.ts +1260 -123
- package/packages/core/src/processes/agent-context-assemble.ts +576 -0
- package/packages/core/src/processes/agent-context.ts +469 -0
- package/packages/core/src/processes/build-runner.ts +387 -236
- package/packages/core/src/processes/dispatcher.ts +211 -55
- package/packages/core/src/processes/execution-no-progress.ts +4 -0
- package/packages/core/src/processes/optimization-activity.ts +120 -0
- package/packages/core/src/processes/phase-failure-budget.ts +1 -0
- package/packages/core/src/processes/repo-view.ts +78 -2
- package/packages/core/src/processes/sandbox-state.ts +53 -6
- package/packages/core/src/processes/tick-publication.ts +2 -0
- package/packages/core/src/processes/workspace-preparation.ts +76 -0
- package/packages/core/src/scenarios/harness.ts +0 -5
- package/packages/core/src/store/account-redaction.ts +1 -0
- package/packages/core/src/store/adapter.ts +52 -1
- package/packages/core/src/store/agent-context.ts +432 -0
- package/packages/core/src/store/build-feed.ts +291 -0
- package/packages/core/src/store/build-scope.ts +19 -1
- package/packages/core/src/store/contract.ts +911 -14
- package/packages/core/src/store/digest.ts +19 -6
- package/packages/core/src/store/histogram.ts +113 -0
- package/packages/core/src/store/local/schema.ts +62 -0
- package/packages/core/src/store/local/store.ts +628 -22
- package/packages/core/src/store/local/ticket-asset-heads.ts +23 -0
- package/packages/core/src/store/memory.ts +461 -69
- package/packages/core/src/store/open-builds.ts +19 -0
- package/packages/core/src/store/phase-session.ts +32 -4
- package/packages/core/src/store/reduced-reads.ts +14 -4
- package/packages/core/src/store/reducer-value-shapes.json +6987 -5749
- package/packages/core/src/store/reducer-values.ts +6 -1
- package/packages/core/src/store/remote/client.ts +208 -2
- package/packages/core/src/store/remote/compatibility.ts +1 -1
- package/packages/core/src/store/remote/index.ts +33 -0
- package/packages/core/src/store/remote/protocol.ts +69 -0
- package/packages/core/src/store/remote/released-clients.json +11 -0
- package/packages/core/src/store/remote/released-reducer-values/1.11.0.json +35680 -0
- package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
- package/packages/core/src/store/retention.ts +23 -1
- package/packages/core/src/store/rollups.ts +337 -0
- package/packages/core/src/store/session-handle.ts +20 -2
- package/packages/core/src/store/snapshots.ts +10 -0
- package/packages/core/src/store/types.ts +108 -9
- package/packages/core/src/testing/dispatch-read-budget.ts +1092 -2
- package/packages/core/src/testing/git-config-isolation.ts +7 -5
- package/packages/core/src/testing/index.ts +27 -0
- package/packages/core/src/testing/memory-operator-sandbox.ts +346 -0
- package/packages/core/src/testing/reduced-read-budget.ts +1873 -98
- package/packages/core/src/web/analytics-source.ts +303 -0
- package/packages/core/src/web/assets/Atkinson-OFL.txt +93 -0
- package/packages/core/src/web/assets/AtkinsonHyperlegibleNext.latin.woff2 +0 -0
- package/packages/core/src/web/assets/JetBrains-OFL.txt +93 -0
- package/packages/core/src/web/assets/JetBrainsMono.latin.woff2 +0 -0
- package/packages/core/src/web/assets/app.css +1 -0
- package/packages/core/src/web/assets/app.js +9 -0
- package/packages/core/src/web/assets/manifest.json +31 -0
- package/packages/core/src/web/assets/theme.js +1 -0
- package/packages/core/src/web/bounded.ts +31 -0
- package/packages/core/src/web/http.ts +315 -0
- package/packages/core/src/web/hub.ts +160 -0
- package/packages/core/src/web/options.ts +38 -0
- package/packages/core/src/web/overview-source.ts +322 -0
- package/packages/core/src/web/page.ts +56 -0
- package/packages/core/src/web/protocol.ts +151 -0
- package/packages/core/src/web/read-only.ts +23 -0
- package/packages/core/src/web/repository-source.ts +35 -0
- package/packages/core/src/web/server.ts +97 -0
- package/skills/code-review/SKILL.md +10 -2
- package/skills/guide/SKILL.md +366 -52
- package/skills/guide/references/accounts.md +2 -1
- package/skills/guide/references/integration-tree.md +2 -2
- package/skills/guide/references/operator-api.md +134 -6
- package/skills/guide/references/optimization-nodes.md +69 -11
- package/skills/guide/references/plugin-authoring.md +37 -1
- package/skills/guide/references/remote-store-protocol.md +94 -13
- package/skills/guide/references/remote-ticket-protocol.md +40 -0
- package/skills/guide/references/restacking.md +20 -4
- package/skills/guide/references/setup.md +14 -2
- package/skills/guide/references/ticket-dependencies.md +10 -3
- package/skills/implement/SKILL.md +23 -4
- package/skills/operate/SKILL.md +134 -32
- package/skills/plan/SKILL.md +10 -4
- package/skills/plan-review/SKILL.md +9 -2
- package/skills/spec/SKILL.md +34 -8
- package/skills/tickets/SKILL.md +51 -5
- package/templates/hosted-service/package.json +2 -2
|
@@ -34,7 +34,14 @@ import {
|
|
|
34
34
|
type SandboxCommandRequest,
|
|
35
35
|
type SandboxCommandResult,
|
|
36
36
|
type SandboxEnvironmentIdentity,
|
|
37
|
+
type SandboxProviderStatus,
|
|
38
|
+
type SandboxProvisionStage,
|
|
39
|
+
type SandboxRefreshResult,
|
|
37
40
|
type SandboxWaitResult,
|
|
41
|
+
redactSandboxMessage,
|
|
42
|
+
SANDBOX_INTERRUPTED_MESSAGE,
|
|
43
|
+
SANDBOX_REFRESH_DIRTY_MESSAGE,
|
|
44
|
+
sandboxRefreshDivergedMessage,
|
|
38
45
|
} from './operator-sandbox'
|
|
39
46
|
import type {
|
|
40
47
|
BuildExecution,
|
|
@@ -186,14 +193,19 @@ export interface VercelSandboxHandle {
|
|
|
186
193
|
stop(opts?: { signal?: AbortSignal }): Promise<unknown>
|
|
187
194
|
delete(opts?: { signal?: AbortSignal }): Promise<void>
|
|
188
195
|
update(
|
|
189
|
-
params: { networkPolicy
|
|
196
|
+
params: { networkPolicy?: NetworkPolicy; timeout?: number },
|
|
190
197
|
opts?: { signal?: AbortSignal },
|
|
191
198
|
): Promise<unknown>
|
|
199
|
+
/** Add `duration` ms to the running session's lifetime (SDK
|
|
200
|
+
* `extendTimeout`: additive, never a set). */
|
|
201
|
+
extendTimeout(duration: number, opts?: { signal?: AbortSignal }): Promise<void>
|
|
192
202
|
}
|
|
193
203
|
|
|
194
204
|
export type VercelSandboxCreateInput = {
|
|
195
205
|
name: string
|
|
196
|
-
source
|
|
206
|
+
/** Absent starts a sandbox without a git source (SDK 3.1.0); only the
|
|
207
|
+
* deployment-fallback operator sandbox omits it and clones in the guest. */
|
|
208
|
+
source?: {
|
|
197
209
|
type: 'git'
|
|
198
210
|
url: string
|
|
199
211
|
revision: string
|
|
@@ -645,6 +657,30 @@ async function relocateCheckout(
|
|
|
645
657
|
}
|
|
646
658
|
}
|
|
647
659
|
|
|
660
|
+
/** Clone the bare HTTPS origin inside the guest with no credential in argv,
|
|
661
|
+
* env or git config; the host-side upload-pack egress transform authenticates
|
|
662
|
+
* the two upload-pack requests. `GIT_TERMINAL_PROMPT=0` makes a missing
|
|
663
|
+
* transform fail fast instead of prompting. */
|
|
664
|
+
async function guestCloneCheckout(
|
|
665
|
+
sandbox: VercelSandboxHandle,
|
|
666
|
+
url: string,
|
|
667
|
+
head: string,
|
|
668
|
+
): Promise<void> {
|
|
669
|
+
await commandOrThrow(sandbox, {
|
|
670
|
+
cmd: 'mkdir',
|
|
671
|
+
args: ['-p', VERCEL_WORKSPACE_PATH.slice(0, VERCEL_WORKSPACE_PATH.lastIndexOf('/'))],
|
|
672
|
+
})
|
|
673
|
+
await commandOrThrow(sandbox, {
|
|
674
|
+
cmd: 'git',
|
|
675
|
+
args: ['clone', '--no-checkout', url, VERCEL_WORKSPACE_PATH],
|
|
676
|
+
env: { GIT_TERMINAL_PROMPT: '0' },
|
|
677
|
+
})
|
|
678
|
+
await commandOrThrow(sandbox, {
|
|
679
|
+
cmd: 'git',
|
|
680
|
+
args: ['-C', VERCEL_WORKSPACE_PATH, 'checkout', '--detach', head],
|
|
681
|
+
})
|
|
682
|
+
}
|
|
683
|
+
|
|
648
684
|
async function commandOrThrow(
|
|
649
685
|
sandbox: VercelSandboxHandle,
|
|
650
686
|
params: {
|
|
@@ -1249,6 +1285,201 @@ async function effectiveArchive(
|
|
|
1249
1285
|
return (await resolveDistributionArchive()).archive
|
|
1250
1286
|
}
|
|
1251
1287
|
|
|
1288
|
+
// ── Operator sandbox provisioning state (#1246) ─────────────────────────────
|
|
1289
|
+
//
|
|
1290
|
+
// A hosted deployment composes the provider per warm function instance and
|
|
1291
|
+
// may freeze it after the response, so provisioning state lives in the
|
|
1292
|
+
// guest, where any process can read it with one probe command. The host
|
|
1293
|
+
// phase (create, checkout, scrub, Bun, system provisioning, distribution)
|
|
1294
|
+
// runs in the caller's background; the slow tail (dependencies, runtimes,
|
|
1295
|
+
// setup, marker) runs as one detached guest command bounded only by the
|
|
1296
|
+
// session timer.
|
|
1297
|
+
|
|
1298
|
+
/** The guest directory holding one fresh provision's state, outside the
|
|
1299
|
+
* checkout: `host` (`<step> <guest epoch seconds>`, the host phase's
|
|
1300
|
+
* heartbeat), one `stage-NN-<name>.sh` per tail stage, `tail.sh`, the
|
|
1301
|
+
* tail's `pid`, `stage`, `log` and `failed` files, and `resuming` (the guest
|
|
1302
|
+
* epoch at which a runtime refresh of a provisioned environment started),
|
|
1303
|
+
* which outranks the success marker until that refresh succeeds. */
|
|
1304
|
+
export const VERCEL_OPERATOR_PROVISION_DIR = `${VERCEL_AUTOBUILD_PATH}/operator-provision`
|
|
1305
|
+
/** Heartbeat age after which a host phase with no running tail counts as
|
|
1306
|
+
* interrupted: above the 300-second hosted function limit, and every host
|
|
1307
|
+
* step refreshes the heartbeat. A host step longer than this on a long-lived
|
|
1308
|
+
* local `ab mcp` can be judged interrupted by another process; the journal's
|
|
1309
|
+
* compare-and-append still settles it once and the next open recovers. */
|
|
1310
|
+
export const VERCEL_OPERATOR_HOST_STALE_SECONDS = 600
|
|
1311
|
+
/** Grace after the `launched` heartbeat for the detached tail to record its
|
|
1312
|
+
* pid before a missing tail counts as interrupted. */
|
|
1313
|
+
export const VERCEL_OPERATOR_LAUNCH_GRACE_SECONDS = 30
|
|
1314
|
+
|
|
1315
|
+
/** Host-phase heartbeat steps. `launched` follows the tail launch. */
|
|
1316
|
+
type OperatorHostStep = 'checkout' | 'provision' | 'launched'
|
|
1317
|
+
|
|
1318
|
+
const PROVISION_STAGES: readonly SandboxProvisionStage[] = [
|
|
1319
|
+
'checkout',
|
|
1320
|
+
'setup',
|
|
1321
|
+
'environment',
|
|
1322
|
+
'resume',
|
|
1323
|
+
'provision',
|
|
1324
|
+
]
|
|
1325
|
+
|
|
1326
|
+
/** One classified probe of an operator sandbox's guest state. Rows are
|
|
1327
|
+
* checked in order and the first match wins: a recorded failure always
|
|
1328
|
+
* outranks an older success marker. */
|
|
1329
|
+
export type VercelOperatorProbe =
|
|
1330
|
+
| { kind: 'failed'; record: string; log: string }
|
|
1331
|
+
| { kind: 'resuming'; ageSeconds: number }
|
|
1332
|
+
| {
|
|
1333
|
+
kind: 'ready'
|
|
1334
|
+
marker: { baseSha?: string }
|
|
1335
|
+
headSha?: string
|
|
1336
|
+
bunVersion?: string
|
|
1337
|
+
distribution?: string
|
|
1338
|
+
}
|
|
1339
|
+
| { kind: 'running'; stage?: string }
|
|
1340
|
+
| { kind: 'host'; step: string; ageSeconds: number }
|
|
1341
|
+
| { kind: 'none' }
|
|
1342
|
+
|
|
1343
|
+
/** The read-only probe, run as `sh -c <script> probe <dir> <marker>
|
|
1344
|
+
* <workspace> <bun> <distribution marker>` with no environment. File
|
|
1345
|
+
* contents ride base64-encoded so the parser never sees raw guest bytes;
|
|
1346
|
+
* ages come from the guest clock. */
|
|
1347
|
+
export const VERCEL_OPERATOR_PROBE_SCRIPT = [
|
|
1348
|
+
'd=$1',
|
|
1349
|
+
'enc() { base64 | tr -d "\\n"; }',
|
|
1350
|
+
'if [ -f "$d/failed" ]; then',
|
|
1351
|
+
' echo "result failed"',
|
|
1352
|
+
' printf "failed %s\\n" "$(head -c 4096 "$d/failed" | enc)"',
|
|
1353
|
+
' printf "log %s\\n" "$(tail -c 4096 "$d/log" 2>/dev/null | enc)"',
|
|
1354
|
+
' exit 0',
|
|
1355
|
+
'fi',
|
|
1356
|
+
'if [ -f "$d/resuming" ]; then',
|
|
1357
|
+
' echo "result resuming"',
|
|
1358
|
+
' printf "resuming %s\\n" "$(head -n 1 "$d/resuming")"',
|
|
1359
|
+
' printf "now %s\\n" "$(date +%s)"',
|
|
1360
|
+
' exit 0',
|
|
1361
|
+
'fi',
|
|
1362
|
+
'if [ -f "$2" ]; then',
|
|
1363
|
+
' echo "result ready"',
|
|
1364
|
+
' printf "marker %s\\n" "$(head -c 4096 "$2" | enc)"',
|
|
1365
|
+
' printf "head %s\\n" "$(git -C "$3" rev-parse HEAD 2>/dev/null)"',
|
|
1366
|
+
' printf "bun %s\\n" "$("$4" --version 2>/dev/null | head -n 1)"',
|
|
1367
|
+
' printf "distribution %s\\n" "$(head -n 1 "$5" 2>/dev/null)"',
|
|
1368
|
+
' exit 0',
|
|
1369
|
+
'fi',
|
|
1370
|
+
'pid=$(cat "$d/pid" 2>/dev/null)',
|
|
1371
|
+
'if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null && grep -q tail.sh "/proc/$pid/cmdline" 2>/dev/null; then',
|
|
1372
|
+
' echo "result running"',
|
|
1373
|
+
' printf "stage %s\\n" "$(head -n 1 "$d/stage" 2>/dev/null)"',
|
|
1374
|
+
' exit 0',
|
|
1375
|
+
'fi',
|
|
1376
|
+
'if [ -f "$d/host" ]; then',
|
|
1377
|
+
' echo "result host"',
|
|
1378
|
+
' printf "host %s\\n" "$(head -n 1 "$d/host")"',
|
|
1379
|
+
' printf "now %s\\n" "$(date +%s)"',
|
|
1380
|
+
' exit 0',
|
|
1381
|
+
'fi',
|
|
1382
|
+
'echo "result none"',
|
|
1383
|
+
].join('\n')
|
|
1384
|
+
|
|
1385
|
+
/** Parse the probe's `key value` lines. Unparseable output is `none`. */
|
|
1386
|
+
export function parseVercelOperatorProbe(stdout: string): VercelOperatorProbe {
|
|
1387
|
+
const fields = new Map<string, string>()
|
|
1388
|
+
for (const line of stdout.split('\n')) {
|
|
1389
|
+
const space = line.indexOf(' ')
|
|
1390
|
+
if (space > 0) fields.set(line.slice(0, space), line.slice(space + 1).trim())
|
|
1391
|
+
}
|
|
1392
|
+
const decode = (value: string | undefined): string =>
|
|
1393
|
+
value === undefined || value === '' ? '' : Buffer.from(value, 'base64').toString('utf8')
|
|
1394
|
+
const optional = (value: string | undefined): string | undefined =>
|
|
1395
|
+
value === undefined || value === '' ? undefined : value
|
|
1396
|
+
switch (fields.get('result')) {
|
|
1397
|
+
case 'failed':
|
|
1398
|
+
return {
|
|
1399
|
+
kind: 'failed',
|
|
1400
|
+
record: decode(fields.get('failed')),
|
|
1401
|
+
log: decode(fields.get('log')),
|
|
1402
|
+
}
|
|
1403
|
+
case 'ready': {
|
|
1404
|
+
let marker: { baseSha?: string } = {}
|
|
1405
|
+
try {
|
|
1406
|
+
const parsed = JSON.parse(decode(fields.get('marker'))) as { baseSha?: unknown }
|
|
1407
|
+
if (typeof parsed?.baseSha === 'string' && /^[0-9a-f]{40,64}$/.test(parsed.baseSha))
|
|
1408
|
+
marker = { baseSha: parsed.baseSha }
|
|
1409
|
+
} catch {
|
|
1410
|
+
// A legacy empty marker records no base head.
|
|
1411
|
+
}
|
|
1412
|
+
const headSha = optional(fields.get('head'))
|
|
1413
|
+
const bunVersion = optional(fields.get('bun'))
|
|
1414
|
+
const distribution = optional(fields.get('distribution'))
|
|
1415
|
+
return {
|
|
1416
|
+
kind: 'ready',
|
|
1417
|
+
marker,
|
|
1418
|
+
...(headSha !== undefined && /^[0-9a-f]{40,64}$/.test(headSha) ? { headSha } : {}),
|
|
1419
|
+
...(bunVersion !== undefined ? { bunVersion } : {}),
|
|
1420
|
+
...(distribution !== undefined ? { distribution } : {}),
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
case 'resuming': {
|
|
1424
|
+
const since = Number(fields.get('resuming'))
|
|
1425
|
+
const now = Number(fields.get('now'))
|
|
1426
|
+
return {
|
|
1427
|
+
kind: 'resuming',
|
|
1428
|
+
ageSeconds:
|
|
1429
|
+
Number.isFinite(since) && Number.isFinite(now) && fields.get('resuming') !== ''
|
|
1430
|
+
? Math.max(0, now - since)
|
|
1431
|
+
: 0,
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
case 'running': {
|
|
1435
|
+
const stage = optional(fields.get('stage'))
|
|
1436
|
+
return { kind: 'running', ...(stage !== undefined ? { stage } : {}) }
|
|
1437
|
+
}
|
|
1438
|
+
case 'host': {
|
|
1439
|
+
const [step = '', at = ''] = (fields.get('host') ?? '').split(/\s+/)
|
|
1440
|
+
const now = Number(fields.get('now'))
|
|
1441
|
+
const then = Number(at)
|
|
1442
|
+
const ageSeconds =
|
|
1443
|
+
Number.isFinite(now) && Number.isFinite(then) && at !== '' ? Math.max(0, now - then) : 0
|
|
1444
|
+
return { kind: 'host', step, ageSeconds }
|
|
1445
|
+
}
|
|
1446
|
+
default:
|
|
1447
|
+
return { kind: 'none' }
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
/** The file-safe form of a runtime name inside a tail stage name. */
|
|
1452
|
+
function tailRuntimeName(runtime: string): string {
|
|
1453
|
+
return runtime.replace(/[^A-Za-z0-9._-]+/g, '_')
|
|
1454
|
+
}
|
|
1455
|
+
|
|
1456
|
+
/** Single-quote one value for a POSIX shell. */
|
|
1457
|
+
function shellQuote(value: string): string {
|
|
1458
|
+
return `'${value.split("'").join(`'\\''`)}'`
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
/** A host-phase failure, already recorded in the guest when `created`. */
|
|
1462
|
+
class OperatorHostFailure extends Error {
|
|
1463
|
+
override readonly name = 'OperatorHostFailure'
|
|
1464
|
+
constructor(
|
|
1465
|
+
readonly failure: { stage: SandboxProvisionStage; message: string },
|
|
1466
|
+
readonly created: boolean,
|
|
1467
|
+
cause: unknown,
|
|
1468
|
+
) {
|
|
1469
|
+
super(failure.message, { cause })
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
/** A host phase stopped by `close` or `release`. */
|
|
1474
|
+
class OperatorAttemptCancelled extends Error {
|
|
1475
|
+
override readonly name = 'OperatorAttemptCancelled'
|
|
1476
|
+
constructor(readonly created: boolean) {
|
|
1477
|
+
super('operator sandbox provisioning was cancelled')
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
const DEPENDENCY_INSTALL_COMMAND = `if [ -f bun.lock ] || [ -f bun.lockb ]; then ${VERCEL_BUN_EXECUTABLE} install --frozen-lockfile; elif [ -f package-lock.json ]; then npm ci; elif [ -f pnpm-lock.yaml ]; then corepack pnpm install --frozen-lockfile; elif [ -f yarn.lock ]; then corepack yarn install --immutable; fi`
|
|
1482
|
+
|
|
1252
1483
|
export interface VercelSandboxProviderOptions {
|
|
1253
1484
|
delegateCredential?: typeof delegateCredential
|
|
1254
1485
|
config: VercelSandboxConfig
|
|
@@ -1299,6 +1530,20 @@ export interface VercelSandboxProviderOptions {
|
|
|
1299
1530
|
* environment is otherwise always built from an empty record — never the
|
|
1300
1531
|
* process environment — so no credential can leak in. */
|
|
1301
1532
|
sandboxEnvironmentVariables?: readonly string[]
|
|
1533
|
+
/** `[orchestrator.sandbox].idleMinutes` (default 30): the provider timeout
|
|
1534
|
+
* an operator sandbox is created and resumed with, extended by every tool
|
|
1535
|
+
* call, so the provider's own timer stops an idle sandbox. Build and
|
|
1536
|
+
* harvest workspaces keep `timeoutSeconds`. */
|
|
1537
|
+
sandboxIdleMinutes?: number
|
|
1538
|
+
/** Internal deployment composition only, never user configuration: the git
|
|
1539
|
+
* read credential of a hosted deployment's fallback operator sandbox. It is
|
|
1540
|
+
* placed only in the host-side upload-pack egress transform (GET
|
|
1541
|
+
* `info/refs?service=git-upload-pack` and POST `git-upload-pack`), never in
|
|
1542
|
+
* a create `source`, a guest command, or the guest env; the operator
|
|
1543
|
+
* sandbox is then created source-less and clones in the guest. Build
|
|
1544
|
+
* provisioning never uses it. Mutually exclusive with a configured
|
|
1545
|
+
* `gitPasswordEnv`. */
|
|
1546
|
+
egressReadCredential?: { username: string; password: string }
|
|
1302
1547
|
}
|
|
1303
1548
|
|
|
1304
1549
|
/** Vercel-backed working copy and executor. Completed SDK command output is
|
|
@@ -1371,6 +1616,11 @@ export class VercelSandboxProvider implements WorkspaceProvider {
|
|
|
1371
1616
|
) {
|
|
1372
1617
|
throw new Error('vercel-sandbox requires an HTTPS BuildStore and scoped AB_TOKEN authority')
|
|
1373
1618
|
}
|
|
1619
|
+
if (options.egressReadCredential !== undefined && options.config.gitPasswordEnv !== undefined) {
|
|
1620
|
+
throw new Error(
|
|
1621
|
+
'vercel-sandbox accepts either a deployment egress read credential or a configured gitPasswordEnv, not both',
|
|
1622
|
+
)
|
|
1623
|
+
}
|
|
1374
1624
|
this.facade = options.facade ?? createVercelSdkFacade(options.env)
|
|
1375
1625
|
this.exec = options.exec ?? spawnExec
|
|
1376
1626
|
this.observeWaitMs = options.observeWaitMs ?? VERCEL_OBSERVE_WAIT_MS
|
|
@@ -1388,6 +1638,12 @@ export class VercelSandboxProvider implements WorkspaceProvider {
|
|
|
1388
1638
|
this.withPolicyLock(identity.workspaceRef, () => this.observeExecution(identity)),
|
|
1389
1639
|
}
|
|
1390
1640
|
this.orchestratorSandbox = {
|
|
1641
|
+
lifecycleSupported: true,
|
|
1642
|
+
open: (input) => this.openOperator(input),
|
|
1643
|
+
status: (input) => this.statusOperator(input),
|
|
1644
|
+
close: (input) => this.closeOperator(input),
|
|
1645
|
+
refresh: (handle, input) =>
|
|
1646
|
+
this.withPolicyLock(handle.environmentId, () => this.refreshOperator(handle, input)),
|
|
1391
1647
|
describe: (input) => this.describeOperatorSandbox(input),
|
|
1392
1648
|
ensure: (input) => this.ensureOperatorSandbox(input),
|
|
1393
1649
|
exec: (handle, request) => this.sandboxExec(handle, request),
|
|
@@ -1987,6 +2243,27 @@ export class VercelSandboxProvider implements WorkspaceProvider {
|
|
|
1987
2243
|
return result.policy
|
|
1988
2244
|
}
|
|
1989
2245
|
|
|
2246
|
+
/** The upload-pack egress transform's authorization: the deployment egress
|
|
2247
|
+
* read credential when set, else the configured env pair, Basic-encoded.
|
|
2248
|
+
* Every policy write after creation goes through here, so a reset never
|
|
2249
|
+
* drops or widens the transform. */
|
|
2250
|
+
private uploadPackAuthorization(): string | undefined {
|
|
2251
|
+
const egress = this.options.egressReadCredential
|
|
2252
|
+
if (egress !== undefined) {
|
|
2253
|
+
return `Basic ${Buffer.from(`${egress.username}:${egress.password}`).toString('base64')}`
|
|
2254
|
+
}
|
|
2255
|
+
if (this.options.config.gitPasswordEnv === undefined) return undefined
|
|
2256
|
+
const username = requireVercelEnvironmentValue(
|
|
2257
|
+
this.options.env,
|
|
2258
|
+
this.options.config.gitUsernameEnv!,
|
|
2259
|
+
)
|
|
2260
|
+
const password = requireVercelEnvironmentValue(
|
|
2261
|
+
this.options.env,
|
|
2262
|
+
this.options.config.gitPasswordEnv,
|
|
2263
|
+
)
|
|
2264
|
+
return `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`
|
|
2265
|
+
}
|
|
2266
|
+
|
|
1990
2267
|
private async normalNetworkPolicy(ref: string): Promise<{
|
|
1991
2268
|
origin: ReturnType<typeof cleanGithubOrigin>
|
|
1992
2269
|
policy: NetworkPolicy
|
|
@@ -1995,15 +2272,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
|
|
|
1995
2272
|
this.origins.set(ref, origin)
|
|
1996
2273
|
return {
|
|
1997
2274
|
origin,
|
|
1998
|
-
policy: this.billingPolicy(
|
|
1999
|
-
uploadPackPolicy(
|
|
2000
|
-
origin,
|
|
2001
|
-
this.options.config.gitPasswordEnv === undefined
|
|
2002
|
-
? undefined
|
|
2003
|
-
: `Basic ${Buffer.from(`${requireVercelEnvironmentValue(this.options.env, this.options.config.gitUsernameEnv!)}:${requireVercelEnvironmentValue(this.options.env, this.options.config.gitPasswordEnv)}`).toString('base64')}`,
|
|
2004
|
-
),
|
|
2005
|
-
ref,
|
|
2006
|
-
),
|
|
2275
|
+
policy: this.billingPolicy(uploadPackPolicy(origin, this.uploadPackAuthorization()), ref),
|
|
2007
2276
|
}
|
|
2008
2277
|
}
|
|
2009
2278
|
|
|
@@ -2487,12 +2756,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
|
|
|
2487
2756
|
if (Object.keys(accounts).length) {
|
|
2488
2757
|
const origin =
|
|
2489
2758
|
this.origins.get(identity.workspaceRef) ?? cleanGithubOrigin(await this.origin())
|
|
2490
|
-
const base = uploadPackPolicy(
|
|
2491
|
-
origin,
|
|
2492
|
-
this.options.config.gitPasswordEnv === undefined
|
|
2493
|
-
? undefined
|
|
2494
|
-
: `Basic ${Buffer.from(`${requireVercelEnvironmentValue(this.options.env, this.options.config.gitUsernameEnv!)}:${requireVercelEnvironmentValue(this.options.env, this.options.config.gitPasswordEnv)}`).toString('base64')}`,
|
|
2495
|
-
)
|
|
2759
|
+
const base = uploadPackPolicy(origin, this.uploadPackAuthorization())
|
|
2496
2760
|
const refreshed = accountPolicy(
|
|
2497
2761
|
base,
|
|
2498
2762
|
accounts,
|
|
@@ -2601,23 +2865,24 @@ export class VercelSandboxProvider implements WorkspaceProvider {
|
|
|
2601
2865
|
}
|
|
2602
2866
|
}
|
|
2603
2867
|
|
|
2604
|
-
/** Provision-or-resume
|
|
2605
|
-
*
|
|
2606
|
-
*
|
|
2607
|
-
* the
|
|
2608
|
-
*
|
|
2609
|
-
*
|
|
2610
|
-
*
|
|
2868
|
+
/** Provision-or-resume, blocking: the provider's own primitive for tests
|
|
2869
|
+
* and callers without a journal. A persistent sandbox auto-resumes on the
|
|
2870
|
+
* first SDK call that needs a running session, so the reuse path applies
|
|
2871
|
+
* the idle timeout and network policy, brings Bun to the pin and re-checks
|
|
2872
|
+
* the distribution marker as the build paths do. A fresh provision runs the
|
|
2873
|
+
* host phase, then waits for the detached tail and probes its outcome; a
|
|
2874
|
+
* failure reaps the environment, because `ensure` has no journal to
|
|
2875
|
+
* publish its evidence to and its caller holds the error. */
|
|
2611
2876
|
private async ensureOperatorSandbox(input: {
|
|
2612
2877
|
repo: string
|
|
2613
2878
|
operator: string
|
|
2614
2879
|
baseBranch: string
|
|
2615
2880
|
}): Promise<SandboxEnvironmentIdentity> {
|
|
2616
|
-
const origin =
|
|
2617
|
-
const name = sandboxEnvironmentName(origin.url, input.operator)
|
|
2881
|
+
const { origin, name } = await this.operatorName(input.operator)
|
|
2618
2882
|
const distributionIdentity = await this.identityStamp()
|
|
2619
2883
|
let sandbox = await this.facade.get(name, this.operationSignal())
|
|
2620
2884
|
if (sandbox !== null) {
|
|
2885
|
+
await this.applyOperatorSession(sandbox, name)
|
|
2621
2886
|
const marker = await sandbox.runCommand({
|
|
2622
2887
|
cmd: 'test',
|
|
2623
2888
|
args: ['-f', VERCEL_PROVISIONED_MARKER],
|
|
@@ -2685,47 +2950,493 @@ export class VercelSandboxProvider implements WorkspaceProvider {
|
|
|
2685
2950
|
}
|
|
2686
2951
|
}
|
|
2687
2952
|
}
|
|
2688
|
-
const
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
|
|
2707
|
-
|
|
2708
|
-
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
|
|
2720
|
-
|
|
2721
|
-
|
|
2722
|
-
|
|
2723
|
-
|
|
2724
|
-
|
|
2953
|
+
const failEnsure = async (
|
|
2954
|
+
failure: { stage: SandboxProvisionStage; message: string },
|
|
2955
|
+
created: boolean,
|
|
2956
|
+
cause?: unknown,
|
|
2957
|
+
): Promise<never> => {
|
|
2958
|
+
if (created) {
|
|
2959
|
+
// Nothing unrecorded or half-built survives a blocking provision.
|
|
2960
|
+
try {
|
|
2961
|
+
await this.reap(name)
|
|
2962
|
+
} catch (deleteError) {
|
|
2963
|
+
throw new AggregateError(
|
|
2964
|
+
[cause ?? new Error(failure.message), deleteError],
|
|
2965
|
+
`operator sandbox ${name} setup failed and its incomplete environment could not be confirmed deleted`,
|
|
2966
|
+
)
|
|
2967
|
+
}
|
|
2968
|
+
}
|
|
2969
|
+
throw new SandboxOperationError(
|
|
2970
|
+
failure.stage === 'environment' ? 'environment' : 'provision',
|
|
2971
|
+
failure.message,
|
|
2972
|
+
cause === undefined ? undefined : { cause },
|
|
2973
|
+
)
|
|
2974
|
+
}
|
|
2975
|
+
let launched: Awaited<ReturnType<typeof this.runOperatorHostPhase>>
|
|
2976
|
+
try {
|
|
2977
|
+
launched = await this.runOperatorHostPhase({ origin, name, baseBranch: input.baseBranch })
|
|
2978
|
+
} catch (error) {
|
|
2979
|
+
if (error instanceof OperatorHostFailure)
|
|
2980
|
+
return failEnsure(error.failure, error.created, error)
|
|
2981
|
+
throw error
|
|
2982
|
+
}
|
|
2983
|
+
if (launched.outcome === 'concurrent') {
|
|
2984
|
+
throw new SandboxOperationError(
|
|
2985
|
+
'provision',
|
|
2986
|
+
`operator sandbox ${name} is being provisioned by another process`,
|
|
2987
|
+
)
|
|
2988
|
+
}
|
|
2989
|
+
const deadline = Date.now() + this.idleMs()
|
|
2990
|
+
await waitForCommandExit(launched.command, () => Date.now() > deadline)
|
|
2991
|
+
const probe = await this.probeOperator(launched.sandbox)
|
|
2992
|
+
if (probe.kind !== 'ready') {
|
|
2993
|
+
return failEnsure(
|
|
2994
|
+
probe.kind === 'failed' ? this.probeFailure(probe) : this.interruptedFailure(),
|
|
2995
|
+
true,
|
|
2996
|
+
)
|
|
2997
|
+
}
|
|
2998
|
+
const sessionId = launched.sandbox.currentSession?.().sessionId
|
|
2999
|
+
return {
|
|
3000
|
+
provider: this.name,
|
|
3001
|
+
environmentId: name,
|
|
3002
|
+
...(sessionId !== undefined ? { sessionId } : {}),
|
|
3003
|
+
workspacePath: VERCEL_WORKSPACE_PATH,
|
|
3004
|
+
baseSha: launched.baseSha,
|
|
3005
|
+
}
|
|
3006
|
+
}
|
|
3007
|
+
|
|
3008
|
+
// ── Operator sandbox lifecycle (#1246) ─────────────────────────────────
|
|
3009
|
+
//
|
|
3010
|
+
// `open` returns after a `get`, at most one probe and one `update`; the
|
|
3011
|
+
// host phase runs as this process's background attempt (which a hosted
|
|
3012
|
+
// caller keeps alive with its background seam) and launches the detached
|
|
3013
|
+
// tail. `status` reads the session status first and never runs a guest
|
|
3014
|
+
// command on a session that is not running: a guest command would resume
|
|
3015
|
+
// it. Failure evidence in the guest is reaped only by `open` (after the
|
|
3016
|
+
// service recorded the failure), `release`, or a blocking `ensure`.
|
|
3017
|
+
|
|
3018
|
+
private readonly operatorInflight = new Map<
|
|
3019
|
+
string,
|
|
3020
|
+
{
|
|
3021
|
+
kind: 'provision' | 'resume'
|
|
3022
|
+
promise: Promise<SandboxProviderStatus>
|
|
3023
|
+
abort: AbortController
|
|
3024
|
+
}
|
|
3025
|
+
>()
|
|
3026
|
+
private readonly operatorFailures = new Map<
|
|
3027
|
+
string,
|
|
3028
|
+
{ stage: SandboxProvisionStage; message: string }
|
|
3029
|
+
>()
|
|
3030
|
+
|
|
3031
|
+
/** The operator sandbox's provider idle timeout, in milliseconds. */
|
|
3032
|
+
private idleMs(): number {
|
|
3033
|
+
return (this.options.sandboxIdleMinutes ?? 30) * 60_000
|
|
3034
|
+
}
|
|
3035
|
+
|
|
3036
|
+
private async operatorName(
|
|
3037
|
+
operator: string,
|
|
3038
|
+
): Promise<{ origin: ReturnType<typeof cleanGithubOrigin>; name: string }> {
|
|
3039
|
+
const origin = cleanGithubOrigin(await this.origin())
|
|
3040
|
+
return { origin, name: sandboxEnvironmentName(origin.url, operator) }
|
|
3041
|
+
}
|
|
3042
|
+
|
|
3043
|
+
/** Every credential value a provisioning message could carry, removed:
|
|
3044
|
+
* forwarded guest values, the upload-pack authorization and git password,
|
|
3045
|
+
* then the forbidden host names' values. */
|
|
3046
|
+
private redactOperatorMessage(message: string): string {
|
|
3047
|
+
let env: Record<string, string> = {}
|
|
3048
|
+
try {
|
|
3049
|
+
env = this.sandboxEnv()
|
|
3050
|
+
} catch {
|
|
3051
|
+
// A missing forwarded value has no value to redact.
|
|
3052
|
+
}
|
|
3053
|
+
let redacted = redactRuntimeError(message, env)
|
|
3054
|
+
const secrets: string[] = []
|
|
3055
|
+
try {
|
|
3056
|
+
const authorization = this.uploadPackAuthorization()
|
|
3057
|
+
if (authorization !== undefined) {
|
|
3058
|
+
secrets.push(authorization, authorization.slice('Basic '.length))
|
|
3059
|
+
}
|
|
3060
|
+
} catch {
|
|
3061
|
+
// An unresolvable credential pair cannot appear in the message.
|
|
3062
|
+
}
|
|
3063
|
+
if (this.options.egressReadCredential !== undefined) {
|
|
3064
|
+
secrets.push(this.options.egressReadCredential.password)
|
|
3065
|
+
}
|
|
3066
|
+
const passwordEnv = this.options.config.gitPasswordEnv
|
|
3067
|
+
if (passwordEnv !== undefined) secrets.push(this.options.env[passwordEnv] ?? '')
|
|
3068
|
+
for (const secret of secrets.sort((a, b) => b.length - a.length)) {
|
|
3069
|
+
if (secret !== '') redacted = redacted.split(secret).join('[REDACTED]')
|
|
3070
|
+
}
|
|
3071
|
+
return redactSandboxMessage(redacted)
|
|
3072
|
+
}
|
|
3073
|
+
|
|
3074
|
+
/** Apply the idle timeout and the current network policy to an operator
|
|
3075
|
+
* sandbox: a resumed session then runs with the idle timeout, and the
|
|
3076
|
+
* upload-pack transform carries the deployment's current read credential. */
|
|
3077
|
+
private async applyOperatorSession(sandbox: VercelSandboxHandle, name: string): Promise<void> {
|
|
3078
|
+
const { policy } = await this.normalNetworkPolicy(name)
|
|
3079
|
+
await sandbox.update(
|
|
3080
|
+
{ timeout: this.idleMs(), networkPolicy: policy },
|
|
3081
|
+
{ signal: this.operationSignal() },
|
|
3082
|
+
)
|
|
3083
|
+
}
|
|
3084
|
+
|
|
3085
|
+
/** Extend the running session so it outlives `max(idleMs, boundMs)` from
|
|
3086
|
+
* now. The SDK's `extendTimeout` adds to the lifetime, so only the deficit
|
|
3087
|
+
* is requested. A failed extension is swallowed: it can only let the
|
|
3088
|
+
* sandbox stop sooner, which is cost-safe, and the next call extends. */
|
|
3089
|
+
private async extendOperatorTimer(sandbox: VercelSandboxHandle, boundMs: number): Promise<void> {
|
|
3090
|
+
const expiresAt = sandbox.sessionExpiresAt
|
|
3091
|
+
if (expiresAt === undefined) return
|
|
3092
|
+
const deficit = Date.now() + Math.max(this.idleMs(), boundMs) - expiresAt
|
|
3093
|
+
if (deficit <= 0) return
|
|
3094
|
+
try {
|
|
3095
|
+
await sandbox.extendTimeout(deficit, { signal: this.operationSignal() })
|
|
3096
|
+
} catch {
|
|
3097
|
+
// Cost-safe: see above.
|
|
3098
|
+
}
|
|
3099
|
+
}
|
|
3100
|
+
|
|
3101
|
+
private async probeOperator(sandbox: VercelSandboxHandle): Promise<VercelOperatorProbe> {
|
|
3102
|
+
const stdout = await readableCommand(sandbox, {
|
|
3103
|
+
cmd: 'sh',
|
|
3104
|
+
args: [
|
|
3105
|
+
'-c',
|
|
3106
|
+
VERCEL_OPERATOR_PROBE_SCRIPT,
|
|
3107
|
+
'probe',
|
|
3108
|
+
VERCEL_OPERATOR_PROVISION_DIR,
|
|
3109
|
+
VERCEL_PROVISIONED_MARKER,
|
|
3110
|
+
VERCEL_WORKSPACE_PATH,
|
|
3111
|
+
VERCEL_BUN_EXECUTABLE,
|
|
3112
|
+
VERCEL_DISTRIBUTION_VERSION_MARKER,
|
|
3113
|
+
],
|
|
2725
3114
|
signal: this.operationSignal(),
|
|
2726
3115
|
})
|
|
3116
|
+
return parseVercelOperatorProbe(stdout)
|
|
3117
|
+
}
|
|
3118
|
+
|
|
3119
|
+
private async heartbeat(sandbox: VercelSandboxHandle, step: OperatorHostStep): Promise<void> {
|
|
3120
|
+
await commandOrThrow(sandbox, {
|
|
3121
|
+
cmd: 'sh',
|
|
3122
|
+
args: [
|
|
3123
|
+
'-c',
|
|
3124
|
+
'printf "%s %s\\n" "$1" "$(date +%s)" > "$2"',
|
|
3125
|
+
'heartbeat',
|
|
3126
|
+
step,
|
|
3127
|
+
`${VERCEL_OPERATOR_PROVISION_DIR}/host`,
|
|
3128
|
+
],
|
|
3129
|
+
signal: this.operationSignal(),
|
|
3130
|
+
})
|
|
3131
|
+
}
|
|
3132
|
+
|
|
3133
|
+
/** Best-effort: record a failure in the guest `failed` file, the durable
|
|
3134
|
+
* evidence any later process reads. The message is already redacted. */
|
|
3135
|
+
private async writeOperatorFailure(
|
|
3136
|
+
sandbox: VercelSandboxHandle,
|
|
3137
|
+
failure: { stage: SandboxProvisionStage; message: string },
|
|
3138
|
+
): Promise<void> {
|
|
2727
3139
|
try {
|
|
2728
|
-
await
|
|
3140
|
+
await sandbox.runCommand({
|
|
3141
|
+
cmd: 'sh',
|
|
3142
|
+
args: [
|
|
3143
|
+
'-c',
|
|
3144
|
+
'mkdir -p "$1" && printf "%s\\n%s\\n" "$2" "$3" > "$1/failed"',
|
|
3145
|
+
'failed',
|
|
3146
|
+
VERCEL_OPERATOR_PROVISION_DIR,
|
|
3147
|
+
failure.stage,
|
|
3148
|
+
failure.message,
|
|
3149
|
+
],
|
|
3150
|
+
signal: this.operationSignal(),
|
|
3151
|
+
})
|
|
3152
|
+
} catch {
|
|
3153
|
+
// The in-process record and the journal remain.
|
|
3154
|
+
}
|
|
3155
|
+
}
|
|
3156
|
+
|
|
3157
|
+
/** The failure a `failed` probe records: a host or resume record carries
|
|
3158
|
+
* its stage and message verbatim; a tail record names its step, mapped onto
|
|
3159
|
+
* the existing stages with the redacted log tail as detail. */
|
|
3160
|
+
private probeFailure(probe: Extract<VercelOperatorProbe, { kind: 'failed' }>): {
|
|
3161
|
+
stage: SandboxProvisionStage
|
|
3162
|
+
message: string
|
|
3163
|
+
} {
|
|
3164
|
+
const [first = '', ...rest] = probe.record.split('\n')
|
|
3165
|
+
const step = first.trim()
|
|
3166
|
+
const recorded = rest.join('\n').trim()
|
|
3167
|
+
if (recorded !== '') {
|
|
3168
|
+
return {
|
|
3169
|
+
stage: (PROVISION_STAGES as readonly string[]).includes(step)
|
|
3170
|
+
? (step as SandboxProvisionStage)
|
|
3171
|
+
: 'provision',
|
|
3172
|
+
message: this.redactOperatorMessage(recorded),
|
|
3173
|
+
}
|
|
3174
|
+
}
|
|
3175
|
+
const detail = this.redactOperatorMessage(probe.log.trim()) || '(no output)'
|
|
3176
|
+
if (step === 'setup') {
|
|
3177
|
+
return { stage: 'setup', message: `operator sandbox setup failed: ${detail}` }
|
|
3178
|
+
}
|
|
3179
|
+
if (step === 'dependencies') {
|
|
3180
|
+
return { stage: 'provision', message: `dependency install failed: ${detail}` }
|
|
3181
|
+
}
|
|
3182
|
+
const runtime = /^runtime-(.+)-(install|preflight)$/.exec(step)
|
|
3183
|
+
if (runtime !== null) {
|
|
3184
|
+
const group = currentRuntimeReferences(this.options.runtimeReferences).find(
|
|
3185
|
+
(candidate) => tailRuntimeName(candidate.runtime) === runtime[1],
|
|
3186
|
+
)
|
|
3187
|
+
return {
|
|
3188
|
+
stage: 'provision',
|
|
3189
|
+
message:
|
|
3190
|
+
group === undefined
|
|
3191
|
+
? `runtime ${runtime[1]} ${runtime[2]} failed: ${detail}`
|
|
3192
|
+
: `runtime ${displayName(group.runtime)} ${runtime[2]} failed (selected by ${group.references.join(', ')}); fix workspace.config.runtimeProvisioning.${group.runtime}.${runtime[2]}: ${detail}`,
|
|
3193
|
+
}
|
|
3194
|
+
}
|
|
3195
|
+
return {
|
|
3196
|
+
stage: 'provision',
|
|
3197
|
+
message: `operator sandbox provisioning step ${step || '(unknown)'} failed: ${detail}`,
|
|
3198
|
+
}
|
|
3199
|
+
}
|
|
3200
|
+
|
|
3201
|
+
/** An interrupted provision: the host heartbeat's step names the stage. */
|
|
3202
|
+
private interruptedFailure(step?: string): {
|
|
3203
|
+
stage: SandboxProvisionStage
|
|
3204
|
+
message: string
|
|
3205
|
+
} {
|
|
3206
|
+
if (step === 'checkout' || step === 'provision') {
|
|
3207
|
+
return {
|
|
3208
|
+
stage: step,
|
|
3209
|
+
message: `provisioning was interrupted during ${step}; call sandbox.open to retry`,
|
|
3210
|
+
}
|
|
3211
|
+
}
|
|
3212
|
+
return { stage: 'provision', message: SANDBOX_INTERRUPTED_MESSAGE }
|
|
3213
|
+
}
|
|
3214
|
+
|
|
3215
|
+
private readyStatus(
|
|
3216
|
+
name: string,
|
|
3217
|
+
sandbox: VercelSandboxHandle,
|
|
3218
|
+
probe: Extract<VercelOperatorProbe, { kind: 'ready' }>,
|
|
3219
|
+
kind?: 'provision' | 'resume',
|
|
3220
|
+
): SandboxProviderStatus {
|
|
3221
|
+
const sessionId = sandbox.currentSession?.().sessionId
|
|
3222
|
+
return {
|
|
3223
|
+
state: 'ready',
|
|
3224
|
+
handle: {
|
|
3225
|
+
provider: this.name,
|
|
3226
|
+
environmentId: name,
|
|
3227
|
+
...(sessionId !== undefined ? { sessionId } : {}),
|
|
3228
|
+
workspacePath: VERCEL_WORKSPACE_PATH,
|
|
3229
|
+
...(probe.marker.baseSha !== undefined ? { baseSha: probe.marker.baseSha } : {}),
|
|
3230
|
+
},
|
|
3231
|
+
...(probe.headSha !== undefined ? { headSha: probe.headSha } : {}),
|
|
3232
|
+
...(kind !== undefined ? { kind } : {}),
|
|
3233
|
+
}
|
|
3234
|
+
}
|
|
3235
|
+
|
|
3236
|
+
/** Classify a running session's probe. `inFlight` marks a provision some
|
|
3237
|
+
* process is still driving (a running tail, a fresh host heartbeat, or a
|
|
3238
|
+
* tail launched within its grace). */
|
|
3239
|
+
private classifyOperatorProbe(
|
|
3240
|
+
name: string,
|
|
3241
|
+
sandbox: VercelSandboxHandle,
|
|
3242
|
+
probe: VercelOperatorProbe,
|
|
3243
|
+
): { status: SandboxProviderStatus; inFlight: boolean } {
|
|
3244
|
+
switch (probe.kind) {
|
|
3245
|
+
case 'failed':
|
|
3246
|
+
return { status: { state: 'failed', failure: this.probeFailure(probe) }, inFlight: false }
|
|
3247
|
+
case 'ready':
|
|
3248
|
+
return { status: this.readyStatus(name, sandbox, probe), inFlight: false }
|
|
3249
|
+
case 'resuming':
|
|
3250
|
+
// Some process is refreshing the toolchain under the old marker.
|
|
3251
|
+
if (probe.ageSeconds < VERCEL_OPERATOR_HOST_STALE_SECONDS) {
|
|
3252
|
+
return { status: { state: 'resuming' }, inFlight: true }
|
|
3253
|
+
}
|
|
3254
|
+
return {
|
|
3255
|
+
status: {
|
|
3256
|
+
state: 'failed',
|
|
3257
|
+
failure: {
|
|
3258
|
+
stage: 'resume',
|
|
3259
|
+
message: 'resuming was interrupted before it finished; call sandbox.open to retry',
|
|
3260
|
+
},
|
|
3261
|
+
},
|
|
3262
|
+
inFlight: false,
|
|
3263
|
+
}
|
|
3264
|
+
case 'running':
|
|
3265
|
+
return { status: { state: 'provisioning' }, inFlight: true }
|
|
3266
|
+
case 'host': {
|
|
3267
|
+
const grace =
|
|
3268
|
+
probe.step === 'launched'
|
|
3269
|
+
? VERCEL_OPERATOR_LAUNCH_GRACE_SECONDS
|
|
3270
|
+
: VERCEL_OPERATOR_HOST_STALE_SECONDS
|
|
3271
|
+
if (probe.ageSeconds < grace) return { status: { state: 'provisioning' }, inFlight: true }
|
|
3272
|
+
return {
|
|
3273
|
+
status: { state: 'failed', failure: this.interruptedFailure(probe.step) },
|
|
3274
|
+
inFlight: false,
|
|
3275
|
+
}
|
|
3276
|
+
}
|
|
3277
|
+
case 'none':
|
|
3278
|
+
return {
|
|
3279
|
+
status: { state: 'failed', failure: this.interruptedFailure() },
|
|
3280
|
+
inFlight: false,
|
|
3281
|
+
}
|
|
3282
|
+
}
|
|
3283
|
+
}
|
|
3284
|
+
|
|
3285
|
+
/** The detached tail's files: one stage script per step, then the runner.
|
|
3286
|
+
* Every stage command is byte-identical to the host-driven chain it
|
|
3287
|
+
* replaces; the files carry no environment values (forwarded values ride
|
|
3288
|
+
* only in the launch's env record). */
|
|
3289
|
+
private operatorTailFiles(baseSha: string): { path: string; content: Uint8Array }[] {
|
|
3290
|
+
const stages: { name: string; script: string }[] = [
|
|
3291
|
+
{ name: 'dependencies', script: DEPENDENCY_INSTALL_COMMAND },
|
|
3292
|
+
]
|
|
3293
|
+
const references = currentRuntimeReferences(this.options.runtimeReferences)
|
|
3294
|
+
for (const group of [...references].sort((left, right) =>
|
|
3295
|
+
left.runtime < right.runtime ? -1 : left.runtime > right.runtime ? 1 : 0,
|
|
3296
|
+
)) {
|
|
3297
|
+
const provisioning = this.options.config.runtimeProvisioning?.[group.runtime]
|
|
3298
|
+
if (provisioning === undefined) {
|
|
3299
|
+
throw new Error(
|
|
3300
|
+
`runtime ${displayName(group.runtime)} selected by ${group.references.join(', ')} has no provisioning; add [workspace.config.runtimeProvisioning.${tomlKey(group.runtime)}] with install and preflight commands`,
|
|
3301
|
+
)
|
|
3302
|
+
}
|
|
3303
|
+
for (const step of ['install', 'preflight'] as const) {
|
|
3304
|
+
stages.push({
|
|
3305
|
+
name: `runtime-${tailRuntimeName(group.runtime)}-${step}`,
|
|
3306
|
+
script: provisioning[step],
|
|
3307
|
+
})
|
|
3308
|
+
}
|
|
3309
|
+
}
|
|
3310
|
+
const setupCommand = this.options.setupCommand
|
|
3311
|
+
if (setupCommand !== undefined && setupCommand.trim() !== '') {
|
|
3312
|
+
stages.push({ name: 'setup', script: `${this.sandboxPathPrefix()}${setupCommand}` })
|
|
3313
|
+
}
|
|
3314
|
+
stages.push({
|
|
3315
|
+
name: 'marker',
|
|
3316
|
+
script: `printf '%s' ${shellQuote(JSON.stringify({ baseSha }))} > ${shellQuote(VERCEL_PROVISIONED_MARKER)}`,
|
|
3317
|
+
})
|
|
3318
|
+
const dir = VERCEL_OPERATOR_PROVISION_DIR
|
|
3319
|
+
const files = stages.map((stage, index) => ({
|
|
3320
|
+
name: stage.name,
|
|
3321
|
+
file: `stage-${String(index + 1).padStart(2, '0')}-${stage.name}.sh`,
|
|
3322
|
+
script: stage.script,
|
|
3323
|
+
}))
|
|
3324
|
+
const runner = [
|
|
3325
|
+
`d=${shellQuote(dir)}`,
|
|
3326
|
+
'echo $$ > "$d/pid"',
|
|
3327
|
+
'run() {',
|
|
3328
|
+
' printf "%s\\n" "$1" > "$d/stage"',
|
|
3329
|
+
' printf "== %s\\n" "$1" >> "$d/log"',
|
|
3330
|
+
' if ! sh "$d/$2" >> "$d/log" 2>&1; then',
|
|
3331
|
+
' printf "%s\\n" "$1" > "$d/failed"',
|
|
3332
|
+
' exit 1',
|
|
3333
|
+
' fi',
|
|
3334
|
+
'}',
|
|
3335
|
+
...files.map((stage) => `run ${shellQuote(stage.name)} ${shellQuote(stage.file)}`),
|
|
3336
|
+
'',
|
|
3337
|
+
].join('\n')
|
|
3338
|
+
return [
|
|
3339
|
+
...files.map((stage) => ({
|
|
3340
|
+
path: `${dir}/${stage.file}`,
|
|
3341
|
+
content: new Uint8Array(Buffer.from(`${stage.script}\n`)),
|
|
3342
|
+
})),
|
|
3343
|
+
{ path: `${dir}/tail.sh`, content: new Uint8Array(Buffer.from(runner)) },
|
|
3344
|
+
]
|
|
3345
|
+
}
|
|
3346
|
+
|
|
3347
|
+
/** The host phase of one fresh provision: create with the idle timeout,
|
|
3348
|
+
* check out and scrub, provision Bun, system steps and the distribution,
|
|
3349
|
+
* write the tail files and launch the detached tail. Each step rewrites
|
|
3350
|
+
* the guest heartbeat first. A failure after create writes the guest
|
|
3351
|
+
* `failed` record and leaves the sandbox for its idle timer — the evidence
|
|
3352
|
+
* must outlive this process until the journal holds it. */
|
|
3353
|
+
private async runOperatorHostPhase(input: {
|
|
3354
|
+
origin: ReturnType<typeof cleanGithubOrigin>
|
|
3355
|
+
name: string
|
|
3356
|
+
baseBranch: string
|
|
3357
|
+
signal?: AbortSignal
|
|
3358
|
+
}): Promise<
|
|
3359
|
+
| { outcome: 'launched'; sandbox: VercelSandboxHandle; command: VercelCommand; baseSha: string }
|
|
3360
|
+
| { outcome: 'concurrent' }
|
|
3361
|
+
> {
|
|
3362
|
+
const { origin, name, signal } = input
|
|
3363
|
+
const checkpoint = (): void => {
|
|
3364
|
+
if (signal?.aborted) throw new OperatorAttemptCancelled(sandbox !== undefined)
|
|
3365
|
+
}
|
|
3366
|
+
let step: OperatorHostStep = 'checkout'
|
|
3367
|
+
let sandbox: VercelSandboxHandle | undefined
|
|
3368
|
+
try {
|
|
3369
|
+
const distributionIdentity = await this.identityStamp()
|
|
3370
|
+
const head = await this.remoteBranchHead(input.baseBranch, `remote base ${input.baseBranch}`)
|
|
3371
|
+
if (head === null) throw new Error(`remote base ${input.baseBranch} does not exist`)
|
|
3372
|
+
// The deployment-fallback operator sandbox (egress read credential) is
|
|
3373
|
+
// created without a git source and clones in the guest: its credential
|
|
3374
|
+
// reaches only the upload-pack egress transform, never the Vercel
|
|
3375
|
+
// source API. Every other provision keeps the configured source clone.
|
|
3376
|
+
const guestClone = this.options.egressReadCredential !== undefined
|
|
3377
|
+
const username =
|
|
3378
|
+
guestClone || this.options.config.gitUsernameEnv === undefined
|
|
3379
|
+
? undefined
|
|
3380
|
+
: requireVercelEnvironmentValue(this.options.env, this.options.config.gitUsernameEnv)
|
|
3381
|
+
const password =
|
|
3382
|
+
guestClone || this.options.config.gitPasswordEnv === undefined
|
|
3383
|
+
? undefined
|
|
3384
|
+
: requireVercelEnvironmentValue(this.options.env, this.options.config.gitPasswordEnv)
|
|
3385
|
+
const readAuth = guestClone
|
|
3386
|
+
? this.uploadPackAuthorization()
|
|
3387
|
+
: password === undefined
|
|
3388
|
+
? undefined
|
|
3389
|
+
: `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`
|
|
3390
|
+
checkpoint()
|
|
3391
|
+
try {
|
|
3392
|
+
sandbox = await this.facade.create({
|
|
3393
|
+
name,
|
|
3394
|
+
...(guestClone
|
|
3395
|
+
? {}
|
|
3396
|
+
: {
|
|
3397
|
+
source: {
|
|
3398
|
+
type: 'git' as const,
|
|
3399
|
+
url: origin.url,
|
|
3400
|
+
revision: head,
|
|
3401
|
+
...(username !== undefined && password !== undefined
|
|
3402
|
+
? { username, password }
|
|
3403
|
+
: {}),
|
|
3404
|
+
},
|
|
3405
|
+
}),
|
|
3406
|
+
image: this.options.config.image,
|
|
3407
|
+
resources: { vcpus: this.options.config.vcpus },
|
|
3408
|
+
timeout: this.idleMs(),
|
|
3409
|
+
persistent: true,
|
|
3410
|
+
...(this.options.config.region !== undefined
|
|
3411
|
+
? { region: this.options.config.region }
|
|
3412
|
+
: {}),
|
|
3413
|
+
...(this.options.config.failoverRegions.length > 0
|
|
3414
|
+
? { failoverRegions: this.options.config.failoverRegions }
|
|
3415
|
+
: {}),
|
|
3416
|
+
...(this.options.config.snapshotExpirationSeconds === undefined
|
|
3417
|
+
? {}
|
|
3418
|
+
: { snapshotExpiration: this.options.config.snapshotExpirationSeconds * 1000 }),
|
|
3419
|
+
networkPolicy: uploadPackPolicy(origin, readAuth),
|
|
3420
|
+
keepLastSnapshots: { count: VERCEL_KEEP_LAST_SNAPSHOTS, deleteEvicted: true },
|
|
3421
|
+
signal: this.operationSignal(),
|
|
3422
|
+
})
|
|
3423
|
+
} catch (error) {
|
|
3424
|
+
// A concurrent instance that created the same name first owns this
|
|
3425
|
+
// provision; anything else is this attempt's failure.
|
|
3426
|
+
const existing = await this.facade.get(name, this.operationSignal()).catch(() => null)
|
|
3427
|
+
if (existing !== null) return { outcome: 'concurrent' }
|
|
3428
|
+
throw error
|
|
3429
|
+
}
|
|
3430
|
+
this.origins.set(name, origin)
|
|
3431
|
+
this.sessions.set(name, sandbox)
|
|
3432
|
+
await commandOrThrow(sandbox, { cmd: 'mkdir', args: ['-p', VERCEL_OPERATOR_PROVISION_DIR] })
|
|
3433
|
+
await this.heartbeat(sandbox, 'checkout')
|
|
3434
|
+
checkpoint()
|
|
3435
|
+
if (guestClone) {
|
|
3436
|
+
await guestCloneCheckout(sandbox, origin.url, head)
|
|
3437
|
+
} else {
|
|
3438
|
+
await relocateCheckout(sandbox, origin.directory)
|
|
3439
|
+
}
|
|
2729
3440
|
await commandOrThrow(sandbox, {
|
|
2730
3441
|
cmd: 'git',
|
|
2731
3442
|
args: ['remote', 'set-url', 'origin', origin.url],
|
|
@@ -2744,84 +3455,491 @@ export class VercelSandboxProvider implements WorkspaceProvider {
|
|
|
2744
3455
|
if (result.exitCode !== 0 && result.exitCode !== 5)
|
|
2745
3456
|
throw new Error(`failed to scrub git config ${key}`)
|
|
2746
3457
|
}
|
|
2747
|
-
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
await
|
|
2751
|
-
|
|
2752
|
-
|
|
3458
|
+
checkpoint()
|
|
3459
|
+
step = 'provision'
|
|
3460
|
+
await this.heartbeat(sandbox, 'provision')
|
|
3461
|
+
await provisionBun(sandbox, this.options.config.image, signal)
|
|
3462
|
+
checkpoint()
|
|
3463
|
+
await runSystemProvisioning(sandbox, this.options.config.provisioning ?? [], signal)
|
|
3464
|
+
checkpoint()
|
|
3465
|
+
await installDistribution(
|
|
3466
|
+
sandbox,
|
|
3467
|
+
await this.archiveBytes(),
|
|
3468
|
+
distributionIdentity,
|
|
3469
|
+
this.operationSignal(),
|
|
3470
|
+
)
|
|
3471
|
+
checkpoint()
|
|
3472
|
+
await sandbox.writeFiles(this.operatorTailFiles(head), { signal: this.operationSignal() })
|
|
3473
|
+
// Forwarded values are demanded only when a runtime or setup stage
|
|
3474
|
+
// runs, as in the host-driven chain this replaces.
|
|
3475
|
+
const setup = this.options.setupCommand
|
|
3476
|
+
const env =
|
|
3477
|
+
currentRuntimeReferences(this.options.runtimeReferences).length > 0 ||
|
|
3478
|
+
(setup !== undefined && setup.trim() !== '')
|
|
3479
|
+
? this.sandboxEnv()
|
|
3480
|
+
: {}
|
|
3481
|
+
checkpoint()
|
|
3482
|
+
const command = (await sandbox.runCommand({
|
|
3483
|
+
cmd: 'sh',
|
|
3484
|
+
args: ['-c', 'exec sh "$1"', 'tail', `${VERCEL_OPERATOR_PROVISION_DIR}/tail.sh`],
|
|
3485
|
+
cwd: VERCEL_WORKSPACE_PATH,
|
|
3486
|
+
env,
|
|
3487
|
+
detached: true,
|
|
3488
|
+
signal: this.operationSignal(),
|
|
3489
|
+
})) as VercelCommand
|
|
3490
|
+
step = 'launched'
|
|
3491
|
+
await this.heartbeat(sandbox, 'launched')
|
|
3492
|
+
await this.extendOperatorTimer(sandbox, 0)
|
|
3493
|
+
return { outcome: 'launched', sandbox, command, baseSha: head }
|
|
3494
|
+
} catch (error) {
|
|
3495
|
+
if (error instanceof OperatorAttemptCancelled || signal?.aborted) {
|
|
3496
|
+
throw new OperatorAttemptCancelled(sandbox !== undefined)
|
|
3497
|
+
}
|
|
3498
|
+
const failure = {
|
|
3499
|
+
stage:
|
|
3500
|
+
error instanceof SandboxOperationError && error.stage === 'environment'
|
|
3501
|
+
? ('environment' as const)
|
|
3502
|
+
: step === 'checkout'
|
|
3503
|
+
? ('checkout' as const)
|
|
3504
|
+
: ('provision' as const),
|
|
3505
|
+
message:
|
|
3506
|
+
this.redactOperatorMessage(error instanceof Error ? error.message : String(error)) ||
|
|
3507
|
+
'operator sandbox provisioning failed',
|
|
3508
|
+
}
|
|
3509
|
+
if (sandbox !== undefined) await this.writeOperatorFailure(sandbox, failure)
|
|
3510
|
+
throw new OperatorHostFailure(failure, sandbox !== undefined, error)
|
|
3511
|
+
}
|
|
3512
|
+
}
|
|
3513
|
+
|
|
3514
|
+
/** Register one background attempt; its body resolves, never rejects. */
|
|
3515
|
+
private startOperatorAttempt(
|
|
3516
|
+
name: string,
|
|
3517
|
+
kind: 'provision' | 'resume',
|
|
3518
|
+
body: (signal: AbortSignal) => Promise<SandboxProviderStatus>,
|
|
3519
|
+
): { status: SandboxProviderStatus; settled: Promise<SandboxProviderStatus> } {
|
|
3520
|
+
const abort = new AbortController()
|
|
3521
|
+
const entry = {
|
|
3522
|
+
kind,
|
|
3523
|
+
abort,
|
|
3524
|
+
promise: Promise.resolve<SandboxProviderStatus>({ state: 'absent' }),
|
|
3525
|
+
}
|
|
3526
|
+
this.operatorInflight.set(name, entry)
|
|
3527
|
+
entry.promise = (async (): Promise<SandboxProviderStatus> => {
|
|
3528
|
+
try {
|
|
3529
|
+
return await body(abort.signal)
|
|
3530
|
+
} catch (error) {
|
|
3531
|
+
const failure = {
|
|
3532
|
+
stage: kind === 'resume' ? ('resume' as const) : ('provision' as const),
|
|
3533
|
+
message:
|
|
3534
|
+
this.redactOperatorMessage(error instanceof Error ? error.message : String(error)) ||
|
|
3535
|
+
'operator sandbox provisioning failed',
|
|
3536
|
+
}
|
|
3537
|
+
this.operatorFailures.set(name, failure)
|
|
3538
|
+
return { state: 'failed', failure }
|
|
3539
|
+
} finally {
|
|
3540
|
+
if (this.operatorInflight.get(name) === entry) this.operatorInflight.delete(name)
|
|
3541
|
+
}
|
|
3542
|
+
})()
|
|
3543
|
+
return {
|
|
3544
|
+
status: { state: kind === 'resume' ? 'resuming' : 'provisioning', kind },
|
|
3545
|
+
settled: entry.promise,
|
|
3546
|
+
}
|
|
3547
|
+
}
|
|
3548
|
+
|
|
3549
|
+
/** A fresh provision, replacing `stale` first when given. Settles
|
|
3550
|
+
* `provisioning` once the tail is launched: the tail's outcome is observed
|
|
3551
|
+
* later through the probe. */
|
|
3552
|
+
private async freshOperatorAttempt(
|
|
3553
|
+
input: { baseBranch: string },
|
|
3554
|
+
origin: ReturnType<typeof cleanGithubOrigin>,
|
|
3555
|
+
name: string,
|
|
3556
|
+
stale: VercelSandboxHandle | undefined,
|
|
3557
|
+
signal: AbortSignal,
|
|
3558
|
+
): Promise<SandboxProviderStatus> {
|
|
3559
|
+
if (stale !== undefined) {
|
|
3560
|
+
// The journal already records this environment's failure (the
|
|
3561
|
+
// service's precondition for calling open). Replace the evidence with
|
|
3562
|
+
// a checkout heartbeat first, so a concurrent probe reads the
|
|
3563
|
+
// replacement as in flight rather than as the old failure.
|
|
3564
|
+
try {
|
|
3565
|
+
await stale.runCommand({
|
|
3566
|
+
cmd: 'sh',
|
|
3567
|
+
args: [
|
|
3568
|
+
'-c',
|
|
3569
|
+
'mkdir -p "$1" && rm -f "$1/failed" "$1/resuming" "$1/pid" "$2" && printf "checkout %s\\n" "$(date +%s)" > "$1/host"',
|
|
3570
|
+
'replace',
|
|
3571
|
+
VERCEL_OPERATOR_PROVISION_DIR,
|
|
3572
|
+
VERCEL_PROVISIONED_MARKER,
|
|
3573
|
+
],
|
|
3574
|
+
signal: this.operationSignal(),
|
|
3575
|
+
})
|
|
3576
|
+
} catch {
|
|
3577
|
+
// The reap below removes it either way.
|
|
3578
|
+
}
|
|
3579
|
+
this.sessions.set(name, stale)
|
|
3580
|
+
try {
|
|
3581
|
+
await this.reap(name)
|
|
3582
|
+
} catch (error) {
|
|
3583
|
+
const failure = {
|
|
3584
|
+
stage: 'checkout' as const,
|
|
3585
|
+
message: this.redactOperatorMessage(
|
|
3586
|
+
`could not replace the previous environment: ${describeError(error)}`,
|
|
3587
|
+
),
|
|
3588
|
+
}
|
|
3589
|
+
this.operatorFailures.set(name, failure)
|
|
3590
|
+
return { state: 'failed', failure }
|
|
3591
|
+
}
|
|
3592
|
+
}
|
|
3593
|
+
if (signal.aborted) return { state: 'absent', cancelled: true }
|
|
3594
|
+
try {
|
|
3595
|
+
await this.runOperatorHostPhase({
|
|
3596
|
+
origin,
|
|
3597
|
+
name,
|
|
3598
|
+
baseBranch: input.baseBranch,
|
|
3599
|
+
signal,
|
|
3600
|
+
})
|
|
3601
|
+
return { state: 'provisioning', kind: 'provision' }
|
|
3602
|
+
} catch (error) {
|
|
3603
|
+
if (error instanceof OperatorAttemptCancelled) {
|
|
3604
|
+
if (error.created) await this.reap(name).catch(() => {})
|
|
3605
|
+
return { state: 'absent', cancelled: true }
|
|
3606
|
+
}
|
|
3607
|
+
if (error instanceof OperatorHostFailure) {
|
|
3608
|
+
this.operatorFailures.set(name, error.failure)
|
|
3609
|
+
return { state: 'failed', failure: error.failure }
|
|
3610
|
+
}
|
|
3611
|
+
throw error
|
|
3612
|
+
}
|
|
3613
|
+
}
|
|
3614
|
+
|
|
3615
|
+
/** Bring a provisioned environment's Bun and distribution to the current
|
|
3616
|
+
* pin, then report it ready. A failure is recorded in the guest first
|
|
3617
|
+
* (stage `resume`), superseding the marker. */
|
|
3618
|
+
private async refreshOperatorRuntime(
|
|
3619
|
+
sandbox: VercelSandboxHandle,
|
|
3620
|
+
name: string,
|
|
3621
|
+
probe: Extract<VercelOperatorProbe, { kind: 'ready' }>,
|
|
3622
|
+
): Promise<SandboxProviderStatus> {
|
|
3623
|
+
try {
|
|
3624
|
+
// Every process's probe reads the refresh as in flight (outranking the
|
|
3625
|
+
// old marker) until it succeeds; a failure supersedes it with `failed`.
|
|
2753
3626
|
await commandOrThrow(sandbox, {
|
|
2754
3627
|
cmd: 'sh',
|
|
2755
3628
|
args: [
|
|
2756
3629
|
'-c',
|
|
2757
|
-
|
|
3630
|
+
'mkdir -p "$1" && printf "%s\\n" "$(date +%s)" > "$1/resuming"',
|
|
3631
|
+
'resuming',
|
|
3632
|
+
VERCEL_OPERATOR_PROVISION_DIR,
|
|
2758
3633
|
],
|
|
2759
|
-
|
|
3634
|
+
signal: this.operationSignal(),
|
|
2760
3635
|
})
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
const runtimeReferences = currentRuntimeReferences(this.options.runtimeReferences)
|
|
2766
|
-
if (runtimeReferences.length > 0) {
|
|
2767
|
-
await bootstrapRuntimes(
|
|
3636
|
+
await ensurePinnedBun(sandbox, this.options.config.image, this.operationSignal())
|
|
3637
|
+
const identity = await this.identityStamp()
|
|
3638
|
+
if (probe.distribution !== identity) {
|
|
3639
|
+
await installDistribution(
|
|
2768
3640
|
sandbox,
|
|
2769
|
-
this.
|
|
2770
|
-
|
|
2771
|
-
runtimeReferences,
|
|
2772
|
-
true,
|
|
3641
|
+
await this.archiveBytes(),
|
|
3642
|
+
identity,
|
|
2773
3643
|
this.operationSignal(),
|
|
2774
3644
|
)
|
|
2775
3645
|
}
|
|
2776
|
-
const setupCommand = this.options.setupCommand
|
|
2777
|
-
if (setupCommand !== undefined && setupCommand.trim() !== '') {
|
|
2778
|
-
await readableCommand(sandbox, {
|
|
2779
|
-
cmd: 'sh',
|
|
2780
|
-
args: ['-c', `${this.sandboxPathPrefix()}${setupCommand}`],
|
|
2781
|
-
cwd: VERCEL_WORKSPACE_PATH,
|
|
2782
|
-
env: this.sandboxEnv(),
|
|
2783
|
-
})
|
|
2784
|
-
}
|
|
2785
3646
|
await commandOrThrow(sandbox, {
|
|
2786
|
-
cmd: '
|
|
2787
|
-
args: [
|
|
3647
|
+
cmd: 'sh',
|
|
3648
|
+
args: ['-c', 'rm -f "$1/resuming"', 'resumed', VERCEL_OPERATOR_PROVISION_DIR],
|
|
3649
|
+
signal: this.operationSignal(),
|
|
2788
3650
|
})
|
|
2789
3651
|
} catch (error) {
|
|
2790
|
-
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
|
|
2794
|
-
|
|
2795
|
-
}
|
|
2796
|
-
|
|
2797
|
-
|
|
2798
|
-
|
|
3652
|
+
const failure = {
|
|
3653
|
+
stage: 'resume' as const,
|
|
3654
|
+
message:
|
|
3655
|
+
this.redactOperatorMessage(error instanceof Error ? error.message : String(error)) ||
|
|
3656
|
+
'operator sandbox resume failed',
|
|
3657
|
+
}
|
|
3658
|
+
await this.writeOperatorFailure(sandbox, failure)
|
|
3659
|
+
this.operatorFailures.set(name, failure)
|
|
3660
|
+
return { state: 'failed', failure }
|
|
3661
|
+
}
|
|
3662
|
+
await this.extendOperatorTimer(sandbox, 0)
|
|
3663
|
+
this.sessions.set(name, sandbox)
|
|
3664
|
+
return this.readyStatus(name, sandbox, probe, 'resume')
|
|
3665
|
+
}
|
|
3666
|
+
|
|
3667
|
+
/** Resume a stopped environment: the only path that recovers evidence
|
|
3668
|
+
* from a stopped sandbox, because status never resumes one. A recorded
|
|
3669
|
+
* failure settles with its recorded stage and message; nothing is reaped
|
|
3670
|
+
* here. */
|
|
3671
|
+
private async resumeOperatorAttempt(
|
|
3672
|
+
sandbox: VercelSandboxHandle,
|
|
3673
|
+
name: string,
|
|
3674
|
+
): Promise<SandboxProviderStatus> {
|
|
3675
|
+
await this.applyOperatorSession(sandbox, name)
|
|
3676
|
+
let probe = await this.probeOperator(sandbox)
|
|
3677
|
+
if (probe.kind === 'resuming') {
|
|
3678
|
+
// The stop ended that refresh; this attempt redoes it.
|
|
3679
|
+
await commandOrThrow(sandbox, {
|
|
3680
|
+
cmd: 'sh',
|
|
3681
|
+
args: ['-c', 'rm -f "$1/resuming"', 'resumed', VERCEL_OPERATOR_PROVISION_DIR],
|
|
3682
|
+
signal: this.operationSignal(),
|
|
3683
|
+
})
|
|
3684
|
+
probe = await this.probeOperator(sandbox)
|
|
3685
|
+
}
|
|
3686
|
+
if (probe.kind === 'ready') return this.refreshOperatorRuntime(sandbox, name, probe)
|
|
3687
|
+
if (probe.kind === 'running') return { state: 'provisioning', kind: 'provision' }
|
|
3688
|
+
const failure =
|
|
3689
|
+
probe.kind === 'failed'
|
|
3690
|
+
? this.probeFailure(probe)
|
|
3691
|
+
: this.interruptedFailure(probe.kind === 'host' ? probe.step : undefined)
|
|
3692
|
+
this.operatorFailures.set(name, failure)
|
|
3693
|
+
return { state: 'failed', failure }
|
|
3694
|
+
}
|
|
3695
|
+
|
|
3696
|
+
private async openOperator(input: {
|
|
3697
|
+
repo: string
|
|
3698
|
+
operator: string
|
|
3699
|
+
baseBranch: string
|
|
3700
|
+
}): Promise<{ status: SandboxProviderStatus; settled?: Promise<SandboxProviderStatus> }> {
|
|
3701
|
+
const { origin, name } = await this.operatorName(input.operator)
|
|
3702
|
+
return this.withPolicyLock(name, async () => {
|
|
3703
|
+
const inflight = this.operatorInflight.get(name)
|
|
3704
|
+
if (inflight !== undefined) {
|
|
3705
|
+
return {
|
|
3706
|
+
status: {
|
|
3707
|
+
state: inflight.kind === 'resume' ? 'resuming' : 'provisioning',
|
|
3708
|
+
kind: inflight.kind,
|
|
3709
|
+
},
|
|
3710
|
+
settled: inflight.promise,
|
|
3711
|
+
}
|
|
3712
|
+
}
|
|
3713
|
+
this.operatorFailures.delete(name)
|
|
3714
|
+
const sandbox = await this.facade.get(name, this.operationSignal())
|
|
3715
|
+
if (sandbox === null) {
|
|
3716
|
+
return this.startOperatorAttempt(name, 'provision', (signal) =>
|
|
3717
|
+
this.freshOperatorAttempt(input, origin, name, undefined, signal),
|
|
2799
3718
|
)
|
|
2800
3719
|
}
|
|
2801
|
-
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
|
|
2805
|
-
|
|
2806
|
-
|
|
3720
|
+
const session = sandbox.sessionStatus
|
|
3721
|
+
if (session === undefined || session === 'running') {
|
|
3722
|
+
await this.applyOperatorSession(sandbox, name)
|
|
3723
|
+
const probe = await this.probeOperator(sandbox)
|
|
3724
|
+
if (probe.kind === 'ready') {
|
|
3725
|
+
if (
|
|
3726
|
+
probe.bunVersion === VERCEL_BUN_VERSION &&
|
|
3727
|
+
probe.distribution === (await this.identityStamp())
|
|
3728
|
+
) {
|
|
3729
|
+
await this.extendOperatorTimer(sandbox, 0)
|
|
3730
|
+
this.sessions.set(name, sandbox)
|
|
3731
|
+
return { status: this.readyStatus(name, sandbox, probe, 'resume') }
|
|
3732
|
+
}
|
|
3733
|
+
return this.startOperatorAttempt(name, 'resume', () =>
|
|
3734
|
+
this.refreshOperatorRuntime(sandbox, name, probe),
|
|
2807
3735
|
)
|
|
3736
|
+
}
|
|
3737
|
+
if (this.classifyOperatorProbe(name, sandbox, probe).inFlight) {
|
|
3738
|
+
// Another process's provision or refresh is in flight.
|
|
3739
|
+
return {
|
|
3740
|
+
status:
|
|
3741
|
+
probe.kind === 'resuming'
|
|
3742
|
+
? { state: 'resuming', kind: 'resume' }
|
|
3743
|
+
: { state: 'provisioning', kind: 'provision' },
|
|
3744
|
+
}
|
|
3745
|
+
}
|
|
3746
|
+
// A failed, interrupted or marker-less environment. The service
|
|
3747
|
+
// calls open only after the journal records its failure, so its
|
|
3748
|
+
// evidence may now be replaced.
|
|
3749
|
+
return this.startOperatorAttempt(name, 'provision', (signal) =>
|
|
3750
|
+
this.freshOperatorAttempt(input, origin, name, sandbox, signal),
|
|
3751
|
+
)
|
|
3752
|
+
}
|
|
3753
|
+
if (session === 'pending') return { status: { state: 'resuming', kind: 'resume' } }
|
|
3754
|
+
return this.startOperatorAttempt(name, 'resume', () =>
|
|
3755
|
+
this.resumeOperatorAttempt(sandbox, name),
|
|
3756
|
+
)
|
|
3757
|
+
})
|
|
3758
|
+
}
|
|
3759
|
+
|
|
3760
|
+
private async statusOperator(input: {
|
|
3761
|
+
repo: string
|
|
3762
|
+
operator: string
|
|
3763
|
+
}): Promise<SandboxProviderStatus> {
|
|
3764
|
+
const { name } = await this.operatorName(input.operator)
|
|
3765
|
+
const inflight = this.operatorInflight.get(name)
|
|
3766
|
+
if (inflight !== undefined) {
|
|
3767
|
+
return { state: inflight.kind === 'resume' ? 'resuming' : 'provisioning' }
|
|
2808
3768
|
}
|
|
2809
|
-
this.
|
|
2810
|
-
|
|
2811
|
-
this.
|
|
2812
|
-
return {
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
|
|
2816
|
-
|
|
2817
|
-
|
|
3769
|
+
const failure = this.operatorFailures.get(name)
|
|
3770
|
+
if (failure !== undefined) return { state: 'failed', failure }
|
|
3771
|
+
const sandbox = await this.facade.get(name, this.operationSignal())
|
|
3772
|
+
if (sandbox === null) return { state: 'absent' }
|
|
3773
|
+
// Never a guest command on a session that is not running: it would
|
|
3774
|
+
// resume it.
|
|
3775
|
+
const session = sandbox.sessionStatus
|
|
3776
|
+
if (session === 'pending') return { state: 'resuming' }
|
|
3777
|
+
if (session !== undefined && session !== 'running') return { state: 'stopped' }
|
|
3778
|
+
const { status, inFlight } = this.classifyOperatorProbe(
|
|
3779
|
+
name,
|
|
3780
|
+
sandbox,
|
|
3781
|
+
await this.probeOperator(sandbox),
|
|
3782
|
+
)
|
|
3783
|
+
// Only a provision in flight keeps the timer alive; polling a ready,
|
|
3784
|
+
// idle environment never does.
|
|
3785
|
+
if (inFlight) await this.extendOperatorTimer(sandbox, 0)
|
|
3786
|
+
return status
|
|
3787
|
+
}
|
|
3788
|
+
|
|
3789
|
+
private async closeOperator(input: {
|
|
3790
|
+
repo: string
|
|
3791
|
+
operator: string
|
|
3792
|
+
environmentId: string
|
|
3793
|
+
}): Promise<{ outcome: 'closed' | 'absent'; attempt?: SandboxProviderStatus }> {
|
|
3794
|
+
const { name } = await this.operatorName(input.operator)
|
|
3795
|
+
let attempt: SandboxProviderStatus | undefined
|
|
3796
|
+
const inflight = this.operatorInflight.get(name)
|
|
3797
|
+
if (inflight !== undefined) {
|
|
3798
|
+
inflight.abort.abort()
|
|
3799
|
+
attempt = await inflight.promise
|
|
2818
3800
|
}
|
|
3801
|
+
return this.withPolicyLock(name, async () => {
|
|
3802
|
+
const withAttempt = <T extends object>(result: T) =>
|
|
3803
|
+
attempt === undefined ? result : { ...result, attempt }
|
|
3804
|
+
const sandbox = await this.facade.get(name, this.operationSignal())
|
|
3805
|
+
if (sandbox === null) return withAttempt({ outcome: 'absent' as const })
|
|
3806
|
+
if (attempt?.cancelled === true) return withAttempt({ outcome: 'absent' as const })
|
|
3807
|
+
const session = sandbox.sessionStatus
|
|
3808
|
+
const running = session === undefined || session === 'running'
|
|
3809
|
+
if (running && attempt === undefined) {
|
|
3810
|
+
const probe = await this.probeOperator(sandbox)
|
|
3811
|
+
const { status, inFlight } = this.classifyOperatorProbe(name, sandbox, probe)
|
|
3812
|
+
if (inFlight && probe.kind !== 'resuming') {
|
|
3813
|
+
// Closing an in-flight provision is a user-requested cancel; a
|
|
3814
|
+
// refresh of a provisioned checkout is stopped, never discarded.
|
|
3815
|
+
this.sessions.set(name, sandbox)
|
|
3816
|
+
await this.reap(name)
|
|
3817
|
+
return { outcome: 'absent' as const, attempt: { state: 'absent', cancelled: true } }
|
|
3818
|
+
}
|
|
3819
|
+
if (status.state === 'failed') attempt = status
|
|
3820
|
+
}
|
|
3821
|
+
// Stopping releases capacity and keeps the snapshot — and with it any
|
|
3822
|
+
// failure evidence, which a later open recovers. A pending session
|
|
3823
|
+
// (another process resuming it) is stopped too, without a guest
|
|
3824
|
+
// command: it would otherwise start and hold capacity until its timer.
|
|
3825
|
+
if (running || session === 'pending') {
|
|
3826
|
+
try {
|
|
3827
|
+
await sandbox.stop({ signal: this.operationSignal() })
|
|
3828
|
+
} catch (error) {
|
|
3829
|
+
// A failed or interrupted stop request is not confirmation: only an
|
|
3830
|
+
// authoritative re-read showing the session no longer active is.
|
|
3831
|
+
// Anything else refuses, so the journal never records `closed`
|
|
3832
|
+
// while the session still holds capacity.
|
|
3833
|
+
const after = await this.facade.get(name, this.operationSignal())
|
|
3834
|
+
if (after === null) return withAttempt({ outcome: 'absent' as const })
|
|
3835
|
+
const now = after.sessionStatus
|
|
3836
|
+
if (now === undefined || now === 'running' || now === 'pending') {
|
|
3837
|
+
throw new SandboxOperationError(
|
|
3838
|
+
'close',
|
|
3839
|
+
`could not confirm operator sandbox ${name} stopped (${describeError(error)}); call sandbox.close again`,
|
|
3840
|
+
{ cause: error },
|
|
3841
|
+
)
|
|
3842
|
+
}
|
|
3843
|
+
}
|
|
3844
|
+
}
|
|
3845
|
+
this.sessions.delete(name)
|
|
3846
|
+
return withAttempt({ outcome: 'closed' as const })
|
|
3847
|
+
})
|
|
3848
|
+
}
|
|
3849
|
+
|
|
3850
|
+
private async refreshOperator(
|
|
3851
|
+
handle: SandboxEnvironmentIdentity,
|
|
3852
|
+
input: { repo: string; baseBranch: string },
|
|
3853
|
+
): Promise<SandboxRefreshResult> {
|
|
3854
|
+
const base = await this.remoteBranchHead(input.baseBranch, `remote base ${input.baseBranch}`)
|
|
3855
|
+
if (base === null) {
|
|
3856
|
+
throw new SandboxOperationError('refresh', `remote base ${input.baseBranch} does not exist`)
|
|
3857
|
+
}
|
|
3858
|
+
const sandbox = await this.sandboxHandle(handle)
|
|
3859
|
+
const git = (args: string[], env?: Record<string, string>) =>
|
|
3860
|
+
sandbox.runCommand({
|
|
3861
|
+
cmd: 'git',
|
|
3862
|
+
args,
|
|
3863
|
+
cwd: VERCEL_WORKSPACE_PATH,
|
|
3864
|
+
...(env !== undefined ? { env } : {}),
|
|
3865
|
+
signal: this.operationSignal(),
|
|
3866
|
+
}) as Promise<VercelCommand>
|
|
3867
|
+
const status = await readableCommand(sandbox, {
|
|
3868
|
+
cmd: 'git',
|
|
3869
|
+
args: ['status', '--porcelain'],
|
|
3870
|
+
cwd: VERCEL_WORKSPACE_PATH,
|
|
3871
|
+
})
|
|
3872
|
+
if (status.trim() !== '') {
|
|
3873
|
+
return { outcome: 'refused', reason: 'dirty', message: SANDBOX_REFRESH_DIRTY_MESSAGE }
|
|
3874
|
+
}
|
|
3875
|
+
const head = (
|
|
3876
|
+
await readableCommand(sandbox, {
|
|
3877
|
+
cmd: 'git',
|
|
3878
|
+
args: ['rev-parse', 'HEAD'],
|
|
3879
|
+
cwd: VERCEL_WORKSPACE_PATH,
|
|
3880
|
+
})
|
|
3881
|
+
).trim()
|
|
3882
|
+
// No credential rides the fetch: the upload-pack egress transform
|
|
3883
|
+
// authenticates it.
|
|
3884
|
+
const fetched = await git(['fetch', '--quiet', 'origin', input.baseBranch], {
|
|
3885
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
3886
|
+
})
|
|
3887
|
+
if (fetched.exitCode !== 0) {
|
|
3888
|
+
const stderr = (await fetched.stderr?.().catch(() => '')) ?? ''
|
|
3889
|
+
throw new SandboxOperationError(
|
|
3890
|
+
'refresh',
|
|
3891
|
+
this.redactOperatorMessage(
|
|
3892
|
+
`git fetch origin ${input.baseBranch} exited ${fetched.exitCode}: ${stderr.trim() || '(no output)'}`,
|
|
3893
|
+
),
|
|
3894
|
+
)
|
|
3895
|
+
}
|
|
3896
|
+
const isAncestor = async (ancestor: string, descendant: string): Promise<boolean> => {
|
|
3897
|
+
const result = await git(['merge-base', '--is-ancestor', ancestor, descendant])
|
|
3898
|
+
if (result.exitCode === 0) return true
|
|
3899
|
+
if (result.exitCode === 1) return false
|
|
3900
|
+
throw new SandboxOperationError(
|
|
3901
|
+
'refresh',
|
|
3902
|
+
`git merge-base --is-ancestor ${ancestor} ${descendant} exited ${result.exitCode}`,
|
|
3903
|
+
)
|
|
3904
|
+
}
|
|
3905
|
+
if (head === base || (await isAncestor(base, head))) {
|
|
3906
|
+
return { outcome: 'current', headSha: head, baseSha: base, previousHeadSha: head }
|
|
3907
|
+
}
|
|
3908
|
+
if (!(await isAncestor(head, base))) {
|
|
3909
|
+
return {
|
|
3910
|
+
outcome: 'refused',
|
|
3911
|
+
reason: 'diverged',
|
|
3912
|
+
message: sandboxRefreshDivergedMessage(head, input.baseBranch, base),
|
|
3913
|
+
}
|
|
3914
|
+
}
|
|
3915
|
+
await readableCommand(sandbox, {
|
|
3916
|
+
cmd: 'git',
|
|
3917
|
+
args: ['-c', 'advice.detachedHead=false', 'checkout', '--quiet', '--detach', base],
|
|
3918
|
+
cwd: VERCEL_WORKSPACE_PATH,
|
|
3919
|
+
})
|
|
3920
|
+
await commandOrThrow(sandbox, {
|
|
3921
|
+
cmd: 'sh',
|
|
3922
|
+
args: [
|
|
3923
|
+
'-c',
|
|
3924
|
+
'printf %s "$1" > "$2"',
|
|
3925
|
+
'marker',
|
|
3926
|
+
JSON.stringify({ baseSha: base }),
|
|
3927
|
+
VERCEL_PROVISIONED_MARKER,
|
|
3928
|
+
],
|
|
3929
|
+
})
|
|
3930
|
+
return { outcome: 'refreshed', headSha: base, baseSha: base, previousHeadSha: head }
|
|
2819
3931
|
}
|
|
2820
3932
|
|
|
2821
3933
|
/** Resolve the live handle behind a journal-carried environment id. A
|
|
2822
|
-
* missing environment is a typed `not-found`; the
|
|
2823
|
-
*
|
|
2824
|
-
|
|
3934
|
+
* missing environment is a typed `not-found`; a session the provider timer
|
|
3935
|
+
* stopped refuses typed `not-ready` (`stopped`) rather than resuming
|
|
3936
|
+
* inline — `sandbox.open` resumes it. A running session's timer is
|
|
3937
|
+
* extended to cover `boundMs` (the call's own wait bound) or the idle
|
|
3938
|
+
* timeout, whichever is longer. */
|
|
3939
|
+
private async sandboxHandle(
|
|
3940
|
+
handle: SandboxEnvironmentIdentity,
|
|
3941
|
+
boundMs = 0,
|
|
3942
|
+
): Promise<VercelSandboxHandle> {
|
|
2825
3943
|
const sandbox = await this.facade.get(handle.environmentId, this.operationSignal())
|
|
2826
3944
|
if (sandbox === null) {
|
|
2827
3945
|
throw new SandboxOperationError(
|
|
@@ -2829,6 +3947,18 @@ export class VercelSandboxProvider implements WorkspaceProvider {
|
|
|
2829
3947
|
`operator sandbox ${handle.environmentId} no longer exists`,
|
|
2830
3948
|
)
|
|
2831
3949
|
}
|
|
3950
|
+
const session = sandbox.sessionStatus
|
|
3951
|
+
if (session !== undefined && session !== 'running') {
|
|
3952
|
+
const state = session === 'pending' ? 'resuming' : 'stopped'
|
|
3953
|
+
throw new SandboxOperationError(
|
|
3954
|
+
'not-ready',
|
|
3955
|
+
state === 'resuming'
|
|
3956
|
+
? 'operator sandbox is resuming; poll sandbox.status until it reports ready'
|
|
3957
|
+
: 'operator sandbox is stopped; call sandbox.open and poll sandbox.status until it reports ready',
|
|
3958
|
+
{ state },
|
|
3959
|
+
)
|
|
3960
|
+
}
|
|
3961
|
+
await this.extendOperatorTimer(sandbox, boundMs)
|
|
2832
3962
|
this.sessions.set(handle.environmentId, sandbox)
|
|
2833
3963
|
return sandbox
|
|
2834
3964
|
}
|
|
@@ -2889,11 +4019,11 @@ export class VercelSandboxProvider implements WorkspaceProvider {
|
|
|
2889
4019
|
handle: SandboxEnvironmentIdentity,
|
|
2890
4020
|
request: SandboxCommandRequest,
|
|
2891
4021
|
): Promise<SandboxCommandResult> {
|
|
2892
|
-
const sandbox = await this.sandboxHandle(handle)
|
|
2893
4022
|
const timeoutSeconds = Math.min(
|
|
2894
4023
|
Math.max(request.timeoutSeconds ?? 120, 1),
|
|
2895
4024
|
SANDBOX_MAX_WAIT_SECONDS,
|
|
2896
4025
|
)
|
|
4026
|
+
const sandbox = await this.sandboxHandle(handle, timeoutSeconds * 1000 + 60_000)
|
|
2897
4027
|
const command = await this.sandboxLaunch(sandbox, request)
|
|
2898
4028
|
const deadline = Date.now() + timeoutSeconds * 1000
|
|
2899
4029
|
let exit: { exitCode: number }
|
|
@@ -2938,8 +4068,8 @@ export class VercelSandboxProvider implements WorkspaceProvider {
|
|
|
2938
4068
|
handle: SandboxEnvironmentIdentity,
|
|
2939
4069
|
input: { commandId: string; waitSeconds: number },
|
|
2940
4070
|
): Promise<SandboxWaitResult> {
|
|
2941
|
-
const sandbox = await this.sandboxHandle(handle)
|
|
2942
4071
|
const waitSeconds = Math.min(Math.max(input.waitSeconds, 0), SANDBOX_MAX_WAIT_SECONDS)
|
|
4072
|
+
const sandbox = await this.sandboxHandle(handle, waitSeconds * 1000 + 60_000)
|
|
2943
4073
|
const lookup = await sandbox.getCommand(input.commandId, { signal: this.operationSignal() })
|
|
2944
4074
|
if (lookup.exitCode !== null) {
|
|
2945
4075
|
const [stdout, stderr] = await Promise.all([
|
|
@@ -3067,6 +4197,13 @@ export class VercelSandboxProvider implements WorkspaceProvider {
|
|
|
3067
4197
|
}): Promise<{
|
|
3068
4198
|
snapshots: { outcome: 'confirmed' | 'unknown'; deleted?: number; error?: string }
|
|
3069
4199
|
}> {
|
|
4200
|
+
// An in-flight attempt is cancelled and awaited before the teardown.
|
|
4201
|
+
const inflight = this.operatorInflight.get(input.environmentId)
|
|
4202
|
+
if (inflight !== undefined) {
|
|
4203
|
+
inflight.abort.abort()
|
|
4204
|
+
await inflight.promise
|
|
4205
|
+
}
|
|
4206
|
+
this.operatorFailures.delete(input.environmentId)
|
|
3070
4207
|
const reap = await this.reap(input.environmentId)
|
|
3071
4208
|
return {
|
|
3072
4209
|
snapshots: {
|