@lucern/sdk 0.3.0-alpha.2 → 0.3.0-alpha.3

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 (163) hide show
  1. package/dist/adminClient.d.ts +2 -0
  2. package/dist/adminClient.js +194 -3
  3. package/dist/adminClient.js.map +1 -1
  4. package/dist/answersClient.d.ts +2 -0
  5. package/dist/answersClient.js +194 -3
  6. package/dist/answersClient.js.map +1 -1
  7. package/dist/audiencesClient.d.ts +2 -0
  8. package/dist/audiencesClient.js +194 -3
  9. package/dist/audiencesClient.js.map +1 -1
  10. package/dist/auditClient.d.ts +2 -0
  11. package/dist/auditClient.js +196 -5
  12. package/dist/auditClient.js.map +1 -1
  13. package/dist/authContext.d.ts +56 -0
  14. package/dist/authContext.js +169 -0
  15. package/dist/authContext.js.map +1 -0
  16. package/dist/authDeviceClient.d.ts +49 -0
  17. package/dist/authDeviceClient.js +108 -0
  18. package/dist/authDeviceClient.js.map +1 -0
  19. package/dist/beliefs/index.d.ts +19 -2
  20. package/dist/beliefs/index.js +2356 -329
  21. package/dist/beliefs/index.js.map +1 -1
  22. package/dist/beliefsClient.d.ts +2 -0
  23. package/dist/beliefsClient.js +198 -7
  24. package/dist/beliefsClient.js.map +1 -1
  25. package/dist/boundaryClientSurface.d.ts +20 -0
  26. package/dist/boundaryClientSurface.js +66 -0
  27. package/dist/boundaryClientSurface.js.map +1 -0
  28. package/dist/{client-B6aWUUwp.d.ts → client-EiG9nJOY.d.ts} +365 -6
  29. package/dist/client.d.ts +20 -3
  30. package/dist/client.js +2356 -329
  31. package/dist/client.js.map +1 -1
  32. package/dist/contextClient.d.ts +2 -0
  33. package/dist/contextClient.js +200 -9
  34. package/dist/contextClient.js.map +1 -1
  35. package/dist/contracts/index.d.ts +1 -0
  36. package/dist/contracts/index.js +104 -1
  37. package/dist/contracts/index.js.map +1 -1
  38. package/dist/contracts/mcpTools.d.ts +46 -1
  39. package/dist/contracts/mcpTools.js +102 -0
  40. package/dist/contracts/mcpTools.js.map +1 -1
  41. package/dist/contradictions/index.d.ts +19 -2
  42. package/dist/contradictions/index.js +2356 -329
  43. package/dist/contradictions/index.js.map +1 -1
  44. package/dist/coreClient.d.ts +9 -0
  45. package/dist/coreClient.js +194 -3
  46. package/dist/coreClient.js.map +1 -1
  47. package/dist/decisions/index.d.ts +19 -2
  48. package/dist/decisions/index.js +2356 -329
  49. package/dist/decisions/index.js.map +1 -1
  50. package/dist/decisionsClient.d.ts +2 -0
  51. package/dist/decisionsClient.js +197 -6
  52. package/dist/decisionsClient.js.map +1 -1
  53. package/dist/edges/index.d.ts +19 -2
  54. package/dist/edges/index.js +2356 -329
  55. package/dist/edges/index.js.map +1 -1
  56. package/dist/embeddingsClient.d.ts +106 -0
  57. package/dist/embeddingsClient.js +707 -0
  58. package/dist/embeddingsClient.js.map +1 -0
  59. package/dist/eventingClient.d.ts +96 -0
  60. package/dist/eventingClient.js +704 -0
  61. package/dist/eventingClient.js.map +1 -0
  62. package/dist/eventsCore.d.ts +2 -0
  63. package/dist/eventsCore.js +194 -3
  64. package/dist/eventsCore.js.map +1 -1
  65. package/dist/evidence/index.d.ts +19 -2
  66. package/dist/evidence/index.js +2356 -329
  67. package/dist/evidence/index.js.map +1 -1
  68. package/dist/evidenceClient.d.ts +2 -0
  69. package/dist/evidenceClient.js +194 -3
  70. package/dist/evidenceClient.js.map +1 -1
  71. package/dist/gatewayFacades.d.ts +4 -2
  72. package/dist/gatewayFacades.js +370 -12
  73. package/dist/gatewayFacades.js.map +1 -1
  74. package/dist/graphAnalysisClient.d.ts +140 -0
  75. package/dist/graphAnalysisClient.js +753 -0
  76. package/dist/graphAnalysisClient.js.map +1 -0
  77. package/dist/graphClient.d.ts +2 -0
  78. package/dist/graphClient.js +201 -10
  79. package/dist/graphClient.js.map +1 -1
  80. package/dist/graphRecommendationsClient.d.ts +56 -0
  81. package/dist/graphRecommendationsClient.js +645 -0
  82. package/dist/graphRecommendationsClient.js.map +1 -0
  83. package/dist/graphStateClassifierClient.d.ts +73 -0
  84. package/dist/graphStateClassifierClient.js +693 -0
  85. package/dist/graphStateClassifierClient.js.map +1 -0
  86. package/dist/harnessClient.d.ts +2 -0
  87. package/dist/harnessClient.js +196 -5
  88. package/dist/harnessClient.js.map +1 -1
  89. package/dist/identityClient.d.ts +89 -3
  90. package/dist/identityClient.js +362 -4
  91. package/dist/identityClient.js.map +1 -1
  92. package/dist/index.d.ts +20 -3
  93. package/dist/index.js +2516 -356
  94. package/dist/index.js.map +1 -1
  95. package/dist/jobsClient.d.ts +98 -0
  96. package/dist/jobsClient.js +703 -0
  97. package/dist/jobsClient.js.map +1 -0
  98. package/dist/learningClient.d.ts +2 -0
  99. package/dist/learningClient.js +196 -5
  100. package/dist/learningClient.js.map +1 -1
  101. package/dist/lenses/index.d.ts +19 -2
  102. package/dist/lenses/index.js +2356 -329
  103. package/dist/lenses/index.js.map +1 -1
  104. package/dist/mcpClient.d.ts +28 -0
  105. package/dist/mcpClient.js +649 -0
  106. package/dist/mcpClient.js.map +1 -0
  107. package/dist/modelRuntimeClient.d.ts +72 -0
  108. package/dist/modelRuntimeClient.js +680 -0
  109. package/dist/modelRuntimeClient.js.map +1 -0
  110. package/dist/nodes/index.d.ts +19 -2
  111. package/dist/nodes/index.js +2356 -329
  112. package/dist/nodes/index.js.map +1 -1
  113. package/dist/ontologies/index.d.ts +19 -2
  114. package/dist/ontologies/index.js +2356 -329
  115. package/dist/ontologies/index.js.map +1 -1
  116. package/dist/ontologyClient.d.ts +2 -0
  117. package/dist/ontologyClient.js +194 -3
  118. package/dist/ontologyClient.js.map +1 -1
  119. package/dist/ontologyLinksClient.d.ts +71 -0
  120. package/dist/ontologyLinksClient.js +674 -0
  121. package/dist/ontologyLinksClient.js.map +1 -0
  122. package/dist/orgGraphSearchClient.d.ts +85 -0
  123. package/dist/orgGraphSearchClient.js +651 -0
  124. package/dist/orgGraphSearchClient.js.map +1 -0
  125. package/dist/packRuntime.d.ts +1 -2
  126. package/dist/packsClient.d.ts +2 -0
  127. package/dist/packsClient.js +194 -3
  128. package/dist/packsClient.js.map +1 -1
  129. package/dist/policyClient.d.ts +2 -0
  130. package/dist/policyClient.js +194 -3
  131. package/dist/policyClient.js.map +1 -1
  132. package/dist/questions/index.d.ts +19 -2
  133. package/dist/questions/index.js +2356 -329
  134. package/dist/questions/index.js.map +1 -1
  135. package/dist/reportsClient.d.ts +2 -0
  136. package/dist/reportsClient.js +196 -5
  137. package/dist/reportsClient.js.map +1 -1
  138. package/dist/schemaClient.d.ts +2 -0
  139. package/dist/schemaClient.js +194 -3
  140. package/dist/schemaClient.js.map +1 -1
  141. package/dist/sdkSurface.d.ts +2 -0
  142. package/dist/sourcesClient.d.ts +2 -0
  143. package/dist/sourcesClient.js +194 -3
  144. package/dist/sourcesClient.js.map +1 -1
  145. package/dist/telemetryClient.d.ts +94 -0
  146. package/dist/telemetryClient.js +718 -0
  147. package/dist/telemetryClient.js.map +1 -0
  148. package/dist/toolRegistryClient.d.ts +107 -0
  149. package/dist/toolRegistryClient.js +732 -0
  150. package/dist/toolRegistryClient.js.map +1 -0
  151. package/dist/topics/index.d.ts +19 -2
  152. package/dist/topics/index.js +2356 -329
  153. package/dist/topics/index.js.map +1 -1
  154. package/dist/topicsClient.d.ts +2 -0
  155. package/dist/topicsClient.js +199 -8
  156. package/dist/topicsClient.js.map +1 -1
  157. package/dist/workflowClient.d.ts +2 -0
  158. package/dist/workflowClient.js +199 -8
  159. package/dist/workflowClient.js.map +1 -1
  160. package/dist/worktrees/index.d.ts +19 -2
  161. package/dist/worktrees/index.js +2356 -329
  162. package/dist/worktrees/index.js.map +1 -1
  163. package/package.json +3 -3
@@ -0,0 +1,680 @@
1
+ // src/authContext.ts
2
+ var LucernSdkAuthContextError = class extends Error {
3
+ reason;
4
+ constructor(reason, message) {
5
+ super(message);
6
+ this.name = "LucernSdkAuthContextError";
7
+ this.reason = reason;
8
+ }
9
+ };
10
+ function cleanString(value) {
11
+ const normalized = value?.trim();
12
+ return normalized ? normalized : void 0;
13
+ }
14
+ function cleanStringList(values) {
15
+ if (!values) {
16
+ return [];
17
+ }
18
+ return values.map((value) => value.trim()).filter(
19
+ (value, index, list) => value.length > 0 && list.indexOf(value) === index
20
+ );
21
+ }
22
+ function requireString(value, reason, label) {
23
+ const normalized = cleanString(value);
24
+ if (!normalized) {
25
+ throw new LucernSdkAuthContextError(
26
+ reason,
27
+ `Canonical Lucern SDK auth context is missing ${label}.`
28
+ );
29
+ }
30
+ return normalized;
31
+ }
32
+ function requirePrincipalType(principalType) {
33
+ if (!principalType) {
34
+ throw new LucernSdkAuthContextError(
35
+ "principal_missing",
36
+ "Canonical Lucern SDK auth context is missing principalType."
37
+ );
38
+ }
39
+ return principalType;
40
+ }
41
+ function requireAuthMode(authMode) {
42
+ if (!authMode) {
43
+ throw new LucernSdkAuthContextError(
44
+ "principal_missing",
45
+ "Canonical Lucern SDK auth context is missing authMode."
46
+ );
47
+ }
48
+ return authMode;
49
+ }
50
+ function ensurePermitMatch(args) {
51
+ const actual = cleanString(args.actual);
52
+ if (actual && actual !== args.expected) {
53
+ throw new LucernSdkAuthContextError(
54
+ "policy_denied",
55
+ `Canonical Lucern SDK auth context has conflicting Permit ${args.field}.`
56
+ );
57
+ }
58
+ }
59
+ function normalizeCanonicalLucernAuthContext(input) {
60
+ if (!input) {
61
+ throw new LucernSdkAuthContextError(
62
+ "principal_missing",
63
+ "Canonical Lucern SDK auth context is required."
64
+ );
65
+ }
66
+ if (input.policyDecision === "deny") {
67
+ throw new LucernSdkAuthContextError(
68
+ "policy_denied",
69
+ "Canonical Lucern SDK auth context carries a denied policy decision."
70
+ );
71
+ }
72
+ const principalId = requireString(
73
+ input.principalId,
74
+ "principal_missing",
75
+ "principalId"
76
+ );
77
+ const tenantId = requireString(input.tenantId, "tenant_missing", "tenantId");
78
+ const workspaceId = requireString(
79
+ input.workspaceId,
80
+ "workspace_missing",
81
+ "workspaceId"
82
+ );
83
+ const roles = cleanStringList(input.roles);
84
+ const scopes = cleanStringList(input.scopes);
85
+ if (roles.length === 0 || scopes.length === 0) {
86
+ throw new LucernSdkAuthContextError(
87
+ "membership_missing",
88
+ "Canonical Lucern SDK auth context requires non-empty roles and scopes."
89
+ );
90
+ }
91
+ const principalType = requirePrincipalType(input.principalType);
92
+ const authMode = requireAuthMode(input.authMode);
93
+ const subject = cleanString(input.permit?.subject) ?? principalId;
94
+ const tenant = cleanString(input.permit?.tenant) ?? tenantId;
95
+ const workspace = cleanString(input.permit?.workspace) ?? workspaceId;
96
+ ensurePermitMatch({
97
+ field: "subject",
98
+ expected: principalId,
99
+ actual: subject
100
+ });
101
+ ensurePermitMatch({ field: "tenant", expected: tenantId, actual: tenant });
102
+ ensurePermitMatch({
103
+ field: "workspace",
104
+ expected: workspaceId,
105
+ actual: workspace
106
+ });
107
+ const context = input.permit?.context ? { ...input.permit.context } : void 0;
108
+ return {
109
+ clerkId: cleanString(input.clerkId),
110
+ principalId,
111
+ tenantId,
112
+ workspaceId,
113
+ principalType,
114
+ authMode,
115
+ roles,
116
+ scopes,
117
+ delegationChain: input.delegationChain ? [...input.delegationChain] : [],
118
+ policyTraceId: cleanString(input.policyTraceId),
119
+ correlationId: cleanString(input.correlationId),
120
+ membershipId: cleanString(input.membershipId),
121
+ permit: {
122
+ subject,
123
+ tenant,
124
+ workspace,
125
+ resource: cleanString(input.permit?.resource),
126
+ action: cleanString(input.permit?.action),
127
+ relation: cleanString(input.permit?.relation),
128
+ context
129
+ }
130
+ };
131
+ }
132
+ function createCanonicalAuthHeaders(authContext) {
133
+ const headers = {
134
+ "x-lucern-principal-id": authContext.principalId,
135
+ "x-lucern-principal-type": authContext.principalType,
136
+ "x-lucern-tenant": authContext.tenantId,
137
+ "x-lucern-tenant-id": authContext.tenantId,
138
+ "x-lucern-workspace": authContext.workspaceId,
139
+ "x-lucern-workspace-id": authContext.workspaceId,
140
+ "x-lucern-auth-mode": authContext.authMode,
141
+ "x-lucern-roles": authContext.roles.join(","),
142
+ "x-lucern-scopes": authContext.scopes.join(","),
143
+ "x-lucern-permit-context": JSON.stringify(authContext.permit)
144
+ };
145
+ if (authContext.clerkId) {
146
+ headers["x-lucern-clerk-id"] = authContext.clerkId;
147
+ headers["x-lucern-user-id"] = authContext.clerkId;
148
+ }
149
+ if (authContext.delegationChain.length > 0) {
150
+ headers["x-lucern-delegation-chain"] = JSON.stringify(
151
+ authContext.delegationChain
152
+ );
153
+ }
154
+ if (authContext.policyTraceId) {
155
+ headers["x-lucern-policy-trace-id"] = authContext.policyTraceId;
156
+ }
157
+ if (authContext.correlationId) {
158
+ headers["x-correlation-id"] = authContext.correlationId;
159
+ headers["x-lucern-correlation-id"] = authContext.correlationId;
160
+ }
161
+ if (authContext.membershipId) {
162
+ headers["x-lucern-membership-id"] = authContext.membershipId;
163
+ }
164
+ return headers;
165
+ }
166
+
167
+ // src/coreClient.ts
168
+ var LucernApiError = class extends Error {
169
+ code;
170
+ status;
171
+ invariant;
172
+ suggestion;
173
+ details;
174
+ requestId;
175
+ correlationId;
176
+ policyTraceId;
177
+ constructor(args) {
178
+ super(args.message);
179
+ this.name = "LucernApiError";
180
+ this.code = args.code;
181
+ this.status = args.status;
182
+ this.invariant = args.invariant;
183
+ this.suggestion = args.suggestion;
184
+ this.details = args.details;
185
+ this.requestId = args.requestId;
186
+ this.correlationId = args.correlationId;
187
+ this.policyTraceId = args.policyTraceId;
188
+ }
189
+ };
190
+ function toQueryString(scope) {
191
+ const params = new URLSearchParams();
192
+ if (scope.tenantId) {
193
+ params.set("tenantId", scope.tenantId);
194
+ }
195
+ if (scope.workspaceId) {
196
+ params.set("workspaceId", scope.workspaceId);
197
+ }
198
+ for (const [key, value] of Object.entries(scope)) {
199
+ if (key === "tenantId" || key === "workspaceId") {
200
+ continue;
201
+ }
202
+ if (value === void 0) {
203
+ continue;
204
+ }
205
+ params.set(key, String(value));
206
+ }
207
+ const serialized = params.toString();
208
+ return serialized.length > 0 ? `?${serialized}` : "";
209
+ }
210
+ function fillRandomBytes(length) {
211
+ const bytes = new Uint8Array(length);
212
+ if (typeof globalThis.crypto?.getRandomValues === "function") {
213
+ globalThis.crypto.getRandomValues(bytes);
214
+ return bytes;
215
+ }
216
+ for (let index = 0; index < length; index += 1) {
217
+ bytes[index] = Math.floor(Math.random() * 256);
218
+ }
219
+ return bytes;
220
+ }
221
+ function generatePortableRequestId() {
222
+ if (typeof globalThis.crypto?.randomUUID === "function") {
223
+ return globalThis.crypto.randomUUID();
224
+ }
225
+ const bytes = fillRandomBytes(16);
226
+ bytes[6] = bytes[6] & 15 | 64;
227
+ bytes[8] = bytes[8] & 63 | 128;
228
+ const hex = Array.from(bytes, (value) => value.toString(16).padStart(2, "0"));
229
+ return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(
230
+ 6,
231
+ 8
232
+ ).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
233
+ }
234
+ function randomIdempotencyKey() {
235
+ return generatePortableRequestId();
236
+ }
237
+ function isRetryableStatus(status) {
238
+ return status >= 500 || status === 408 || status === 429;
239
+ }
240
+ function fallbackErrorCode(status) {
241
+ if (status === 401) {
242
+ return "AUTHENTICATION_REQUIRED";
243
+ }
244
+ if (status === 403) {
245
+ return "FORBIDDEN";
246
+ }
247
+ if (status === 404) {
248
+ return "NOT_FOUND";
249
+ }
250
+ if (status === 408) {
251
+ return "UPSTREAM_ERROR";
252
+ }
253
+ if (status === 409) {
254
+ return "CONFLICT";
255
+ }
256
+ if (status === 429) {
257
+ return "RATE_LIMIT_EXCEEDED";
258
+ }
259
+ if (status >= 500) {
260
+ return "UPSTREAM_ERROR";
261
+ }
262
+ return "INTERNAL_ERROR";
263
+ }
264
+ function delay(ms) {
265
+ return new Promise((resolve) => setTimeout(resolve, ms));
266
+ }
267
+ function parseRetryAfterMs(value) {
268
+ if (!value) {
269
+ return null;
270
+ }
271
+ const trimmed = value.trim();
272
+ if (!trimmed) {
273
+ return null;
274
+ }
275
+ const numeric = Number(trimmed);
276
+ if (Number.isFinite(numeric)) {
277
+ return Math.max(0, Math.round(numeric * 1e3));
278
+ }
279
+ const parsedDate = Date.parse(trimmed);
280
+ if (Number.isFinite(parsedDate)) {
281
+ return Math.max(0, parsedDate - Date.now());
282
+ }
283
+ return null;
284
+ }
285
+ function computeRetryDelayMs(args) {
286
+ const baseDelay = args.status === 429 ? Math.max(
287
+ args.retryAfterMs ?? 0,
288
+ Math.min(1e3 * 2 ** args.attempt, 1e4)
289
+ ) : Math.min(1e3 * 2 ** args.attempt, 4e3);
290
+ if (args.status !== 429) {
291
+ return baseDelay;
292
+ }
293
+ const jitterWindow = Math.max(250, Math.round(baseDelay * 0.25));
294
+ return baseDelay + Math.round(Math.random() * jitterWindow);
295
+ }
296
+ function timeoutError(timeoutMs) {
297
+ const error = new Error(`Request timed out after ${timeoutMs}ms`);
298
+ error.name = "AbortError";
299
+ return error;
300
+ }
301
+ function readPolicySummaryFromDetails(details) {
302
+ if (!details || typeof details !== "object" || Array.isArray(details)) {
303
+ return null;
304
+ }
305
+ const directSummary = details.summary;
306
+ if (typeof directSummary === "string" && directSummary.trim().length > 0) {
307
+ return directSummary.trim();
308
+ }
309
+ const policy = details.policy;
310
+ if (!policy || typeof policy !== "object" || Array.isArray(policy)) {
311
+ return null;
312
+ }
313
+ const explanation = policy.explanation;
314
+ if (!explanation || typeof explanation !== "object" || Array.isArray(explanation)) {
315
+ return null;
316
+ }
317
+ const nestedSummary = explanation.summary;
318
+ if (typeof nestedSummary === "string" && nestedSummary.trim().length > 0) {
319
+ return nestedSummary.trim();
320
+ }
321
+ return null;
322
+ }
323
+ async function resolveConfiguredAuthContext(authContext) {
324
+ if (typeof authContext === "function") {
325
+ return await authContext();
326
+ }
327
+ return authContext;
328
+ }
329
+ function mergeHeaderRecord(base, addition) {
330
+ const headers = new Headers(base);
331
+ for (const [key, value] of Object.entries(addition)) {
332
+ const existing = headers.get(key);
333
+ if (existing !== null && existing !== value) {
334
+ throw new LucernSdkAuthContextError(
335
+ "policy_denied",
336
+ `Canonical Lucern SDK auth context conflicts with existing ${key} header.`
337
+ );
338
+ }
339
+ headers.set(key, value);
340
+ }
341
+ return Object.fromEntries(headers.entries());
342
+ }
343
+ function createGatewayRequestClient(config = {}) {
344
+ const fetchImpl = config.fetchImpl ?? fetch;
345
+ const baseUrl = config.baseUrl?.replace(/\/+$/, "") ?? "";
346
+ const maxRetries = config.maxRetries ?? 2;
347
+ const requestIdFactory = config.requestIdFactory ?? (() => generatePortableRequestId());
348
+ async function resolveAuthHeaders() {
349
+ const base = config.getAuthHeaders ? await config.getAuthHeaders() : {};
350
+ const authContextInput = await resolveConfiguredAuthContext(
351
+ config.authContext
352
+ );
353
+ if (!authContextInput && !config.requireCanonicalAuthContext) {
354
+ return base;
355
+ }
356
+ const authContext = normalizeCanonicalLucernAuthContext(authContextInput);
357
+ return mergeHeaderRecord(base, createCanonicalAuthHeaders(authContext));
358
+ }
359
+ async function fetchWithTimeout(url, init, timeoutMs) {
360
+ const controller = new AbortController();
361
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
362
+ try {
363
+ return await fetchImpl(url, { ...init, signal: controller.signal });
364
+ } catch (error) {
365
+ if (controller.signal.aborted) {
366
+ throw timeoutError(timeoutMs);
367
+ }
368
+ throw error;
369
+ } finally {
370
+ clearTimeout(timer);
371
+ }
372
+ }
373
+ async function parsePayload(response) {
374
+ const text = await response.text();
375
+ if (!text) {
376
+ return null;
377
+ }
378
+ try {
379
+ return JSON.parse(text);
380
+ } catch {
381
+ return null;
382
+ }
383
+ }
384
+ function resolveTimeoutMs(method, requestTimeoutMs) {
385
+ if (typeof requestTimeoutMs === "number") {
386
+ return requestTimeoutMs;
387
+ }
388
+ const methodTimeoutMs = config.timeoutMsByMethod?.[method];
389
+ if (typeof methodTimeoutMs === "number") {
390
+ return methodTimeoutMs;
391
+ }
392
+ return config.timeoutMs ?? 15e3;
393
+ }
394
+ function buildApiError(args) {
395
+ const failure = args.failure;
396
+ const legacyError = failure && typeof failure.error === "object" && failure.error !== null ? failure.error : failure?.legacyError;
397
+ const correlationId = failure?.correlationId ?? args.response.headers.get("x-lucern-correlation-id")?.trim() ?? args.requestId;
398
+ const policyTraceId = failure?.policyTraceId ?? args.response.headers.get("x-lucern-policy-trace-id")?.trim() ?? null;
399
+ const details = failure?.details ?? legacyError?.details;
400
+ const policySummary = readPolicySummaryFromDetails(details);
401
+ return new LucernApiError({
402
+ code: failure?.code ?? legacyError?.code ?? fallbackErrorCode(args.response.status),
403
+ message: policySummary ?? (typeof failure?.error === "string" ? failure.error : legacyError?.message ?? (args.response.ok ? "Platform API returned an invalid success payload." : "Platform API request failed.")),
404
+ status: args.response.status,
405
+ invariant: failure?.invariant,
406
+ suggestion: failure?.suggestion,
407
+ details,
408
+ requestId: args.requestId,
409
+ correlationId,
410
+ policyTraceId
411
+ });
412
+ }
413
+ async function request(args) {
414
+ const authHeaders = await resolveAuthHeaders();
415
+ const method = args.method ?? "GET";
416
+ const timeoutMs = resolveTimeoutMs(method, args.timeoutMs);
417
+ const headers = new Headers({
418
+ "content-type": "application/json",
419
+ ...authHeaders
420
+ });
421
+ if (args.idempotencyKey) {
422
+ headers.set("idempotency-key", args.idempotencyKey);
423
+ }
424
+ const requestId = headers.get("x-correlation-id")?.trim() || headers.get("x-request-id")?.trim() || args.requestId || requestIdFactory();
425
+ if (!headers.has("x-correlation-id") && !headers.has("x-request-id")) {
426
+ headers.set("x-correlation-id", requestId);
427
+ }
428
+ const url = `${baseUrl}${args.path}`;
429
+ const serializedBody = args.body ? JSON.stringify(args.body) : void 0;
430
+ const init = {
431
+ method,
432
+ headers,
433
+ body: serializedBody
434
+ };
435
+ let lastError;
436
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
437
+ const hookRequestContext = {
438
+ requestId,
439
+ attempt,
440
+ maxRetries,
441
+ method,
442
+ path: args.path,
443
+ url,
444
+ headers: new Headers(headers),
445
+ body: serializedBody,
446
+ timeoutMs
447
+ };
448
+ await config.onRequest?.(hookRequestContext);
449
+ const startedAt = Date.now();
450
+ try {
451
+ const response = await fetchWithTimeout(url, init, timeoutMs);
452
+ const responseClone = response.clone();
453
+ const payload = await parsePayload(response);
454
+ const retryAfterMs = parseRetryAfterMs(
455
+ response.headers.get("Retry-After")
456
+ );
457
+ if (!response.ok || !payload?.success) {
458
+ const failure = payload && !payload.success ? payload : null;
459
+ const apiError = buildApiError({
460
+ requestId,
461
+ response,
462
+ failure
463
+ });
464
+ const willRetry = attempt < maxRetries && isRetryableStatus(response.status);
465
+ await config.onResponse?.({
466
+ ...hookRequestContext,
467
+ durationMs: Date.now() - startedAt,
468
+ status: response.status,
469
+ response: responseClone,
470
+ error: apiError,
471
+ correlationId: apiError.correlationId ?? requestId,
472
+ policyTraceId: apiError.policyTraceId ?? null,
473
+ retryAfterMs,
474
+ willRetry
475
+ });
476
+ if (willRetry) {
477
+ lastError = apiError;
478
+ await delay(
479
+ computeRetryDelayMs({
480
+ attempt,
481
+ status: response.status,
482
+ retryAfterMs
483
+ })
484
+ );
485
+ continue;
486
+ }
487
+ throw apiError;
488
+ }
489
+ const successPayload = payload;
490
+ await config.onResponse?.({
491
+ ...hookRequestContext,
492
+ durationMs: Date.now() - startedAt,
493
+ status: response.status,
494
+ response: responseClone,
495
+ correlationId: successPayload.correlationId ?? response.headers.get("x-lucern-correlation-id")?.trim() ?? requestId,
496
+ policyTraceId: successPayload.policyTraceId ?? response.headers.get("x-lucern-policy-trace-id")?.trim() ?? null,
497
+ idempotentReplay: successPayload.idempotentReplay,
498
+ retryAfterMs,
499
+ willRetry: false
500
+ });
501
+ return successPayload;
502
+ } catch (fetchError) {
503
+ if (fetchError instanceof LucernApiError) {
504
+ throw fetchError;
505
+ }
506
+ const willRetry = attempt < maxRetries;
507
+ await config.onResponse?.({
508
+ ...hookRequestContext,
509
+ durationMs: Date.now() - startedAt,
510
+ error: fetchError,
511
+ correlationId: requestId,
512
+ policyTraceId: null,
513
+ willRetry
514
+ });
515
+ lastError = fetchError;
516
+ if (willRetry) {
517
+ await delay(computeRetryDelayMs({ attempt }));
518
+ }
519
+ }
520
+ }
521
+ throw lastError instanceof Error ? lastError : new Error("Platform API request failed after retries.");
522
+ }
523
+ return {
524
+ request
525
+ };
526
+ }
527
+
528
+ // src/sdkSurface.ts
529
+ function createListResult(items, legacyKey) {
530
+ const result = {
531
+ items,
532
+ total: items.length
533
+ };
534
+ if (legacyKey) {
535
+ result[legacyKey] = items;
536
+ }
537
+ return result;
538
+ }
539
+ function mapGatewayData(response, mapper) {
540
+ return {
541
+ ...response,
542
+ data: mapper(response.data)
543
+ };
544
+ }
545
+
546
+ // src/boundaryClientSurface.ts
547
+ function cleanOptionalString(value) {
548
+ const normalized = value?.trim();
549
+ return normalized ? normalized : void 0;
550
+ }
551
+ function cleanRequiredString(value, label) {
552
+ const normalized = cleanOptionalString(value);
553
+ if (!normalized) {
554
+ throw new Error(`${label} is required`);
555
+ }
556
+ return normalized;
557
+ }
558
+ function assertKnownKeys(input, allowed, operation) {
559
+ const allowedSet = new Set(allowed);
560
+ const unknownKeys = Object.keys(input).filter((key) => !allowedSet.has(key));
561
+ if (unknownKeys.length > 0) {
562
+ throw new Error(
563
+ `${operation} received unsupported field(s): ${unknownKeys.join(", ")}`
564
+ );
565
+ }
566
+ }
567
+ function knownPayload(input, allowed, operation) {
568
+ assertKnownKeys(input, allowed, operation);
569
+ return { ...input };
570
+ }
571
+ function listResultFromEnvelope(data, legacyKey) {
572
+ const record = data && typeof data === "object" ? data : {};
573
+ return createListResult(
574
+ Array.isArray(record[legacyKey]) ? record[legacyKey] : Array.isArray(data) ? data : [],
575
+ legacyKey
576
+ );
577
+ }
578
+
579
+ // src/modelRuntimeClient.ts
580
+ var MODEL_RUNTIME_FIELDS = [
581
+ "tenantId",
582
+ "workspaceId",
583
+ "principalId",
584
+ "functionName",
585
+ "slotKey",
586
+ "modelId",
587
+ "provider",
588
+ "routingPolicy",
589
+ "metadata",
590
+ "limit",
591
+ "cursor"
592
+ ];
593
+ function scopeQuery(input) {
594
+ return {
595
+ tenantId: cleanRequiredString(input.tenantId, "tenantId"),
596
+ workspaceId: input.workspaceId,
597
+ principalId: input.principalId,
598
+ provider: input.provider,
599
+ limit: input.limit,
600
+ cursor: input.cursor
601
+ };
602
+ }
603
+ function modelRuntimeBody(input, operation) {
604
+ return knownPayload(input, MODEL_RUNTIME_FIELDS, operation);
605
+ }
606
+ function createModelRuntimeClient(config = {}) {
607
+ const gateway = createGatewayRequestClient(config);
608
+ return {
609
+ listModels(input) {
610
+ return gateway.request({
611
+ path: `/api/platform/v1/model-runtime/models${toQueryString(
612
+ scopeQuery(input)
613
+ )}`
614
+ }).then(
615
+ (response) => mapGatewayData(
616
+ response,
617
+ (data) => listResultFromEnvelope(data, "models")
618
+ )
619
+ );
620
+ },
621
+ getModel(input) {
622
+ cleanRequiredString(input.tenantId, "tenantId");
623
+ cleanRequiredString(input.modelId, "modelId");
624
+ return gateway.request({
625
+ path: `/api/platform/v1/model-runtime/models/${encodeURIComponent(
626
+ input.modelId
627
+ )}${toQueryString({
628
+ tenantId: input.tenantId,
629
+ workspaceId: input.workspaceId,
630
+ principalId: input.principalId
631
+ })}`
632
+ });
633
+ },
634
+ listFunctionSlots(input) {
635
+ return gateway.request({
636
+ path: `/api/platform/v1/model-runtime/function-slots${toQueryString({
637
+ ...scopeQuery(input),
638
+ functionName: input.functionName
639
+ })}`
640
+ }).then(
641
+ (response) => mapGatewayData(
642
+ response,
643
+ (data) => listResultFromEnvelope(data, "slots")
644
+ )
645
+ );
646
+ },
647
+ resolveSlot(input, idempotencyKey) {
648
+ cleanRequiredString(input.tenantId, "tenantId");
649
+ cleanRequiredString(input.functionName, "functionName");
650
+ return gateway.request({
651
+ path: "/api/platform/v1/model-runtime/function-slots/resolve",
652
+ method: "POST",
653
+ body: modelRuntimeBody(
654
+ input,
655
+ "modelRuntime.resolveSlot"
656
+ ),
657
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
658
+ });
659
+ },
660
+ updateSlotConfig(input, idempotencyKey) {
661
+ cleanRequiredString(input.tenantId, "tenantId");
662
+ cleanRequiredString(input.functionName, "functionName");
663
+ cleanRequiredString(input.slotKey, "slotKey");
664
+ cleanRequiredString(input.modelId, "modelId");
665
+ return gateway.request({
666
+ path: "/api/platform/v1/model-runtime/slot-configs",
667
+ method: "PUT",
668
+ body: modelRuntimeBody(
669
+ input,
670
+ "modelRuntime.updateSlotConfig"
671
+ ),
672
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
673
+ });
674
+ }
675
+ };
676
+ }
677
+
678
+ export { MODEL_RUNTIME_FIELDS, createModelRuntimeClient };
679
+ //# sourceMappingURL=modelRuntimeClient.js.map
680
+ //# sourceMappingURL=modelRuntimeClient.js.map