@lucern/sdk 0.3.0-alpha.16 → 0.3.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +0 -8
- package/README.md +4 -110
- package/dist/adminClient.d.ts +8 -10
- package/dist/adminClient.js +39 -260
- package/dist/adminClient.js.map +1 -1
- package/dist/answersClient.d.ts +0 -2
- package/dist/answersClient.js +11 -239
- package/dist/answersClient.js.map +1 -1
- package/dist/audience/index.d.ts +1 -2
- package/dist/audience/index.js +3 -1
- package/dist/audience/index.js.map +1 -1
- package/dist/audiencesClient.d.ts +16 -18
- package/dist/audiencesClient.js +90 -315
- package/dist/audiencesClient.js.map +1 -1
- package/dist/auditClient.d.ts +0 -2
- package/dist/auditClient.js +15 -245
- package/dist/auditClient.js.map +1 -1
- package/dist/beliefs/index.d.ts +5 -27
- package/dist/beliefs/index.js +1177 -3842
- package/dist/beliefs/index.js.map +1 -1
- package/dist/beliefsClient.d.ts +2 -4
- package/dist/beliefsClient.js +26 -248
- package/dist/beliefsClient.js.map +1 -1
- package/dist/client-B6aWUUwp.d.ts +2552 -0
- package/dist/client.d.ts +27 -3041
- package/dist/client.js +1177 -3842
- package/dist/client.js.map +1 -1
- package/dist/contextClient.d.ts +3 -6
- package/dist/contextClient.js +30 -270
- package/dist/contextClient.js.map +1 -1
- package/dist/contextFacade.js +16 -25
- package/dist/contextFacade.js.map +1 -1
- package/dist/contextPackCompiler.js +30 -19
- package/dist/contextPackCompiler.js.map +1 -1
- package/dist/contextPackPolicy.js +17 -7
- package/dist/contextPackPolicy.js.map +1 -1
- package/dist/contextTypes.d.ts +0 -2
- package/dist/contracts/api-enums.contract.d.ts +2 -2
- package/dist/contracts/api-enums.contract.js +1 -6
- package/dist/contracts/api-enums.contract.js.map +1 -1
- package/dist/contracts/auth-session.contract.d.ts +1 -1
- package/dist/contracts/auth-session.contract.js +1 -13
- package/dist/contracts/auth-session.contract.js.map +1 -1
- package/dist/contracts/index.d.ts +0 -1
- package/dist/contracts/index.js +6 -133
- package/dist/contracts/index.js.map +1 -1
- package/dist/contracts/lens-filter.contract.js +3 -4
- package/dist/contracts/lens-filter.contract.js.map +1 -1
- package/dist/contracts/lens-workflow.contract.js +3 -4
- package/dist/contracts/lens-workflow.contract.js.map +1 -1
- package/dist/contracts/lensFilter.js +3 -4
- package/dist/contracts/lensFilter.js.map +1 -1
- package/dist/contracts/lensWorkflow.js +3 -4
- package/dist/contracts/lensWorkflow.js.map +1 -1
- package/dist/contracts/mcpTools.d.ts +1 -46
- package/dist/contracts/mcpTools.js +0 -108
- package/dist/contracts/mcpTools.js.map +1 -1
- package/dist/contradictions/index.d.ts +4 -26
- package/dist/contradictions/index.js +1177 -3842
- package/dist/contradictions/index.js.map +1 -1
- package/dist/coreClient.d.ts +2 -28
- package/dist/coreClient.js +14 -240
- package/dist/coreClient.js.map +1 -1
- package/dist/decisions/index.d.ts +14 -36
- package/dist/decisions/index.js +1177 -3842
- package/dist/decisions/index.js.map +1 -1
- package/dist/decisionsClient.d.ts +12 -6
- package/dist/decisionsClient.js +37 -253
- package/dist/decisionsClient.js.map +1 -1
- package/dist/edges/index.d.ts +87 -49
- package/dist/edges/index.js +1177 -3842
- package/dist/edges/index.js.map +1 -1
- package/dist/events.js +3 -6
- package/dist/events.js.map +1 -1
- package/dist/eventsCore.d.ts +1 -3
- package/dist/eventsCore.js +14 -240
- package/dist/eventsCore.js.map +1 -1
- package/dist/evidence/index.d.ts +4 -26
- package/dist/evidence/index.js +1177 -3842
- package/dist/evidence/index.js.map +1 -1
- package/dist/evidenceClient.d.ts +0 -2
- package/dist/evidenceClient.js +14 -240
- package/dist/evidenceClient.js.map +1 -1
- package/dist/facade/context.d.ts +1 -2
- package/dist/facade/context.js +16 -25
- package/dist/facade/context.js.map +1 -1
- package/dist/gatewayFacades.d.ts +46 -90
- package/dist/gatewayFacades.js +128 -609
- package/dist/gatewayFacades.js.map +1 -1
- package/dist/graphClient.d.ts +13 -8
- package/dist/graphClient.js +45 -262
- package/dist/graphClient.js.map +1 -1
- package/dist/harnessClient.d.ts +24 -15
- package/dist/harnessClient.js +42 -253
- package/dist/harnessClient.js.map +1 -1
- package/dist/identityClient.d.ts +11 -115
- package/dist/identityClient.js +33 -555
- package/dist/identityClient.js.map +1 -1
- package/dist/index.d.ts +6 -32
- package/dist/index.js +2580 -5825
- package/dist/index.js.map +1 -1
- package/dist/learningClient.d.ts +6 -8
- package/dist/learningClient.js +44 -270
- package/dist/learningClient.js.map +1 -1
- package/dist/lenses/index.d.ts +38 -78
- package/dist/lenses/index.js +1177 -3842
- package/dist/lenses/index.js.map +1 -1
- package/dist/nodes/index.d.ts +21 -65
- package/dist/nodes/index.js +1177 -3842
- package/dist/nodes/index.js.map +1 -1
- package/dist/ontologies/index.d.ts +32 -55
- package/dist/ontologies/index.js +1177 -3842
- package/dist/ontologies/index.js.map +1 -1
- package/dist/ontologyClient.d.ts +25 -19
- package/dist/ontologyClient.js +40 -276
- package/dist/ontologyClient.js.map +1 -1
- package/dist/packsClient.d.ts +23 -11
- package/dist/packsClient.js +46 -252
- package/dist/packsClient.js.map +1 -1
- package/dist/policyClient.d.ts +10 -13
- package/dist/policyClient.js +25 -261
- package/dist/policyClient.js.map +1 -1
- package/dist/questions/index.d.ts +4 -26
- package/dist/questions/index.js +1177 -3842
- package/dist/questions/index.js.map +1 -1
- package/dist/realtime/index.d.ts +1 -1
- package/dist/reportsClient.d.ts +7 -9
- package/dist/reportsClient.js +53 -299
- package/dist/reportsClient.js.map +1 -1
- package/dist/schemaClient.d.ts +3 -5
- package/dist/schemaClient.js +29 -253
- package/dist/schemaClient.js.map +1 -1
- package/dist/sdkSurface.d.ts +3 -8
- package/dist/sdkSurface.js +6 -10
- package/dist/sdkSurface.js.map +1 -1
- package/dist/sourcesClient.d.ts +0 -2
- package/dist/sourcesClient.js +14 -240
- package/dist/sourcesClient.js.map +1 -1
- package/dist/topics/index.d.ts +9 -37
- package/dist/topics/index.js +1177 -3844
- package/dist/topics/index.js.map +1 -1
- package/dist/topicsClient.d.ts +0 -4
- package/dist/topicsClient.js +24 -255
- package/dist/topicsClient.js.map +1 -1
- package/dist/types.d.ts +0 -17
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/dist/workflowClient.d.ts +40 -60
- package/dist/workflowClient.js +58 -261
- package/dist/workflowClient.js.map +1 -1
- package/dist/worktrees/index.d.ts +33 -71
- package/dist/worktrees/index.js +1177 -3842
- package/dist/worktrees/index.js.map +1 -1
- package/package.json +3 -17
- package/dist/accessControl.d.ts +0 -79
- package/dist/accessControl.js +0 -1270
- package/dist/accessControl.js.map +0 -1
- package/dist/authContext.d.ts +0 -56
- package/dist/authContext.js +0 -170
- package/dist/authContext.js.map +0 -1
- package/dist/authDeviceClient.d.ts +0 -49
- package/dist/authDeviceClient.js +0 -121
- package/dist/authDeviceClient.js.map +0 -1
- package/dist/boundaryClientSurface.d.ts +0 -20
- package/dist/boundaryClientSurface.js +0 -73
- package/dist/boundaryClientSurface.js.map +0 -1
- package/dist/clientHelpers.d.ts +0 -48
- package/dist/clientHelpers.js +0 -137
- package/dist/clientHelpers.js.map +0 -1
- package/dist/control-plane.d.ts +0 -69
- package/dist/control-plane.js +0 -674
- package/dist/control-plane.js.map +0 -1
- package/dist/embeddingsClient.d.ts +0 -106
- package/dist/embeddingsClient.js +0 -749
- package/dist/embeddingsClient.js.map +0 -1
- package/dist/eventingClient.d.ts +0 -96
- package/dist/eventingClient.js +0 -746
- package/dist/eventingClient.js.map +0 -1
- package/dist/functionSurface.d.ts +0 -144
- package/dist/functionSurface.js +0 -1227
- package/dist/functionSurface.js.map +0 -1
- package/dist/functionSurfaceClient.d.ts +0 -8
- package/dist/functionSurfaceClient.js +0 -1227
- package/dist/functionSurfaceClient.js.map +0 -1
- package/dist/graphAnalysisClient.d.ts +0 -192
- package/dist/graphAnalysisClient.js +0 -817
- package/dist/graphAnalysisClient.js.map +0 -1
- package/dist/graphIntel.d.ts +0 -4
- package/dist/graphIntel.js +0 -3
- package/dist/graphIntel.js.map +0 -1
- package/dist/graphIntelligence.d.ts +0 -2
- package/dist/graphIntelligence.js +0 -47
- package/dist/graphIntelligence.js.map +0 -1
- package/dist/graphRecommendationsClient.d.ts +0 -56
- package/dist/graphRecommendationsClient.js +0 -682
- package/dist/graphRecommendationsClient.js.map +0 -1
- package/dist/graphStateClassifierClient.d.ts +0 -73
- package/dist/graphStateClassifierClient.js +0 -734
- package/dist/graphStateClassifierClient.js.map +0 -1
- package/dist/infisicalRuntime.d.ts +0 -43
- package/dist/infisicalRuntime.js +0 -346
- package/dist/infisicalRuntime.js.map +0 -1
- package/dist/jobsClient.d.ts +0 -98
- package/dist/jobsClient.js +0 -744
- package/dist/jobsClient.js.map +0 -1
- package/dist/mcpClient.d.ts +0 -28
- package/dist/mcpClient.js +0 -687
- package/dist/mcpClient.js.map +0 -1
- package/dist/modelRuntimeClient.d.ts +0 -72
- package/dist/modelRuntimeClient.js +0 -722
- package/dist/modelRuntimeClient.js.map +0 -1
- package/dist/ontologyLinksClient.d.ts +0 -71
- package/dist/ontologyLinksClient.js +0 -715
- package/dist/ontologyLinksClient.js.map +0 -1
- package/dist/orgGraphSearchClient.d.ts +0 -85
- package/dist/orgGraphSearchClient.js +0 -690
- package/dist/orgGraphSearchClient.js.map +0 -1
- package/dist/secrets.d.ts +0 -1
- package/dist/secrets.js +0 -3
- package/dist/secrets.js.map +0 -1
- package/dist/telemetryClient.d.ts +0 -94
- package/dist/telemetryClient.js +0 -759
- package/dist/telemetryClient.js.map +0 -1
- package/dist/toolRegistryClient.d.ts +0 -115
- package/dist/toolRegistryClient.js +0 -785
- package/dist/toolRegistryClient.js.map +0 -1
package/dist/contextClient.d.ts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
import { GatewayClientConfig, PlatformGatewaySuccess } from './coreClient.js';
|
|
2
2
|
import { PublicCompiledContext, CompileContextInput } from './contextTypes.js';
|
|
3
|
-
import './authContext.js';
|
|
4
|
-
import './contracts/auth-session.contract.js';
|
|
5
3
|
import './types.js';
|
|
6
4
|
import './contracts/workflow-runtime.contract.js';
|
|
7
5
|
import './contracts/lens-workflow.contract.js';
|
|
@@ -18,13 +16,12 @@ type CompileContextResponse = PublicCompiledContext;
|
|
|
18
16
|
*/
|
|
19
17
|
declare function createContextClient(config?: ContextClientConfig): {
|
|
20
18
|
/**
|
|
21
|
-
* Compile a focused reasoning context pack.
|
|
22
|
-
* @param
|
|
19
|
+
* Compile a focused reasoning context pack for a topic scope.
|
|
20
|
+
* @param topicId - The topic to compile context for.
|
|
23
21
|
* @param input - Optional compile parameters (query, budget, ranking, etc.).
|
|
24
22
|
* @returns The compiled context payload with beliefs, questions, and evidence.
|
|
25
23
|
*/
|
|
26
|
-
compile(
|
|
27
|
-
compileByQuery(input?: CompileContextInput): Promise<PlatformGatewaySuccess<PublicCompiledContext>>;
|
|
24
|
+
compile(topicId: string, input?: CompileContextInput): Promise<PlatformGatewaySuccess<PublicCompiledContext>>;
|
|
28
25
|
};
|
|
29
26
|
|
|
30
27
|
export { CompileContextInput, type CompileContextResponse, type ContextClientConfig, PublicCompiledContext, createContextClient };
|
package/dist/contextClient.js
CHANGED
|
@@ -1,170 +1,3 @@
|
|
|
1
|
-
// src/authContext.ts
|
|
2
|
-
var LucernSdkAuthContextError = class extends Error {
|
|
3
|
-
reason;
|
|
4
|
-
constructor(reason, message) {
|
|
5
|
-
super(message);
|
|
6
|
-
this.name = "LucernSdkAuthContextError";
|
|
7
|
-
this.reason = reason;
|
|
8
|
-
}
|
|
9
|
-
};
|
|
10
|
-
function cleanString(value) {
|
|
11
|
-
const normalized = value?.trim();
|
|
12
|
-
return normalized ? normalized : void 0;
|
|
13
|
-
}
|
|
14
|
-
function cleanStringList(values) {
|
|
15
|
-
if (!values) {
|
|
16
|
-
return [];
|
|
17
|
-
}
|
|
18
|
-
return values.map((value) => value.trim()).filter(
|
|
19
|
-
(value, index, list) => value.length > 0 && list.indexOf(value) === index
|
|
20
|
-
);
|
|
21
|
-
}
|
|
22
|
-
function requireString(value, reason, label) {
|
|
23
|
-
const normalized = cleanString(value);
|
|
24
|
-
if (!normalized) {
|
|
25
|
-
throw new LucernSdkAuthContextError(
|
|
26
|
-
reason,
|
|
27
|
-
`Canonical Lucern SDK auth context is missing ${label}.`
|
|
28
|
-
);
|
|
29
|
-
}
|
|
30
|
-
return normalized;
|
|
31
|
-
}
|
|
32
|
-
function requirePrincipalType(principalType) {
|
|
33
|
-
if (!principalType) {
|
|
34
|
-
throw new LucernSdkAuthContextError(
|
|
35
|
-
"principal_missing",
|
|
36
|
-
"Canonical Lucern SDK auth context is missing principalType."
|
|
37
|
-
);
|
|
38
|
-
}
|
|
39
|
-
return principalType;
|
|
40
|
-
}
|
|
41
|
-
function requireAuthMode(authMode) {
|
|
42
|
-
if (!authMode) {
|
|
43
|
-
throw new LucernSdkAuthContextError(
|
|
44
|
-
"principal_missing",
|
|
45
|
-
"Canonical Lucern SDK auth context is missing authMode."
|
|
46
|
-
);
|
|
47
|
-
}
|
|
48
|
-
return authMode;
|
|
49
|
-
}
|
|
50
|
-
function ensurePermitMatch(args) {
|
|
51
|
-
const actual = cleanString(args.actual);
|
|
52
|
-
if (actual && actual !== args.expected) {
|
|
53
|
-
throw new LucernSdkAuthContextError(
|
|
54
|
-
"policy_denied",
|
|
55
|
-
`Canonical Lucern SDK auth context has conflicting Permit ${args.field}.`
|
|
56
|
-
);
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
function normalizeCanonicalLucernAuthContext(input) {
|
|
60
|
-
if (!input) {
|
|
61
|
-
throw new LucernSdkAuthContextError(
|
|
62
|
-
"principal_missing",
|
|
63
|
-
"Canonical Lucern SDK auth context is required."
|
|
64
|
-
);
|
|
65
|
-
}
|
|
66
|
-
if (input.policyDecision === "deny") {
|
|
67
|
-
throw new LucernSdkAuthContextError(
|
|
68
|
-
"policy_denied",
|
|
69
|
-
"Canonical Lucern SDK auth context carries a denied policy decision."
|
|
70
|
-
);
|
|
71
|
-
}
|
|
72
|
-
const principalId = requireString(
|
|
73
|
-
input.principalId,
|
|
74
|
-
"principal_missing",
|
|
75
|
-
"principalId"
|
|
76
|
-
);
|
|
77
|
-
const tenantId = requireString(input.tenantId, "tenant_missing", "tenantId");
|
|
78
|
-
const workspaceId = requireString(
|
|
79
|
-
input.workspaceId,
|
|
80
|
-
"workspace_missing",
|
|
81
|
-
"workspaceId"
|
|
82
|
-
);
|
|
83
|
-
const roles = cleanStringList(input.roles);
|
|
84
|
-
const scopes = cleanStringList(input.scopes);
|
|
85
|
-
const principalType = requirePrincipalType(input.principalType);
|
|
86
|
-
const authMode = requireAuthMode(input.authMode);
|
|
87
|
-
const roleBasedInteractiveAuth = authMode === "interactive_user" && roles.length > 0;
|
|
88
|
-
if (roles.length === 0 || scopes.length === 0 && !roleBasedInteractiveAuth) {
|
|
89
|
-
throw new LucernSdkAuthContextError(
|
|
90
|
-
"membership_missing",
|
|
91
|
-
"Canonical Lucern SDK auth context requires non-empty roles and scopes."
|
|
92
|
-
);
|
|
93
|
-
}
|
|
94
|
-
const subject = cleanString(input.permit?.subject) ?? principalId;
|
|
95
|
-
const tenant = cleanString(input.permit?.tenant) ?? tenantId;
|
|
96
|
-
const workspace = cleanString(input.permit?.workspace) ?? workspaceId;
|
|
97
|
-
ensurePermitMatch({
|
|
98
|
-
field: "subject",
|
|
99
|
-
expected: principalId,
|
|
100
|
-
actual: subject
|
|
101
|
-
});
|
|
102
|
-
ensurePermitMatch({ field: "tenant", expected: tenantId, actual: tenant });
|
|
103
|
-
ensurePermitMatch({
|
|
104
|
-
field: "workspace",
|
|
105
|
-
expected: workspaceId,
|
|
106
|
-
actual: workspace
|
|
107
|
-
});
|
|
108
|
-
const context = input.permit?.context ? { ...input.permit.context } : void 0;
|
|
109
|
-
return {
|
|
110
|
-
clerkId: cleanString(input.clerkId),
|
|
111
|
-
principalId,
|
|
112
|
-
tenantId,
|
|
113
|
-
workspaceId,
|
|
114
|
-
principalType,
|
|
115
|
-
authMode,
|
|
116
|
-
roles,
|
|
117
|
-
scopes,
|
|
118
|
-
delegationChain: input.delegationChain ? [...input.delegationChain] : [],
|
|
119
|
-
policyTraceId: cleanString(input.policyTraceId),
|
|
120
|
-
correlationId: cleanString(input.correlationId),
|
|
121
|
-
membershipId: cleanString(input.membershipId),
|
|
122
|
-
permit: {
|
|
123
|
-
subject,
|
|
124
|
-
tenant,
|
|
125
|
-
workspace,
|
|
126
|
-
resource: cleanString(input.permit?.resource),
|
|
127
|
-
action: cleanString(input.permit?.action),
|
|
128
|
-
relation: cleanString(input.permit?.relation),
|
|
129
|
-
context
|
|
130
|
-
}
|
|
131
|
-
};
|
|
132
|
-
}
|
|
133
|
-
function createCanonicalAuthHeaders(authContext) {
|
|
134
|
-
const headers = {
|
|
135
|
-
"x-lucern-principal-id": authContext.principalId,
|
|
136
|
-
"x-lucern-principal-type": authContext.principalType,
|
|
137
|
-
"x-lucern-tenant": authContext.tenantId,
|
|
138
|
-
"x-lucern-tenant-id": authContext.tenantId,
|
|
139
|
-
"x-lucern-workspace": authContext.workspaceId,
|
|
140
|
-
"x-lucern-workspace-id": authContext.workspaceId,
|
|
141
|
-
"x-lucern-auth-mode": authContext.authMode,
|
|
142
|
-
"x-lucern-roles": authContext.roles.join(","),
|
|
143
|
-
"x-lucern-scopes": authContext.scopes.join(","),
|
|
144
|
-
"x-lucern-permit-context": JSON.stringify(authContext.permit)
|
|
145
|
-
};
|
|
146
|
-
if (authContext.clerkId) {
|
|
147
|
-
headers["x-lucern-clerk-id"] = authContext.clerkId;
|
|
148
|
-
headers["x-lucern-user-id"] = authContext.clerkId;
|
|
149
|
-
}
|
|
150
|
-
if (authContext.delegationChain.length > 0) {
|
|
151
|
-
headers["x-lucern-delegation-chain"] = JSON.stringify(
|
|
152
|
-
authContext.delegationChain
|
|
153
|
-
);
|
|
154
|
-
}
|
|
155
|
-
if (authContext.policyTraceId) {
|
|
156
|
-
headers["x-lucern-policy-trace-id"] = authContext.policyTraceId;
|
|
157
|
-
}
|
|
158
|
-
if (authContext.correlationId) {
|
|
159
|
-
headers["x-correlation-id"] = authContext.correlationId;
|
|
160
|
-
headers["x-lucern-correlation-id"] = authContext.correlationId;
|
|
161
|
-
}
|
|
162
|
-
if (authContext.membershipId) {
|
|
163
|
-
headers["x-lucern-membership-id"] = authContext.membershipId;
|
|
164
|
-
}
|
|
165
|
-
return headers;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
1
|
// src/coreClient.ts
|
|
169
2
|
var LucernApiError = class extends Error {
|
|
170
3
|
code;
|
|
@@ -276,11 +109,8 @@ function timeoutError(timeoutMs) {
|
|
|
276
109
|
error.name = "AbortError";
|
|
277
110
|
return error;
|
|
278
111
|
}
|
|
279
|
-
function isRecord(value) {
|
|
280
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
281
|
-
}
|
|
282
112
|
function readPolicySummaryFromDetails(details) {
|
|
283
|
-
if (!
|
|
113
|
+
if (!details || typeof details !== "object" || Array.isArray(details)) {
|
|
284
114
|
return null;
|
|
285
115
|
}
|
|
286
116
|
const directSummary = details.summary;
|
|
@@ -288,11 +118,11 @@ function readPolicySummaryFromDetails(details) {
|
|
|
288
118
|
return directSummary.trim();
|
|
289
119
|
}
|
|
290
120
|
const policy = details.policy;
|
|
291
|
-
if (!
|
|
121
|
+
if (!policy || typeof policy !== "object" || Array.isArray(policy)) {
|
|
292
122
|
return null;
|
|
293
123
|
}
|
|
294
124
|
const explanation = policy.explanation;
|
|
295
|
-
if (!
|
|
125
|
+
if (!explanation || typeof explanation !== "object" || Array.isArray(explanation)) {
|
|
296
126
|
return null;
|
|
297
127
|
}
|
|
298
128
|
const nestedSummary = explanation.summary;
|
|
@@ -301,59 +131,16 @@ function readPolicySummaryFromDetails(details) {
|
|
|
301
131
|
}
|
|
302
132
|
return null;
|
|
303
133
|
}
|
|
304
|
-
async function resolveConfiguredAuthContext(authContext) {
|
|
305
|
-
if (typeof authContext === "function") {
|
|
306
|
-
return await authContext();
|
|
307
|
-
}
|
|
308
|
-
return authContext;
|
|
309
|
-
}
|
|
310
|
-
function mergeHeaderRecord(base, addition) {
|
|
311
|
-
const headers = new Headers(base);
|
|
312
|
-
for (const [key, value] of Object.entries(addition)) {
|
|
313
|
-
const existing = headers.get(key);
|
|
314
|
-
if (existing !== null && existing !== value) {
|
|
315
|
-
throw new LucernSdkAuthContextError(
|
|
316
|
-
"policy_denied",
|
|
317
|
-
`Canonical Lucern SDK auth context conflicts with existing ${key} header.`
|
|
318
|
-
);
|
|
319
|
-
}
|
|
320
|
-
headers.set(key, value);
|
|
321
|
-
}
|
|
322
|
-
return Object.fromEntries(headers.entries());
|
|
323
|
-
}
|
|
324
|
-
function cleanHeaderValue(value) {
|
|
325
|
-
const normalized = value?.trim();
|
|
326
|
-
return normalized ? normalized : void 0;
|
|
327
|
-
}
|
|
328
134
|
function createGatewayRequestClient(config = {}) {
|
|
329
135
|
const fetchImpl = config.fetchImpl ?? fetch;
|
|
330
136
|
const baseUrl = config.baseUrl?.replace(/\/+$/, "") ?? "";
|
|
331
137
|
const maxRetries = config.maxRetries ?? 2;
|
|
332
138
|
const requestIdFactory = config.requestIdFactory ?? (() => generatePortableRequestId());
|
|
333
139
|
async function resolveAuthHeaders() {
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
const setIfAbsent = (name, value) => {
|
|
337
|
-
const normalized = cleanHeaderValue(value);
|
|
338
|
-
if (normalized && !headers.has(name)) {
|
|
339
|
-
headers.set(name, normalized);
|
|
340
|
-
}
|
|
341
|
-
};
|
|
342
|
-
setIfAbsent("x-lucern-key", config.apiKey);
|
|
343
|
-
setIfAbsent("x-lucern-session-token", config.userToken);
|
|
344
|
-
setIfAbsent("x-lucern-environment", config.environment);
|
|
345
|
-
setIfAbsent("x-lucern-clerk-id", config.clerkId);
|
|
346
|
-
setIfAbsent("x-lucern-user-id", config.userId ?? config.clerkId);
|
|
347
|
-
setIfAbsent("x-lucern-deployment-host", config.deploymentHost);
|
|
348
|
-
const base = Object.fromEntries(headers.entries());
|
|
349
|
-
const authContextInput = await resolveConfiguredAuthContext(
|
|
350
|
-
config.authContext
|
|
351
|
-
);
|
|
352
|
-
if (!authContextInput && !config.requireCanonicalAuthContext) {
|
|
353
|
-
return base;
|
|
140
|
+
if (!config.getAuthHeaders) {
|
|
141
|
+
return {};
|
|
354
142
|
}
|
|
355
|
-
|
|
356
|
-
return mergeHeaderRecord(base, createCanonicalAuthHeaders(authContext));
|
|
143
|
+
return await config.getAuthHeaders();
|
|
357
144
|
}
|
|
358
145
|
async function fetchWithTimeout(url, init, timeoutMs) {
|
|
359
146
|
const controller = new AbortController();
|
|
@@ -374,11 +161,11 @@ function createGatewayRequestClient(config = {}) {
|
|
|
374
161
|
if (!text) {
|
|
375
162
|
return null;
|
|
376
163
|
}
|
|
377
|
-
|
|
378
|
-
|
|
164
|
+
try {
|
|
165
|
+
return JSON.parse(text);
|
|
166
|
+
} catch {
|
|
379
167
|
return null;
|
|
380
168
|
}
|
|
381
|
-
return isRecord(parsed.value) ? parsed.value : null;
|
|
382
169
|
}
|
|
383
170
|
function resolveTimeoutMs(method, requestTimeoutMs) {
|
|
384
171
|
if (typeof requestTimeoutMs === "number") {
|
|
@@ -390,31 +177,16 @@ function createGatewayRequestClient(config = {}) {
|
|
|
390
177
|
}
|
|
391
178
|
return config.timeoutMs ?? 15e3;
|
|
392
179
|
}
|
|
393
|
-
function tryParseGatewayEnvelopeJson(text) {
|
|
394
|
-
const trimmed = text.trim();
|
|
395
|
-
if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) {
|
|
396
|
-
return { ok: false, reason: "non-json" };
|
|
397
|
-
}
|
|
398
|
-
try {
|
|
399
|
-
return { ok: true, value: JSON.parse(trimmed) };
|
|
400
|
-
} catch (error) {
|
|
401
|
-
if (error instanceof SyntaxError) {
|
|
402
|
-
return { ok: false, reason: "invalid-json", error };
|
|
403
|
-
}
|
|
404
|
-
throw error;
|
|
405
|
-
}
|
|
406
|
-
}
|
|
407
180
|
function buildApiError(args) {
|
|
408
181
|
const failure = args.failure;
|
|
409
|
-
const legacyError = failure &&
|
|
182
|
+
const legacyError = failure && typeof failure.error === "object" && failure.error !== null ? failure.error : failure?.legacyError;
|
|
410
183
|
const correlationId = failure?.correlationId ?? args.response.headers.get("x-lucern-correlation-id")?.trim() ?? args.requestId;
|
|
411
184
|
const policyTraceId = failure?.policyTraceId ?? args.response.headers.get("x-lucern-policy-trace-id")?.trim() ?? null;
|
|
412
185
|
const details = failure?.details ?? legacyError?.details;
|
|
413
186
|
const policySummary = readPolicySummaryFromDetails(details);
|
|
414
|
-
const failureMessage = typeof failure?.error === "string" ? failure.error : legacyError?.message;
|
|
415
187
|
return new LucernApiError({
|
|
416
188
|
code: failure?.code ?? legacyError?.code ?? fallbackErrorCode(args.response.status),
|
|
417
|
-
message: policySummary ??
|
|
189
|
+
message: policySummary ?? (typeof failure?.error === "string" ? failure.error : legacyError?.message ?? (args.response.ok ? "Platform API returned an invalid success payload." : "Platform API request failed.")),
|
|
418
190
|
status: args.response.status,
|
|
419
191
|
invariant: failure?.invariant,
|
|
420
192
|
suggestion: failure?.suggestion,
|
|
@@ -540,7 +312,7 @@ function createGatewayRequestClient(config = {}) {
|
|
|
540
312
|
}
|
|
541
313
|
|
|
542
314
|
// src/contextClient.ts
|
|
543
|
-
function
|
|
315
|
+
function cleanString(value) {
|
|
544
316
|
return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
|
|
545
317
|
}
|
|
546
318
|
function cleanNumber(value) {
|
|
@@ -549,55 +321,50 @@ function cleanNumber(value) {
|
|
|
549
321
|
function cleanBoolean(value) {
|
|
550
322
|
return typeof value === "boolean" ? value : void 0;
|
|
551
323
|
}
|
|
552
|
-
function buildCompileContextRequest(
|
|
553
|
-
const
|
|
554
|
-
const
|
|
555
|
-
const topicId = typeof topicIdOrInput === "string" ? cleanString2(topicIdOrInput) : cleanString2(effectiveInput.topicId);
|
|
556
|
-
if (topicId) {
|
|
557
|
-
payload.topicId = topicId;
|
|
558
|
-
}
|
|
559
|
-
const query = cleanString2(effectiveInput.query);
|
|
324
|
+
function buildCompileContextRequest(topicId, input = {}) {
|
|
325
|
+
const payload = { topicId };
|
|
326
|
+
const query = cleanString(input.query);
|
|
560
327
|
if (query) {
|
|
561
328
|
payload.query = query;
|
|
562
329
|
}
|
|
563
|
-
const budget = cleanNumber(
|
|
330
|
+
const budget = cleanNumber(input.budget) ?? cleanNumber(input.tokenBudget);
|
|
564
331
|
if (budget !== void 0) {
|
|
565
332
|
payload.budget = budget;
|
|
566
333
|
}
|
|
567
|
-
const ranking =
|
|
334
|
+
const ranking = cleanString(input.ranking) ?? cleanString(input.rankingProfile);
|
|
568
335
|
if (ranking) {
|
|
569
336
|
payload.ranking = ranking;
|
|
570
337
|
}
|
|
571
|
-
const limit = cleanNumber(
|
|
338
|
+
const limit = cleanNumber(input.limit);
|
|
572
339
|
if (limit !== void 0) {
|
|
573
340
|
payload.limit = limit;
|
|
574
341
|
}
|
|
575
|
-
const maxDepth = cleanNumber(
|
|
342
|
+
const maxDepth = cleanNumber(input.maxDepth);
|
|
576
343
|
if (maxDepth !== void 0) {
|
|
577
344
|
payload.maxDepth = maxDepth;
|
|
578
345
|
}
|
|
579
|
-
const includeEntities = cleanBoolean(
|
|
346
|
+
const includeEntities = cleanBoolean(input.includeEntities);
|
|
580
347
|
if (includeEntities !== void 0) {
|
|
581
348
|
payload.includeEntities = includeEntities;
|
|
582
349
|
}
|
|
583
|
-
const mode =
|
|
350
|
+
const mode = cleanString(input.mode);
|
|
584
351
|
if (mode) {
|
|
585
352
|
payload.mode = mode;
|
|
586
353
|
}
|
|
587
|
-
const includeFailures = cleanBoolean(
|
|
354
|
+
const includeFailures = cleanBoolean(input.includeFailures);
|
|
588
355
|
if (includeFailures !== void 0) {
|
|
589
356
|
payload.includeFailures = includeFailures;
|
|
590
357
|
}
|
|
591
|
-
const worktreeId =
|
|
358
|
+
const worktreeId = cleanString(input.worktreeId);
|
|
592
359
|
if (worktreeId) {
|
|
593
360
|
payload.worktreeId = worktreeId;
|
|
594
361
|
}
|
|
595
|
-
const sessionId =
|
|
362
|
+
const sessionId = cleanString(input.sessionId);
|
|
596
363
|
if (sessionId) {
|
|
597
364
|
payload.sessionId = sessionId;
|
|
598
365
|
}
|
|
599
|
-
if (Array.isArray(
|
|
600
|
-
payload.packWeightOverrides =
|
|
366
|
+
if (Array.isArray(input.packWeightOverrides) && input.packWeightOverrides.length > 0) {
|
|
367
|
+
payload.packWeightOverrides = input.packWeightOverrides;
|
|
601
368
|
}
|
|
602
369
|
return {
|
|
603
370
|
path: "/api/platform/v1/context/compile",
|
|
@@ -609,20 +376,13 @@ function createContextClient(config = {}) {
|
|
|
609
376
|
const gateway = createGatewayRequestClient(config);
|
|
610
377
|
return {
|
|
611
378
|
/**
|
|
612
|
-
* Compile a focused reasoning context pack.
|
|
613
|
-
* @param
|
|
379
|
+
* Compile a focused reasoning context pack for a topic scope.
|
|
380
|
+
* @param topicId - The topic to compile context for.
|
|
614
381
|
* @param input - Optional compile parameters (query, budget, ranking, etc.).
|
|
615
382
|
* @returns The compiled context payload with beliefs, questions, and evidence.
|
|
616
383
|
*/
|
|
617
|
-
async compile(
|
|
618
|
-
const request = buildCompileContextRequest(
|
|
619
|
-
return gateway.request({
|
|
620
|
-
...request,
|
|
621
|
-
body: request.body
|
|
622
|
-
});
|
|
623
|
-
},
|
|
624
|
-
async compileByQuery(input = {}) {
|
|
625
|
-
const request = buildCompileContextRequest(input);
|
|
384
|
+
async compile(topicId, input = {}) {
|
|
385
|
+
const request = buildCompileContextRequest(topicId, input);
|
|
626
386
|
return gateway.request({
|
|
627
387
|
...request,
|
|
628
388
|
body: request.body
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/authContext.ts","../src/coreClient.ts","../src/contextClient.ts"],"names":["cleanString"],"mappings":";AA+DO,IAAM,yBAAA,GAAN,cAAwC,KAAA,CAAM;AAA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AA,MAAM,OAAA,GAAU,2BAA2B,MAAM,CAAA;AAEjD,EAAA,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOL,MAAM,OAAA,CACJ,cAAA,GAA+C,EAAC,EAChD,KAAA,GAA6B,EAAC,EAC9B;AACA,MAAA,MAAM,OAAA,GAAU,0BAAA,CAA2B,cAAA,EAAgB,KAAK,CAAA;AAChE,MAAA,OAAO,QAAQ,OAAA,CAAgC;AAAA,QAC7C,GAAG,OAAA;AAAA,QACH,MAAM,OAAA,CAAQ;AAAA,OACf,CAAA;AAAA,IACH,CAAA;AAAA,IACA,MAAM,cAAA,CAAe,KAAA,GAA6B,EAAC,EAAG;AACpD,MAAA,MAAM,OAAA,GAAU,2BAA2B,KAAK,CAAA;AAChD,MAAA,OAAO,QAAQ,OAAA,CAAgC;AAAA,QAC7C,GAAG,OAAA;AAAA,QACH,MAAM,OAAA,CAAQ;AAAA,OACf,CAAA;AAAA,IACH;AAAA,GACF;AACF","file":"contextClient.js","sourcesContent":["import type {\n SessionAuthMode,\n SessionDelegationHop,\n SessionPrincipalType,\n} from \"./contracts/auth-session.contract\";\nimport type { JsonObject } from \"./types\";\n\nexport type LucernSdkAuthFailureReason =\n | \"principal_missing\"\n | \"tenant_missing\"\n | \"membership_missing\"\n | \"workspace_missing\"\n | \"clerk_alias_missing\"\n | \"clerk_alias_unrecognized\"\n | \"policy_denied\"\n | \"policy_unavailable\"\n | \"policy_unknown\";\n\nexport type PermitReadyAuthContext = {\n subject: string;\n tenant: string;\n workspace: string;\n resource?: string;\n action?: string;\n relation?: string;\n context?: JsonObject;\n};\n\nexport type LucernSdkAuthPolicyDecision = \"allow\" | \"deny\" | \"unknown\";\n\nexport type LucernSdkAuthContextInput = {\n clerkId?: string;\n principalId?: string;\n tenantId?: string;\n workspaceId?: string | null;\n principalType?: SessionPrincipalType;\n authMode?: SessionAuthMode;\n roles?: readonly string[];\n scopes?: readonly string[];\n delegationChain?: readonly SessionDelegationHop[];\n policyTraceId?: string;\n correlationId?: string;\n membershipId?: string;\n policyDecision?: LucernSdkAuthPolicyDecision;\n permit?: Partial<PermitReadyAuthContext>;\n};\n\nexport type CanonicalLucernSdkAuthContext = {\n clerkId?: string;\n principalId: string;\n tenantId: string;\n workspaceId: string;\n principalType: SessionPrincipalType;\n authMode: SessionAuthMode;\n roles: string[];\n scopes: string[];\n delegationChain: SessionDelegationHop[];\n policyTraceId?: string;\n correlationId?: string;\n membershipId?: string;\n permit: PermitReadyAuthContext;\n};\n\nexport class LucernSdkAuthContextError extends Error {\n readonly reason: LucernSdkAuthFailureReason;\n\n constructor(reason: LucernSdkAuthFailureReason, message: string) {\n super(message);\n this.name = \"LucernSdkAuthContextError\";\n this.reason = reason;\n }\n}\n\nfunction cleanString(value: string | null | undefined): string | undefined {\n const normalized = value?.trim();\n return normalized ? normalized : undefined;\n}\n\nfunction cleanStringList(values: readonly string[] | undefined): string[] {\n if (!values) {\n return [];\n }\n return values\n .map((value) => value.trim())\n .filter(\n (value, index, list) =>\n value.length > 0 && list.indexOf(value) === index\n );\n}\n\nfunction requireString(\n value: string | null | undefined,\n reason: LucernSdkAuthFailureReason,\n label: string\n): string {\n const normalized = cleanString(value);\n if (!normalized) {\n throw new LucernSdkAuthContextError(\n reason,\n `Canonical Lucern SDK auth context is missing ${label}.`\n );\n }\n return normalized;\n}\n\nfunction requirePrincipalType(\n principalType: SessionPrincipalType | undefined\n): SessionPrincipalType {\n if (!principalType) {\n throw new LucernSdkAuthContextError(\n \"principal_missing\",\n \"Canonical Lucern SDK auth context is missing principalType.\"\n );\n }\n return principalType;\n}\n\nfunction requireAuthMode(authMode: SessionAuthMode | undefined): SessionAuthMode {\n if (!authMode) {\n throw new LucernSdkAuthContextError(\n \"principal_missing\",\n \"Canonical Lucern SDK auth context is missing authMode.\"\n );\n }\n return authMode;\n}\n\nfunction ensurePermitMatch(args: {\n field: keyof PermitReadyAuthContext;\n expected: string;\n actual?: string;\n}) {\n const actual = cleanString(args.actual);\n if (actual && actual !== args.expected) {\n throw new LucernSdkAuthContextError(\n \"policy_denied\",\n `Canonical Lucern SDK auth context has conflicting Permit ${args.field}.`\n );\n }\n}\n\nexport function normalizeCanonicalLucernAuthContext(\n input: LucernSdkAuthContextInput | undefined\n): CanonicalLucernSdkAuthContext {\n if (!input) {\n throw new LucernSdkAuthContextError(\n \"principal_missing\",\n \"Canonical Lucern SDK auth context is required.\"\n );\n }\n\n if (input.policyDecision === \"deny\") {\n throw new LucernSdkAuthContextError(\n \"policy_denied\",\n \"Canonical Lucern SDK auth context carries a denied policy decision.\"\n );\n }\n\n const principalId = requireString(\n input.principalId,\n \"principal_missing\",\n \"principalId\"\n );\n const tenantId = requireString(input.tenantId, \"tenant_missing\", \"tenantId\");\n const workspaceId = requireString(\n input.workspaceId,\n \"workspace_missing\",\n \"workspaceId\"\n );\n const roles = cleanStringList(input.roles);\n const scopes = cleanStringList(input.scopes);\n const principalType = requirePrincipalType(input.principalType);\n const authMode = requireAuthMode(input.authMode);\n const roleBasedInteractiveAuth =\n authMode === \"interactive_user\" && roles.length > 0;\n if (\n roles.length === 0 ||\n (scopes.length === 0 && !roleBasedInteractiveAuth)\n ) {\n throw new LucernSdkAuthContextError(\n \"membership_missing\",\n \"Canonical Lucern SDK auth context requires non-empty roles and scopes.\"\n );\n }\n\n const subject = cleanString(input.permit?.subject) ?? principalId;\n const tenant = cleanString(input.permit?.tenant) ?? tenantId;\n const workspace = cleanString(input.permit?.workspace) ?? workspaceId;\n\n ensurePermitMatch({\n field: \"subject\",\n expected: principalId,\n actual: subject,\n });\n ensurePermitMatch({ field: \"tenant\", expected: tenantId, actual: tenant });\n ensurePermitMatch({\n field: \"workspace\",\n expected: workspaceId,\n actual: workspace,\n });\n\n const context = input.permit?.context\n ? ({ ...input.permit.context } as JsonObject)\n : undefined;\n\n return {\n clerkId: cleanString(input.clerkId),\n principalId,\n tenantId,\n workspaceId,\n principalType,\n authMode,\n roles,\n scopes,\n delegationChain: input.delegationChain ? [...input.delegationChain] : [],\n policyTraceId: cleanString(input.policyTraceId),\n correlationId: cleanString(input.correlationId),\n membershipId: cleanString(input.membershipId),\n permit: {\n subject,\n tenant,\n workspace,\n resource: cleanString(input.permit?.resource),\n action: cleanString(input.permit?.action),\n relation: cleanString(input.permit?.relation),\n context,\n },\n };\n}\n\nexport function createCanonicalAuthHeaders(\n authContext: CanonicalLucernSdkAuthContext\n): Record<string, string> {\n const headers: Record<string, string> = {\n \"x-lucern-principal-id\": authContext.principalId,\n \"x-lucern-principal-type\": authContext.principalType,\n \"x-lucern-tenant\": authContext.tenantId,\n \"x-lucern-tenant-id\": authContext.tenantId,\n \"x-lucern-workspace\": authContext.workspaceId,\n \"x-lucern-workspace-id\": authContext.workspaceId,\n \"x-lucern-auth-mode\": authContext.authMode,\n \"x-lucern-roles\": authContext.roles.join(\",\"),\n \"x-lucern-scopes\": authContext.scopes.join(\",\"),\n \"x-lucern-permit-context\": JSON.stringify(authContext.permit),\n };\n\n if (authContext.clerkId) {\n headers[\"x-lucern-clerk-id\"] = authContext.clerkId;\n headers[\"x-lucern-user-id\"] = authContext.clerkId;\n }\n if (authContext.delegationChain.length > 0) {\n headers[\"x-lucern-delegation-chain\"] = JSON.stringify(\n authContext.delegationChain\n );\n }\n if (authContext.policyTraceId) {\n headers[\"x-lucern-policy-trace-id\"] = authContext.policyTraceId;\n }\n if (authContext.correlationId) {\n headers[\"x-correlation-id\"] = authContext.correlationId;\n headers[\"x-lucern-correlation-id\"] = authContext.correlationId;\n }\n if (authContext.membershipId) {\n headers[\"x-lucern-membership-id\"] = authContext.membershipId;\n }\n\n return headers;\n}\n","import {\n createCanonicalAuthHeaders,\n LucernSdkAuthContextError,\n normalizeCanonicalLucernAuthContext,\n type LucernSdkAuthContextInput,\n} from \"./authContext\";\nimport type { JsonObject, JsonValue } from \"./types\";\n\n/** Tenant and workspace identifiers used to scope gateway requests. */\nexport type GatewayScope = {\n tenantId?: string;\n workspaceId?: string;\n};\n\n/** Successful response envelope from the platform gateway with correlation metadata. */\nexport type PlatformGatewaySuccess<T> = {\n success: true;\n data: T;\n correlationId: string;\n policyTraceId: string | null;\n idempotentReplay: boolean;\n};\n\n/** Failed response envelope with structured error codes and optional invariant references. */\nexport type PlatformGatewayFailure = {\n success: false;\n /**\n * Error string is the canonical envelope field.\n * Object form is legacy-only compatibility for older gateway responses.\n */\n error:\n | string\n | {\n code: string;\n message: string;\n details?: JsonValue;\n };\n code?: string;\n invariant?: string | null;\n suggestion?: string | null;\n details?: JsonValue;\n legacyError?: {\n code: string;\n message: string;\n details?: JsonValue;\n };\n correlationId: string;\n policyTraceId: string | null;\n};\n\n/** Discriminated union of success and failure gateway responses. */\nexport type PlatformGatewayEnvelope<T> =\n | PlatformGatewaySuccess<T>\n | PlatformGatewayFailure;\n\n/**\n * Structured error thrown when a platform API request fails.\n *\n * Includes HTTP status, machine-readable error code, optional invariant\n * reference, and actionable suggestions for common failure modes.\n */\nexport class LucernApiError extends Error {\n public readonly code: string;\n public readonly status: number;\n public readonly invariant?: string | null;\n public readonly suggestion?: string | null;\n public readonly details?: JsonValue;\n public readonly requestId?: string;\n public readonly correlationId?: string;\n public readonly policyTraceId?: string | null;\n\n constructor(args: {\n code: string;\n message: string;\n status: number;\n invariant?: string | null;\n suggestion?: string | null;\n details?: JsonValue;\n requestId?: string;\n correlationId?: string;\n policyTraceId?: string | null;\n }) {\n super(args.message);\n this.name = \"LucernApiError\";\n this.code = args.code;\n this.status = args.status;\n this.invariant = args.invariant;\n this.suggestion = args.suggestion;\n this.details = args.details;\n this.requestId = args.requestId;\n this.correlationId = args.correlationId;\n this.policyTraceId = args.policyTraceId;\n }\n}\n\n/** Supported HTTP methods for gateway requests. */\nexport type GatewayHttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\ntype FetchLike = (\n input: RequestInfo | URL,\n init?: RequestInit\n) => Promise<Response>;\n\ntype JsonParseAttempt =\n | { ok: true; value: unknown }\n | { ok: false; reason: \"non-json\" | \"invalid-json\"; error?: SyntaxError };\n\n/** Context passed to the `onRequest` hook before each gateway request attempt. */\nexport type GatewayRequestHookContext = {\n requestId: string;\n attempt: number;\n maxRetries: number;\n method: GatewayHttpMethod;\n path: string;\n url: string;\n headers: Headers;\n body?: string;\n timeoutMs: number;\n};\n\n/** Context passed to the `onResponse` hook after each gateway request attempt (including retries and failures). */\nexport type GatewayResponseHookContext = GatewayRequestHookContext & {\n durationMs: number;\n status?: number;\n response?: Response;\n error?: unknown;\n correlationId?: string;\n policyTraceId?: string | null;\n idempotentReplay?: boolean;\n retryAfterMs?: number | null;\n willRetry: boolean;\n};\n\nexport type GatewayClientEnvironment = \"sandbox\" | \"production\";\n\n/**\n * Low-level transport configuration for the platform gateway client.\n *\n * Most developers should use {@link createLucernClient} instead, which wraps\n * this config with higher-level conveniences like `apiKey` and `environment`.\n */\nexport type GatewayClientConfig = {\n baseUrl?: string;\n fetchImpl?: FetchLike;\n /** Lucern tenant API key or service API key. Sent as `x-lucern-key`. */\n apiKey?: string;\n /**\n * Lucern platform session token. This is not a Clerk JWT.\n * Server-side tenant proxies should normally send `apiKey` plus `clerkId`.\n */\n userToken?: string;\n /** Gateway environment label for legacy sandbox/production routing. */\n environment?: GatewayClientEnvironment;\n /** Clerk subject for the current end user. */\n clerkId?: string;\n /** Optional explicit user subject. Defaults to `clerkId` when omitted. */\n userId?: string;\n /** Optional deployment host hint for front-door routing. */\n deploymentHost?: string;\n getAuthHeaders?:\n | (() => Promise<Record<string, string>>)\n | (() => Record<string, string>);\n /**\n * Canonical Master Control identity tuple applied to every SDK request.\n * Use this for tenant/workspace-scoped graph and identity operations.\n */\n authContext?:\n | LucernSdkAuthContextInput\n | (() => Promise<LucernSdkAuthContextInput | undefined>)\n | (() => LucernSdkAuthContextInput | undefined);\n /** When true, requests fail before fetch if `authContext` is absent. */\n requireCanonicalAuthContext?: boolean;\n /** Max retries for transient errors (5xx, network). Defaults to 2. */\n maxRetries?: number;\n /** Request timeout in ms. Defaults to 15000. */\n timeoutMs?: number;\n /** Optional timeout overrides by HTTP method. */\n timeoutMsByMethod?: Partial<Record<GatewayHttpMethod, number>>;\n /** Optional request ID factory used for correlation headers. */\n requestIdFactory?: () => string;\n /** Invoked before each request attempt, including retries. */\n onRequest?:\n | ((context: GatewayRequestHookContext) => void)\n | ((context: GatewayRequestHookContext) => Promise<void>);\n /** Invoked after each request attempt, including retries and failures. */\n onResponse?:\n | ((context: GatewayResponseHookContext) => void)\n | ((context: GatewayResponseHookContext) => Promise<void>);\n};\n\n/**\n * Serialize a gateway query object into a URL query string.\n */\nexport function toQueryString(\n scope: GatewayScope & Record<string, string | number | boolean | undefined>\n): string {\n const params = new URLSearchParams();\n if (scope.tenantId) {\n params.set(\"tenantId\", scope.tenantId);\n }\n if (scope.workspaceId) {\n params.set(\"workspaceId\", scope.workspaceId);\n }\n for (const [key, value] of Object.entries(scope)) {\n if (key === \"tenantId\" || key === \"workspaceId\") {\n continue;\n }\n if (value === undefined) {\n continue;\n }\n params.set(key, String(value));\n }\n const serialized = params.toString();\n return serialized.length > 0 ? `?${serialized}` : \"\";\n}\n\nfunction fillRandomBytes(length: number): Uint8Array {\n const bytes = new Uint8Array(length);\n if (typeof globalThis.crypto?.getRandomValues === \"function\") {\n globalThis.crypto.getRandomValues(bytes);\n return bytes;\n }\n\n for (let index = 0; index < length; index += 1) {\n bytes[index] = Math.floor(Math.random() * 256);\n }\n return bytes;\n}\n\nfunction generatePortableRequestId(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n\n const bytes = fillRandomBytes(16);\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = Array.from(bytes, (value) => value.toString(16).padStart(2, \"0\"));\n return `${hex.slice(0, 4).join(\"\")}-${hex.slice(4, 6).join(\"\")}-${hex.slice(\n 6,\n 8\n ).join(\"\")}-${hex.slice(8, 10).join(\"\")}-${hex.slice(10).join(\"\")}`;\n}\n\n/**\n * Generate a random idempotency key for retry-safe writes.\n */\nexport const randomIdempotencyKey = generatePortableRequestId;\n\nfunction isRetryableStatus(status: number): boolean {\n return status >= 500 || status === 408 || status === 429;\n}\n\nfunction fallbackErrorCode(status: number): string {\n if (status === 401) {\n return \"AUTHENTICATION_REQUIRED\";\n }\n if (status === 403) {\n return \"FORBIDDEN\";\n }\n if (status === 404) {\n return \"NOT_FOUND\";\n }\n if (status === 408) {\n return \"UPSTREAM_ERROR\";\n }\n if (status === 409) {\n return \"CONFLICT\";\n }\n if (status === 429) {\n return \"RATE_LIMIT_EXCEEDED\";\n }\n if (status >= 500) {\n return \"UPSTREAM_ERROR\";\n }\n return \"INTERNAL_ERROR\";\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction parseRetryAfterMs(value: string | null): number | null {\n if (!value) {\n return null;\n }\n const trimmed = value.trim();\n if (!trimmed) {\n return null;\n }\n const numeric = Number(trimmed);\n if (Number.isFinite(numeric)) {\n return Math.max(0, Math.round(numeric * 1000));\n }\n const parsedDate = Date.parse(trimmed);\n if (Number.isFinite(parsedDate)) {\n return Math.max(0, parsedDate - Date.now());\n }\n return null;\n}\n\nfunction computeRetryDelayMs(args: {\n attempt: number;\n status?: number;\n retryAfterMs?: number | null;\n}): number {\n const baseDelay =\n args.status === 429\n ? Math.max(\n args.retryAfterMs ?? 0,\n Math.min(1000 * 2 ** args.attempt, 10_000)\n )\n : Math.min(1000 * 2 ** args.attempt, 4000);\n\n if (args.status !== 429) {\n return baseDelay;\n }\n\n const jitterWindow = Math.max(250, Math.round(baseDelay * 0.25));\n return baseDelay + Math.round(Math.random() * jitterWindow);\n}\n\nfunction timeoutError(timeoutMs: number): Error {\n const error = new Error(`Request timed out after ${timeoutMs}ms`);\n error.name = \"AbortError\";\n return error;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction readPolicySummaryFromDetails(details?: JsonValue): string | null {\n if (!isRecord(details)) {\n return null;\n }\n\n const directSummary = details.summary;\n if (typeof directSummary === \"string\" && directSummary.trim().length > 0) {\n return directSummary.trim();\n }\n\n const policy = details.policy;\n if (!isRecord(policy)) {\n return null;\n }\n\n const explanation = policy.explanation;\n if (!isRecord(explanation)) {\n return null;\n }\n\n const nestedSummary = explanation.summary;\n if (typeof nestedSummary === \"string\" && nestedSummary.trim().length > 0) {\n return nestedSummary.trim();\n }\n\n return null;\n}\n\nasync function resolveConfiguredAuthContext(\n authContext: GatewayClientConfig[\"authContext\"]\n): Promise<LucernSdkAuthContextInput | undefined> {\n if (typeof authContext === \"function\") {\n return await authContext();\n }\n return authContext;\n}\n\nfunction mergeHeaderRecord(\n base: Record<string, string>,\n addition: Record<string, string>\n): Record<string, string> {\n const headers = new Headers(base);\n for (const [key, value] of Object.entries(addition)) {\n const existing = headers.get(key);\n if (existing !== null && existing !== value) {\n throw new LucernSdkAuthContextError(\n \"policy_denied\",\n `Canonical Lucern SDK auth context conflicts with existing ${key} header.`\n );\n }\n headers.set(key, value);\n }\n return Object.fromEntries(headers.entries());\n}\n\nfunction cleanHeaderValue(value: string | null | undefined): string | undefined {\n const normalized = value?.trim();\n return normalized ? normalized : undefined;\n}\n\n/**\n * Create the transport client used by all SDK modules.\n */\nexport function createGatewayRequestClient(config: GatewayClientConfig = {}) {\n const fetchImpl = config.fetchImpl ?? fetch;\n const baseUrl = config.baseUrl?.replace(/\\/+$/, \"\") ?? \"\";\n const maxRetries = config.maxRetries ?? 2;\n const requestIdFactory = config.requestIdFactory ?? (() => generatePortableRequestId());\n\n async function resolveAuthHeaders(): Promise<Record<string, string>> {\n const provided = config.getAuthHeaders ? await config.getAuthHeaders() : {};\n const headers = new Headers(provided);\n const setIfAbsent = (name: string, value: string | undefined) => {\n const normalized = cleanHeaderValue(value);\n if (normalized && !headers.has(name)) {\n headers.set(name, normalized);\n }\n };\n\n setIfAbsent(\"x-lucern-key\", config.apiKey);\n setIfAbsent(\"x-lucern-session-token\", config.userToken);\n setIfAbsent(\"x-lucern-environment\", config.environment);\n setIfAbsent(\"x-lucern-clerk-id\", config.clerkId);\n setIfAbsent(\"x-lucern-user-id\", config.userId ?? config.clerkId);\n setIfAbsent(\"x-lucern-deployment-host\", config.deploymentHost);\n\n const base = Object.fromEntries(headers.entries());\n const authContextInput = await resolveConfiguredAuthContext(\n config.authContext\n );\n if (!authContextInput && !config.requireCanonicalAuthContext) {\n return base;\n }\n const authContext = normalizeCanonicalLucernAuthContext(authContextInput);\n return mergeHeaderRecord(base, createCanonicalAuthHeaders(authContext));\n }\n\n async function fetchWithTimeout(\n url: string,\n init: RequestInit,\n timeoutMs: number\n ): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await fetchImpl(url, { ...init, signal: controller.signal });\n } catch (error) {\n if (controller.signal.aborted) {\n throw timeoutError(timeoutMs);\n }\n throw error;\n } finally {\n clearTimeout(timer);\n }\n }\n\n async function parsePayload<T>(\n response: Response\n ): Promise<PlatformGatewayEnvelope<T> | null> {\n const text = await response.text();\n if (!text) {\n return null;\n }\n const parsed = tryParseGatewayEnvelopeJson(text);\n if (!parsed.ok) {\n return null;\n }\n return isRecord(parsed.value)\n ? (parsed.value as PlatformGatewayEnvelope<T>)\n : null;\n }\n\n function resolveTimeoutMs(\n method: GatewayHttpMethod,\n requestTimeoutMs?: number\n ): number {\n if (typeof requestTimeoutMs === \"number\") {\n return requestTimeoutMs;\n }\n const methodTimeoutMs = config.timeoutMsByMethod?.[method];\n if (typeof methodTimeoutMs === \"number\") {\n return methodTimeoutMs;\n }\n return config.timeoutMs ?? 15_000;\n }\n\n function tryParseGatewayEnvelopeJson(text: string): JsonParseAttempt {\n const trimmed = text.trim();\n if (!trimmed.startsWith(\"{\") && !trimmed.startsWith(\"[\")) {\n return { ok: false, reason: \"non-json\" };\n }\n try {\n return { ok: true, value: JSON.parse(trimmed) };\n } catch (error) {\n if (error instanceof SyntaxError) {\n return { ok: false, reason: \"invalid-json\", error };\n }\n throw error;\n }\n }\n\n function buildApiError(args: {\n requestId: string;\n response: Response;\n failure?: PlatformGatewayFailure | null;\n }): LucernApiError {\n const failure = args.failure;\n const legacyError =\n failure && isRecord(failure.error) ? failure.error : failure?.legacyError;\n const correlationId =\n failure?.correlationId ??\n args.response.headers.get(\"x-lucern-correlation-id\")?.trim() ??\n args.requestId;\n const policyTraceId =\n failure?.policyTraceId ??\n args.response.headers.get(\"x-lucern-policy-trace-id\")?.trim() ??\n null;\n const details = failure?.details ?? legacyError?.details;\n const policySummary = readPolicySummaryFromDetails(details);\n const failureMessage =\n typeof failure?.error === \"string\"\n ? failure.error\n : legacyError?.message;\n\n return new LucernApiError({\n code:\n failure?.code ??\n legacyError?.code ??\n fallbackErrorCode(args.response.status),\n message:\n policySummary ??\n failureMessage ??\n (args.response.ok\n ? \"Platform API returned an invalid success payload.\"\n : \"Platform API request failed.\"),\n status: args.response.status,\n invariant: failure?.invariant,\n suggestion: failure?.suggestion,\n details,\n requestId: args.requestId,\n correlationId,\n policyTraceId,\n });\n }\n\n async function request<T>(args: {\n path: string;\n method?: GatewayHttpMethod;\n body?: JsonObject;\n idempotencyKey?: string;\n requestId?: string;\n timeoutMs?: number;\n }): Promise<PlatformGatewaySuccess<T>> {\n const authHeaders = await resolveAuthHeaders();\n const method = args.method ?? \"GET\";\n const timeoutMs = resolveTimeoutMs(method, args.timeoutMs);\n const headers = new Headers({\n \"content-type\": \"application/json\",\n ...authHeaders,\n });\n if (args.idempotencyKey) {\n headers.set(\"idempotency-key\", args.idempotencyKey);\n }\n const requestId =\n headers.get(\"x-correlation-id\")?.trim() ||\n headers.get(\"x-request-id\")?.trim() ||\n args.requestId ||\n requestIdFactory();\n if (!headers.has(\"x-correlation-id\") && !headers.has(\"x-request-id\")) {\n headers.set(\"x-correlation-id\", requestId);\n }\n\n const url = `${baseUrl}${args.path}`;\n const serializedBody = args.body ? JSON.stringify(args.body) : undefined;\n const init: RequestInit = {\n method,\n headers,\n body: serializedBody,\n };\n\n let lastError: unknown;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const hookRequestContext: GatewayRequestHookContext = {\n requestId,\n attempt,\n maxRetries,\n method,\n path: args.path,\n url,\n headers: new Headers(headers),\n body: serializedBody,\n timeoutMs,\n };\n await config.onRequest?.(hookRequestContext);\n const startedAt = Date.now();\n try {\n const response = await fetchWithTimeout(url, init, timeoutMs);\n const responseClone = response.clone();\n const payload = await parsePayload<T>(response);\n const retryAfterMs = parseRetryAfterMs(\n response.headers.get(\"Retry-After\")\n );\n\n if (!response.ok || !payload?.success) {\n const failure =\n payload && !payload.success ? (payload as PlatformGatewayFailure) : null;\n const apiError = buildApiError({\n requestId,\n response,\n failure,\n });\n const willRetry = attempt < maxRetries && isRetryableStatus(response.status);\n\n await config.onResponse?.({\n ...hookRequestContext,\n durationMs: Date.now() - startedAt,\n status: response.status,\n response: responseClone,\n error: apiError,\n correlationId: apiError.correlationId ?? requestId,\n policyTraceId: apiError.policyTraceId ?? null,\n retryAfterMs,\n willRetry,\n });\n\n if (willRetry) {\n lastError = apiError;\n await delay(\n computeRetryDelayMs({\n attempt,\n status: response.status,\n retryAfterMs,\n })\n );\n continue;\n }\n\n throw apiError;\n }\n\n const successPayload = payload as PlatformGatewaySuccess<T>;\n await config.onResponse?.({\n ...hookRequestContext,\n durationMs: Date.now() - startedAt,\n status: response.status,\n response: responseClone,\n correlationId:\n successPayload.correlationId ??\n response.headers.get(\"x-lucern-correlation-id\")?.trim() ??\n requestId,\n policyTraceId:\n successPayload.policyTraceId ??\n response.headers.get(\"x-lucern-policy-trace-id\")?.trim() ??\n null,\n idempotentReplay: successPayload.idempotentReplay,\n retryAfterMs,\n willRetry: false,\n });\n\n return successPayload;\n } catch (fetchError) {\n if (fetchError instanceof LucernApiError) {\n throw fetchError;\n }\n const willRetry = attempt < maxRetries;\n await config.onResponse?.({\n ...hookRequestContext,\n durationMs: Date.now() - startedAt,\n error: fetchError,\n correlationId: requestId,\n policyTraceId: null,\n willRetry,\n });\n lastError = fetchError;\n if (willRetry) {\n await delay(computeRetryDelayMs({ attempt }));\n }\n }\n }\n\n throw lastError instanceof Error\n ? lastError\n : new Error(\"Platform API request failed after retries.\");\n }\n\n return {\n request,\n };\n}\n","import {\n createGatewayRequestClient,\n type GatewayClientConfig,\n} from \"./coreClient\";\nimport type {\n CompileContextInput,\n PublicCompiledContext,\n} from \"./contextTypes\";\nimport type { JsonObject } from \"./types\";\n\n/** Configuration for the context client. */\nexport type ContextClientConfig = GatewayClientConfig;\n\n/** Alias for the compiled context payload returned by the gateway. */\nexport type CompileContextResponse = PublicCompiledContext;\n\n/** Internal request shape for the context compile endpoint. */\ntype ContextClientRequest = {\n path: \"/api/platform/v1/context/compile\";\n method: \"POST\";\n body: Record<string, unknown>;\n};\n\nfunction cleanString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim().length > 0\n ? value.trim()\n : undefined;\n}\n\nfunction cleanNumber(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction cleanBoolean(value: unknown): boolean | undefined {\n return typeof value === \"boolean\" ? value : undefined;\n}\n\nfunction buildCompileContextRequest(\n topicIdOrInput: string | CompileContextInput = {},\n input: CompileContextInput = {}\n): ContextClientRequest {\n const effectiveInput =\n typeof topicIdOrInput === \"string\" ? input : topicIdOrInput;\n const payload: Record<string, unknown> = {};\n\n const topicId =\n typeof topicIdOrInput === \"string\"\n ? cleanString(topicIdOrInput)\n : cleanString(effectiveInput.topicId);\n if (topicId) {\n payload.topicId = topicId;\n }\n\n const query = cleanString(effectiveInput.query);\n if (query) {\n payload.query = query;\n }\n\n const budget =\n cleanNumber(effectiveInput.budget) ?? cleanNumber(effectiveInput.tokenBudget);\n if (budget !== undefined) {\n payload.budget = budget;\n }\n\n const ranking =\n cleanString(effectiveInput.ranking) ?? cleanString(effectiveInput.rankingProfile);\n if (ranking) {\n payload.ranking = ranking;\n }\n\n const limit = cleanNumber(effectiveInput.limit);\n if (limit !== undefined) {\n payload.limit = limit;\n }\n\n const maxDepth = cleanNumber(effectiveInput.maxDepth);\n if (maxDepth !== undefined) {\n payload.maxDepth = maxDepth;\n }\n\n const includeEntities = cleanBoolean(effectiveInput.includeEntities);\n if (includeEntities !== undefined) {\n payload.includeEntities = includeEntities;\n }\n\n const mode = cleanString(effectiveInput.mode);\n if (mode) {\n payload.mode = mode;\n }\n\n const includeFailures = cleanBoolean(effectiveInput.includeFailures);\n if (includeFailures !== undefined) {\n payload.includeFailures = includeFailures;\n }\n\n const worktreeId = cleanString(effectiveInput.worktreeId);\n if (worktreeId) {\n payload.worktreeId = worktreeId;\n }\n\n const sessionId = cleanString(effectiveInput.sessionId);\n if (sessionId) {\n payload.sessionId = sessionId;\n }\n\n if (\n Array.isArray(effectiveInput.packWeightOverrides) &&\n effectiveInput.packWeightOverrides.length > 0\n ) {\n payload.packWeightOverrides = effectiveInput.packWeightOverrides;\n }\n\n return {\n path: \"/api/platform/v1/context/compile\",\n method: \"POST\",\n body: payload,\n };\n}\n\n/**\n * Create the context client for compiling reasoning context packs.\n * @param config - Gateway transport configuration.\n * @returns An object with a `compile` method for building context packs.\n */\nexport function createContextClient(config: ContextClientConfig = {}) {\n const gateway = createGatewayRequestClient(config);\n\n return {\n /**\n * Compile a focused reasoning context pack.\n * @param topicIdOrInput - Optional topic ID, or compile input for query-first resolution.\n * @param input - Optional compile parameters (query, budget, ranking, etc.).\n * @returns The compiled context payload with beliefs, questions, and evidence.\n */\n async compile(\n topicIdOrInput: string | CompileContextInput = {},\n input: CompileContextInput = {}\n ) {\n const request = buildCompileContextRequest(topicIdOrInput, input);\n return gateway.request<CompileContextResponse>({\n ...request,\n body: request.body as JsonObject,\n });\n },\n async compileByQuery(input: CompileContextInput = {}) {\n const request = buildCompileContextRequest(input);\n return gateway.request<CompileContextResponse>({\n ...request,\n body: request.body as JsonObject,\n });\n },\n };\n}\n\nexport type { CompileContextInput, PublicCompiledContext } from \"./contextTypes\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/coreClient.ts","../src/contextClient.ts"],"names":[],"mappings":";AAuDO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA,EACxB,IAAA;AAAA,EACA,MAAA;AAAA,EACA,SAAA;AAAA,EACA,UAAA;AAAA,EACA,OAAA;AAAA,EACA,SAAA;AAAA,EACA,aAAA;AAAA,EACA,aAAA;AAAA,EAEhB,YAAY,IAAA,EAUT;AACD,IAAA,KAAA,CAAM,KAAK,OAAO,CAAA;AAClB,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AACZ,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AACnB,IAAA,IAAA,CAAK,YAAY,IAAA,CAAK,SAAA;AACtB,IAAA,IAAA,CAAK,aAAa,IAAA,CAAK,UAAA;AACvB,IAAA,IAAA,CAAK,UAAU,IAAA,CAAK,OAAA;AACpB,IAAA,IAAA,CAAK,YAAY,IAAA,CAAK,SAAA;AACtB,IAAA,IAAA,CAAK,gBAAgB,IAAA,CAAK,aAAA;AAC1B,IAAA,IAAA,CAAK,gBAAgB,IAAA,CAAK,aAAA;AAAA,EAC5B;AACF,CAAA;AA4FA,SAAS,gBAAgB,MAAA,EAA4B;AACnD,EAAA,MAAM,KAAA,GAAQ,IAAI,UAAA,CAAW,MAAM,CAAA;AACnC,EAAA,IAAI,OAAO,UAAA,CAAW,MAAA,EAAQ,eAAA,KAAoB,UAAA,EAAY;AAC5D,IAAA,UAAA,CAAW,MAAA,CAAO,gBAAgB,KAAK,CAAA;AACvC,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,KAAA,IAAS,KAAA,GAAQ,CAAA,EAAG,KAAA,GAAQ,MAAA,EAAQ,SAAS,CAAA,EAAG;AAC9C,IAAA,KAAA,CAAM,KAAK,CAAA,GAAI,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B,KAAK,KAAA,CAAM,mBAAA,CAAoB,SAAS,CAAA,EAAG;AACpF,IAAA,OAAA,CAAQ,sBAAsB,KAAA,CAAM,mBAAA;AAAA,EACtC;AAEA,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,kCAAA;AAAA,IACN,MAAA,EAAQ,MAAA;AAAA,IACR,IAAA,EAAM;AAAA,GACR;AACF;AAOO,SAAS,mBAAA,CAAoB,MAAA,GAA8B,EAAC,EAAG;AACpE,EAAA,MAAM,OAAA,GAAU,2BAA2B,MAAM,CAAA;AAEjD,EAAA,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOL,MAAM,OAAA,CAAQ,OAAA,EAAiB,KAAA,GAA6B,EAAC,EAAG;AAC9D,MAAA,MAAM,OAAA,GAAU,0BAAA,CAA2B,OAAA,EAAS,KAAK,CAAA;AACzD,MAAA,OAAO,QAAQ,OAAA,CAAgC;AAAA,QAC7C,GAAG,OAAA;AAAA,QACH,MAAM,OAAA,CAAQ;AAAA,OACf,CAAA;AAAA,IACH;AAAA,GACF;AACF","file":"contextClient.js","sourcesContent":["import type { JsonObject, JsonValue } from \"./types\";\n\n/** Tenant and workspace identifiers used to scope gateway requests. */\nexport type GatewayScope = {\n tenantId?: string;\n workspaceId?: string;\n};\n\n/** Successful response envelope from the platform gateway with correlation metadata. */\nexport type PlatformGatewaySuccess<T> = {\n success: true;\n data: T;\n correlationId: string;\n policyTraceId: string | null;\n idempotentReplay: boolean;\n};\n\n/** Failed response envelope with structured error codes and optional invariant references. */\nexport type PlatformGatewayFailure = {\n success: false;\n /**\n * Error string is the canonical envelope field.\n * Object form is legacy-only compatibility for older gateway responses.\n */\n error:\n | string\n | {\n code: string;\n message: string;\n details?: JsonValue;\n };\n code?: string;\n invariant?: string | null;\n suggestion?: string | null;\n details?: JsonValue;\n legacyError?: {\n code: string;\n message: string;\n details?: JsonValue;\n };\n correlationId: string;\n policyTraceId: string | null;\n};\n\n/** Discriminated union of success and failure gateway responses. */\nexport type PlatformGatewayEnvelope<T> =\n | PlatformGatewaySuccess<T>\n | PlatformGatewayFailure;\n\n/**\n * Structured error thrown when a platform API request fails.\n *\n * Includes HTTP status, machine-readable error code, optional invariant\n * reference, and actionable suggestions for common failure modes.\n */\nexport class LucernApiError extends Error {\n public readonly code: string;\n public readonly status: number;\n public readonly invariant?: string | null;\n public readonly suggestion?: string | null;\n public readonly details?: JsonValue;\n public readonly requestId?: string;\n public readonly correlationId?: string;\n public readonly policyTraceId?: string | null;\n\n constructor(args: {\n code: string;\n message: string;\n status: number;\n invariant?: string | null;\n suggestion?: string | null;\n details?: JsonValue;\n requestId?: string;\n correlationId?: string;\n policyTraceId?: string | null;\n }) {\n super(args.message);\n this.name = \"LucernApiError\";\n this.code = args.code;\n this.status = args.status;\n this.invariant = args.invariant;\n this.suggestion = args.suggestion;\n this.details = args.details;\n this.requestId = args.requestId;\n this.correlationId = args.correlationId;\n this.policyTraceId = args.policyTraceId;\n }\n}\n\n/** Supported HTTP methods for gateway requests. */\nexport type GatewayHttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\ntype FetchLike = (\n input: RequestInfo | URL,\n init?: RequestInit\n) => Promise<Response>;\n\n/** Context passed to the `onRequest` hook before each gateway request attempt. */\nexport type GatewayRequestHookContext = {\n requestId: string;\n attempt: number;\n maxRetries: number;\n method: GatewayHttpMethod;\n path: string;\n url: string;\n headers: Headers;\n body?: string;\n timeoutMs: number;\n};\n\n/** Context passed to the `onResponse` hook after each gateway request attempt (including retries and failures). */\nexport type GatewayResponseHookContext = GatewayRequestHookContext & {\n durationMs: number;\n status?: number;\n response?: Response;\n error?: unknown;\n correlationId?: string;\n policyTraceId?: string | null;\n idempotentReplay?: boolean;\n retryAfterMs?: number | null;\n willRetry: boolean;\n};\n\n/**\n * Low-level transport configuration for the platform gateway client.\n *\n * Most developers should use {@link createLucernClient} instead, which wraps\n * this config with higher-level conveniences like `apiKey` and `environment`.\n */\nexport type GatewayClientConfig = {\n baseUrl?: string;\n fetchImpl?: FetchLike;\n getAuthHeaders?:\n | (() => Promise<Record<string, string>>)\n | (() => Record<string, string>);\n /** Max retries for transient errors (5xx, network). Defaults to 2. */\n maxRetries?: number;\n /** Request timeout in ms. Defaults to 15000. */\n timeoutMs?: number;\n /** Optional timeout overrides by HTTP method. */\n timeoutMsByMethod?: Partial<Record<GatewayHttpMethod, number>>;\n /** Optional request ID factory used for correlation headers. */\n requestIdFactory?: () => string;\n /** Invoked before each request attempt, including retries. */\n onRequest?:\n | ((context: GatewayRequestHookContext) => void)\n | ((context: GatewayRequestHookContext) => Promise<void>);\n /** Invoked after each request attempt, including retries and failures. */\n onResponse?:\n | ((context: GatewayResponseHookContext) => void)\n | ((context: GatewayResponseHookContext) => Promise<void>);\n};\n\n/**\n * Serialize a gateway query object into a URL query string.\n */\nexport function toQueryString(\n scope: GatewayScope & Record<string, string | number | boolean | undefined>\n): string {\n const params = new URLSearchParams();\n if (scope.tenantId) {\n params.set(\"tenantId\", scope.tenantId);\n }\n if (scope.workspaceId) {\n params.set(\"workspaceId\", scope.workspaceId);\n }\n for (const [key, value] of Object.entries(scope)) {\n if (key === \"tenantId\" || key === \"workspaceId\") {\n continue;\n }\n if (value === undefined) {\n continue;\n }\n params.set(key, String(value));\n }\n const serialized = params.toString();\n return serialized.length > 0 ? `?${serialized}` : \"\";\n}\n\nfunction fillRandomBytes(length: number): Uint8Array {\n const bytes = new Uint8Array(length);\n if (typeof globalThis.crypto?.getRandomValues === \"function\") {\n globalThis.crypto.getRandomValues(bytes);\n return bytes;\n }\n\n for (let index = 0; index < length; index += 1) {\n bytes[index] = Math.floor(Math.random() * 256);\n }\n return bytes;\n}\n\nfunction generatePortableRequestId(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n\n const bytes = fillRandomBytes(16);\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = Array.from(bytes, (value) => value.toString(16).padStart(2, \"0\"));\n return `${hex.slice(0, 4).join(\"\")}-${hex.slice(4, 6).join(\"\")}-${hex.slice(\n 6,\n 8\n ).join(\"\")}-${hex.slice(8, 10).join(\"\")}-${hex.slice(10).join(\"\")}`;\n}\n\n/**\n * Generate a random idempotency key for retry-safe writes.\n */\nexport function randomIdempotencyKey(): string {\n return generatePortableRequestId();\n}\n\nfunction isRetryableStatus(status: number): boolean {\n return status >= 500 || status === 408 || status === 429;\n}\n\nfunction fallbackErrorCode(status: number): string {\n if (status === 401) {\n return \"AUTHENTICATION_REQUIRED\";\n }\n if (status === 403) {\n return \"FORBIDDEN\";\n }\n if (status === 404) {\n return \"NOT_FOUND\";\n }\n if (status === 408) {\n return \"UPSTREAM_ERROR\";\n }\n if (status === 409) {\n return \"CONFLICT\";\n }\n if (status === 429) {\n return \"RATE_LIMIT_EXCEEDED\";\n }\n if (status >= 500) {\n return \"UPSTREAM_ERROR\";\n }\n return \"INTERNAL_ERROR\";\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction parseRetryAfterMs(value: string | null): number | null {\n if (!value) {\n return null;\n }\n const trimmed = value.trim();\n if (!trimmed) {\n return null;\n }\n const numeric = Number(trimmed);\n if (Number.isFinite(numeric)) {\n return Math.max(0, Math.round(numeric * 1000));\n }\n const parsedDate = Date.parse(trimmed);\n if (Number.isFinite(parsedDate)) {\n return Math.max(0, parsedDate - Date.now());\n }\n return null;\n}\n\nfunction computeRetryDelayMs(args: {\n attempt: number;\n status?: number;\n retryAfterMs?: number | null;\n}): number {\n const baseDelay =\n args.status === 429\n ? Math.max(\n args.retryAfterMs ?? 0,\n Math.min(1000 * 2 ** args.attempt, 10_000)\n )\n : Math.min(1000 * 2 ** args.attempt, 4000);\n\n if (args.status !== 429) {\n return baseDelay;\n }\n\n const jitterWindow = Math.max(250, Math.round(baseDelay * 0.25));\n return baseDelay + Math.round(Math.random() * jitterWindow);\n}\n\nfunction timeoutError(timeoutMs: number): Error {\n const error = new Error(`Request timed out after ${timeoutMs}ms`);\n error.name = \"AbortError\";\n return error;\n}\n\nfunction readPolicySummaryFromDetails(details?: JsonValue): string | null {\n if (!details || typeof details !== \"object\" || Array.isArray(details)) {\n return null;\n }\n\n const directSummary = (details as { summary?: JsonValue }).summary;\n if (typeof directSummary === \"string\" && directSummary.trim().length > 0) {\n return directSummary.trim();\n }\n\n const policy = (details as { policy?: JsonValue }).policy;\n if (!policy || typeof policy !== \"object\" || Array.isArray(policy)) {\n return null;\n }\n\n const explanation = (policy as { explanation?: JsonValue }).explanation;\n if (!explanation || typeof explanation !== \"object\" || Array.isArray(explanation)) {\n return null;\n }\n\n const nestedSummary = (explanation as { summary?: JsonValue }).summary;\n if (typeof nestedSummary === \"string\" && nestedSummary.trim().length > 0) {\n return nestedSummary.trim();\n }\n\n return null;\n}\n\n/**\n * Create the transport client used by all SDK modules.\n */\nexport function createGatewayRequestClient(config: GatewayClientConfig = {}) {\n const fetchImpl = config.fetchImpl ?? fetch;\n const baseUrl = config.baseUrl?.replace(/\\/+$/, \"\") ?? \"\";\n const maxRetries = config.maxRetries ?? 2;\n const requestIdFactory = config.requestIdFactory ?? (() => generatePortableRequestId());\n\n async function resolveAuthHeaders(): Promise<Record<string, string>> {\n if (!config.getAuthHeaders) {\n return {};\n }\n return await config.getAuthHeaders();\n }\n\n async function fetchWithTimeout(\n url: string,\n init: RequestInit,\n timeoutMs: number\n ): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await fetchImpl(url, { ...init, signal: controller.signal });\n } catch (error) {\n if (controller.signal.aborted) {\n throw timeoutError(timeoutMs);\n }\n throw error;\n } finally {\n clearTimeout(timer);\n }\n }\n\n async function parsePayload<T>(\n response: Response\n ): Promise<PlatformGatewayEnvelope<T> | null> {\n const text = await response.text();\n if (!text) {\n return null;\n }\n try {\n return JSON.parse(text) as PlatformGatewayEnvelope<T>;\n } catch {\n return null;\n }\n }\n\n function resolveTimeoutMs(\n method: GatewayHttpMethod,\n requestTimeoutMs?: number\n ): number {\n if (typeof requestTimeoutMs === \"number\") {\n return requestTimeoutMs;\n }\n const methodTimeoutMs = config.timeoutMsByMethod?.[method];\n if (typeof methodTimeoutMs === \"number\") {\n return methodTimeoutMs;\n }\n return config.timeoutMs ?? 15_000;\n }\n\n function buildApiError(args: {\n requestId: string;\n response: Response;\n failure?: PlatformGatewayFailure | null;\n }): LucernApiError {\n const failure = args.failure;\n const legacyError =\n failure && typeof failure.error === \"object\" && failure.error !== null\n ? failure.error\n : failure?.legacyError;\n const correlationId =\n failure?.correlationId ??\n args.response.headers.get(\"x-lucern-correlation-id\")?.trim() ??\n args.requestId;\n const policyTraceId =\n failure?.policyTraceId ??\n args.response.headers.get(\"x-lucern-policy-trace-id\")?.trim() ??\n null;\n const details = failure?.details ?? legacyError?.details;\n const policySummary = readPolicySummaryFromDetails(details);\n\n return new LucernApiError({\n code: failure?.code ?? legacyError?.code ?? fallbackErrorCode(args.response.status),\n message:\n policySummary ??\n (typeof failure?.error === \"string\"\n ? failure.error\n : legacyError?.message ??\n (args.response.ok\n ? \"Platform API returned an invalid success payload.\"\n : \"Platform API request failed.\")),\n status: args.response.status,\n invariant: failure?.invariant,\n suggestion: failure?.suggestion,\n details,\n requestId: args.requestId,\n correlationId,\n policyTraceId,\n });\n }\n\n async function request<T>(args: {\n path: string;\n method?: GatewayHttpMethod;\n body?: JsonObject;\n idempotencyKey?: string;\n requestId?: string;\n timeoutMs?: number;\n }): Promise<PlatformGatewaySuccess<T>> {\n const authHeaders = await resolveAuthHeaders();\n const method = args.method ?? \"GET\";\n const timeoutMs = resolveTimeoutMs(method, args.timeoutMs);\n const headers = new Headers({\n \"content-type\": \"application/json\",\n ...authHeaders,\n });\n if (args.idempotencyKey) {\n headers.set(\"idempotency-key\", args.idempotencyKey);\n }\n const requestId =\n headers.get(\"x-correlation-id\")?.trim() ||\n headers.get(\"x-request-id\")?.trim() ||\n args.requestId ||\n requestIdFactory();\n if (!headers.has(\"x-correlation-id\") && !headers.has(\"x-request-id\")) {\n headers.set(\"x-correlation-id\", requestId);\n }\n\n const url = `${baseUrl}${args.path}`;\n const serializedBody = args.body ? JSON.stringify(args.body) : undefined;\n const init: RequestInit = {\n method,\n headers,\n body: serializedBody,\n };\n\n let lastError: unknown;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const hookRequestContext: GatewayRequestHookContext = {\n requestId,\n attempt,\n maxRetries,\n method,\n path: args.path,\n url,\n headers: new Headers(headers),\n body: serializedBody,\n timeoutMs,\n };\n await config.onRequest?.(hookRequestContext);\n const startedAt = Date.now();\n try {\n const response = await fetchWithTimeout(url, init, timeoutMs);\n const responseClone = response.clone();\n const payload = await parsePayload<T>(response);\n const retryAfterMs = parseRetryAfterMs(\n response.headers.get(\"Retry-After\")\n );\n\n if (!response.ok || !payload?.success) {\n const failure =\n payload && !payload.success ? (payload as PlatformGatewayFailure) : null;\n const apiError = buildApiError({\n requestId,\n response,\n failure,\n });\n const willRetry = attempt < maxRetries && isRetryableStatus(response.status);\n\n await config.onResponse?.({\n ...hookRequestContext,\n durationMs: Date.now() - startedAt,\n status: response.status,\n response: responseClone,\n error: apiError,\n correlationId: apiError.correlationId ?? requestId,\n policyTraceId: apiError.policyTraceId ?? null,\n retryAfterMs,\n willRetry,\n });\n\n if (willRetry) {\n lastError = apiError;\n await delay(\n computeRetryDelayMs({\n attempt,\n status: response.status,\n retryAfterMs,\n })\n );\n continue;\n }\n\n throw apiError;\n }\n\n const successPayload = payload as PlatformGatewaySuccess<T>;\n await config.onResponse?.({\n ...hookRequestContext,\n durationMs: Date.now() - startedAt,\n status: response.status,\n response: responseClone,\n correlationId:\n successPayload.correlationId ??\n response.headers.get(\"x-lucern-correlation-id\")?.trim() ??\n requestId,\n policyTraceId:\n successPayload.policyTraceId ??\n response.headers.get(\"x-lucern-policy-trace-id\")?.trim() ??\n null,\n idempotentReplay: successPayload.idempotentReplay,\n retryAfterMs,\n willRetry: false,\n });\n\n return successPayload;\n } catch (fetchError) {\n if (fetchError instanceof LucernApiError) {\n throw fetchError;\n }\n const willRetry = attempt < maxRetries;\n await config.onResponse?.({\n ...hookRequestContext,\n durationMs: Date.now() - startedAt,\n error: fetchError,\n correlationId: requestId,\n policyTraceId: null,\n willRetry,\n });\n lastError = fetchError;\n if (willRetry) {\n await delay(computeRetryDelayMs({ attempt }));\n }\n }\n }\n\n throw lastError instanceof Error\n ? lastError\n : new Error(\"Platform API request failed after retries.\");\n }\n\n return {\n request,\n };\n}\n","import {\n createGatewayRequestClient,\n type GatewayClientConfig,\n} from \"./coreClient\";\nimport type {\n CompileContextInput,\n PublicCompiledContext,\n} from \"./contextTypes\";\nimport type { JsonObject } from \"./types\";\n\n/** Configuration for the context client. */\nexport type ContextClientConfig = GatewayClientConfig;\n\n/** Alias for the compiled context payload returned by the gateway. */\nexport type CompileContextResponse = PublicCompiledContext;\n\n/** Internal request shape for the context compile endpoint. */\ntype ContextClientRequest = {\n path: \"/api/platform/v1/context/compile\";\n method: \"POST\";\n body: Record<string, unknown>;\n};\n\nfunction cleanString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim().length > 0\n ? value.trim()\n : undefined;\n}\n\nfunction cleanNumber(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction cleanBoolean(value: unknown): boolean | undefined {\n return typeof value === \"boolean\" ? value : undefined;\n}\n\nfunction buildCompileContextRequest(\n topicId: string,\n input: CompileContextInput = {}\n): ContextClientRequest {\n const payload: Record<string, unknown> = { topicId };\n\n const query = cleanString(input.query);\n if (query) {\n payload.query = query;\n }\n\n const budget = cleanNumber(input.budget) ?? cleanNumber(input.tokenBudget);\n if (budget !== undefined) {\n payload.budget = budget;\n }\n\n const ranking = cleanString(input.ranking) ?? cleanString(input.rankingProfile);\n if (ranking) {\n payload.ranking = ranking;\n }\n\n const limit = cleanNumber(input.limit);\n if (limit !== undefined) {\n payload.limit = limit;\n }\n\n const maxDepth = cleanNumber(input.maxDepth);\n if (maxDepth !== undefined) {\n payload.maxDepth = maxDepth;\n }\n\n const includeEntities = cleanBoolean(input.includeEntities);\n if (includeEntities !== undefined) {\n payload.includeEntities = includeEntities;\n }\n\n const mode = cleanString(input.mode);\n if (mode) {\n payload.mode = mode;\n }\n\n const includeFailures = cleanBoolean(input.includeFailures);\n if (includeFailures !== undefined) {\n payload.includeFailures = includeFailures;\n }\n\n const worktreeId = cleanString(input.worktreeId);\n if (worktreeId) {\n payload.worktreeId = worktreeId;\n }\n\n const sessionId = cleanString(input.sessionId);\n if (sessionId) {\n payload.sessionId = sessionId;\n }\n\n if (Array.isArray(input.packWeightOverrides) && input.packWeightOverrides.length > 0) {\n payload.packWeightOverrides = input.packWeightOverrides;\n }\n\n return {\n path: \"/api/platform/v1/context/compile\",\n method: \"POST\",\n body: payload,\n };\n}\n\n/**\n * Create the context client for compiling reasoning context packs.\n * @param config - Gateway transport configuration.\n * @returns An object with a `compile` method for building context packs.\n */\nexport function createContextClient(config: ContextClientConfig = {}) {\n const gateway = createGatewayRequestClient(config);\n\n return {\n /**\n * Compile a focused reasoning context pack for a topic scope.\n * @param topicId - The topic to compile context for.\n * @param input - Optional compile parameters (query, budget, ranking, etc.).\n * @returns The compiled context payload with beliefs, questions, and evidence.\n */\n async compile(topicId: string, input: CompileContextInput = {}) {\n const request = buildCompileContextRequest(topicId, input);\n return gateway.request<CompileContextResponse>({\n ...request,\n body: request.body as JsonObject,\n });\n },\n };\n}\n\nexport type { CompileContextInput, PublicCompiledContext } from \"./contextTypes\";\n"]}
|