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

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 (206) hide show
  1. package/.turbo/turbo-build.log +7 -0
  2. package/.turbo/turbo-typecheck.log +4 -0
  3. package/CHANGELOG.md +13 -0
  4. package/examples/README.md +69 -0
  5. package/examples/contradiction.ts +94 -0
  6. package/examples/investigation-context.ts +118 -0
  7. package/examples/questions-and-tasks.ts +55 -0
  8. package/examples/quickstart.ts +97 -0
  9. package/examples/shared.ts +318 -0
  10. package/examples/strict-public-types.ts +143 -0
  11. package/examples/worktree-lifecycle.ts +79 -0
  12. package/package.json +16 -58
  13. package/src/README.md +6 -0
  14. package/src/adminClient.ts +789 -0
  15. package/{dist/lib/platform/sdk/answersClient.d.ts → src/answersClient.ts} +17 -4
  16. package/src/audiencesClient.ts +209 -0
  17. package/src/auditClient.ts +50 -0
  18. package/src/beliefsClient.ts +319 -0
  19. package/src/client.ts +2647 -0
  20. package/src/contextClient.ts +130 -0
  21. package/{dist/lib/platform/sdk/contextFacade.d.ts → src/contextFacade.ts} +6 -1
  22. package/src/contextPackCompiler.ts +828 -0
  23. package/src/contextPackSchema.ts +251 -0
  24. package/src/contextTypes.ts +153 -0
  25. package/src/contracts/api-enums.contract.ts +202 -0
  26. package/src/contracts/auth-session.contract.ts +109 -0
  27. package/src/contracts/context-pack.contract.ts +700 -0
  28. package/src/contracts/contextPack.ts +1 -0
  29. package/src/contracts/index.ts +10 -0
  30. package/src/contracts/lens-filter.contract.ts +183 -0
  31. package/src/contracts/lens-workflow.contract.ts +162 -0
  32. package/src/contracts/lensFilter.ts +1 -0
  33. package/src/contracts/lensWorkflow.ts +1 -0
  34. package/src/contracts/mcp-tools.contract.ts +3636 -0
  35. package/src/contracts/mcpTools.ts +1 -0
  36. package/src/contracts/prompt.contract.ts +50 -0
  37. package/src/contracts/prompt.ts +1 -0
  38. package/src/contracts/sdk-tools.contract.ts +1457 -0
  39. package/src/contracts/sdkTools.ts +1 -0
  40. package/src/contracts/workflow-runtime.contract.ts +440 -0
  41. package/src/contracts/workflowRuntime.ts +1 -0
  42. package/src/controlObjectOwnership.ts +286 -0
  43. package/src/coreClient.ts +570 -0
  44. package/src/customTools.ts +398 -0
  45. package/src/decisionsClient.ts +286 -0
  46. package/src/domainContext.ts +15 -0
  47. package/src/events.ts +531 -0
  48. package/src/eventsCore.ts +168 -0
  49. package/src/facade/beliefs.ts +83 -0
  50. package/src/facade/context.ts +110 -0
  51. package/src/facade/contradictions.ts +29 -0
  52. package/src/facade/edges.ts +30 -0
  53. package/src/facade/events.ts +23 -0
  54. package/src/facade/evidence.ts +41 -0
  55. package/src/facade/graph.ts +38 -0
  56. package/src/facade/identity.ts +16 -0
  57. package/src/facade/ontologies.ts +34 -0
  58. package/src/facade/questions.ts +59 -0
  59. package/src/facade/search.ts +16 -0
  60. package/src/facade/tasks.ts +37 -0
  61. package/src/facade/topics.ts +42 -0
  62. package/src/facade/webhooks.ts +58 -0
  63. package/src/facade/worktrees.ts +51 -0
  64. package/src/gatewayFacades.ts +1666 -0
  65. package/src/graphClient.ts +529 -0
  66. package/src/harnessClient.ts +585 -0
  67. package/src/identityClient.ts +278 -0
  68. package/src/learningClient.ts +95 -0
  69. package/src/mcpParityClient.ts +240 -0
  70. package/src/mcpParitySurface.ts +70 -0
  71. package/src/ontologyClient.ts +275 -0
  72. package/src/packRuntime.ts +3 -0
  73. package/src/packsClient.ts +260 -0
  74. package/src/policyClient.ts +572 -0
  75. package/src/realtime/index.ts +51 -0
  76. package/src/realtime/refs.ts +17 -0
  77. package/src/reportsClient.ts +99 -0
  78. package/src/schemaClient.ts +129 -0
  79. package/src/sdkSurface.ts +190 -0
  80. package/src/topicsClient.ts +243 -0
  81. package/src/types.ts +807 -0
  82. package/src/workflowClient.ts +826 -0
  83. package/tsconfig.json +9 -0
  84. package/dist/.generated +0 -2
  85. package/dist/index.d.ts +0 -3
  86. package/dist/index.js +0 -3
  87. package/dist/lib/platform/auth/credentials.d.ts +0 -5
  88. package/dist/lib/platform/auth/credentials.js +0 -40
  89. package/dist/lib/platform/sdk/adminClient.d.ts +0 -404
  90. package/dist/lib/platform/sdk/adminClient.js +0 -384
  91. package/dist/lib/platform/sdk/answersClient.js +0 -21
  92. package/dist/lib/platform/sdk/audiencesClient.d.ts +0 -93
  93. package/dist/lib/platform/sdk/audiencesClient.js +0 -111
  94. package/dist/lib/platform/sdk/auditClient.d.ts +0 -24
  95. package/dist/lib/platform/sdk/auditClient.js +0 -21
  96. package/dist/lib/platform/sdk/beliefsClient.d.ts +0 -157
  97. package/dist/lib/platform/sdk/beliefsClient.js +0 -124
  98. package/dist/lib/platform/sdk/client.d.ts +0 -2369
  99. package/dist/lib/platform/sdk/client.js +0 -1831
  100. package/dist/lib/platform/sdk/contextClient.d.ts +0 -21
  101. package/dist/lib/platform/sdk/contextClient.js +0 -86
  102. package/dist/lib/platform/sdk/contextFacade.js +0 -10
  103. package/dist/lib/platform/sdk/contextPackCompiler.d.ts +0 -100
  104. package/dist/lib/platform/sdk/contextPackCompiler.js +0 -534
  105. package/dist/lib/platform/sdk/contextTypes.d.ts +0 -133
  106. package/dist/lib/platform/sdk/contextTypes.js +0 -1
  107. package/dist/lib/platform/sdk/controlObjectOwnership.d.ts +0 -308
  108. package/dist/lib/platform/sdk/controlObjectOwnership.js +0 -220
  109. package/dist/lib/platform/sdk/coreClient.d.ts +0 -139
  110. package/dist/lib/platform/sdk/coreClient.js +0 -366
  111. package/dist/lib/platform/sdk/customTools.d.ts +0 -83
  112. package/dist/lib/platform/sdk/customTools.js +0 -247
  113. package/dist/lib/platform/sdk/decisionsClient.d.ts +0 -106
  114. package/dist/lib/platform/sdk/decisionsClient.js +0 -129
  115. package/dist/lib/platform/sdk/domainContext.d.ts +0 -1
  116. package/dist/lib/platform/sdk/domainContext.js +0 -1
  117. package/dist/lib/platform/sdk/events.d.ts +0 -176
  118. package/dist/lib/platform/sdk/events.js +0 -261
  119. package/dist/lib/platform/sdk/eventsCore.d.ts +0 -13
  120. package/dist/lib/platform/sdk/eventsCore.js +0 -13
  121. package/dist/lib/platform/sdk/gatewayFacades.d.ts +0 -586
  122. package/dist/lib/platform/sdk/gatewayFacades.js +0 -845
  123. package/dist/lib/platform/sdk/graphClient.d.ts +0 -266
  124. package/dist/lib/platform/sdk/graphClient.js +0 -235
  125. package/dist/lib/platform/sdk/harnessClient.d.ts +0 -309
  126. package/dist/lib/platform/sdk/harnessClient.js +0 -219
  127. package/dist/lib/platform/sdk/identityClient.d.ts +0 -134
  128. package/dist/lib/platform/sdk/identityClient.js +0 -131
  129. package/dist/lib/platform/sdk/index.js +0 -49
  130. package/dist/lib/platform/sdk/learningClient.d.ts +0 -40
  131. package/dist/lib/platform/sdk/learningClient.js +0 -53
  132. package/dist/lib/platform/sdk/mcpParityClient.d.ts +0 -69
  133. package/dist/lib/platform/sdk/mcpParityClient.js +0 -196
  134. package/dist/lib/platform/sdk/mcpParitySurface.d.ts +0 -10
  135. package/dist/lib/platform/sdk/mcpParitySurface.js +0 -57
  136. package/dist/lib/platform/sdk/ontologyClient.d.ts +0 -131
  137. package/dist/lib/platform/sdk/ontologyClient.js +0 -161
  138. package/dist/lib/platform/sdk/packRuntime.d.ts +0 -1
  139. package/dist/lib/platform/sdk/packRuntime.js +0 -1
  140. package/dist/lib/platform/sdk/packsClient.d.ts +0 -126
  141. package/dist/lib/platform/sdk/packsClient.js +0 -157
  142. package/dist/lib/platform/sdk/policyClient.d.ts +0 -293
  143. package/dist/lib/platform/sdk/policyClient.js +0 -277
  144. package/dist/lib/platform/sdk/promptCatalog.js +0 -1
  145. package/dist/lib/platform/sdk/reportsClient.d.ts +0 -34
  146. package/dist/lib/platform/sdk/reportsClient.js +0 -64
  147. package/dist/lib/platform/sdk/schemaClient.d.ts +0 -59
  148. package/dist/lib/platform/sdk/schemaClient.js +0 -71
  149. package/dist/lib/platform/sdk/sdkSurface.d.ts +0 -56
  150. package/dist/lib/platform/sdk/sdkSurface.js +0 -140
  151. package/dist/lib/platform/sdk/topicsClient.d.ts +0 -78
  152. package/dist/lib/platform/sdk/topicsClient.js +0 -118
  153. package/dist/lib/platform/sdk/types.d.ts +0 -692
  154. package/dist/lib/platform/sdk/types.js +0 -1
  155. package/dist/lib/platform/sdk/version.d.ts +0 -2
  156. package/dist/lib/platform/sdk/workflowClient.d.ts +0 -313
  157. package/dist/lib/platform/sdk/workflowClient.js +0 -366
  158. package/dist/lucern/contracts/src/api-enums.contract.d.ts +0 -58
  159. package/dist/lucern/contracts/src/api-enums.contract.js +0 -147
  160. package/dist/lucern/contracts/src/auth-context.contract.d.ts +0 -8
  161. package/dist/lucern/contracts/src/auth-context.contract.js +0 -8
  162. package/dist/lucern/contracts/src/auth-session.contract.d.ts +0 -8
  163. package/dist/lucern/contracts/src/auth-session.contract.js +0 -8
  164. package/dist/lucern/contracts/src/auth.contract.d.ts +0 -88
  165. package/dist/lucern/contracts/src/auth.contract.js +0 -57
  166. package/dist/lucern/contracts/src/context-pack.contract.d.ts +0 -494
  167. package/dist/lucern/contracts/src/context-pack.contract.js +0 -169
  168. package/dist/lucern/contracts/src/convex-admin.contract.d.ts +0 -5
  169. package/dist/lucern/contracts/src/convex-admin.contract.js +0 -1
  170. package/dist/lucern/contracts/src/events-types.contract.d.ts +0 -8
  171. package/dist/lucern/contracts/src/events-types.contract.js +0 -8
  172. package/dist/lucern/contracts/src/events.contract.d.ts +0 -176
  173. package/dist/lucern/contracts/src/events.contract.js +0 -159
  174. package/dist/lucern/contracts/src/gateway.contract.d.ts +0 -74
  175. package/dist/lucern/contracts/src/gateway.contract.js +0 -19
  176. package/dist/lucern/contracts/src/ids.contract.d.ts +0 -7
  177. package/dist/lucern/contracts/src/ids.contract.js +0 -24
  178. package/dist/lucern/contracts/src/index.d.ts +0 -29
  179. package/dist/lucern/contracts/src/index.js +0 -29
  180. package/dist/lucern/contracts/src/lens-filter.contract.d.ts +0 -70
  181. package/dist/lucern/contracts/src/lens-filter.contract.js +0 -95
  182. package/dist/lucern/contracts/src/lens-workflow.contract.d.ts +0 -84
  183. package/dist/lucern/contracts/src/lens-workflow.contract.js +0 -54
  184. package/dist/lucern/contracts/src/mcp-tools.contract.d.ts +0 -151
  185. package/dist/lucern/contracts/src/mcp-tools.contract.js +0 -3281
  186. package/dist/lucern/contracts/src/ontology-matching.contract.d.ts +0 -8
  187. package/dist/lucern/contracts/src/ontology-matching.contract.js +0 -8
  188. package/dist/lucern/contracts/src/prompt.contract.d.ts +0 -24
  189. package/dist/lucern/contracts/src/prompt.contract.js +0 -24
  190. package/dist/lucern/contracts/src/sdk-methods.contract.d.ts +0 -358
  191. package/dist/lucern/contracts/src/sdk-methods.contract.js +0 -19
  192. package/dist/lucern/contracts/src/sdk-tools.contract.d.ts +0 -92
  193. package/dist/lucern/contracts/src/sdk-tools.contract.js +0 -1398
  194. package/dist/lucern/contracts/src/text-matching.contract.d.ts +0 -53
  195. package/dist/lucern/contracts/src/text-matching.contract.js +0 -277
  196. package/dist/lucern/contracts/src/topic-scope.contract.d.ts +0 -8
  197. package/dist/lucern/contracts/src/topic-scope.contract.js +0 -8
  198. package/dist/lucern/contracts/src/workflow-runtime.contract.d.ts +0 -161
  199. package/dist/lucern/contracts/src/workflow-runtime.contract.js +0 -257
  200. package/dist/realtime-refs.d.ts +0 -1
  201. package/dist/realtime-refs.js +0 -1
  202. package/dist/realtime.d.ts +0 -1
  203. package/dist/realtime.js +0 -1
  204. /package/{dist/lib/platform/sdk/index.d.ts → src/index.ts} +0 -0
  205. /package/{dist/lib/platform/sdk/promptCatalog.d.ts → src/promptCatalog.ts} +0 -0
  206. /package/{dist/lib/platform/sdk/version.js → src/version.ts} +0 -0
@@ -0,0 +1,570 @@
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
+ }