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

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 (227) hide show
  1. package/CHANGELOG.md +0 -8
  2. package/README.md +4 -110
  3. package/dist/adminClient.d.ts +8 -10
  4. package/dist/adminClient.js +39 -260
  5. package/dist/adminClient.js.map +1 -1
  6. package/dist/answersClient.d.ts +0 -2
  7. package/dist/answersClient.js +11 -239
  8. package/dist/answersClient.js.map +1 -1
  9. package/dist/audience/index.d.ts +1 -2
  10. package/dist/audience/index.js +3 -1
  11. package/dist/audience/index.js.map +1 -1
  12. package/dist/audiencesClient.d.ts +16 -18
  13. package/dist/audiencesClient.js +90 -315
  14. package/dist/audiencesClient.js.map +1 -1
  15. package/dist/auditClient.d.ts +0 -2
  16. package/dist/auditClient.js +15 -245
  17. package/dist/auditClient.js.map +1 -1
  18. package/dist/beliefs/index.d.ts +5 -27
  19. package/dist/beliefs/index.js +1177 -3842
  20. package/dist/beliefs/index.js.map +1 -1
  21. package/dist/beliefsClient.d.ts +2 -4
  22. package/dist/beliefsClient.js +26 -248
  23. package/dist/beliefsClient.js.map +1 -1
  24. package/dist/client-B6aWUUwp.d.ts +2552 -0
  25. package/dist/client.d.ts +27 -3041
  26. package/dist/client.js +1177 -3842
  27. package/dist/client.js.map +1 -1
  28. package/dist/contextClient.d.ts +3 -6
  29. package/dist/contextClient.js +30 -270
  30. package/dist/contextClient.js.map +1 -1
  31. package/dist/contextFacade.js +16 -25
  32. package/dist/contextFacade.js.map +1 -1
  33. package/dist/contextPackCompiler.js +30 -19
  34. package/dist/contextPackCompiler.js.map +1 -1
  35. package/dist/contextPackPolicy.js +17 -7
  36. package/dist/contextPackPolicy.js.map +1 -1
  37. package/dist/contextTypes.d.ts +0 -2
  38. package/dist/contracts/api-enums.contract.d.ts +2 -2
  39. package/dist/contracts/api-enums.contract.js +1 -6
  40. package/dist/contracts/api-enums.contract.js.map +1 -1
  41. package/dist/contracts/auth-session.contract.d.ts +1 -1
  42. package/dist/contracts/auth-session.contract.js +1 -13
  43. package/dist/contracts/auth-session.contract.js.map +1 -1
  44. package/dist/contracts/index.d.ts +0 -1
  45. package/dist/contracts/index.js +6 -133
  46. package/dist/contracts/index.js.map +1 -1
  47. package/dist/contracts/lens-filter.contract.js +3 -4
  48. package/dist/contracts/lens-filter.contract.js.map +1 -1
  49. package/dist/contracts/lens-workflow.contract.js +3 -4
  50. package/dist/contracts/lens-workflow.contract.js.map +1 -1
  51. package/dist/contracts/lensFilter.js +3 -4
  52. package/dist/contracts/lensFilter.js.map +1 -1
  53. package/dist/contracts/lensWorkflow.js +3 -4
  54. package/dist/contracts/lensWorkflow.js.map +1 -1
  55. package/dist/contracts/mcpTools.d.ts +1 -46
  56. package/dist/contracts/mcpTools.js +0 -108
  57. package/dist/contracts/mcpTools.js.map +1 -1
  58. package/dist/contradictions/index.d.ts +4 -26
  59. package/dist/contradictions/index.js +1177 -3842
  60. package/dist/contradictions/index.js.map +1 -1
  61. package/dist/coreClient.d.ts +2 -28
  62. package/dist/coreClient.js +14 -240
  63. package/dist/coreClient.js.map +1 -1
  64. package/dist/decisions/index.d.ts +14 -36
  65. package/dist/decisions/index.js +1177 -3842
  66. package/dist/decisions/index.js.map +1 -1
  67. package/dist/decisionsClient.d.ts +12 -6
  68. package/dist/decisionsClient.js +37 -253
  69. package/dist/decisionsClient.js.map +1 -1
  70. package/dist/edges/index.d.ts +87 -49
  71. package/dist/edges/index.js +1177 -3842
  72. package/dist/edges/index.js.map +1 -1
  73. package/dist/events.js +3 -6
  74. package/dist/events.js.map +1 -1
  75. package/dist/eventsCore.d.ts +1 -3
  76. package/dist/eventsCore.js +14 -240
  77. package/dist/eventsCore.js.map +1 -1
  78. package/dist/evidence/index.d.ts +4 -26
  79. package/dist/evidence/index.js +1177 -3842
  80. package/dist/evidence/index.js.map +1 -1
  81. package/dist/evidenceClient.d.ts +0 -2
  82. package/dist/evidenceClient.js +14 -240
  83. package/dist/evidenceClient.js.map +1 -1
  84. package/dist/facade/context.d.ts +1 -2
  85. package/dist/facade/context.js +16 -25
  86. package/dist/facade/context.js.map +1 -1
  87. package/dist/gatewayFacades.d.ts +46 -90
  88. package/dist/gatewayFacades.js +128 -609
  89. package/dist/gatewayFacades.js.map +1 -1
  90. package/dist/graphClient.d.ts +13 -8
  91. package/dist/graphClient.js +45 -262
  92. package/dist/graphClient.js.map +1 -1
  93. package/dist/harnessClient.d.ts +24 -15
  94. package/dist/harnessClient.js +42 -253
  95. package/dist/harnessClient.js.map +1 -1
  96. package/dist/identityClient.d.ts +11 -115
  97. package/dist/identityClient.js +33 -555
  98. package/dist/identityClient.js.map +1 -1
  99. package/dist/index.d.ts +6 -32
  100. package/dist/index.js +2580 -5825
  101. package/dist/index.js.map +1 -1
  102. package/dist/learningClient.d.ts +6 -8
  103. package/dist/learningClient.js +44 -270
  104. package/dist/learningClient.js.map +1 -1
  105. package/dist/lenses/index.d.ts +38 -78
  106. package/dist/lenses/index.js +1177 -3842
  107. package/dist/lenses/index.js.map +1 -1
  108. package/dist/nodes/index.d.ts +21 -65
  109. package/dist/nodes/index.js +1177 -3842
  110. package/dist/nodes/index.js.map +1 -1
  111. package/dist/ontologies/index.d.ts +32 -55
  112. package/dist/ontologies/index.js +1177 -3842
  113. package/dist/ontologies/index.js.map +1 -1
  114. package/dist/ontologyClient.d.ts +25 -19
  115. package/dist/ontologyClient.js +40 -276
  116. package/dist/ontologyClient.js.map +1 -1
  117. package/dist/packsClient.d.ts +23 -11
  118. package/dist/packsClient.js +46 -252
  119. package/dist/packsClient.js.map +1 -1
  120. package/dist/policyClient.d.ts +10 -13
  121. package/dist/policyClient.js +25 -261
  122. package/dist/policyClient.js.map +1 -1
  123. package/dist/questions/index.d.ts +4 -26
  124. package/dist/questions/index.js +1177 -3842
  125. package/dist/questions/index.js.map +1 -1
  126. package/dist/realtime/index.d.ts +1 -1
  127. package/dist/reportsClient.d.ts +7 -9
  128. package/dist/reportsClient.js +53 -299
  129. package/dist/reportsClient.js.map +1 -1
  130. package/dist/schemaClient.d.ts +3 -5
  131. package/dist/schemaClient.js +29 -253
  132. package/dist/schemaClient.js.map +1 -1
  133. package/dist/sdkSurface.d.ts +3 -8
  134. package/dist/sdkSurface.js +6 -10
  135. package/dist/sdkSurface.js.map +1 -1
  136. package/dist/sourcesClient.d.ts +0 -2
  137. package/dist/sourcesClient.js +14 -240
  138. package/dist/sourcesClient.js.map +1 -1
  139. package/dist/topics/index.d.ts +9 -37
  140. package/dist/topics/index.js +1177 -3844
  141. package/dist/topics/index.js.map +1 -1
  142. package/dist/topicsClient.d.ts +0 -4
  143. package/dist/topicsClient.js +24 -255
  144. package/dist/topicsClient.js.map +1 -1
  145. package/dist/types.d.ts +0 -17
  146. package/dist/version.d.ts +1 -1
  147. package/dist/version.js +1 -1
  148. package/dist/version.js.map +1 -1
  149. package/dist/workflowClient.d.ts +40 -60
  150. package/dist/workflowClient.js +58 -261
  151. package/dist/workflowClient.js.map +1 -1
  152. package/dist/worktrees/index.d.ts +33 -71
  153. package/dist/worktrees/index.js +1177 -3842
  154. package/dist/worktrees/index.js.map +1 -1
  155. package/package.json +3 -17
  156. package/dist/accessControl.d.ts +0 -79
  157. package/dist/accessControl.js +0 -1270
  158. package/dist/accessControl.js.map +0 -1
  159. package/dist/authContext.d.ts +0 -56
  160. package/dist/authContext.js +0 -170
  161. package/dist/authContext.js.map +0 -1
  162. package/dist/authDeviceClient.d.ts +0 -49
  163. package/dist/authDeviceClient.js +0 -121
  164. package/dist/authDeviceClient.js.map +0 -1
  165. package/dist/boundaryClientSurface.d.ts +0 -20
  166. package/dist/boundaryClientSurface.js +0 -73
  167. package/dist/boundaryClientSurface.js.map +0 -1
  168. package/dist/clientHelpers.d.ts +0 -48
  169. package/dist/clientHelpers.js +0 -137
  170. package/dist/clientHelpers.js.map +0 -1
  171. package/dist/control-plane.d.ts +0 -69
  172. package/dist/control-plane.js +0 -674
  173. package/dist/control-plane.js.map +0 -1
  174. package/dist/embeddingsClient.d.ts +0 -106
  175. package/dist/embeddingsClient.js +0 -749
  176. package/dist/embeddingsClient.js.map +0 -1
  177. package/dist/eventingClient.d.ts +0 -96
  178. package/dist/eventingClient.js +0 -746
  179. package/dist/eventingClient.js.map +0 -1
  180. package/dist/functionSurface.d.ts +0 -144
  181. package/dist/functionSurface.js +0 -1227
  182. package/dist/functionSurface.js.map +0 -1
  183. package/dist/functionSurfaceClient.d.ts +0 -8
  184. package/dist/functionSurfaceClient.js +0 -1227
  185. package/dist/functionSurfaceClient.js.map +0 -1
  186. package/dist/graphAnalysisClient.d.ts +0 -192
  187. package/dist/graphAnalysisClient.js +0 -817
  188. package/dist/graphAnalysisClient.js.map +0 -1
  189. package/dist/graphIntel.d.ts +0 -4
  190. package/dist/graphIntel.js +0 -3
  191. package/dist/graphIntel.js.map +0 -1
  192. package/dist/graphIntelligence.d.ts +0 -2
  193. package/dist/graphIntelligence.js +0 -47
  194. package/dist/graphIntelligence.js.map +0 -1
  195. package/dist/graphRecommendationsClient.d.ts +0 -56
  196. package/dist/graphRecommendationsClient.js +0 -682
  197. package/dist/graphRecommendationsClient.js.map +0 -1
  198. package/dist/graphStateClassifierClient.d.ts +0 -73
  199. package/dist/graphStateClassifierClient.js +0 -734
  200. package/dist/graphStateClassifierClient.js.map +0 -1
  201. package/dist/infisicalRuntime.d.ts +0 -43
  202. package/dist/infisicalRuntime.js +0 -346
  203. package/dist/infisicalRuntime.js.map +0 -1
  204. package/dist/jobsClient.d.ts +0 -98
  205. package/dist/jobsClient.js +0 -744
  206. package/dist/jobsClient.js.map +0 -1
  207. package/dist/mcpClient.d.ts +0 -28
  208. package/dist/mcpClient.js +0 -687
  209. package/dist/mcpClient.js.map +0 -1
  210. package/dist/modelRuntimeClient.d.ts +0 -72
  211. package/dist/modelRuntimeClient.js +0 -722
  212. package/dist/modelRuntimeClient.js.map +0 -1
  213. package/dist/ontologyLinksClient.d.ts +0 -71
  214. package/dist/ontologyLinksClient.js +0 -715
  215. package/dist/ontologyLinksClient.js.map +0 -1
  216. package/dist/orgGraphSearchClient.d.ts +0 -85
  217. package/dist/orgGraphSearchClient.js +0 -690
  218. package/dist/orgGraphSearchClient.js.map +0 -1
  219. package/dist/secrets.d.ts +0 -1
  220. package/dist/secrets.js +0 -3
  221. package/dist/secrets.js.map +0 -1
  222. package/dist/telemetryClient.d.ts +0 -94
  223. package/dist/telemetryClient.js +0 -759
  224. package/dist/telemetryClient.js.map +0 -1
  225. package/dist/toolRegistryClient.d.ts +0 -115
  226. package/dist/toolRegistryClient.js +0 -785
  227. package/dist/toolRegistryClient.js.map +0 -1
@@ -1,759 +0,0 @@
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 cleanHeaderValue(value) {
346
- const normalized = value?.trim();
347
- return normalized ? normalized : void 0;
348
- }
349
- function createGatewayRequestClient(config = {}) {
350
- const fetchImpl = config.fetchImpl ?? fetch;
351
- const baseUrl = config.baseUrl?.replace(/\/+$/, "") ?? "";
352
- const maxRetries = config.maxRetries ?? 2;
353
- const requestIdFactory = config.requestIdFactory ?? (() => generatePortableRequestId());
354
- async function resolveAuthHeaders() {
355
- const provided = config.getAuthHeaders ? await config.getAuthHeaders() : {};
356
- const headers = new Headers(provided);
357
- const setIfAbsent = (name, value) => {
358
- const normalized = cleanHeaderValue(value);
359
- if (normalized && !headers.has(name)) {
360
- headers.set(name, normalized);
361
- }
362
- };
363
- setIfAbsent("x-lucern-key", config.apiKey);
364
- setIfAbsent("x-lucern-session-token", config.userToken);
365
- setIfAbsent("x-lucern-environment", config.environment);
366
- setIfAbsent("x-lucern-clerk-id", config.clerkId);
367
- setIfAbsent("x-lucern-user-id", config.userId ?? config.clerkId);
368
- setIfAbsent("x-lucern-deployment-host", config.deploymentHost);
369
- const base = Object.fromEntries(headers.entries());
370
- const authContextInput = await resolveConfiguredAuthContext(
371
- config.authContext
372
- );
373
- if (!authContextInput && !config.requireCanonicalAuthContext) {
374
- return base;
375
- }
376
- const authContext = normalizeCanonicalLucernAuthContext(authContextInput);
377
- return mergeHeaderRecord(base, createCanonicalAuthHeaders(authContext));
378
- }
379
- async function fetchWithTimeout(url, init, timeoutMs) {
380
- const controller = new AbortController();
381
- const timer = setTimeout(() => controller.abort(), timeoutMs);
382
- try {
383
- return await fetchImpl(url, { ...init, signal: controller.signal });
384
- } catch (error) {
385
- if (controller.signal.aborted) {
386
- throw timeoutError(timeoutMs);
387
- }
388
- throw error;
389
- } finally {
390
- clearTimeout(timer);
391
- }
392
- }
393
- async function parsePayload(response) {
394
- const text = await response.text();
395
- if (!text) {
396
- return null;
397
- }
398
- const parsed = tryParseGatewayEnvelopeJson(text);
399
- if (!parsed.ok) {
400
- return null;
401
- }
402
- return isRecord(parsed.value) ? parsed.value : null;
403
- }
404
- function resolveTimeoutMs(method, requestTimeoutMs) {
405
- if (typeof requestTimeoutMs === "number") {
406
- return requestTimeoutMs;
407
- }
408
- const methodTimeoutMs = config.timeoutMsByMethod?.[method];
409
- if (typeof methodTimeoutMs === "number") {
410
- return methodTimeoutMs;
411
- }
412
- return config.timeoutMs ?? 15e3;
413
- }
414
- function tryParseGatewayEnvelopeJson(text) {
415
- const trimmed = text.trim();
416
- if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) {
417
- return { ok: false, reason: "non-json" };
418
- }
419
- try {
420
- return { ok: true, value: JSON.parse(trimmed) };
421
- } catch (error) {
422
- if (error instanceof SyntaxError) {
423
- return { ok: false, reason: "invalid-json", error };
424
- }
425
- throw error;
426
- }
427
- }
428
- function buildApiError(args) {
429
- const failure = args.failure;
430
- const legacyError = failure && isRecord(failure.error) ? failure.error : failure?.legacyError;
431
- const correlationId = failure?.correlationId ?? args.response.headers.get("x-lucern-correlation-id")?.trim() ?? args.requestId;
432
- const policyTraceId = failure?.policyTraceId ?? args.response.headers.get("x-lucern-policy-trace-id")?.trim() ?? null;
433
- const details = failure?.details ?? legacyError?.details;
434
- const policySummary = readPolicySummaryFromDetails(details);
435
- const failureMessage = typeof failure?.error === "string" ? failure.error : legacyError?.message;
436
- return new LucernApiError({
437
- code: failure?.code ?? legacyError?.code ?? fallbackErrorCode(args.response.status),
438
- message: policySummary ?? failureMessage ?? (args.response.ok ? "Platform API returned an invalid success payload." : "Platform API request failed."),
439
- status: args.response.status,
440
- invariant: failure?.invariant,
441
- suggestion: failure?.suggestion,
442
- details,
443
- requestId: args.requestId,
444
- correlationId,
445
- policyTraceId
446
- });
447
- }
448
- async function request(args) {
449
- const authHeaders = await resolveAuthHeaders();
450
- const method = args.method ?? "GET";
451
- const timeoutMs = resolveTimeoutMs(method, args.timeoutMs);
452
- const headers = new Headers({
453
- "content-type": "application/json",
454
- ...authHeaders
455
- });
456
- if (args.idempotencyKey) {
457
- headers.set("idempotency-key", args.idempotencyKey);
458
- }
459
- const requestId = headers.get("x-correlation-id")?.trim() || headers.get("x-request-id")?.trim() || args.requestId || requestIdFactory();
460
- if (!headers.has("x-correlation-id") && !headers.has("x-request-id")) {
461
- headers.set("x-correlation-id", requestId);
462
- }
463
- const url = `${baseUrl}${args.path}`;
464
- const serializedBody = args.body ? JSON.stringify(args.body) : void 0;
465
- const init = {
466
- method,
467
- headers,
468
- body: serializedBody
469
- };
470
- let lastError;
471
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
472
- const hookRequestContext = {
473
- requestId,
474
- attempt,
475
- maxRetries,
476
- method,
477
- path: args.path,
478
- url,
479
- headers: new Headers(headers),
480
- body: serializedBody,
481
- timeoutMs
482
- };
483
- await config.onRequest?.(hookRequestContext);
484
- const startedAt = Date.now();
485
- try {
486
- const response = await fetchWithTimeout(url, init, timeoutMs);
487
- const responseClone = response.clone();
488
- const payload = await parsePayload(response);
489
- const retryAfterMs = parseRetryAfterMs(
490
- response.headers.get("Retry-After")
491
- );
492
- if (!response.ok || !payload?.success) {
493
- const failure = payload && !payload.success ? payload : null;
494
- const apiError = buildApiError({
495
- requestId,
496
- response,
497
- failure
498
- });
499
- const willRetry = attempt < maxRetries && isRetryableStatus(response.status);
500
- await config.onResponse?.({
501
- ...hookRequestContext,
502
- durationMs: Date.now() - startedAt,
503
- status: response.status,
504
- response: responseClone,
505
- error: apiError,
506
- correlationId: apiError.correlationId ?? requestId,
507
- policyTraceId: apiError.policyTraceId ?? null,
508
- retryAfterMs,
509
- willRetry
510
- });
511
- if (willRetry) {
512
- lastError = apiError;
513
- await delay(
514
- computeRetryDelayMs({
515
- attempt,
516
- status: response.status,
517
- retryAfterMs
518
- })
519
- );
520
- continue;
521
- }
522
- throw apiError;
523
- }
524
- const successPayload = payload;
525
- await config.onResponse?.({
526
- ...hookRequestContext,
527
- durationMs: Date.now() - startedAt,
528
- status: response.status,
529
- response: responseClone,
530
- correlationId: successPayload.correlationId ?? response.headers.get("x-lucern-correlation-id")?.trim() ?? requestId,
531
- policyTraceId: successPayload.policyTraceId ?? response.headers.get("x-lucern-policy-trace-id")?.trim() ?? null,
532
- idempotentReplay: successPayload.idempotentReplay,
533
- retryAfterMs,
534
- willRetry: false
535
- });
536
- return successPayload;
537
- } catch (fetchError) {
538
- if (fetchError instanceof LucernApiError) {
539
- throw fetchError;
540
- }
541
- const willRetry = attempt < maxRetries;
542
- await config.onResponse?.({
543
- ...hookRequestContext,
544
- durationMs: Date.now() - startedAt,
545
- error: fetchError,
546
- correlationId: requestId,
547
- policyTraceId: null,
548
- willRetry
549
- });
550
- lastError = fetchError;
551
- if (willRetry) {
552
- await delay(computeRetryDelayMs({ attempt }));
553
- }
554
- }
555
- }
556
- throw lastError instanceof Error ? lastError : new Error("Platform API request failed after retries.");
557
- }
558
- return {
559
- request
560
- };
561
- }
562
-
563
- // src/sdkSurface.ts
564
- function createListResult(items, legacyKey) {
565
- const result = {
566
- items,
567
- total: items.length
568
- };
569
- {
570
- return {
571
- ...result,
572
- [legacyKey]: items
573
- };
574
- }
575
- }
576
- function mapGatewayData(response, mapper) {
577
- return {
578
- ...response,
579
- data: mapper(response.data)
580
- };
581
- }
582
-
583
- // src/boundaryClientSurface.ts
584
- function cleanOptionalString(value) {
585
- const normalized = value?.trim();
586
- return normalized ? normalized : void 0;
587
- }
588
- function isRecord2(value) {
589
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
590
- }
591
- function cleanRequiredString(value, label) {
592
- const normalized = cleanOptionalString(value);
593
- if (!normalized) {
594
- throw new Error(`${label} is required`);
595
- }
596
- return normalized;
597
- }
598
- function assertKnownKeys(input, allowed, operation) {
599
- const allowedSet = new Set(allowed);
600
- const unknownKeys = Object.keys(input).filter((key) => !allowedSet.has(key));
601
- if (unknownKeys.length > 0) {
602
- throw new Error(
603
- `${operation} received unsupported field(s): ${unknownKeys.join(", ")}`
604
- );
605
- }
606
- }
607
- function knownPayload(input, allowed, operation) {
608
- assertKnownKeys(input, allowed, operation);
609
- return { ...input };
610
- }
611
- function listResultFromEnvelope(data, legacyKey) {
612
- const record = isRecord2(data) ? data : {};
613
- const legacyItems = record[legacyKey];
614
- return createListResult(
615
- Array.isArray(legacyItems) ? legacyItems : Array.isArray(data) ? data : [],
616
- legacyKey
617
- );
618
- }
619
-
620
- // src/telemetryClient.ts
621
- var TELEMETRY_FIELDS = [
622
- "tenantId",
623
- "workspaceId",
624
- "principalId",
625
- "topicId",
626
- "worktreeId",
627
- "eventLevel",
628
- "eventType",
629
- "message",
630
- "toolName",
631
- "toolCalls",
632
- "decision",
633
- "policySubject",
634
- "policyAction",
635
- "policyResource",
636
- "runId",
637
- "runType",
638
- "status",
639
- "durationMs",
640
- "error",
641
- "metadata",
642
- "limit",
643
- "cursor"
644
- ];
645
- function query(input) {
646
- return {
647
- tenantId: cleanRequiredString(input.tenantId, "tenantId"),
648
- workspaceId: input.workspaceId,
649
- principalId: input.principalId,
650
- topicId: input.topicId,
651
- worktreeId: input.worktreeId,
652
- runType: input.runType,
653
- status: input.status,
654
- limit: input.limit,
655
- cursor: input.cursor
656
- };
657
- }
658
- function body(input, operation) {
659
- return knownPayload(input, TELEMETRY_FIELDS, operation);
660
- }
661
- function createTelemetryClient(config = {}) {
662
- const gateway = createGatewayRequestClient(config);
663
- return {
664
- logSystemEvent(input, idempotencyKey) {
665
- cleanRequiredString(input.tenantId, "tenantId");
666
- cleanRequiredString(input.eventType, "eventType");
667
- cleanRequiredString(input.message, "message");
668
- return gateway.request({
669
- path: "/api/platform/v1/telemetry/system-events",
670
- method: "POST",
671
- body: body(
672
- input,
673
- "telemetry.logSystemEvent"
674
- ),
675
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
676
- });
677
- },
678
- logToolCallsBatch(input, idempotencyKey) {
679
- cleanRequiredString(input.tenantId, "tenantId");
680
- return gateway.request({
681
- path: "/api/platform/v1/telemetry/tool-calls/batch",
682
- method: "POST",
683
- body: body(
684
- input,
685
- "telemetry.logToolCallsBatch"
686
- ),
687
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
688
- });
689
- },
690
- recordEpistemicAudit(input, idempotencyKey) {
691
- cleanRequiredString(input.tenantId, "tenantId");
692
- cleanRequiredString(input.eventType, "eventType");
693
- return gateway.request({
694
- path: "/api/platform/v1/telemetry/epistemic-audits",
695
- method: "POST",
696
- body: body(
697
- input,
698
- "telemetry.recordEpistemicAudit"
699
- ),
700
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
701
- });
702
- },
703
- recordPolicyDecision(input, idempotencyKey) {
704
- cleanRequiredString(input.tenantId, "tenantId");
705
- cleanRequiredString(input.decision, "decision");
706
- return gateway.request({
707
- path: "/api/platform/v1/telemetry/policy-decisions",
708
- method: "POST",
709
- body: body(
710
- input,
711
- "telemetry.recordPolicyDecision"
712
- ),
713
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
714
- });
715
- },
716
- startRun(input, idempotencyKey) {
717
- cleanRequiredString(input.tenantId, "tenantId");
718
- cleanRequiredString(input.runType, "runType");
719
- return gateway.request({
720
- path: "/api/platform/v1/telemetry/runs/start",
721
- method: "POST",
722
- body: body(
723
- input,
724
- "telemetry.startRun"
725
- ),
726
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
727
- });
728
- },
729
- finishRun(input, idempotencyKey) {
730
- cleanRequiredString(input.tenantId, "tenantId");
731
- cleanRequiredString(input.runId, "runId");
732
- return gateway.request({
733
- path: `/api/platform/v1/telemetry/runs/${encodeURIComponent(
734
- input.runId
735
- )}/finish`,
736
- method: "POST",
737
- body: body(
738
- input,
739
- "telemetry.finishRun"
740
- ),
741
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
742
- });
743
- },
744
- listRuns(input) {
745
- return gateway.request({
746
- path: `/api/platform/v1/telemetry/runs${toQueryString(query(input))}`
747
- }).then(
748
- (response) => mapGatewayData(
749
- response,
750
- (data) => listResultFromEnvelope(data, "runs")
751
- )
752
- );
753
- }
754
- };
755
- }
756
-
757
- export { TELEMETRY_FIELDS, createTelemetryClient };
758
- //# sourceMappingURL=telemetryClient.js.map
759
- //# sourceMappingURL=telemetryClient.js.map