@nexart/ai-execution 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +44 -9
  2. package/dist/index.cjs +696 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.d.cts +56 -0
  5. package/dist/index.d.ts +55 -11
  6. package/dist/index.mjs +638 -0
  7. package/dist/index.mjs.map +1 -0
  8. package/dist/providers/anthropic.cjs +258 -0
  9. package/dist/providers/anthropic.cjs.map +1 -0
  10. package/dist/providers/anthropic.d.cts +24 -0
  11. package/dist/providers/anthropic.d.ts +7 -5
  12. package/dist/providers/anthropic.mjs +221 -0
  13. package/dist/providers/anthropic.mjs.map +1 -0
  14. package/dist/providers/openai.cjs +259 -0
  15. package/dist/providers/openai.cjs.map +1 -0
  16. package/dist/providers/openai.d.cts +24 -0
  17. package/dist/providers/openai.d.ts +7 -5
  18. package/dist/providers/openai.mjs +222 -0
  19. package/dist/providers/openai.mjs.map +1 -0
  20. package/dist/providers/wrap.cjs +221 -0
  21. package/dist/providers/wrap.cjs.map +1 -0
  22. package/dist/providers/wrap.d.cts +9 -0
  23. package/dist/providers/wrap.d.ts +5 -3
  24. package/dist/providers/wrap.mjs +186 -0
  25. package/dist/providers/wrap.mjs.map +1 -0
  26. package/dist/{types.d.ts → types-342Snbrb.d.cts} +31 -16
  27. package/dist/types-342Snbrb.d.ts +169 -0
  28. package/package.json +18 -11
  29. package/dist/archive.d.ts +0 -4
  30. package/dist/archive.d.ts.map +0 -1
  31. package/dist/archive.js +0 -28
  32. package/dist/archive.js.map +0 -1
  33. package/dist/attest.d.ts +0 -3
  34. package/dist/attest.d.ts.map +0 -1
  35. package/dist/attest.js +0 -79
  36. package/dist/attest.js.map +0 -1
  37. package/dist/canonicalJson.d.ts +0 -2
  38. package/dist/canonicalJson.d.ts.map +0 -1
  39. package/dist/canonicalJson.js +0 -38
  40. package/dist/canonicalJson.js.map +0 -1
  41. package/dist/cer.d.ts +0 -7
  42. package/dist/cer.d.ts.map +0 -1
  43. package/dist/cer.js +0 -61
  44. package/dist/cer.js.map +0 -1
  45. package/dist/certify.d.ts +0 -3
  46. package/dist/certify.d.ts.map +0 -1
  47. package/dist/certify.js +0 -27
  48. package/dist/certify.js.map +0 -1
  49. package/dist/errors.d.ts +0 -11
  50. package/dist/errors.d.ts.map +0 -1
  51. package/dist/errors.js +0 -21
  52. package/dist/errors.js.map +0 -1
  53. package/dist/hash.d.ts +0 -6
  54. package/dist/hash.d.ts.map +0 -1
  55. package/dist/hash.js +0 -32
  56. package/dist/hash.js.map +0 -1
  57. package/dist/index.d.ts.map +0 -1
  58. package/dist/index.js +0 -11
  59. package/dist/index.js.map +0 -1
  60. package/dist/providers/anthropic.d.ts.map +0 -1
  61. package/dist/providers/anthropic.js +0 -61
  62. package/dist/providers/anthropic.js.map +0 -1
  63. package/dist/providers/openai.d.ts.map +0 -1
  64. package/dist/providers/openai.js +0 -62
  65. package/dist/providers/openai.js.map +0 -1
  66. package/dist/providers/wrap.d.ts.map +0 -1
  67. package/dist/providers/wrap.js +0 -28
  68. package/dist/providers/wrap.js.map +0 -1
  69. package/dist/run.d.ts +0 -14
  70. package/dist/run.d.ts.map +0 -1
  71. package/dist/run.js +0 -62
  72. package/dist/run.js.map +0 -1
  73. package/dist/snapshot.d.ts +0 -4
  74. package/dist/snapshot.d.ts.map +0 -1
  75. package/dist/snapshot.js +0 -113
  76. package/dist/snapshot.js.map +0 -1
  77. package/dist/types.d.ts.map +0 -1
  78. package/dist/types.js +0 -2
  79. package/dist/types.js.map +0 -1
package/dist/index.mjs ADDED
@@ -0,0 +1,638 @@
1
+ // src/types.ts
2
+ var CerVerifyCode = {
3
+ OK: "OK",
4
+ CERTIFICATE_HASH_MISMATCH: "CERTIFICATE_HASH_MISMATCH",
5
+ SNAPSHOT_HASH_MISMATCH: "SNAPSHOT_HASH_MISMATCH",
6
+ INPUT_HASH_MISMATCH: "INPUT_HASH_MISMATCH",
7
+ OUTPUT_HASH_MISMATCH: "OUTPUT_HASH_MISMATCH",
8
+ INVALID_SHA256_FORMAT: "INVALID_SHA256_FORMAT",
9
+ CANONICALIZATION_ERROR: "CANONICALIZATION_ERROR",
10
+ SCHEMA_ERROR: "SCHEMA_ERROR",
11
+ UNKNOWN_ERROR: "UNKNOWN_ERROR"
12
+ };
13
+
14
+ // src/errors.ts
15
+ var CerVerificationError = class extends Error {
16
+ errors;
17
+ constructor(errors) {
18
+ super(`CER verification failed: ${errors.join("; ")}`);
19
+ this.name = "CerVerificationError";
20
+ this.errors = errors;
21
+ }
22
+ };
23
+ var CerAttestationError = class extends Error {
24
+ statusCode;
25
+ responseBody;
26
+ details;
27
+ constructor(message, statusCode, responseBody, details) {
28
+ super(message);
29
+ this.name = "CerAttestationError";
30
+ this.statusCode = statusCode;
31
+ this.responseBody = responseBody;
32
+ this.details = details;
33
+ }
34
+ };
35
+
36
+ // src/canonicalJson.ts
37
+ function toCanonicalJson(value) {
38
+ return canonicalize(value);
39
+ }
40
+ function canonicalize(value) {
41
+ if (value === null) {
42
+ return "null";
43
+ }
44
+ if (typeof value === "boolean") {
45
+ return value ? "true" : "false";
46
+ }
47
+ if (typeof value === "number") {
48
+ if (!Number.isFinite(value)) {
49
+ throw new Error(`Non-finite number not allowed in canonical JSON: ${value}`);
50
+ }
51
+ return JSON.stringify(value);
52
+ }
53
+ if (typeof value === "string") {
54
+ return JSON.stringify(value);
55
+ }
56
+ if (Array.isArray(value)) {
57
+ const items = value.map((item) => canonicalize(item));
58
+ return "[" + items.join(",") + "]";
59
+ }
60
+ if (typeof value === "object") {
61
+ const obj = value;
62
+ const keys = Object.keys(obj).sort();
63
+ const entries = keys.map((key) => {
64
+ const val = obj[key];
65
+ if (val === void 0) {
66
+ return null;
67
+ }
68
+ return JSON.stringify(key) + ":" + canonicalize(val);
69
+ }).filter((e) => e !== null);
70
+ return "{" + entries.join(",") + "}";
71
+ }
72
+ throw new Error(`Unsupported type for canonical JSON: ${typeof value}`);
73
+ }
74
+
75
+ // src/hash.ts
76
+ import * as crypto from "crypto";
77
+ function sha256Hex(data) {
78
+ const hash = crypto.createHash("sha256");
79
+ if (typeof data === "string") {
80
+ hash.update(data, "utf-8");
81
+ } else {
82
+ hash.update(data);
83
+ }
84
+ return hash.digest("hex");
85
+ }
86
+ function hashUtf8(value) {
87
+ return `sha256:${sha256Hex(value)}`;
88
+ }
89
+ function hashCanonicalJson(value) {
90
+ const canonical = toCanonicalJson(value);
91
+ return `sha256:${sha256Hex(canonical)}`;
92
+ }
93
+ function computeInputHash(input) {
94
+ if (typeof input === "string") {
95
+ return hashUtf8(input);
96
+ }
97
+ return hashCanonicalJson(input);
98
+ }
99
+ function computeOutputHash(output) {
100
+ if (typeof output === "string") {
101
+ return hashUtf8(output);
102
+ }
103
+ return hashCanonicalJson(output);
104
+ }
105
+
106
+ // src/snapshot.ts
107
+ var PACKAGE_VERSION = "0.4.1";
108
+ function validateParameters(params) {
109
+ const errors = [];
110
+ if (typeof params.temperature !== "number" || !Number.isFinite(params.temperature)) {
111
+ errors.push(`parameters.temperature must be a finite number, got: ${params.temperature}`);
112
+ }
113
+ if (typeof params.maxTokens !== "number" || !Number.isFinite(params.maxTokens)) {
114
+ errors.push(`parameters.maxTokens must be a finite number, got: ${params.maxTokens}`);
115
+ }
116
+ if (params.topP !== null && (typeof params.topP !== "number" || !Number.isFinite(params.topP))) {
117
+ errors.push(`parameters.topP must be a finite number or null, got: ${params.topP}`);
118
+ }
119
+ if (params.seed !== null && (typeof params.seed !== "number" || !Number.isFinite(params.seed))) {
120
+ errors.push(`parameters.seed must be a finite number or null, got: ${params.seed}`);
121
+ }
122
+ return errors;
123
+ }
124
+ function createSnapshot(params) {
125
+ const paramErrors = validateParameters(params.parameters);
126
+ if (paramErrors.length > 0) {
127
+ throw new Error(`Invalid parameters: ${paramErrors.join("; ")}`);
128
+ }
129
+ const inputHash = computeInputHash(params.input);
130
+ const outputHash = computeOutputHash(params.output);
131
+ const snapshot = {
132
+ type: "ai.execution.v1",
133
+ protocolVersion: "1.2.0",
134
+ executionSurface: "ai",
135
+ executionId: params.executionId,
136
+ timestamp: params.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
137
+ provider: params.provider,
138
+ model: params.model,
139
+ modelVersion: params.modelVersion ?? null,
140
+ prompt: params.prompt,
141
+ input: params.input,
142
+ inputHash,
143
+ parameters: {
144
+ temperature: params.parameters.temperature,
145
+ maxTokens: params.parameters.maxTokens,
146
+ topP: params.parameters.topP ?? null,
147
+ seed: params.parameters.seed ?? null
148
+ },
149
+ output: params.output,
150
+ outputHash,
151
+ sdkVersion: params.sdkVersion ?? PACKAGE_VERSION,
152
+ appId: params.appId ?? null
153
+ };
154
+ if (params.runId !== void 0) snapshot.runId = params.runId ?? null;
155
+ if (params.stepId !== void 0) snapshot.stepId = params.stepId ?? null;
156
+ if (params.stepIndex !== void 0) snapshot.stepIndex = params.stepIndex ?? null;
157
+ if (params.workflowId !== void 0) snapshot.workflowId = params.workflowId ?? null;
158
+ if (params.conversationId !== void 0) snapshot.conversationId = params.conversationId ?? null;
159
+ if (params.prevStepHash !== void 0) snapshot.prevStepHash = params.prevStepHash ?? null;
160
+ return snapshot;
161
+ }
162
+ function verifySnapshot(snapshot) {
163
+ const schemaErrors = [];
164
+ const formatErrors = [];
165
+ const inputHashErrors = [];
166
+ const outputHashErrors = [];
167
+ if (snapshot.type !== "ai.execution.v1") {
168
+ schemaErrors.push(`Expected type "ai.execution.v1", got "${snapshot.type}"`);
169
+ }
170
+ if (snapshot.protocolVersion !== "1.2.0") {
171
+ schemaErrors.push(`Expected protocolVersion "1.2.0", got "${snapshot.protocolVersion}"`);
172
+ }
173
+ if (snapshot.executionSurface !== "ai") {
174
+ schemaErrors.push(`Expected executionSurface "ai", got "${snapshot.executionSurface}"`);
175
+ }
176
+ if (!snapshot.executionId || typeof snapshot.executionId !== "string") {
177
+ schemaErrors.push("executionId must be a non-empty string");
178
+ }
179
+ if (!snapshot.timestamp || typeof snapshot.timestamp !== "string") {
180
+ schemaErrors.push("timestamp must be a non-empty string");
181
+ }
182
+ if (!snapshot.provider || typeof snapshot.provider !== "string") {
183
+ schemaErrors.push("provider must be a non-empty string");
184
+ }
185
+ if (!snapshot.model || typeof snapshot.model !== "string") {
186
+ schemaErrors.push("model must be a non-empty string");
187
+ }
188
+ if (!snapshot.prompt || typeof snapshot.prompt !== "string") {
189
+ schemaErrors.push("prompt must be a non-empty string");
190
+ }
191
+ if (snapshot.input === void 0 || snapshot.input === null) {
192
+ schemaErrors.push("input must be a string or object");
193
+ }
194
+ if (snapshot.output === void 0 || snapshot.output === null) {
195
+ schemaErrors.push("output must be a string or object");
196
+ }
197
+ const paramErrors = validateParameters(snapshot.parameters);
198
+ schemaErrors.push(...paramErrors);
199
+ if (!snapshot.inputHash || !snapshot.inputHash.startsWith("sha256:")) {
200
+ formatErrors.push(`inputHash must start with "sha256:", got "${snapshot.inputHash}"`);
201
+ }
202
+ if (!snapshot.outputHash || !snapshot.outputHash.startsWith("sha256:")) {
203
+ formatErrors.push(`outputHash must start with "sha256:", got "${snapshot.outputHash}"`);
204
+ }
205
+ if (formatErrors.length === 0) {
206
+ const expectedInputHash = computeInputHash(snapshot.input);
207
+ if (snapshot.inputHash !== expectedInputHash) {
208
+ inputHashErrors.push(`inputHash mismatch: expected ${expectedInputHash}, got ${snapshot.inputHash}`);
209
+ }
210
+ const expectedOutputHash = computeOutputHash(snapshot.output);
211
+ if (snapshot.outputHash !== expectedOutputHash) {
212
+ outputHashErrors.push(`outputHash mismatch: expected ${expectedOutputHash}, got ${snapshot.outputHash}`);
213
+ }
214
+ }
215
+ const errors = [...schemaErrors, ...formatErrors, ...inputHashErrors, ...outputHashErrors];
216
+ if (errors.length === 0) {
217
+ return { ok: true, errors: [], code: CerVerifyCode.OK };
218
+ }
219
+ let code;
220
+ let details;
221
+ if (schemaErrors.length > 0) {
222
+ code = CerVerifyCode.SCHEMA_ERROR;
223
+ details = schemaErrors;
224
+ } else if (formatErrors.length > 0) {
225
+ code = CerVerifyCode.INVALID_SHA256_FORMAT;
226
+ details = formatErrors;
227
+ } else if (inputHashErrors.length > 0 && outputHashErrors.length > 0) {
228
+ code = CerVerifyCode.SNAPSHOT_HASH_MISMATCH;
229
+ details = [...inputHashErrors, ...outputHashErrors];
230
+ } else if (inputHashErrors.length > 0) {
231
+ code = CerVerifyCode.INPUT_HASH_MISMATCH;
232
+ details = inputHashErrors;
233
+ } else if (outputHashErrors.length > 0) {
234
+ code = CerVerifyCode.OUTPUT_HASH_MISMATCH;
235
+ details = outputHashErrors;
236
+ } else {
237
+ code = CerVerifyCode.UNKNOWN_ERROR;
238
+ details = errors;
239
+ }
240
+ return { ok: false, errors, code, details };
241
+ }
242
+
243
+ // src/cer.ts
244
+ function computeCertificateHash(payload) {
245
+ const canonical = toCanonicalJson(payload);
246
+ return `sha256:${sha256Hex(canonical)}`;
247
+ }
248
+ function sealCer(snapshot, options) {
249
+ const createdAt = options?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString();
250
+ const payload = {
251
+ bundleType: "cer.ai.execution.v1",
252
+ createdAt,
253
+ snapshot,
254
+ version: "0.1"
255
+ };
256
+ const certificateHash = computeCertificateHash(payload);
257
+ const bundle = {
258
+ bundleType: "cer.ai.execution.v1",
259
+ certificateHash,
260
+ createdAt,
261
+ version: "0.1",
262
+ snapshot
263
+ };
264
+ if (options?.meta) {
265
+ bundle.meta = options.meta;
266
+ }
267
+ return bundle;
268
+ }
269
+ function verifyCer(bundle) {
270
+ const schemaErrors = [];
271
+ const formatErrors = [];
272
+ if (bundle.bundleType !== "cer.ai.execution.v1") {
273
+ schemaErrors.push(`Expected bundleType "cer.ai.execution.v1", got "${bundle.bundleType}"`);
274
+ }
275
+ if (bundle.version !== "0.1") {
276
+ schemaErrors.push(`Expected version "0.1", got "${bundle.version}"`);
277
+ }
278
+ if (!bundle.createdAt || typeof bundle.createdAt !== "string") {
279
+ schemaErrors.push("createdAt must be a non-empty string");
280
+ }
281
+ if (!bundle.certificateHash || !bundle.certificateHash.startsWith("sha256:")) {
282
+ formatErrors.push(`certificateHash must start with "sha256:", got "${bundle.certificateHash}"`);
283
+ }
284
+ if (!bundle.snapshot) {
285
+ schemaErrors.push("snapshot is required");
286
+ const allErrors = [...schemaErrors, ...formatErrors];
287
+ return { ok: false, errors: allErrors, code: CerVerifyCode.SCHEMA_ERROR, details: schemaErrors };
288
+ }
289
+ let canonicalizationError = null;
290
+ let snapshotResult = null;
291
+ try {
292
+ snapshotResult = verifySnapshot(bundle.snapshot);
293
+ } catch (err) {
294
+ canonicalizationError = err instanceof Error ? err.message : String(err);
295
+ }
296
+ if (canonicalizationError !== null) {
297
+ const errors2 = [...schemaErrors, ...formatErrors, canonicalizationError];
298
+ return { ok: false, errors: errors2, code: CerVerifyCode.CANONICALIZATION_ERROR, details: [canonicalizationError] };
299
+ }
300
+ const snapshotErrors = snapshotResult.errors;
301
+ const certHashErrors = [];
302
+ try {
303
+ const payload = {
304
+ bundleType: "cer.ai.execution.v1",
305
+ createdAt: bundle.createdAt,
306
+ snapshot: bundle.snapshot,
307
+ version: "0.1"
308
+ };
309
+ const expectedHash = computeCertificateHash(payload);
310
+ if (bundle.certificateHash !== expectedHash) {
311
+ certHashErrors.push(`certificateHash mismatch: expected ${expectedHash}, got ${bundle.certificateHash}`);
312
+ }
313
+ } catch (err) {
314
+ const msg = err instanceof Error ? err.message : String(err);
315
+ const errors2 = [...schemaErrors, ...formatErrors, ...snapshotErrors, msg];
316
+ return { ok: false, errors: errors2, code: CerVerifyCode.CANONICALIZATION_ERROR, details: [msg] };
317
+ }
318
+ const errors = [...schemaErrors, ...formatErrors, ...snapshotErrors, ...certHashErrors];
319
+ if (errors.length === 0) {
320
+ return { ok: true, errors: [], code: CerVerifyCode.OK };
321
+ }
322
+ let code;
323
+ let details;
324
+ if (schemaErrors.length > 0) {
325
+ code = CerVerifyCode.SCHEMA_ERROR;
326
+ details = schemaErrors;
327
+ } else if (formatErrors.length > 0) {
328
+ code = CerVerifyCode.INVALID_SHA256_FORMAT;
329
+ details = formatErrors;
330
+ } else if (certHashErrors.length > 0 && snapshotErrors.length === 0) {
331
+ code = CerVerifyCode.CERTIFICATE_HASH_MISMATCH;
332
+ details = certHashErrors;
333
+ } else if (snapshotResult && snapshotResult.code !== CerVerifyCode.OK) {
334
+ code = snapshotResult.code;
335
+ details = snapshotResult.details ?? snapshotErrors;
336
+ } else if (certHashErrors.length > 0) {
337
+ code = CerVerifyCode.CERTIFICATE_HASH_MISMATCH;
338
+ details = certHashErrors;
339
+ } else {
340
+ code = CerVerifyCode.UNKNOWN_ERROR;
341
+ details = errors;
342
+ }
343
+ return { ok: false, errors, code, details };
344
+ }
345
+
346
+ // src/certify.ts
347
+ import * as crypto2 from "crypto";
348
+ function certifyDecision(params) {
349
+ const executionId = params.executionId ?? crypto2.randomUUID();
350
+ const snapshot = createSnapshot({
351
+ executionId,
352
+ timestamp: params.timestamp,
353
+ provider: params.provider,
354
+ model: params.model,
355
+ modelVersion: params.modelVersion,
356
+ prompt: params.prompt,
357
+ input: params.input,
358
+ parameters: params.parameters,
359
+ output: params.output,
360
+ sdkVersion: params.sdkVersion,
361
+ appId: params.appId,
362
+ runId: params.runId,
363
+ stepId: params.stepId,
364
+ stepIndex: params.stepIndex,
365
+ workflowId: params.workflowId,
366
+ conversationId: params.conversationId,
367
+ prevStepHash: params.prevStepHash
368
+ });
369
+ return sealCer(snapshot, { meta: params.meta });
370
+ }
371
+
372
+ // src/run.ts
373
+ import * as crypto3 from "crypto";
374
+ var RunBuilder = class {
375
+ runId;
376
+ workflowId;
377
+ conversationId;
378
+ appId;
379
+ stepIndex = 0;
380
+ prevStepHash = null;
381
+ steps = [];
382
+ constructor(options) {
383
+ this.runId = options?.runId ?? crypto3.randomUUID();
384
+ this.workflowId = options?.workflowId ?? null;
385
+ this.conversationId = options?.conversationId ?? null;
386
+ this.appId = options?.appId ?? null;
387
+ }
388
+ step(params) {
389
+ const stepId = params.stepId ?? crypto3.randomUUID();
390
+ const executionId = `${this.runId}-step-${this.stepIndex}`;
391
+ const snapshot = createSnapshot({
392
+ executionId,
393
+ timestamp: params.timestamp,
394
+ provider: params.provider,
395
+ model: params.model,
396
+ modelVersion: params.modelVersion,
397
+ prompt: params.prompt,
398
+ input: params.input,
399
+ parameters: params.parameters,
400
+ output: params.output,
401
+ appId: this.appId,
402
+ runId: this.runId,
403
+ stepId,
404
+ stepIndex: this.stepIndex,
405
+ workflowId: this.workflowId,
406
+ conversationId: this.conversationId,
407
+ prevStepHash: this.prevStepHash
408
+ });
409
+ const bundle = sealCer(snapshot, { meta: params.meta });
410
+ this.steps.push({
411
+ stepIndex: this.stepIndex,
412
+ stepId,
413
+ executionId,
414
+ certificateHash: bundle.certificateHash,
415
+ prevStepHash: this.prevStepHash
416
+ });
417
+ this.prevStepHash = bundle.certificateHash;
418
+ this.stepIndex++;
419
+ return bundle;
420
+ }
421
+ finalize() {
422
+ return {
423
+ runId: this.runId,
424
+ workflowId: this.workflowId,
425
+ conversationId: this.conversationId,
426
+ stepCount: this.steps.length,
427
+ steps: [...this.steps],
428
+ finalStepHash: this.prevStepHash
429
+ };
430
+ }
431
+ };
432
+
433
+ // src/sanitize.ts
434
+ function deepRemoveUndefined(value) {
435
+ if (value === null || value === void 0) return value;
436
+ if (typeof value === "bigint") {
437
+ throw new Error("BigInt values are not JSON-safe and cannot be sanitized");
438
+ }
439
+ if (typeof value === "function") {
440
+ throw new Error("Function values are not JSON-safe and cannot be sanitized");
441
+ }
442
+ if (typeof value === "symbol") {
443
+ throw new Error("Symbol values are not JSON-safe and cannot be sanitized");
444
+ }
445
+ if (Array.isArray(value)) {
446
+ return value.map(deepRemoveUndefined);
447
+ }
448
+ if (typeof value === "object") {
449
+ const result = {};
450
+ for (const [key, val] of Object.entries(value)) {
451
+ if (val === void 0) continue;
452
+ result[key] = deepRemoveUndefined(val);
453
+ }
454
+ return result;
455
+ }
456
+ return value;
457
+ }
458
+ function sanitizeForAttestation(bundle) {
459
+ return deepRemoveUndefined(bundle);
460
+ }
461
+ function hasAttestation(bundle) {
462
+ if (typeof bundle !== "object" || bundle === null) return false;
463
+ const b = bundle;
464
+ if (typeof b.attestationId === "string" && b.attestationId.length > 0) return true;
465
+ if (typeof b.nodeRuntimeHash === "string" && b.nodeRuntimeHash.length > 0) return true;
466
+ if (typeof b.attestation === "object" && b.attestation !== null) {
467
+ const att = b.attestation;
468
+ if (typeof att.attestationId === "string" && att.attestationId.length > 0) return true;
469
+ if (typeof att.nodeRuntimeHash === "string" && att.nodeRuntimeHash.length > 0) return true;
470
+ }
471
+ return false;
472
+ }
473
+
474
+ // src/attest.ts
475
+ var SHA256_PATTERN = /^sha256:[0-9a-f]{64}$/;
476
+ var DEFAULT_TIMEOUT_MS = 1e4;
477
+ function validateHashFormat(value, fieldName) {
478
+ if (typeof value !== "string") return null;
479
+ if (!SHA256_PATTERN.test(value)) {
480
+ return `${fieldName} is not in sha256:<64hex> format: "${value}"`;
481
+ }
482
+ return null;
483
+ }
484
+ async function attest(bundle, options) {
485
+ const url = `${options.nodeUrl.replace(/\/+$/, "")}/api/attest`;
486
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
487
+ const sanitized = sanitizeForAttestation(bundle);
488
+ const controller = new AbortController();
489
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
490
+ let response;
491
+ try {
492
+ response = await fetch(url, {
493
+ method: "POST",
494
+ headers: {
495
+ "Content-Type": "application/json",
496
+ "Authorization": `Bearer ${options.apiKey}`
497
+ },
498
+ body: JSON.stringify(sanitized),
499
+ signal: controller.signal
500
+ });
501
+ } catch (err) {
502
+ clearTimeout(timer);
503
+ const error = err;
504
+ if (error.name === "AbortError") {
505
+ throw new CerAttestationError(
506
+ `Attestation request timed out after ${timeoutMs}ms`
507
+ );
508
+ }
509
+ throw new CerAttestationError(
510
+ `Network error contacting attestation node: ${error.message}`
511
+ );
512
+ } finally {
513
+ clearTimeout(timer);
514
+ }
515
+ let body;
516
+ try {
517
+ body = await response.json();
518
+ } catch {
519
+ const text = await response.text().catch(() => "");
520
+ throw new CerAttestationError(
521
+ `Attestation node returned non-JSON response (${response.status}): ${text}`,
522
+ response.status
523
+ );
524
+ }
525
+ if (!response.ok) {
526
+ const result2 = body;
527
+ const msg = typeof result2.error === "string" ? result2.error : `HTTP ${response.status}`;
528
+ const details = Array.isArray(result2.details) ? result2.details : void 0;
529
+ throw new CerAttestationError(
530
+ `Attestation failed: ${msg}`,
531
+ response.status,
532
+ body,
533
+ details
534
+ );
535
+ }
536
+ const result = body;
537
+ const errors = [];
538
+ if (typeof result.certificateHash === "string" && result.certificateHash !== bundle.certificateHash) {
539
+ errors.push(
540
+ `Node returned certificateHash "${result.certificateHash}" but bundle has "${bundle.certificateHash}"`
541
+ );
542
+ }
543
+ const certHashErr = validateHashFormat(result.certificateHash, "response.certificateHash");
544
+ if (certHashErr) errors.push(certHashErr);
545
+ const runtimeHashErr = validateHashFormat(result.nodeRuntimeHash, "response.nodeRuntimeHash");
546
+ if (runtimeHashErr) errors.push(runtimeHashErr);
547
+ if (errors.length > 0) {
548
+ throw new CerAttestationError(
549
+ `Attestation response validation failed: ${errors.join("; ")}`,
550
+ response.status,
551
+ body,
552
+ errors
553
+ );
554
+ }
555
+ return {
556
+ ok: true,
557
+ attestationId: typeof result.attestationId === "string" ? result.attestationId : void 0,
558
+ nodeRuntimeHash: typeof result.nodeRuntimeHash === "string" ? result.nodeRuntimeHash : void 0,
559
+ certificateHash: typeof result.certificateHash === "string" ? result.certificateHash : void 0,
560
+ protocolVersion: typeof result.protocolVersion === "string" ? result.protocolVersion : void 0,
561
+ raw: body
562
+ };
563
+ }
564
+
565
+ // src/archive.ts
566
+ function exportCer(bundle) {
567
+ return toCanonicalJson(bundle);
568
+ }
569
+ function importCer(json) {
570
+ let parsed;
571
+ try {
572
+ parsed = JSON.parse(json);
573
+ } catch (err) {
574
+ throw new CerVerificationError([`Invalid JSON: ${err.message}`]);
575
+ }
576
+ const bundle = parsed;
577
+ if (!bundle || typeof bundle !== "object") {
578
+ throw new CerVerificationError(["Parsed value is not an object"]);
579
+ }
580
+ if (bundle.bundleType !== "cer.ai.execution.v1") {
581
+ throw new CerVerificationError([`Expected bundleType "cer.ai.execution.v1", got "${bundle.bundleType}"`]);
582
+ }
583
+ const result = verifyCer(bundle);
584
+ if (!result.ok) {
585
+ throw new CerVerificationError(result.errors);
586
+ }
587
+ return bundle;
588
+ }
589
+
590
+ // src/providers/wrap.ts
591
+ import * as crypto4 from "crypto";
592
+ function wrapProvider(config) {
593
+ return {
594
+ async execute(params) {
595
+ const raw = await config.callFn(params.providerInput);
596
+ const output = config.extractOutput(raw);
597
+ const modelVersion = config.extractModelVersion ? config.extractModelVersion(raw) : params.modelVersion ?? null;
598
+ const snapshot = createSnapshot({
599
+ executionId: params.executionId ?? crypto4.randomUUID(),
600
+ provider: config.provider,
601
+ model: params.model,
602
+ modelVersion,
603
+ prompt: params.prompt,
604
+ input: params.input,
605
+ parameters: params.parameters,
606
+ output,
607
+ appId: params.appId
608
+ });
609
+ const bundle = sealCer(snapshot, { meta: params.meta });
610
+ return { output, snapshot, bundle };
611
+ }
612
+ };
613
+ }
614
+ export {
615
+ CerAttestationError,
616
+ CerVerificationError,
617
+ CerVerifyCode,
618
+ RunBuilder,
619
+ attest,
620
+ certifyDecision,
621
+ computeInputHash,
622
+ computeOutputHash,
623
+ createSnapshot,
624
+ exportCer,
625
+ hasAttestation,
626
+ hashCanonicalJson,
627
+ hashUtf8,
628
+ importCer,
629
+ sanitizeForAttestation,
630
+ sealCer,
631
+ sha256Hex,
632
+ toCanonicalJson,
633
+ verifyCer as verify,
634
+ verifyCer,
635
+ verifySnapshot,
636
+ wrapProvider
637
+ };
638
+ //# sourceMappingURL=index.mjs.map