@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,60 @@
1
+ import { parseSchema } from "@leitwerk-dev/protocol";
2
+ import * as v from "valibot";
3
+
4
+ export const IPC_PROTOCOL_VERSION = "leitwerk/worker-ipc/v1" as const;
5
+
6
+ export const IPC_ENVELOPE_SCHEMA = v.object({
7
+ protocol: v.literal(IPC_PROTOCOL_VERSION),
8
+ messageId: v.string(),
9
+ correlationId: v.optional(v.string()),
10
+ type: v.string(),
11
+ instanceId: v.string(),
12
+ workerId: v.string(),
13
+ sentAt: v.string(),
14
+ payload: v.unknown(),
15
+ });
16
+
17
+ export type IpcEnvelope = v.InferOutput<typeof IPC_ENVELOPE_SCHEMA>;
18
+
19
+ export function validateEnvelope(
20
+ msg: unknown,
21
+ ): { ok: true; envelope: IpcEnvelope } | { ok: false; error: string } {
22
+ if (
23
+ typeof msg === "object" &&
24
+ msg !== null &&
25
+ "protocol" in msg &&
26
+ typeof msg.protocol === "string" &&
27
+ msg.protocol !== IPC_PROTOCOL_VERSION
28
+ ) {
29
+ return {
30
+ ok: false,
31
+ error: `Worker IPC protocol '${msg.protocol}' is incompatible with expected protocol '${IPC_PROTOCOL_VERSION}'`,
32
+ };
33
+ }
34
+ const envelope = parseSchema(IPC_ENVELOPE_SCHEMA, msg, "ipc envelope");
35
+ return envelope.ok
36
+ ? { ok: true, envelope: envelope.value }
37
+ : { ok: false, error: envelope.error };
38
+ }
39
+
40
+ export function serializeMessage<TEnvelope extends IpcEnvelope>(envelope: TEnvelope): string {
41
+ return JSON.stringify(envelope);
42
+ }
43
+
44
+ export function deserializeMessage(
45
+ line: string,
46
+ ): { ok: true; message: IpcEnvelope } | { ok: false; error: string } {
47
+ const trimmed =
48
+ line.length > 0 && line.charCodeAt(line.length - 1) === 0x0d ? line.slice(0, -1) : line;
49
+ let parsed: unknown;
50
+ try {
51
+ parsed = JSON.parse(trimmed) as unknown;
52
+ } catch {
53
+ return { ok: false, error: "invalid JSON" };
54
+ }
55
+ const validated = validateEnvelope(parsed);
56
+ if (!validated.ok) {
57
+ return { ok: false, error: validated.error };
58
+ }
59
+ return { ok: true, message: validated.envelope };
60
+ }
@@ -0,0 +1,85 @@
1
+ import { validateEnvelope } from "./ipc-codec.js";
2
+ import type { ServerToWorkerMessage, WorkerToServerMessage } from "./ipc-messages.js";
3
+
4
+ export type IpcDecodeResult<TMessage> =
5
+ | { ok: true; message: TMessage }
6
+ | { ok: false; error: string };
7
+
8
+ const SERVER_TO_WORKER_TYPES = [
9
+ "worker.start",
10
+ "worker.turn_start_accepted",
11
+ "worker.credential_update_accepted",
12
+ "worker.question_response",
13
+ "input.batch",
14
+ "worker.stop",
15
+ "worker.abort_turn",
16
+ ] as const satisfies readonly ServerToWorkerMessage["type"][];
17
+
18
+ const WORKER_TO_SERVER_TYPES = [
19
+ "worker.hello",
20
+ "worker.credential_update",
21
+ "worker.ready",
22
+ "worker.heartbeat",
23
+ "worker.state",
24
+ "worker.input_consumed",
25
+ "worker.event",
26
+ "worker.turn_started",
27
+ "worker.question_requested",
28
+ "worker.turn_outcome",
29
+ "worker.turn_failed",
30
+ "worker.lifecycle_parked",
31
+ "worker.cleanup_started",
32
+ "worker.cleanup_completed",
33
+ "worker.failed",
34
+ ] as const satisfies readonly WorkerToServerMessage["type"][];
35
+
36
+ function hasMessageType<TType extends string>(
37
+ allowed: readonly TType[],
38
+ value: string,
39
+ ): value is TType {
40
+ return (allowed as readonly string[]).includes(value);
41
+ }
42
+
43
+ /**
44
+ * Validate the generic IPC envelope and narrow it to the correct typed message
45
+ * union member for the given direction.
46
+ *
47
+ * This intentionally stops at the message discriminant boundary: it validates
48
+ * envelope structure + known message type, but does not deeply validate the
49
+ * payload shape. Payload fields are trusted to come from same-version
50
+ * leitwerk components, so malformed payloads from a buggy sender can still
51
+ * pass through as typed data.
52
+ */
53
+ function decodeKnownMessage<TMessage extends { type: string }>(
54
+ msg: unknown,
55
+ allowed: readonly TMessage["type"][],
56
+ direction: string,
57
+ ): IpcDecodeResult<TMessage> {
58
+ const validated = validateEnvelope(msg);
59
+ if (!validated.ok) {
60
+ return { ok: false, error: validated.error };
61
+ }
62
+ if (!hasMessageType(allowed, validated.envelope.type)) {
63
+ return {
64
+ ok: false,
65
+ error: `unexpected ${direction} message type: ${validated.envelope.type}`,
66
+ };
67
+ }
68
+ return { ok: true, message: validated.envelope as unknown as TMessage };
69
+ }
70
+
71
+ /**
72
+ * Decode a parsed envelope coming from the server side of the IPC channel.
73
+ * Only envelope structure + message type are runtime-validated.
74
+ */
75
+ export function decodeServerToWorkerMessage(msg: unknown): IpcDecodeResult<ServerToWorkerMessage> {
76
+ return decodeKnownMessage(msg, SERVER_TO_WORKER_TYPES, "server-to-worker");
77
+ }
78
+
79
+ /**
80
+ * Decode a parsed envelope coming from the worker side of the IPC channel.
81
+ * Only envelope structure + message type are runtime-validated.
82
+ */
83
+ export function decodeWorkerToServerMessage(msg: unknown): IpcDecodeResult<WorkerToServerMessage> {
84
+ return decodeKnownMessage(msg, WORKER_TO_SERVER_TYPES, "worker-to-server");
85
+ }
@@ -0,0 +1,381 @@
1
+ import type {
2
+ CurrentExecutionRef,
3
+ NormalizedQuestion,
4
+ PreparedTurnStart,
5
+ ProcessInputTarget,
6
+ ProcessLifecycleStatus,
7
+ ProcessSemanticEntryRefKey,
8
+ ProcessTurnRecordPathType,
9
+ ProcessTurnType,
10
+ TurnFailedPayload,
11
+ TurnStartRecord,
12
+ WorkerBootstrapReceipt,
13
+ } from "@leitwerk-dev/domain";
14
+ import type { ConfigSnapshot } from "@leitwerk-dev/protocol/config-snapshot";
15
+ import { IPC_PROTOCOL_VERSION, type IpcEnvelope } from "./ipc-codec.js";
16
+
17
+ export interface ProcessInstanceSnapshot {
18
+ id?: string;
19
+ processId?: string;
20
+ selectedTurnId?: string | null;
21
+ lifecycleStatus?: ProcessLifecycleStatus;
22
+ currentExecution?: CurrentExecutionRef;
23
+ planRevision?: number;
24
+ title?: string | null;
25
+ externalId?: string | null;
26
+ externalUrl?: string | null;
27
+ metadata?: Record<string, unknown> | null;
28
+ defaultModelProfileId?: string | null;
29
+ turnConfigsJson?: string | null;
30
+ selectedTurnModelProfileId?: string | null;
31
+ paramsJson?: string | null;
32
+ stateJson?: string | null;
33
+ createdAt?: string;
34
+ updatedAt?: string;
35
+ }
36
+
37
+ export interface ProcessProjectSnapshot {
38
+ id?: string;
39
+ instanceId?: string;
40
+ key: string;
41
+ repoLocator: string;
42
+ repoLocatorKind?: "remote_url" | "local_path";
43
+ baseBranch: string;
44
+ workBranch?: string | null;
45
+ externalId?: string | null;
46
+ externalUrl?: string | null;
47
+ metadata?: Record<string, unknown> | null;
48
+ pipelineStatus?: string | null;
49
+ createdAt?: string;
50
+ updatedAt?: string;
51
+ }
52
+
53
+ export interface InputDelivery {
54
+ inputId: string;
55
+ sequence: number;
56
+ source: string;
57
+ kind: string;
58
+ target: ProcessInputTarget | null;
59
+ receivedAt: string;
60
+ bodyMarkdown: string;
61
+ }
62
+
63
+ export interface WorkerRuntimeContextSnapshot {
64
+ processSnapshot: ProcessInstanceSnapshot;
65
+ projectSnapshots: ProcessProjectSnapshot[];
66
+ turnResultMarkdownBySemanticRef?: Partial<Record<ProcessSemanticEntryRefKey, string>>;
67
+ turnResultMarkdownByProduct?: Record<string, string>;
68
+ }
69
+
70
+ export interface WorkerCredentialMaterial {
71
+ providerId: string;
72
+ revision: number;
73
+ /** Secret payload. This type is valid only in worker.start and credential-update frames. */
74
+ values: Record<string, string>;
75
+ }
76
+
77
+ export interface WorkerGitSshCredential {
78
+ projectKey: string;
79
+ kind: "git_ssh";
80
+ credentialRef: string;
81
+ /** Secret values; valid only while preparing worker.start. */
82
+ privateKey: string;
83
+ knownHosts: string;
84
+ }
85
+
86
+ export interface LlmWorkerStartBootstrap {
87
+ kind: "llm";
88
+ resourceBundle: { digest: string; archiveBase64: string };
89
+ credential: WorkerCredentialMaterial | null;
90
+ }
91
+
92
+ export interface AutomaticWorkerStartBootstrap {
93
+ kind: "automatic";
94
+ }
95
+
96
+ interface WorkerStartPayloadBase extends WorkerRuntimeContextSnapshot {
97
+ workerLeaseId: string;
98
+ turnStart: TurnStartRecord;
99
+ /**
100
+ * The immutable pre-acceptance tree plan from the lease that first accepted
101
+ * this start. It is supplied only when a replacement resumes a running turn.
102
+ */
103
+ acceptedPreparedStart?: PreparedTurnStart | null;
104
+ pendingInputs: InputDelivery[];
105
+ treePaths: {
106
+ primaryTreeFile: string;
107
+ workspaceRoot: string;
108
+ };
109
+ resume: boolean;
110
+ resumeLeafEntryId?: string | null;
111
+ /** Fresh secret material resolved for this physical worker start only. */
112
+ repositoryCredentials?: WorkerGitSshCredential[];
113
+ }
114
+
115
+ export type WorkerStartPayload =
116
+ | (WorkerStartPayloadBase & {
117
+ bootstrap: LlmWorkerStartBootstrap;
118
+ configSnapshot: ConfigSnapshot;
119
+ })
120
+ | (WorkerStartPayloadBase & { bootstrap: AutomaticWorkerStartBootstrap });
121
+
122
+ export interface InputBatchPayload {
123
+ inputs: InputDelivery[];
124
+ }
125
+
126
+ export interface WorkerStopPayload {
127
+ reason: string;
128
+ }
129
+
130
+ export interface WorkerAbortTurnPayload {
131
+ reason: string;
132
+ }
133
+
134
+ export interface WorkerTurnStartAcceptedPayload {
135
+ startRecordId: string;
136
+ turnRecordId: string;
137
+ }
138
+
139
+ export interface WorkerQuestionResponsePayload {
140
+ turnRecordId: string;
141
+ toolCallId: string;
142
+ answers: string[];
143
+ }
144
+
145
+ export interface WorkerQuestionRequestedPayload {
146
+ turnRecordId: string;
147
+ toolCallId: string;
148
+ questions: NormalizedQuestion[];
149
+ }
150
+
151
+ export interface WorkerCredentialUpdateResultPayload {
152
+ providerId: string;
153
+ accepted: boolean;
154
+ currentRevision: number | null;
155
+ safeReason?: string;
156
+ }
157
+
158
+ export type ServerToWorkerMessage =
159
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
160
+ type: "worker.start";
161
+ payload: WorkerStartPayload;
162
+ })
163
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
164
+ type: "worker.turn_start_accepted";
165
+ payload: WorkerTurnStartAcceptedPayload;
166
+ })
167
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
168
+ type: "worker.credential_update_accepted";
169
+ payload: WorkerCredentialUpdateResultPayload;
170
+ })
171
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
172
+ type: "worker.question_response";
173
+ payload: WorkerQuestionResponsePayload;
174
+ })
175
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
176
+ type: "input.batch";
177
+ payload: InputBatchPayload;
178
+ })
179
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
180
+ type: "worker.stop";
181
+ payload: WorkerStopPayload;
182
+ })
183
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
184
+ type: "worker.abort_turn";
185
+ payload: WorkerAbortTurnPayload;
186
+ });
187
+
188
+ export interface WorkerHelloPayload {
189
+ /** Package/runtime version for diagnostics. */
190
+ version: string;
191
+ /** Server-worker API compatibility version. Missing only on legacy/test workers. */
192
+ apiVersion?: string;
193
+ capabilities: string[];
194
+ }
195
+
196
+ export interface WorkerReadyPayload {
197
+ receipt: WorkerBootstrapReceipt;
198
+ resumed: boolean;
199
+ primaryTreeFile: string;
200
+ workspaceRoot: string;
201
+ aggregatedAgentsSources: string[];
202
+ loadedSkills: string[];
203
+ loadedAgentsFiles: Array<{ path: string; sizeBytes: number }>;
204
+ loadedSkillFiles: Array<{ name: string; path: string }>;
205
+ rootEntryId?: string | null;
206
+ }
207
+
208
+ export interface WorkerHeartbeatPayload {
209
+ /** Diagnostic worker-local runtime state; not the authoritative lease transition channel. */
210
+ state: string;
211
+ lastSequenceConsumed: number;
212
+ currentTurnId?: string;
213
+ currentSelectedTurnId?: string | null;
214
+ }
215
+
216
+ export interface WorkerStatePayload {
217
+ /** Explicit server-visible runtime transition, e.g. idle -> busy or busy -> idle. */
218
+ from: string;
219
+ to: string;
220
+ reason: string;
221
+ }
222
+
223
+ export interface WorkerInputConsumedPayload {
224
+ inputId: string;
225
+ sequence: number;
226
+ deliveryMode: string;
227
+ currentPrimaryPathLeafId?: string | null;
228
+ rootEntryId?: string | null;
229
+ targetSemanticRef?: ProcessSemanticEntryRefKey | null;
230
+ targetProductName?: string | null;
231
+ targetEntryId?: string | null;
232
+ }
233
+
234
+ export interface WorkerEventPayload {
235
+ eventType: string;
236
+ selectedTurnId?: string | null;
237
+ /**
238
+ * Object-shaped event data emitted by trusted worker senders. Decode helpers
239
+ * do not deeply validate this field at runtime; they only narrow it at the
240
+ * protocol boundary after envelope + message-type validation.
241
+ */
242
+ data: Record<string, unknown>;
243
+ }
244
+
245
+ export interface WorkerTurnStartedPayload {
246
+ startRecordId: string;
247
+ proposedTurnRecordId: string;
248
+ }
249
+
250
+ export interface WorkerCredentialUpdatePayload {
251
+ providerId: string;
252
+ expectedRevision: number;
253
+ /** Secret payload. It must not be copied into receipts, events, or turn state. */
254
+ values: Record<string, string>;
255
+ }
256
+
257
+ export interface WorkerTurnOutcomePayload {
258
+ turnRecordId: string;
259
+ turnId: string;
260
+ turnType: ProcessTurnType;
261
+ outcome: string;
262
+ params: Record<string, unknown>;
263
+ pathType?: ProcessTurnRecordPathType;
264
+ forkPiEntryId?: string | null;
265
+ resultPiEntryId?: string | null;
266
+ turnResultMarkdown?: string | null;
267
+ rootEntryId?: string | null;
268
+ }
269
+
270
+ export interface WorkerTurnFailedPayload
271
+ extends Omit<TurnFailedPayload, "instanceId" | "errorClass"> {
272
+ errorClass?: string;
273
+ }
274
+
275
+ export interface WorkerLifecycleParkedPayload {
276
+ selectedTurnId: string | null;
277
+ reason?: string;
278
+ errorClass?: string;
279
+ }
280
+
281
+ export interface WorkerCleanupStartedPayload {
282
+ reason: string;
283
+ }
284
+
285
+ export interface WorkerCleanupCompletedPayload {
286
+ releasedLocks: string[];
287
+ removedTransientPaths: string[];
288
+ }
289
+
290
+ export interface WorkerFailedPayload {
291
+ state: string;
292
+ errorCode: string;
293
+ message: string;
294
+ errorClass: string;
295
+ selectedTurnId?: string | null;
296
+ retryAttempt?: number;
297
+ }
298
+
299
+ export type WorkerToServerMessage =
300
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
301
+ type: "worker.hello";
302
+ payload: WorkerHelloPayload;
303
+ })
304
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
305
+ type: "worker.credential_update";
306
+ payload: WorkerCredentialUpdatePayload;
307
+ })
308
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
309
+ type: "worker.ready";
310
+ payload: WorkerReadyPayload;
311
+ })
312
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
313
+ type: "worker.heartbeat";
314
+ payload: WorkerHeartbeatPayload;
315
+ })
316
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
317
+ type: "worker.state";
318
+ payload: WorkerStatePayload;
319
+ })
320
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
321
+ type: "worker.input_consumed";
322
+ payload: WorkerInputConsumedPayload;
323
+ })
324
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
325
+ type: "worker.event";
326
+ payload: WorkerEventPayload;
327
+ })
328
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
329
+ type: "worker.turn_started";
330
+ payload: WorkerTurnStartedPayload;
331
+ })
332
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
333
+ type: "worker.question_requested";
334
+ payload: WorkerQuestionRequestedPayload;
335
+ })
336
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
337
+ type: "worker.turn_outcome";
338
+ payload: WorkerTurnOutcomePayload;
339
+ })
340
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
341
+ type: "worker.turn_failed";
342
+ payload: WorkerTurnFailedPayload;
343
+ })
344
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
345
+ type: "worker.lifecycle_parked";
346
+ payload: WorkerLifecycleParkedPayload;
347
+ })
348
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
349
+ type: "worker.cleanup_started";
350
+ payload: WorkerCleanupStartedPayload;
351
+ })
352
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
353
+ type: "worker.cleanup_completed";
354
+ payload: WorkerCleanupCompletedPayload;
355
+ })
356
+ | (Omit<IpcEnvelope, "type" | "payload"> & {
357
+ type: "worker.failed";
358
+ payload: WorkerFailedPayload;
359
+ });
360
+
361
+ export type AnyIpcMessage = ServerToWorkerMessage | WorkerToServerMessage;
362
+ export type IpcMessageType = AnyIpcMessage["type"];
363
+ export type IpcMessageOfType<TType extends IpcMessageType> = Extract<
364
+ AnyIpcMessage,
365
+ { type: TType }
366
+ >;
367
+
368
+ export function createIpcMessage<TMessage extends AnyIpcMessage>(
369
+ args: Omit<TMessage, "protocol" | "sentAt"> & { sentAt?: string },
370
+ ): TMessage {
371
+ return {
372
+ protocol: IPC_PROTOCOL_VERSION,
373
+ messageId: args.messageId,
374
+ correlationId: args.correlationId,
375
+ type: args.type,
376
+ instanceId: args.instanceId,
377
+ workerId: args.workerId,
378
+ sentAt: args.sentAt ?? new Date().toISOString(),
379
+ payload: args.payload,
380
+ } as TMessage;
381
+ }
@@ -0,0 +1,162 @@
1
+ import { createHash } from "node:crypto";
2
+ import path from "node:path";
3
+
4
+ const BLOCK_SIZE = 512;
5
+
6
+ export interface PiResourceFile {
7
+ path: string;
8
+ content: Uint8Array;
9
+ }
10
+
11
+ export interface PiResourceBundle {
12
+ digest: string;
13
+ bytes: Uint8Array;
14
+ }
15
+
16
+ export interface ExtractedPiResourceFile {
17
+ path: string;
18
+ content: Uint8Array;
19
+ }
20
+
21
+ function fail(message: string): never {
22
+ throw new Error(`Invalid Pi resource bundle: ${message}`);
23
+ }
24
+
25
+ export function validateResourceRelativePath(value: string): string {
26
+ if (!value || path.posix.isAbsolute(value) || value.includes("\\")) {
27
+ fail(`unsafe path '${value}'`);
28
+ }
29
+ const normalized = path.posix.normalize(value);
30
+ if (normalized === "." || normalized === ".." || normalized.startsWith("../")) {
31
+ fail(`unsafe path '${value}'`);
32
+ }
33
+ return normalized;
34
+ }
35
+
36
+ function writeString(buffer: Buffer, offset: number, length: number, value: string): void {
37
+ const encoded = Buffer.from(value, "utf8");
38
+ if (encoded.length > length) fail(`header value too long: ${value}`);
39
+ encoded.copy(buffer, offset);
40
+ }
41
+
42
+ function writeOctal(buffer: Buffer, offset: number, length: number, value: number): void {
43
+ const encoded = value.toString(8).padStart(length - 1, "0");
44
+ if (encoded.length > length - 1) fail(`numeric header value too large: ${value}`);
45
+ writeString(buffer, offset, length - 1, encoded);
46
+ buffer[offset + length - 1] = 0;
47
+ }
48
+
49
+ function header(name: string, size: number): Buffer {
50
+ if (Buffer.byteLength(name) > 100) fail(`path exceeds canonical ustar name limit: ${name}`);
51
+ const result = Buffer.alloc(BLOCK_SIZE);
52
+ writeString(result, 0, 100, name);
53
+ writeOctal(result, 100, 8, 0o644);
54
+ writeOctal(result, 108, 8, 0);
55
+ writeOctal(result, 116, 8, 0);
56
+ writeOctal(result, 124, 12, size);
57
+ writeOctal(result, 136, 12, 0);
58
+ result.fill(0x20, 148, 156);
59
+ result[156] = "0".charCodeAt(0);
60
+ writeString(result, 257, 6, "ustar");
61
+ writeString(result, 263, 2, "00");
62
+ const sum = result.reduce((total, byte) => total + byte, 0);
63
+ writeString(result, 148, 8, `${sum.toString(8).padStart(6, "0")}\0 `);
64
+ return result;
65
+ }
66
+
67
+ function padding(size: number): Buffer {
68
+ const length = (BLOCK_SIZE - (size % BLOCK_SIZE)) % BLOCK_SIZE;
69
+ return Buffer.alloc(length);
70
+ }
71
+
72
+ export function sha256Digest(bytes: Uint8Array): string {
73
+ return createHash("sha256").update(bytes).digest("hex");
74
+ }
75
+
76
+ /** Creates a deterministic, uncompressed ustar archive containing regular files only. */
77
+ export function createCanonicalPiResourceBundle(
78
+ files: readonly PiResourceFile[],
79
+ ): PiResourceBundle {
80
+ const seen = new Set<string>();
81
+ const normalized = files.map((file) => {
82
+ const resourcePath = validateResourceRelativePath(file.path);
83
+ if (seen.has(resourcePath)) fail(`duplicate path '${resourcePath}'`);
84
+ seen.add(resourcePath);
85
+ return { path: resourcePath, content: Buffer.from(file.content) };
86
+ });
87
+ normalized.sort((left, right) => Buffer.compare(Buffer.from(left.path), Buffer.from(right.path)));
88
+ const chunks: Buffer[] = [];
89
+ for (const file of normalized) {
90
+ chunks.push(header(file.path, file.content.length), file.content, padding(file.content.length));
91
+ }
92
+ chunks.push(Buffer.alloc(BLOCK_SIZE * 2));
93
+ const bytes = Buffer.concat(chunks);
94
+ return { bytes, digest: sha256Digest(bytes) };
95
+ }
96
+
97
+ function readNullString(block: Uint8Array, start: number, length: number): string {
98
+ const end = block.subarray(start, start + length).indexOf(0);
99
+ return Buffer.from(block.subarray(start, end < 0 ? start + length : start + end)).toString(
100
+ "utf8",
101
+ );
102
+ }
103
+
104
+ function readOctal(block: Uint8Array, start: number, length: number): number {
105
+ const raw = readNullString(block, start, length).trim();
106
+ if (!/^[0-7]*$/.test(raw)) fail("non-octal numeric field");
107
+ return raw ? Number.parseInt(raw, 8) : 0;
108
+ }
109
+
110
+ function verifyChecksum(block: Uint8Array): void {
111
+ const expected = readOctal(block, 148, 8);
112
+ let actual = 0;
113
+ for (let index = 0; index < BLOCK_SIZE; index++) {
114
+ actual += index >= 148 && index < 156 ? 32 : block[index];
115
+ }
116
+ if (actual !== expected) fail("header checksum mismatch");
117
+ }
118
+
119
+ function allZero(block: Uint8Array): boolean {
120
+ return block.every((byte) => byte === 0);
121
+ }
122
+
123
+ /** Parses only the narrow regular-file ustar subset emitted by this module. */
124
+ export function verifyCanonicalPiResourceBundle(
125
+ bytes: Uint8Array,
126
+ expectedDigest?: string,
127
+ ): ExtractedPiResourceFile[] {
128
+ if (expectedDigest && sha256Digest(bytes) !== expectedDigest) fail("content digest mismatch");
129
+ if (bytes.length < BLOCK_SIZE * 2 || bytes.length % BLOCK_SIZE !== 0) {
130
+ fail("invalid archive length");
131
+ }
132
+ const files: ExtractedPiResourceFile[] = [];
133
+ const paths = new Set<string>();
134
+ let offset = 0;
135
+ while (offset < bytes.length) {
136
+ const block = bytes.subarray(offset, offset + BLOCK_SIZE);
137
+ if (allZero(block)) {
138
+ if (!allZero(bytes.subarray(offset + BLOCK_SIZE, offset + BLOCK_SIZE * 2))) {
139
+ fail("missing end blocks");
140
+ }
141
+ if (offset + BLOCK_SIZE * 2 !== bytes.length) fail("data after end blocks");
142
+ return files;
143
+ }
144
+ verifyChecksum(block);
145
+ if (readNullString(block, 257, 6) !== "ustar") fail("unsupported tar format");
146
+ const type = readNullString(block, 156, 1);
147
+ if (type !== "" && type !== "0") fail(`unsupported entry type '${type}'`);
148
+ if (readNullString(block, 157, 100) || readNullString(block, 345, 155)) {
149
+ fail("links and ustar path prefixes are unsupported");
150
+ }
151
+ const name = validateResourceRelativePath(readNullString(block, 0, 100));
152
+ if (paths.has(name)) fail(`duplicate path '${name}'`);
153
+ paths.add(name);
154
+ const size = readOctal(block, 124, 12);
155
+ const contentStart = offset + BLOCK_SIZE;
156
+ const contentEnd = contentStart + size;
157
+ if (contentEnd > bytes.length) fail("truncated file content");
158
+ files.push({ path: name, content: bytes.slice(contentStart, contentEnd) });
159
+ offset = contentEnd + ((BLOCK_SIZE - (size % BLOCK_SIZE)) % BLOCK_SIZE);
160
+ }
161
+ fail("missing end blocks");
162
+ }