@leitwerk-dev/worker-protocol 0.1.0 → 0.1.2

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 (45) hide show
  1. package/dist/index.d.ts +448 -11
  2. package/dist/index.js +451 -10
  3. package/dist/index.js.map +1 -1
  4. package/dist/worker-result-image.d.ts +18 -16
  5. package/dist/worker-result-image.js +28 -54
  6. package/dist/worker-result-image.js.map +1 -1
  7. package/package.json +3 -3
  8. package/dist/index.d.ts.map +0 -1
  9. package/dist/ipc-codec.d.ts +0 -29
  10. package/dist/ipc-codec.d.ts.map +0 -1
  11. package/dist/ipc-codec.js +0 -48
  12. package/dist/ipc-codec.js.map +0 -1
  13. package/dist/ipc-decode.d.ts +0 -19
  14. package/dist/ipc-decode.d.ts.map +0 -1
  15. package/dist/ipc-decode.js +0 -68
  16. package/dist/ipc-decode.js.map +0 -1
  17. package/dist/ipc-messages.d.ts +0 -310
  18. package/dist/ipc-messages.d.ts.map +0 -1
  19. package/dist/ipc-messages.js +0 -14
  20. package/dist/ipc-messages.js.map +0 -1
  21. package/dist/pi-resource-bundle.d.ts +0 -19
  22. package/dist/pi-resource-bundle.d.ts.map +0 -1
  23. package/dist/pi-resource-bundle.js +0 -139
  24. package/dist/pi-resource-bundle.js.map +0 -1
  25. package/dist/pi-resource-manifest.d.ts +0 -48
  26. package/dist/pi-resource-manifest.d.ts.map +0 -1
  27. package/dist/pi-resource-manifest.js +0 -101
  28. package/dist/pi-resource-manifest.js.map +0 -1
  29. package/dist/testing.d.ts +0 -3
  30. package/dist/testing.d.ts.map +0 -1
  31. package/dist/testing.js +0 -33
  32. package/dist/testing.js.map +0 -1
  33. package/dist/worker-api-version.d.ts +0 -9
  34. package/dist/worker-api-version.d.ts.map +0 -1
  35. package/dist/worker-api-version.js +0 -9
  36. package/dist/worker-api-version.js.map +0 -1
  37. package/dist/worker-ipc-transport.d.ts +0 -8
  38. package/dist/worker-ipc-transport.d.ts.map +0 -1
  39. package/dist/worker-ipc-transport.js +0 -8
  40. package/dist/worker-ipc-transport.js.map +0 -1
  41. package/dist/worker-result-image.d.ts.map +0 -1
  42. package/dist/worker-session-snapshot.d.ts +0 -6
  43. package/dist/worker-session-snapshot.d.ts.map +0 -1
  44. package/dist/worker-session-snapshot.js +0 -8
  45. package/dist/worker-session-snapshot.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,11 +1,452 @@
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/ipc-codec.ts
17
+ import { parseSchema } from "@leitwerk-dev/protocol";
18
+ import * as v from "valibot";
19
+ var IPC_PROTOCOL_VERSION = "leitwerk/worker-ipc/v1";
20
+ var IPC_ENVELOPE_SCHEMA = v.object({
21
+ protocol: v.literal(IPC_PROTOCOL_VERSION),
22
+ messageId: v.string(),
23
+ correlationId: v.optional(v.string()),
24
+ type: v.string(),
25
+ instanceId: v.string(),
26
+ workerId: v.string(),
27
+ sentAt: v.string(),
28
+ payload: v.unknown()
29
+ });
30
+ function validateEnvelope(msg) {
31
+ if (typeof msg === "object" && msg !== null && "protocol" in msg && typeof msg.protocol === "string" && msg.protocol !== IPC_PROTOCOL_VERSION) {
32
+ return {
33
+ ok: false,
34
+ error: `Worker IPC protocol '${msg.protocol}' is incompatible with expected protocol '${IPC_PROTOCOL_VERSION}'`
35
+ };
36
+ }
37
+ const envelope = parseSchema(IPC_ENVELOPE_SCHEMA, msg, "ipc envelope");
38
+ return envelope.ok ? { ok: true, envelope: envelope.value } : { ok: false, error: envelope.error };
39
+ }
40
+ function serializeMessage(envelope) {
41
+ return JSON.stringify(envelope);
42
+ }
43
+ function deserializeMessage(line) {
44
+ const trimmed = line.length > 0 && line.charCodeAt(line.length - 1) === 13 ? line.slice(0, -1) : line;
45
+ let parsed;
46
+ try {
47
+ parsed = JSON.parse(trimmed);
48
+ } catch {
49
+ return { ok: false, error: "invalid JSON" };
50
+ }
51
+ const validated = validateEnvelope(parsed);
52
+ if (!validated.ok) {
53
+ return { ok: false, error: validated.error };
54
+ }
55
+ return { ok: true, message: validated.envelope };
56
+ }
57
+
58
+ // src/ipc-decode.ts
59
+ var SERVER_TO_WORKER_TYPES = [
60
+ "worker.start",
61
+ "worker.turn_start_accepted",
62
+ "worker.credential_update_accepted",
63
+ "worker.question_response",
64
+ "input.batch",
65
+ "worker.stop",
66
+ "worker.abort_turn"
67
+ ];
68
+ var WORKER_TO_SERVER_TYPES = [
69
+ "worker.hello",
70
+ "worker.credential_update",
71
+ "worker.ready",
72
+ "worker.heartbeat",
73
+ "worker.state",
74
+ "worker.input_consumed",
75
+ "worker.event",
76
+ "worker.turn_started",
77
+ "worker.question_requested",
78
+ "worker.turn_outcome",
79
+ "worker.turn_failed",
80
+ "worker.lifecycle_parked",
81
+ "worker.cleanup_started",
82
+ "worker.cleanup_completed",
83
+ "worker.failed"
84
+ ];
85
+ function hasMessageType(allowed, value) {
86
+ return allowed.includes(value);
87
+ }
88
+ function decodeKnownMessage(msg, allowed, direction) {
89
+ const validated = validateEnvelope(msg);
90
+ if (!validated.ok) {
91
+ return { ok: false, error: validated.error };
92
+ }
93
+ if (!hasMessageType(allowed, validated.envelope.type)) {
94
+ return {
95
+ ok: false,
96
+ error: `unexpected ${direction} message type: ${validated.envelope.type}`
97
+ };
98
+ }
99
+ return { ok: true, message: validated.envelope };
100
+ }
101
+ function decodeServerToWorkerMessage(msg) {
102
+ return decodeKnownMessage(msg, SERVER_TO_WORKER_TYPES, "server-to-worker");
103
+ }
104
+ function decodeWorkerToServerMessage(msg) {
105
+ return decodeKnownMessage(msg, WORKER_TO_SERVER_TYPES, "worker-to-server");
106
+ }
107
+
108
+ // src/ipc-messages.ts
109
+ function createIpcMessage(args) {
110
+ return {
111
+ protocol: IPC_PROTOCOL_VERSION,
112
+ messageId: args.messageId,
113
+ correlationId: args.correlationId,
114
+ type: args.type,
115
+ instanceId: args.instanceId,
116
+ workerId: args.workerId,
117
+ sentAt: args.sentAt ?? (/* @__PURE__ */ new Date()).toISOString(),
118
+ payload: args.payload
119
+ };
120
+ }
121
+
122
+ // src/pi-resource-bundle.ts
123
+ import { createHash } from "crypto";
124
+ import path from "path";
125
+ var BLOCK_SIZE = 512;
126
+ function fail(message) {
127
+ throw new Error(`Invalid Pi resource bundle: ${message}`);
128
+ }
129
+ function validateResourceRelativePath(value) {
130
+ if (!value || path.posix.isAbsolute(value) || value.includes("\\")) {
131
+ fail(`unsafe path '${value}'`);
132
+ }
133
+ const normalized = path.posix.normalize(value);
134
+ if (normalized === "." || normalized === ".." || normalized.startsWith("../")) {
135
+ fail(`unsafe path '${value}'`);
136
+ }
137
+ return normalized;
138
+ }
139
+ function writeString(buffer, offset, length, value) {
140
+ const encoded = Buffer.from(value, "utf8");
141
+ if (encoded.length > length) fail(`header value too long: ${value}`);
142
+ encoded.copy(buffer, offset);
143
+ }
144
+ function writeOctal(buffer, offset, length, value) {
145
+ const encoded = value.toString(8).padStart(length - 1, "0");
146
+ if (encoded.length > length - 1) fail(`numeric header value too large: ${value}`);
147
+ writeString(buffer, offset, length - 1, encoded);
148
+ buffer[offset + length - 1] = 0;
149
+ }
150
+ function header(name, size) {
151
+ if (Buffer.byteLength(name) > 100) fail(`path exceeds canonical ustar name limit: ${name}`);
152
+ const result = Buffer.alloc(BLOCK_SIZE);
153
+ writeString(result, 0, 100, name);
154
+ writeOctal(result, 100, 8, 420);
155
+ writeOctal(result, 108, 8, 0);
156
+ writeOctal(result, 116, 8, 0);
157
+ writeOctal(result, 124, 12, size);
158
+ writeOctal(result, 136, 12, 0);
159
+ result.fill(32, 148, 156);
160
+ result[156] = "0".charCodeAt(0);
161
+ writeString(result, 257, 6, "ustar");
162
+ writeString(result, 263, 2, "00");
163
+ const sum = result.reduce((total, byte) => total + byte, 0);
164
+ writeString(result, 148, 8, `${sum.toString(8).padStart(6, "0")}\0 `);
165
+ return result;
166
+ }
167
+ function padding(size) {
168
+ const length = (BLOCK_SIZE - size % BLOCK_SIZE) % BLOCK_SIZE;
169
+ return Buffer.alloc(length);
170
+ }
171
+ function sha256Digest(bytes) {
172
+ return createHash("sha256").update(bytes).digest("hex");
173
+ }
174
+ function createCanonicalPiResourceBundle(files) {
175
+ const seen = /* @__PURE__ */ new Set();
176
+ const normalized = files.map((file) => {
177
+ const resourcePath = validateResourceRelativePath(file.path);
178
+ if (seen.has(resourcePath)) fail(`duplicate path '${resourcePath}'`);
179
+ seen.add(resourcePath);
180
+ return { path: resourcePath, content: Buffer.from(file.content) };
181
+ });
182
+ normalized.sort((left, right) => Buffer.compare(Buffer.from(left.path), Buffer.from(right.path)));
183
+ const chunks = [];
184
+ for (const file of normalized) {
185
+ chunks.push(header(file.path, file.content.length), file.content, padding(file.content.length));
186
+ }
187
+ chunks.push(Buffer.alloc(BLOCK_SIZE * 2));
188
+ const bytes = Buffer.concat(chunks);
189
+ return { bytes, digest: sha256Digest(bytes) };
190
+ }
191
+ function readNullString(block, start, length) {
192
+ const end = block.subarray(start, start + length).indexOf(0);
193
+ return Buffer.from(block.subarray(start, end < 0 ? start + length : start + end)).toString(
194
+ "utf8"
195
+ );
196
+ }
197
+ function readOctal(block, start, length) {
198
+ const raw = readNullString(block, start, length).trim();
199
+ if (!/^[0-7]*$/.test(raw)) fail("non-octal numeric field");
200
+ return raw ? Number.parseInt(raw, 8) : 0;
201
+ }
202
+ function verifyChecksum(block) {
203
+ const expected = readOctal(block, 148, 8);
204
+ let actual = 0;
205
+ for (let index = 0; index < BLOCK_SIZE; index++) {
206
+ actual += index >= 148 && index < 156 ? 32 : block[index];
207
+ }
208
+ if (actual !== expected) fail("header checksum mismatch");
209
+ }
210
+ function allZero(block) {
211
+ return block.every((byte) => byte === 0);
212
+ }
213
+ function verifyCanonicalPiResourceBundle(bytes, expectedDigest) {
214
+ if (expectedDigest && sha256Digest(bytes) !== expectedDigest) fail("content digest mismatch");
215
+ if (bytes.length < BLOCK_SIZE * 2 || bytes.length % BLOCK_SIZE !== 0) {
216
+ fail("invalid archive length");
217
+ }
218
+ const files = [];
219
+ const paths = /* @__PURE__ */ new Set();
220
+ let offset = 0;
221
+ while (offset < bytes.length) {
222
+ const block = bytes.subarray(offset, offset + BLOCK_SIZE);
223
+ if (allZero(block)) {
224
+ if (!allZero(bytes.subarray(offset + BLOCK_SIZE, offset + BLOCK_SIZE * 2))) {
225
+ fail("missing end blocks");
226
+ }
227
+ if (offset + BLOCK_SIZE * 2 !== bytes.length) fail("data after end blocks");
228
+ return files;
229
+ }
230
+ verifyChecksum(block);
231
+ if (readNullString(block, 257, 6) !== "ustar") fail("unsupported tar format");
232
+ const type = readNullString(block, 156, 1);
233
+ if (type !== "" && type !== "0") fail(`unsupported entry type '${type}'`);
234
+ if (readNullString(block, 157, 100) || readNullString(block, 345, 155)) {
235
+ fail("links and ustar path prefixes are unsupported");
236
+ }
237
+ const name = validateResourceRelativePath(readNullString(block, 0, 100));
238
+ if (paths.has(name)) fail(`duplicate path '${name}'`);
239
+ paths.add(name);
240
+ const size = readOctal(block, 124, 12);
241
+ const contentStart = offset + BLOCK_SIZE;
242
+ const contentEnd = contentStart + size;
243
+ if (contentEnd > bytes.length) fail("truncated file content");
244
+ files.push({ path: name, content: bytes.slice(contentStart, contentEnd) });
245
+ offset = contentEnd + (BLOCK_SIZE - size % BLOCK_SIZE) % BLOCK_SIZE;
246
+ }
247
+ fail("missing end blocks");
248
+ }
249
+
250
+ // src/pi-resource-manifest.ts
251
+ import * as v2 from "valibot";
252
+ var PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION = 1;
253
+ var nonBlankStringSchema = v2.pipe(
254
+ v2.string(),
255
+ v2.check((value) => value.trim() !== "", "Expected a non-empty string")
256
+ );
257
+ var jsonObjectSchema = v2.record(v2.string(), v2.unknown());
258
+ var positiveSafeIntegerSchema = v2.pipe(v2.number(), v2.safeInteger(), v2.minValue(1));
259
+ var nonNegativeSafeIntegerSchema = v2.pipe(v2.number(), v2.safeInteger(), v2.minValue(0));
260
+ var piResourceManifestSchema = v2.strictObject({
261
+ schemaVersion: v2.literal(PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION),
262
+ model: v2.strictObject({
263
+ profileId: nonBlankStringSchema,
264
+ providerId: nonBlankStringSchema,
265
+ modelId: nonBlankStringSchema,
266
+ thinkingLevel: nonBlankStringSchema
267
+ }),
268
+ providerOptions: v2.record(v2.string(), nonBlankStringSchema),
269
+ providerWorkerConfig: v2.nullable(
270
+ v2.strictObject({
271
+ version: positiveSafeIntegerSchema,
272
+ value: jsonObjectSchema
273
+ })
274
+ ),
275
+ declaredCredentialPaths: v2.array(nonBlankStringSchema),
276
+ compatibility: v2.strictObject({
277
+ workerApiVersion: nonBlankStringSchema,
278
+ piVersion: nonBlankStringSchema,
279
+ protocolVersion: v2.optional(nonBlankStringSchema)
280
+ }),
281
+ provenance: v2.array(
282
+ v2.strictObject({
283
+ kind: v2.picklist(["extension", "skill", "prompt", "generated"]),
284
+ ownerExtensionId: v2.nullable(nonBlankStringSchema),
285
+ packageName: v2.nullable(nonBlankStringSchema),
286
+ snapshotPath: nonBlankStringSchema,
287
+ sha256: v2.pipe(v2.string(), v2.regex(/^[a-f0-9]{64}$/)),
288
+ size: nonNegativeSafeIntegerSchema
289
+ })
290
+ )
291
+ });
292
+ function invalidManifest(message, cause) {
293
+ throw new Error(`Invalid managed Pi resource snapshot: ${message}`, { cause });
294
+ }
295
+ function parsePiResourceManifest(raw) {
296
+ let manifest;
297
+ try {
298
+ manifest = v2.parse(piResourceManifestSchema, raw);
299
+ } catch (error) {
300
+ invalidManifest("generated.json does not match the resource manifest schema", error);
301
+ }
302
+ let declaredCredentialPaths;
303
+ let provenance;
304
+ try {
305
+ declaredCredentialPaths = manifest.declaredCredentialPaths.map(validateResourceRelativePath);
306
+ provenance = manifest.provenance.map((item) => ({
307
+ ...item,
308
+ snapshotPath: validateResourceRelativePath(item.snapshotPath)
309
+ }));
310
+ } catch (error) {
311
+ invalidManifest("generated.json contains an unsafe path", error);
312
+ }
313
+ if (new Set(declaredCredentialPaths).size !== declaredCredentialPaths.length) {
314
+ invalidManifest("generated.json declares a credential path more than once");
315
+ }
316
+ const provenancePaths = provenance.map((item) => item.snapshotPath);
317
+ if (new Set(provenancePaths).size !== provenancePaths.length) {
318
+ invalidManifest("generated.json contains duplicate provenance paths");
319
+ }
320
+ for (const credentialPath of declaredCredentialPaths) {
321
+ if (credentialPath === "generated.json" || provenancePaths.includes(credentialPath)) {
322
+ invalidManifest(`credential path '${credentialPath}' overlaps immutable snapshot content`);
323
+ }
324
+ }
325
+ return { ...manifest, declaredCredentialPaths, provenance };
326
+ }
327
+ function canonicalizeJson(value, location = "value") {
328
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
329
+ if (typeof value === "number") {
330
+ if (!Number.isFinite(value)) throw new Error(`${location} contains a non-finite number`);
331
+ return Object.is(value, -0) ? 0 : value;
332
+ }
333
+ if (Array.isArray(value)) {
334
+ return value.map((item, index) => canonicalizeJson(item, `${location}[${index}]`));
335
+ }
336
+ if (typeof value !== "object") throw new Error(`${location} contains a non-JSON value`);
337
+ const prototype = Object.getPrototypeOf(value);
338
+ if (prototype !== Object.prototype && prototype !== null) {
339
+ throw new Error(`${location} contains a non-plain object`);
340
+ }
341
+ return Object.fromEntries(
342
+ Object.keys(value).sort((left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right))).map((key) => [key, canonicalizeJson(value[key], `${location}.${key}`)])
343
+ );
344
+ }
345
+ function canonicalJsonStringify(value, location = "value") {
346
+ return JSON.stringify(canonicalizeJson(value, location));
347
+ }
348
+ function canonicalJsonEqual(left, right) {
349
+ return canonicalJsonStringify(left) === canonicalJsonStringify(right);
350
+ }
351
+
352
+ // src/testing.ts
353
+ function createTestConfigSnapshot() {
354
+ return {
355
+ workers: {
356
+ heartbeat_interval: "5s",
357
+ turn_max_duration: "30m",
358
+ turn_inactivity_timeout: "5m",
359
+ turn_abort_grace_period: "5s"
360
+ },
361
+ pi: {
362
+ agent_dir: "~/.pi/leitwerk",
363
+ model_profiles: [],
364
+ process_title_generation: {
365
+ model_profile: null,
366
+ retry: {
367
+ max_attempts: 6,
368
+ base_delay: "5s",
369
+ max_delay: "5m"
370
+ }
371
+ },
372
+ retry: {
373
+ enabled: true,
374
+ max_retries: 3,
375
+ base_delay: "2s",
376
+ provider: {
377
+ timeout: null,
378
+ max_retries: null,
379
+ max_retry_delay: "60s"
380
+ }
381
+ }
382
+ }
383
+ };
384
+ }
385
+
386
+ // src/worker-api-version.ts
387
+ var WORKER_API_VERSION = "2026-07-26";
388
+
389
+ // src/worker-ipc-transport.ts
390
+ var WORKER_INSTANCE_ID_ENV = "LEITWERK_INSTANCE_ID";
391
+ var WORKER_ID_ENV = "LEITWERK_WORKER_ID";
392
+ var WORKER_IPC_SERVER_URL_ENV = "LEITWERK_SERVER_URL";
393
+ var WORKER_IPC_CONNECT_TOKEN_ENV = "LEITWERK_WORKER_CONNECT_TOKEN";
394
+ var WORKER_IPC_RECONNECT_ENV = "LEITWERK_WORKER_RECONNECT";
395
+ var WORKER_SNAPSHOT_TOKEN_ENV = "LEITWERK_WORKER_SNAPSHOT_TOKEN";
396
+ var WORKER_SERVER_EPOCH_ENV = "LEITWERK_SERVER_EPOCH";
397
+
398
+ // src/worker-session-snapshot.ts
399
+ var WORKER_SESSION_SNAPSHOT_CONTENT_TYPE = "application/x-ndjson";
400
+ var WORKER_SESSION_SNAPSHOT_WORKER_ID_HEADER = "x-leitwerk-worker-id";
401
+ var WORKER_SESSION_SNAPSHOT_REASON_HEADER = "x-leitwerk-session-snapshot-reason";
402
+ var WORKER_SESSION_SNAPSHOT_TURN_RECORD_ID_HEADER = "x-leitwerk-turn-record-id";
403
+ function buildWorkerSessionSnapshotPath(instanceId) {
404
+ return `/internal/workers/${encodeURIComponent(instanceId)}/session-snapshot`;
405
+ }
406
+ export {
407
+ IPC_ENVELOPE_SCHEMA,
408
+ IPC_PROTOCOL_VERSION,
409
+ PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION,
410
+ RESULT_IMAGE_ID_PATTERN,
411
+ RESULT_IMAGE_MAX_SIZE_BYTES,
412
+ RESULT_IMAGE_MIME_TYPES,
413
+ RESULT_IMAGE_STORAGE_SEGMENT_PATTERN,
414
+ WORKER_API_VERSION,
415
+ WORKER_ID_ENV,
416
+ WORKER_INSTANCE_ID_ENV,
417
+ WORKER_IPC_CONNECT_TOKEN_ENV,
418
+ WORKER_IPC_RECONNECT_ENV,
419
+ WORKER_IPC_SERVER_URL_ENV,
420
+ WORKER_RESULT_IMAGE_WORKER_ID_HEADER,
421
+ WORKER_SERVER_EPOCH_ENV,
422
+ WORKER_SESSION_SNAPSHOT_CONTENT_TYPE,
423
+ WORKER_SESSION_SNAPSHOT_REASON_HEADER,
424
+ WORKER_SESSION_SNAPSHOT_TURN_RECORD_ID_HEADER,
425
+ WORKER_SESSION_SNAPSHOT_WORKER_ID_HEADER,
426
+ WORKER_SNAPSHOT_TOKEN_ENV,
427
+ buildManagedResultImagePath,
428
+ buildWorkerResultImageUploadPath,
429
+ buildWorkerSessionSnapshotPath,
430
+ canonicalJsonEqual,
431
+ canonicalJsonStringify,
432
+ canonicalizeJson,
433
+ createCanonicalPiResourceBundle,
434
+ createIpcMessage,
435
+ createTestConfigSnapshot,
436
+ decodeServerToWorkerMessage,
437
+ decodeWorkerToServerMessage,
438
+ deserializeMessage,
439
+ isResultImageStorageSegment,
440
+ parseManagedResultImagePath,
441
+ parsePiResourceManifest,
442
+ parseResultImageId,
443
+ parseWorkerResultImageUploadResponse,
444
+ piResourceManifestSchema,
445
+ serializeMessage,
446
+ sha256Digest,
447
+ validateEnvelope,
448
+ validateResourceRelativePath,
449
+ verifyCanonicalPiResourceBundle,
450
+ workerResultImageUploadResponseSchema
451
+ };
11
452
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","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,"sources":["../src/ipc-codec.ts","../src/ipc-decode.ts","../src/ipc-messages.ts","../src/pi-resource-bundle.ts","../src/pi-resource-manifest.ts","../src/testing.ts","../src/worker-api-version.ts","../src/worker-ipc-transport.ts","../src/worker-session-snapshot.ts"],"sourcesContent":["import { parseSchema } from \"@leitwerk-dev/protocol\";\nimport * as v from \"valibot\";\n\nexport const IPC_PROTOCOL_VERSION = \"leitwerk/worker-ipc/v1\" as const;\n\nexport const IPC_ENVELOPE_SCHEMA = v.object({\n\tprotocol: v.literal(IPC_PROTOCOL_VERSION),\n\tmessageId: v.string(),\n\tcorrelationId: v.optional(v.string()),\n\ttype: v.string(),\n\tinstanceId: v.string(),\n\tworkerId: v.string(),\n\tsentAt: v.string(),\n\tpayload: v.unknown(),\n});\n\nexport type IpcEnvelope = v.InferOutput<typeof IPC_ENVELOPE_SCHEMA>;\n\nexport function validateEnvelope(\n\tmsg: unknown,\n): { ok: true; envelope: IpcEnvelope } | { ok: false; error: string } {\n\tif (\n\t\ttypeof msg === \"object\" &&\n\t\tmsg !== null &&\n\t\t\"protocol\" in msg &&\n\t\ttypeof msg.protocol === \"string\" &&\n\t\tmsg.protocol !== IPC_PROTOCOL_VERSION\n\t) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `Worker IPC protocol '${msg.protocol}' is incompatible with expected protocol '${IPC_PROTOCOL_VERSION}'`,\n\t\t};\n\t}\n\tconst envelope = parseSchema(IPC_ENVELOPE_SCHEMA, msg, \"ipc envelope\");\n\treturn envelope.ok\n\t\t? { ok: true, envelope: envelope.value }\n\t\t: { ok: false, error: envelope.error };\n}\n\nexport function serializeMessage<TEnvelope extends IpcEnvelope>(envelope: TEnvelope): string {\n\treturn JSON.stringify(envelope);\n}\n\nexport function deserializeMessage(\n\tline: string,\n): { ok: true; message: IpcEnvelope } | { ok: false; error: string } {\n\tconst trimmed =\n\t\tline.length > 0 && line.charCodeAt(line.length - 1) === 0x0d ? line.slice(0, -1) : line;\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(trimmed) as unknown;\n\t} catch {\n\t\treturn { ok: false, error: \"invalid JSON\" };\n\t}\n\tconst validated = validateEnvelope(parsed);\n\tif (!validated.ok) {\n\t\treturn { ok: false, error: validated.error };\n\t}\n\treturn { ok: true, message: validated.envelope };\n}\n","import { validateEnvelope } from \"./ipc-codec.js\";\nimport type { ServerToWorkerMessage, WorkerToServerMessage } from \"./ipc-messages.js\";\n\nexport type IpcDecodeResult<TMessage> =\n\t| { ok: true; message: TMessage }\n\t| { ok: false; error: string };\n\nconst SERVER_TO_WORKER_TYPES = [\n\t\"worker.start\",\n\t\"worker.turn_start_accepted\",\n\t\"worker.credential_update_accepted\",\n\t\"worker.question_response\",\n\t\"input.batch\",\n\t\"worker.stop\",\n\t\"worker.abort_turn\",\n] as const satisfies readonly ServerToWorkerMessage[\"type\"][];\n\nconst WORKER_TO_SERVER_TYPES = [\n\t\"worker.hello\",\n\t\"worker.credential_update\",\n\t\"worker.ready\",\n\t\"worker.heartbeat\",\n\t\"worker.state\",\n\t\"worker.input_consumed\",\n\t\"worker.event\",\n\t\"worker.turn_started\",\n\t\"worker.question_requested\",\n\t\"worker.turn_outcome\",\n\t\"worker.turn_failed\",\n\t\"worker.lifecycle_parked\",\n\t\"worker.cleanup_started\",\n\t\"worker.cleanup_completed\",\n\t\"worker.failed\",\n] as const satisfies readonly WorkerToServerMessage[\"type\"][];\n\nfunction hasMessageType<TType extends string>(\n\tallowed: readonly TType[],\n\tvalue: string,\n): value is TType {\n\treturn (allowed as readonly string[]).includes(value);\n}\n\n/**\n * Validate the generic IPC envelope and narrow it to the correct typed message\n * union member for the given direction.\n *\n * This intentionally stops at the message discriminant boundary: it validates\n * envelope structure + known message type, but does not deeply validate the\n * payload shape. Payload fields are trusted to come from same-version\n * leitwerk components, so malformed payloads from a buggy sender can still\n * pass through as typed data.\n */\nfunction decodeKnownMessage<TMessage extends { type: string }>(\n\tmsg: unknown,\n\tallowed: readonly TMessage[\"type\"][],\n\tdirection: string,\n): IpcDecodeResult<TMessage> {\n\tconst validated = validateEnvelope(msg);\n\tif (!validated.ok) {\n\t\treturn { ok: false, error: validated.error };\n\t}\n\tif (!hasMessageType(allowed, validated.envelope.type)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `unexpected ${direction} message type: ${validated.envelope.type}`,\n\t\t};\n\t}\n\treturn { ok: true, message: validated.envelope as unknown as TMessage };\n}\n\n/**\n * Decode a parsed envelope coming from the server side of the IPC channel.\n * Only envelope structure + message type are runtime-validated.\n */\nexport function decodeServerToWorkerMessage(msg: unknown): IpcDecodeResult<ServerToWorkerMessage> {\n\treturn decodeKnownMessage(msg, SERVER_TO_WORKER_TYPES, \"server-to-worker\");\n}\n\n/**\n * Decode a parsed envelope coming from the worker side of the IPC channel.\n * Only envelope structure + message type are runtime-validated.\n */\nexport function decodeWorkerToServerMessage(msg: unknown): IpcDecodeResult<WorkerToServerMessage> {\n\treturn decodeKnownMessage(msg, WORKER_TO_SERVER_TYPES, \"worker-to-server\");\n}\n","import type {\n\tCurrentExecutionRef,\n\tNormalizedQuestion,\n\tPreparedTurnStart,\n\tProcessInputTarget,\n\tProcessLifecycleStatus,\n\tProcessSemanticEntryRefKey,\n\tProcessTurnRecordPathType,\n\tProcessTurnType,\n\tTurnFailedPayload,\n\tTurnStartRecord,\n\tWorkerBootstrapReceipt,\n} from \"@leitwerk-dev/domain\";\nimport type { ConfigSnapshot } from \"@leitwerk-dev/protocol/config-snapshot\";\nimport { IPC_PROTOCOL_VERSION, type IpcEnvelope } from \"./ipc-codec.js\";\n\nexport interface ProcessInstanceSnapshot {\n\tid?: string;\n\tprocessId?: string;\n\tselectedTurnId?: string | null;\n\tlifecycleStatus?: ProcessLifecycleStatus;\n\tcurrentExecution?: CurrentExecutionRef;\n\tplanRevision?: number;\n\ttitle?: string | null;\n\texternalId?: string | null;\n\texternalUrl?: string | null;\n\tmetadata?: Record<string, unknown> | null;\n\tdefaultModelProfileId?: string | null;\n\tturnConfigsJson?: string | null;\n\tselectedTurnModelProfileId?: string | null;\n\tparamsJson?: string | null;\n\tstateJson?: string | null;\n\tcreatedAt?: string;\n\tupdatedAt?: string;\n}\n\nexport interface ProcessProjectSnapshot {\n\tid?: string;\n\tinstanceId?: string;\n\tkey: string;\n\trepoLocator: string;\n\trepoLocatorKind?: \"remote_url\" | \"local_path\";\n\tbaseBranch: string;\n\tworkBranch?: string | null;\n\texternalId?: string | null;\n\texternalUrl?: string | null;\n\tmetadata?: Record<string, unknown> | null;\n\tpipelineStatus?: string | null;\n\tcreatedAt?: string;\n\tupdatedAt?: string;\n}\n\nexport interface InputDelivery {\n\tinputId: string;\n\tsequence: number;\n\tsource: string;\n\tkind: string;\n\ttarget: ProcessInputTarget | null;\n\treceivedAt: string;\n\tbodyMarkdown: string;\n}\n\nexport interface WorkerRuntimeContextSnapshot {\n\tprocessSnapshot: ProcessInstanceSnapshot;\n\tprojectSnapshots: ProcessProjectSnapshot[];\n\tturnResultMarkdownBySemanticRef?: Partial<Record<ProcessSemanticEntryRefKey, string>>;\n\tturnResultMarkdownByProduct?: Record<string, string>;\n}\n\nexport interface WorkerCredentialMaterial {\n\tproviderId: string;\n\trevision: number;\n\t/** Secret payload. This type is valid only in worker.start and credential-update frames. */\n\tvalues: Record<string, string>;\n}\n\nexport interface WorkerGitSshCredential {\n\tprojectKey: string;\n\tkind: \"git_ssh\";\n\tcredentialRef: string;\n\t/** Secret values; valid only while preparing worker.start. */\n\tprivateKey: string;\n\tknownHosts: string;\n}\n\nexport interface LlmWorkerStartBootstrap {\n\tkind: \"llm\";\n\tresourceBundle: { digest: string; archiveBase64: string };\n\tcredential: WorkerCredentialMaterial | null;\n}\n\nexport interface AutomaticWorkerStartBootstrap {\n\tkind: \"automatic\";\n}\n\ninterface WorkerStartPayloadBase extends WorkerRuntimeContextSnapshot {\n\tworkerLeaseId: string;\n\tturnStart: TurnStartRecord;\n\t/**\n\t * The immutable pre-acceptance tree plan from the lease that first accepted\n\t * this start. It is supplied only when a replacement resumes a running turn.\n\t */\n\tacceptedPreparedStart?: PreparedTurnStart | null;\n\tpendingInputs: InputDelivery[];\n\ttreePaths: {\n\t\tprimaryTreeFile: string;\n\t\tworkspaceRoot: string;\n\t};\n\tresume: boolean;\n\tresumeLeafEntryId?: string | null;\n\t/** Fresh secret material resolved for this physical worker start only. */\n\trepositoryCredentials?: WorkerGitSshCredential[];\n}\n\nexport type WorkerStartPayload =\n\t| (WorkerStartPayloadBase & {\n\t\t\tbootstrap: LlmWorkerStartBootstrap;\n\t\t\tconfigSnapshot: ConfigSnapshot;\n\t })\n\t| (WorkerStartPayloadBase & { bootstrap: AutomaticWorkerStartBootstrap });\n\nexport interface InputBatchPayload {\n\tinputs: InputDelivery[];\n}\n\nexport interface WorkerStopPayload {\n\treason: string;\n}\n\nexport interface WorkerAbortTurnPayload {\n\treason: string;\n}\n\nexport interface WorkerTurnStartAcceptedPayload {\n\tstartRecordId: string;\n\tturnRecordId: string;\n}\n\nexport interface WorkerQuestionResponsePayload {\n\tturnRecordId: string;\n\ttoolCallId: string;\n\tanswers: string[];\n}\n\nexport interface WorkerQuestionRequestedPayload {\n\tturnRecordId: string;\n\ttoolCallId: string;\n\tquestions: NormalizedQuestion[];\n}\n\nexport interface WorkerCredentialUpdateResultPayload {\n\tproviderId: string;\n\taccepted: boolean;\n\tcurrentRevision: number | null;\n\tsafeReason?: string;\n}\n\nexport type ServerToWorkerMessage =\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.start\";\n\t\t\tpayload: WorkerStartPayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.turn_start_accepted\";\n\t\t\tpayload: WorkerTurnStartAcceptedPayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.credential_update_accepted\";\n\t\t\tpayload: WorkerCredentialUpdateResultPayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.question_response\";\n\t\t\tpayload: WorkerQuestionResponsePayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"input.batch\";\n\t\t\tpayload: InputBatchPayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.stop\";\n\t\t\tpayload: WorkerStopPayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.abort_turn\";\n\t\t\tpayload: WorkerAbortTurnPayload;\n\t });\n\nexport interface WorkerHelloPayload {\n\t/** Package/runtime version for diagnostics. */\n\tversion: string;\n\t/** Server-worker API compatibility version. Missing only on legacy/test workers. */\n\tapiVersion?: string;\n\tcapabilities: string[];\n}\n\nexport interface WorkerReadyPayload {\n\treceipt: WorkerBootstrapReceipt;\n\tresumed: boolean;\n\tprimaryTreeFile: string;\n\tworkspaceRoot: string;\n\taggregatedAgentsSources: string[];\n\tloadedSkills: string[];\n\tloadedAgentsFiles: Array<{ path: string; sizeBytes: number }>;\n\tloadedSkillFiles: Array<{ name: string; path: string }>;\n\trootEntryId?: string | null;\n}\n\nexport interface WorkerHeartbeatPayload {\n\t/** Diagnostic worker-local runtime state; not the authoritative lease transition channel. */\n\tstate: string;\n\tlastSequenceConsumed: number;\n\tcurrentTurnId?: string;\n\tcurrentSelectedTurnId?: string | null;\n}\n\nexport interface WorkerStatePayload {\n\t/** Explicit server-visible runtime transition, e.g. idle -> busy or busy -> idle. */\n\tfrom: string;\n\tto: string;\n\treason: string;\n}\n\nexport interface WorkerInputConsumedPayload {\n\tinputId: string;\n\tsequence: number;\n\tdeliveryMode: string;\n\tcurrentPrimaryPathLeafId?: string | null;\n\trootEntryId?: string | null;\n\ttargetSemanticRef?: ProcessSemanticEntryRefKey | null;\n\ttargetProductName?: string | null;\n\ttargetEntryId?: string | null;\n}\n\nexport interface WorkerEventPayload {\n\teventType: string;\n\tselectedTurnId?: string | null;\n\t/**\n\t * Object-shaped event data emitted by trusted worker senders. Decode helpers\n\t * do not deeply validate this field at runtime; they only narrow it at the\n\t * protocol boundary after envelope + message-type validation.\n\t */\n\tdata: Record<string, unknown>;\n}\n\nexport interface WorkerTurnStartedPayload {\n\tstartRecordId: string;\n\tproposedTurnRecordId: string;\n}\n\nexport interface WorkerCredentialUpdatePayload {\n\tproviderId: string;\n\texpectedRevision: number;\n\t/** Secret payload. It must not be copied into receipts, events, or turn state. */\n\tvalues: Record<string, string>;\n}\n\nexport interface WorkerTurnOutcomePayload {\n\tturnRecordId: string;\n\tturnId: string;\n\tturnType: ProcessTurnType;\n\toutcome: string;\n\tparams: Record<string, unknown>;\n\tpathType?: ProcessTurnRecordPathType;\n\tforkPiEntryId?: string | null;\n\tresultPiEntryId?: string | null;\n\tturnResultMarkdown?: string | null;\n\trootEntryId?: string | null;\n}\n\nexport interface WorkerTurnFailedPayload\n\textends Omit<TurnFailedPayload, \"instanceId\" | \"errorClass\"> {\n\terrorClass?: string;\n}\n\nexport interface WorkerLifecycleParkedPayload {\n\tselectedTurnId: string | null;\n\treason?: string;\n\terrorClass?: string;\n}\n\nexport interface WorkerCleanupStartedPayload {\n\treason: string;\n}\n\nexport interface WorkerCleanupCompletedPayload {\n\treleasedLocks: string[];\n\tremovedTransientPaths: string[];\n}\n\nexport interface WorkerFailedPayload {\n\tstate: string;\n\terrorCode: string;\n\tmessage: string;\n\terrorClass: string;\n\tselectedTurnId?: string | null;\n\tretryAttempt?: number;\n}\n\nexport type WorkerToServerMessage =\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.hello\";\n\t\t\tpayload: WorkerHelloPayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.credential_update\";\n\t\t\tpayload: WorkerCredentialUpdatePayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.ready\";\n\t\t\tpayload: WorkerReadyPayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.heartbeat\";\n\t\t\tpayload: WorkerHeartbeatPayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.state\";\n\t\t\tpayload: WorkerStatePayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.input_consumed\";\n\t\t\tpayload: WorkerInputConsumedPayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.event\";\n\t\t\tpayload: WorkerEventPayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.turn_started\";\n\t\t\tpayload: WorkerTurnStartedPayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.question_requested\";\n\t\t\tpayload: WorkerQuestionRequestedPayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.turn_outcome\";\n\t\t\tpayload: WorkerTurnOutcomePayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.turn_failed\";\n\t\t\tpayload: WorkerTurnFailedPayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.lifecycle_parked\";\n\t\t\tpayload: WorkerLifecycleParkedPayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.cleanup_started\";\n\t\t\tpayload: WorkerCleanupStartedPayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.cleanup_completed\";\n\t\t\tpayload: WorkerCleanupCompletedPayload;\n\t })\n\t| (Omit<IpcEnvelope, \"type\" | \"payload\"> & {\n\t\t\ttype: \"worker.failed\";\n\t\t\tpayload: WorkerFailedPayload;\n\t });\n\nexport type AnyIpcMessage = ServerToWorkerMessage | WorkerToServerMessage;\nexport type IpcMessageType = AnyIpcMessage[\"type\"];\nexport type IpcMessageOfType<TType extends IpcMessageType> = Extract<\n\tAnyIpcMessage,\n\t{ type: TType }\n>;\n\nexport function createIpcMessage<TMessage extends AnyIpcMessage>(\n\targs: Omit<TMessage, \"protocol\" | \"sentAt\"> & { sentAt?: string },\n): TMessage {\n\treturn {\n\t\tprotocol: IPC_PROTOCOL_VERSION,\n\t\tmessageId: args.messageId,\n\t\tcorrelationId: args.correlationId,\n\t\ttype: args.type,\n\t\tinstanceId: args.instanceId,\n\t\tworkerId: args.workerId,\n\t\tsentAt: args.sentAt ?? new Date().toISOString(),\n\t\tpayload: args.payload,\n\t} as TMessage;\n}\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\n\nconst BLOCK_SIZE = 512;\n\nexport interface PiResourceFile {\n\tpath: string;\n\tcontent: Uint8Array;\n}\n\nexport interface PiResourceBundle {\n\tdigest: string;\n\tbytes: Uint8Array;\n}\n\nexport interface ExtractedPiResourceFile {\n\tpath: string;\n\tcontent: Uint8Array;\n}\n\nfunction fail(message: string): never {\n\tthrow new Error(`Invalid Pi resource bundle: ${message}`);\n}\n\nexport function validateResourceRelativePath(value: string): string {\n\tif (!value || path.posix.isAbsolute(value) || value.includes(\"\\\\\")) {\n\t\tfail(`unsafe path '${value}'`);\n\t}\n\tconst normalized = path.posix.normalize(value);\n\tif (normalized === \".\" || normalized === \"..\" || normalized.startsWith(\"../\")) {\n\t\tfail(`unsafe path '${value}'`);\n\t}\n\treturn normalized;\n}\n\nfunction writeString(buffer: Buffer, offset: number, length: number, value: string): void {\n\tconst encoded = Buffer.from(value, \"utf8\");\n\tif (encoded.length > length) fail(`header value too long: ${value}`);\n\tencoded.copy(buffer, offset);\n}\n\nfunction writeOctal(buffer: Buffer, offset: number, length: number, value: number): void {\n\tconst encoded = value.toString(8).padStart(length - 1, \"0\");\n\tif (encoded.length > length - 1) fail(`numeric header value too large: ${value}`);\n\twriteString(buffer, offset, length - 1, encoded);\n\tbuffer[offset + length - 1] = 0;\n}\n\nfunction header(name: string, size: number): Buffer {\n\tif (Buffer.byteLength(name) > 100) fail(`path exceeds canonical ustar name limit: ${name}`);\n\tconst result = Buffer.alloc(BLOCK_SIZE);\n\twriteString(result, 0, 100, name);\n\twriteOctal(result, 100, 8, 0o644);\n\twriteOctal(result, 108, 8, 0);\n\twriteOctal(result, 116, 8, 0);\n\twriteOctal(result, 124, 12, size);\n\twriteOctal(result, 136, 12, 0);\n\tresult.fill(0x20, 148, 156);\n\tresult[156] = \"0\".charCodeAt(0);\n\twriteString(result, 257, 6, \"ustar\");\n\twriteString(result, 263, 2, \"00\");\n\tconst sum = result.reduce((total, byte) => total + byte, 0);\n\twriteString(result, 148, 8, `${sum.toString(8).padStart(6, \"0\")}\\0 `);\n\treturn result;\n}\n\nfunction padding(size: number): Buffer {\n\tconst length = (BLOCK_SIZE - (size % BLOCK_SIZE)) % BLOCK_SIZE;\n\treturn Buffer.alloc(length);\n}\n\nexport function sha256Digest(bytes: Uint8Array): string {\n\treturn createHash(\"sha256\").update(bytes).digest(\"hex\");\n}\n\n/** Creates a deterministic, uncompressed ustar archive containing regular files only. */\nexport function createCanonicalPiResourceBundle(\n\tfiles: readonly PiResourceFile[],\n): PiResourceBundle {\n\tconst seen = new Set<string>();\n\tconst normalized = files.map((file) => {\n\t\tconst resourcePath = validateResourceRelativePath(file.path);\n\t\tif (seen.has(resourcePath)) fail(`duplicate path '${resourcePath}'`);\n\t\tseen.add(resourcePath);\n\t\treturn { path: resourcePath, content: Buffer.from(file.content) };\n\t});\n\tnormalized.sort((left, right) => Buffer.compare(Buffer.from(left.path), Buffer.from(right.path)));\n\tconst chunks: Buffer[] = [];\n\tfor (const file of normalized) {\n\t\tchunks.push(header(file.path, file.content.length), file.content, padding(file.content.length));\n\t}\n\tchunks.push(Buffer.alloc(BLOCK_SIZE * 2));\n\tconst bytes = Buffer.concat(chunks);\n\treturn { bytes, digest: sha256Digest(bytes) };\n}\n\nfunction readNullString(block: Uint8Array, start: number, length: number): string {\n\tconst end = block.subarray(start, start + length).indexOf(0);\n\treturn Buffer.from(block.subarray(start, end < 0 ? start + length : start + end)).toString(\n\t\t\"utf8\",\n\t);\n}\n\nfunction readOctal(block: Uint8Array, start: number, length: number): number {\n\tconst raw = readNullString(block, start, length).trim();\n\tif (!/^[0-7]*$/.test(raw)) fail(\"non-octal numeric field\");\n\treturn raw ? Number.parseInt(raw, 8) : 0;\n}\n\nfunction verifyChecksum(block: Uint8Array): void {\n\tconst expected = readOctal(block, 148, 8);\n\tlet actual = 0;\n\tfor (let index = 0; index < BLOCK_SIZE; index++) {\n\t\tactual += index >= 148 && index < 156 ? 32 : block[index];\n\t}\n\tif (actual !== expected) fail(\"header checksum mismatch\");\n}\n\nfunction allZero(block: Uint8Array): boolean {\n\treturn block.every((byte) => byte === 0);\n}\n\n/** Parses only the narrow regular-file ustar subset emitted by this module. */\nexport function verifyCanonicalPiResourceBundle(\n\tbytes: Uint8Array,\n\texpectedDigest?: string,\n): ExtractedPiResourceFile[] {\n\tif (expectedDigest && sha256Digest(bytes) !== expectedDigest) fail(\"content digest mismatch\");\n\tif (bytes.length < BLOCK_SIZE * 2 || bytes.length % BLOCK_SIZE !== 0) {\n\t\tfail(\"invalid archive length\");\n\t}\n\tconst files: ExtractedPiResourceFile[] = [];\n\tconst paths = new Set<string>();\n\tlet offset = 0;\n\twhile (offset < bytes.length) {\n\t\tconst block = bytes.subarray(offset, offset + BLOCK_SIZE);\n\t\tif (allZero(block)) {\n\t\t\tif (!allZero(bytes.subarray(offset + BLOCK_SIZE, offset + BLOCK_SIZE * 2))) {\n\t\t\t\tfail(\"missing end blocks\");\n\t\t\t}\n\t\t\tif (offset + BLOCK_SIZE * 2 !== bytes.length) fail(\"data after end blocks\");\n\t\t\treturn files;\n\t\t}\n\t\tverifyChecksum(block);\n\t\tif (readNullString(block, 257, 6) !== \"ustar\") fail(\"unsupported tar format\");\n\t\tconst type = readNullString(block, 156, 1);\n\t\tif (type !== \"\" && type !== \"0\") fail(`unsupported entry type '${type}'`);\n\t\tif (readNullString(block, 157, 100) || readNullString(block, 345, 155)) {\n\t\t\tfail(\"links and ustar path prefixes are unsupported\");\n\t\t}\n\t\tconst name = validateResourceRelativePath(readNullString(block, 0, 100));\n\t\tif (paths.has(name)) fail(`duplicate path '${name}'`);\n\t\tpaths.add(name);\n\t\tconst size = readOctal(block, 124, 12);\n\t\tconst contentStart = offset + BLOCK_SIZE;\n\t\tconst contentEnd = contentStart + size;\n\t\tif (contentEnd > bytes.length) fail(\"truncated file content\");\n\t\tfiles.push({ path: name, content: bytes.slice(contentStart, contentEnd) });\n\t\toffset = contentEnd + ((BLOCK_SIZE - (size % BLOCK_SIZE)) % BLOCK_SIZE);\n\t}\n\tfail(\"missing end blocks\");\n}\n","import * as v from \"valibot\";\nimport { validateResourceRelativePath } from \"./pi-resource-bundle.js\";\n\nexport const PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION = 1;\n\nconst nonBlankStringSchema = v.pipe(\n\tv.string(),\n\tv.check((value) => value.trim() !== \"\", \"Expected a non-empty string\"),\n);\nconst jsonObjectSchema = v.record(v.string(), v.unknown());\nconst positiveSafeIntegerSchema = v.pipe(v.number(), v.safeInteger(), v.minValue(1));\nconst nonNegativeSafeIntegerSchema = v.pipe(v.number(), v.safeInteger(), v.minValue(0));\n\nexport const piResourceManifestSchema = v.strictObject({\n\tschemaVersion: v.literal(PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION),\n\tmodel: v.strictObject({\n\t\tprofileId: nonBlankStringSchema,\n\t\tproviderId: nonBlankStringSchema,\n\t\tmodelId: nonBlankStringSchema,\n\t\tthinkingLevel: nonBlankStringSchema,\n\t}),\n\tproviderOptions: v.record(v.string(), nonBlankStringSchema),\n\tproviderWorkerConfig: v.nullable(\n\t\tv.strictObject({\n\t\t\tversion: positiveSafeIntegerSchema,\n\t\t\tvalue: jsonObjectSchema,\n\t\t}),\n\t),\n\tdeclaredCredentialPaths: v.array(nonBlankStringSchema),\n\tcompatibility: v.strictObject({\n\t\tworkerApiVersion: nonBlankStringSchema,\n\t\tpiVersion: nonBlankStringSchema,\n\t\tprotocolVersion: v.optional(nonBlankStringSchema),\n\t}),\n\tprovenance: v.array(\n\t\tv.strictObject({\n\t\t\tkind: v.picklist([\"extension\", \"skill\", \"prompt\", \"generated\"]),\n\t\t\townerExtensionId: v.nullable(nonBlankStringSchema),\n\t\t\tpackageName: v.nullable(nonBlankStringSchema),\n\t\t\tsnapshotPath: nonBlankStringSchema,\n\t\t\tsha256: v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/)),\n\t\t\tsize: nonNegativeSafeIntegerSchema,\n\t\t}),\n\t),\n});\n\ntype DeepReadonly<T> = T extends readonly unknown[]\n\t? { readonly [Index in keyof T]: DeepReadonly<T[Index]> }\n\t: T extends object\n\t\t? { readonly [Key in keyof T]: DeepReadonly<T[Key]> }\n\t\t: T;\n\nexport type PiResourceManifest = DeepReadonly<v.InferOutput<typeof piResourceManifestSchema>>;\nexport type PiResourceSnapshotModel = PiResourceManifest[\"model\"];\nexport type PiResourceSnapshotWorkerConfig = NonNullable<\n\tPiResourceManifest[\"providerWorkerConfig\"]\n>;\nexport type PiResourceSnapshotCompatibility = PiResourceManifest[\"compatibility\"];\nexport type PiResourceFileProvenance = PiResourceManifest[\"provenance\"][number];\nexport type PiResourceProvenanceKind = PiResourceFileProvenance[\"kind\"];\n\nfunction invalidManifest(message: string, cause?: unknown): never {\n\tthrow new Error(`Invalid managed Pi resource snapshot: ${message}`, { cause });\n}\n\n/** Parses and validates the complete generated.json contract. */\nexport function parsePiResourceManifest(raw: unknown): PiResourceManifest {\n\tlet manifest: PiResourceManifest;\n\ttry {\n\t\tmanifest = v.parse(piResourceManifestSchema, raw);\n\t} catch (error) {\n\t\tinvalidManifest(\"generated.json does not match the resource manifest schema\", error);\n\t}\n\n\tlet declaredCredentialPaths: string[];\n\tlet provenance: PiResourceFileProvenance[];\n\ttry {\n\t\tdeclaredCredentialPaths = manifest.declaredCredentialPaths.map(validateResourceRelativePath);\n\t\tprovenance = manifest.provenance.map((item) => ({\n\t\t\t...item,\n\t\t\tsnapshotPath: validateResourceRelativePath(item.snapshotPath),\n\t\t}));\n\t} catch (error) {\n\t\tinvalidManifest(\"generated.json contains an unsafe path\", error);\n\t}\n\tif (new Set(declaredCredentialPaths).size !== declaredCredentialPaths.length) {\n\t\tinvalidManifest(\"generated.json declares a credential path more than once\");\n\t}\n\tconst provenancePaths = provenance.map((item) => item.snapshotPath);\n\tif (new Set(provenancePaths).size !== provenancePaths.length) {\n\t\tinvalidManifest(\"generated.json contains duplicate provenance paths\");\n\t}\n\tfor (const credentialPath of declaredCredentialPaths) {\n\t\tif (credentialPath === \"generated.json\" || provenancePaths.includes(credentialPath)) {\n\t\t\tinvalidManifest(`credential path '${credentialPath}' overlaps immutable snapshot content`);\n\t\t}\n\t}\n\treturn { ...manifest, declaredCredentialPaths, provenance };\n}\n\ntype JsonRecord = Record<string, unknown>;\n\nexport function canonicalizeJson(value: unknown, location = \"value\"): unknown {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) throw new Error(`${location} contains a non-finite number`);\n\t\treturn Object.is(value, -0) ? 0 : value;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.map((item, index) => canonicalizeJson(item, `${location}[${index}]`));\n\t}\n\tif (typeof value !== \"object\") throw new Error(`${location} contains a non-JSON value`);\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype !== Object.prototype && prototype !== null) {\n\t\tthrow new Error(`${location} contains a non-plain object`);\n\t}\n\treturn Object.fromEntries(\n\t\tObject.keys(value as JsonRecord)\n\t\t\t.sort((left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right)))\n\t\t\t.map((key) => [key, canonicalizeJson((value as JsonRecord)[key], `${location}.${key}`)]),\n\t);\n}\n\nexport function canonicalJsonStringify(value: unknown, location = \"value\"): string {\n\treturn JSON.stringify(canonicalizeJson(value, location));\n}\n\nexport function canonicalJsonEqual(left: unknown, right: unknown): boolean {\n\treturn canonicalJsonStringify(left) === canonicalJsonStringify(right);\n}\n","import type { ConfigSnapshot } from \"@leitwerk-dev/protocol/config-snapshot\";\n\nexport function createTestConfigSnapshot(): ConfigSnapshot {\n\treturn {\n\t\tworkers: {\n\t\t\theartbeat_interval: \"5s\",\n\t\t\tturn_max_duration: \"30m\",\n\t\t\tturn_inactivity_timeout: \"5m\",\n\t\t\tturn_abort_grace_period: \"5s\",\n\t\t},\n\t\tpi: {\n\t\t\tagent_dir: \"~/.pi/leitwerk\",\n\t\t\tmodel_profiles: [],\n\t\t\tprocess_title_generation: {\n\t\t\t\tmodel_profile: null,\n\t\t\t\tretry: {\n\t\t\t\t\tmax_attempts: 6,\n\t\t\t\t\tbase_delay: \"5s\",\n\t\t\t\t\tmax_delay: \"5m\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tretry: {\n\t\t\t\tenabled: true,\n\t\t\t\tmax_retries: 3,\n\t\t\t\tbase_delay: \"2s\",\n\t\t\t\tprovider: {\n\t\t\t\t\ttimeout: null,\n\t\t\t\t\tmax_retries: null,\n\t\t\t\t\tmax_retry_delay: \"60s\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t};\n}\n","/**\n * Compatibility version for the server ↔ worker runtime API.\n *\n * Container image labels use the same value (`leitwerk.dev/worker-api-version`).\n * Workers also report it in `worker.hello` so the server can fail fast when a\n * pod image is from an incompatible leitwerk build line.\n */\nexport const WORKER_API_VERSION = \"2026-07-26\";\n","export const WORKER_INSTANCE_ID_ENV = \"LEITWERK_INSTANCE_ID\";\nexport const WORKER_ID_ENV = \"LEITWERK_WORKER_ID\";\nexport const WORKER_IPC_SERVER_URL_ENV = \"LEITWERK_SERVER_URL\";\nexport const WORKER_IPC_CONNECT_TOKEN_ENV = \"LEITWERK_WORKER_CONNECT_TOKEN\";\nexport const WORKER_IPC_RECONNECT_ENV = \"LEITWERK_WORKER_RECONNECT\";\nexport const WORKER_SNAPSHOT_TOKEN_ENV = \"LEITWERK_WORKER_SNAPSHOT_TOKEN\";\nexport const WORKER_SERVER_EPOCH_ENV = \"LEITWERK_SERVER_EPOCH\";\n","export const WORKER_SESSION_SNAPSHOT_CONTENT_TYPE = \"application/x-ndjson\";\nexport const WORKER_SESSION_SNAPSHOT_WORKER_ID_HEADER = \"x-leitwerk-worker-id\";\nexport const WORKER_SESSION_SNAPSHOT_REASON_HEADER = \"x-leitwerk-session-snapshot-reason\";\nexport const WORKER_SESSION_SNAPSHOT_TURN_RECORD_ID_HEADER = \"x-leitwerk-turn-record-id\";\nexport function buildWorkerSessionSnapshotPath(instanceId: string): string {\n\treturn `/internal/workers/${encodeURIComponent(instanceId)}/session-snapshot`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,mBAAmB;AAC5B,YAAY,OAAO;AAEZ,IAAM,uBAAuB;AAE7B,IAAM,sBAAwB,SAAO;AAAA,EAC3C,UAAY,UAAQ,oBAAoB;AAAA,EACxC,WAAa,SAAO;AAAA,EACpB,eAAiB,WAAW,SAAO,CAAC;AAAA,EACpC,MAAQ,SAAO;AAAA,EACf,YAAc,SAAO;AAAA,EACrB,UAAY,SAAO;AAAA,EACnB,QAAU,SAAO;AAAA,EACjB,SAAW,UAAQ;AACpB,CAAC;AAIM,SAAS,iBACf,KACqE;AACrE,MACC,OAAO,QAAQ,YACf,QAAQ,QACR,cAAc,OACd,OAAO,IAAI,aAAa,YACxB,IAAI,aAAa,sBAChB;AACD,WAAO;AAAA,MACN,IAAI;AAAA,MACJ,OAAO,wBAAwB,IAAI,QAAQ,6CAA6C,oBAAoB;AAAA,IAC7G;AAAA,EACD;AACA,QAAM,WAAW,YAAY,qBAAqB,KAAK,cAAc;AACrE,SAAO,SAAS,KACb,EAAE,IAAI,MAAM,UAAU,SAAS,MAAM,IACrC,EAAE,IAAI,OAAO,OAAO,SAAS,MAAM;AACvC;AAEO,SAAS,iBAAgD,UAA6B;AAC5F,SAAO,KAAK,UAAU,QAAQ;AAC/B;AAEO,SAAS,mBACf,MACoE;AACpE,QAAM,UACL,KAAK,SAAS,KAAK,KAAK,WAAW,KAAK,SAAS,CAAC,MAAM,KAAO,KAAK,MAAM,GAAG,EAAE,IAAI;AACpF,MAAI;AACJ,MAAI;AACH,aAAS,KAAK,MAAM,OAAO;AAAA,EAC5B,QAAQ;AACP,WAAO,EAAE,IAAI,OAAO,OAAO,eAAe;AAAA,EAC3C;AACA,QAAM,YAAY,iBAAiB,MAAM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A+B,YAA4B;AAC1E,SAAO,qBAAqB,mBAAmB,UAAU,CAAC;AAC3D;","names":["v"]}
@@ -1,27 +1,29 @@
1
- import * as v from "valibot";
2
- export declare const WORKER_RESULT_IMAGE_WORKER_ID_HEADER = "x-leitwerk-worker-id";
3
- export declare const RESULT_IMAGE_MIME_TYPES: readonly ["image/png", "image/jpeg", "image/webp"];
4
- export declare const RESULT_IMAGE_MAX_SIZE_BYTES: number;
5
- export declare const RESULT_IMAGE_STORAGE_SEGMENT_PATTERN: RegExp;
6
- export declare const RESULT_IMAGE_ID_PATTERN: RegExp;
7
- export type ResultImageMimeType = (typeof RESULT_IMAGE_MIME_TYPES)[number];
8
- export declare function isResultImageStorageSegment(value: string): boolean;
9
- export declare function parseResultImageId(value: string): {
1
+ import * as v from 'valibot';
2
+
3
+ declare const WORKER_RESULT_IMAGE_WORKER_ID_HEADER = "x-leitwerk-worker-id";
4
+ declare const RESULT_IMAGE_MIME_TYPES: readonly ["image/png", "image/jpeg", "image/webp"];
5
+ declare const RESULT_IMAGE_MAX_SIZE_BYTES: number;
6
+ declare const RESULT_IMAGE_STORAGE_SEGMENT_PATTERN: RegExp;
7
+ declare const RESULT_IMAGE_ID_PATTERN: RegExp;
8
+ type ResultImageMimeType = (typeof RESULT_IMAGE_MIME_TYPES)[number];
9
+ declare function isResultImageStorageSegment(value: string): boolean;
10
+ declare function parseResultImageId(value: string): {
10
11
  extension: "png" | "jpg" | "webp";
11
12
  } | null;
12
- export declare const workerResultImageUploadResponseSchema: v.ObjectSchema<{
13
+ declare const workerResultImageUploadResponseSchema: v.ObjectSchema<{
13
14
  readonly imageId: v.StringSchema<undefined>;
14
15
  readonly url: v.StringSchema<undefined>;
15
16
  readonly mimeType: v.PicklistSchema<readonly ["image/png", "image/jpeg", "image/webp"], undefined>;
16
17
  readonly byteSize: v.NumberSchema<undefined>;
17
18
  }, undefined>;
18
- export type WorkerResultImageUploadResponse = v.InferOutput<typeof workerResultImageUploadResponseSchema>;
19
- export declare function buildWorkerResultImageUploadPath(instanceId: string, turnRecordId: string): string;
20
- export declare function buildManagedResultImagePath(instanceId: string, turnRecordId: string, imageId: string): string;
21
- export declare function parseManagedResultImagePath(value: string): {
19
+ type WorkerResultImageUploadResponse = v.InferOutput<typeof workerResultImageUploadResponseSchema>;
20
+ declare function buildWorkerResultImageUploadPath(instanceId: string, turnRecordId: string): string;
21
+ declare function buildManagedResultImagePath(instanceId: string, turnRecordId: string, imageId: string): string;
22
+ declare function parseManagedResultImagePath(value: string): {
22
23
  instanceId: string;
23
24
  turnRecordId: string;
24
25
  imageId: string;
25
26
  } | null;
26
- export declare function parseWorkerResultImageUploadResponse(value: unknown): WorkerResultImageUploadResponse | null;
27
- //# sourceMappingURL=worker-result-image.d.ts.map
27
+ declare function parseWorkerResultImageUploadResponse(value: unknown): WorkerResultImageUploadResponse | null;
28
+
29
+ export { RESULT_IMAGE_ID_PATTERN, RESULT_IMAGE_MAX_SIZE_BYTES, RESULT_IMAGE_MIME_TYPES, RESULT_IMAGE_STORAGE_SEGMENT_PATTERN, type ResultImageMimeType, WORKER_RESULT_IMAGE_WORKER_ID_HEADER, type WorkerResultImageUploadResponse, buildManagedResultImagePath, buildWorkerResultImageUploadPath, isResultImageStorageSegment, parseManagedResultImagePath, parseResultImageId, parseWorkerResultImageUploadResponse, workerResultImageUploadResponseSchema };