@lucern/sdk 0.2.0-alpha.7 → 0.2.0-alpha.8

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 (257) hide show
  1. package/dist/adminClient.d.ts +409 -0
  2. package/dist/adminClient.js +755 -0
  3. package/dist/adminClient.js.map +1 -0
  4. package/dist/answersClient.d.ts +23 -0
  5. package/dist/answersClient.js +333 -0
  6. package/dist/answersClient.js.map +1 -0
  7. package/dist/audiencesClient.d.ts +99 -0
  8. package/dist/audiencesClient.js +472 -0
  9. package/dist/audiencesClient.js.map +1 -0
  10. package/dist/auditClient.d.ts +29 -0
  11. package/dist/auditClient.js +386 -0
  12. package/dist/auditClient.js.map +1 -0
  13. package/dist/beliefsClient.d.ts +162 -0
  14. package/dist/beliefsClient.js +477 -0
  15. package/dist/beliefsClient.js.map +1 -0
  16. package/dist/client.d.ts +2378 -0
  17. package/dist/client.js +6134 -0
  18. package/dist/client.js.map +1 -0
  19. package/dist/contextClient.d.ts +27 -0
  20. package/dist/contextClient.js +396 -0
  21. package/dist/contextClient.js.map +1 -0
  22. package/dist/contextFacade.d.ts +2 -0
  23. package/dist/contextFacade.js +73 -0
  24. package/dist/contextFacade.js.map +1 -0
  25. package/dist/contextPackCompiler.d.ts +102 -0
  26. package/dist/contextPackCompiler.js +1091 -0
  27. package/dist/contextPackCompiler.js.map +1 -0
  28. package/dist/contextPackPolicy.d.ts +84 -0
  29. package/dist/contextPackPolicy.js +347 -0
  30. package/dist/contextPackPolicy.js.map +1 -0
  31. package/dist/contextPackSchema.d.ts +7 -0
  32. package/{src/contextPackSchema.ts → dist/contextPackSchema.js} +22 -70
  33. package/dist/contextPackSchema.js.map +1 -0
  34. package/dist/contextTypes.d.ts +135 -0
  35. package/dist/contextTypes.js +3 -0
  36. package/dist/contextTypes.js.map +1 -0
  37. package/dist/contracts/api-enums.contract.d.ts +81 -0
  38. package/dist/contracts/api-enums.contract.js +92 -0
  39. package/dist/contracts/api-enums.contract.js.map +1 -0
  40. package/dist/contracts/auth-session.contract.d.ts +55 -0
  41. package/dist/contracts/auth-session.contract.js +48 -0
  42. package/dist/contracts/auth-session.contract.js.map +1 -0
  43. package/dist/contracts/context-pack.contract.d.ts +492 -0
  44. package/dist/contracts/context-pack.contract.js +98 -0
  45. package/dist/contracts/context-pack.contract.js.map +1 -0
  46. package/dist/contracts/contextPack.d.ts +1 -0
  47. package/dist/contracts/contextPack.js +98 -0
  48. package/dist/contracts/contextPack.js.map +1 -0
  49. package/dist/contracts/index.d.ts +9 -0
  50. package/dist/contracts/index.js +4892 -0
  51. package/dist/contracts/index.js.map +1 -0
  52. package/dist/contracts/lens-filter.contract.d.ts +72 -0
  53. package/dist/contracts/lens-filter.contract.js +71 -0
  54. package/dist/contracts/lens-filter.contract.js.map +1 -0
  55. package/dist/contracts/lens-workflow.contract.d.ts +87 -0
  56. package/dist/contracts/lens-workflow.contract.js +123 -0
  57. package/dist/contracts/lens-workflow.contract.js.map +1 -0
  58. package/dist/contracts/lensFilter.d.ts +1 -0
  59. package/dist/contracts/lensFilter.js +71 -0
  60. package/dist/contracts/lensFilter.js.map +1 -0
  61. package/dist/contracts/lensWorkflow.d.ts +2 -0
  62. package/dist/contracts/lensWorkflow.js +123 -0
  63. package/dist/contracts/lensWorkflow.js.map +1 -0
  64. package/dist/contracts/mcp-tools.contract.d.ts +1 -0
  65. package/dist/contracts/mcp-tools.contract.js +2986 -0
  66. package/dist/contracts/mcp-tools.contract.js.map +1 -0
  67. package/dist/contracts/mcpTools.d.ts +1 -0
  68. package/dist/contracts/mcpTools.js +2986 -0
  69. package/dist/contracts/mcpTools.js.map +1 -0
  70. package/dist/contracts/prompt.contract.d.ts +26 -0
  71. package/dist/contracts/prompt.contract.js +12 -0
  72. package/dist/contracts/prompt.contract.js.map +1 -0
  73. package/dist/contracts/prompt.d.ts +1 -0
  74. package/dist/contracts/prompt.js +12 -0
  75. package/dist/contracts/prompt.js.map +1 -0
  76. package/dist/contracts/sdk-tools.contract.d.ts +2 -0
  77. package/dist/contracts/sdk-tools.contract.js +4134 -0
  78. package/dist/contracts/sdk-tools.contract.js.map +1 -0
  79. package/dist/contracts/sdkTools.d.ts +2 -0
  80. package/dist/contracts/sdkTools.js +4134 -0
  81. package/dist/contracts/sdkTools.js.map +1 -0
  82. package/dist/contracts/workflow-runtime.contract.d.ts +163 -0
  83. package/dist/contracts/workflow-runtime.contract.js +245 -0
  84. package/dist/contracts/workflow-runtime.contract.js.map +1 -0
  85. package/dist/contracts/workflowRuntime.d.ts +1 -0
  86. package/dist/contracts/workflowRuntime.js +245 -0
  87. package/dist/contracts/workflowRuntime.js.map +1 -0
  88. package/dist/controlObjectOwnership.d.ts +310 -0
  89. package/{src/controlObjectOwnership.ts → dist/controlObjectOwnership.js} +53 -124
  90. package/dist/controlObjectOwnership.js.map +1 -0
  91. package/dist/coreClient.d.ts +144 -0
  92. package/dist/coreClient.js +339 -0
  93. package/dist/coreClient.js.map +1 -0
  94. package/dist/customTools.d.ts +88 -0
  95. package/dist/customTools.js +248 -0
  96. package/dist/customTools.js.map +1 -0
  97. package/dist/decisionsClient.d.ts +111 -0
  98. package/dist/decisionsClient.js +522 -0
  99. package/dist/decisionsClient.js.map +1 -0
  100. package/dist/domainContext.d.ts +1 -0
  101. package/dist/domainContext.js +3 -0
  102. package/dist/domainContext.js.map +1 -0
  103. package/dist/events.d.ts +178 -0
  104. package/dist/events.js +249 -0
  105. package/dist/events.js.map +1 -0
  106. package/dist/eventsCore.d.ts +49 -0
  107. package/dist/eventsCore.js +429 -0
  108. package/dist/eventsCore.js.map +1 -0
  109. package/dist/facade/context.d.ts +18 -0
  110. package/dist/facade/context.js +73 -0
  111. package/dist/facade/context.js.map +1 -0
  112. package/dist/gatewayFacades.d.ts +591 -0
  113. package/dist/gatewayFacades.js +1953 -0
  114. package/dist/gatewayFacades.js.map +1 -0
  115. package/dist/graphClient.d.ts +271 -0
  116. package/dist/graphClient.js +698 -0
  117. package/dist/graphClient.js.map +1 -0
  118. package/dist/harnessClient.d.ts +314 -0
  119. package/dist/harnessClient.js +607 -0
  120. package/dist/harnessClient.js.map +1 -0
  121. package/dist/identityClient.d.ts +140 -0
  122. package/dist/identityClient.js +497 -0
  123. package/dist/identityClient.js.map +1 -0
  124. package/dist/index.d.ts +42 -0
  125. package/dist/index.js +11381 -0
  126. package/dist/index.js.map +1 -0
  127. package/dist/learningClient.d.ts +46 -0
  128. package/dist/learningClient.js +409 -0
  129. package/dist/learningClient.js.map +1 -0
  130. package/dist/mcpParityClient.d.ts +74 -0
  131. package/dist/mcpParityClient.js +516 -0
  132. package/dist/mcpParityClient.js.map +1 -0
  133. package/dist/mcpParitySurface.d.ts +12 -0
  134. package/{src/mcpParitySurface.ts → dist/mcpParitySurface.js} +9 -14
  135. package/dist/mcpParitySurface.js.map +1 -0
  136. package/dist/mcpTools-DPZxowDX.d.ts +254 -0
  137. package/dist/ontologyClient.d.ts +137 -0
  138. package/dist/ontologyClient.js +513 -0
  139. package/dist/ontologyClient.js.map +1 -0
  140. package/dist/packRuntime.d.ts +2 -0
  141. package/dist/packRuntime.js +3 -0
  142. package/dist/packRuntime.js.map +1 -0
  143. package/dist/packsClient.d.ts +131 -0
  144. package/dist/packsClient.js +525 -0
  145. package/dist/packsClient.js.map +1 -0
  146. package/dist/policyClient.d.ts +299 -0
  147. package/dist/policyClient.js +625 -0
  148. package/dist/policyClient.js.map +1 -0
  149. package/dist/realtime/index.d.ts +29 -0
  150. package/dist/realtime/index.js +23 -0
  151. package/dist/realtime/index.js.map +1 -0
  152. package/{src/realtime/refs.ts → dist/realtime/refs.d.ts} +5 -5
  153. package/dist/realtime/refs.js +9 -0
  154. package/dist/realtime/refs.js.map +1 -0
  155. package/dist/reportsClient.d.ts +41 -0
  156. package/dist/reportsClient.js +418 -0
  157. package/dist/reportsClient.js.map +1 -0
  158. package/dist/schemaClient.d.ts +64 -0
  159. package/dist/schemaClient.js +434 -0
  160. package/dist/schemaClient.js.map +1 -0
  161. package/dist/sdkSurface.d.ts +61 -0
  162. package/dist/sdkSurface.js +112 -0
  163. package/dist/sdkSurface.js.map +1 -0
  164. package/dist/sdkTools-CwXJDACb.d.ts +150 -0
  165. package/dist/topicsClient.d.ts +84 -0
  166. package/dist/topicsClient.js +492 -0
  167. package/dist/topicsClient.js.map +1 -0
  168. package/dist/types.d.ts +696 -0
  169. package/dist/types.js +3 -0
  170. package/dist/types.js.map +1 -0
  171. package/dist/version.d.ts +4 -0
  172. package/dist/version.js +6 -0
  173. package/dist/version.js.map +1 -0
  174. package/dist/workflowClient.d.ts +316 -0
  175. package/dist/workflowClient.js +830 -0
  176. package/dist/workflowClient.js.map +1 -0
  177. package/package.json +31 -7
  178. package/.turbo/turbo-build.log +0 -7
  179. package/.turbo/turbo-typecheck.log +0 -4
  180. package/examples/README.md +0 -69
  181. package/examples/contradiction.ts +0 -94
  182. package/examples/investigation-context.ts +0 -118
  183. package/examples/questions-and-tasks.ts +0 -55
  184. package/examples/quickstart.ts +0 -97
  185. package/examples/shared.ts +0 -318
  186. package/examples/strict-public-types.ts +0 -143
  187. package/examples/worktree-lifecycle.ts +0 -79
  188. package/src/README.md +0 -6
  189. package/src/adminClient.ts +0 -789
  190. package/src/answersClient.ts +0 -29
  191. package/src/audiencesClient.ts +0 -209
  192. package/src/auditClient.ts +0 -50
  193. package/src/beliefsClient.ts +0 -319
  194. package/src/client.ts +0 -2647
  195. package/src/contextClient.ts +0 -130
  196. package/src/contextFacade.ts +0 -15
  197. package/src/contextPackCompiler.ts +0 -828
  198. package/src/contextTypes.ts +0 -153
  199. package/src/contracts/api-enums.contract.ts +0 -202
  200. package/src/contracts/auth-session.contract.ts +0 -109
  201. package/src/contracts/context-pack.contract.ts +0 -700
  202. package/src/contracts/contextPack.ts +0 -1
  203. package/src/contracts/index.ts +0 -10
  204. package/src/contracts/lens-filter.contract.ts +0 -183
  205. package/src/contracts/lens-workflow.contract.ts +0 -162
  206. package/src/contracts/lensFilter.ts +0 -1
  207. package/src/contracts/lensWorkflow.ts +0 -1
  208. package/src/contracts/mcp-tools.contract.ts +0 -3636
  209. package/src/contracts/mcpTools.ts +0 -1
  210. package/src/contracts/prompt.contract.ts +0 -50
  211. package/src/contracts/prompt.ts +0 -1
  212. package/src/contracts/sdk-tools.contract.ts +0 -1457
  213. package/src/contracts/sdkTools.ts +0 -1
  214. package/src/contracts/workflow-runtime.contract.ts +0 -440
  215. package/src/contracts/workflowRuntime.ts +0 -1
  216. package/src/coreClient.ts +0 -570
  217. package/src/customTools.ts +0 -398
  218. package/src/decisionsClient.ts +0 -286
  219. package/src/domainContext.ts +0 -15
  220. package/src/events.ts +0 -531
  221. package/src/eventsCore.ts +0 -168
  222. package/src/facade/beliefs.ts +0 -83
  223. package/src/facade/context.ts +0 -110
  224. package/src/facade/contradictions.ts +0 -29
  225. package/src/facade/edges.ts +0 -30
  226. package/src/facade/events.ts +0 -23
  227. package/src/facade/evidence.ts +0 -41
  228. package/src/facade/graph.ts +0 -38
  229. package/src/facade/identity.ts +0 -16
  230. package/src/facade/ontologies.ts +0 -34
  231. package/src/facade/questions.ts +0 -59
  232. package/src/facade/search.ts +0 -16
  233. package/src/facade/tasks.ts +0 -37
  234. package/src/facade/topics.ts +0 -42
  235. package/src/facade/webhooks.ts +0 -58
  236. package/src/facade/worktrees.ts +0 -51
  237. package/src/gatewayFacades.ts +0 -1666
  238. package/src/graphClient.ts +0 -529
  239. package/src/harnessClient.ts +0 -585
  240. package/src/identityClient.ts +0 -278
  241. package/src/index.ts +0 -49
  242. package/src/learningClient.ts +0 -95
  243. package/src/mcpParityClient.ts +0 -240
  244. package/src/ontologyClient.ts +0 -275
  245. package/src/packRuntime.ts +0 -3
  246. package/src/packsClient.ts +0 -260
  247. package/src/policyClient.ts +0 -572
  248. package/src/promptCatalog.ts +0 -1
  249. package/src/realtime/index.ts +0 -51
  250. package/src/reportsClient.ts +0 -99
  251. package/src/schemaClient.ts +0 -129
  252. package/src/sdkSurface.ts +0 -190
  253. package/src/topicsClient.ts +0 -243
  254. package/src/types.ts +0 -807
  255. package/src/version.ts +0 -2
  256. package/src/workflowClient.ts +0 -826
  257. package/tsconfig.json +0 -9
package/src/coreClient.ts DELETED
@@ -1,570 +0,0 @@
1
- import type { JsonObject, JsonValue } from "./types";
2
-
3
- /** Tenant and workspace identifiers used to scope gateway requests. */
4
- export type GatewayScope = {
5
- tenantId?: string;
6
- workspaceId?: string;
7
- };
8
-
9
- /** Successful response envelope from the platform gateway with correlation metadata. */
10
- export type PlatformGatewaySuccess<T> = {
11
- success: true;
12
- data: T;
13
- correlationId: string;
14
- policyTraceId: string | null;
15
- idempotentReplay: boolean;
16
- };
17
-
18
- /** Failed response envelope with structured error codes and optional invariant references. */
19
- export type PlatformGatewayFailure = {
20
- success: false;
21
- /**
22
- * Error string is the canonical envelope field.
23
- * Object form is legacy-only compatibility for older gateway responses.
24
- */
25
- error:
26
- | string
27
- | {
28
- code: string;
29
- message: string;
30
- details?: JsonValue;
31
- };
32
- code?: string;
33
- invariant?: string | null;
34
- suggestion?: string | null;
35
- details?: JsonValue;
36
- legacyError?: {
37
- code: string;
38
- message: string;
39
- details?: JsonValue;
40
- };
41
- correlationId: string;
42
- policyTraceId: string | null;
43
- };
44
-
45
- /** Discriminated union of success and failure gateway responses. */
46
- export type PlatformGatewayEnvelope<T> =
47
- | PlatformGatewaySuccess<T>
48
- | PlatformGatewayFailure;
49
-
50
- /**
51
- * Structured error thrown when a platform API request fails.
52
- *
53
- * Includes HTTP status, machine-readable error code, optional invariant
54
- * reference, and actionable suggestions for common failure modes.
55
- */
56
- export class LucernApiError extends Error {
57
- public readonly code: string;
58
- public readonly status: number;
59
- public readonly invariant?: string | null;
60
- public readonly suggestion?: string | null;
61
- public readonly details?: JsonValue;
62
- public readonly requestId?: string;
63
- public readonly correlationId?: string;
64
- public readonly policyTraceId?: string | null;
65
-
66
- constructor(args: {
67
- code: string;
68
- message: string;
69
- status: number;
70
- invariant?: string | null;
71
- suggestion?: string | null;
72
- details?: JsonValue;
73
- requestId?: string;
74
- correlationId?: string;
75
- policyTraceId?: string | null;
76
- }) {
77
- super(args.message);
78
- this.name = "LucernApiError";
79
- this.code = args.code;
80
- this.status = args.status;
81
- this.invariant = args.invariant;
82
- this.suggestion = args.suggestion;
83
- this.details = args.details;
84
- this.requestId = args.requestId;
85
- this.correlationId = args.correlationId;
86
- this.policyTraceId = args.policyTraceId;
87
- }
88
- }
89
-
90
- /** Supported HTTP methods for gateway requests. */
91
- export type GatewayHttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
92
-
93
- type FetchLike = (
94
- input: RequestInfo | URL,
95
- init?: RequestInit
96
- ) => Promise<Response>;
97
-
98
- /** Context passed to the `onRequest` hook before each gateway request attempt. */
99
- export type GatewayRequestHookContext = {
100
- requestId: string;
101
- attempt: number;
102
- maxRetries: number;
103
- method: GatewayHttpMethod;
104
- path: string;
105
- url: string;
106
- headers: Headers;
107
- body?: string;
108
- timeoutMs: number;
109
- };
110
-
111
- /** Context passed to the `onResponse` hook after each gateway request attempt (including retries and failures). */
112
- export type GatewayResponseHookContext = GatewayRequestHookContext & {
113
- durationMs: number;
114
- status?: number;
115
- response?: Response;
116
- error?: unknown;
117
- correlationId?: string;
118
- policyTraceId?: string | null;
119
- idempotentReplay?: boolean;
120
- retryAfterMs?: number | null;
121
- willRetry: boolean;
122
- };
123
-
124
- /**
125
- * Low-level transport configuration for the platform gateway client.
126
- *
127
- * Most developers should use {@link createLucernClient} instead, which wraps
128
- * this config with higher-level conveniences like `apiKey` and `environment`.
129
- */
130
- export type GatewayClientConfig = {
131
- baseUrl?: string;
132
- fetchImpl?: FetchLike;
133
- getAuthHeaders?:
134
- | (() => Promise<Record<string, string>>)
135
- | (() => Record<string, string>);
136
- /** Max retries for transient errors (5xx, network). Defaults to 2. */
137
- maxRetries?: number;
138
- /** Request timeout in ms. Defaults to 15000. */
139
- timeoutMs?: number;
140
- /** Optional timeout overrides by HTTP method. */
141
- timeoutMsByMethod?: Partial<Record<GatewayHttpMethod, number>>;
142
- /** Optional request ID factory used for correlation headers. */
143
- requestIdFactory?: () => string;
144
- /** Invoked before each request attempt, including retries. */
145
- onRequest?:
146
- | ((context: GatewayRequestHookContext) => void)
147
- | ((context: GatewayRequestHookContext) => Promise<void>);
148
- /** Invoked after each request attempt, including retries and failures. */
149
- onResponse?:
150
- | ((context: GatewayResponseHookContext) => void)
151
- | ((context: GatewayResponseHookContext) => Promise<void>);
152
- };
153
-
154
- /**
155
- * Serialize a gateway query object into a URL query string.
156
- */
157
- export function toQueryString(
158
- scope: GatewayScope & Record<string, string | number | boolean | undefined>
159
- ): string {
160
- const params = new URLSearchParams();
161
- if (scope.tenantId) {
162
- params.set("tenantId", scope.tenantId);
163
- }
164
- if (scope.workspaceId) {
165
- params.set("workspaceId", scope.workspaceId);
166
- }
167
- for (const [key, value] of Object.entries(scope)) {
168
- if (key === "tenantId" || key === "workspaceId") {
169
- continue;
170
- }
171
- if (value === undefined) {
172
- continue;
173
- }
174
- params.set(key, String(value));
175
- }
176
- const serialized = params.toString();
177
- return serialized.length > 0 ? `?${serialized}` : "";
178
- }
179
-
180
- function fillRandomBytes(length: number): Uint8Array {
181
- const bytes = new Uint8Array(length);
182
- if (typeof globalThis.crypto?.getRandomValues === "function") {
183
- globalThis.crypto.getRandomValues(bytes);
184
- return bytes;
185
- }
186
-
187
- for (let index = 0; index < length; index += 1) {
188
- bytes[index] = Math.floor(Math.random() * 256);
189
- }
190
- return bytes;
191
- }
192
-
193
- function generatePortableRequestId(): string {
194
- if (typeof globalThis.crypto?.randomUUID === "function") {
195
- return globalThis.crypto.randomUUID();
196
- }
197
-
198
- const bytes = fillRandomBytes(16);
199
- bytes[6] = (bytes[6] & 0x0f) | 0x40;
200
- bytes[8] = (bytes[8] & 0x3f) | 0x80;
201
- const hex = Array.from(bytes, (value) => value.toString(16).padStart(2, "0"));
202
- return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(
203
- 6,
204
- 8
205
- ).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
206
- }
207
-
208
- /**
209
- * Generate a random idempotency key for retry-safe writes.
210
- */
211
- export function randomIdempotencyKey(): string {
212
- return generatePortableRequestId();
213
- }
214
-
215
- function isRetryableStatus(status: number): boolean {
216
- return status >= 500 || status === 408 || status === 429;
217
- }
218
-
219
- function fallbackErrorCode(status: number): string {
220
- if (status === 401) {
221
- return "AUTHENTICATION_REQUIRED";
222
- }
223
- if (status === 403) {
224
- return "FORBIDDEN";
225
- }
226
- if (status === 404) {
227
- return "NOT_FOUND";
228
- }
229
- if (status === 408) {
230
- return "UPSTREAM_ERROR";
231
- }
232
- if (status === 409) {
233
- return "CONFLICT";
234
- }
235
- if (status === 429) {
236
- return "RATE_LIMIT_EXCEEDED";
237
- }
238
- if (status >= 500) {
239
- return "UPSTREAM_ERROR";
240
- }
241
- return "INTERNAL_ERROR";
242
- }
243
-
244
- function delay(ms: number): Promise<void> {
245
- return new Promise((resolve) => setTimeout(resolve, ms));
246
- }
247
-
248
- function parseRetryAfterMs(value: string | null): number | null {
249
- if (!value) {
250
- return null;
251
- }
252
- const trimmed = value.trim();
253
- if (!trimmed) {
254
- return null;
255
- }
256
- const numeric = Number(trimmed);
257
- if (Number.isFinite(numeric)) {
258
- return Math.max(0, Math.round(numeric * 1000));
259
- }
260
- const parsedDate = Date.parse(trimmed);
261
- if (Number.isFinite(parsedDate)) {
262
- return Math.max(0, parsedDate - Date.now());
263
- }
264
- return null;
265
- }
266
-
267
- function computeRetryDelayMs(args: {
268
- attempt: number;
269
- status?: number;
270
- retryAfterMs?: number | null;
271
- }): number {
272
- const baseDelay =
273
- args.status === 429
274
- ? Math.max(
275
- args.retryAfterMs ?? 0,
276
- Math.min(1000 * 2 ** args.attempt, 10_000)
277
- )
278
- : Math.min(1000 * 2 ** args.attempt, 4000);
279
-
280
- if (args.status !== 429) {
281
- return baseDelay;
282
- }
283
-
284
- const jitterWindow = Math.max(250, Math.round(baseDelay * 0.25));
285
- return baseDelay + Math.round(Math.random() * jitterWindow);
286
- }
287
-
288
- function timeoutError(timeoutMs: number): Error {
289
- const error = new Error(`Request timed out after ${timeoutMs}ms`);
290
- error.name = "AbortError";
291
- return error;
292
- }
293
-
294
- function readPolicySummaryFromDetails(details?: JsonValue): string | null {
295
- if (!details || typeof details !== "object" || Array.isArray(details)) {
296
- return null;
297
- }
298
-
299
- const directSummary = (details as { summary?: JsonValue }).summary;
300
- if (typeof directSummary === "string" && directSummary.trim().length > 0) {
301
- return directSummary.trim();
302
- }
303
-
304
- const policy = (details as { policy?: JsonValue }).policy;
305
- if (!policy || typeof policy !== "object" || Array.isArray(policy)) {
306
- return null;
307
- }
308
-
309
- const explanation = (policy as { explanation?: JsonValue }).explanation;
310
- if (!explanation || typeof explanation !== "object" || Array.isArray(explanation)) {
311
- return null;
312
- }
313
-
314
- const nestedSummary = (explanation as { summary?: JsonValue }).summary;
315
- if (typeof nestedSummary === "string" && nestedSummary.trim().length > 0) {
316
- return nestedSummary.trim();
317
- }
318
-
319
- return null;
320
- }
321
-
322
- /**
323
- * Create the transport client used by all SDK modules.
324
- */
325
- export function createGatewayRequestClient(config: GatewayClientConfig = {}) {
326
- const fetchImpl = config.fetchImpl ?? fetch;
327
- const baseUrl = config.baseUrl?.replace(/\/+$/, "") ?? "";
328
- const maxRetries = config.maxRetries ?? 2;
329
- const requestIdFactory = config.requestIdFactory ?? (() => generatePortableRequestId());
330
-
331
- async function resolveAuthHeaders(): Promise<Record<string, string>> {
332
- if (!config.getAuthHeaders) {
333
- return {};
334
- }
335
- return await config.getAuthHeaders();
336
- }
337
-
338
- async function fetchWithTimeout(
339
- url: string,
340
- init: RequestInit,
341
- timeoutMs: number
342
- ): Promise<Response> {
343
- const controller = new AbortController();
344
- const timer = setTimeout(() => controller.abort(), timeoutMs);
345
- try {
346
- return await fetchImpl(url, { ...init, signal: controller.signal });
347
- } catch (error) {
348
- if (controller.signal.aborted) {
349
- throw timeoutError(timeoutMs);
350
- }
351
- throw error;
352
- } finally {
353
- clearTimeout(timer);
354
- }
355
- }
356
-
357
- async function parsePayload<T>(
358
- response: Response
359
- ): Promise<PlatformGatewayEnvelope<T> | null> {
360
- const text = await response.text();
361
- if (!text) {
362
- return null;
363
- }
364
- try {
365
- return JSON.parse(text) as PlatformGatewayEnvelope<T>;
366
- } catch {
367
- return null;
368
- }
369
- }
370
-
371
- function resolveTimeoutMs(
372
- method: GatewayHttpMethod,
373
- requestTimeoutMs?: number
374
- ): number {
375
- if (typeof requestTimeoutMs === "number") {
376
- return requestTimeoutMs;
377
- }
378
- const methodTimeoutMs = config.timeoutMsByMethod?.[method];
379
- if (typeof methodTimeoutMs === "number") {
380
- return methodTimeoutMs;
381
- }
382
- return config.timeoutMs ?? 15_000;
383
- }
384
-
385
- function buildApiError(args: {
386
- requestId: string;
387
- response: Response;
388
- failure?: PlatformGatewayFailure | null;
389
- }): LucernApiError {
390
- const failure = args.failure;
391
- const legacyError =
392
- failure && typeof failure.error === "object" && failure.error !== null
393
- ? failure.error
394
- : failure?.legacyError;
395
- const correlationId =
396
- failure?.correlationId ??
397
- args.response.headers.get("x-lucern-correlation-id")?.trim() ??
398
- args.requestId;
399
- const policyTraceId =
400
- failure?.policyTraceId ??
401
- args.response.headers.get("x-lucern-policy-trace-id")?.trim() ??
402
- null;
403
- const details = failure?.details ?? legacyError?.details;
404
- const policySummary = readPolicySummaryFromDetails(details);
405
-
406
- return new LucernApiError({
407
- code: failure?.code ?? legacyError?.code ?? fallbackErrorCode(args.response.status),
408
- message:
409
- policySummary ??
410
- (typeof failure?.error === "string"
411
- ? failure.error
412
- : legacyError?.message ??
413
- (args.response.ok
414
- ? "Platform API returned an invalid success payload."
415
- : "Platform API request failed.")),
416
- status: args.response.status,
417
- invariant: failure?.invariant,
418
- suggestion: failure?.suggestion,
419
- details,
420
- requestId: args.requestId,
421
- correlationId,
422
- policyTraceId,
423
- });
424
- }
425
-
426
- async function request<T>(args: {
427
- path: string;
428
- method?: GatewayHttpMethod;
429
- body?: JsonObject;
430
- idempotencyKey?: string;
431
- requestId?: string;
432
- timeoutMs?: number;
433
- }): Promise<PlatformGatewaySuccess<T>> {
434
- const authHeaders = await resolveAuthHeaders();
435
- const method = args.method ?? "GET";
436
- const timeoutMs = resolveTimeoutMs(method, args.timeoutMs);
437
- const headers = new Headers({
438
- "content-type": "application/json",
439
- ...authHeaders,
440
- });
441
- if (args.idempotencyKey) {
442
- headers.set("idempotency-key", args.idempotencyKey);
443
- }
444
- const requestId =
445
- headers.get("x-correlation-id")?.trim() ||
446
- headers.get("x-request-id")?.trim() ||
447
- args.requestId ||
448
- requestIdFactory();
449
- if (!headers.has("x-correlation-id") && !headers.has("x-request-id")) {
450
- headers.set("x-correlation-id", requestId);
451
- }
452
-
453
- const url = `${baseUrl}${args.path}`;
454
- const serializedBody = args.body ? JSON.stringify(args.body) : undefined;
455
- const init: RequestInit = {
456
- method,
457
- headers,
458
- body: serializedBody,
459
- };
460
-
461
- let lastError: unknown;
462
-
463
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
464
- const hookRequestContext: GatewayRequestHookContext = {
465
- requestId,
466
- attempt,
467
- maxRetries,
468
- method,
469
- path: args.path,
470
- url,
471
- headers: new Headers(headers),
472
- body: serializedBody,
473
- timeoutMs,
474
- };
475
- await config.onRequest?.(hookRequestContext);
476
- const startedAt = Date.now();
477
- try {
478
- const response = await fetchWithTimeout(url, init, timeoutMs);
479
- const responseClone = response.clone();
480
- const payload = await parsePayload<T>(response);
481
- const retryAfterMs = parseRetryAfterMs(
482
- response.headers.get("Retry-After")
483
- );
484
-
485
- if (!response.ok || !payload?.success) {
486
- const failure =
487
- payload && !payload.success ? (payload as PlatformGatewayFailure) : null;
488
- const apiError = buildApiError({
489
- requestId,
490
- response,
491
- failure,
492
- });
493
- const willRetry = attempt < maxRetries && isRetryableStatus(response.status);
494
-
495
- await config.onResponse?.({
496
- ...hookRequestContext,
497
- durationMs: Date.now() - startedAt,
498
- status: response.status,
499
- response: responseClone,
500
- error: apiError,
501
- correlationId: apiError.correlationId ?? requestId,
502
- policyTraceId: apiError.policyTraceId ?? null,
503
- retryAfterMs,
504
- willRetry,
505
- });
506
-
507
- if (willRetry) {
508
- lastError = apiError;
509
- await delay(
510
- computeRetryDelayMs({
511
- attempt,
512
- status: response.status,
513
- retryAfterMs,
514
- })
515
- );
516
- continue;
517
- }
518
-
519
- throw apiError;
520
- }
521
-
522
- const successPayload = payload as PlatformGatewaySuccess<T>;
523
- await config.onResponse?.({
524
- ...hookRequestContext,
525
- durationMs: Date.now() - startedAt,
526
- status: response.status,
527
- response: responseClone,
528
- correlationId:
529
- successPayload.correlationId ??
530
- response.headers.get("x-lucern-correlation-id")?.trim() ??
531
- requestId,
532
- policyTraceId:
533
- successPayload.policyTraceId ??
534
- response.headers.get("x-lucern-policy-trace-id")?.trim() ??
535
- null,
536
- idempotentReplay: successPayload.idempotentReplay,
537
- retryAfterMs,
538
- willRetry: false,
539
- });
540
-
541
- return successPayload;
542
- } catch (fetchError) {
543
- if (fetchError instanceof LucernApiError) {
544
- throw fetchError;
545
- }
546
- const willRetry = attempt < maxRetries;
547
- await config.onResponse?.({
548
- ...hookRequestContext,
549
- durationMs: Date.now() - startedAt,
550
- error: fetchError,
551
- correlationId: requestId,
552
- policyTraceId: null,
553
- willRetry,
554
- });
555
- lastError = fetchError;
556
- if (willRetry) {
557
- await delay(computeRetryDelayMs({ attempt }));
558
- }
559
- }
560
- }
561
-
562
- throw lastError instanceof Error
563
- ? lastError
564
- : new Error("Platform API request failed after retries.");
565
- }
566
-
567
- return {
568
- request,
569
- };
570
- }