@lucern/sdk 0.3.0-alpha.0 → 0.3.0-alpha.10

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