@leitwerk-dev/worker-runners 0.1.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 (88) hide show
  1. package/dist/LICENSE +13 -0
  2. package/dist/chunk-2TSWMVLZ.js +220 -0
  3. package/dist/chunk-2TSWMVLZ.js.map +1 -0
  4. package/dist/chunk-6WACBFXN.js +78 -0
  5. package/dist/chunk-6WACBFXN.js.map +1 -0
  6. package/dist/chunk-CCV2UXAM.js +187 -0
  7. package/dist/chunk-CCV2UXAM.js.map +1 -0
  8. package/dist/chunk-DL3Y3R6E.js +107 -0
  9. package/dist/chunk-DL3Y3R6E.js.map +1 -0
  10. package/dist/chunk-HLTGLGUS.js +223 -0
  11. package/dist/chunk-HLTGLGUS.js.map +1 -0
  12. package/dist/chunk-IRFVGUXJ.js +31 -0
  13. package/dist/chunk-IRFVGUXJ.js.map +1 -0
  14. package/dist/chunk-PM7IYWFL.js +394 -0
  15. package/dist/chunk-PM7IYWFL.js.map +1 -0
  16. package/dist/docker-engine-client-Cpmy2yma.d.ts +87 -0
  17. package/dist/docker-engine-client.d.ts +86 -0
  18. package/dist/docker-engine-client.d.ts.map +1 -0
  19. package/dist/docker-engine-client.js +10 -0
  20. package/dist/docker-engine-client.js.map +1 -0
  21. package/dist/docker-engine-http-client.d.ts +26 -0
  22. package/dist/docker-engine-http-client.d.ts.map +1 -0
  23. package/dist/docker-engine-http-client.js +202 -0
  24. package/dist/docker-engine-http-client.js.map +1 -0
  25. package/dist/docker-worker-runner.d.ts +35 -0
  26. package/dist/docker-worker-runner.d.ts.map +1 -0
  27. package/dist/docker-worker-runner.js +236 -0
  28. package/dist/docker-worker-runner.js.map +1 -0
  29. package/dist/fake-docker-engine-client.d.ts +40 -0
  30. package/dist/fake-docker-engine-client.d.ts.map +1 -0
  31. package/dist/fake-docker-engine-client.js +131 -0
  32. package/dist/fake-docker-engine-client.js.map +1 -0
  33. package/dist/index.d.ts +12 -0
  34. package/dist/index.d.ts.map +1 -0
  35. package/dist/index.js +10 -0
  36. package/dist/index.js.map +1 -0
  37. package/dist/kubernetes-api-client-DF77hbtl.d.ts +278 -0
  38. package/dist/kubernetes-api-client.d.ts +71 -0
  39. package/dist/kubernetes-api-client.d.ts.map +1 -0
  40. package/dist/kubernetes-api-client.js +142 -0
  41. package/dist/kubernetes-api-client.js.map +1 -0
  42. package/dist/kubernetes-http-client.d.ts +15 -0
  43. package/dist/kubernetes-http-client.d.ts.map +1 -0
  44. package/dist/kubernetes-http-client.js +296 -0
  45. package/dist/kubernetes-http-client.js.map +1 -0
  46. package/dist/kubernetes-manifests.d.ts +232 -0
  47. package/dist/kubernetes-manifests.d.ts.map +1 -0
  48. package/dist/kubernetes-manifests.js +370 -0
  49. package/dist/kubernetes-manifests.js.map +1 -0
  50. package/dist/kubernetes-worker-runner.d.ts +24 -0
  51. package/dist/kubernetes-worker-runner.d.ts.map +1 -0
  52. package/dist/kubernetes-worker-runner.js +162 -0
  53. package/dist/kubernetes-worker-runner.js.map +1 -0
  54. package/dist/local-worker-runner.d.ts +26 -0
  55. package/dist/local-worker-runner.d.ts.map +1 -0
  56. package/dist/local-worker-runner.js +109 -0
  57. package/dist/local-worker-runner.js.map +1 -0
  58. package/dist/process-volume-retention.d.ts +21 -0
  59. package/dist/process-volume-retention.d.ts.map +1 -0
  60. package/dist/process-volume-retention.js +46 -0
  61. package/dist/process-volume-retention.js.map +1 -0
  62. package/dist/runner-utils.d.ts +16 -0
  63. package/dist/runner-utils.d.ts.map +1 -0
  64. package/dist/runner-utils.js +36 -0
  65. package/dist/runner-utils.js.map +1 -0
  66. package/dist/types.d.ts +121 -0
  67. package/dist/types.d.ts.map +1 -0
  68. package/dist/types.js +12 -0
  69. package/dist/types.js.map +1 -0
  70. package/dist/worker-labels.d.ts +50 -0
  71. package/dist/worker-labels.d.ts.map +1 -0
  72. package/dist/worker-labels.js +83 -0
  73. package/dist/worker-labels.js.map +1 -0
  74. package/package.json +71 -0
  75. package/src/docker-engine-client.ts +86 -0
  76. package/src/docker-engine-http-client.ts +275 -0
  77. package/src/docker-worker-runner.ts +296 -0
  78. package/src/fake-docker-engine-client.ts +182 -0
  79. package/src/index.ts +102 -0
  80. package/src/kubernetes-api-client.ts +231 -0
  81. package/src/kubernetes-http-client.ts +402 -0
  82. package/src/kubernetes-manifests.ts +609 -0
  83. package/src/kubernetes-worker-runner.ts +228 -0
  84. package/src/local-worker-runner.ts +145 -0
  85. package/src/process-volume-retention.ts +72 -0
  86. package/src/runner-utils.ts +37 -0
  87. package/src/types.ts +130 -0
  88. package/src/worker-labels.ts +112 -0
@@ -0,0 +1,228 @@
1
+ import { readFileSync } from "node:fs";
2
+ import type { KubernetesApiClient } from "./kubernetes-api-client.js";
3
+ import {
4
+ buildKubernetesDockerConfigJsonSecretManifest,
5
+ buildKubernetesProcessNamespaceManifest,
6
+ buildKubernetesProcessPvcManifest,
7
+ buildKubernetesServerCaConfigMapManifest,
8
+ buildKubernetesWorkerPodManifest,
9
+ KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_KEY,
10
+ KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_NAME,
11
+ KUBERNETES_WORKER_SERVER_CA_MOUNT_PATH,
12
+ type KubernetesPodSpecOptions,
13
+ type KubernetesProcessVolumeSpec,
14
+ kubernetesProcessNamespaceName,
15
+ kubernetesProcessPvcName,
16
+ volumeRefFromPvc,
17
+ } from "./kubernetes-manifests.js";
18
+ import { UnitExitNotifier } from "./runner-utils.js";
19
+ import type {
20
+ IsolatedStartWorkerInput,
21
+ ProcessVolume,
22
+ StopWorkerOptions,
23
+ WorkerRunner,
24
+ WorkerUnit,
25
+ WorkerUnitDescriptor,
26
+ WorkerUnitRef,
27
+ } from "./types.js";
28
+ import {
29
+ managedProcessNamespaceLabelSelector,
30
+ managedWorkerLabelSelector,
31
+ parseWorkerUnitIdentity,
32
+ WORKER_LABEL_COMPONENT,
33
+ WORKER_LABEL_INSTANCE_ID,
34
+ WORKER_LABEL_MANAGED_BY,
35
+ WORKER_LABEL_MANAGED_BY_VALUE,
36
+ } from "./worker-labels.js";
37
+
38
+ export interface KubernetesWorkerRunnerOptions {
39
+ client: KubernetesApiClient;
40
+ /** Prefix used to derive one Kubernetes namespace per process instance. */
41
+ processNamespacePrefix: string;
42
+ volume: KubernetesProcessVolumeSpec;
43
+ /** Server-local CA bundle copied into each process namespace for worker TLS trust. */
44
+ serverCaFile?: string;
45
+ /** Namespace containing operator-managed source image-pull Secrets. */
46
+ serverNamespace?: string;
47
+ /** Docker registry Secrets copied into every process namespace. */
48
+ imagePullSecretCopies?: Array<{ sourceName: string; targetName: string }>;
49
+ pod?: Omit<KubernetesPodSpecOptions, "namespace">;
50
+ }
51
+
52
+ export function createKubernetesWorkerRunner(options: KubernetesWorkerRunnerOptions): {
53
+ runner: WorkerRunner<IsolatedStartWorkerInput>;
54
+ volume: ProcessVolume;
55
+ } {
56
+ const { client } = options;
57
+ const serverCaFile = options.serverCaFile?.trim();
58
+ const namespaceForProcess = (instanceId: string) =>
59
+ kubernetesProcessNamespaceName(instanceId, options.processNamespacePrefix);
60
+
61
+ const volume: ProcessVolume = {
62
+ async ensure(instanceId) {
63
+ const namespaceManifest = buildKubernetesProcessNamespaceManifest({
64
+ instanceId,
65
+ processNamespacePrefix: options.processNamespacePrefix,
66
+ });
67
+ await client.ensureNamespace(namespaceManifest);
68
+ for (const copy of options.imagePullSecretCopies ?? []) {
69
+ const dockerConfigJson = await client.getDockerConfigJsonSecret(
70
+ copy.sourceName,
71
+ options.serverNamespace ?? "leitwerk-system",
72
+ );
73
+ await client.ensureDockerConfigJsonSecret(
74
+ buildKubernetesDockerConfigJsonSecretManifest({
75
+ instanceId,
76
+ namespace: namespaceManifest.metadata.name,
77
+ name: copy.targetName,
78
+ dockerConfigJson,
79
+ }),
80
+ );
81
+ }
82
+ if (serverCaFile) {
83
+ await client.ensureConfigMap(
84
+ buildKubernetesServerCaConfigMapManifest({
85
+ instanceId,
86
+ namespace: namespaceManifest.metadata.name,
87
+ caPem: readFileSync(serverCaFile, "utf8"),
88
+ }),
89
+ );
90
+ }
91
+ const workerServiceAccount = options.pod?.workerServiceAccount?.trim();
92
+ if (workerServiceAccount && workerServiceAccount !== "default") {
93
+ await client.ensureServiceAccount(workerServiceAccount, namespaceManifest.metadata.name, {
94
+ [WORKER_LABEL_MANAGED_BY]: WORKER_LABEL_MANAGED_BY_VALUE,
95
+ [WORKER_LABEL_COMPONENT]: "worker-service-account",
96
+ [WORKER_LABEL_INSTANCE_ID]: instanceId,
97
+ });
98
+ }
99
+ const manifest = buildKubernetesProcessPvcManifest({
100
+ instanceId,
101
+ namespace: namespaceManifest.metadata.name,
102
+ volume: options.volume,
103
+ });
104
+ await client.ensurePersistentVolumeClaim(manifest);
105
+ return volumeRefFromPvc({
106
+ instanceId,
107
+ pvcName: manifest.metadata.name,
108
+ mountPath: options.volume.mountPath,
109
+ namespace: manifest.metadata.namespace,
110
+ });
111
+ },
112
+ async release(instanceId) {
113
+ await client.deletePersistentVolumeClaim(
114
+ kubernetesProcessPvcName(instanceId, options.volume.namePrefix),
115
+ namespaceForProcess(instanceId),
116
+ );
117
+ },
118
+ async deleteProcessResources(instanceId) {
119
+ await client.deleteNamespace(namespaceForProcess(instanceId));
120
+ },
121
+ };
122
+
123
+ const exitNotifier = new UnitExitNotifier();
124
+ const unsubscribers = new Map<string, () => void>();
125
+
126
+ function unitKey(namespace: string, unitId: string): string {
127
+ return `${namespace}/${unitId}`;
128
+ }
129
+
130
+ function watchPod(unitId: string, namespace: string): void {
131
+ const key = unitKey(namespace, unitId);
132
+ if (unsubscribers.has(key)) return;
133
+ const unsubscribe = client.onPodExit(unitId, namespace, (info) => {
134
+ exitNotifier.fireExit(key, info);
135
+ unsubscribers.get(key)?.();
136
+ unsubscribers.delete(key);
137
+ });
138
+ unsubscribers.set(key, unsubscribe);
139
+ }
140
+
141
+ const runner: WorkerRunner<IsolatedStartWorkerInput> = {
142
+ async start(input: IsolatedStartWorkerInput): Promise<WorkerUnit> {
143
+ if (input.isolation.dind !== false) {
144
+ throw new Error("Kubernetes worker runner does not support Docker-in-Docker profiles");
145
+ }
146
+ const processNamespace = input.volume.namespace ?? namespaceForProcess(input.instanceId);
147
+ const manifest = buildKubernetesWorkerPodManifest(input, {
148
+ namespace: processNamespace,
149
+ ...(options.pod ?? {}),
150
+ ...(serverCaFile
151
+ ? {
152
+ serverCaConfigMap: {
153
+ name: KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_NAME,
154
+ key: KUBERNETES_WORKER_SERVER_CA_CONFIG_MAP_KEY,
155
+ mountPath: KUBERNETES_WORKER_SERVER_CA_MOUNT_PATH,
156
+ },
157
+ }
158
+ : {}),
159
+ });
160
+ await client.createPod(manifest);
161
+ const ref: WorkerUnitRef = {
162
+ instanceId: input.instanceId,
163
+ workerId: input.workerId,
164
+ unitId: manifest.metadata.name,
165
+ namespace: manifest.metadata.namespace,
166
+ };
167
+ watchPod(ref.unitId, ref.namespace ?? processNamespace);
168
+ return exitNotifier.wrapUnit(ref, unitKey(ref.namespace ?? processNamespace, ref.unitId));
169
+ },
170
+ async stop(ref: WorkerUnitRef, opts: StopWorkerOptions): Promise<void> {
171
+ await client.deletePod(ref.unitId, ref.namespace ?? namespaceForProcess(ref.instanceId), {
172
+ gracePeriodSeconds: Math.max(0, Math.ceil(opts.graceMs / 1000)),
173
+ });
174
+ },
175
+ async list(): Promise<WorkerUnitDescriptor[]> {
176
+ const namespaces = await client.listNamespaces(managedProcessNamespaceLabelSelector());
177
+ const descriptors: WorkerUnitDescriptor[] = [];
178
+ for (const namespace of namespaces) {
179
+ if (!namespace.name.startsWith(options.processNamespacePrefix)) continue;
180
+ const pods = await client.listPods(namespace.name, managedWorkerLabelSelector());
181
+ for (const pod of pods) {
182
+ const identity = parseWorkerUnitIdentity(pod.labels);
183
+ if (!identity) continue;
184
+ descriptors.push({
185
+ instanceId: identity.instanceId,
186
+ workerId: identity.workerId,
187
+ unitId: pod.name,
188
+ namespace: pod.namespace,
189
+ observedState:
190
+ pod.phase === "Failed" || pod.phase === "Succeeded"
191
+ ? "terminal"
192
+ : pod.phase === "Pending"
193
+ ? "pending"
194
+ : pod.phase === "Running"
195
+ ? "running"
196
+ : "unknown",
197
+ });
198
+ }
199
+ }
200
+ return descriptors;
201
+ },
202
+ async adopt(descriptor: WorkerUnitDescriptor): Promise<WorkerUnit> {
203
+ const podNamespace = descriptor.namespace ?? namespaceForProcess(descriptor.instanceId);
204
+ const pod = await client.getPod(descriptor.unitId, podNamespace);
205
+ const identity = pod ? parseWorkerUnitIdentity(pod.labels) : null;
206
+ if (
207
+ !identity ||
208
+ identity.instanceId !== descriptor.instanceId ||
209
+ identity.workerId !== descriptor.workerId
210
+ ) {
211
+ throw new Error(`Cannot adopt worker pod ${descriptor.unitId}: labels changed`);
212
+ }
213
+ if (!pod || pod.phase === "Failed" || pod.phase === "Succeeded") {
214
+ throw new Error(`Cannot adopt worker pod ${descriptor.unitId}: not running`);
215
+ }
216
+ const ref: WorkerUnitRef = {
217
+ instanceId: descriptor.instanceId,
218
+ workerId: descriptor.workerId,
219
+ unitId: descriptor.unitId,
220
+ namespace: podNamespace,
221
+ };
222
+ watchPod(ref.unitId, podNamespace);
223
+ return exitNotifier.wrapUnit(ref, unitKey(podNamespace, ref.unitId));
224
+ },
225
+ };
226
+
227
+ return { runner, volume };
228
+ }
@@ -0,0 +1,145 @@
1
+ import { type ChildProcess, spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { UnitExitNotifier } from "./runner-utils.js";
6
+ import type {
7
+ LocalStartWorkerInput,
8
+ StopWorkerOptions,
9
+ WorkerExitInfo,
10
+ WorkerRunner,
11
+ WorkerUnit,
12
+ WorkerUnitDescriptor,
13
+ WorkerUnitRef,
14
+ } from "./types.js";
15
+
16
+ export const DEFAULT_LOCAL_WORKER_ENTRY_SPECIFIER = "@leitwerk-dev/worker/worker-entry";
17
+
18
+ export interface LocalWorkerRunnerOptions {
19
+ /** Command used to launch the worker. Defaults to `node`. */
20
+ command?: string;
21
+ /** Worker entry args. The default package subpath is resolved to the installed entry file. */
22
+ args?: readonly string[];
23
+ /** Working directory for the spawned worker. Defaults to the installed server package dir. */
24
+ cwd?: string;
25
+ /** Test seam. Production uses node's spawn directly. */
26
+ localWorkerSpawnImpl?: typeof spawn;
27
+ }
28
+
29
+ interface LocalWorkerUnitState {
30
+ ref: WorkerUnitRef;
31
+ child: ChildProcess;
32
+ status: "running" | "stopping" | "exited";
33
+ }
34
+
35
+ let localUnitCounter = 0;
36
+
37
+ function nextUnitId(instanceId: string, workerId: string): string {
38
+ localUnitCounter += 1;
39
+ return `local_${instanceId}_${workerId}_${localUnitCounter}`;
40
+ }
41
+
42
+ function findServerPackageDir(): string {
43
+ let current = path.dirname(fileURLToPath(import.meta.url));
44
+ while (true) {
45
+ const candidate = path.join(current, "package.json");
46
+ if (existsSync(candidate)) return current;
47
+ const parent = path.dirname(current);
48
+ if (parent === current) return process.cwd();
49
+ current = parent;
50
+ }
51
+ }
52
+
53
+ function resolveDefaultWorkerEntryPath(): string {
54
+ return fileURLToPath(import.meta.resolve(DEFAULT_LOCAL_WORKER_ENTRY_SPECIFIER));
55
+ }
56
+
57
+ export function resolveLocalWorkerSpawnArgs(args: readonly string[]): string[] {
58
+ return args[0] === DEFAULT_LOCAL_WORKER_ENTRY_SPECIFIER
59
+ ? [resolveDefaultWorkerEntryPath(), ...args.slice(1)]
60
+ : [...args];
61
+ }
62
+
63
+ function exitInfo(code: number | null, signal: NodeJS.Signals | null): WorkerExitInfo {
64
+ return { exitCode: code, signal };
65
+ }
66
+
67
+ /**
68
+ * Best-effort local development/test {@link WorkerRunner}.
69
+ *
70
+ * This runner implements the shared runner contract needed to start and stop a
71
+ * local worker over the production WebSocket IPC path. It is not an isolation
72
+ * boundary, has no restart adoption, and ignores image/resource profile semantics.
73
+ * Docker and Kubernetes remain the contract-defining production runners.
74
+ */
75
+ export function createLocalWorkerRunner(options: LocalWorkerRunnerOptions): {
76
+ runner: WorkerRunner<LocalStartWorkerInput>;
77
+ } {
78
+ const command = options.command ?? "node";
79
+ const args = resolveLocalWorkerSpawnArgs(options.args ?? [DEFAULT_LOCAL_WORKER_ENTRY_SPECIFIER]);
80
+ const cwd = options.cwd ?? findServerPackageDir();
81
+ const localWorkerSpawnImpl = options.localWorkerSpawnImpl ?? spawn;
82
+ const units = new Map<string, LocalWorkerUnitState>();
83
+ const exitNotifier = new UnitExitNotifier();
84
+
85
+ function wrap(ref: WorkerUnitRef): WorkerUnit {
86
+ return exitNotifier.wrapUnit(ref, ref.unitId);
87
+ }
88
+
89
+ const runner: WorkerRunner<LocalStartWorkerInput> = {
90
+ async start(input: LocalStartWorkerInput): Promise<WorkerUnit> {
91
+ if (input.isolation.dind !== false) {
92
+ throw new Error("Local worker runner does not support Docker-in-Docker profiles");
93
+ }
94
+ const unitId = nextUnitId(input.instanceId, input.workerId);
95
+ const ref: WorkerUnitRef = { instanceId: input.instanceId, workerId: input.workerId, unitId };
96
+ const child = localWorkerSpawnImpl(command, args, {
97
+ cwd,
98
+ stdio: ["ignore", "inherit", "inherit"],
99
+ env: { ...process.env, ...input.env },
100
+ });
101
+ const state: LocalWorkerUnitState = {
102
+ ref,
103
+ child,
104
+ status: "running",
105
+ };
106
+ units.set(unitId, state);
107
+ child.once("exit", (code, signal) => {
108
+ state.status = "exited";
109
+ exitNotifier.fireExit(unitId, exitInfo(code, signal));
110
+ });
111
+ child.once("error", (error) => {
112
+ state.status = "exited";
113
+ exitNotifier.fireExit(unitId, {
114
+ exitCode: null,
115
+ signal: null,
116
+ reason: error instanceof Error ? error.message : String(error),
117
+ });
118
+ });
119
+ return wrap(ref);
120
+ },
121
+ async stop(ref: WorkerUnitRef, opts: StopWorkerOptions): Promise<void> {
122
+ const state = units.get(ref.unitId);
123
+ if (!state || state.status === "exited") return;
124
+ state.status = "stopping";
125
+ const child = state.child;
126
+ const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()));
127
+ child.kill("SIGTERM");
128
+ const timedOut = await Promise.race([
129
+ exited.then(() => false),
130
+ new Promise<boolean>((resolve) => setTimeout(() => resolve(true), opts.graceMs)),
131
+ ]);
132
+ if (timedOut) child.kill("SIGKILL");
133
+ },
134
+ async list(): Promise<WorkerUnitDescriptor[]> {
135
+ return [];
136
+ },
137
+ async adopt(descriptor: WorkerUnitDescriptor): Promise<WorkerUnit> {
138
+ throw new Error(
139
+ `Cannot adopt local worker ${descriptor.unitId}: local runner does not support adoption`,
140
+ );
141
+ },
142
+ };
143
+
144
+ return { runner };
145
+ }
@@ -0,0 +1,72 @@
1
+ import type { ProcessInstance } from "@leitwerk-dev/domain";
2
+ import { parseDurationMs } from "@leitwerk-dev/watcher-utils";
3
+ import type { ProcessVolume } from "./types.js";
4
+
5
+ export interface ProcessVolumeRetentionPolicy {
6
+ completedProcessRetention: string;
7
+ errorProcessRetention: string;
8
+ }
9
+
10
+ export interface PlanProcessVolumeRetentionCleanupInput {
11
+ processes: readonly ProcessInstance[];
12
+ now: Date;
13
+ policy: ProcessVolumeRetentionPolicy;
14
+ alreadyReleased?: ReadonlySet<string>;
15
+ }
16
+
17
+ function retentionMs(value: string): number {
18
+ return parseDurationMs(value, Number.POSITIVE_INFINITY, { allowHours: true });
19
+ }
20
+
21
+ function closedAtMs(process: ProcessInstance): number | null {
22
+ if (!process.closedAt) {
23
+ return null;
24
+ }
25
+ const parsed = Date.parse(process.closedAt);
26
+ return Number.isFinite(parsed) ? parsed : null;
27
+ }
28
+
29
+ export function planProcessVolumeRetentionCleanup(
30
+ input: PlanProcessVolumeRetentionCleanupInput,
31
+ ): string[] {
32
+ const completedRetentionMs = retentionMs(input.policy.completedProcessRetention);
33
+ const errorRetentionMs = retentionMs(input.policy.errorProcessRetention);
34
+ const nowMs = input.now.getTime();
35
+ const alreadyReleased = input.alreadyReleased ?? new Set<string>();
36
+ const candidates: string[] = [];
37
+ for (const process of input.processes) {
38
+ if (alreadyReleased.has(process.id)) {
39
+ continue;
40
+ }
41
+ const closed = closedAtMs(process);
42
+ if (closed === null) {
43
+ continue;
44
+ }
45
+ const retention =
46
+ process.lifecycleStatus === "completed"
47
+ ? completedRetentionMs
48
+ : process.lifecycleStatus === "aborted" || process.lifecycleStatus === "error"
49
+ ? errorRetentionMs
50
+ : Number.POSITIVE_INFINITY;
51
+ if (nowMs - closed >= retention) {
52
+ candidates.push(process.id);
53
+ }
54
+ }
55
+ return candidates;
56
+ }
57
+
58
+ export async function cleanupRetainedProcessVolumes(input: {
59
+ volume?: ProcessVolume;
60
+ processes: readonly ProcessInstance[];
61
+ now: Date;
62
+ policy: ProcessVolumeRetentionPolicy;
63
+ alreadyReleased?: ReadonlySet<string>;
64
+ }): Promise<string[]> {
65
+ const candidates = planProcessVolumeRetentionCleanup(input);
66
+ if (input.volume) {
67
+ for (const instanceId of candidates) {
68
+ await input.volume.release(instanceId);
69
+ }
70
+ }
71
+ return candidates;
72
+ }
@@ -0,0 +1,37 @@
1
+ import type { WorkerExitInfo, WorkerUnit, WorkerUnitRef } from "./types.js";
2
+
3
+ /**
4
+ * Shared exit-notification machinery used by every {@link WorkerRunner}.
5
+ *
6
+ * Each runner implementation tracks physical unit exits and maps them to
7
+ * `WorkerUnit.onExit` callbacks. This utility captures the identical map +
8
+ * fire/wrap logic and leaves only the unit-keying to each runner.
9
+ */
10
+ export class UnitExitNotifier {
11
+ private readonly listeners = new Map<string, Array<(info: WorkerExitInfo) => void>>();
12
+ private readonly exited = new Map<string, WorkerExitInfo>();
13
+
14
+ onExit(key: string, listener: (info: WorkerExitInfo) => void): void {
15
+ const exit = this.exited.get(key);
16
+ if (exit) {
17
+ queueMicrotask(() => listener(exit));
18
+ return;
19
+ }
20
+ const list = this.listeners.get(key) ?? [];
21
+ list.push(listener);
22
+ this.listeners.set(key, list);
23
+ }
24
+
25
+ fireExit(key: string, info: WorkerExitInfo): void {
26
+ if (this.exited.has(key)) return;
27
+ this.exited.set(key, info);
28
+ const list = this.listeners.get(key);
29
+ if (!list) return;
30
+ this.listeners.delete(key);
31
+ for (const listener of list.splice(0)) listener(info);
32
+ }
33
+
34
+ wrapUnit<T extends WorkerUnitRef>(ref: T, key: string): WorkerUnit {
35
+ return { ...ref, onExit: (listener) => this.onExit(key, listener) };
36
+ }
37
+ }
package/src/types.ts ADDED
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Runner API seams shared by worker run modes (Docker, Kubernetes, best-effort local).
3
+ *
4
+ * The seam is cut so the runtimes share everything except the runtime-specific
5
+ * bodies of two interfaces. The IPC transport is deliberately *not* a runner
6
+ * axis: the runner only injects connect env, the worker dials back over
7
+ * WebSocket, and the existing `WorkerWebSocketIpcManager` binds the socket to
8
+ * the lease. The supervisor stays the lease/lifecycle coordinator; the runner
9
+ * only does runtime-specific work.
10
+ */
11
+
12
+ /**
13
+ * Durable per-process storage handle.
14
+ *
15
+ * The server NEVER mounts or reads the volume contents. It learns tree and leaf
16
+ * state over the protocol (the session-snapshot exchange), never by reading the
17
+ * volume, which keeps every run mode symmetric.
18
+ */
19
+ export interface VolumeRef {
20
+ instanceId: string;
21
+ /** Runtime-specific identifier (host path, named volume, PVC name). */
22
+ id: string;
23
+ /** Path inside the worker container where the volume is mounted. */
24
+ mountPath: string;
25
+ /** Runtime-specific namespace/project for the volume (Kubernetes process namespace). */
26
+ namespace?: string;
27
+ }
28
+
29
+ export interface ProcessVolume {
30
+ /** Idempotently provisions durable storage for a process instance. */
31
+ ensure(instanceId: string): Promise<VolumeRef>;
32
+ /** Retention cleanup only. Stopping a worker never calls this. */
33
+ release(instanceId: string): Promise<void>;
34
+ /** Permanently deletes every runner-managed resource owned by a deleted process. */
35
+ deleteProcessResources(instanceId: string): Promise<void>;
36
+ }
37
+
38
+ /**
39
+ * Output of runtime-profile selection. MVP resolves to a single configured
40
+ * worker image; repository branch content must never select an image.
41
+ */
42
+ export interface ResolvedWorkerImage {
43
+ /** Fully qualified image reference, ideally digest-pinned. */
44
+ reference: string;
45
+ }
46
+
47
+ export interface WorkerResourceLimits {
48
+ cpu?: string;
49
+ memory?: string;
50
+ }
51
+
52
+ /**
53
+ * Nested-container capability for the worker.
54
+ *
55
+ * - `{ dind: false }` — default unprivileged worker.
56
+ * - `{ dind: "privileged" }` — inner `dockerd` started inside the worker.
57
+ * - `{ dind: "sysbox" }` — nested daemon without `--privileged` (host must
58
+ * provide the sysbox runtime).
59
+ */
60
+ export type WorkerIsolation = { dind: false } | { dind: "privileged" | "sysbox" };
61
+
62
+ export interface WorkerUnitRef {
63
+ instanceId: string;
64
+ workerId: string;
65
+ /** Runtime-specific handle id (container id, pod name). */
66
+ unitId: string;
67
+ /** Runtime-specific namespace/project for the unit (Kubernetes process namespace). */
68
+ namespace?: string;
69
+ }
70
+
71
+ export interface WorkerExitInfo {
72
+ /** Process exit code when the runtime reports one. */
73
+ exitCode: number | null;
74
+ /** Termination signal when the runtime reports one. */
75
+ signal: string | null;
76
+ /** True when the runtime killed the unit for exceeding memory limits. */
77
+ oomKilled?: boolean;
78
+ /** Human-readable reason surfaced by the runtime, if any. */
79
+ reason?: string;
80
+ }
81
+
82
+ export interface WorkerUnit extends WorkerUnitRef {
83
+ /** Maps physical worker exit into the supervisor's existing failure paths. */
84
+ onExit(listener: (info: WorkerExitInfo) => void): void;
85
+ }
86
+
87
+ export interface WorkerUnitDescriptor extends WorkerUnitRef {
88
+ observedState?: "running" | "pending" | "terminal" | "unknown";
89
+ }
90
+
91
+ interface StartWorkerInputBase {
92
+ instanceId: string;
93
+ workerId: string;
94
+ serverEpoch: string;
95
+ /** Runtime-profile selection output; MVP = single image. */
96
+ image: ResolvedWorkerImage;
97
+ /** Server URL, ids, connect token, `PI_CODING_AGENT_DIR`, etc. */
98
+ env: Record<string, string>;
99
+ isolation: WorkerIsolation;
100
+ resources?: WorkerResourceLimits;
101
+ }
102
+
103
+ /** Start input for the best-effort local runner, which uses configured host storage. */
104
+ export interface LocalStartWorkerInput extends StartWorkerInputBase {
105
+ runnerKind: "local";
106
+ volume?: never;
107
+ }
108
+
109
+ /** Start input for isolated runners, whose durable process volume is mandatory. */
110
+ export interface IsolatedStartWorkerInput extends StartWorkerInputBase {
111
+ runnerKind: "isolated";
112
+ volume: VolumeRef;
113
+ }
114
+
115
+ export type StartWorkerInput = LocalStartWorkerInput | IsolatedStartWorkerInput;
116
+
117
+ export interface StopWorkerOptions {
118
+ /** Grace period before forceful termination. The volume is always kept. */
119
+ graceMs: number;
120
+ }
121
+
122
+ export interface WorkerRunner<TStartInput extends StartWorkerInput = StartWorkerInput> {
123
+ start(input: TStartInput): Promise<WorkerUnit>;
124
+ /** Stops the unit but keeps the process volume for resume. */
125
+ stop(ref: WorkerUnitRef, opts: StopWorkerOptions): Promise<void>;
126
+ /** Adoption scan: lists labelled worker units. */
127
+ list(): Promise<WorkerUnitDescriptor[]>;
128
+ /** Reconnects to a live unit discovered by {@link WorkerRunner.list}. */
129
+ adopt(descriptor: WorkerUnitDescriptor): Promise<WorkerUnit>;
130
+ }