@leitwerk-dev/worker-protocol 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/LICENSE +13 -0
  2. package/dist/chunk-DVN32ANP.js +62 -0
  3. package/dist/chunk-DVN32ANP.js.map +1 -0
  4. package/dist/index.d.ts +11 -0
  5. package/dist/index.d.ts.map +1 -0
  6. package/dist/index.js +11 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/ipc-codec.d.ts +29 -0
  9. package/dist/ipc-codec.d.ts.map +1 -0
  10. package/dist/ipc-codec.js +48 -0
  11. package/dist/ipc-codec.js.map +1 -0
  12. package/dist/ipc-decode.d.ts +19 -0
  13. package/dist/ipc-decode.d.ts.map +1 -0
  14. package/dist/ipc-decode.js +68 -0
  15. package/dist/ipc-decode.js.map +1 -0
  16. package/dist/ipc-messages.d.ts +310 -0
  17. package/dist/ipc-messages.d.ts.map +1 -0
  18. package/dist/ipc-messages.js +14 -0
  19. package/dist/ipc-messages.js.map +1 -0
  20. package/dist/pi-resource-bundle.d.ts +19 -0
  21. package/dist/pi-resource-bundle.d.ts.map +1 -0
  22. package/dist/pi-resource-bundle.js +139 -0
  23. package/dist/pi-resource-bundle.js.map +1 -0
  24. package/dist/pi-resource-manifest.d.ts +48 -0
  25. package/dist/pi-resource-manifest.d.ts.map +1 -0
  26. package/dist/pi-resource-manifest.js +101 -0
  27. package/dist/pi-resource-manifest.js.map +1 -0
  28. package/dist/testing.d.ts +3 -0
  29. package/dist/testing.d.ts.map +1 -0
  30. package/dist/testing.js +33 -0
  31. package/dist/testing.js.map +1 -0
  32. package/dist/worker-api-version.d.ts +9 -0
  33. package/dist/worker-api-version.d.ts.map +1 -0
  34. package/dist/worker-api-version.js +9 -0
  35. package/dist/worker-api-version.js.map +1 -0
  36. package/dist/worker-ipc-transport.d.ts +8 -0
  37. package/dist/worker-ipc-transport.d.ts.map +1 -0
  38. package/dist/worker-ipc-transport.js +8 -0
  39. package/dist/worker-ipc-transport.js.map +1 -0
  40. package/dist/worker-result-image.d.ts +27 -0
  41. package/dist/worker-result-image.d.ts.map +1 -0
  42. package/dist/worker-result-image.js +55 -0
  43. package/dist/worker-result-image.js.map +1 -0
  44. package/dist/worker-session-snapshot.d.ts +6 -0
  45. package/dist/worker-session-snapshot.d.ts.map +1 -0
  46. package/dist/worker-session-snapshot.js +8 -0
  47. package/dist/worker-session-snapshot.js.map +1 -0
  48. package/package.json +46 -0
  49. package/src/index.ts +10 -0
  50. package/src/ipc-codec.ts +60 -0
  51. package/src/ipc-decode.ts +85 -0
  52. package/src/ipc-messages.ts +381 -0
  53. package/src/pi-resource-bundle.ts +162 -0
  54. package/src/pi-resource-manifest.ts +130 -0
  55. package/src/testing.ts +34 -0
  56. package/src/worker-api-version.ts +8 -0
  57. package/src/worker-ipc-transport.ts +7 -0
  58. package/src/worker-result-image.ts +78 -0
  59. package/src/worker-session-snapshot.ts +7 -0
@@ -0,0 +1,130 @@
1
+ import * as v from "valibot";
2
+ import { validateResourceRelativePath } from "./pi-resource-bundle.js";
3
+
4
+ export const PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION = 1;
5
+
6
+ const nonBlankStringSchema = v.pipe(
7
+ v.string(),
8
+ v.check((value) => value.trim() !== "", "Expected a non-empty string"),
9
+ );
10
+ const jsonObjectSchema = v.record(v.string(), v.unknown());
11
+ const positiveSafeIntegerSchema = v.pipe(v.number(), v.safeInteger(), v.minValue(1));
12
+ const nonNegativeSafeIntegerSchema = v.pipe(v.number(), v.safeInteger(), v.minValue(0));
13
+
14
+ export const piResourceManifestSchema = v.strictObject({
15
+ schemaVersion: v.literal(PI_RESOURCE_SNAPSHOT_SCHEMA_VERSION),
16
+ model: v.strictObject({
17
+ profileId: nonBlankStringSchema,
18
+ providerId: nonBlankStringSchema,
19
+ modelId: nonBlankStringSchema,
20
+ thinkingLevel: nonBlankStringSchema,
21
+ }),
22
+ providerOptions: v.record(v.string(), nonBlankStringSchema),
23
+ providerWorkerConfig: v.nullable(
24
+ v.strictObject({
25
+ version: positiveSafeIntegerSchema,
26
+ value: jsonObjectSchema,
27
+ }),
28
+ ),
29
+ declaredCredentialPaths: v.array(nonBlankStringSchema),
30
+ compatibility: v.strictObject({
31
+ workerApiVersion: nonBlankStringSchema,
32
+ piVersion: nonBlankStringSchema,
33
+ protocolVersion: v.optional(nonBlankStringSchema),
34
+ }),
35
+ provenance: v.array(
36
+ v.strictObject({
37
+ kind: v.picklist(["extension", "skill", "prompt", "generated"]),
38
+ ownerExtensionId: v.nullable(nonBlankStringSchema),
39
+ packageName: v.nullable(nonBlankStringSchema),
40
+ snapshotPath: nonBlankStringSchema,
41
+ sha256: v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/)),
42
+ size: nonNegativeSafeIntegerSchema,
43
+ }),
44
+ ),
45
+ });
46
+
47
+ type DeepReadonly<T> = T extends readonly unknown[]
48
+ ? { readonly [Index in keyof T]: DeepReadonly<T[Index]> }
49
+ : T extends object
50
+ ? { readonly [Key in keyof T]: DeepReadonly<T[Key]> }
51
+ : T;
52
+
53
+ export type PiResourceManifest = DeepReadonly<v.InferOutput<typeof piResourceManifestSchema>>;
54
+ export type PiResourceSnapshotModel = PiResourceManifest["model"];
55
+ export type PiResourceSnapshotWorkerConfig = NonNullable<
56
+ PiResourceManifest["providerWorkerConfig"]
57
+ >;
58
+ export type PiResourceSnapshotCompatibility = PiResourceManifest["compatibility"];
59
+ export type PiResourceFileProvenance = PiResourceManifest["provenance"][number];
60
+ export type PiResourceProvenanceKind = PiResourceFileProvenance["kind"];
61
+
62
+ function invalidManifest(message: string, cause?: unknown): never {
63
+ throw new Error(`Invalid managed Pi resource snapshot: ${message}`, { cause });
64
+ }
65
+
66
+ /** Parses and validates the complete generated.json contract. */
67
+ export function parsePiResourceManifest(raw: unknown): PiResourceManifest {
68
+ let manifest: PiResourceManifest;
69
+ try {
70
+ manifest = v.parse(piResourceManifestSchema, raw);
71
+ } catch (error) {
72
+ invalidManifest("generated.json does not match the resource manifest schema", error);
73
+ }
74
+
75
+ let declaredCredentialPaths: string[];
76
+ let provenance: PiResourceFileProvenance[];
77
+ try {
78
+ declaredCredentialPaths = manifest.declaredCredentialPaths.map(validateResourceRelativePath);
79
+ provenance = manifest.provenance.map((item) => ({
80
+ ...item,
81
+ snapshotPath: validateResourceRelativePath(item.snapshotPath),
82
+ }));
83
+ } catch (error) {
84
+ invalidManifest("generated.json contains an unsafe path", error);
85
+ }
86
+ if (new Set(declaredCredentialPaths).size !== declaredCredentialPaths.length) {
87
+ invalidManifest("generated.json declares a credential path more than once");
88
+ }
89
+ const provenancePaths = provenance.map((item) => item.snapshotPath);
90
+ if (new Set(provenancePaths).size !== provenancePaths.length) {
91
+ invalidManifest("generated.json contains duplicate provenance paths");
92
+ }
93
+ for (const credentialPath of declaredCredentialPaths) {
94
+ if (credentialPath === "generated.json" || provenancePaths.includes(credentialPath)) {
95
+ invalidManifest(`credential path '${credentialPath}' overlaps immutable snapshot content`);
96
+ }
97
+ }
98
+ return { ...manifest, declaredCredentialPaths, provenance };
99
+ }
100
+
101
+ type JsonRecord = Record<string, unknown>;
102
+
103
+ export function canonicalizeJson(value: unknown, location = "value"): unknown {
104
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
105
+ if (typeof value === "number") {
106
+ if (!Number.isFinite(value)) throw new Error(`${location} contains a non-finite number`);
107
+ return Object.is(value, -0) ? 0 : value;
108
+ }
109
+ if (Array.isArray(value)) {
110
+ return value.map((item, index) => canonicalizeJson(item, `${location}[${index}]`));
111
+ }
112
+ if (typeof value !== "object") throw new Error(`${location} contains a non-JSON value`);
113
+ const prototype = Object.getPrototypeOf(value);
114
+ if (prototype !== Object.prototype && prototype !== null) {
115
+ throw new Error(`${location} contains a non-plain object`);
116
+ }
117
+ return Object.fromEntries(
118
+ Object.keys(value as JsonRecord)
119
+ .sort((left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right)))
120
+ .map((key) => [key, canonicalizeJson((value as JsonRecord)[key], `${location}.${key}`)]),
121
+ );
122
+ }
123
+
124
+ export function canonicalJsonStringify(value: unknown, location = "value"): string {
125
+ return JSON.stringify(canonicalizeJson(value, location));
126
+ }
127
+
128
+ export function canonicalJsonEqual(left: unknown, right: unknown): boolean {
129
+ return canonicalJsonStringify(left) === canonicalJsonStringify(right);
130
+ }
package/src/testing.ts ADDED
@@ -0,0 +1,34 @@
1
+ import type { ConfigSnapshot } from "@leitwerk-dev/protocol/config-snapshot";
2
+
3
+ export function createTestConfigSnapshot(): ConfigSnapshot {
4
+ return {
5
+ workers: {
6
+ heartbeat_interval: "5s",
7
+ turn_max_duration: "30m",
8
+ turn_inactivity_timeout: "5m",
9
+ turn_abort_grace_period: "5s",
10
+ },
11
+ pi: {
12
+ agent_dir: "~/.pi/leitwerk",
13
+ model_profiles: [],
14
+ process_title_generation: {
15
+ model_profile: null,
16
+ retry: {
17
+ max_attempts: 6,
18
+ base_delay: "5s",
19
+ max_delay: "5m",
20
+ },
21
+ },
22
+ retry: {
23
+ enabled: true,
24
+ max_retries: 3,
25
+ base_delay: "2s",
26
+ provider: {
27
+ timeout: null,
28
+ max_retries: null,
29
+ max_retry_delay: "60s",
30
+ },
31
+ },
32
+ },
33
+ };
34
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Compatibility version for the server ↔ worker runtime API.
3
+ *
4
+ * Container image labels use the same value (`leitwerk.dev/worker-api-version`).
5
+ * Workers also report it in `worker.hello` so the server can fail fast when a
6
+ * pod image is from an incompatible leitwerk build line.
7
+ */
8
+ export const WORKER_API_VERSION = "2026-07-26";
@@ -0,0 +1,7 @@
1
+ export const WORKER_INSTANCE_ID_ENV = "LEITWERK_INSTANCE_ID";
2
+ export const WORKER_ID_ENV = "LEITWERK_WORKER_ID";
3
+ export const WORKER_IPC_SERVER_URL_ENV = "LEITWERK_SERVER_URL";
4
+ export const WORKER_IPC_CONNECT_TOKEN_ENV = "LEITWERK_WORKER_CONNECT_TOKEN";
5
+ export const WORKER_IPC_RECONNECT_ENV = "LEITWERK_WORKER_RECONNECT";
6
+ export const WORKER_SNAPSHOT_TOKEN_ENV = "LEITWERK_WORKER_SNAPSHOT_TOKEN";
7
+ export const WORKER_SERVER_EPOCH_ENV = "LEITWERK_SERVER_EPOCH";
@@ -0,0 +1,78 @@
1
+ import * as v from "valibot";
2
+
3
+ export const WORKER_RESULT_IMAGE_WORKER_ID_HEADER = "x-leitwerk-worker-id";
4
+ export const RESULT_IMAGE_MIME_TYPES = ["image/png", "image/jpeg", "image/webp"] as const;
5
+ export const RESULT_IMAGE_MAX_SIZE_BYTES = 10 * 1024 * 1024;
6
+ export const RESULT_IMAGE_STORAGE_SEGMENT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
7
+ export const RESULT_IMAGE_ID_PATTERN = /^img_[A-Za-z0-9]+\.(png|jpg|webp)$/;
8
+ export type ResultImageMimeType = (typeof RESULT_IMAGE_MIME_TYPES)[number];
9
+
10
+ export function isResultImageStorageSegment(value: string): boolean {
11
+ return RESULT_IMAGE_STORAGE_SEGMENT_PATTERN.test(value);
12
+ }
13
+
14
+ export function parseResultImageId(value: string): { extension: "png" | "jpg" | "webp" } | null {
15
+ const extension = RESULT_IMAGE_ID_PATTERN.exec(value)?.[1];
16
+ return extension === "png" || extension === "jpg" || extension === "webp" ? { extension } : null;
17
+ }
18
+
19
+ function assertResultImageStorageSegment(value: string): void {
20
+ if (!isResultImageStorageSegment(value)) throw new Error("Invalid result image storage id");
21
+ }
22
+
23
+ export const workerResultImageUploadResponseSchema = v.object({
24
+ imageId: v.string(),
25
+ url: v.string(),
26
+ mimeType: v.picklist(RESULT_IMAGE_MIME_TYPES),
27
+ byteSize: v.number(),
28
+ });
29
+
30
+ export type WorkerResultImageUploadResponse = v.InferOutput<
31
+ typeof workerResultImageUploadResponseSchema
32
+ >;
33
+
34
+ export function buildWorkerResultImageUploadPath(instanceId: string, turnRecordId: string): string {
35
+ assertResultImageStorageSegment(instanceId);
36
+ assertResultImageStorageSegment(turnRecordId);
37
+ return `/internal/workers/${instanceId}/turn-records/${turnRecordId}/result-images`;
38
+ }
39
+
40
+ export function buildManagedResultImagePath(
41
+ instanceId: string,
42
+ turnRecordId: string,
43
+ imageId: string,
44
+ ): string {
45
+ assertResultImageStorageSegment(instanceId);
46
+ assertResultImageStorageSegment(turnRecordId);
47
+ if (!parseResultImageId(imageId)) throw new Error("Invalid result image id");
48
+ return `/api/processes/${instanceId}/turn-records/${turnRecordId}/result-images/${imageId}`;
49
+ }
50
+
51
+ const MANAGED_RESULT_IMAGE_PATH =
52
+ /^\/api\/processes\/([^/]+)\/turn-records\/([^/]+)\/result-images\/([^/]+)$/;
53
+
54
+ export function parseManagedResultImagePath(value: string): {
55
+ instanceId: string;
56
+ turnRecordId: string;
57
+ imageId: string;
58
+ } | null {
59
+ const match = MANAGED_RESULT_IMAGE_PATH.exec(value);
60
+ const instanceId = match?.[1];
61
+ const turnRecordId = match?.[2];
62
+ const imageId = match?.[3];
63
+ return instanceId &&
64
+ turnRecordId &&
65
+ imageId &&
66
+ isResultImageStorageSegment(instanceId) &&
67
+ isResultImageStorageSegment(turnRecordId) &&
68
+ parseResultImageId(imageId)
69
+ ? { instanceId, turnRecordId, imageId }
70
+ : null;
71
+ }
72
+
73
+ export function parseWorkerResultImageUploadResponse(
74
+ value: unknown,
75
+ ): WorkerResultImageUploadResponse | null {
76
+ const parsed = v.safeParse(workerResultImageUploadResponseSchema, value);
77
+ return parsed.success ? parsed.output : null;
78
+ }
@@ -0,0 +1,7 @@
1
+ export const WORKER_SESSION_SNAPSHOT_CONTENT_TYPE = "application/x-ndjson";
2
+ export const WORKER_SESSION_SNAPSHOT_WORKER_ID_HEADER = "x-leitwerk-worker-id";
3
+ export const WORKER_SESSION_SNAPSHOT_REASON_HEADER = "x-leitwerk-session-snapshot-reason";
4
+ export const WORKER_SESSION_SNAPSHOT_TURN_RECORD_ID_HEADER = "x-leitwerk-turn-record-id";
5
+ export function buildWorkerSessionSnapshotPath(instanceId: string): string {
6
+ return `/internal/workers/${encodeURIComponent(instanceId)}/session-snapshot`;
7
+ }