@leitwerk-dev/worker-protocol 0.1.8 → 0.2.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 (39) hide show
  1. package/dist/docker-config.d.ts +23 -0
  2. package/dist/docker-config.d.ts.map +1 -0
  3. package/dist/index.d.ts +1 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +512 -10
  6. package/dist/index.js.map +1 -1
  7. package/dist/ipc-decode.d.ts.map +1 -1
  8. package/dist/ipc-messages.d.ts +66 -14
  9. package/dist/ipc-messages.d.ts.map +1 -1
  10. package/dist/testing.d.ts +9 -0
  11. package/dist/testing.d.ts.map +1 -1
  12. package/dist/worker-api-version.d.ts +1 -1
  13. package/dist/worker-result-image.js +28 -54
  14. package/dist/worker-result-image.js.map +1 -1
  15. package/package.json +4 -4
  16. package/src/docker-config.ts +38 -0
  17. package/src/index.ts +1 -0
  18. package/src/ipc-decode.ts +3 -0
  19. package/src/ipc-messages.ts +71 -16
  20. package/src/testing.ts +17 -0
  21. package/src/worker-api-version.ts +1 -1
  22. package/dist/ipc-codec.js +0 -48
  23. package/dist/ipc-codec.js.map +0 -1
  24. package/dist/ipc-decode.js +0 -71
  25. package/dist/ipc-decode.js.map +0 -1
  26. package/dist/ipc-messages.js +0 -14
  27. package/dist/ipc-messages.js.map +0 -1
  28. package/dist/pi-resource-bundle.js +0 -139
  29. package/dist/pi-resource-bundle.js.map +0 -1
  30. package/dist/pi-resource-manifest.js +0 -101
  31. package/dist/pi-resource-manifest.js.map +0 -1
  32. package/dist/testing.js +0 -33
  33. package/dist/testing.js.map +0 -1
  34. package/dist/worker-api-version.js +0 -9
  35. package/dist/worker-api-version.js.map +0 -1
  36. package/dist/worker-ipc-transport.js +0 -8
  37. package/dist/worker-ipc-transport.js.map +0 -1
  38. package/dist/worker-session-snapshot.js +0 -8
  39. package/dist/worker-session-snapshot.js.map +0 -1
@@ -0,0 +1,23 @@
1
+ import * as v from "valibot";
2
+ export declare const dockerRegistryCredentialSchema: v.ObjectSchema<{
3
+ readonly registry: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>;
4
+ readonly username: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.NonEmptyAction<string, undefined>, v.RegexAction<string, undefined>]>;
5
+ readonly password: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.NonEmptyAction<string, undefined>]>;
6
+ }, undefined>;
7
+ export declare const ipAddressSchema: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.NonEmptyAction<string, undefined>, v.CheckAction<string, "Expected an IPv4 or IPv6 address">]>;
8
+ export type DockerNetworkConfig = v.InferOutput<typeof dockerNetworkSchema>;
9
+ export declare const dockerNetworkSchema: v.StrictObjectSchema<{
10
+ readonly bridge_cidr: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, undefined>]>;
11
+ readonly address_pools: v.SchemaWithPipe<readonly [v.ArraySchema<v.SchemaWithPipe<readonly [v.StrictObjectSchema<{
12
+ readonly base: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, undefined>]>;
13
+ readonly size: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MaxValueAction<number, 30, undefined>]>;
14
+ }, undefined>, v.CheckAction<{
15
+ base: string;
16
+ size: number;
17
+ }, undefined>]>, undefined>, v.NonEmptyAction<{
18
+ base: string;
19
+ size: number;
20
+ }[], undefined>]>;
21
+ readonly dns: v.SchemaWithPipe<readonly [v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.NonEmptyAction<string, undefined>, v.CheckAction<string, "Expected an IPv4 or IPv6 address">]>, undefined>, v.NonEmptyAction<string[], undefined>]>;
22
+ }, undefined>;
23
+ //# sourceMappingURL=docker-config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"docker-config.d.ts","sourceRoot":"","sources":["../src/docker-config.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,CAAC,MAAM,SAAS,CAAC;AAE7B,eAAO,MAAM,8BAA8B;;;;aAIzC,CAAC;AAEH,eAAO,MAAM,eAAe,wJAI3B,CAAC;AAOF,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,WAAW,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAE5E,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;aAe9B,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export * from "./docker-config.js";
1
2
  export * from "./ipc-codec.js";
2
3
  export * from "./ipc-decode.js";
3
4
  export * from "./ipc-messages.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,cAAc,CAAC;AAC7B,cAAc,yBAAyB,CAAC;AACxC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,0BAA0B,CAAC;AACzC,cAAc,8BAA8B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC;AACnC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,cAAc,CAAC;AAC7B,cAAc,yBAAyB,CAAC;AACxC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,0BAA0B,CAAC;AACzC,cAAc,8BAA8B,CAAC"}
package/dist/index.js CHANGED
@@ -1,11 +1,513 @@
1
- export * from "./ipc-codec.js";
2
- export * from "./ipc-decode.js";
3
- export * from "./ipc-messages.js";
4
- export * from "./pi-resource-bundle.js";
5
- export * from "./pi-resource-manifest.js";
6
- export * from "./testing.js";
7
- export * from "./worker-api-version.js";
8
- export * from "./worker-ipc-transport.js";
9
- export * from "./worker-result-image.js";
10
- export * from "./worker-session-snapshot.js";
1
+ import {
2
+ RESULT_IMAGE_ID_PATTERN,
3
+ RESULT_IMAGE_MAX_SIZE_BYTES,
4
+ RESULT_IMAGE_MIME_TYPES,
5
+ RESULT_IMAGE_STORAGE_SEGMENT_PATTERN,
6
+ WORKER_RESULT_IMAGE_WORKER_ID_HEADER,
7
+ buildManagedResultImagePath,
8
+ buildWorkerResultImageUploadPath,
9
+ isResultImageStorageSegment,
10
+ parseManagedResultImagePath,
11
+ parseResultImageId,
12
+ parseWorkerResultImageUploadResponse,
13
+ workerResultImageUploadResponseSchema
14
+ } from "./chunk-DVN32ANP.js";
15
+
16
+ // src/docker-config.ts
17
+ import { isIP } from "net";
18
+ import * as v from "valibot";
19
+ var dockerRegistryCredentialSchema = v.object({
20
+ registry: v.pipe(v.string(), v.regex(/^[a-z0-9]+(?:[.-][a-z0-9]+)*(?::[0-9]{1,5})?$/)),
21
+ username: v.pipe(v.string(), v.nonEmpty(), v.regex(/^[^:\r\n\0]+$/)),
22
+ password: v.pipe(v.string(), v.nonEmpty())
23
+ });
24
+ var ipAddressSchema = v.pipe(
25
+ v.string(),
26
+ v.nonEmpty(),
27
+ v.check((value) => isIP(value) !== 0, "Expected an IPv4 or IPv6 address")
28
+ );
29
+ var ipv4CidrSchema = v.pipe(
30
+ v.string(),
31
+ v.check(
32
+ (value) => /^.+\/(?:[1-9]|[12][0-9]|30)$/.test(value) && isIP(value.split("/")[0] ?? "") === 4
33
+ )
34
+ );
35
+ var dockerNetworkSchema = v.strictObject({
36
+ bridge_cidr: ipv4CidrSchema,
37
+ address_pools: v.pipe(
38
+ v.array(
39
+ v.pipe(
40
+ v.strictObject({
41
+ base: ipv4CidrSchema,
42
+ size: v.pipe(v.number(), v.integer(), v.maxValue(30))
43
+ }),
44
+ v.check((pool) => pool.size >= Number(pool.base.split("/")[1]))
45
+ )
46
+ ),
47
+ v.nonEmpty()
48
+ ),
49
+ dns: v.pipe(v.array(ipAddressSchema), v.nonEmpty())
50
+ });
51
+
52
+ // src/ipc-codec.ts
53
+ import { parseSchema } from "@leitwerk-dev/protocol";
54
+ import * as v2 from "valibot";
55
+ var IPC_PROTOCOL_VERSION = "leitwerk/worker-ipc/v1";
56
+ var IPC_ENVELOPE_SCHEMA = v2.object({
57
+ protocol: v2.literal(IPC_PROTOCOL_VERSION),
58
+ messageId: v2.string(),
59
+ correlationId: v2.optional(v2.string()),
60
+ type: v2.string(),
61
+ instanceId: v2.string(),
62
+ workerId: v2.string(),
63
+ sentAt: v2.string(),
64
+ payload: v2.unknown()
65
+ });
66
+ function validateEnvelope(msg) {
67
+ if (typeof msg === "object" && msg !== null && "protocol" in msg && typeof msg.protocol === "string" && msg.protocol !== IPC_PROTOCOL_VERSION) {
68
+ return {
69
+ ok: false,
70
+ error: `Worker IPC protocol '${msg.protocol}' is incompatible with expected protocol '${IPC_PROTOCOL_VERSION}'`
71
+ };
72
+ }
73
+ const envelope = parseSchema(IPC_ENVELOPE_SCHEMA, msg, "ipc envelope");
74
+ return envelope.ok ? { ok: true, envelope: envelope.value } : { ok: false, error: envelope.error };
75
+ }
76
+ function serializeMessage(envelope) {
77
+ return JSON.stringify(envelope);
78
+ }
79
+ function deserializeMessage(line) {
80
+ const trimmed = line.length > 0 && line.charCodeAt(line.length - 1) === 13 ? line.slice(0, -1) : line;
81
+ let parsed;
82
+ try {
83
+ parsed = JSON.parse(trimmed);
84
+ } catch {
85
+ return { ok: false, error: "invalid JSON" };
86
+ }
87
+ const validated = validateEnvelope(parsed);
88
+ if (!validated.ok) {
89
+ return { ok: false, error: validated.error };
90
+ }
91
+ return { ok: true, message: validated.envelope };
92
+ }
93
+
94
+ // src/ipc-decode.ts
95
+ var SERVER_TO_WORKER_TYPES = [
96
+ "worker.start",
97
+ "worker.turn_start_accepted",
98
+ "worker.turn_terminal_recorded",
99
+ "worker.credential_update_accepted",
100
+ "worker.question_response",
101
+ "worker.integration_tool_result",
102
+ "input.batch",
103
+ "worker.stop",
104
+ "worker.abort_turn"
105
+ ];
106
+ var WORKER_TO_SERVER_TYPES = [
107
+ "worker.hello",
108
+ "worker.credential_update",
109
+ "worker.bootstrap_progress",
110
+ "worker.diagnostic_trace",
111
+ "worker.ready",
112
+ "worker.heartbeat",
113
+ "worker.state",
114
+ "worker.input_consumed",
115
+ "worker.event",
116
+ "worker.turn_started",
117
+ "worker.question_requested",
118
+ "worker.integration_tool_request",
119
+ "worker.integration_tool_cancel",
120
+ "worker.turn_outcome",
121
+ "worker.turn_failed",
122
+ "worker.lifecycle_parked",
123
+ "worker.cleanup_started",
124
+ "worker.cleanup_completed",
125
+ "worker.failed"
126
+ ];
127
+ function hasMessageType(allowed, value) {
128
+ return allowed.includes(value);
129
+ }
130
+ function decodeKnownMessage(msg, allowed, direction) {
131
+ const validated = validateEnvelope(msg);
132
+ if (!validated.ok) {
133
+ return { ok: false, error: validated.error };
134
+ }
135
+ if (!hasMessageType(allowed, validated.envelope.type)) {
136
+ return {
137
+ ok: false,
138
+ error: `unexpected ${direction} message type: ${validated.envelope.type}`
139
+ };
140
+ }
141
+ return { ok: true, message: validated.envelope };
142
+ }
143
+ function decodeServerToWorkerMessage(msg) {
144
+ return decodeKnownMessage(msg, SERVER_TO_WORKER_TYPES, "server-to-worker");
145
+ }
146
+ function decodeWorkerToServerMessage(msg) {
147
+ return decodeKnownMessage(msg, WORKER_TO_SERVER_TYPES, "worker-to-server");
148
+ }
149
+
150
+ // src/ipc-messages.ts
151
+ function createIpcMessage(args) {
152
+ return {
153
+ protocol: IPC_PROTOCOL_VERSION,
154
+ messageId: args.messageId,
155
+ correlationId: args.correlationId,
156
+ type: args.type,
157
+ instanceId: args.instanceId,
158
+ workerId: args.workerId,
159
+ sentAt: args.sentAt ?? (/* @__PURE__ */ new Date()).toISOString(),
160
+ payload: args.payload
161
+ };
162
+ }
163
+
164
+ // src/pi-resource-bundle.ts
165
+ import { createHash } from "crypto";
166
+ import path from "path";
167
+ var BLOCK_SIZE = 512;
168
+ function fail(message) {
169
+ throw new Error(`Invalid Pi resource bundle: ${message}`);
170
+ }
171
+ function validateResourceRelativePath(value) {
172
+ if (!value || path.posix.isAbsolute(value) || value.includes("\\")) {
173
+ fail(`unsafe path '${value}'`);
174
+ }
175
+ const normalized = path.posix.normalize(value);
176
+ if (normalized === "." || normalized === ".." || normalized.startsWith("../")) {
177
+ fail(`unsafe path '${value}'`);
178
+ }
179
+ return normalized;
180
+ }
181
+ function writeString(buffer, offset, length, value) {
182
+ const encoded = Buffer.from(value, "utf8");
183
+ if (encoded.length > length) fail(`header value too long: ${value}`);
184
+ encoded.copy(buffer, offset);
185
+ }
186
+ function writeOctal(buffer, offset, length, value) {
187
+ const encoded = value.toString(8).padStart(length - 1, "0");
188
+ if (encoded.length > length - 1) fail(`numeric header value too large: ${value}`);
189
+ writeString(buffer, offset, length - 1, encoded);
190
+ buffer[offset + length - 1] = 0;
191
+ }
192
+ function header(name, size) {
193
+ if (Buffer.byteLength(name) > 100) fail(`path exceeds canonical ustar name limit: ${name}`);
194
+ const result = Buffer.alloc(BLOCK_SIZE);
195
+ writeString(result, 0, 100, name);
196
+ writeOctal(result, 100, 8, 420);
197
+ writeOctal(result, 108, 8, 0);
198
+ writeOctal(result, 116, 8, 0);
199
+ writeOctal(result, 124, 12, size);
200
+ writeOctal(result, 136, 12, 0);
201
+ result.fill(32, 148, 156);
202
+ result[156] = "0".charCodeAt(0);
203
+ writeString(result, 257, 6, "ustar");
204
+ writeString(result, 263, 2, "00");
205
+ const sum = result.reduce((total, byte) => total + byte, 0);
206
+ writeString(result, 148, 8, `${sum.toString(8).padStart(6, "0")}\0 `);
207
+ return result;
208
+ }
209
+ function padding(size) {
210
+ const length = (BLOCK_SIZE - size % BLOCK_SIZE) % BLOCK_SIZE;
211
+ return Buffer.alloc(length);
212
+ }
213
+ function sha256Digest(bytes) {
214
+ return createHash("sha256").update(bytes).digest("hex");
215
+ }
216
+ function createCanonicalPiResourceBundle(files) {
217
+ const seen = /* @__PURE__ */ new Set();
218
+ const normalized = files.map((file) => {
219
+ const resourcePath = validateResourceRelativePath(file.path);
220
+ if (seen.has(resourcePath)) fail(`duplicate path '${resourcePath}'`);
221
+ seen.add(resourcePath);
222
+ return { path: resourcePath, content: Buffer.from(file.content) };
223
+ });
224
+ normalized.sort((left, right) => Buffer.compare(Buffer.from(left.path), Buffer.from(right.path)));
225
+ const chunks = [];
226
+ for (const file of normalized) {
227
+ chunks.push(header(file.path, file.content.length), file.content, padding(file.content.length));
228
+ }
229
+ chunks.push(Buffer.alloc(BLOCK_SIZE * 2));
230
+ const bytes = Buffer.concat(chunks);
231
+ return { bytes, digest: sha256Digest(bytes) };
232
+ }
233
+ function readNullString(block, start, length) {
234
+ const end = block.subarray(start, start + length).indexOf(0);
235
+ return Buffer.from(block.subarray(start, end < 0 ? start + length : start + end)).toString(
236
+ "utf8"
237
+ );
238
+ }
239
+ function readOctal(block, start, length) {
240
+ const raw = readNullString(block, start, length).trim();
241
+ if (!/^[0-7]*$/.test(raw)) fail("non-octal numeric field");
242
+ return raw ? Number.parseInt(raw, 8) : 0;
243
+ }
244
+ function verifyChecksum(block) {
245
+ const expected = readOctal(block, 148, 8);
246
+ let actual = 0;
247
+ for (let index = 0; index < BLOCK_SIZE; index++) {
248
+ actual += index >= 148 && index < 156 ? 32 : block[index];
249
+ }
250
+ if (actual !== expected) fail("header checksum mismatch");
251
+ }
252
+ function allZero(block) {
253
+ return block.every((byte) => byte === 0);
254
+ }
255
+ function verifyCanonicalPiResourceBundle(bytes, expectedDigest) {
256
+ if (expectedDigest && sha256Digest(bytes) !== expectedDigest) fail("content digest mismatch");
257
+ if (bytes.length < BLOCK_SIZE * 2 || bytes.length % BLOCK_SIZE !== 0) {
258
+ fail("invalid archive length");
259
+ }
260
+ const files = [];
261
+ const paths = /* @__PURE__ */ new Set();
262
+ let offset = 0;
263
+ while (offset < bytes.length) {
264
+ const block = bytes.subarray(offset, offset + BLOCK_SIZE);
265
+ if (allZero(block)) {
266
+ if (!allZero(bytes.subarray(offset + BLOCK_SIZE, offset + BLOCK_SIZE * 2))) {
267
+ fail("missing end blocks");
268
+ }
269
+ if (offset + BLOCK_SIZE * 2 !== bytes.length) fail("data after end blocks");
270
+ return files;
271
+ }
272
+ verifyChecksum(block);
273
+ if (readNullString(block, 257, 6) !== "ustar") fail("unsupported tar format");
274
+ const type = readNullString(block, 156, 1);
275
+ if (type !== "" && type !== "0") fail(`unsupported entry type '${type}'`);
276
+ if (readNullString(block, 157, 100) || readNullString(block, 345, 155)) {
277
+ fail("links and ustar path prefixes are unsupported");
278
+ }
279
+ const name = validateResourceRelativePath(readNullString(block, 0, 100));
280
+ if (paths.has(name)) fail(`duplicate path '${name}'`);
281
+ paths.add(name);
282
+ const size = readOctal(block, 124, 12);
283
+ const contentStart = offset + BLOCK_SIZE;
284
+ const contentEnd = contentStart + size;
285
+ if (contentEnd > bytes.length) fail("truncated file content");
286
+ files.push({ path: name, content: bytes.slice(contentStart, contentEnd) });
287
+ offset = contentEnd + (BLOCK_SIZE - size % BLOCK_SIZE) % BLOCK_SIZE;
288
+ }
289
+ fail("missing end blocks");
290
+ }
291
+
292
+ // src/pi-resource-manifest.ts
293
+ import * as v3 from "valibot";
294
+ var PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION = 1;
295
+ var nonBlankStringSchema = v3.pipe(
296
+ v3.string(),
297
+ v3.check((value) => value.trim() !== "", "Expected a non-empty string")
298
+ );
299
+ var jsonObjectSchema = v3.record(v3.string(), v3.unknown());
300
+ var positiveSafeIntegerSchema = v3.pipe(v3.number(), v3.safeInteger(), v3.minValue(1));
301
+ var nonNegativeSafeIntegerSchema = v3.pipe(v3.number(), v3.safeInteger(), v3.minValue(0));
302
+ var piResourceManifestSchema = v3.strictObject({
303
+ schemaVersion: v3.literal(PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION),
304
+ model: v3.strictObject({
305
+ profileId: nonBlankStringSchema,
306
+ providerId: nonBlankStringSchema,
307
+ modelId: nonBlankStringSchema,
308
+ thinkingLevel: nonBlankStringSchema
309
+ }),
310
+ providerOptions: v3.record(v3.string(), nonBlankStringSchema),
311
+ providerWorkerConfig: v3.nullable(
312
+ v3.strictObject({
313
+ version: positiveSafeIntegerSchema,
314
+ value: jsonObjectSchema
315
+ })
316
+ ),
317
+ declaredCredentialPaths: v3.array(nonBlankStringSchema),
318
+ compatibility: v3.strictObject({
319
+ workerApiVersion: nonBlankStringSchema,
320
+ piVersion: nonBlankStringSchema,
321
+ protocolVersion: v3.optional(nonBlankStringSchema)
322
+ }),
323
+ provenance: v3.array(
324
+ v3.strictObject({
325
+ kind: v3.picklist(["extension", "skill", "prompt", "generated"]),
326
+ ownerExtensionId: v3.nullable(nonBlankStringSchema),
327
+ packageName: v3.nullable(nonBlankStringSchema),
328
+ snapshotPath: nonBlankStringSchema,
329
+ sha256: v3.pipe(v3.string(), v3.regex(/^[a-f0-9]{64}$/)),
330
+ size: nonNegativeSafeIntegerSchema
331
+ })
332
+ )
333
+ });
334
+ function invalidManifest(message, cause) {
335
+ throw new Error(`Invalid managed Pi resource snapshot: ${message}`, { cause });
336
+ }
337
+ function parsePiResourceManifest(raw) {
338
+ let manifest;
339
+ try {
340
+ manifest = v3.parse(piResourceManifestSchema, raw);
341
+ } catch (error) {
342
+ invalidManifest("generated.json does not match the resource manifest schema", error);
343
+ }
344
+ let declaredCredentialPaths;
345
+ let provenance;
346
+ try {
347
+ declaredCredentialPaths = manifest.declaredCredentialPaths.map(validateResourceRelativePath);
348
+ provenance = manifest.provenance.map((item) => ({
349
+ ...item,
350
+ snapshotPath: validateResourceRelativePath(item.snapshotPath)
351
+ }));
352
+ } catch (error) {
353
+ invalidManifest("generated.json contains an unsafe path", error);
354
+ }
355
+ if (new Set(declaredCredentialPaths).size !== declaredCredentialPaths.length) {
356
+ invalidManifest("generated.json declares a credential path more than once");
357
+ }
358
+ const provenancePaths = provenance.map((item) => item.snapshotPath);
359
+ if (new Set(provenancePaths).size !== provenancePaths.length) {
360
+ invalidManifest("generated.json contains duplicate provenance paths");
361
+ }
362
+ for (const credentialPath of declaredCredentialPaths) {
363
+ if (credentialPath === "generated.json" || provenancePaths.includes(credentialPath)) {
364
+ invalidManifest(`credential path '${credentialPath}' overlaps immutable snapshot content`);
365
+ }
366
+ }
367
+ return { ...manifest, declaredCredentialPaths, provenance };
368
+ }
369
+ function canonicalizeJson(value, location = "value") {
370
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
371
+ if (typeof value === "number") {
372
+ if (!Number.isFinite(value)) throw new Error(`${location} contains a non-finite number`);
373
+ return Object.is(value, -0) ? 0 : value;
374
+ }
375
+ if (Array.isArray(value)) {
376
+ return value.map((item, index) => canonicalizeJson(item, `${location}[${index}]`));
377
+ }
378
+ if (typeof value !== "object") throw new Error(`${location} contains a non-JSON value`);
379
+ const prototype = Object.getPrototypeOf(value);
380
+ if (prototype !== Object.prototype && prototype !== null) {
381
+ throw new Error(`${location} contains a non-plain object`);
382
+ }
383
+ return Object.fromEntries(
384
+ Object.keys(value).sort((left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right))).map((key) => [key, canonicalizeJson(value[key], `${location}.${key}`)])
385
+ );
386
+ }
387
+ function canonicalJsonStringify(value, location = "value") {
388
+ return JSON.stringify(canonicalizeJson(value, location));
389
+ }
390
+ function canonicalJsonEqual(left, right) {
391
+ return canonicalJsonStringify(left) === canonicalJsonStringify(right);
392
+ }
393
+
394
+ // src/testing.ts
395
+ async function flushAsyncWork(iterations = 30) {
396
+ for (let i = 0; i < iterations; i++) {
397
+ await new Promise((resolve) => setImmediate(resolve));
398
+ }
399
+ }
400
+ function createTestIpcEnvelopeBase(instanceId, workerId, messageId) {
401
+ return {
402
+ protocol: IPC_PROTOCOL_VERSION,
403
+ messageId,
404
+ instanceId,
405
+ workerId,
406
+ sentAt: (/* @__PURE__ */ new Date()).toISOString()
407
+ };
408
+ }
409
+ function createTestConfigSnapshot() {
410
+ return {
411
+ workers: {
412
+ heartbeat_interval: "5s",
413
+ turn_max_duration: "30m",
414
+ turn_inactivity_timeout: "5m",
415
+ turn_abort_grace_period: "5s"
416
+ },
417
+ pi: {
418
+ agent_dir: "~/.pi/leitwerk",
419
+ model_profiles: [],
420
+ process_title_generation: {
421
+ model_profile: null,
422
+ retry: {
423
+ max_attempts: 6,
424
+ base_delay: "5s",
425
+ max_delay: "5m"
426
+ }
427
+ },
428
+ retry: {
429
+ enabled: true,
430
+ max_retries: 3,
431
+ base_delay: "2s",
432
+ provider: {
433
+ timeout: null,
434
+ max_retries: null,
435
+ max_retry_delay: "60s"
436
+ }
437
+ }
438
+ }
439
+ };
440
+ }
441
+
442
+ // src/worker-api-version.ts
443
+ var WORKER_API_VERSION = "2026-09-16";
444
+
445
+ // src/worker-ipc-transport.ts
446
+ var WORKER_INSTANCE_ID_ENV = "LEITWERK_INSTANCE_ID";
447
+ var WORKER_ID_ENV = "LEITWERK_WORKER_ID";
448
+ var WORKER_IPC_SERVER_URL_ENV = "LEITWERK_SERVER_URL";
449
+ var WORKER_IPC_CONNECT_TOKEN_ENV = "LEITWERK_WORKER_CONNECT_TOKEN";
450
+ var WORKER_IPC_RECONNECT_ENV = "LEITWERK_WORKER_RECONNECT";
451
+ var WORKER_SNAPSHOT_TOKEN_ENV = "LEITWERK_WORKER_SNAPSHOT_TOKEN";
452
+ var WORKER_SERVER_EPOCH_ENV = "LEITWERK_SERVER_EPOCH";
453
+
454
+ // src/worker-session-snapshot.ts
455
+ var WORKER_SESSION_SNAPSHOT_CONTENT_TYPE = "application/x-ndjson";
456
+ var WORKER_SESSION_SNAPSHOT_WORKER_ID_HEADER = "x-leitwerk-worker-id";
457
+ var WORKER_SESSION_SNAPSHOT_REASON_HEADER = "x-leitwerk-session-snapshot-reason";
458
+ var WORKER_SESSION_SNAPSHOT_TURN_RECORD_ID_HEADER = "x-leitwerk-turn-record-id";
459
+ function buildWorkerSessionSnapshotPath(instanceId) {
460
+ return `/internal/workers/${encodeURIComponent(instanceId)}/session-snapshot`;
461
+ }
462
+ export {
463
+ IPC_ENVELOPE_SCHEMA,
464
+ IPC_PROTOCOL_VERSION,
465
+ PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION,
466
+ RESULT_IMAGE_ID_PATTERN,
467
+ RESULT_IMAGE_MAX_SIZE_BYTES,
468
+ RESULT_IMAGE_MIME_TYPES,
469
+ RESULT_IMAGE_STORAGE_SEGMENT_PATTERN,
470
+ WORKER_API_VERSION,
471
+ WORKER_ID_ENV,
472
+ WORKER_INSTANCE_ID_ENV,
473
+ WORKER_IPC_CONNECT_TOKEN_ENV,
474
+ WORKER_IPC_RECONNECT_ENV,
475
+ WORKER_IPC_SERVER_URL_ENV,
476
+ WORKER_RESULT_IMAGE_WORKER_ID_HEADER,
477
+ WORKER_SERVER_EPOCH_ENV,
478
+ WORKER_SESSION_SNAPSHOT_CONTENT_TYPE,
479
+ WORKER_SESSION_SNAPSHOT_REASON_HEADER,
480
+ WORKER_SESSION_SNAPSHOT_TURN_RECORD_ID_HEADER,
481
+ WORKER_SESSION_SNAPSHOT_WORKER_ID_HEADER,
482
+ WORKER_SNAPSHOT_TOKEN_ENV,
483
+ buildManagedResultImagePath,
484
+ buildWorkerResultImageUploadPath,
485
+ buildWorkerSessionSnapshotPath,
486
+ canonicalJsonEqual,
487
+ canonicalJsonStringify,
488
+ canonicalizeJson,
489
+ createCanonicalPiResourceBundle,
490
+ createIpcMessage,
491
+ createTestConfigSnapshot,
492
+ createTestIpcEnvelopeBase,
493
+ decodeServerToWorkerMessage,
494
+ decodeWorkerToServerMessage,
495
+ deserializeMessage,
496
+ dockerNetworkSchema,
497
+ dockerRegistryCredentialSchema,
498
+ flushAsyncWork,
499
+ ipAddressSchema,
500
+ isResultImageStorageSegment,
501
+ parseManagedResultImagePath,
502
+ parsePiResourceManifest,
503
+ parseResultImageId,
504
+ parseWorkerResultImageUploadResponse,
505
+ piResourceManifestSchema,
506
+ serializeMessage,
507
+ sha256Digest,
508
+ validateEnvelope,
509
+ validateResourceRelativePath,
510
+ verifyCanonicalPiResourceBundle,
511
+ workerResultImageUploadResponseSchema
512
+ };
11
513
  //# sourceMappingURL=index.js.map