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

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