@ship.zone/runner 2.1.0 → 4.0.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 (200) hide show
  1. package/.smartconfig.json +118 -3
  2. package/changelog.md +101 -0
  3. package/dist_rust/runnerworkspace_linux_amd64_musl +0 -0
  4. package/dist_rust/runnerworkspace_linux_amd64_musl.third-party-notices.json +679 -0
  5. package/dist_rust/runnerworkspace_linux_amd64_musl.third-party-notices.txt +15719 -0
  6. package/dist_rust/runnerworkspace_linux_amd64_musl.tsrust-build.json +5 -5
  7. package/dist_rust/runnerworkspace_linux_arm64_musl +0 -0
  8. package/dist_rust/runnerworkspace_linux_arm64_musl.third-party-notices.json +679 -0
  9. package/dist_rust/runnerworkspace_linux_arm64_musl.third-party-notices.txt +15719 -0
  10. package/dist_rust/runnerworkspace_linux_arm64_musl.tsrust-build.json +5 -5
  11. package/dist_ts/00_commitinfo_data.d.ts +8 -0
  12. package/dist_ts/00_commitinfo_data.js +9 -0
  13. package/dist_ts/api-client.d.ts +47 -0
  14. package/dist_ts/api-client.js +600 -0
  15. package/dist_ts/artifact-manager.d.ts +11 -0
  16. package/dist_ts/artifact-manager.js +140 -0
  17. package/dist_ts/attempt-state.d.ts +18 -0
  18. package/dist_ts/attempt-state.js +151 -0
  19. package/dist_ts/cache-manager.d.ts +13 -0
  20. package/dist_ts/cache-manager.js +300 -0
  21. package/dist_ts/cli-entry.d.ts +2 -0
  22. package/dist_ts/cli-entry.js +18 -0
  23. package/dist_ts/cli.d.ts +14 -0
  24. package/dist_ts/cli.js +243 -0
  25. package/dist_ts/config.d.ts +8 -0
  26. package/dist_ts/config.js +495 -0
  27. package/dist_ts/egress-proxy.d.ts +99 -0
  28. package/dist_ts/egress-proxy.js +607 -0
  29. package/dist_ts/errors.d.ts +41 -0
  30. package/dist_ts/errors.js +90 -0
  31. package/dist_ts/filesystem.d.ts +73 -0
  32. package/dist_ts/filesystem.js +207 -0
  33. package/dist_ts/index.d.ts +20 -0
  34. package/dist_ts/index.js +21 -0
  35. package/dist_ts/interfaces.d.ts +685 -0
  36. package/dist_ts/interfaces.js +3 -0
  37. package/dist_ts/log-sender.d.ts +26 -0
  38. package/dist_ts/log-sender.js +124 -0
  39. package/dist_ts/microvm-executor.d.ts +90 -0
  40. package/dist_ts/microvm-executor.js +1045 -0
  41. package/dist_ts/node-version.d.ts +11 -0
  42. package/dist_ts/node-version.js +43 -0
  43. package/dist_ts/npm-grants.d.ts +9 -0
  44. package/dist_ts/npm-grants.js +44 -0
  45. package/dist_ts/oci-registry.d.ts +73 -0
  46. package/dist_ts/oci-registry.js +508 -0
  47. package/dist_ts/plugins.d.ts +23 -0
  48. package/dist_ts/plugins.js +27 -0
  49. package/dist_ts/protocol-validator.d.ts +39 -0
  50. package/dist_ts/protocol-validator.js +488 -0
  51. package/dist_ts/redactor.d.ts +78 -0
  52. package/dist_ts/redactor.js +235 -0
  53. package/dist_ts/registration-state.d.ts +16 -0
  54. package/dist_ts/registration-state.js +171 -0
  55. package/dist_ts/runner.d.ts +65 -0
  56. package/dist_ts/runner.js +912 -0
  57. package/dist_ts/source-workspace.d.ts +10 -0
  58. package/dist_ts/source-workspace.js +125 -0
  59. package/dist_ts/spec-version.d.ts +11 -0
  60. package/dist_ts/spec-version.js +41 -0
  61. package/dist_ts/staging-scavenger.d.ts +7 -0
  62. package/dist_ts/staging-scavenger.js +63 -0
  63. package/dist_ts/state-owner.d.ts +74 -0
  64. package/dist_ts/state-owner.js +291 -0
  65. package/dist_ts/transfer-archive.d.ts +78 -0
  66. package/dist_ts/transfer-archive.js +1619 -0
  67. package/dist_ts/validation.d.ts +11 -0
  68. package/dist_ts/validation.js +79 -0
  69. package/dist_ts/vsock-protocol.d.ts +130 -0
  70. package/dist_ts/vsock-protocol.js +336 -0
  71. package/dist_ts/wire-schema.d.ts +10 -0
  72. package/dist_ts/wire-schema.js +114 -0
  73. package/native-notices/crates/bitflags-2.13.1/license-apache +201 -0
  74. package/native-notices/crates/bitflags-2.13.1/license-mit +25 -0
  75. package/native-notices/crates/cc-1.8.0/license-apache +201 -0
  76. package/native-notices/crates/cc-1.8.0/license-mit +25 -0
  77. package/native-notices/crates/cfg-if-1.0.4/license-apache +201 -0
  78. package/native-notices/crates/cfg-if-1.0.4/license-mit +25 -0
  79. package/native-notices/crates/cfg_aliases-0.2.2/license +9 -0
  80. package/native-notices/crates/cfg_aliases-0.2.2/notices.md +26 -0
  81. package/native-notices/crates/find-msvc-tools-0.1.14/license-apache +201 -0
  82. package/native-notices/crates/find-msvc-tools-0.1.14/license-mit +25 -0
  83. package/native-notices/crates/itoa-1.0.18/license-apache +176 -0
  84. package/native-notices/crates/itoa-1.0.18/license-mit +23 -0
  85. package/native-notices/crates/libc-0.2.189/license-apache +176 -0
  86. package/native-notices/crates/libc-0.2.189/license-mit +25 -0
  87. package/native-notices/crates/memchr-2.8.3/copying +3 -0
  88. package/native-notices/crates/memchr-2.8.3/license-mit +21 -0
  89. package/native-notices/crates/memchr-2.8.3/unlicense +24 -0
  90. package/native-notices/crates/nix-0.30.1/license +21 -0
  91. package/native-notices/crates/proc-macro2-1.0.107/license-apache +176 -0
  92. package/native-notices/crates/proc-macro2-1.0.107/license-mit +23 -0
  93. package/native-notices/crates/quote-1.0.47/license-apache +176 -0
  94. package/native-notices/crates/quote-1.0.47/license-mit +23 -0
  95. package/native-notices/crates/serde-1.0.229/license-apache +176 -0
  96. package/native-notices/crates/serde-1.0.229/license-mit +23 -0
  97. package/native-notices/crates/serde_core-1.0.229/license-apache +176 -0
  98. package/native-notices/crates/serde_core-1.0.229/license-mit +23 -0
  99. package/native-notices/crates/serde_derive-1.0.229/license-apache +176 -0
  100. package/native-notices/crates/serde_derive-1.0.229/license-mit +23 -0
  101. package/native-notices/crates/serde_json-1.0.151/license-apache +176 -0
  102. package/native-notices/crates/serde_json-1.0.151/license-mit +23 -0
  103. package/native-notices/crates/shlex-2.0.1/license-apache +13 -0
  104. package/native-notices/crates/shlex-2.0.1/license-mit +21 -0
  105. package/native-notices/crates/syn-3.0.3/license-apache +176 -0
  106. package/native-notices/crates/syn-3.0.3/license-mit +23 -0
  107. package/native-notices/crates/tikv-jemalloc-sys-0.7.1+5.3.1-0-g81034ce1f1373e37dc865038e1bc8eeecf559ce8/license-apache +201 -0
  108. package/native-notices/crates/tikv-jemalloc-sys-0.7.1+5.3.1-0-g81034ce1f1373e37dc865038e1bc8eeecf559ce8/license-mit +25 -0
  109. package/native-notices/crates/tikv-jemallocator-0.7.0/license-apache +201 -0
  110. package/native-notices/crates/tikv-jemallocator-0.7.0/license-mit +25 -0
  111. package/native-notices/crates/unicode-ident-1.0.24/license-apache +176 -0
  112. package/native-notices/crates/unicode-ident-1.0.24/license-mit +23 -0
  113. package/native-notices/crates/unicode-ident-1.0.24/license-unicode +39 -0
  114. package/native-notices/crates/zmij-1.0.23/license-mit +23 -0
  115. package/native-notices/manifest.json +763 -0
  116. package/native-notices/native/tikv-jemalloc-sys-0.7.1+5.3.1-0-g81034ce1f1373e37dc865038e1bc8eeecf559ce8/jemalloc-5.3.1/jemalloc-copying +27 -0
  117. package/native-notices/readme.md +46 -0
  118. package/native-notices/runtime/gcc/gpl-3.0.txt +674 -0
  119. package/native-notices/runtime/gcc/runtime-library-exception-3.1.txt +73 -0
  120. package/native-notices/runtime/libunwind-22.1.2/license.txt +311 -0
  121. package/native-notices/runtime/musl-1.2.5/copyright +193 -0
  122. package/native-notices/rust/compiler-builtins-license.txt +275 -0
  123. package/native-notices/rust/copyright-library.html +8266 -0
  124. package/native-notices/rust/crates/addr2line-0.25.1/license-apache +201 -0
  125. package/native-notices/rust/crates/addr2line-0.25.1/license-mit +25 -0
  126. package/native-notices/rust/crates/adler2-2.0.1/license-0bsd +12 -0
  127. package/native-notices/rust/crates/adler2-2.0.1/license-apache +201 -0
  128. package/native-notices/rust/crates/adler2-2.0.1/license-mit +23 -0
  129. package/native-notices/rust/crates/memchr-2.7.6/copying +3 -0
  130. package/native-notices/rust/crates/memchr-2.7.6/license-mit +21 -0
  131. package/native-notices/rust/crates/memchr-2.7.6/unlicense +24 -0
  132. package/native-notices/rust/crates/miniz_oxide-0.8.9/license +25 -0
  133. package/native-notices/rust/crates/miniz_oxide-0.8.9/license-apache.md +177 -0
  134. package/native-notices/rust/crates/miniz_oxide-0.8.9/license-mit.md +24 -0
  135. package/native-notices/rust/crates/miniz_oxide-0.8.9/license-zlib.md +14 -0
  136. package/native-notices/rust/crates/object-0.37.3/license-apache +201 -0
  137. package/native-notices/rust/crates/object-0.37.3/license-mit +25 -0
  138. package/native-notices/rust/licenses/apache-2.0.txt +73 -0
  139. package/native-notices/rust/licenses/bsd-2-clause.txt +9 -0
  140. package/native-notices/rust/licenses/cc-by-sa-4.0.txt +427 -0
  141. package/native-notices/rust/licenses/gcc-exception-3.1.txt +30 -0
  142. package/native-notices/rust/licenses/gpl-2.0-only.txt +133 -0
  143. package/native-notices/rust/licenses/gpl-3.0-or-later.txt +202 -0
  144. package/native-notices/rust/licenses/isc.txt +7 -0
  145. package/native-notices/rust/licenses/llvm-exception.txt +15 -0
  146. package/native-notices/rust/licenses/mit.txt +9 -0
  147. package/native-notices/rust/licenses/ncsa.txt +29 -0
  148. package/native-notices/rust/licenses/ofl-1.1.txt +43 -0
  149. package/native-notices/rust/licenses/unicode-3.0.txt +39 -0
  150. package/package.json +31 -26
  151. package/readme.md +157 -95
  152. package/rust/.cargo/config.toml +1 -1
  153. package/rust/Cargo.lock +1 -0
  154. package/rust/Cargo.toml +3 -2
  155. package/rust/src/cpio.rs +147 -0
  156. package/rust/src/extfs.rs +747 -0
  157. package/rust/src/guest.rs +2411 -0
  158. package/rust/src/lib.rs +197 -1
  159. package/rust/src/main.rs +7 -2
  160. package/rust/src/oci_tar.rs +842 -0
  161. package/rust-toolchain.toml +4 -0
  162. package/ts/00_commitinfo_data.ts +2 -2
  163. package/ts/api-client.ts +29 -8
  164. package/ts/artifact-manager.ts +9 -7
  165. package/ts/attempt-state.ts +75 -84
  166. package/ts/cache-manager.ts +22 -28
  167. package/ts/cli-entry.ts +17 -0
  168. package/ts/cli.ts +86 -53
  169. package/ts/config.ts +146 -62
  170. package/ts/egress-proxy.ts +649 -0
  171. package/ts/errors.ts +19 -0
  172. package/ts/filesystem.ts +316 -0
  173. package/ts/index.ts +20 -15
  174. package/ts/interfaces.ts +105 -23
  175. package/ts/log-sender.ts +4 -4
  176. package/ts/microvm-executor.ts +1265 -0
  177. package/ts/node-version.ts +49 -0
  178. package/ts/npm-grants.ts +49 -0
  179. package/ts/oci-registry.ts +649 -0
  180. package/ts/plugins.ts +25 -3
  181. package/ts/protocol-validator.ts +34 -30
  182. package/ts/redactor.ts +2 -2
  183. package/ts/registration-state.ts +82 -90
  184. package/ts/runner.ts +81 -34
  185. package/ts/source-workspace.ts +11 -8
  186. package/ts/spec-version.ts +2 -2
  187. package/ts/staging-scavenger.ts +37 -26
  188. package/ts/state-owner.ts +353 -0
  189. package/ts/transfer-archive.ts +214 -243
  190. package/ts/validation.ts +1 -1
  191. package/ts/vsock-protocol.ts +437 -0
  192. package/ts/wire-schema.ts +3 -3
  193. package/deno.json +0 -56
  194. package/deno.lock +0 -1495
  195. package/dist_npm/mod.d.ts +0 -967
  196. package/dist_npm/mod.js +0 -10058
  197. package/mod.ts +0 -8
  198. package/musl-copyright.md +0 -81
  199. package/third-party-licenses.md +0 -187
  200. package/ts/oci-executor.ts +0 -3137
@@ -0,0 +1,1265 @@
1
+ import * as plugins from './plugins.js';
2
+ import { ConfigurationError, ProtocolError, ResourceCleanupError, RunnerError } from './errors.js';
3
+ import {
4
+ createNewWriteFlags,
5
+ isNotFound,
6
+ lstatIfPresent,
7
+ makeTempDir,
8
+ readBoundedRegularFile,
9
+ removePath,
10
+ sha256Hex,
11
+ syncDirectory,
12
+ withOpenFile,
13
+ writeAll,
14
+ } from './filesystem.js';
15
+ import type {
16
+ ICompiledStep,
17
+ IExecutionContext,
18
+ IExecutionResult,
19
+ IJobExecutor,
20
+ IMicroVmShapeInfo,
21
+ IOciExecutorConfig,
22
+ IOciRuntimeFacts,
23
+ IPrepareOciLeaseContext,
24
+ IPreparedOciLease,
25
+ IRunnerConfig,
26
+ IRuntimeWorkspaceExporter,
27
+ IWorkspaceExport,
28
+ IWorkspaceExportRequest,
29
+ TExecutionStopReason,
30
+ TOciArchitecture,
31
+ TOciHelperTarget,
32
+ } from './interfaces.js';
33
+ import {
34
+ type IMaterializedOciImage,
35
+ OciRegistryClient,
36
+ parseDigestPinnedImageReference,
37
+ resolveImageReference,
38
+ } from './oci-registry.js';
39
+ import { EgressAllowlistController, grantOriginsFromLease } from './egress-proxy.js';
40
+ import { buildNpmrcContent, GUEST_NPMRC_PATH } from './npm-grants.js';
41
+ import {
42
+ ensurePrivateStateDirectory,
43
+ resolvePackagedWorkspaceHelperPath,
44
+ type RunnerStateOwner,
45
+ workspaceHelperMaximumBytes,
46
+ } from './state-owner.js';
47
+ import { validateEnvironmentName } from './validation.js';
48
+ import { GUEST_VSOCK_PORT, GuestVsockClient } from './vsock-protocol.js';
49
+
50
+ const { join, resolve } = plugins.path;
51
+
52
+ const defaultSmartVmSocketPath = '/run/smartvm/helper.sock';
53
+ const activeVmsFileName = 'active-vms.json';
54
+ const workspaceHelperDirectoryName = 'workspace-helpers';
55
+ const ociCacheDirectoryName = 'oci-cache';
56
+ const workspaceExportsDirectoryName = 'workspace-exports';
57
+ const maximumCommandArguments = 128;
58
+ const maximumCommandArgumentBytes = 16 * 1024;
59
+ const maximumCommandBytes = 128 * 1024;
60
+ const vsockConnectRetryIntervalMs = 50;
61
+ const vsockConnectTimeoutMs = 15_000;
62
+ const tarBlockSize = 512;
63
+
64
+ export interface IMicroVmHandle {
65
+ readonly vmId: string;
66
+ readonly slot: number;
67
+ readonly shapeId: string;
68
+ readonly imageDigest: string;
69
+ start(options?: { timeoutMs?: number }): Promise<void>;
70
+ connectVsock(port: number): Promise<plugins.net.Socket>;
71
+ kill(): Promise<void>;
72
+ destroy(): Promise<void>;
73
+ }
74
+
75
+ export interface ISmartVmClient {
76
+ readonly info: {
77
+ readonly packageVersion: string;
78
+ readonly arch: 'x86_64' | 'aarch64';
79
+ readonly firecrackerVersion: string;
80
+ readonly slotCount: number;
81
+ readonly shapes: readonly IMicroVmShapeInfo[];
82
+ readonly dogfood: boolean;
83
+ };
84
+ checkHost(): Promise<{ ok: boolean; dogfood: boolean; items: Array<{ id: string; status: string; detail: string }> }>;
85
+ computeImageDigest(input: plugins.smartvm.IStageImageInput): Promise<{ imageDigest: string }>;
86
+ createVMFromImage(
87
+ input: plugins.smartvm.IStageImageInput,
88
+ options: Omit<plugins.smartvm.ICreateVMOptions, 'imageDigest'>,
89
+ ): Promise<IMicroVmHandle>;
90
+ getVM(vmId: string): Promise<IMicroVmHandle | undefined>;
91
+ close(): Promise<void>;
92
+ }
93
+
94
+ export interface IMicroVmExecutorDependencies {
95
+ connectSmartVm?: (options: plugins.smartvm.ISmartVMConnectOptions) => Promise<ISmartVmClient>;
96
+ resolveHelperPath?: (target: TOciHelperTarget) => Promise<string>;
97
+ materializeImage?: (
98
+ image: string,
99
+ architecture: TOciArchitecture,
100
+ signal?: AbortSignal,
101
+ ) => Promise<IMaterializedOciImage>;
102
+ buildInitrd?: (helperPath: string, outputPath: string) => Promise<void>;
103
+ fetchImplementation?: typeof fetch;
104
+ now?: () => number;
105
+ }
106
+
107
+ const parseContainerUser = (user: string): { uid: number; gid: number } => {
108
+ const match = /^([1-9][0-9]*)(?::([1-9][0-9]*))?$/.exec(user);
109
+ if (!match) {
110
+ throw new ConfigurationError('oci.containerUser must be a numeric non-root UID[:GID]');
111
+ }
112
+ const uid = Number(match[1]);
113
+ const gid = Number(match[2] ?? match[1]);
114
+ if (
115
+ !Number.isSafeInteger(uid) || !Number.isSafeInteger(gid) ||
116
+ uid <= 0 || gid <= 0 || uid > 4_294_967_294 || gid > 4_294_967_294
117
+ ) {
118
+ throw new ConfigurationError('oci.containerUser must be a numeric non-root UID[:GID]');
119
+ }
120
+ return { uid, gid };
121
+ };
122
+
123
+ const archFromSmartVm = (arch: 'x86_64' | 'aarch64'): {
124
+ architecture: TOciArchitecture;
125
+ helperTarget: TOciHelperTarget;
126
+ } => {
127
+ if (arch === 'x86_64') return { architecture: 'amd64', helperTarget: 'linux_amd64' };
128
+ if (arch === 'aarch64') return { architecture: 'arm64', helperTarget: 'linux_arm64' };
129
+ throw new RunnerError(`Unsupported Firecracker host architecture: ${String(arch)}`);
130
+ };
131
+
132
+ /** Selects the smallest SmartVM shape whose memory and vCPU count fit the job's ceilings. */
133
+ export const selectShapeForJob = (
134
+ shapes: readonly IMicroVmShapeInfo[],
135
+ memoryBytes: number,
136
+ cpus: number,
137
+ guestMemoryOverheadBytes: number,
138
+ ): IMicroVmShapeInfo => {
139
+ const requiredMemMib = Math.ceil((memoryBytes + guestMemoryOverheadBytes) / (1024 * 1024));
140
+ const requiredVcpus = Math.max(1, Math.ceil(cpus));
141
+ const sorted = [...shapes].sort((a, b) => (a.memMib - b.memMib) || (a.vcpus - b.vcpus));
142
+ const match = sorted.find((shape) => shape.memMib >= requiredMemMib && shape.vcpus >= requiredVcpus);
143
+ if (!match) {
144
+ throw new RunnerError(
145
+ `No Firecracker shape fits ${requiredMemMib} MiB memory and ${requiredVcpus} vCPU(s)`,
146
+ );
147
+ }
148
+ return match;
149
+ };
150
+
151
+ const stopReasonForAbort = (reason: unknown): TExecutionStopReason => {
152
+ if (
153
+ reason === 'job_canceled' ||
154
+ reason === 'lease_lost' ||
155
+ reason === 'lease_expired' ||
156
+ reason === 'runner_shutdown' ||
157
+ reason === 'job_timeout' ||
158
+ reason === 'log_delivery_failed' ||
159
+ reason === 'resource_limit'
160
+ ) {
161
+ return reason;
162
+ }
163
+ return 'job_canceled';
164
+ };
165
+
166
+ const validateStepCommand = (command: readonly string[]): void => {
167
+ if (command.length === 0 || command.length > maximumCommandArguments) {
168
+ throw new ProtocolError('Step command argument count is out of bounds');
169
+ }
170
+ let totalBytes = 0;
171
+ for (const argument of command) {
172
+ const length = Buffer.byteLength(argument, 'utf8');
173
+ if (length > maximumCommandArgumentBytes || argument.includes('\0')) {
174
+ throw new ProtocolError('Step command argument is invalid or exceeds size limit');
175
+ }
176
+ totalBytes += length;
177
+ }
178
+ if (totalBytes > maximumCommandBytes) {
179
+ throw new ProtocolError('Step command exceeds maximum byte length');
180
+ }
181
+ };
182
+
183
+ const buildStepEnvironment = (
184
+ config: IRunnerConfig,
185
+ step: ICompiledStep,
186
+ secrets: Record<string, string>,
187
+ defaultEnv?: Record<string, string>,
188
+ ): Record<string, string> => {
189
+ const env: Record<string, string> = {};
190
+ if (
191
+ defaultEnv?.PATH &&
192
+ !Object.hasOwn(step.environment, 'PATH') &&
193
+ !Object.hasOwn(secrets, 'PATH')
194
+ ) {
195
+ env.PATH = defaultEnv.PATH;
196
+ }
197
+ let combinedCount = 0;
198
+ for (const [key, value] of Object.entries(step.environment)) {
199
+ validateEnvironmentName(key);
200
+ if (Buffer.byteLength(value, 'utf8') > config.maximumEnvironmentValueBytes) {
201
+ throw new ProtocolError(`Environment variable ${key} exceeds maximum value size`);
202
+ }
203
+ env[key] = value;
204
+ combinedCount += 1;
205
+ }
206
+ for (const [key, value] of Object.entries(secrets)) {
207
+ validateEnvironmentName(key);
208
+ if (Object.hasOwn(step.environment, key)) {
209
+ throw new ProtocolError(`Secret ${key} collides with step environment`);
210
+ }
211
+ if (Buffer.byteLength(value, 'utf8') > config.maximumSecretBytes) {
212
+ throw new ProtocolError(`Secret ${key} exceeds maximum value size`);
213
+ }
214
+ env[key] = value;
215
+ combinedCount += 1;
216
+ }
217
+ if (combinedCount > config.maximumEnvironmentVariables) {
218
+ throw new ProtocolError('Combined step environment and secrets exceed limit');
219
+ }
220
+ return env;
221
+ };
222
+
223
+ const defaultBuildInitrd = async (helperPath: string, outputPath: string): Promise<void> => {
224
+ await new Promise<void>((resolvePromise, rejectPromise) => {
225
+ const child = plugins.childProcess.spawn(
226
+ helperPath,
227
+ ['build-initrd', '--binary', helperPath, '--output', outputPath],
228
+ { env: {}, stdio: ['ignore', 'pipe', 'pipe'] },
229
+ );
230
+ const stderr: Buffer[] = [];
231
+ child.stderr.on('data', (chunk: Buffer) => stderr.push(chunk));
232
+ child.once('error', (error) => {
233
+ rejectPromise(new RunnerError(`Unable to build Firecracker initrd: ${error.message}`, { cause: error }));
234
+ });
235
+ child.once('close', (code) => {
236
+ if (code === 0) resolvePromise();
237
+ else {
238
+ const msg = Buffer.concat(stderr).toString('utf8').trim();
239
+ rejectPromise(new RunnerError(`Failed to build Firecracker initrd (exit ${code}): ${msg}`));
240
+ }
241
+ });
242
+ });
243
+ };
244
+
245
+ // --- Minimal deterministic USTAR + PAX tar helpers for host <-> guest vsock transfer ---
246
+
247
+ const pushPaxRecord = (out: Buffer[], key: string, value: Buffer): void => {
248
+ const keyBuf = Buffer.from(key, 'utf8');
249
+ const baseLen = 1 + keyBuf.length + 1 + value.length + 1;
250
+ let total = baseLen + 1;
251
+ while (baseLen + String(total).length !== total) {
252
+ total = baseLen + String(total).length;
253
+ }
254
+ out.push(Buffer.from(`${total} ${key}=`, 'utf8'), value, Buffer.from('\n'));
255
+ };
256
+
257
+ const writeUstarHeader = (
258
+ name: string,
259
+ typeflag: string,
260
+ mode: number,
261
+ size: number,
262
+ mtime: number,
263
+ linkname: string,
264
+ ): Buffer => {
265
+ const header = Buffer.alloc(tarBlockSize);
266
+ Buffer.from(name, 'utf8').copy(header, 0, 0, Math.min(Buffer.byteLength(name, 'utf8'), 100));
267
+ header.write(`${(mode & 0o7777).toString(8).padStart(7, '0')}\0`, 100, 'ascii');
268
+ header.write(`${(0).toString(8).padStart(7, '0')}\0`, 108, 'ascii');
269
+ header.write(`${(0).toString(8).padStart(7, '0')}\0`, 116, 'ascii');
270
+ header.write(`${Math.min(size, 0o77777777777).toString(8).padStart(11, '0')}\0`, 124, 'ascii');
271
+ header.write(`${Math.min(Math.max(0, Math.floor(mtime)), 0o77777777777).toString(8).padStart(11, '0')}\0`, 136, 'ascii');
272
+ header.fill(0x20, 148, 156);
273
+ header.write(typeflag, 156, 1, 'ascii');
274
+ Buffer.from(linkname, 'utf8').copy(header, 157, 0, Math.min(Buffer.byteLength(linkname, 'utf8'), 100));
275
+ header.write('ustar\0', 257, 'ascii');
276
+ header.write('00', 263, 'ascii');
277
+ let checksum = 0;
278
+ for (let i = 0; i < tarBlockSize; i += 1) checksum += header[i];
279
+ header.write(`${checksum.toString(8).padStart(6, '0')}\0 `, 148, 'ascii');
280
+ return header;
281
+ };
282
+
283
+ const padTarBlock = (length: number): Buffer => {
284
+ const rem = length % tarBlockSize;
285
+ return rem === 0 ? Buffer.alloc(0) : Buffer.alloc(tarBlockSize - rem);
286
+ };
287
+
288
+ const packDirectoryToTar = async (
289
+ rootDir: string,
290
+ maximumBytes: number,
291
+ maximumEntries: number,
292
+ ): Promise<{ tarBytes: Buffer; logicalBytes: number; entryCount: number }> => {
293
+ const chunks: Buffer[] = [];
294
+ let logicalBytes = 0;
295
+ let entryCount = 0;
296
+
297
+ const walk = async (rel: string): Promise<void> => {
298
+ const abs = rel ? join(rootDir, rel) : rootDir;
299
+ const names = (await plugins.fs.readdir(abs)).sort();
300
+ for (const name of names) {
301
+ const childRel = rel ? `${rel}/${name}` : name;
302
+ const childAbs = join(rootDir, childRel);
303
+ const stat = await plugins.fs.lstat(childAbs);
304
+ entryCount += 1;
305
+ if (entryCount > maximumEntries) {
306
+ throw new RunnerError('Workspace entry count exceeds limit during VM transfer');
307
+ }
308
+
309
+ const emitEntry = (
310
+ typeflag: string,
311
+ mode: number,
312
+ data: Buffer,
313
+ linkname: string,
314
+ ): void => {
315
+ const paxParts: Buffer[] = [];
316
+ if (Buffer.byteLength(childRel, 'utf8') > 100) {
317
+ pushPaxRecord(paxParts, 'path', Buffer.from(childRel, 'utf8'));
318
+ }
319
+ if (Buffer.byteLength(linkname, 'utf8') > 100) {
320
+ pushPaxRecord(paxParts, 'linkpath', Buffer.from(linkname, 'utf8'));
321
+ }
322
+ if (data.length > 0o77777777777) {
323
+ pushPaxRecord(paxParts, 'size', Buffer.from(String(data.length), 'utf8'));
324
+ }
325
+ if (paxParts.length > 0) {
326
+ const paxBuf = Buffer.concat(paxParts);
327
+ chunks.push(writeUstarHeader('pax/header', 'x', 0o644, paxBuf.length, 0, ''));
328
+ chunks.push(paxBuf, padTarBlock(paxBuf.length));
329
+ }
330
+ chunks.push(writeUstarHeader(childRel, typeflag, mode, data.length, Math.floor(stat.mtimeMs / 1000), linkname));
331
+ if (data.length > 0) {
332
+ chunks.push(data, padTarBlock(data.length));
333
+ }
334
+ };
335
+
336
+ if (stat.isDirectory()) {
337
+ emitEntry('5', stat.mode & 0o777, Buffer.alloc(0), '');
338
+ await walk(childRel);
339
+ } else if (stat.isSymbolicLink()) {
340
+ const target = await plugins.fs.readlink(childAbs);
341
+ emitEntry('2', 0o777, Buffer.alloc(0), target);
342
+ } else if (stat.isFile()) {
343
+ logicalBytes += stat.size;
344
+ if (logicalBytes > maximumBytes) {
345
+ throw new RunnerError('Workspace size exceeds limit during VM transfer');
346
+ }
347
+ const data = await plugins.fs.readFile(childAbs);
348
+ emitEntry('0', stat.mode & 0o777, data, '');
349
+ } else {
350
+ throw new RunnerError('Workspace contains unsupported special file');
351
+ }
352
+ }
353
+ };
354
+
355
+ await walk('');
356
+ chunks.push(Buffer.alloc(tarBlockSize * 2));
357
+ return { tarBytes: Buffer.concat(chunks), logicalBytes, entryCount };
358
+ };
359
+
360
+ const parseTarOctal = (buf: Buffer): number => {
361
+ const text = buf.toString('ascii').replace(/\0.*$/, '').trim();
362
+ return text.length === 0 ? 0 : Number.parseInt(text, 8);
363
+ };
364
+
365
+ const parsePaxBuffer = (buf: Buffer): Record<string, string> => {
366
+ const result: Record<string, string> = {};
367
+ let pos = 0;
368
+ while (pos < buf.length) {
369
+ const space = buf.indexOf(0x20, pos);
370
+ if (space < 0) break;
371
+ const len = Number.parseInt(buf.subarray(pos, space).toString('ascii'), 10);
372
+ if (!Number.isFinite(len) || len <= 0 || pos + len > buf.length) break;
373
+ const rec = buf.subarray(space + 1, pos + len).toString('utf8').replace(/\n$/, '');
374
+ const eq = rec.indexOf('=');
375
+ if (eq > 0) result[rec.slice(0, eq)] = rec.slice(eq + 1);
376
+ pos += len;
377
+ }
378
+ return result;
379
+ };
380
+
381
+ const unpackTarToDirectory = async (
382
+ tarBytes: Buffer,
383
+ destinationDir: string,
384
+ maximumBytes: number,
385
+ maximumEntries: number,
386
+ ): Promise<{ logicalBytes: number; entryCount: number }> => {
387
+ let offset = 0;
388
+ let paxNext: Record<string, string> = {};
389
+ let logicalBytes = 0;
390
+ let entryCount = 0;
391
+
392
+ while (offset + tarBlockSize <= tarBytes.length) {
393
+ const header = tarBytes.subarray(offset, offset + tarBlockSize);
394
+ offset += tarBlockSize;
395
+ if (header.every((byte) => byte === 0)) break;
396
+
397
+ const typeflag = String.fromCharCode(header[156]);
398
+ let size = parseTarOctal(header.subarray(124, 136));
399
+ const mode = parseTarOctal(header.subarray(100, 108)) & 0o777;
400
+ const rawName = header.subarray(0, 100).toString('utf8').replace(/\0.*$/, '');
401
+ const prefix = header.subarray(345, 500).toString('utf8').replace(/\0.*$/, '');
402
+ let entryPath = prefix ? `${prefix}/${rawName}` : rawName;
403
+ let linkname = header.subarray(157, 257).toString('utf8').replace(/\0.*$/, '');
404
+
405
+ if (typeflag === 'x') {
406
+ const payload = tarBytes.subarray(offset, offset + size);
407
+ paxNext = { ...paxNext, ...parsePaxBuffer(payload) };
408
+ offset += Math.ceil(size / tarBlockSize) * tarBlockSize;
409
+ continue;
410
+ }
411
+
412
+ if (paxNext.path) entryPath = paxNext.path;
413
+ if (paxNext.linkpath) linkname = paxNext.linkpath;
414
+ if (paxNext.size) size = Number.parseInt(paxNext.size, 10);
415
+ paxNext = {};
416
+
417
+ const payload = tarBytes.subarray(offset, offset + size);
418
+ offset += Math.ceil(size / tarBlockSize) * tarBlockSize;
419
+
420
+ const parts = entryPath.split('/').filter((segment) => segment.length > 0 && segment !== '.');
421
+ if (parts.length === 0 || parts.some((segment) => segment === '..')) {
422
+ throw new RunnerError('Exported tar contains invalid path');
423
+ }
424
+ entryCount += 1;
425
+ if (entryCount > maximumEntries) {
426
+ throw new RunnerError('Exported workspace exceeds maximum entry count');
427
+ }
428
+ const targetPath = join(destinationDir, ...parts);
429
+ await plugins.fs.mkdir(plugins.path.dirname(targetPath), { recursive: true, mode: 0o700 });
430
+
431
+ if (typeflag === '5') {
432
+ await plugins.fs.mkdir(targetPath, { recursive: true, mode: mode || 0o755 });
433
+ } else if (typeflag === '2') {
434
+ await plugins.fs.symlink(linkname, targetPath);
435
+ } else if (typeflag === '0' || typeflag === '\0') {
436
+ logicalBytes += payload.byteLength;
437
+ if (logicalBytes > maximumBytes) {
438
+ throw new RunnerError('Exported workspace exceeds maximum byte count');
439
+ }
440
+ await plugins.fs.writeFile(targetPath, payload, { mode: mode || 0o644 });
441
+ } else {
442
+ throw new RunnerError(`Exported workspace contains unsupported tar entry type ${typeflag}`);
443
+ }
444
+ }
445
+
446
+ return { logicalBytes, entryCount };
447
+ };
448
+
449
+ /**
450
+ * Executes compiled `oci` jobs inside fresh, single-attempt Firecracker microVMs managed via
451
+ * `@push.rocks/smartvm`.
452
+ *
453
+ * Each attempt boots a pinned Linux kernel + static `runnerworkspace` PID 1 initramfs with the
454
+ * job's digest-pinned Docker/OCI image attached as a read-only ext2 rootfs (`/dev/vda`). Steps run
455
+ * inside fresh Linux namespaces pivoted into that read-only OCI rootfs as a numeric non-root user
456
+ * with all capabilities dropped, `NO_NEW_PRIVS`, loopback-only networking, and bounded `/workspace`.
457
+ */
458
+ export class MicroVmExecutor implements IJobExecutor {
459
+ private readonly connectSmartVm: NonNullable<IMicroVmExecutorDependencies['connectSmartVm']>;
460
+ private readonly resolveHelperPath: NonNullable<IMicroVmExecutorDependencies['resolveHelperPath']>;
461
+ private readonly buildInitrdImpl: NonNullable<IMicroVmExecutorDependencies['buildInitrd']>;
462
+ private readonly now: () => number;
463
+ private readonly user: { uid: number; gid: number };
464
+ private smartvmPromise?: Promise<ISmartVmClient>;
465
+ private runtimeFacts?: IOciRuntimeFacts;
466
+ private registryClient?: OciRegistryClient;
467
+
468
+ constructor(
469
+ private readonly config: IRunnerConfig,
470
+ private readonly stateOwner: RunnerStateOwner,
471
+ private readonly dependencies: IMicroVmExecutorDependencies = {},
472
+ ) {
473
+ this.connectSmartVm = dependencies.connectSmartVm ??
474
+ ((options) => plugins.smartvm.SmartVM.connect(options) as Promise<ISmartVmClient>);
475
+ this.resolveHelperPath = dependencies.resolveHelperPath ?? resolvePackagedWorkspaceHelperPath;
476
+ this.buildInitrdImpl = dependencies.buildInitrd ?? defaultBuildInitrd;
477
+ this.now = dependencies.now ?? Date.now;
478
+ this.user = parseContainerUser(config.oci.containerUser);
479
+ }
480
+
481
+ private async getSmartVm(): Promise<ISmartVmClient> {
482
+ if (!this.smartvmPromise) {
483
+ const runtimeDir = this.config.oci.smartvmRuntimeDir ??
484
+ (process.env.XDG_RUNTIME_DIR
485
+ ? undefined
486
+ : join(resolve(this.config.stateDirectory), 'smartvm-runtime'));
487
+ if (runtimeDir) {
488
+ await plugins.fs.mkdir(runtimeDir, { recursive: true, mode: 0o700 });
489
+ }
490
+ const options: plugins.smartvm.ISmartVMConnectOptions = {
491
+ ...(this.config.oci.smartvmSocketPath ? { helperSocketPath: this.config.oci.smartvmSocketPath } : {}),
492
+ ...(runtimeDir ? { runtimeDir } : {}),
493
+ ...(this.config.oci.smartvmBridgePath ? { bridgeBinaryPath: this.config.oci.smartvmBridgePath } : {}),
494
+ requestTimeoutMs: this.config.requestTimeoutMs,
495
+ };
496
+ this.smartvmPromise = this.connectSmartVm(options).catch((error) => {
497
+ this.smartvmPromise = undefined;
498
+ throw error;
499
+ });
500
+ }
501
+ return await this.smartvmPromise;
502
+ }
503
+
504
+ async close(): Promise<void> {
505
+ if (!this.smartvmPromise) return;
506
+ const client = await this.smartvmPromise.catch(() => undefined);
507
+ this.smartvmPromise = undefined;
508
+ if (client) await client.close();
509
+ }
510
+
511
+ private async materializeHelperAndInitrd(target: TOciHelperTarget): Promise<{
512
+ helperPath: string;
513
+ helperSha256: string;
514
+ initrdPath: string;
515
+ }> {
516
+ return await this.stateOwner.serialize(async () => {
517
+ const stateRoot = await ensurePrivateStateDirectory(this.config.stateDirectory);
518
+ const helperDir = join(stateRoot, workspaceHelperDirectoryName);
519
+ await plugins.fs.mkdir(helperDir, { recursive: true, mode: 0o700 });
520
+
521
+ const sourcePath = this.config.oci.workspaceHelperPath ??
522
+ await this.resolveHelperPath(target);
523
+ const { bytes: sourceBytes } = await readBoundedRegularFile(
524
+ sourcePath,
525
+ workspaceHelperMaximumBytes,
526
+ 'Workspace helper',
527
+ );
528
+ if (sourceBytes.byteLength === 0) {
529
+ throw new RunnerError('Workspace helper binary is empty');
530
+ }
531
+ const helperSha256 = sha256Hex(sourceBytes);
532
+ const helperPath = join(helperDir, `runnerworkspace_${target}_musl_${helperSha256}`);
533
+ const existingHelper = await lstatIfPresent(helperPath);
534
+ if (!existingHelper) {
535
+ const tempHelper = join(helperDir, `.${plugins.crypto.randomUUID()}.helper.tmp`);
536
+ try {
537
+ await withOpenFile(
538
+ tempHelper,
539
+ createNewWriteFlags,
540
+ 0o755,
541
+ async (file) => {
542
+ await writeAll(file, sourceBytes, 'Workspace helper write failed');
543
+ await file.sync();
544
+ },
545
+ 'Workspace helper write and close failed',
546
+ );
547
+ await plugins.fs.chmod(tempHelper, 0o755);
548
+ await plugins.fs.rename(tempHelper, helperPath);
549
+ } catch (error) {
550
+ await removePath(tempHelper).catch(() => {});
551
+ throw error;
552
+ }
553
+ }
554
+
555
+ const initrdPath = join(helperDir, `initrd_${target}_${helperSha256}.cpio`);
556
+ const existingInitrd = await lstatIfPresent(initrdPath);
557
+ if (!existingInitrd || !existingInitrd.isFile() || existingInitrd.size === 0) {
558
+ const tempInitrd = join(helperDir, `.${plugins.crypto.randomUUID()}.initrd.tmp`);
559
+ try {
560
+ await this.buildInitrdImpl(helperPath, tempInitrd);
561
+ await plugins.fs.rename(tempInitrd, initrdPath);
562
+ } catch (error) {
563
+ await removePath(tempInitrd).catch(() => {});
564
+ throw error;
565
+ }
566
+ }
567
+ await syncDirectory(helperDir, 'Workspace helper directory sync failed');
568
+ return { helperPath, helperSha256, initrdPath };
569
+ });
570
+ }
571
+
572
+ private async verifyKernelFile(kernelPath: string): Promise<void> {
573
+ const stat = await lstatIfPresent(kernelPath);
574
+ if (!stat || !stat.isFile() || stat.size === 0) {
575
+ throw new RunnerError(`Firecracker kernel file is missing or invalid: ${kernelPath}`);
576
+ }
577
+ }
578
+
579
+ private getRegistryClient(helperPath: string): OciRegistryClient {
580
+ if (!this.registryClient) {
581
+ this.registryClient = new OciRegistryClient({
582
+ cacheDirectory: join(resolve(this.config.stateDirectory), ociCacheDirectoryName),
583
+ helperPath,
584
+ allowInsecureLoopback: this.config.allowInsecureLoopback,
585
+ requestTimeoutMs: this.config.requestTimeoutMs,
586
+ maximumRootfsBytes: this.config.oci.maximumRootfsBytes,
587
+ fetchImplementation: this.dependencies.fetchImplementation,
588
+ });
589
+ }
590
+ return this.registryClient;
591
+ }
592
+
593
+ async verifyRuntime(): Promise<IOciRuntimeFacts> {
594
+ if (this.runtimeFacts) return this.runtimeFacts;
595
+ this.stateOwner.assertHeld();
596
+ await this.verifyKernelFile(this.config.oci.kernelPath);
597
+ const smartvm = await this.getSmartVm();
598
+ const report = await smartvm.checkHost();
599
+ if (!report.ok) {
600
+ const failures = report.items
601
+ .filter((item) => item.status === 'fail')
602
+ .map((item) => `${item.id}: ${item.detail}`)
603
+ .join('; ');
604
+ throw new RunnerError(`Firecracker host check failed: ${failures || 'host check not ok'}`);
605
+ }
606
+ if (smartvm.info.shapes.length === 0) {
607
+ throw new RunnerError('Firecracker smartvm-helper exposes no VM shapes');
608
+ }
609
+ const { architecture, helperTarget } = archFromSmartVm(smartvm.info.arch);
610
+ const { helperPath, helperSha256, initrdPath } = await this.materializeHelperAndInitrd(
611
+ helperTarget,
612
+ );
613
+ this.runtimeFacts = {
614
+ engine: 'firecracker',
615
+ firecrackerVersion: smartvm.info.firecrackerVersion,
616
+ endpoint: this.config.oci.smartvmSocketPath ?? defaultSmartVmSocketPath,
617
+ os: 'linux',
618
+ architecture,
619
+ helperTarget,
620
+ helperPath,
621
+ helperSha256,
622
+ initrdPath,
623
+ kernelPath: this.config.oci.kernelPath,
624
+ shapes: smartvm.info.shapes,
625
+ };
626
+ return this.runtimeFacts;
627
+ }
628
+
629
+ async prepareLease(context: IPrepareOciLeaseContext): Promise<IPreparedOciLease> {
630
+ const runtime = await this.verifyRuntime();
631
+ if (context.signal.aborted) throw context.signal.reason;
632
+
633
+ const job = context.lease.job;
634
+ const jobResources = job.resources;
635
+ const memoryBytes = jobResources?.memoryBytes ?? this.config.oci.defaultMemoryBytes;
636
+ const cpus = jobResources?.cpus ?? this.config.oci.defaultCpus;
637
+ const shape = selectShapeForJob(
638
+ runtime.shapes,
639
+ memoryBytes,
640
+ cpus,
641
+ this.config.oci.guestMemoryOverheadBytes,
642
+ );
643
+
644
+ // Validate egress allowlist rules fail-closed before accepting the lease.
645
+ if (job.network.mode === 'egress') {
646
+ new EgressAllowlistController({
647
+ allow: job.network.allow,
648
+ grantOrigins: grantOriginsFromLease(context.lease.grants),
649
+ blockedCidrs: this.config.oci.egressBlockedCidrs,
650
+ });
651
+ }
652
+
653
+ const smartvm = await this.getSmartVm();
654
+
655
+ if ('build' in job) {
656
+ const builderRootfsPath = this.config.oci.builderRootfsPath;
657
+ if (!builderRootfsPath) {
658
+ throw new RunnerError(
659
+ 'oci.builderRootfsPath must be configured to execute oci-image builds',
660
+ );
661
+ }
662
+ const stat = await lstatIfPresent(builderRootfsPath);
663
+ if (!stat || !stat.isFile() || stat.size === 0) {
664
+ throw new RunnerError(
665
+ `Firecracker builder rootfs is missing or invalid: ${builderRootfsPath}`,
666
+ );
667
+ }
668
+ // Verify every base image reference resolves to an exact digest-pinned image.
669
+ for (const base of job.build.baseImages) {
670
+ const resolved = resolveImageReference(base.image, context.lease.bindings);
671
+ parseDigestPinnedImageReference(resolved);
672
+ }
673
+ const { imageDigest } = await smartvm.computeImageDigest({
674
+ kernelPath: runtime.kernelPath,
675
+ rootfsPath: builderRootfsPath,
676
+ initrdPath: runtime.initrdPath,
677
+ bootArgs: this.config.oci.bootArgs,
678
+ });
679
+ return {
680
+ preparationId: plugins.crypto.randomUUID(),
681
+ attemptId: context.lease.attemptId,
682
+ image: builderRootfsPath,
683
+ imageArchitecture: runtime.architecture,
684
+ rootfsPath: builderRootfsPath,
685
+ imageDigest,
686
+ shapeId: shape.id,
687
+ cleanup: async () => {},
688
+ };
689
+ }
690
+
691
+ const image = resolveImageReference(job.execution.image, context.lease.bindings);
692
+ parseDigestPinnedImageReference(image);
693
+
694
+ const materialized = this.dependencies.materializeImage
695
+ ? await this.dependencies.materializeImage(image, runtime.architecture, context.signal)
696
+ : await this.getRegistryClient(runtime.helperPath).materializeImage(
697
+ image,
698
+ runtime.architecture,
699
+ context.signal,
700
+ context.lease.grants,
701
+ );
702
+
703
+ if (materialized.os !== 'linux' || materialized.architecture !== runtime.architecture) {
704
+ await materialized.cleanup().catch(() => {});
705
+ throw new ProtocolError(
706
+ `Materialized image platform ${materialized.os}/${materialized.architecture} does not match linux/${runtime.architecture}`,
707
+ );
708
+ }
709
+
710
+ const { imageDigest } = await smartvm.computeImageDigest({
711
+ kernelPath: runtime.kernelPath,
712
+ rootfsPath: materialized.rootfsPath,
713
+ initrdPath: runtime.initrdPath,
714
+ bootArgs: this.config.oci.bootArgs,
715
+ });
716
+
717
+ return {
718
+ preparationId: plugins.crypto.randomUUID(),
719
+ attemptId: context.lease.attemptId,
720
+ image,
721
+ imageArchitecture: materialized.architecture,
722
+ rootfsPath: materialized.rootfsPath,
723
+ imageDigest,
724
+ shapeId: shape.id,
725
+ defaultEnv: materialized.defaultEnv,
726
+ defaultWorkingDir: materialized.defaultWorkingDir,
727
+ cleanup: () => materialized.cleanup(),
728
+ };
729
+ }
730
+
731
+ private activeVmsPath(): string {
732
+ return join(resolve(this.config.stateDirectory), activeVmsFileName);
733
+ }
734
+
735
+ private async readActiveVms(): Promise<string[]> {
736
+ const path = this.activeVmsPath();
737
+ try {
738
+ const { bytes } = await readBoundedRegularFile(path, 64 * 1024, 'Active VM journal');
739
+ const parsed = JSON.parse(new TextDecoder().decode(bytes)) as unknown;
740
+ if (!Array.isArray(parsed)) return [];
741
+ return parsed.filter((entry): entry is string => typeof entry === 'string' && entry.length > 0);
742
+ } catch (error) {
743
+ if (isNotFound(error)) return [];
744
+ throw error;
745
+ }
746
+ }
747
+
748
+ private async writeActiveVms(vmIds: readonly string[]): Promise<void> {
749
+ await this.stateOwner.serialize(async () => {
750
+ const stateRoot = await ensurePrivateStateDirectory(this.config.stateDirectory);
751
+ const path = join(stateRoot, activeVmsFileName);
752
+ if (vmIds.length === 0) {
753
+ try {
754
+ await removePath(path);
755
+ } catch (error) {
756
+ if (!isNotFound(error)) throw error;
757
+ }
758
+ return;
759
+ }
760
+ const temp = join(stateRoot, `.${plugins.crypto.randomUUID()}.active-vms.tmp`);
761
+ const bytes = new TextEncoder().encode(`${JSON.stringify([...new Set(vmIds)])}\n`);
762
+ try {
763
+ await withOpenFile(
764
+ temp,
765
+ createNewWriteFlags,
766
+ 0o600,
767
+ async (file) => {
768
+ await writeAll(file, bytes, 'Active VM journal write failed');
769
+ await file.sync();
770
+ },
771
+ 'Active VM journal write and close failed',
772
+ );
773
+ await plugins.fs.rename(temp, path);
774
+ await syncDirectory(stateRoot, 'State directory sync failed');
775
+ } catch (error) {
776
+ await removePath(temp).catch(() => {});
777
+ throw error;
778
+ }
779
+ });
780
+ }
781
+
782
+ private async trackVm(vmId: string): Promise<void> {
783
+ const existing = await this.readActiveVms();
784
+ if (!existing.includes(vmId)) {
785
+ await this.writeActiveVms([...existing, vmId]);
786
+ }
787
+ }
788
+
789
+ private async untrackVm(vmId: string): Promise<void> {
790
+ const existing = await this.readActiveVms();
791
+ await this.writeActiveVms(existing.filter((entry) => entry !== vmId));
792
+ }
793
+
794
+ async reconcileOrphans(_runnerId: string, _currentSessionId: string): Promise<void> {
795
+ this.stateOwner.assertHeld();
796
+ const tracked = await this.readActiveVms();
797
+ if (tracked.length === 0) return;
798
+ const smartvm = await this.getSmartVm();
799
+ const remaining: string[] = [];
800
+ const errors: unknown[] = [];
801
+ for (const vmId of tracked) {
802
+ try {
803
+ const vm = await smartvm.getVM(vmId);
804
+ if (vm) await vm.destroy();
805
+ } catch (error) {
806
+ remaining.push(vmId);
807
+ errors.push(error);
808
+ }
809
+ }
810
+ await this.writeActiveVms(remaining);
811
+ if (errors.length > 0) {
812
+ throw new ResourceCleanupError('Failed to destroy orphaned Firecracker microVM(s)', errors);
813
+ }
814
+ }
815
+
816
+ private async connectGuestVsock(
817
+ vm: IMicroVmHandle,
818
+ signal: AbortSignal,
819
+ ): Promise<GuestVsockClient> {
820
+ const deadline = this.now() + vsockConnectTimeoutMs;
821
+ let lastError: unknown;
822
+ while (this.now() < deadline) {
823
+ if (signal.aborted) throw signal.reason;
824
+ try {
825
+ const socket = await vm.connectVsock(GUEST_VSOCK_PORT);
826
+ const client = new GuestVsockClient(socket);
827
+ try {
828
+ await client.hello();
829
+ return client;
830
+ } catch (error) {
831
+ client.close();
832
+ lastError = error;
833
+ }
834
+ } catch (error) {
835
+ lastError = error;
836
+ }
837
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, vsockConnectRetryIntervalMs));
838
+ }
839
+ throw new RunnerError(
840
+ `Timed out waiting for Firecracker guest agent on vsock port ${GUEST_VSOCK_PORT}`,
841
+ { cause: lastError },
842
+ );
843
+ }
844
+
845
+ async execute(context: IExecutionContext): Promise<IExecutionResult> {
846
+ const runtime = await this.verifyRuntime();
847
+ if (context.signal.aborted) {
848
+ return { exitCode: null, stopReason: stopReasonForAbort(context.signal.reason) };
849
+ }
850
+ if (!context.preparedLease.rootfsPath || !context.preparedLease.shapeId) {
851
+ throw new RunnerError('Prepared lease is missing Firecracker rootfsPath or shapeId');
852
+ }
853
+
854
+ const job = context.lease.job;
855
+ const memoryBytes = job.resources?.memoryBytes ?? this.config.oci.defaultMemoryBytes;
856
+ const cpus = job.resources?.cpus ?? this.config.oci.defaultCpus;
857
+ const pids = job.resources?.pids ?? this.config.oci.defaultPids;
858
+ const sharedMemoryBytes =
859
+ job.resources?.sharedMemoryBytes ?? this.config.oci.defaultSharedMemoryBytes;
860
+ const workspaceBytes = Math.min(
861
+ this.config.oci.workspaceSizeBytes,
862
+ job.requirements.limits.maximumWorkspaceBytes,
863
+ );
864
+ const workspaceEntries = Math.min(
865
+ this.config.maximumWorkspaceEntries,
866
+ job.requirements.limits.maximumWorkspaceEntries,
867
+ );
868
+
869
+ const smartvm = await this.getSmartVm();
870
+ const vm = await smartvm.createVMFromImage(
871
+ {
872
+ kernelPath: runtime.kernelPath,
873
+ rootfsPath: context.preparedLease.rootfsPath,
874
+ initrdPath: runtime.initrdPath,
875
+ bootArgs: this.config.oci.bootArgs,
876
+ },
877
+ { shapeId: context.preparedLease.shapeId },
878
+ );
879
+ await this.trackVm(vm.vmId);
880
+
881
+ let guest: GuestVsockClient | undefined;
882
+ let cleaned = false;
883
+ const exportDirs: string[] = [];
884
+
885
+ const destroyVm = async (): Promise<void> => {
886
+ if (cleaned) return;
887
+ cleaned = true;
888
+ const errors: unknown[] = [];
889
+ if (guest) {
890
+ try {
891
+ await Promise.race([
892
+ guest.shutdown(),
893
+ new Promise<void>((resolvePromise) => setTimeout(resolvePromise, 500)),
894
+ ]);
895
+ } catch {
896
+ // Best-effort graceful shutdown before destroy.
897
+ }
898
+ guest.close();
899
+ guest = undefined;
900
+ }
901
+ try {
902
+ await vm.destroy();
903
+ } catch (error) {
904
+ errors.push(error);
905
+ }
906
+ try {
907
+ await this.untrackVm(vm.vmId);
908
+ } catch (error) {
909
+ errors.push(error);
910
+ }
911
+ for (const dir of exportDirs) {
912
+ try {
913
+ await removePath(dir, { recursive: true });
914
+ } catch (error) {
915
+ if (!isNotFound(error)) errors.push(error);
916
+ }
917
+ }
918
+ if (errors.length > 0) {
919
+ throw new ResourceCleanupError('Firecracker microVM cleanup failed', errors);
920
+ }
921
+ };
922
+
923
+ try {
924
+ await vm.start();
925
+ guest = await this.connectGuestVsock(vm, context.signal);
926
+
927
+ const npmrcContent = context.lease.npmGrants && context.lease.npmGrants.length > 0
928
+ ? buildNpmrcContent(context.lease.npmGrants)
929
+ : undefined;
930
+ const profile = job.requirements.executionProfile;
931
+
932
+ await guest.prepareWorkspace({
933
+ workspaceSizeBytes: workspaceBytes,
934
+ maximumWorkspaceEntries: workspaceEntries,
935
+ uid: profile === 'vm' ? 0 : this.user.uid,
936
+ gid: profile === 'vm' ? 0 : this.user.gid,
937
+ mode: profile,
938
+ ...(npmrcContent ? { npmrcContent } : {}),
939
+ });
940
+
941
+ const packed = await packDirectoryToTar(
942
+ context.workspacePath,
943
+ workspaceBytes,
944
+ workspaceEntries,
945
+ );
946
+ if (packed.entryCount > 0) {
947
+ await guest.importTar(packed.tarBytes, {
948
+ maximumBytes: workspaceBytes,
949
+ maximumEntries: workspaceEntries,
950
+ uid: profile === 'vm' ? 0 : this.user.uid,
951
+ gid: profile === 'vm' ? 0 : this.user.gid,
952
+ });
953
+ }
954
+
955
+ const attemptDeadline = this.now() + context.timeoutMs;
956
+ let lastExitCode: number | null = 0;
957
+ let stopReason: TExecutionStopReason | undefined;
958
+ let producedImage: IExecutionResult['producedImage'];
959
+
960
+ if ('build' in job) {
961
+ const pushGrant = context.lease.grants.find((g) => g.access === 'push');
962
+ if (!pushGrant) {
963
+ throw new ProtocolError('oci-image lease is missing its push grant');
964
+ }
965
+ const buildSecrets: Record<string, string> = {};
966
+ for (const secretRef of job.build.secrets) {
967
+ const val = job.secrets[secretRef.environment];
968
+ if (val === undefined) {
969
+ throw new ProtocolError(`Build secret ${secretRef.id} references unknown secret`);
970
+ }
971
+ buildSecrets[secretRef.id] = val;
972
+ }
973
+ const resolvedBaseImages = job.build.baseImages.map((base) => ({
974
+ name: base.name,
975
+ image: resolveImageReference(base.image, context.lease.bindings),
976
+ }));
977
+ const buildTimeoutMs = Math.max(1, attemptDeadline - this.now());
978
+ const buildAbort = new AbortController();
979
+ const onContextAbort = (): void => buildAbort.abort(context.signal.reason);
980
+ context.signal.addEventListener('abort', onContextAbort, { once: true });
981
+ const stdoutDecoder = new TextDecoder('utf-8');
982
+ const stderrDecoder = new TextDecoder('utf-8');
983
+ let logFailure: unknown;
984
+
985
+ const buildRes = await guest
986
+ .runImageBuild(
987
+ {
988
+ context: job.build.context,
989
+ dockerfile: job.build.dockerfile,
990
+ ...(job.build.target ? { target: job.build.target } : {}),
991
+ platform: job.requirements.platform,
992
+ buildArgs: job.build.buildArgs,
993
+ secrets: buildSecrets,
994
+ labels: job.build.labels,
995
+ baseImages: resolvedBaseImages,
996
+ ...(npmrcContent ? { npmrcContent } : {}),
997
+ pushRegistry: pushGrant.registry,
998
+ pushRepository: pushGrant.repository,
999
+ grants: context.lease.grants.map((g) => ({
1000
+ registry: g.registry,
1001
+ username: g.username,
1002
+ secret: g.secret,
1003
+ })),
1004
+ timeoutMs: Math.min(buildTimeoutMs, this.config.oci.maximumTimeoutMs),
1005
+ ...(this.config.oci.buildctlPath ? { buildctlPath: this.config.oci.buildctlPath } : {}),
1006
+ },
1007
+ {
1008
+ signal: buildAbort.signal,
1009
+ onStdout: async (chunk) => {
1010
+ const text = stdoutDecoder.decode(chunk, { stream: true });
1011
+ if (text.length > 0) {
1012
+ try {
1013
+ await context.onLog('stdout', text);
1014
+ } catch (error) {
1015
+ logFailure = error;
1016
+ buildAbort.abort('log_delivery_failed');
1017
+ }
1018
+ }
1019
+ },
1020
+ onStderr: async (chunk) => {
1021
+ const text = stderrDecoder.decode(chunk, { stream: true });
1022
+ if (text.length > 0) {
1023
+ try {
1024
+ await context.onLog('stderr', text);
1025
+ } catch (error) {
1026
+ logFailure = error;
1027
+ buildAbort.abort('log_delivery_failed');
1028
+ }
1029
+ }
1030
+ },
1031
+ },
1032
+ )
1033
+ .finally(() => {
1034
+ context.signal.removeEventListener('abort', onContextAbort);
1035
+ });
1036
+
1037
+ const tailOut = stdoutDecoder.decode();
1038
+ if (tailOut.length > 0 && !logFailure) {
1039
+ try {
1040
+ await context.onLog('stdout', tailOut);
1041
+ } catch (error) {
1042
+ logFailure = error;
1043
+ }
1044
+ }
1045
+ const tailErr = stderrDecoder.decode();
1046
+ if (tailErr.length > 0 && !logFailure) {
1047
+ try {
1048
+ await context.onLog('stderr', tailErr);
1049
+ } catch (error) {
1050
+ logFailure = error;
1051
+ }
1052
+ }
1053
+
1054
+ if (logFailure) {
1055
+ stopReason = 'log_delivery_failed';
1056
+ lastExitCode = null;
1057
+ } else if (buildRes.timedOut) {
1058
+ stopReason = 'job_timeout';
1059
+ lastExitCode = null;
1060
+ } else if (buildRes.canceled || context.signal.aborted) {
1061
+ stopReason = stopReasonForAbort(context.signal.reason);
1062
+ lastExitCode = null;
1063
+ } else if (buildRes.exitCode === 0) {
1064
+ if (
1065
+ !buildRes.manifestDigest ||
1066
+ buildRes.mediaType !== 'application/vnd.oci.image.manifest.v1+json' ||
1067
+ typeof buildRes.sizeBytes !== 'number' ||
1068
+ buildRes.sizeBytes < 1
1069
+ ) {
1070
+ throw new RunnerError('BuildKit succeeded without a valid OCI single-manifest record');
1071
+ }
1072
+ producedImage = {
1073
+ manifestDigest: buildRes.manifestDigest,
1074
+ mediaType: 'application/vnd.oci.image.manifest.v1+json',
1075
+ sizeBytes: buildRes.sizeBytes,
1076
+ platform: job.requirements.platform,
1077
+ };
1078
+ lastExitCode = 0;
1079
+ } else {
1080
+ lastExitCode = buildRes.exitCode ?? 1;
1081
+ }
1082
+ } else {
1083
+ for (const step of job.steps) {
1084
+ if (context.signal.aborted) {
1085
+ stopReason = stopReasonForAbort(context.signal.reason);
1086
+ lastExitCode = null;
1087
+ break;
1088
+ }
1089
+ const remainingMs = attemptDeadline - this.now();
1090
+ if (remainingMs <= 0) {
1091
+ stopReason = 'job_timeout';
1092
+ lastExitCode = null;
1093
+ break;
1094
+ }
1095
+
1096
+ validateStepCommand(step.command);
1097
+ const env = buildStepEnvironment(
1098
+ this.config,
1099
+ step,
1100
+ job.secrets,
1101
+ context.preparedLease.defaultEnv,
1102
+ );
1103
+ if (npmrcContent) {
1104
+ env.NPM_CONFIG_USERCONFIG = GUEST_NPMRC_PATH;
1105
+ }
1106
+ const workingDirectory = job.execution.workingDirectory ?? '/workspace';
1107
+ const stepTimeoutMs = Math.min(remainingMs, this.config.oci.maximumTimeoutMs);
1108
+
1109
+ const stepAbort = new AbortController();
1110
+ const onContextAbort = (): void => stepAbort.abort(context.signal.reason);
1111
+ context.signal.addEventListener('abort', onContextAbort, { once: true });
1112
+ const stdoutDecoder = new TextDecoder('utf-8');
1113
+ const stderrDecoder = new TextDecoder('utf-8');
1114
+ let logFailure: unknown;
1115
+
1116
+ const stepResult = await guest
1117
+ .runStep(
1118
+ {
1119
+ command: [...step.command],
1120
+ env,
1121
+ workingDirectory,
1122
+ uid: profile === 'vm' ? 0 : this.user.uid,
1123
+ gid: profile === 'vm' ? 0 : this.user.gid,
1124
+ rootMode: profile === 'vm',
1125
+ timeoutMs: stepTimeoutMs,
1126
+ memoryBytes,
1127
+ cpus,
1128
+ pids,
1129
+ sharedMemoryBytes,
1130
+ temporarySizeBytes: this.config.oci.temporarySizeBytes,
1131
+ maximumWorkspaceBytes: workspaceBytes,
1132
+ maximumWorkspaceEntries: workspaceEntries,
1133
+ },
1134
+ {
1135
+ signal: stepAbort.signal,
1136
+ onStdout: async (chunk) => {
1137
+ const text = stdoutDecoder.decode(chunk, { stream: true });
1138
+ if (text.length > 0) {
1139
+ try {
1140
+ await context.onLog('stdout', text);
1141
+ } catch (error) {
1142
+ logFailure = error;
1143
+ stepAbort.abort('log_delivery_failed');
1144
+ }
1145
+ }
1146
+ },
1147
+ onStderr: async (chunk) => {
1148
+ const text = stderrDecoder.decode(chunk, { stream: true });
1149
+ if (text.length > 0) {
1150
+ try {
1151
+ await context.onLog('stderr', text);
1152
+ } catch (error) {
1153
+ logFailure = error;
1154
+ stepAbort.abort('log_delivery_failed');
1155
+ }
1156
+ }
1157
+ },
1158
+ },
1159
+ )
1160
+ .finally(() => {
1161
+ context.signal.removeEventListener('abort', onContextAbort);
1162
+ });
1163
+
1164
+ const tailOut = stdoutDecoder.decode();
1165
+ if (tailOut.length > 0 && !logFailure) {
1166
+ try {
1167
+ await context.onLog('stdout', tailOut);
1168
+ } catch (error) {
1169
+ logFailure = error;
1170
+ }
1171
+ }
1172
+ const tailErr = stderrDecoder.decode();
1173
+ if (tailErr.length > 0 && !logFailure) {
1174
+ try {
1175
+ await context.onLog('stderr', tailErr);
1176
+ } catch (error) {
1177
+ logFailure = error;
1178
+ }
1179
+ }
1180
+
1181
+ if (logFailure) {
1182
+ stopReason = 'log_delivery_failed';
1183
+ lastExitCode = null;
1184
+ break;
1185
+ }
1186
+ if (stepResult.oomKilled) {
1187
+ stopReason = 'resource_limit';
1188
+ lastExitCode = null;
1189
+ break;
1190
+ }
1191
+ if (stepResult.timedOut) {
1192
+ stopReason = 'job_timeout';
1193
+ lastExitCode = null;
1194
+ break;
1195
+ }
1196
+ if (stepResult.canceled || context.signal.aborted) {
1197
+ stopReason = stopReasonForAbort(context.signal.reason);
1198
+ lastExitCode = null;
1199
+ break;
1200
+ }
1201
+ lastExitCode = stepResult.exitCode;
1202
+ if (lastExitCode !== 0) break;
1203
+ }
1204
+ }
1205
+
1206
+ const exportsRoot = join(resolve(this.config.stateDirectory), workspaceExportsDirectoryName);
1207
+ const activeGuest = guest;
1208
+ const exporter: IRuntimeWorkspaceExporter = {
1209
+ exportSelected: async (request: IWorkspaceExportRequest): Promise<IWorkspaceExport> => {
1210
+ if (cleaned || !activeGuest) {
1211
+ throw new RunnerError('Cannot export workspace after Firecracker microVM cleanup');
1212
+ }
1213
+ if (request.signal?.aborted) throw request.signal.reason;
1214
+ await plugins.fs.mkdir(exportsRoot, { recursive: true, mode: 0o700 });
1215
+ const destDir = await makeTempDir({ dir: exportsRoot, prefix: 'export-' });
1216
+ await plugins.fs.chmod(destDir, 0o700);
1217
+ exportDirs.push(destDir);
1218
+ const { tarBytes } = await activeGuest.exportTar({
1219
+ selections: request.selections,
1220
+ maximumBytes: request.maximumBytes,
1221
+ maximumEntries: request.maximumEntries,
1222
+ });
1223
+ const metadata = await unpackTarToDirectory(
1224
+ tarBytes,
1225
+ destDir,
1226
+ request.maximumBytes,
1227
+ request.maximumEntries,
1228
+ );
1229
+ let exportCleaned = false;
1230
+ return {
1231
+ path: destDir,
1232
+ metadata,
1233
+ cleanup: async () => {
1234
+ if (exportCleaned) return;
1235
+ exportCleaned = true;
1236
+ await removePath(destDir, { recursive: true }).catch((error) => {
1237
+ if (!isNotFound(error)) throw error;
1238
+ });
1239
+ },
1240
+ };
1241
+ },
1242
+ cleanup: destroyVm,
1243
+ };
1244
+
1245
+ return {
1246
+ exitCode: profile === 'oci-image' ? null : lastExitCode,
1247
+ ...(stopReason ? { stopReason } : {}),
1248
+ ...(producedImage ? { producedImage } : {}),
1249
+ workspace: exporter,
1250
+ };
1251
+ } catch (error) {
1252
+ try {
1253
+ await destroyVm();
1254
+ } catch (cleanupError) {
1255
+ throw new ResourceCleanupError('Execution and Firecracker cleanup failed', [
1256
+ error,
1257
+ cleanupError,
1258
+ ]);
1259
+ }
1260
+ throw error;
1261
+ }
1262
+ }
1263
+ }
1264
+
1265
+ export type { IOciExecutorConfig };