@opendatalabs/personal-server-ts-core 1.9.0 → 1.10.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 (52) hide show
  1. package/dist/derivatives/compute.d.ts.map +1 -1
  2. package/dist/derivatives/compute.js +10 -3
  3. package/dist/derivatives/compute.js.map +1 -1
  4. package/dist/derivatives/e2ee/aad.d.ts +22 -0
  5. package/dist/derivatives/e2ee/aad.d.ts.map +1 -0
  6. package/dist/derivatives/e2ee/aad.js +32 -0
  7. package/dist/derivatives/e2ee/aad.js.map +1 -0
  8. package/dist/derivatives/e2ee/attestation.d.ts +122 -0
  9. package/dist/derivatives/e2ee/attestation.d.ts.map +1 -0
  10. package/dist/derivatives/e2ee/attestation.js +217 -0
  11. package/dist/derivatives/e2ee/attestation.js.map +1 -0
  12. package/dist/derivatives/e2ee/index.d.ts +6 -0
  13. package/dist/derivatives/e2ee/index.d.ts.map +1 -0
  14. package/dist/derivatives/e2ee/index.js +6 -0
  15. package/dist/derivatives/e2ee/index.js.map +1 -0
  16. package/dist/derivatives/e2ee/jcs.d.ts +17 -0
  17. package/dist/derivatives/e2ee/jcs.d.ts.map +1 -0
  18. package/dist/derivatives/e2ee/jcs.js +55 -0
  19. package/dist/derivatives/e2ee/jcs.js.map +1 -0
  20. package/dist/derivatives/e2ee/phala.d.ts +55 -0
  21. package/dist/derivatives/e2ee/phala.d.ts.map +1 -0
  22. package/dist/derivatives/e2ee/phala.js +167 -0
  23. package/dist/derivatives/e2ee/phala.js.map +1 -0
  24. package/dist/derivatives/e2ee/suite.d.ts +56 -0
  25. package/dist/derivatives/e2ee/suite.d.ts.map +1 -0
  26. package/dist/derivatives/e2ee/suite.js +164 -0
  27. package/dist/derivatives/e2ee/suite.js.map +1 -0
  28. package/dist/derivatives/index.d.ts +2 -1
  29. package/dist/derivatives/index.d.ts.map +1 -1
  30. package/dist/derivatives/index.js +1 -0
  31. package/dist/derivatives/index.js.map +1 -1
  32. package/dist/derivatives/inference.d.ts +48 -16
  33. package/dist/derivatives/inference.d.ts.map +1 -1
  34. package/dist/derivatives/inference.js +132 -68
  35. package/dist/derivatives/inference.js.map +1 -1
  36. package/dist/schemas/server-config.d.ts +2 -0
  37. package/dist/schemas/server-config.d.ts.map +1 -1
  38. package/dist/schemas/server-config.js +5 -0
  39. package/dist/schemas/server-config.js.map +1 -1
  40. package/dist/test-utils/e2ee-fixtures.d.ts +94 -0
  41. package/dist/test-utils/e2ee-fixtures.d.ts.map +1 -0
  42. package/dist/test-utils/e2ee-fixtures.js +116 -0
  43. package/dist/test-utils/e2ee-fixtures.js.map +1 -0
  44. package/dist/test-utils/e2ee-gateway.d.ts +61 -0
  45. package/dist/test-utils/e2ee-gateway.d.ts.map +1 -0
  46. package/dist/test-utils/e2ee-gateway.js +248 -0
  47. package/dist/test-utils/e2ee-gateway.js.map +1 -0
  48. package/dist/test-utils/index.d.ts +2 -0
  49. package/dist/test-utils/index.d.ts.map +1 -1
  50. package/dist/test-utils/index.js +2 -0
  51. package/dist/test-utils/index.js.map +1 -1
  52. package/package.json +1 -1
@@ -0,0 +1,55 @@
1
+ /**
2
+ * `InferenceRequestEncryption` for the Phala confidential-inference gateway
3
+ * (E2EE v2, X25519 suite). Per request:
4
+ *
5
+ * 1. get the gateway's attested E2EE key (cached for a short TTL, shared
6
+ * across concurrent computes, re-fetched on `e2ee_model_key_mismatch`
7
+ * or when the served `X-ACI-Keyset-Digest` no longer matches the pin)
8
+ * 2. generate a fresh client X25519 key pair, a 32-byte nonce and the
9
+ * Unix-seconds timestamp; set the five X-E2EE-* request headers
10
+ * 3. encrypt every `messages.{m}.content` to the gateway key under the
11
+ * request AAD
12
+ * 4. hand back a decryptor bound to that request context: the response
13
+ * field (`choices.{i}.message.content`) is encrypted to the client key
14
+ * under the response AAD, which also binds the clear response `id`
15
+ *
16
+ * Fail closed: no verified key means no request; a response field that is
17
+ * not valid ciphertext for this request is an error, never accepted as
18
+ * plaintext. Error messages carry no prompt or answer text.
19
+ */
20
+ import { type InferenceRequestEncryption } from "../inference.js";
21
+ import { type AciAttestationReport, type GatewayE2eeKey } from "./attestation.js";
22
+ export declare const E2EE_HEADER_VERSION = "X-E2EE-Version";
23
+ export declare const E2EE_HEADER_CLIENT_PUB_KEY = "X-Client-Pub-Key";
24
+ export declare const E2EE_HEADER_MODEL_PUB_KEY = "X-Model-Pub-Key";
25
+ export declare const E2EE_HEADER_NONCE = "X-E2EE-Nonce";
26
+ export declare const E2EE_HEADER_TIMESTAMP = "X-E2EE-Timestamp";
27
+ export declare const ACI_HEADER_KEYSET_DIGEST = "X-ACI-Keyset-Digest";
28
+ export declare const DEFAULT_E2EE_KEY_TTL_MS: number;
29
+ export interface PhalaE2eeEncryptionOptions {
30
+ /** Chat completions base; the attestation report is fetched through it. */
31
+ baseUrl: string;
32
+ fetch?: typeof fetch;
33
+ /** Milliseconds since epoch (default Date.now). */
34
+ clock?: () => number;
35
+ /** How long a verified key is reused before a fresh report is fetched. */
36
+ keyTtlMs?: number;
37
+ /** Require this keyset `key_id` (default: select by algo only). */
38
+ expectedKeyId?: string;
39
+ /** Hardware evidence verification hook; see attestation.ts. */
40
+ verifyEvidence?: (report: AciAttestationReport) => Promise<void>;
41
+ /** Fallback origin for the attestation route; `null` disables it. */
42
+ fallbackAttestationBaseUrl?: string | null;
43
+ logger?: {
44
+ info?(payload: Record<string, unknown>, message: string): void;
45
+ warn?(payload: Record<string, unknown>, message: string): void;
46
+ };
47
+ }
48
+ export interface PhalaE2eeEncryption extends InferenceRequestEncryption {
49
+ /** Drop the cached key; the next request fetches a fresh report. */
50
+ invalidateKey(): void;
51
+ /** The verified key currently in use, if any (diagnostics). */
52
+ currentKey(): GatewayE2eeKey | null;
53
+ }
54
+ export declare function createPhalaE2eeEncryption(options: PhalaE2eeEncryptionOptions): PhalaE2eeEncryption;
55
+ //# sourceMappingURL=phala.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"phala.d.ts","sourceRoot":"","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,mBAAoB,SAAQ,0BAA0B;IACrE,oEAAoE;IACpE,aAAa,IAAI,IAAI,CAAC;IACtB,+DAA+D;IAC/D,UAAU,IAAI,cAAc,GAAG,IAAI,CAAC;CACrC;AAmBD,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,0BAA0B,GAClC,mBAAmB,CAwJrB"}
@@ -0,0 +1,167 @@
1
+ /**
2
+ * `InferenceRequestEncryption` for the Phala confidential-inference gateway
3
+ * (E2EE v2, X25519 suite). Per request:
4
+ *
5
+ * 1. get the gateway's attested E2EE key (cached for a short TTL, shared
6
+ * across concurrent computes, re-fetched on `e2ee_model_key_mismatch`
7
+ * or when the served `X-ACI-Keyset-Digest` no longer matches the pin)
8
+ * 2. generate a fresh client X25519 key pair, a 32-byte nonce and the
9
+ * Unix-seconds timestamp; set the five X-E2EE-* request headers
10
+ * 3. encrypt every `messages.{m}.content` to the gateway key under the
11
+ * request AAD
12
+ * 4. hand back a decryptor bound to that request context: the response
13
+ * field (`choices.{i}.message.content`) is encrypted to the client key
14
+ * under the response AAD, which also binds the clear response `id`
15
+ *
16
+ * Fail closed: no verified key means no request; a response field that is
17
+ * not valid ciphertext for this request is an error, never accepted as
18
+ * plaintext. Error messages carry no prompt or answer text.
19
+ */
20
+ import { InferenceRequestError, } from "../inference.js";
21
+ import { requestFieldAad, responseFieldAad } from "./aad.js";
22
+ import { E2eeAttestationError, fetchGatewayE2eeKey, } from "./attestation.js";
23
+ import { E2eeCipherError, bytesToHex, decryptField, encryptField, generateX25519KeyPair, randomBytes, } from "./suite.js";
24
+ export const E2EE_HEADER_VERSION = "X-E2EE-Version";
25
+ export const E2EE_HEADER_CLIENT_PUB_KEY = "X-Client-Pub-Key";
26
+ export const E2EE_HEADER_MODEL_PUB_KEY = "X-Model-Pub-Key";
27
+ export const E2EE_HEADER_NONCE = "X-E2EE-Nonce";
28
+ export const E2EE_HEADER_TIMESTAMP = "X-E2EE-Timestamp";
29
+ export const ACI_HEADER_KEYSET_DIGEST = "X-ACI-Keyset-Digest";
30
+ export const DEFAULT_E2EE_KEY_TTL_MS = 5 * 60_000;
31
+ function keyFetchError(err) {
32
+ if (err instanceof E2eeAttestationError) {
33
+ return new InferenceRequestError(`e2ee key fetch failed (${err.code}): ${err.message}`, null, {
34
+ errorType: `e2ee_attestation_${err.code}`,
35
+ retryable: err.code === "fetch_failed",
36
+ });
37
+ }
38
+ const name = err instanceof Error ? err.name : "Error";
39
+ return new InferenceRequestError(`e2ee key fetch failed (${name})`, null, {
40
+ retryable: false,
41
+ });
42
+ }
43
+ export function createPhalaE2eeEncryption(options) {
44
+ const clock = options.clock ?? Date.now;
45
+ const ttlMs = options.keyTtlMs ?? DEFAULT_E2EE_KEY_TTL_MS;
46
+ let cached = null;
47
+ let inFlight = null;
48
+ const fetchKey = async () => {
49
+ const key = await fetchGatewayE2eeKey({
50
+ baseUrl: options.baseUrl,
51
+ fetch: options.fetch,
52
+ clock,
53
+ expectedKeyId: options.expectedKeyId,
54
+ verifyEvidence: options.verifyEvidence,
55
+ fallbackBaseUrl: options.fallbackAttestationBaseUrl,
56
+ });
57
+ options.logger?.info?.({
58
+ keyId: key.keyId,
59
+ algo: key.algo,
60
+ keysetDigest: key.keysetDigest,
61
+ notAfter: key.notAfter,
62
+ source: key.source,
63
+ evidenceVerified: Boolean(options.verifyEvidence),
64
+ }, "E2EE gateway key verified");
65
+ return key;
66
+ };
67
+ const getKey = async () => {
68
+ const now = clock();
69
+ if (cached &&
70
+ now - cached.fetchedAt < ttlMs &&
71
+ Math.floor(now / 1000) < cached.key.notAfter) {
72
+ return cached.key;
73
+ }
74
+ if (!inFlight) {
75
+ inFlight = fetchKey()
76
+ .then((key) => {
77
+ cached = { key, fetchedAt: clock() };
78
+ return key;
79
+ })
80
+ .finally(() => {
81
+ inFlight = null;
82
+ });
83
+ }
84
+ try {
85
+ return await inFlight;
86
+ }
87
+ catch (err) {
88
+ throw keyFetchError(err);
89
+ }
90
+ };
91
+ const invalidateKey = () => {
92
+ cached = null;
93
+ };
94
+ return {
95
+ invalidateKey,
96
+ currentKey: () => cached?.key ?? null,
97
+ async encryptRequest({ model, messages, headers }) {
98
+ if (typeof model !== "string" || model === "") {
99
+ // The AAD binds the model; the gateway rejects a missing one anyway.
100
+ throw new InferenceRequestError("e2ee requires a non-empty request model", null, { errorType: "e2ee_invalid_payload_model", retryable: false });
101
+ }
102
+ const gatewayKey = await getKey();
103
+ const client = await generateX25519KeyPair();
104
+ const context = {
105
+ algo: gatewayKey.algo,
106
+ model,
107
+ nonce: bytesToHex(randomBytes(32)),
108
+ ts: Math.floor(clock() / 1000),
109
+ };
110
+ headers.set(E2EE_HEADER_VERSION, "2");
111
+ headers.set(E2EE_HEADER_CLIENT_PUB_KEY, bytesToHex(client.publicKey));
112
+ headers.set(E2EE_HEADER_MODEL_PUB_KEY, gatewayKey.publicKeyHex);
113
+ headers.set(E2EE_HEADER_NONCE, context.nonce);
114
+ headers.set(E2EE_HEADER_TIMESTAMP, String(context.ts));
115
+ const encrypted = [];
116
+ for (let index = 0; index < messages.length; index += 1) {
117
+ const message = messages[index];
118
+ let content;
119
+ try {
120
+ content = await encryptField({
121
+ plaintext: message.content,
122
+ recipientPublicKey: gatewayKey.publicKey,
123
+ aad: requestFieldAad(context, `messages.${index}.content`),
124
+ });
125
+ }
126
+ catch (err) {
127
+ const name = err instanceof Error ? err.name : "Error";
128
+ throw new InferenceRequestError(`e2ee request encryption failed (${name})`, null, { retryable: false });
129
+ }
130
+ encrypted.push({ ...message, content });
131
+ }
132
+ const request = {
133
+ messages: encrypted,
134
+ async decryptResponse({ content, field, id, headers: response }) {
135
+ const served = response.get(ACI_HEADER_KEYSET_DIGEST);
136
+ if (served && served !== gatewayKey.keysetDigest) {
137
+ // The gateway rotated its keyset: re-verify before the next
138
+ // request. This reply was still encrypted for our client key.
139
+ options.logger?.warn?.({ pinned: gatewayKey.keysetDigest, served }, "E2EE keyset digest changed; refetching the attestation report");
140
+ invalidateKey();
141
+ }
142
+ try {
143
+ return await decryptField({
144
+ wire: content,
145
+ privateKey: client.privateKey,
146
+ aad: responseFieldAad(context, field, id),
147
+ });
148
+ }
149
+ catch (err) {
150
+ const detail = err instanceof E2eeCipherError ? err.message : "unexpected error";
151
+ throw new InferenceRequestError(`e2ee response decryption failed for ${field} (${detail})`, null, { errorType: "e2ee_decryption_failed", retryable: false });
152
+ }
153
+ },
154
+ };
155
+ return request;
156
+ },
157
+ async onRejected({ errorType }) {
158
+ if (errorType === "e2ee_model_key_mismatch") {
159
+ options.logger?.warn?.({ keyId: cached?.key.keyId ?? null }, "E2EE model key rejected by the gateway; refetching the attestation report");
160
+ invalidateKey();
161
+ return true;
162
+ }
163
+ return false;
164
+ },
165
+ };
166
+ }
167
+ //# sourceMappingURL=phala.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"phala.js","sourceRoot":"","sources":["../../../src/derivatives/e2ee/phala.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EACL,qBAAqB,GAItB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAC7D,OAAO,EACL,oBAAoB,EACpB,mBAAmB,GAGpB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,eAAe,EACf,UAAU,EACV,YAAY,EACZ,YAAY,EACZ,qBAAqB,EACrB,WAAW,GACZ,MAAM,YAAY,CAAC;AAEpB,MAAM,CAAC,MAAM,mBAAmB,GAAG,gBAAgB,CAAC;AACpD,MAAM,CAAC,MAAM,0BAA0B,GAAG,kBAAkB,CAAC;AAC7D,MAAM,CAAC,MAAM,yBAAyB,GAAG,iBAAiB,CAAC;AAC3D,MAAM,CAAC,MAAM,iBAAiB,GAAG,cAAc,CAAC;AAChD,MAAM,CAAC,MAAM,qBAAqB,GAAG,kBAAkB,CAAC;AACxD,MAAM,CAAC,MAAM,wBAAwB,GAAG,qBAAqB,CAAC;AAE9D,MAAM,CAAC,MAAM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B,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,CAAC;yBAC1C,CAAC,CAAC;oBACL,CAAC;oBAAC,OAAO,GAAG,EAAE,CAAC;wBACb,MAAM,MAAM,GACV,GAAG,YAAY,eAAe,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,kBAAkB,CAAC;wBACpE,MAAM,IAAI,qBAAqB,CAC7B,uCAAuC,KAAK,KAAK,MAAM,GAAG,EAC1D,IAAI,EACJ,EAAE,SAAS,EAAE,wBAAwB,EAAE,SAAS,EAAE,KAAK,EAAE,CAC1D,CAAC;oBACJ,CAAC;gBACH,CAAC;aACF,CAAC;YACF,OAAO,OAAO,CAAC;QACjB,CAAC;QAED,KAAK,CAAC,UAAU,CAAC,EAAE,SAAS,EAAE;YAC5B,IAAI,SAAS,KAAK,yBAAyB,EAAE,CAAC;gBAC5C,OAAO,CAAC,MAAM,EAAE,IAAI,EAAE,CACpB,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,CAAC,KAAK,IAAI,IAAI,EAAE,EACpC,2EAA2E,CAC5E,CAAC;gBACF,aAAa,EAAE,CAAC;gBAChB,OAAO,IAAI,CAAC;YACd,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * E2EE v2 cipher suite `x25519-aes-256-gcm-hkdf-sha256` on WebCrypto only
3
+ * (X25519 deriveBits, HKDF-SHA256, AES-256-GCM, getRandomValues), so the
4
+ * same code runs in Node 22+ and in the browser (PS-Lite). No Node-only
5
+ * import lives in this directory.
6
+ *
7
+ * Wire format of one encrypted field value (spec section 4), lowercase hex:
8
+ *
9
+ * ephemeral_public_key (32) || aes_gcm_nonce (12) || ciphertext || tag (16)
10
+ *
11
+ * key = HKDF-SHA256(salt = none, ikm = X25519(ephemeral, recipient),
12
+ * info = "aci.e2ee.v2.x25519", len = 32)
13
+ *
14
+ * A fresh ephemeral key and AES-GCM nonce per field; the AAD is the JCS
15
+ * bytes built in aad.ts.
16
+ */
17
+ export declare const E2EE_ALGO_X25519 = "x25519-aes-256-gcm-hkdf-sha256";
18
+ export declare const E2EE_HKDF_INFO_X25519 = "aci.e2ee.v2.x25519";
19
+ export interface E2eeKeyPair {
20
+ privateKey: CryptoKey;
21
+ /** Raw 32-byte X25519 public key. */
22
+ publicKey: Uint8Array;
23
+ }
24
+ export declare class E2eeCipherError extends Error {
25
+ constructor(message: string);
26
+ }
27
+ export declare function randomBytes(length: number): Uint8Array;
28
+ export declare function bytesToHex(bytes: Uint8Array): string;
29
+ export declare function hexToBytes(hex: string): Uint8Array;
30
+ /** Spec section 4: hex with an optional `0x` prefix, 32 bytes for X25519. */
31
+ export declare function parseX25519PublicKey(hex: string): Uint8Array;
32
+ export declare function generateX25519KeyPair(): Promise<E2eeKeyPair>;
33
+ /**
34
+ * Import a private key from its 32-byte seed. Only for tests and tooling
35
+ * that need a deterministic key; production keys come from generate.
36
+ */
37
+ export declare function importX25519PrivateKey(seed: Uint8Array, publicKey: Uint8Array): Promise<E2eeKeyPair>;
38
+ export interface EncryptFieldInput {
39
+ plaintext: string;
40
+ recipientPublicKey: Uint8Array;
41
+ aad: Uint8Array;
42
+ /** Test hooks: a fixed ephemeral key / nonce make the output reproducible. */
43
+ ephemeral?: E2eeKeyPair;
44
+ nonce?: Uint8Array;
45
+ }
46
+ /** One field value -> lowercase hex wire value. */
47
+ export declare function encryptField(input: EncryptFieldInput): Promise<string>;
48
+ export interface DecryptFieldInput {
49
+ /** Hex wire value (either case, optional 0x). */
50
+ wire: string;
51
+ privateKey: CryptoKey;
52
+ aad: Uint8Array;
53
+ }
54
+ /** Hex wire value -> plaintext; throws E2eeCipherError on any failure. */
55
+ export declare function decryptField(input: DecryptFieldInput): Promise<string>;
56
+ //# sourceMappingURL=suite.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"suite.d.ts","sourceRoot":"","sources":["../../../src/derivatives/e2ee/suite.ts"],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AC,KAAK,EAAE,iBAAiB,GAAG,OAAO,CAAC,MAAM,CAAC,CAwC5E"}
@@ -0,0 +1,164 @@
1
+ /**
2
+ * E2EE v2 cipher suite `x25519-aes-256-gcm-hkdf-sha256` on WebCrypto only
3
+ * (X25519 deriveBits, HKDF-SHA256, AES-256-GCM, getRandomValues), so the
4
+ * same code runs in Node 22+ and in the browser (PS-Lite). No Node-only
5
+ * import lives in this directory.
6
+ *
7
+ * Wire format of one encrypted field value (spec section 4), lowercase hex:
8
+ *
9
+ * ephemeral_public_key (32) || aes_gcm_nonce (12) || ciphertext || tag (16)
10
+ *
11
+ * key = HKDF-SHA256(salt = none, ikm = X25519(ephemeral, recipient),
12
+ * info = "aci.e2ee.v2.x25519", len = 32)
13
+ *
14
+ * A fresh ephemeral key and AES-GCM nonce per field; the AAD is the JCS
15
+ * bytes built in aad.ts.
16
+ */
17
+ export const E2EE_ALGO_X25519 = "x25519-aes-256-gcm-hkdf-sha256";
18
+ export const E2EE_HKDF_INFO_X25519 = "aci.e2ee.v2.x25519";
19
+ const X25519_PUBLIC_KEY_BYTES = 32;
20
+ const AES_GCM_NONCE_BYTES = 12;
21
+ const AES_GCM_TAG_BYTES = 16;
22
+ export class E2eeCipherError extends Error {
23
+ constructor(message) {
24
+ super(message);
25
+ this.name = "E2eeCipherError";
26
+ }
27
+ }
28
+ function subtle() {
29
+ const api = globalThis.crypto?.subtle;
30
+ if (!api)
31
+ throw new E2eeCipherError("WebCrypto is not available");
32
+ return api;
33
+ }
34
+ export function randomBytes(length) {
35
+ const bytes = new Uint8Array(length);
36
+ globalThis.crypto.getRandomValues(bytes);
37
+ return bytes;
38
+ }
39
+ export function bytesToHex(bytes) {
40
+ let out = "";
41
+ for (const byte of bytes)
42
+ out += byte.toString(16).padStart(2, "0");
43
+ return out;
44
+ }
45
+ export function hexToBytes(hex) {
46
+ const clean = hex.startsWith("0x") || hex.startsWith("0X") ? hex.slice(2) : hex;
47
+ if (clean.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(clean)) {
48
+ throw new E2eeCipherError("malformed hex");
49
+ }
50
+ const out = new Uint8Array(clean.length / 2);
51
+ for (let i = 0; i < out.length; i += 1) {
52
+ out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
53
+ }
54
+ return out;
55
+ }
56
+ /** Spec section 4: hex with an optional `0x` prefix, 32 bytes for X25519. */
57
+ export function parseX25519PublicKey(hex) {
58
+ const bytes = hexToBytes(hex);
59
+ if (bytes.length !== X25519_PUBLIC_KEY_BYTES) {
60
+ throw new E2eeCipherError("X25519 public key must be 32 bytes");
61
+ }
62
+ return bytes;
63
+ }
64
+ function concat(...parts) {
65
+ const total = parts.reduce((sum, part) => sum + part.length, 0);
66
+ const out = new Uint8Array(total);
67
+ let offset = 0;
68
+ for (const part of parts) {
69
+ out.set(part, offset);
70
+ offset += part.length;
71
+ }
72
+ return out;
73
+ }
74
+ /** Copy into a plain ArrayBuffer (WebCrypto rejects some typed-array views). */
75
+ function toBuffer(bytes) {
76
+ const out = new ArrayBuffer(bytes.byteLength);
77
+ new Uint8Array(out).set(bytes);
78
+ return out;
79
+ }
80
+ export async function generateX25519KeyPair() {
81
+ const pair = (await subtle().generateKey({ name: "X25519" }, false, [
82
+ "deriveBits",
83
+ ]));
84
+ const raw = await subtle().exportKey("raw", pair.publicKey);
85
+ return { privateKey: pair.privateKey, publicKey: new Uint8Array(raw) };
86
+ }
87
+ /**
88
+ * Import a private key from its 32-byte seed. Only for tests and tooling
89
+ * that need a deterministic key; production keys come from generate.
90
+ */
91
+ export async function importX25519PrivateKey(seed, publicKey) {
92
+ const b64u = (bytes) => btoa(String.fromCharCode(...bytes))
93
+ .replace(/\+/g, "-")
94
+ .replace(/\//g, "_")
95
+ .replace(/=+$/, "");
96
+ const privateKey = await subtle().importKey("jwk", { kty: "OKP", crv: "X25519", d: b64u(seed), x: b64u(publicKey) }, { name: "X25519" }, false, ["deriveBits"]);
97
+ return { privateKey, publicKey };
98
+ }
99
+ async function deriveFieldKey(privateKey, peerPublicKey, usage) {
100
+ const api = subtle();
101
+ const peer = await api.importKey("raw", toBuffer(peerPublicKey), { name: "X25519" }, false, []);
102
+ const shared = await api.deriveBits({ name: "X25519", public: peer }, privateKey, X25519_PUBLIC_KEY_BYTES * 8);
103
+ const ikm = await api.importKey("raw", shared, "HKDF", false, ["deriveKey"]);
104
+ return api.deriveKey({
105
+ name: "HKDF",
106
+ hash: "SHA-256",
107
+ salt: new Uint8Array(0),
108
+ info: new TextEncoder().encode(E2EE_HKDF_INFO_X25519),
109
+ }, ikm, { name: "AES-GCM", length: 256 }, false, [usage]);
110
+ }
111
+ /** One field value -> lowercase hex wire value. */
112
+ export async function encryptField(input) {
113
+ const ephemeral = input.ephemeral ?? (await generateX25519KeyPair());
114
+ const nonce = input.nonce ?? randomBytes(AES_GCM_NONCE_BYTES);
115
+ if (nonce.length !== AES_GCM_NONCE_BYTES) {
116
+ throw new E2eeCipherError("AES-GCM nonce must be 12 bytes");
117
+ }
118
+ const key = await deriveFieldKey(ephemeral.privateKey, input.recipientPublicKey, "encrypt");
119
+ const sealed = await subtle().encrypt({
120
+ name: "AES-GCM",
121
+ iv: toBuffer(nonce),
122
+ additionalData: toBuffer(input.aad),
123
+ tagLength: AES_GCM_TAG_BYTES * 8,
124
+ }, key, new TextEncoder().encode(input.plaintext));
125
+ return bytesToHex(concat(ephemeral.publicKey, nonce, new Uint8Array(sealed)));
126
+ }
127
+ /** Hex wire value -> plaintext; throws E2eeCipherError on any failure. */
128
+ export async function decryptField(input) {
129
+ let bytes;
130
+ try {
131
+ bytes = hexToBytes(input.wire);
132
+ }
133
+ catch {
134
+ throw new E2eeCipherError("ciphertext is not hex");
135
+ }
136
+ const minimum = X25519_PUBLIC_KEY_BYTES + AES_GCM_NONCE_BYTES + AES_GCM_TAG_BYTES;
137
+ if (bytes.length < minimum) {
138
+ throw new E2eeCipherError("ciphertext is too short");
139
+ }
140
+ const ephemeralPublicKey = bytes.subarray(0, X25519_PUBLIC_KEY_BYTES);
141
+ const nonce = bytes.subarray(X25519_PUBLIC_KEY_BYTES, X25519_PUBLIC_KEY_BYTES + AES_GCM_NONCE_BYTES);
142
+ const sealed = bytes.subarray(X25519_PUBLIC_KEY_BYTES + AES_GCM_NONCE_BYTES);
143
+ let key;
144
+ try {
145
+ key = await deriveFieldKey(input.privateKey, ephemeralPublicKey, "decrypt");
146
+ }
147
+ catch {
148
+ throw new E2eeCipherError("key agreement failed");
149
+ }
150
+ let opened;
151
+ try {
152
+ opened = await subtle().decrypt({
153
+ name: "AES-GCM",
154
+ iv: toBuffer(nonce),
155
+ additionalData: toBuffer(input.aad),
156
+ tagLength: AES_GCM_TAG_BYTES * 8,
157
+ }, key, toBuffer(sealed));
158
+ }
159
+ catch {
160
+ throw new E2eeCipherError("authentication failed");
161
+ }
162
+ return new TextDecoder().decode(opened);
163
+ }
164
+ //# sourceMappingURL=suite.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"suite.js","sourceRoot":"","sources":["../../../src/derivatives/e2ee/suite.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,MAAM,CAAC,MAAM,gBAAgB,GAAG,gCAAgC,CAAC;AACjE,MAAM,CAAC,MAAM,qBAAqB,GAAG,oBAAoB,CAAC;AAE1D,MAAM,uBAAuB,GAAG,EAAE,CAAC;AACnC,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAQ7B,MAAM,OAAO,eAAgB,SAAQ,KAAK;IACxC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;IAChC,CAAC;CACF;AAED,SAAS,MAAM;IACb,MAAM,GAAG,GAAG,UAAU,CAAC,MAAM,EAAE,MAAM,CAAC;IACtC,IAAI,CAAC,GAAG;QAAE,MAAM,IAAI,eAAe,CAAC,4BAA4B,CAAC,CAAC;IAClE,OAAO,GAAG,C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EAAE,EAAE,QAAQ,CAAC,KAAK,CAAC;YACnB,cAAc,EAAE,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC;YACnC,SAAS,EAAE,iBAAiB,GAAG,CAAC;SACjC,EACD,GAAG,EACH,QAAQ,CAAC,MAAM,CAAC,CACjB,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,eAAe,CAAC,uBAAuB,CAAC,CAAC;IACrD,CAAC;IACD,OAAO,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;AAC1C,CAAC"}
@@ -2,8 +2,9 @@ export { questionRegistrationView, type QuestionRegisteredBy, type QuestionRegis
2
2
  export { createInMemoryQuestionStore, matchesQuestionFilter, sortQuestions, } from "./store.js";
3
3
  export { MAX_ECHOED_SCOPE_CHARS, MAX_MODEL_CHARS, MAX_QUESTION_CHARS, MAX_QUESTION_SOURCE_SCOPES, createQuestionRegistration, findDerivationCycle, parseQuestionInput, uncoveredSourceScopes, type CreateQuestionRegistrationInput, type ParsedQuestionInput, } from "./registration.js";
4
4
  export { DEFAULT_MAX_SOURCE_CHARS, DEFAULT_MAX_SOURCE_ITEMS, SYSTEM_PROMPT, buildQuestionMessages, parseAnswer, sortNewestFirst, trimSourceData, type ParsedAnswer, type PromptSource, type TrimResult, } from "./prompt.js";
5
- export { DEFAULT_INFERENCE_BASE_URL, DEFAULT_INFERENCE_MAX_TOKENS, DEFAULT_INFERENCE_MODEL, DEFAULT_INFERENCE_REQUEST_FIELDS, DEFAULT_INFERENCE_TIMEOUT_MS, InferenceRequestError, createFakeInferenceProvider, createOpenAiCompatibleInferenceProvider, type FakeInferenceProvider, type FakeInferenceProviderOptions, type InferenceChatInput, type InferenceChatResult, type InferenceMessage, type InferenceProvider, type InferenceRequestEncryption, type InferenceRole, type InferenceUsage, type OpenAiCompatibleInferenceOptions, } from "./inference.js";
5
+ export { DEFAULT_INFERENCE_BASE_URL, DEFAULT_INFERENCE_MAX_TOKENS, DEFAULT_INFERENCE_MODEL, DEFAULT_INFERENCE_REQUEST_FIELDS, DEFAULT_INFERENCE_TIMEOUT_MS, InferenceRequestError, createFakeInferenceProvider, createOpenAiCompatibleInferenceProvider, type EncryptedInferenceRequest, type FakeInferenceProvider, type FakeInferenceProviderOptions, type InferenceChatInput, type InferenceChatResult, type InferenceMessage, type InferenceProvider, type InferenceRequestEncryption, type InferenceRole, type InferenceUsage, type OpenAiCompatibleInferenceOptions, } from "./inference.js";
6
6
  export { computeQuestion, type ComputeLogger, type ComputeOutcome, type ComputeSyncNotifier, type DerivativeAnswerRecord, type QuestionComputeDeps, } from "./compute.js";
7
7
  export { createRecomputeScheduler, type RecomputeScheduler, type RecomputeSchedulerOptions, type SchedulerTimers, } from "./scheduler.js";
8
8
  export { MAX_QUESTION_BODY_BYTES, handlePersonalServerDerivativesRequest, type PersonalServerDerivativesApiDeps, } from "./api.js";
9
+ export { DEFAULT_E2EE_KEY_TTL_MS, E2EE_ALGO_X25519, E2eeAttestationError, E2eeCipherError, PHALA_GATEWAY_BASE_URL, createPhalaE2eeEncryption, fetchGatewayE2eeKey, verifyAciReportBinding, type AciAttestationReport, type E2eeAttestationErrorCode, type FetchGatewayE2eeKeyOptions, type GatewayE2eeKey, type PhalaE2eeEncryption, type PhalaE2eeEncryptionOptions, } from "./e2ee/index.js";
9
10
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/derivatives/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EACxB,KAAK,oBAAoB,EACzB,KAAK,oBAAoB,EACzB,KAAK,yBAAyB,EAC9B,KAAK,wBAAwB,EAC7B,KAAK,cAAc,EACnB,KAAK,aAAa,EAClB,KAAK,uBAAuB,GAC7B,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,2BAA2B,EAC3B,qBAAqB,EACrB,aAAa,GACd,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,sBAAsB,EACtB,eAAe,EACf,kBAAkB,EAClB,0BAA0B,EAC1B,0BAA0B,EAC1B,mBAAmB,EACnB,kBAAkB,EAClB,qBAAqB,EACrB,KAAK,+BAA+B,EACpC,KAAK,mBAAmB,GACzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,wBAAwB,EACxB,wBAAwB,EACxB,aAAa,EACb,qBAAqB,EACrB,WAAW,EACX,eAAe,EACf,cAAc,EACd,KAAK,YAAY,EACjB,KAAK,YAAY,EACjB,KAAK,UAAU,GAChB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,0BAA0B,EAC1B,4BAA4B,EAC5B,uBAAuB,EACvB,gCAAgC,EAChC,4BAA4B,EAC5B,qBAAqB,EACrB,2BAA2B,EAC3B,uCAAuC,EACvC,KAAK,qBAAqB,EAC1B,KAAK,4BAA4B,EACjC,KAAK,kBAAkB,EACvB,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,EACtB,KAAK,0BAA0B,EAC/B,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,gCAAgC,GACtC,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,eAAe,EACf,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,mBAAmB,EACxB,KAAK,sBAAsB,EAC3B,KAAK,mBAAmB,GACzB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,wBAAwB,EACxB,KAAK,kBAAkB,EACvB,KAAK,yBAAyB,EAC9B,KAAK,eAAe,GACrB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,uBAAuB,EACvB,sCAAsC,EACtC,KAAK,gCAAgC,GACtC,MAAM,UAAU,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/derivatives/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EACxB,KAAK,oBAAoB,EACzB,KAAK,oBAAoB,EACzB,KAAK,yBAAyB,EAC9B,KAAK,wBAAwB,EAC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M,UAAU,CAAC;AAClB,OAAO,EACL,uBAAuB,EACvB,gBAAgB,EAChB,oBAAoB,EACpB,eAAe,EACf,sBAAsB,EACtB,yBAAyB,EACzB,mBAAmB,EACnB,sBAAsB,EACtB,KAAK,oBAAoB,EACzB,KAAK,wBAAwB,EAC7B,KAAK,0BAA0B,EAC/B,KAAK,cAAc,EACnB,KAAK,mBAAmB,EACxB,KAAK,0BAA0B,GAChC,MAAM,iBAAiB,CAAC"}
@@ -6,4 +6,5 @@ export { DEFAULT_INFERENCE_BASE_URL, DEFAULT_INFERENCE_MAX_TOKENS, DEFAULT_INFER
6
6
  export { computeQuestion, } from "./compute.js";
7
7
  export { createRecomputeScheduler, } from "./scheduler.js";
8
8
  export { MAX_QUESTION_BODY_BYTES, handlePersonalServerDerivativesRequest, } from "./api.js";
9
+ export { DEFAULT_E2EE_KEY_TTL_MS, E2EE_ALGO_X25519, E2eeAttestationError, E2eeCipherError, PHALA_GATEWAY_BASE_URL, createPhalaE2eeEncryption, fetchGatewayE2eeKey, verifyAciReportBinding, } from "./e2ee/index.js";
9
10
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/derivatives/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,GAQzB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,2BAA2B,EAC3B,qBAAqB,EACrB,aAAa,GACd,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,sBAAsB,EACtB,eAAe,EACf,kBAAkB,EAClB,0BAA0B,EAC1B,0BAA0B,EAC1B,mBAAmB,EACnB,kBAAkB,EAClB,qBAAqB,GAGtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,wBAAwB,EACxB,wBAAwB,EACxB,aAAa,EACb,qBAAqB,EACrB,WAAW,EACX,eAAe,EACf,cAAc,GAIf,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,0BAA0B,EAC1B,4BAA4B,EAC5B,uBAAuB,EACvB,gCAAgC,EAChC,4BAA4B,EAC5B,qBAAqB,EACrB,2BAA2B,EAC3B,uCAAuC,GAWxC,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,eAAe,GAMhB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,wBAAwB,GAIzB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,uBAAuB,EACvB,sCAAsC,GAEvC,MAAM,UAAU,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/derivatives/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,GAQzB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,2BAA2B,EAC3B,qBAAqB,EACrB,aAAa,GACd,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,sBAAsB,EACtB,eAAe,EACf,kBAAkB,EAClB,0BAA0B,EAC1B,0BAA0B,EAC1B,mBAAmB,EACnB,kBAAkB,EAClB,qBAAqB,GAGtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,wBAAwB,EACxB,wBAAwB,EACxB,aAAa,EACb,qBAAqB,EACrB,WAAW,EACX,eAAe,EACf,cAAc,GAIf,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,0BAA0B,EAC1B,4BAA4B,EAC5B,uBAAuB,EACvB,gCAAgC,EAChC,4BAA4B,EAC5B,qBAAqB,EACrB,2BAA2B,EAC3B,uCAAuC,GAYxC,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,eAAe,GAMhB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,wBAAwB,GAIzB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,uBAAuB,EACvB,sCAAsC,GAEvC,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,uBAAuB,EACvB,gBAAgB,EAChB,oBAAoB,EACpB,eAAe,EACf,sBAAsB,EACtB,yBAAyB,EACzB,mBAAmB,EACnB,sBAAsB,GAOvB,MAAM,iBAAiB,CAAC"}
@@ -7,13 +7,13 @@
7
7
  * optional API key header exists for local development against a provider
8
8
  * directly.
9
9
  *
10
- * E2EE SEAM (not implemented): the Phala confidential-inference E2EE v2
11
- * protocol encrypts each `messages[i].content` to the model's public key
12
- * and adds the headers X-E2EE-Version, X-Client-Pub-Key, X-Model-Pub-Key,
13
- * X-E2EE-Nonce and X-E2EE-Timestamp; the response content comes back
14
- * encrypted to the client key. `InferenceRequestEncryption` below is the
15
- * hook where that lands: it sees the outgoing messages + headers and the
16
- * incoming content + headers, and nothing else in this module has to change.
10
+ * E2EE SEAM: the Phala confidential-inference E2EE v2 protocol encrypts each
11
+ * `messages[i].content` to the gateway's attested public key and adds the
12
+ * headers X-E2EE-Version, X-Client-Pub-Key, X-Model-Pub-Key, X-E2EE-Nonce
13
+ * and X-E2EE-Timestamp; the response content comes back encrypted to the
14
+ * client key. `InferenceRequestEncryption` below is the hook, implemented
15
+ * by `createPhalaE2eeEncryption` in ./e2ee. This module only knows the
16
+ * shape: encrypt the outgoing messages, decrypt the one response field.
17
17
  */
18
18
  export type InferenceRole = "system" | "user" | "assistant";
19
19
  export interface InferenceMessage {
@@ -43,24 +43,46 @@ export interface InferenceProvider {
43
43
  readonly defaultModel: string;
44
44
  chat(input: InferenceChatInput): Promise<InferenceChatResult>;
45
45
  }
46
+ /**
47
+ * One encrypted request: the messages to send and the decryptor bound to
48
+ * that request's context (nonce, timestamp, client key), since the response
49
+ * AAD is built from them.
50
+ */
51
+ export interface EncryptedInferenceRequest {
52
+ messages: InferenceMessage[];
53
+ /**
54
+ * Decrypt one response field. `field` is the spec field path
55
+ * (`choices.{i}.message.content`), `id` the clear response `id` or "".
56
+ */
57
+ decryptResponse(input: {
58
+ content: string;
59
+ field: string;
60
+ id: string;
61
+ headers: Headers;
62
+ }): Promise<string>;
63
+ }
46
64
  /**
47
65
  * E2EE seam. Implement to encrypt message contents end to end (Phala E2EE
48
- * v2); absent = plaintext over TLS to the relay. Both hooks run inside
66
+ * v2); absent = plaintext over TLS to the relay. Runs inside
49
67
  * `createOpenAiCompatibleInferenceProvider`, around the single fetch.
50
68
  */
51
69
  export interface InferenceRequestEncryption {
52
70
  /** Encrypt `messages[i].content` and add the X-E2EE-* request headers. */
53
71
  encryptRequest(input: {
72
+ model: string;
54
73
  messages: InferenceMessage[];
55
74
  headers: Headers;
56
- }): Promise<{
57
- messages: InferenceMessage[];
58
- }>;
59
- /** Decrypt the assistant content using the response headers. */
60
- decryptResponse(input: {
61
- content: string;
75
+ }): Promise<EncryptedInferenceRequest>;
76
+ /**
77
+ * Called once when the provider rejects the request (non-2xx) with the
78
+ * OpenAI-style `error.type` when the body carries one. Return true to
79
+ * re-encrypt and resend once (e.g. after `e2ee_model_key_mismatch`).
80
+ */
81
+ onRejected?(input: {
82
+ status: number;
83
+ errorType: string | null;
62
84
  headers: Headers;
63
- }): Promise<string>;
85
+ }): Promise<boolean>;
64
86
  }
65
87
  export declare const DEFAULT_INFERENCE_BASE_URL = "https://inference.phala.com/v1";
66
88
  export declare const DEFAULT_INFERENCE_MODEL = "z-ai/glm-5.2";
@@ -86,7 +108,17 @@ export declare const DEFAULT_INFERENCE_REQUEST_FIELDS: Record<string, unknown>;
86
108
  /** Thrown for a non-2xx or malformed provider reply. Carries no prompt text. */
87
109
  export declare class InferenceRequestError extends Error {
88
110
  readonly status: number | null;
89
- constructor(message: string, status: number | null);
111
+ /** OpenAI-style `error.type` of the rejection, when the body had one. */
112
+ readonly errorType: string | null;
113
+ /**
114
+ * Explicit retry hint. When undefined the compute layer falls back to the
115
+ * status: no response, 429 or 5xx are retried.
116
+ */
117
+ readonly retryable: boolean | undefined;
118
+ constructor(message: string, status: number | null, options?: {
119
+ errorType?: string | null;
120
+ retryable?: boolean;
121
+ });
90
122
  }
91
123
  export declare function createOpenAiCompatibleInferenceProvider(options?: OpenAiCompatibleInferenceOptions): InferenceProvider;
92
124
  export interface FakeInferenceProviderOptions {
@@ -1 +1 @@
1
- {"version":3,"file":"inference.d.ts","sourceRoot":"","sources":["../../src/derivat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