overvues 0.0.1 → 0.4.10

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 (78) hide show
  1. package/README.md +58 -2
  2. package/dist/ansi.js +24 -0
  3. package/dist/attach-client.js +586 -0
  4. package/dist/auth-connect-browser.js +112 -0
  5. package/dist/auth-connect.js +306 -0
  6. package/dist/browser-bootstrap.js +190 -0
  7. package/dist/browser-loopback.js +289 -0
  8. package/dist/build-identity.js +6 -0
  9. package/dist/codex-reviewer-apparmor.json +4 -0
  10. package/dist/codex-reviewer-seccomp.json +1238 -0
  11. package/dist/codex-runtime-protocol.js +1 -0
  12. package/dist/codex-subscription.js +53 -0
  13. package/dist/config.js +297 -0
  14. package/dist/connect-comparison-code.js +26 -0
  15. package/dist/development-runner.js +109 -0
  16. package/dist/dns-doctor.js +390 -0
  17. package/dist/docker-names.js +47 -0
  18. package/dist/doctor.js +114 -0
  19. package/dist/gadget-job.js +804 -0
  20. package/dist/health-check.js +112 -0
  21. package/dist/help.js +71 -0
  22. package/dist/host-auth.js +22 -0
  23. package/dist/host-diagnostics.js +20 -0
  24. package/dist/host-runtime-identity.js +39 -0
  25. package/dist/host-runtime-metadata.js +56 -0
  26. package/dist/host-service.js +377 -0
  27. package/dist/host-stack.js +484 -0
  28. package/dist/host-supervisor.js +237 -0
  29. package/dist/host-update.js +387 -0
  30. package/dist/hub-address.js +100 -0
  31. package/dist/hub-client.js +459 -0
  32. package/dist/hub-kind.js +88 -0
  33. package/dist/identity.js +73 -0
  34. package/dist/index.js +185 -0
  35. package/dist/init.js +295 -0
  36. package/dist/isolated-run-cache.js +116 -0
  37. package/dist/local-stack.js +685 -0
  38. package/dist/machine-capacity.js +128 -0
  39. package/dist/managed-runner-image.js +13 -0
  40. package/dist/os-acted-record.js +49 -0
  41. package/dist/os-adapter.js +8190 -0
  42. package/dist/os-command.js +292 -0
  43. package/dist/os-handoff.js +274 -0
  44. package/dist/os-keychain.js +247 -0
  45. package/dist/os-machine.js +818 -0
  46. package/dist/os-owner.js +61 -0
  47. package/dist/os-private-file.js +98 -0
  48. package/dist/os-protocol.js +468 -0
  49. package/dist/os-session-store.js +133 -0
  50. package/dist/os-status.js +102 -0
  51. package/dist/picker.js +863 -0
  52. package/dist/portable-workspace-capability.js +60 -0
  53. package/dist/project-environment-capability.js +62 -0
  54. package/dist/project-environment.js +28 -0
  55. package/dist/project-preparation.js +134 -0
  56. package/dist/readiness.js +28 -0
  57. package/dist/redaction.js +27 -0
  58. package/dist/reviewer-isolation-capability.js +61 -0
  59. package/dist/runner-api-auth.js +80 -0
  60. package/dist/runner-command-fence.js +536 -0
  61. package/dist/runner-inspection.js +57 -0
  62. package/dist/runner-inventory.js +587 -0
  63. package/dist/runner-server.js +2520 -0
  64. package/dist/runner-session.js +470 -0
  65. package/dist/runner-slug-folder.js +39 -0
  66. package/dist/runner-slug.js +40 -0
  67. package/dist/setup.js +139 -0
  68. package/dist/shutdown.js +102 -0
  69. package/dist/splash.js +65 -0
  70. package/dist/staged-workspaces.js +441 -0
  71. package/dist/staging-disk.js +97 -0
  72. package/dist/terminal-lane.js +339 -0
  73. package/dist/terminal-recovery.js +502 -0
  74. package/licenses/capnweb.txt +23 -0
  75. package/licenses/moby-profiles.txt +212 -0
  76. package/licenses/ws.txt +22 -0
  77. package/package.json +28 -7
  78. package/cli.js +0 -2
@@ -0,0 +1,470 @@
1
+ import { HubClient, } from "./hub-client.js";
2
+ import { redactEnvValues } from "./redaction.js";
3
+ import { OS } from "./identity.js";
4
+ import { runnerAuthorizationHeaders } from "./runner-api-auth.js";
5
+ const AWAITING_REPLY_LIMIT_MS = 10_000;
6
+ function sleep(ms) {
7
+ return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
8
+ }
9
+ function readRunnerErrorPrefix(action) {
10
+ switch (action) {
11
+ case "create":
12
+ return "Execution machine create failed";
13
+ case "status":
14
+ return "Execution machine status failed";
15
+ case "inspect":
16
+ return "Execution machine inspection failed";
17
+ case "start":
18
+ return "Execution machine start failed";
19
+ case "stop":
20
+ return "Execution machine stop failed";
21
+ case "destroy":
22
+ return "Execution machine destroy failed";
23
+ case "prepare-project":
24
+ return "Execution machine project preparation failed";
25
+ case "idle-prepare":
26
+ return "Execution machine idle stop preparation failed";
27
+ case "idle-release":
28
+ return "Execution machine idle claim release failed";
29
+ case "terminal-lane-ticket":
30
+ return "Terminal lane ticket failed";
31
+ case "gadget-job":
32
+ return "Build and tests could not run";
33
+ case "gadget-map-back":
34
+ return `The ${OS.noun} edit could not be mapped back`;
35
+ }
36
+ }
37
+ async function readResponseBody(response) {
38
+ const text = await response.text().catch(() => "");
39
+ if (!text)
40
+ return {};
41
+ try {
42
+ return JSON.parse(text);
43
+ }
44
+ catch {
45
+ return { text };
46
+ }
47
+ }
48
+ function extractErrorMessage(status, body) {
49
+ if (body && typeof body === "object") {
50
+ const record = body;
51
+ if (typeof record.error === "string" && record.error.trim()) {
52
+ return record.error.trim();
53
+ }
54
+ if (typeof record.text === "string" && record.text.trim()) {
55
+ return record.text.trim();
56
+ }
57
+ }
58
+ return `HTTP ${status}`;
59
+ }
60
+ class LocalRunnerRequestError extends Error {
61
+ code;
62
+ currentCommandGeneration;
63
+ constructor(message, code, currentCommandGeneration) {
64
+ super(message);
65
+ this.name = "LocalRunnerRequestError";
66
+ this.code = code;
67
+ this.currentCommandGeneration = currentCommandGeneration;
68
+ }
69
+ }
70
+ export class RunnerSessionController {
71
+ options;
72
+ hub = null;
73
+ stateVersion = null;
74
+ awaitingSignature = null;
75
+ /** The runner_state_version the in-flight advertisement was written against. */
76
+ awaitingBaseVersion = null;
77
+ awaitingSince = 0;
78
+ registeredSignature = null;
79
+ deferredSignature = null;
80
+ reportedMismatchSignature = null;
81
+ connectionAdvertisementPending = true;
82
+ heartbeat = null;
83
+ heartbeatRefreshPending = false;
84
+ constructor(options) {
85
+ this.options = options;
86
+ }
87
+ async ensureConnected() {
88
+ if (!this.options.hubUrl || this.hub)
89
+ return;
90
+ this.hub = new HubClient({
91
+ hubUrl: this.options.hubUrl,
92
+ cfAccessHeaders: this.options.cfAccessHeaders,
93
+ });
94
+ this.hub.setMachineId(this.options.machineId);
95
+ this.hub.on("connected", () => {
96
+ this.stateVersion = null;
97
+ this.awaitingSignature = null;
98
+ this.awaitingBaseVersion = null;
99
+ this.registeredSignature = null;
100
+ this.deferredSignature = null;
101
+ this.reportedMismatchSignature = null;
102
+ this.connectionAdvertisementPending = true;
103
+ this.startHeartbeat();
104
+ });
105
+ this.hub.on("disconnected", () => {
106
+ this.stateVersion = null;
107
+ this.awaitingSignature = null;
108
+ this.awaitingBaseVersion = null;
109
+ this.registeredSignature = null;
110
+ this.connectionAdvertisementPending = true;
111
+ });
112
+ this.hub.on("machine-updated", (machine) => {
113
+ if (machine.id !== this.options.machineId)
114
+ return;
115
+ // A broadcast at or below the version our in-flight write was based on
116
+ // left the Hub before that write landed (the reconnect's machine-alive
117
+ // echo, another writer, an alarm). It cannot answer the write, so it is
118
+ // neither a confirmation nor a rejection: keep waiting for the reply.
119
+ if (this.awaitingSignature
120
+ && this.awaitingBaseVersion !== null
121
+ && machine.runner_state_version <= this.awaitingBaseVersion) {
122
+ return;
123
+ }
124
+ this.stateVersion = machine.runner_state_version;
125
+ const remoteSignature = this.options.getMachineSignature(machine);
126
+ this.registeredSignature = remoteSignature;
127
+ if (this.awaitingSignature === remoteSignature && remoteSignature) {
128
+ this.awaitingSignature = null;
129
+ this.awaitingBaseVersion = null;
130
+ this.deferredSignature = null;
131
+ this.reportedMismatchSignature = null;
132
+ this.connectionAdvertisementPending = false;
133
+ this.options.onRegistered?.(remoteSignature);
134
+ }
135
+ else if (this.awaitingSignature && remoteSignature !== this.awaitingSignature) {
136
+ this.deferredSignature = this.awaitingSignature;
137
+ if (this.reportedMismatchSignature !== this.awaitingSignature) {
138
+ this.reportedMismatchSignature = this.awaitingSignature;
139
+ this.options.onLog?.("Hub did not confirm the advertised host capabilities and running version. Registration remains unverified; retrying on the next health check.");
140
+ }
141
+ this.awaitingSignature = null;
142
+ this.awaitingBaseVersion = null;
143
+ }
144
+ this.flush();
145
+ });
146
+ this.hub.on("runner-control-request", (request) => {
147
+ void this.handleRunnerControlRequest(request);
148
+ });
149
+ const hub = this.hub;
150
+ const sendOs = (message) => {
151
+ if (this.hub === hub)
152
+ hub.sendOsMessage(message);
153
+ };
154
+ this.hub.on("connected", () => this.options.os?.connected(sendOs));
155
+ this.hub.on("os-message", (message) => {
156
+ void this.options.os?.receive(message, sendOs).catch((error) => {
157
+ this.options.onLog?.(`${OS.noun} request failed: ${error instanceof Error ? error.message : String(error)}`);
158
+ });
159
+ });
160
+ this.hub.on("error", (err) => {
161
+ const versionConflict = err.message.match(/Version conflict \(current: (\d+)\)/);
162
+ if (versionConflict) {
163
+ this.stateVersion = Number.parseInt(versionConflict[1], 10);
164
+ this.awaitingSignature = null;
165
+ this.awaitingBaseVersion = null;
166
+ this.flush();
167
+ return;
168
+ }
169
+ this.options.onLog?.(`Runner session: ${err.message}`);
170
+ });
171
+ this.hub.connect();
172
+ }
173
+ flush() {
174
+ const state = this.options.buildState();
175
+ if (!state || !this.hub || this.stateVersion == null || this.awaitingSignature) {
176
+ return;
177
+ }
178
+ if (this.hub.getSocket()?.readyState !== WebSocket.OPEN) {
179
+ return;
180
+ }
181
+ const signature = this.options.getStateSignature(state);
182
+ if (signature === this.deferredSignature)
183
+ return;
184
+ if (!this.connectionAdvertisementPending && signature === this.registeredSignature) {
185
+ return;
186
+ }
187
+ this.awaitingSignature = signature;
188
+ this.awaitingBaseVersion = this.stateVersion;
189
+ this.awaitingSince = Date.now();
190
+ this.hub.sendMachineUpdateRunnerState(this.options.machineId, state, this.stateVersion);
191
+ }
192
+ async sync(timeoutMs) {
193
+ await this.ensureConnected();
194
+ this.registeredSignature = null;
195
+ this.awaitingSignature = null;
196
+ this.awaitingBaseVersion = null;
197
+ this.connectionAdvertisementPending = true;
198
+ this.flush();
199
+ await this.waitForRegistration(timeoutMs);
200
+ }
201
+ async waitForRegistration(timeoutMs) {
202
+ const state = this.options.buildState();
203
+ if (!state) {
204
+ throw new Error("Host registration state is not available");
205
+ }
206
+ const signature = this.options.getStateSignature(state);
207
+ const deadline = Date.now() + timeoutMs;
208
+ while (Date.now() < deadline) {
209
+ await this.ensureConnected();
210
+ if (!this.connectionAdvertisementPending
211
+ && this.registeredSignature === signature
212
+ && !this.awaitingSignature) {
213
+ return;
214
+ }
215
+ this.flush();
216
+ await sleep(200);
217
+ }
218
+ throw new Error("Timed out waiting for host registration");
219
+ }
220
+ close() {
221
+ if (this.heartbeat) {
222
+ clearInterval(this.heartbeat);
223
+ this.heartbeat = null;
224
+ }
225
+ this.hub?.close();
226
+ this.hub = null;
227
+ this.options.os?.close();
228
+ this.stateVersion = null;
229
+ this.awaitingSignature = null;
230
+ this.awaitingBaseVersion = null;
231
+ this.registeredSignature = null;
232
+ this.connectionAdvertisementPending = true;
233
+ this.deferredSignature = null;
234
+ this.reportedMismatchSignature = null;
235
+ }
236
+ startHeartbeat() {
237
+ if (this.heartbeat)
238
+ return;
239
+ this.heartbeat = setInterval(() => {
240
+ void this.refreshHeartbeatState();
241
+ }, 30_000);
242
+ if (typeof this.heartbeat === "object" && "unref" in this.heartbeat) {
243
+ this.heartbeat.unref();
244
+ }
245
+ }
246
+ async refreshHeartbeatState() {
247
+ if (this.heartbeatRefreshPending)
248
+ return;
249
+ this.heartbeatRefreshPending = true;
250
+ try {
251
+ await this.options.refreshState?.();
252
+ }
253
+ catch (error) {
254
+ this.options.onLog?.(`Runner health refresh failed: ${error instanceof Error ? error.message : String(error)}`);
255
+ }
256
+ finally {
257
+ // The Hub answers every write with a broadcast or an error. One that
258
+ // never came (a dropped frame) must not block advertisements forever.
259
+ if (this.awaitingSignature && Date.now() - this.awaitingSince >= AWAITING_REPLY_LIMIT_MS) {
260
+ this.awaitingSignature = null;
261
+ this.awaitingBaseVersion = null;
262
+ }
263
+ this.connectionAdvertisementPending = true;
264
+ this.deferredSignature = null;
265
+ this.flush();
266
+ this.heartbeatRefreshPending = false;
267
+ }
268
+ }
269
+ async handleRunnerControlRequest(request) {
270
+ const hub = this.hub;
271
+ if (!hub)
272
+ return;
273
+ const startedAt = performance.now();
274
+ // Received before it runs: the Hub then knows the command was delivered
275
+ // and gives it the time a Start waiting behind a Stop can take, instead
276
+ // of treating a slow answer as a lost one. Sent on whichever socket is
277
+ // current; one sent while reconnecting is delivered after.
278
+ hub.sendRunnerControlReceived(request.requestId);
279
+ try {
280
+ const result = await this.executeLocalRunnerRequest(request);
281
+ if (request.action === "create" || request.action === "start") {
282
+ // With the runner's own timing line, splits the Hub's create ack into
283
+ // the runner's share and the Hub-to-host round trip.
284
+ this.options.onLog?.(`Runner ${request.action} for ${request.slug} answered locally in ${Math.round(performance.now() - startedAt)} ms`);
285
+ }
286
+ if (this.hub !== hub)
287
+ return;
288
+ hub.sendRunnerControlResponse(request.requestId, true, result);
289
+ }
290
+ catch (error) {
291
+ const rawMessage = error instanceof Error ? error.message : String(error);
292
+ if (request.action === "create" || request.action === "start" || request.action === "stop") {
293
+ // The Hub shows only a reference id for a failed command; without this
294
+ // line a start the runner refused looked like one it never received.
295
+ const code = error instanceof LocalRunnerRequestError && error.code ? ` (${error.code})` : "";
296
+ this.options.onLog?.(`Runner ${request.action} for ${request.slug} failed locally in ${Math.round(performance.now() - startedAt)} ms${code}: `
297
+ + redactEnvValues(rawMessage, request.envVars ?? {}));
298
+ }
299
+ if (this.hub !== hub)
300
+ return;
301
+ hub.sendRunnerControlResponse(request.requestId, false, undefined, redactEnvValues(rawMessage, request.envVars ?? {}), error instanceof LocalRunnerRequestError ? error.code : undefined, error instanceof LocalRunnerRequestError ? error.currentCommandGeneration : undefined);
302
+ }
303
+ }
304
+ runnerFetch(url, init = {}) {
305
+ const option = this.options.runnerApiToken;
306
+ const token = typeof option === "function" ? option() : option;
307
+ return fetch(url, {
308
+ ...init,
309
+ headers: { ...init.headers, ...runnerAuthorizationHeaders(token) },
310
+ });
311
+ }
312
+ async executeLocalRunnerRequest(request) {
313
+ const baseUrl = `http://127.0.0.1:${this.options.runnerPort}`;
314
+ let response;
315
+ switch (request.action) {
316
+ case "create":
317
+ response = await this.runnerFetch(`${baseUrl}/envs`, {
318
+ method: "POST",
319
+ headers: { "Content-Type": "application/json" },
320
+ body: JSON.stringify({
321
+ slug: request.slug,
322
+ repoUrl: request.repoUrl,
323
+ envVars: request.envVars ?? {},
324
+ ...(request.commandGeneration !== undefined ? { commandGeneration: request.commandGeneration } : {}),
325
+ ...(request.operationId ? { operationId: request.operationId } : {}),
326
+ ...(request.desiredState ? { desiredState: request.desiredState } : {}),
327
+ }),
328
+ });
329
+ break;
330
+ case "status":
331
+ response = await this.runnerFetch(`${baseUrl}/envs/${encodeURIComponent(request.slug)}`);
332
+ break;
333
+ case "inspect":
334
+ response = await this.runnerFetch(`${baseUrl}/envs/${encodeURIComponent(request.slug)}/inspection`);
335
+ break;
336
+ case "start":
337
+ response = await this.runnerFetch(`${baseUrl}/envs/${encodeURIComponent(request.slug)}/start`, {
338
+ method: "POST",
339
+ headers: { "Content-Type": "application/json" },
340
+ body: JSON.stringify({
341
+ repoUrl: request.repoUrl,
342
+ envVars: request.envVars ?? {},
343
+ ...(request.commandGeneration !== undefined ? { commandGeneration: request.commandGeneration } : {}),
344
+ ...(request.operationId ? { operationId: request.operationId } : {}),
345
+ ...(request.desiredState ? { desiredState: request.desiredState } : {}),
346
+ }),
347
+ });
348
+ break;
349
+ case "stop":
350
+ response = await this.runnerFetch(`${baseUrl}/envs/${encodeURIComponent(request.slug)}/stop`, {
351
+ method: "POST",
352
+ headers: { "Content-Type": "application/json" },
353
+ body: JSON.stringify({
354
+ ...(request.commandGeneration !== undefined ? { commandGeneration: request.commandGeneration } : {}),
355
+ ...(request.operationId ? { operationId: request.operationId } : {}),
356
+ ...(request.desiredState ? { desiredState: request.desiredState } : {}),
357
+ ...(request.idleClaimId ? { idleClaimId: request.idleClaimId } : {}),
358
+ }),
359
+ });
360
+ break;
361
+ case "idle-prepare":
362
+ // Host idle stop, phase one: claim and save, nothing else.
363
+ response = await this.runnerFetch(`${baseUrl}/envs/${encodeURIComponent(request.slug)}/idle-prepare`, {
364
+ method: "POST",
365
+ headers: { "Content-Type": "application/json" },
366
+ body: JSON.stringify({
367
+ idleTimeoutMs: request.idleTimeoutMs,
368
+ ...(request.claimTtlMs ? { claimTtlMs: request.claimTtlMs } : {}),
369
+ }),
370
+ });
371
+ break;
372
+ case "idle-release":
373
+ response = await this.runnerFetch(`${baseUrl}/envs/${encodeURIComponent(request.slug)}/idle-release`, {
374
+ method: "POST",
375
+ headers: { "Content-Type": "application/json" },
376
+ body: JSON.stringify({ claimId: request.claimId }),
377
+ });
378
+ break;
379
+ case "destroy":
380
+ response = await this.runnerFetch(`${baseUrl}/envs/${encodeURIComponent(request.slug)}`, {
381
+ method: "DELETE",
382
+ headers: { "Content-Type": "application/json" },
383
+ body: JSON.stringify({
384
+ ...(request.commandGeneration !== undefined ? { commandGeneration: request.commandGeneration } : {}),
385
+ ...(request.operationId ? { operationId: request.operationId } : {}),
386
+ ...(request.desiredState ? { desiredState: request.desiredState } : {}),
387
+ }),
388
+ });
389
+ break;
390
+ case "prepare-project":
391
+ // About a repository, not an environment: no slug, no command fence.
392
+ response = await this.runnerFetch(`${baseUrl}/projects/prepare`, {
393
+ method: "POST",
394
+ headers: { "Content-Type": "application/json" },
395
+ body: JSON.stringify({
396
+ repoUrl: request.repoUrl,
397
+ headSha: request.headSha,
398
+ envVars: request.envVars ?? {},
399
+ ...(request.stage === false ? { stage: false } : {}),
400
+ }),
401
+ });
402
+ break;
403
+ case "terminal-lane-ticket":
404
+ response = await this.runnerFetch(`${baseUrl}/envs/${encodeURIComponent(request.slug)}/terminal-lane-tickets`, {
405
+ method: "POST",
406
+ headers: { "Content-Type": "application/json" },
407
+ body: JSON.stringify({
408
+ sessionId: request.sessionId,
409
+ viewerConnectionId: request.viewerConnectionId,
410
+ }),
411
+ });
412
+ break;
413
+ case "gadget-job":
414
+ // Only the four fields the runner accepts are passed on, whatever else the message
415
+ // held: this client never adds environment variables, a slug or anything of its own.
416
+ response = await this.runnerFetch(`${baseUrl}/gadget-jobs`, {
417
+ method: "POST",
418
+ headers: { "Content-Type": "application/json" },
419
+ body: JSON.stringify({
420
+ appId: request.gadgetJob?.appId,
421
+ ...(request.gadgetJob?.commit ? { commit: request.gadgetJob.commit } : {}),
422
+ files: request.gadgetJob?.files,
423
+ ...(request.gadgetJob?.catalog ? { catalog: request.gadgetJob.catalog } : {}),
424
+ }),
425
+ });
426
+ break;
427
+ case "gadget-map-back":
428
+ // As above: only the fields the runner accepts are passed on.
429
+ response = await this.runnerFetch(`${baseUrl}/gadget-map-backs`, {
430
+ method: "POST",
431
+ headers: { "Content-Type": "application/json" },
432
+ body: JSON.stringify({
433
+ appId: request.gadgetMapBack?.appId,
434
+ ...(request.gadgetMapBack?.commit ? { commit: request.gadgetMapBack.commit } : {}),
435
+ files: request.gadgetMapBack?.files,
436
+ osFiles: request.gadgetMapBack?.osFiles,
437
+ }),
438
+ });
439
+ break;
440
+ default:
441
+ throw new LocalRunnerRequestError(`Unsupported runner control action: ${String(request.action)}`);
442
+ }
443
+ const body = await readResponseBody(response);
444
+ if (!response.ok) {
445
+ const responseCode = body && typeof body === "object" && typeof body.code === "string"
446
+ ? body.code
447
+ : undefined;
448
+ const recognizedCode = responseCode === "runner_command_superseded_before_mutation"
449
+ || responseCode === "runner_command_superseded"
450
+ || responseCode === "runner_command_conflict"
451
+ || responseCode === "runner_not_found"
452
+ || responseCode === "idle_stop_superseded"
453
+ || responseCode === "machine_full"
454
+ || responseCode === "gadget_jobs_full"
455
+ ? responseCode
456
+ : undefined;
457
+ const currentCommandGeneration = body
458
+ && typeof body === "object"
459
+ && Number.isSafeInteger(body.currentCommandGeneration)
460
+ && body.currentCommandGeneration > 0
461
+ ? body.currentCommandGeneration
462
+ : undefined;
463
+ throw new LocalRunnerRequestError(`${readRunnerErrorPrefix(request.action)}: ${extractErrorMessage(response.status, body)}`, recognizedCode
464
+ ?? (response.status === 404 && request.action === "status"
465
+ ? "runner_not_found"
466
+ : undefined), currentCommandGeneration);
467
+ }
468
+ return body;
469
+ }
470
+ }
@@ -0,0 +1,39 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readdirSync } from "node:fs";
3
+ /**
4
+ * Folder names on the machine for one environment slug.
5
+ *
6
+ * macOS disks ignore case by default, so a folder named after the raw slug
7
+ * (or after anything case-sensitive derived from it, such as base64) would
8
+ * give two slugs that differ only in capitals one folder, while their
9
+ * containers and volumes stay apart. These names are the lowercased slug,
10
+ * `+`, and 32 hex digits of the exact slug's SHA-256: distinct for any two
11
+ * different slugs even to a disk that ignores case. `+` never appears in a
12
+ * slug or in base64url, so no folder an earlier runner named can be mistaken
13
+ * for one of these. At most 128 + 1 + 32 = 161 bytes, under the 255 a folder
14
+ * name may have.
15
+ *
16
+ * Kept apart from `runner-slug.ts`, which the Hub imports and which must stay
17
+ * free of Node modules.
18
+ */
19
+ export const SLUG_FOLDER_HASH_HEX_DIGITS = 32;
20
+ export function caseSafeSlugFolderName(slug, hexDigits = SLUG_FOLDER_HASH_HEX_DIGITS) {
21
+ return `${slug.toLowerCase()}+${createHash("sha256").update(slug, "utf8").digest("hex").slice(0, hexDigits)}`;
22
+ }
23
+ /**
24
+ * The first of `names` that is a directory in `parent`, comparing each
25
+ * entry's own name exactly: on a case-insensitive disk `Foo` would also
26
+ * "exist" when only `foo` does. Null when none is there.
27
+ */
28
+ export function findExactDirectoryEntry(parent, names) {
29
+ let entries;
30
+ try {
31
+ entries = new Set(readdirSync(parent, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name));
32
+ }
33
+ catch (error) {
34
+ if (error.code === "ENOENT")
35
+ return null;
36
+ throw error;
37
+ }
38
+ return names.find((name) => entries.has(name)) ?? null;
39
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The runner turns an environment's slug into Docker names and into folders
3
+ * on the machine (`<state dir>/opencode/<folder>`, mounted read-write and
4
+ * deleted on destroy, and the command fence's folder; names in
5
+ * `runner-slug-folder.ts`, or the raw or base64url slug for folders an earlier
6
+ * runner made). The runner checks the slug itself, and the Hub refuses the
7
+ * same slugs with this same rule before a request reaches a runner: one plain
8
+ * name, never a path. This file must stay free of Node modules, because the
9
+ * Hub imports it.
10
+ *
11
+ * Slugs in use are lowercase letters, digits and hyphens. Slugs named after a
12
+ * repository can also carry what repository names allow (upper case, `.`,
13
+ * `_`), and a repository such as `.github` gives a slug that starts with a dot,
14
+ * so those stay accepted. Refused: path separators and anything else, `..`
15
+ * anywhere (so never `.` or `..` as a whole name), a leading `-` (it could read
16
+ * as an option), and more than 128 characters (folder names must stay under
17
+ * 255 bytes: a base64url slug is at most 172, a new folder name at most 161).
18
+ */
19
+ export const MAX_RUNNER_SLUG_LENGTH = 128;
20
+ const RUNNER_SLUG = /^[A-Za-z0-9_.][A-Za-z0-9_.-]*$/;
21
+ export class RunnerSlugError extends Error {
22
+ status = 400;
23
+ code = "invalid_slug";
24
+ constructor(message = "Invalid environment slug: use letters, digits, '.', '_' and '-' only, at most 128 characters, no '..' and no leading '-'.") {
25
+ super(message);
26
+ this.name = "RunnerSlugError";
27
+ }
28
+ }
29
+ export function isValidRunnerSlug(slug) {
30
+ return typeof slug === "string"
31
+ && slug.length > 0
32
+ && slug.length <= MAX_RUNNER_SLUG_LENGTH
33
+ && RUNNER_SLUG.test(slug)
34
+ && !slug.includes("..")
35
+ && slug !== ".";
36
+ }
37
+ export function assertValidRunnerSlug(slug) {
38
+ if (!isValidRunnerSlug(slug))
39
+ throw new RunnerSlugError();
40
+ }