@leitwerk-dev/worker-runners 0.1.9 → 0.2.1

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 (161) hide show
  1. package/dist/{chunk-6WACBFXN.js → chunk-2P3CWUP3.js} +16 -5
  2. package/dist/chunk-2P3CWUP3.js.map +1 -0
  3. package/dist/chunk-4F7EMXMU.js +119 -0
  4. package/dist/chunk-4F7EMXMU.js.map +1 -0
  5. package/dist/chunk-6UZ2REWV.js +90 -0
  6. package/dist/chunk-6UZ2REWV.js.map +1 -0
  7. package/dist/{chunk-DL3Y3R6E.js → chunk-A3XSYWA5.js} +74 -8
  8. package/dist/chunk-A3XSYWA5.js.map +1 -0
  9. package/dist/{chunk-2TSWMVLZ.js → chunk-BRIIMAZX.js} +158 -39
  10. package/dist/chunk-BRIIMAZX.js.map +1 -0
  11. package/dist/{chunk-IRFVGUXJ.js → chunk-DFPYUJIK.js} +10 -3
  12. package/dist/chunk-DFPYUJIK.js.map +1 -0
  13. package/dist/{chunk-HLTGLGUS.js → chunk-H4JEE3ZT.js} +70 -93
  14. package/dist/chunk-H4JEE3ZT.js.map +1 -0
  15. package/dist/chunk-ISH4647R.js +506 -0
  16. package/dist/chunk-ISH4647R.js.map +1 -0
  17. package/dist/chunk-UGKQOL5E.js +39 -0
  18. package/dist/chunk-UGKQOL5E.js.map +1 -0
  19. package/dist/chunk-V7TTFLGE.js +899 -0
  20. package/dist/chunk-V7TTFLGE.js.map +1 -0
  21. package/dist/chunk-YDYI3BD2.js +315 -0
  22. package/dist/chunk-YDYI3BD2.js.map +1 -0
  23. package/dist/chunk-ZGFD76I6.js +16 -0
  24. package/dist/chunk-ZGFD76I6.js.map +1 -0
  25. package/dist/docker-client-public.d.ts +2 -0
  26. package/dist/docker-client-public.d.ts.map +1 -0
  27. package/dist/docker-client-public.js +7 -0
  28. package/dist/docker-client-public.js.map +1 -0
  29. package/dist/{docker-engine-client-Cpmy2yma.d.ts → docker-engine-client-Btw6ZTXk.d.ts} +48 -34
  30. package/dist/docker-engine-client.d.ts +47 -33
  31. package/dist/docker-engine-client.d.ts.map +1 -1
  32. package/dist/docker-engine-http-client.d.ts +18 -9
  33. package/dist/docker-engine-http-client.d.ts.map +1 -1
  34. package/dist/docker-engine-http-client.js +12 -201
  35. package/dist/docker-engine-http-client.js.map +1 -1
  36. package/dist/docker-public.d.ts +2 -0
  37. package/dist/docker-public.d.ts.map +1 -0
  38. package/dist/docker-public.js +13 -0
  39. package/dist/docker-public.js.map +1 -0
  40. package/dist/docker-worker-runner.d.ts +25 -8
  41. package/dist/docker-worker-runner.d.ts.map +1 -1
  42. package/dist/docker-worker-runner.js +12 -235
  43. package/dist/docker-worker-runner.js.map +1 -1
  44. package/dist/fake-docker-engine-client.d.ts.map +1 -1
  45. package/dist/filesystem-process-state-exporter.d.ts +10 -0
  46. package/dist/filesystem-process-state-exporter.d.ts.map +1 -0
  47. package/dist/helper-process-state-exporter.d.ts +28 -0
  48. package/dist/helper-process-state-exporter.d.ts.map +1 -0
  49. package/dist/index.d.ts +2 -11
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.js +46 -9
  52. package/dist/index.js.map +1 -1
  53. package/dist/kubernetes-api-client-CEe7pHC4.d.ts +453 -0
  54. package/dist/kubernetes-api-client.d.ts +113 -6
  55. package/dist/kubernetes-api-client.d.ts.map +1 -1
  56. package/dist/kubernetes-client-public.d.ts +2 -0
  57. package/dist/kubernetes-client-public.d.ts.map +1 -0
  58. package/dist/kubernetes-client-public.js +9 -0
  59. package/dist/kubernetes-client-public.js.map +1 -0
  60. package/dist/kubernetes-http-client.d.ts +11 -0
  61. package/dist/kubernetes-http-client.d.ts.map +1 -1
  62. package/dist/kubernetes-http-client.js +10 -295
  63. package/dist/kubernetes-http-client.js.map +1 -1
  64. package/dist/kubernetes-manifests.d.ts +189 -83
  65. package/dist/kubernetes-manifests.d.ts.map +1 -1
  66. package/dist/kubernetes-public.d.ts +2 -0
  67. package/dist/kubernetes-public.d.ts.map +1 -0
  68. package/dist/kubernetes-public.js +13 -0
  69. package/dist/kubernetes-public.js.map +1 -0
  70. package/dist/kubernetes-startup-sampler.d.ts +14 -0
  71. package/dist/kubernetes-startup-sampler.d.ts.map +1 -0
  72. package/dist/kubernetes-volume-pool-api.d.ts +114 -0
  73. package/dist/kubernetes-volume-pool-api.d.ts.map +1 -0
  74. package/dist/kubernetes-volume-pool.d.ts +41 -0
  75. package/dist/kubernetes-volume-pool.d.ts.map +1 -0
  76. package/dist/kubernetes-worker-runner.d.ts +46 -6
  77. package/dist/kubernetes-worker-runner.d.ts.map +1 -1
  78. package/dist/kubernetes-worker-runner.js +12 -161
  79. package/dist/kubernetes-worker-runner.js.map +1 -1
  80. package/dist/local-public.d.ts +2 -0
  81. package/dist/local-public.d.ts.map +1 -0
  82. package/dist/local-public.js +11 -0
  83. package/dist/local-public.js.map +1 -0
  84. package/dist/local-worker-runner.d.ts +22 -5
  85. package/dist/local-worker-runner.d.ts.map +1 -1
  86. package/dist/local-worker-runner.js +14 -108
  87. package/dist/local-worker-runner.js.map +1 -1
  88. package/dist/process-volume-retention.d.ts +15 -0
  89. package/dist/process-volume-retention.d.ts.map +1 -1
  90. package/dist/runner-utils.d.ts +8 -1
  91. package/dist/runner-utils.d.ts.map +1 -1
  92. package/dist/session-transfer-helper-cli.d.ts +2 -0
  93. package/dist/session-transfer-helper-cli.d.ts.map +1 -0
  94. package/dist/session-transfer-helper-cli.js +9 -0
  95. package/dist/session-transfer-helper-cli.js.map +1 -0
  96. package/dist/session-transfer-helper.d.ts +7 -0
  97. package/dist/session-transfer-helper.d.ts.map +1 -0
  98. package/dist/session-transfer-helper.js +11 -0
  99. package/dist/session-transfer-helper.js.map +1 -0
  100. package/dist/types-public.d.ts +3 -0
  101. package/dist/types-public.d.ts.map +1 -0
  102. package/dist/types-public.js +7 -0
  103. package/dist/types-public.js.map +1 -0
  104. package/dist/types.d.ts +140 -39
  105. package/dist/types.d.ts.map +1 -1
  106. package/dist/types.js +6 -11
  107. package/dist/types.js.map +1 -1
  108. package/dist/worker-labels.d.ts +36 -2
  109. package/dist/worker-labels.d.ts.map +1 -1
  110. package/package.json +26 -23
  111. package/src/docker-client-public.ts +1 -0
  112. package/src/docker-engine-client.ts +62 -36
  113. package/src/docker-engine-http-client.ts +90 -96
  114. package/src/docker-public.ts +1 -0
  115. package/src/docker-worker-runner.ts +194 -58
  116. package/src/fake-docker-engine-client.ts +13 -41
  117. package/src/filesystem-process-state-exporter.ts +42 -0
  118. package/src/helper-process-state-exporter.ts +149 -0
  119. package/src/index.ts +5 -94
  120. package/src/kubernetes-api-client.ts +179 -13
  121. package/src/kubernetes-client-public.ts +1 -0
  122. package/src/kubernetes-http-client.ts +239 -92
  123. package/src/kubernetes-manifests.ts +469 -345
  124. package/src/kubernetes-public.ts +1 -0
  125. package/src/kubernetes-startup-sampler.ts +191 -0
  126. package/src/kubernetes-volume-pool-api.ts +241 -0
  127. package/src/kubernetes-volume-pool.ts +375 -0
  128. package/src/kubernetes-worker-runner.ts +361 -44
  129. package/src/local-public.ts +1 -0
  130. package/src/local-worker-runner.ts +93 -10
  131. package/src/process-volume-retention.ts +15 -0
  132. package/src/runner-utils.ts +17 -2
  133. package/src/session-transfer-helper-cli.ts +5 -0
  134. package/src/session-transfer-helper.ts +108 -0
  135. package/src/types-public.ts +12 -0
  136. package/src/types.ts +169 -36
  137. package/src/worker-labels.ts +47 -2
  138. package/dist/chunk-2TSWMVLZ.js.map +0 -1
  139. package/dist/chunk-6WACBFXN.js.map +0 -1
  140. package/dist/chunk-DL3Y3R6E.js.map +0 -1
  141. package/dist/chunk-DUFA24LP.js +0 -401
  142. package/dist/chunk-DUFA24LP.js.map +0 -1
  143. package/dist/chunk-HLTGLGUS.js.map +0 -1
  144. package/dist/chunk-IRFVGUXJ.js.map +0 -1
  145. package/dist/chunk-P4DIFRBH.js +0 -187
  146. package/dist/chunk-P4DIFRBH.js.map +0 -1
  147. package/dist/docker-engine-client.js +0 -10
  148. package/dist/docker-engine-client.js.map +0 -1
  149. package/dist/fake-docker-engine-client.js +0 -131
  150. package/dist/fake-docker-engine-client.js.map +0 -1
  151. package/dist/kubernetes-api-client-BcwF2uon.d.ts +0 -286
  152. package/dist/kubernetes-api-client.js +0 -142
  153. package/dist/kubernetes-api-client.js.map +0 -1
  154. package/dist/kubernetes-manifests.js +0 -379
  155. package/dist/kubernetes-manifests.js.map +0 -1
  156. package/dist/process-volume-retention.js +0 -46
  157. package/dist/process-volume-retention.js.map +0 -1
  158. package/dist/runner-utils.js +0 -36
  159. package/dist/runner-utils.js.map +0 -1
  160. package/dist/worker-labels.js +0 -83
  161. package/dist/worker-labels.js.map +0 -1
@@ -1,10 +1,13 @@
1
- import { type ChildProcess, spawn } from "node:child_process";
1
+ import { type ChildProcess, execFile, spawn } from "node:child_process";
2
2
  import { existsSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
+ import { promisify } from "node:util";
6
+ import { createFilesystemProcessStateExporter } from "./filesystem-process-state-exporter.js";
5
7
  import { UnitExitNotifier } from "./runner-utils.js";
6
8
  import type {
7
9
  LocalStartWorkerInput,
10
+ ProcessStateExporter,
8
11
  StopWorkerOptions,
9
12
  WorkerExitInfo,
10
13
  WorkerRunner,
@@ -13,17 +16,46 @@ import type {
13
16
  WorkerUnitRef,
14
17
  } from "./types.js";
15
18
 
19
+ /** @internal */
16
20
  export const DEFAULT_LOCAL_WORKER_ENTRY_SPECIFIER = "@leitwerk-dev/worker/worker-entry";
17
21
 
22
+ /** @internal */
18
23
  export interface LocalWorkerRunnerOptions {
19
- /** Command used to launch the worker. Defaults to `node`. */
24
+ /** Command used to launch the worker. Defaults to `node`. @internal */
20
25
  command?: string;
21
- /** Worker entry args. The default package subpath is resolved to the installed entry file. */
26
+ /** Worker entry args. The default package subpath is resolved to the installed entry file. @internal */
22
27
  args?: readonly string[];
23
- /** Working directory for the spawned worker. Defaults to the installed server package dir. */
28
+ /** Working directory for the spawned worker. Defaults to the installed server package dir. @internal */
24
29
  cwd?: string;
25
- /** Test seam. Production uses node's spawn directly. */
30
+ /** Process storage roots used by the read-only session exporter. @internal */
31
+ processWorkspacesDir?: string;
32
+ /** @internal */
33
+ treeFilesDir?: string;
34
+ /** Explicit acknowledgement that Docker processes inherit host Docker authority. @internal */
35
+ allowHostDocker?: boolean;
36
+ /** Test seam. Production uses node's spawn directly. @internal */
26
37
  localWorkerSpawnImpl?: typeof spawn;
38
+ /** Test seam for the shared host-Docker preflight. @internal */
39
+ dockerPreflightImpl?: (timeoutMs: number) => Promise<void>;
40
+ }
41
+
42
+ /** Verifies that the inherited Docker CLI context can reach its daemon. @internal */
43
+ export async function preflightHostDocker(timeoutMs: number): Promise<void> {
44
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
45
+ throw new Error("Docker preflight requires a positive startup timeout");
46
+ }
47
+ try {
48
+ await promisify(execFile)("docker", ["info"], {
49
+ env: process.env,
50
+ timeout: timeoutMs,
51
+ killSignal: "SIGKILL",
52
+ });
53
+ } catch (error) {
54
+ if (error && typeof error === "object" && "killed" in error && error.killed) {
55
+ throw new Error(`Docker preflight timed out after ${timeoutMs}ms`, { cause: error });
56
+ }
57
+ throw error;
58
+ }
27
59
  }
28
60
 
29
61
  interface LocalWorkerUnitState {
@@ -54,6 +86,7 @@ function resolveDefaultWorkerEntryPath(): string {
54
86
  return fileURLToPath(import.meta.resolve(DEFAULT_LOCAL_WORKER_ENTRY_SPECIFIER));
55
87
  }
56
88
 
89
+ /** @internal */
57
90
  export function resolveLocalWorkerSpawnArgs(args: readonly string[]): string[] {
58
91
  return args[0] === DEFAULT_LOCAL_WORKER_ENTRY_SPECIFIER
59
92
  ? [resolveDefaultWorkerEntryPath(), ...args.slice(1)]
@@ -72,13 +105,18 @@ function exitInfo(code: number | null, signal: NodeJS.Signals | null): WorkerExi
72
105
  * boundary, has no restart adoption, and ignores image/resource profile semantics.
73
106
  * Docker and Kubernetes remain the contract-defining production runners.
74
107
  */
108
+ /** @internal */
75
109
  export function createLocalWorkerRunner(options: LocalWorkerRunnerOptions): {
110
+ /** @internal */
76
111
  runner: WorkerRunner<LocalStartWorkerInput>;
112
+ /** @internal */
113
+ exporter: ProcessStateExporter;
77
114
  } {
78
115
  const command = options.command ?? "node";
79
116
  const args = resolveLocalWorkerSpawnArgs(options.args ?? [DEFAULT_LOCAL_WORKER_ENTRY_SPECIFIER]);
80
117
  const cwd = options.cwd ?? findServerPackageDir();
81
118
  const localWorkerSpawnImpl = options.localWorkerSpawnImpl ?? spawn;
119
+ const dockerPreflightImpl = options.dockerPreflightImpl ?? preflightHostDocker;
82
120
  const units = new Map<string, LocalWorkerUnitState>();
83
121
  const exitNotifier = new UnitExitNotifier();
84
122
 
@@ -87,16 +125,50 @@ export function createLocalWorkerRunner(options: LocalWorkerRunnerOptions): {
87
125
  }
88
126
 
89
127
  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");
128
+ async start(input: LocalStartWorkerInput, observer): Promise<WorkerUnit> {
129
+ observer?.report("preparing_runtime");
130
+ if (input.docker) {
131
+ if (options.allowHostDocker !== true) {
132
+ throw new Error("Docker-requiring processes need local_worker.allow_host_docker: true");
133
+ }
134
+ try {
135
+ const configuredTimeoutMs = Number.parseInt(
136
+ input.env.LEITWERK_WORKER_STARTUP_TIMEOUT_MS ?? "30000",
137
+ 10,
138
+ );
139
+ const deadlineMs = Number.parseInt(
140
+ input.env.LEITWERK_WORKER_STARTUP_DEADLINE_MS ?? "",
141
+ 10,
142
+ );
143
+ const timeoutMs = Number.isFinite(deadlineMs)
144
+ ? Math.min(configuredTimeoutMs, deadlineMs - Date.now())
145
+ : configuredTimeoutMs;
146
+ if (timeoutMs <= 0)
147
+ throw new Error("Worker startup deadline expired before Docker preflight");
148
+ await dockerPreflightImpl(timeoutMs);
149
+ if (Date.now() >= deadlineMs) {
150
+ throw new Error("Worker startup deadline expired during Docker preflight");
151
+ }
152
+ } catch (error) {
153
+ throw new Error("Local Docker preflight failed: Docker CLI or daemon is unavailable", {
154
+ cause: error,
155
+ });
156
+ }
93
157
  }
94
158
  const unitId = nextUnitId(input.instanceId, input.workerId);
95
159
  const ref: WorkerUnitRef = { instanceId: input.instanceId, workerId: input.workerId, unitId };
160
+ observer?.report("starting_runtime");
96
161
  const child = localWorkerSpawnImpl(command, args, {
97
162
  cwd,
98
163
  stdio: ["ignore", "inherit", "inherit"],
99
- env: { ...process.env, ...input.env },
164
+ env: {
165
+ ...Object.fromEntries(
166
+ Object.entries(process.env).filter(
167
+ ([key]) => !/(?:^|_)(?:TOKEN|API_KEY|PASSWORD|SECRET)$/.test(key),
168
+ ),
169
+ ),
170
+ ...input.env,
171
+ },
100
172
  });
101
173
  const state: LocalWorkerUnitState = {
102
174
  ref,
@@ -141,5 +213,16 @@ export function createLocalWorkerRunner(options: LocalWorkerRunnerOptions): {
141
213
  },
142
214
  };
143
215
 
144
- return { runner };
216
+ const processWorkspacesDir = path.resolve(
217
+ options.processWorkspacesDir ?? "/tmp/leitwerk/workspaces",
218
+ );
219
+ const treeFilesDir = path.resolve(options.treeFilesDir ?? "/tmp/leitwerk/trees");
220
+ const exporter = createFilesystemProcessStateExporter({
221
+ allowedRoots: [processWorkspacesDir, treeFilesDir],
222
+ resolveSource: (instanceId) => ({
223
+ workspaceRoot: path.join(processWorkspacesDir, instanceId),
224
+ sessionFile: path.join(treeFilesDir, `${instanceId}.jsonl`),
225
+ }),
226
+ });
227
+ return { runner, exporter };
145
228
  }
@@ -2,15 +2,23 @@ import type { ProcessInstance } from "@leitwerk-dev/domain";
2
2
  import { parseDurationMs } from "@leitwerk-dev/watcher-utils";
3
3
  import type { ProcessVolume } from "./types.js";
4
4
 
5
+ /** @internal */
5
6
  export interface ProcessVolumeRetentionPolicy {
7
+ /** @internal */
6
8
  completedProcessRetention: string;
9
+ /** @internal */
7
10
  errorProcessRetention: string;
8
11
  }
9
12
 
13
+ /** @internal */
10
14
  export interface PlanProcessVolumeRetentionCleanupInput {
15
+ /** @internal */
11
16
  processes: readonly ProcessInstance[];
17
+ /** @internal */
12
18
  now: Date;
19
+ /** @internal */
13
20
  policy: ProcessVolumeRetentionPolicy;
21
+ /** @internal */
14
22
  alreadyReleased?: ReadonlySet<string>;
15
23
  }
16
24
 
@@ -26,6 +34,7 @@ function closedAtMs(process: ProcessInstance): number | null {
26
34
  return Number.isFinite(parsed) ? parsed : null;
27
35
  }
28
36
 
37
+ /** @internal */
29
38
  export function planProcessVolumeRetentionCleanup(
30
39
  input: PlanProcessVolumeRetentionCleanupInput,
31
40
  ): string[] {
@@ -55,11 +64,17 @@ export function planProcessVolumeRetentionCleanup(
55
64
  return candidates;
56
65
  }
57
66
 
67
+ /** @internal */
58
68
  export async function cleanupRetainedProcessVolumes(input: {
69
+ /** @internal */
59
70
  volume?: ProcessVolume;
71
+ /** @internal */
60
72
  processes: readonly ProcessInstance[];
73
+ /** @internal */
61
74
  now: Date;
75
+ /** @internal */
62
76
  policy: ProcessVolumeRetentionPolicy;
77
+ /** @internal */
63
78
  alreadyReleased?: ReadonlySet<string>;
64
79
  }): Promise<string[]> {
65
80
  const candidates = planProcessVolumeRetentionCleanup(input);
@@ -7,10 +7,12 @@ import type { WorkerExitInfo, WorkerUnit, WorkerUnitRef } from "./types.js";
7
7
  * `WorkerUnit.onExit` callbacks. This utility captures the identical map +
8
8
  * fire/wrap logic and leaves only the unit-keying to each runner.
9
9
  */
10
+ /** @internal */
10
11
  export class UnitExitNotifier {
11
12
  private readonly listeners = new Map<string, Array<(info: WorkerExitInfo) => void>>();
12
13
  private readonly exited = new Map<string, WorkerExitInfo>();
13
14
 
15
+ /** @internal */
14
16
  onExit(key: string, listener: (info: WorkerExitInfo) => void): void {
15
17
  const exit = this.exited.get(key);
16
18
  if (exit) {
@@ -22,6 +24,7 @@ export class UnitExitNotifier {
22
24
  this.listeners.set(key, list);
23
25
  }
24
26
 
27
+ /** @internal */
25
28
  fireExit(key: string, info: WorkerExitInfo): void {
26
29
  if (this.exited.has(key)) return;
27
30
  this.exited.set(key, info);
@@ -31,7 +34,19 @@ export class UnitExitNotifier {
31
34
  for (const listener of list.splice(0)) listener(info);
32
35
  }
33
36
 
34
- wrapUnit<T extends WorkerUnitRef>(ref: T, key: string): WorkerUnit {
35
- return { ...ref, onExit: (listener) => this.onExit(key, listener) };
37
+ /** @internal */
38
+ wrapUnit<T extends WorkerUnitRef>(
39
+ ref: T,
40
+ key: string,
41
+ options?: {
42
+ /** @internal */
43
+ replacementHandoff?: WorkerUnit["replacementHandoff"];
44
+ },
45
+ ): WorkerUnit {
46
+ return {
47
+ ...ref,
48
+ ...(options?.replacementHandoff ? { replacementHandoff: options.replacementHandoff } : {}),
49
+ onExit: (listener) => this.onExit(key, listener),
50
+ };
36
51
  }
37
52
  }
@@ -0,0 +1,5 @@
1
+ import { runSessionTransferHelper } from "./session-transfer-helper.js";
2
+
3
+ runSessionTransferHelper().catch(() => {
4
+ process.exitCode = 1;
5
+ });
@@ -0,0 +1,108 @@
1
+ import path from "node:path";
2
+ import { Readable } from "node:stream";
3
+ import {
4
+ parseSessionTransferHelperSpec,
5
+ prepareTransferArchive,
6
+ } from "@leitwerk-dev/session-transfer";
7
+
8
+ /** @internal */
9
+ export const SESSION_TRANSFER_HELPER_ENTRY_PATH =
10
+ "/app/packages/worker-runners/dist/session-transfer-helper-cli.js";
11
+ /** @internal */
12
+ export const SESSION_TRANSFER_HELPER_MOUNT_PATH = "/state";
13
+
14
+ interface HelperEnvironment {
15
+ exportId: string;
16
+ credential: string;
17
+ serverUrl: URL;
18
+ }
19
+
20
+ function required(name: string): string {
21
+ const value = process.env[name]?.trim();
22
+ if (!value) throw new Error(`Missing ${name}`);
23
+ return value;
24
+ }
25
+
26
+ function readEnvironment(): HelperEnvironment {
27
+ const serverUrl = new URL(required("LEITWERK_EXPORT_SERVER_URL"));
28
+ if (!/^https?:$/.test(serverUrl.protocol) || serverUrl.username || serverUrl.password) {
29
+ throw new Error("Invalid helper server URL");
30
+ }
31
+ return {
32
+ exportId: required("LEITWERK_EXPORT_ID"),
33
+ credential: required("LEITWERK_EXPORT_CREDENTIAL"),
34
+ serverUrl,
35
+ };
36
+ }
37
+
38
+ function helperUrl(environment: HelperEnvironment, suffix: string): URL {
39
+ return new URL(
40
+ `/internal/session-transfer-exports/${encodeURIComponent(environment.exportId)}${suffix}`,
41
+ environment.serverUrl,
42
+ );
43
+ }
44
+
45
+ async function helperFetch(
46
+ environment: HelperEnvironment,
47
+ suffix: string,
48
+ init: RequestInit & { duplex?: "half" },
49
+ ): Promise<Response> {
50
+ const response = await fetch(helperUrl(environment, suffix), {
51
+ ...init,
52
+ redirect: "manual",
53
+ headers: {
54
+ ...init.headers,
55
+ Authorization: `Bearer ${environment.credential}`,
56
+ },
57
+ });
58
+ if (response.status < 200 || response.status >= 300) {
59
+ throw new Error(`Helper request failed with HTTP ${response.status}`);
60
+ }
61
+ return response;
62
+ }
63
+
64
+ async function helperRequest(
65
+ environment: HelperEnvironment,
66
+ suffix: string,
67
+ init: RequestInit & { duplex?: "half" },
68
+ ): Promise<void> {
69
+ const response = await helperFetch(environment, suffix, init);
70
+ await response.arrayBuffer();
71
+ }
72
+
73
+ async function readHelperSpec(environment: HelperEnvironment) {
74
+ const response = await helperFetch(environment, "/spec", { method: "GET" });
75
+ return parseSessionTransferHelperSpec(await response.json());
76
+ }
77
+
78
+ /** @internal */
79
+ export async function runSessionTransferHelper(): Promise<void> {
80
+ const environment = readEnvironment();
81
+ const spec = await readHelperSpec(environment);
82
+ const workspaceRoot = path.join(SESSION_TRANSFER_HELPER_MOUNT_PATH, "workspace");
83
+ const sessionFile = path.join(SESSION_TRANSFER_HELPER_MOUNT_PATH, "tree", "primary.jsonl");
84
+ const prepared = await prepareTransferArchive({
85
+ workspaceRoot,
86
+ sessionFile,
87
+ manifest: spec.manifest,
88
+ limits: spec.limits,
89
+ });
90
+ await helperRequest(environment, "/preflight", {
91
+ method: "POST",
92
+ headers: { "Content-Type": "application/json" },
93
+ body: JSON.stringify({
94
+ manifest: prepared.manifest,
95
+ preflight: {
96
+ entriesTotal: prepared.preflight.entriesTotal,
97
+ logicalBytesTotal: prepared.preflight.logicalBytesTotal,
98
+ },
99
+ }),
100
+ });
101
+ const archive = prepared.stream({});
102
+ await helperRequest(environment, "/stream", {
103
+ method: "PUT",
104
+ headers: { "Content-Type": "application/vnd.leitwerk.session-transfer+tar+zstd" },
105
+ body: Readable.toWeb(archive) as ReadableStream,
106
+ duplex: "half",
107
+ });
108
+ }
@@ -0,0 +1,12 @@
1
+ export type {
2
+ ProcessVolume,
3
+ ResolvedWorkerImage,
4
+ StopWorkerOptions,
5
+ WorkerExitInfo,
6
+ WorkerRunner,
7
+ WorkerStartObserver,
8
+ WorkerUnit,
9
+ WorkerUnitDescriptor,
10
+ WorkerUnitRef,
11
+ } from "./types.js";
12
+ export { WorkerStartDiagnosticError } from "./types.js";
package/src/types.ts CHANGED
@@ -1,3 +1,11 @@
1
+ import type { Readable } from "node:stream";
2
+ import type {
3
+ LeitwerkTransferManifestV1,
4
+ SessionTransferLimits,
5
+ SessionTransferPreflight,
6
+ SessionTransferPreflightReport,
7
+ } from "@leitwerk-dev/session-transfer";
8
+
1
9
  /**
2
10
  * Runner API seams shared by worker run modes (Docker, Kubernetes, best-effort local).
3
11
  *
@@ -16,22 +24,97 @@
16
24
  * state over the protocol (the session-snapshot exchange), never by reading the
17
25
  * volume, which keeps every run mode symmetric.
18
26
  */
27
+ /** @internal */
19
28
  export interface VolumeRef {
29
+ /** @internal */
20
30
  instanceId: string;
21
- /** Runtime-specific identifier (host path, named volume, PVC name). */
31
+ /** Runtime-specific identifier (host path, named volume, PVC name). @internal */
22
32
  id: string;
23
- /** Path inside the worker container where the volume is mounted. */
33
+ /** Path inside the worker container where the volume is mounted. @internal */
24
34
  mountPath: string;
25
- /** Runtime-specific namespace/project for the volume (Kubernetes process namespace). */
35
+ /** Runtime-specific namespace/project for the volume (Kubernetes process namespace). @internal */
26
36
  namespace?: string;
27
37
  }
28
38
 
39
+ /** @internal */
40
+ export interface ProcessVolumeRequirements {
41
+ /** New Kubernetes PVC capacity. Existing volumes are unchanged; other runners ignore it. @internal */
42
+ size?: string;
43
+ /** Select storage compatible with a private Docker daemon. @internal */
44
+ docker?: boolean;
45
+ }
46
+
47
+ /** @internal */
48
+ export type ProcessStateExportPreflight = SessionTransferPreflight;
49
+ /** @internal */
50
+ export type ProcessStateExportHelperReport = SessionTransferPreflightReport;
51
+
52
+ /** Server-owned, credential-scoped relay used by isolated export helpers. @internal */
53
+ export interface ProcessStateExportHelperRelay {
54
+ /** @internal */
55
+ readonly exportId: string;
56
+ /** @internal */
57
+ readonly credential: string;
58
+ /** @internal */
59
+ waitForPreflight(signal?: AbortSignal): Promise<ProcessStateExportHelperReport>;
60
+ /** @internal */
61
+ activateStream(): Readable;
62
+ /** @internal */
63
+ fail(error: Error): void;
64
+ }
65
+
66
+ /** @internal */
67
+ export interface PreparedProcessStateExport {
68
+ /** @internal */
69
+ manifest: LeitwerkTransferManifestV1;
70
+ /** @internal */
71
+ preflight: ProcessStateExportPreflight;
72
+ /** @internal */
73
+ stream(input: {
74
+ /** @internal */
75
+ signal?: AbortSignal;
76
+ }): Readable;
77
+ }
78
+
79
+ /** Purpose-specific read-only export seam. It never creates a worker lease. @internal */
80
+ export interface ProcessStateExporter {
81
+ /** @internal */
82
+ prepare(input: {
83
+ /** @internal */
84
+ instanceId: string;
85
+ /** @internal */
86
+ manifest: LeitwerkTransferManifestV1;
87
+ /** @internal */
88
+ limits: SessionTransferLimits;
89
+ /** @internal */
90
+ signal?: AbortSignal;
91
+ }): Promise<PreparedProcessStateExport>;
92
+ /** Removes stale runner-specific export helpers after restart. @internal */
93
+ reconcile(): Promise<void>;
94
+ }
95
+
96
+ /** @internal */
97
+ export interface ProcessStateExportHelperRelayProvider {
98
+ /** @internal */
99
+ create(input: {
100
+ /** @internal */
101
+ instanceId: string;
102
+ /** @internal */
103
+ manifest: LeitwerkTransferManifestV1;
104
+ }): ProcessStateExportHelperRelay;
105
+ }
106
+
107
+ /** @internal */
29
108
  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. */
109
+ /** Idempotently provisions durable storage for a process instance. @internal */
110
+ ensure(
111
+ instanceId: string,
112
+ requirements?: ProcessVolumeRequirements,
113
+ observer?: WorkerStartObserver,
114
+ ): Promise<VolumeRef>;
115
+ /** Retention cleanup only. Stopping a worker never calls this. @internal */
33
116
  release(instanceId: string): Promise<void>;
34
- /** Permanently deletes every runner-managed resource owned by a deleted process. */
117
+ /** Permanently deletes every runner-managed resource owned by a deleted process. @internal */
35
118
  deleteProcessResources(instanceId: string): Promise<void>;
36
119
  }
37
120
 
@@ -39,92 +122,142 @@ export interface ProcessVolume {
39
122
  * Output of runtime-profile selection. MVP resolves to a single configured
40
123
  * worker image; repository branch content must never select an image.
41
124
  */
125
+ /** @internal */
42
126
  export interface ResolvedWorkerImage {
43
- /** Fully qualified image reference, ideally digest-pinned. */
127
+ /** Fully qualified image reference, ideally digest-pinned. @internal */
44
128
  reference: string;
45
129
  }
46
130
 
131
+ /** @internal */
47
132
  export interface WorkerResourceLimits {
133
+ /** @internal */
48
134
  cpu?: string;
135
+ /** @internal */
49
136
  memory?: string;
50
137
  }
51
138
 
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
-
139
+ /** @internal */
62
140
  export interface WorkerUnitRef {
141
+ /** @internal */
63
142
  instanceId: string;
143
+ /** @internal */
64
144
  workerId: string;
65
- /** Runtime-specific handle id (container id, pod name). */
145
+ /** Runtime-specific handle id (container id, pod name). @internal */
66
146
  unitId: string;
67
- /** Runtime-specific namespace/project for the unit (Kubernetes process namespace). */
147
+ /** Runtime-specific namespace/project for the unit (Kubernetes process namespace). @internal */
68
148
  namespace?: string;
69
149
  }
70
150
 
151
+ /** @internal */
152
+ export class WorkerStartDiagnosticError extends Error {
153
+ /** @internal */
154
+ readonly publicDiagnostic: string;
155
+
156
+ /** @internal */
157
+ constructor(publicDiagnostic: string, cause?: unknown) {
158
+ super("Worker runtime start failed", { cause });
159
+ this.name = "WorkerStartDiagnosticError";
160
+ this.publicDiagnostic = publicDiagnostic;
161
+ }
162
+ }
163
+
164
+ /** @internal */
71
165
  export interface WorkerExitInfo {
72
- /** Process exit code when the runtime reports one. */
166
+ /** Process exit code when the runtime reports one. @internal */
73
167
  exitCode: number | null;
74
- /** Termination signal when the runtime reports one. */
168
+ /** Termination signal when the runtime reports one. @internal */
75
169
  signal: string | null;
76
- /** True when the runtime killed the unit for exceeding memory limits. */
170
+ /** True when the runtime killed the unit for exceeding memory limits. @internal */
77
171
  oomKilled?: boolean;
78
- /** Human-readable reason surfaced by the runtime, if any. */
172
+ /** Human-readable reason surfaced by the runtime, if any. @internal */
79
173
  reason?: string;
80
174
  }
81
175
 
176
+ /** @internal */
82
177
  export interface WorkerUnit extends WorkerUnitRef {
83
- /** Maps physical worker exit into the supervisor's existing failure paths. */
178
+ /** Require successful runtime removal before the supervisor permits replacement. @internal */
179
+ replacementHandoff?: "stop-before-replacement";
180
+ /** Maps physical worker exit into the supervisor's existing failure paths. @internal */
84
181
  onExit(listener: (info: WorkerExitInfo) => void): void;
85
182
  }
86
183
 
184
+ /** @internal */
87
185
  export interface WorkerUnitDescriptor extends WorkerUnitRef {
186
+ /** @internal */
88
187
  observedState?: "running" | "pending" | "terminal" | "unknown";
89
188
  }
90
189
 
190
+ /** @internal */
91
191
  interface StartWorkerInputBase {
192
+ /** @internal */
92
193
  instanceId: string;
194
+ /** @internal */
93
195
  workerId: string;
196
+ /** @internal */
94
197
  serverEpoch: string;
95
- /** Runtime-profile selection output; MVP = single image. */
198
+ /** Runtime-profile selection output; MVP = single image. @internal */
96
199
  image: ResolvedWorkerImage;
97
- /** Server URL, ids, connect token, `PI_CODING_AGENT_DIR`, etc. */
200
+ /** Server URL, ids, connect token, `PI_CODING_AGENT_DIR`, etc. @internal */
98
201
  env: Record<string, string>;
99
- isolation: WorkerIsolation;
202
+ /** Start the image's private Docker daemon before the worker. @internal */
203
+ docker: boolean;
204
+ /** @internal */
100
205
  resources?: WorkerResourceLimits;
206
+ /** @internal */
207
+ resourceRequests?: WorkerResourceLimits;
101
208
  }
102
209
 
103
- /** Start input for the best-effort local runner, which uses configured host storage. */
210
+ /** Start input for the best-effort local runner, which uses configured host storage. @internal */
104
211
  export interface LocalStartWorkerInput extends StartWorkerInputBase {
212
+ /** @internal */
105
213
  runnerKind: "local";
214
+ /** @internal */
106
215
  volume?: never;
107
216
  }
108
217
 
109
- /** Start input for isolated runners, whose durable process volume is mandatory. */
218
+ /** Start input for isolated runners, whose durable process volume is mandatory. @internal */
110
219
  export interface IsolatedStartWorkerInput extends StartWorkerInputBase {
220
+ /** @internal */
111
221
  runnerKind: "isolated";
222
+ /** @internal */
112
223
  volume: VolumeRef;
113
224
  }
114
225
 
226
+ /** @internal */
115
227
  export type StartWorkerInput = LocalStartWorkerInput | IsolatedStartWorkerInput;
116
228
 
229
+ /** @internal */
117
230
  export interface StopWorkerOptions {
118
- /** Grace period before forceful termination. The volume is always kept. */
231
+ /** Grace period before forceful termination. The volume is always kept. @internal */
119
232
  graceMs: number;
120
233
  }
121
234
 
235
+ /** @internal */
236
+ export type WorkerStartPhase = "preparing_runtime" | "allocating_runtime" | "starting_runtime";
237
+
238
+ /** @internal */
239
+ export interface WorkerStartObserver {
240
+ /** @internal */
241
+ observe?(
242
+ observation: Omit<
243
+ import("@leitwerk-dev/domain").StartupObservation,
244
+ "workerLeaseId" | "turnRecordId"
245
+ >,
246
+ ): void;
247
+ /** @internal */
248
+ shouldStop?(): boolean;
249
+ /** @internal */
250
+ report(phase: WorkerStartPhase): void;
251
+ }
252
+
253
+ /** @internal */
122
254
  export interface WorkerRunner<TStartInput extends StartWorkerInput = StartWorkerInput> {
123
- start(input: TStartInput): Promise<WorkerUnit>;
124
- /** Stops the unit but keeps the process volume for resume. */
255
+ /** @internal */
256
+ start(input: TStartInput, observer?: WorkerStartObserver): Promise<WorkerUnit>;
257
+ /** Stops the unit but keeps the process volume for resume. @internal */
125
258
  stop(ref: WorkerUnitRef, opts: StopWorkerOptions): Promise<void>;
126
- /** Adoption scan: lists labelled worker units. */
259
+ /** Adoption scan: lists labelled worker units. @internal */
127
260
  list(): Promise<WorkerUnitDescriptor[]>;
128
- /** Reconnects to a live unit discovered by {@link WorkerRunner.list}. */
129
- adopt(descriptor: WorkerUnitDescriptor): Promise<WorkerUnit>;
261
+ /** Reconnects to a live unit discovered by {@link WorkerRunner.list}. @internal */
262
+ adopt(descriptor: WorkerUnitDescriptor, observer?: WorkerStartObserver): Promise<WorkerUnit>;
130
263
  }