@lucern/sdk 0.2.0-alpha.9 → 0.3.0-alpha.1
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/README.md +33 -15
- package/dist/adminClient.d.ts +15 -9
- package/dist/adminClient.js.map +1 -1
- package/dist/audience/index.d.ts +38 -0
- package/dist/audience/index.js +110 -0
- package/dist/audience/index.js.map +1 -0
- package/dist/beliefs/index.d.ts +463 -0
- package/dist/beliefs/index.js +6695 -0
- package/dist/beliefs/index.js.map +1 -0
- package/dist/beliefs/lifecycle.d.ts +24 -0
- package/dist/beliefs/lifecycle.js +98 -0
- package/dist/beliefs/lifecycle.js.map +1 -0
- package/dist/beliefsClient.d.ts +76 -12
- package/dist/beliefsClient.js +139 -7
- package/dist/beliefsClient.js.map +1 -1
- package/dist/client-B6aWUUwp.d.ts +2552 -0
- package/dist/client.d.ts +31 -2377
- package/dist/client.js +802 -263
- package/dist/client.js.map +1 -1
- package/dist/contracts/api-enums.contract.d.ts +1 -1
- package/dist/contracts/api-enums.contract.js +8 -2
- package/dist/contracts/api-enums.contract.js.map +1 -1
- package/dist/contracts/index.d.ts +4 -2
- package/dist/contracts/index.js +119 -4283
- package/dist/contracts/index.js.map +1 -1
- package/dist/contracts/mcpTools.d.ts +2 -1
- package/dist/contracts/mcpTools.js +22 -2981
- package/dist/contracts/mcpTools.js.map +1 -1
- package/dist/contracts/sdk-tools.contract.d.ts +1 -2
- package/dist/contracts/sdk-tools.contract.js +1 -4132
- package/dist/contracts/sdk-tools.contract.js.map +1 -1
- package/dist/contracts/sdkTools.d.ts +1 -2
- package/dist/contracts/sdkTools.js +20 -4127
- package/dist/contracts/sdkTools.js.map +1 -1
- package/dist/contracts/tool-contracts.d.ts +1 -0
- package/dist/contracts/tool-contracts.js +3 -0
- package/dist/contracts/tool-contracts.js.map +1 -0
- package/dist/contracts/workflow-runtime.contract.js +1 -1
- package/dist/contracts/workflow-runtime.contract.js.map +1 -1
- package/dist/contracts/workflowRuntime.js +1 -1
- package/dist/contracts/workflowRuntime.js.map +1 -1
- package/dist/contradictions/index.d.ts +156 -0
- package/dist/contradictions/index.js +6689 -0
- package/dist/contradictions/index.js.map +1 -0
- package/dist/customTools.d.ts +1 -1
- package/dist/decisions/index.d.ts +66 -0
- package/dist/decisions/index.js +6691 -0
- package/dist/decisions/index.js.map +1 -0
- package/dist/edges/index.d.ts +202 -0
- package/dist/edges/index.js +6690 -0
- package/dist/edges/index.js.map +1 -0
- package/dist/events.js +7 -5
- package/dist/events.js.map +1 -1
- package/dist/evidence/index.d.ts +294 -0
- package/dist/evidence/index.js +6690 -0
- package/dist/evidence/index.js.map +1 -0
- package/dist/evidenceClient.d.ts +119 -0
- package/dist/evidenceClient.js +350 -0
- package/dist/evidenceClient.js.map +1 -0
- package/dist/gatewayFacades.d.ts +25 -15
- package/dist/gatewayFacades.js +39 -5
- package/dist/gatewayFacades.js.map +1 -1
- package/dist/identityClient.d.ts +3 -3
- package/dist/identityClient.js.map +1 -1
- package/dist/index.d.ts +7 -6
- package/dist/index.js +1145 -3313
- package/dist/index.js.map +1 -1
- package/dist/lenses/index.d.ts +194 -0
- package/dist/lenses/index.js +6689 -0
- package/dist/lenses/index.js.map +1 -0
- package/dist/nodes/index.d.ts +61 -0
- package/dist/nodes/index.js +6691 -0
- package/dist/nodes/index.js.map +1 -0
- package/dist/ontologies/index.d.ts +179 -0
- package/dist/ontologies/index.js +6692 -0
- package/dist/ontologies/index.js.map +1 -0
- package/dist/opinion.d.ts +11 -0
- package/dist/opinion.js +35 -0
- package/dist/opinion.js.map +1 -0
- package/dist/questions/index.d.ts +295 -0
- package/dist/questions/index.js +6692 -0
- package/dist/questions/index.js.map +1 -0
- package/dist/sdk-tools.contract-B4c1Zr1o.d.ts +22 -0
- package/dist/sourcesClient.d.ts +24 -0
- package/dist/{mcpParityClient.js → sourcesClient.js} +15 -192
- package/dist/sourcesClient.js.map +1 -0
- package/dist/tool-contracts-BUiL9P6z.d.ts +22 -0
- package/dist/topics/index.d.ts +66 -0
- package/dist/topics/index.js +6690 -0
- package/dist/topics/index.js.map +1 -0
- package/dist/types.d.ts +27 -8
- package/dist/workflowClient.d.ts +18 -5
- package/dist/workflowClient.js +19 -7
- package/dist/workflowClient.js.map +1 -1
- package/dist/worktrees/index.d.ts +211 -0
- package/dist/worktrees/index.js +6692 -0
- package/dist/worktrees/index.js.map +1 -0
- package/package.json +56 -3
- package/dist/contracts/mcp-tools.contract.d.ts +0 -1
- package/dist/contracts/mcp-tools.contract.js +0 -2986
- package/dist/contracts/mcp-tools.contract.js.map +0 -1
- package/dist/mcpParityClient.d.ts +0 -74
- package/dist/mcpParityClient.js.map +0 -1
- package/dist/mcpParitySurface.d.ts +0 -12
- package/dist/mcpParitySurface.js +0 -65
- package/dist/mcpParitySurface.js.map +0 -1
- package/dist/mcpTools-DPZxowDX.d.ts +0 -254
- package/dist/sdkTools-CwXJDACb.d.ts +0 -150
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { GatewayClientConfig, PlatformGatewaySuccess } from './coreClient.js';
|
|
2
|
+
import './types.js';
|
|
3
|
+
import './contracts/workflow-runtime.contract.js';
|
|
4
|
+
import './contracts/lens-workflow.contract.js';
|
|
5
|
+
import './contracts/lens-filter.contract.js';
|
|
6
|
+
|
|
7
|
+
type EvidenceClassificationRelation = "supports" | "contradicts" | "irrelevant";
|
|
8
|
+
type ModelFallbackConfig = {
|
|
9
|
+
modelKey: string;
|
|
10
|
+
modelId: string;
|
|
11
|
+
temperature: number;
|
|
12
|
+
maxTokens: number;
|
|
13
|
+
};
|
|
14
|
+
type ResolvedModelConfig = ModelFallbackConfig & {
|
|
15
|
+
promptName: string;
|
|
16
|
+
};
|
|
17
|
+
type TracingAdapter = {
|
|
18
|
+
startGeneration(input: {
|
|
19
|
+
name: string;
|
|
20
|
+
userId?: string;
|
|
21
|
+
promptName: string;
|
|
22
|
+
model: string;
|
|
23
|
+
input: unknown;
|
|
24
|
+
}): Promise<{
|
|
25
|
+
start: () => void;
|
|
26
|
+
end: (output: unknown) => Promise<void>;
|
|
27
|
+
error: (err: unknown) => Promise<void>;
|
|
28
|
+
}>;
|
|
29
|
+
};
|
|
30
|
+
type PromptResolver = (name: string) => Promise<string | null>;
|
|
31
|
+
type ModelResolver = (slotKey: string, fallback: ResolvedModelConfig) => Promise<ResolvedModelConfig>;
|
|
32
|
+
type ClassificationRuntimeAdapter = (input: {
|
|
33
|
+
beliefId: string;
|
|
34
|
+
evidenceId: string;
|
|
35
|
+
belief: string;
|
|
36
|
+
evidence: string;
|
|
37
|
+
prompt: string;
|
|
38
|
+
model: ResolvedModelConfig;
|
|
39
|
+
}) => Promise<{
|
|
40
|
+
relation: EvidenceClassificationRelation;
|
|
41
|
+
rationale: string;
|
|
42
|
+
}>;
|
|
43
|
+
type SerializableClassifyEvidenceConfig = {
|
|
44
|
+
promptName?: string;
|
|
45
|
+
modelSlotKey?: string;
|
|
46
|
+
modelFallback?: ModelFallbackConfig;
|
|
47
|
+
edgeWeightPolicy?: {
|
|
48
|
+
supports: number;
|
|
49
|
+
contradicts: number;
|
|
50
|
+
};
|
|
51
|
+
statusTransition?: {
|
|
52
|
+
onSupports: string;
|
|
53
|
+
onContradicts: string;
|
|
54
|
+
};
|
|
55
|
+
writeLegacyTables?: boolean;
|
|
56
|
+
};
|
|
57
|
+
type ClassifyEvidenceConfig = SerializableClassifyEvidenceConfig & {
|
|
58
|
+
trustDiscountPolicy?: (relation: Exclude<EvidenceClassificationRelation, "irrelevant">, rationale: string) => number;
|
|
59
|
+
tracing?: TracingAdapter;
|
|
60
|
+
promptResolver?: PromptResolver;
|
|
61
|
+
modelResolver?: ModelResolver;
|
|
62
|
+
classifier?: ClassificationRuntimeAdapter;
|
|
63
|
+
};
|
|
64
|
+
type ClassifyEvidenceResult = {
|
|
65
|
+
beliefId: string;
|
|
66
|
+
evidenceId: string;
|
|
67
|
+
relation: EvidenceClassificationRelation;
|
|
68
|
+
rationale: string;
|
|
69
|
+
usedFallback: boolean;
|
|
70
|
+
edgeWeight?: number;
|
|
71
|
+
promptName: string;
|
|
72
|
+
model: ResolvedModelConfig;
|
|
73
|
+
link?: {
|
|
74
|
+
edgeGlobalId: string;
|
|
75
|
+
linkId?: string;
|
|
76
|
+
confidence: number;
|
|
77
|
+
writeLegacyTables: boolean;
|
|
78
|
+
};
|
|
79
|
+
statusUpdate?: {
|
|
80
|
+
previousStatus?: string;
|
|
81
|
+
newStatus: string;
|
|
82
|
+
historyWritten: boolean;
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
type ClassifyEvidenceBatchItem = {
|
|
86
|
+
evidenceId?: string;
|
|
87
|
+
insightId?: string;
|
|
88
|
+
nodeId?: string;
|
|
89
|
+
text?: string;
|
|
90
|
+
};
|
|
91
|
+
type ClassifyEvidenceBatchResult = {
|
|
92
|
+
items: ClassifyEvidenceResult[];
|
|
93
|
+
summary: {
|
|
94
|
+
supporting: number;
|
|
95
|
+
contradicting: number;
|
|
96
|
+
irrelevant: number;
|
|
97
|
+
};
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
/** Configuration for the evidence classification client. */
|
|
101
|
+
type EvidenceClientConfig = GatewayClientConfig;
|
|
102
|
+
/**
|
|
103
|
+
* Serializable config accepted by the HTTP SDK surface.
|
|
104
|
+
* Runtime-only ports stay inside the kernel adapter.
|
|
105
|
+
*/
|
|
106
|
+
type EvidenceClassificationRequestConfig = SerializableClassifyEvidenceConfig;
|
|
107
|
+
/**
|
|
108
|
+
* Create the evidence classification client.
|
|
109
|
+
*
|
|
110
|
+
* This surface mirrors the promoted kernel primitive through the platform
|
|
111
|
+
* gateway. Auth-scoped callers do not provide `createdBy`; the gateway derives
|
|
112
|
+
* it from the authenticated principal.
|
|
113
|
+
*/
|
|
114
|
+
declare function createEvidenceClient(config?: EvidenceClientConfig): {
|
|
115
|
+
classifyEvidence(beliefId: string, evidenceId: string, classificationConfig?: EvidenceClassificationRequestConfig, idempotencyKey?: string): Promise<PlatformGatewaySuccess<ClassifyEvidenceResult>>;
|
|
116
|
+
classifyEvidenceBatch(beliefId: string, evidence: ClassifyEvidenceBatchItem[], classificationConfig?: EvidenceClassificationRequestConfig, idempotencyKey?: string): Promise<PlatformGatewaySuccess<ClassifyEvidenceBatchResult>>;
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
export { type ClassifyEvidenceBatchItem, type ClassifyEvidenceBatchResult, type ClassifyEvidenceConfig, type ClassifyEvidenceResult, type EvidenceClassificationRequestConfig, type EvidenceClientConfig, PlatformGatewaySuccess, type SerializableClassifyEvidenceConfig, createEvidenceClient };
|
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
// src/coreClient.ts
|
|
2
|
+
var LucernApiError = class extends Error {
|
|
3
|
+
code;
|
|
4
|
+
status;
|
|
5
|
+
invariant;
|
|
6
|
+
suggestion;
|
|
7
|
+
details;
|
|
8
|
+
requestId;
|
|
9
|
+
correlationId;
|
|
10
|
+
policyTraceId;
|
|
11
|
+
constructor(args) {
|
|
12
|
+
super(args.message);
|
|
13
|
+
this.name = "LucernApiError";
|
|
14
|
+
this.code = args.code;
|
|
15
|
+
this.status = args.status;
|
|
16
|
+
this.invariant = args.invariant;
|
|
17
|
+
this.suggestion = args.suggestion;
|
|
18
|
+
this.details = args.details;
|
|
19
|
+
this.requestId = args.requestId;
|
|
20
|
+
this.correlationId = args.correlationId;
|
|
21
|
+
this.policyTraceId = args.policyTraceId;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
function fillRandomBytes(length) {
|
|
25
|
+
const bytes = new Uint8Array(length);
|
|
26
|
+
if (typeof globalThis.crypto?.getRandomValues === "function") {
|
|
27
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
28
|
+
return bytes;
|
|
29
|
+
}
|
|
30
|
+
for (let index = 0; index < length; index += 1) {
|
|
31
|
+
bytes[index] = Math.floor(Math.random() * 256);
|
|
32
|
+
}
|
|
33
|
+
return bytes;
|
|
34
|
+
}
|
|
35
|
+
function generatePortableRequestId() {
|
|
36
|
+
if (typeof globalThis.crypto?.randomUUID === "function") {
|
|
37
|
+
return globalThis.crypto.randomUUID();
|
|
38
|
+
}
|
|
39
|
+
const bytes = fillRandomBytes(16);
|
|
40
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
41
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
42
|
+
const hex = Array.from(bytes, (value) => value.toString(16).padStart(2, "0"));
|
|
43
|
+
return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(
|
|
44
|
+
6,
|
|
45
|
+
8
|
|
46
|
+
).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
|
|
47
|
+
}
|
|
48
|
+
function randomIdempotencyKey() {
|
|
49
|
+
return generatePortableRequestId();
|
|
50
|
+
}
|
|
51
|
+
function isRetryableStatus(status) {
|
|
52
|
+
return status >= 500 || status === 408 || status === 429;
|
|
53
|
+
}
|
|
54
|
+
function fallbackErrorCode(status) {
|
|
55
|
+
if (status === 401) {
|
|
56
|
+
return "AUTHENTICATION_REQUIRED";
|
|
57
|
+
}
|
|
58
|
+
if (status === 403) {
|
|
59
|
+
return "FORBIDDEN";
|
|
60
|
+
}
|
|
61
|
+
if (status === 404) {
|
|
62
|
+
return "NOT_FOUND";
|
|
63
|
+
}
|
|
64
|
+
if (status === 408) {
|
|
65
|
+
return "UPSTREAM_ERROR";
|
|
66
|
+
}
|
|
67
|
+
if (status === 409) {
|
|
68
|
+
return "CONFLICT";
|
|
69
|
+
}
|
|
70
|
+
if (status === 429) {
|
|
71
|
+
return "RATE_LIMIT_EXCEEDED";
|
|
72
|
+
}
|
|
73
|
+
if (status >= 500) {
|
|
74
|
+
return "UPSTREAM_ERROR";
|
|
75
|
+
}
|
|
76
|
+
return "INTERNAL_ERROR";
|
|
77
|
+
}
|
|
78
|
+
function delay(ms) {
|
|
79
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
80
|
+
}
|
|
81
|
+
function parseRetryAfterMs(value) {
|
|
82
|
+
if (!value) {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
const trimmed = value.trim();
|
|
86
|
+
if (!trimmed) {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
const numeric = Number(trimmed);
|
|
90
|
+
if (Number.isFinite(numeric)) {
|
|
91
|
+
return Math.max(0, Math.round(numeric * 1e3));
|
|
92
|
+
}
|
|
93
|
+
const parsedDate = Date.parse(trimmed);
|
|
94
|
+
if (Number.isFinite(parsedDate)) {
|
|
95
|
+
return Math.max(0, parsedDate - Date.now());
|
|
96
|
+
}
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
function computeRetryDelayMs(args) {
|
|
100
|
+
const baseDelay = args.status === 429 ? Math.max(
|
|
101
|
+
args.retryAfterMs ?? 0,
|
|
102
|
+
Math.min(1e3 * 2 ** args.attempt, 1e4)
|
|
103
|
+
) : Math.min(1e3 * 2 ** args.attempt, 4e3);
|
|
104
|
+
if (args.status !== 429) {
|
|
105
|
+
return baseDelay;
|
|
106
|
+
}
|
|
107
|
+
const jitterWindow = Math.max(250, Math.round(baseDelay * 0.25));
|
|
108
|
+
return baseDelay + Math.round(Math.random() * jitterWindow);
|
|
109
|
+
}
|
|
110
|
+
function timeoutError(timeoutMs) {
|
|
111
|
+
const error = new Error(`Request timed out after ${timeoutMs}ms`);
|
|
112
|
+
error.name = "AbortError";
|
|
113
|
+
return error;
|
|
114
|
+
}
|
|
115
|
+
function readPolicySummaryFromDetails(details) {
|
|
116
|
+
if (!details || typeof details !== "object" || Array.isArray(details)) {
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
const directSummary = details.summary;
|
|
120
|
+
if (typeof directSummary === "string" && directSummary.trim().length > 0) {
|
|
121
|
+
return directSummary.trim();
|
|
122
|
+
}
|
|
123
|
+
const policy = details.policy;
|
|
124
|
+
if (!policy || typeof policy !== "object" || Array.isArray(policy)) {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
const explanation = policy.explanation;
|
|
128
|
+
if (!explanation || typeof explanation !== "object" || Array.isArray(explanation)) {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
const nestedSummary = explanation.summary;
|
|
132
|
+
if (typeof nestedSummary === "string" && nestedSummary.trim().length > 0) {
|
|
133
|
+
return nestedSummary.trim();
|
|
134
|
+
}
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
function createGatewayRequestClient(config = {}) {
|
|
138
|
+
const fetchImpl = config.fetchImpl ?? fetch;
|
|
139
|
+
const baseUrl = config.baseUrl?.replace(/\/+$/, "") ?? "";
|
|
140
|
+
const maxRetries = config.maxRetries ?? 2;
|
|
141
|
+
const requestIdFactory = config.requestIdFactory ?? (() => generatePortableRequestId());
|
|
142
|
+
async function resolveAuthHeaders() {
|
|
143
|
+
if (!config.getAuthHeaders) {
|
|
144
|
+
return {};
|
|
145
|
+
}
|
|
146
|
+
return await config.getAuthHeaders();
|
|
147
|
+
}
|
|
148
|
+
async function fetchWithTimeout(url, init, timeoutMs) {
|
|
149
|
+
const controller = new AbortController();
|
|
150
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
151
|
+
try {
|
|
152
|
+
return await fetchImpl(url, { ...init, signal: controller.signal });
|
|
153
|
+
} catch (error) {
|
|
154
|
+
if (controller.signal.aborted) {
|
|
155
|
+
throw timeoutError(timeoutMs);
|
|
156
|
+
}
|
|
157
|
+
throw error;
|
|
158
|
+
} finally {
|
|
159
|
+
clearTimeout(timer);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
async function parsePayload(response) {
|
|
163
|
+
const text = await response.text();
|
|
164
|
+
if (!text) {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
try {
|
|
168
|
+
return JSON.parse(text);
|
|
169
|
+
} catch {
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
function resolveTimeoutMs(method, requestTimeoutMs) {
|
|
174
|
+
if (typeof requestTimeoutMs === "number") {
|
|
175
|
+
return requestTimeoutMs;
|
|
176
|
+
}
|
|
177
|
+
const methodTimeoutMs = config.timeoutMsByMethod?.[method];
|
|
178
|
+
if (typeof methodTimeoutMs === "number") {
|
|
179
|
+
return methodTimeoutMs;
|
|
180
|
+
}
|
|
181
|
+
return config.timeoutMs ?? 15e3;
|
|
182
|
+
}
|
|
183
|
+
function buildApiError(args) {
|
|
184
|
+
const failure = args.failure;
|
|
185
|
+
const legacyError = failure && typeof failure.error === "object" && failure.error !== null ? failure.error : failure?.legacyError;
|
|
186
|
+
const correlationId = failure?.correlationId ?? args.response.headers.get("x-lucern-correlation-id")?.trim() ?? args.requestId;
|
|
187
|
+
const policyTraceId = failure?.policyTraceId ?? args.response.headers.get("x-lucern-policy-trace-id")?.trim() ?? null;
|
|
188
|
+
const details = failure?.details ?? legacyError?.details;
|
|
189
|
+
const policySummary = readPolicySummaryFromDetails(details);
|
|
190
|
+
return new LucernApiError({
|
|
191
|
+
code: failure?.code ?? legacyError?.code ?? fallbackErrorCode(args.response.status),
|
|
192
|
+
message: policySummary ?? (typeof failure?.error === "string" ? failure.error : legacyError?.message ?? (args.response.ok ? "Platform API returned an invalid success payload." : "Platform API request failed.")),
|
|
193
|
+
status: args.response.status,
|
|
194
|
+
invariant: failure?.invariant,
|
|
195
|
+
suggestion: failure?.suggestion,
|
|
196
|
+
details,
|
|
197
|
+
requestId: args.requestId,
|
|
198
|
+
correlationId,
|
|
199
|
+
policyTraceId
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
async function request(args) {
|
|
203
|
+
const authHeaders = await resolveAuthHeaders();
|
|
204
|
+
const method = args.method ?? "GET";
|
|
205
|
+
const timeoutMs = resolveTimeoutMs(method, args.timeoutMs);
|
|
206
|
+
const headers = new Headers({
|
|
207
|
+
"content-type": "application/json",
|
|
208
|
+
...authHeaders
|
|
209
|
+
});
|
|
210
|
+
if (args.idempotencyKey) {
|
|
211
|
+
headers.set("idempotency-key", args.idempotencyKey);
|
|
212
|
+
}
|
|
213
|
+
const requestId = headers.get("x-correlation-id")?.trim() || headers.get("x-request-id")?.trim() || args.requestId || requestIdFactory();
|
|
214
|
+
if (!headers.has("x-correlation-id") && !headers.has("x-request-id")) {
|
|
215
|
+
headers.set("x-correlation-id", requestId);
|
|
216
|
+
}
|
|
217
|
+
const url = `${baseUrl}${args.path}`;
|
|
218
|
+
const serializedBody = args.body ? JSON.stringify(args.body) : void 0;
|
|
219
|
+
const init = {
|
|
220
|
+
method,
|
|
221
|
+
headers,
|
|
222
|
+
body: serializedBody
|
|
223
|
+
};
|
|
224
|
+
let lastError;
|
|
225
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
226
|
+
const hookRequestContext = {
|
|
227
|
+
requestId,
|
|
228
|
+
attempt,
|
|
229
|
+
maxRetries,
|
|
230
|
+
method,
|
|
231
|
+
path: args.path,
|
|
232
|
+
url,
|
|
233
|
+
headers: new Headers(headers),
|
|
234
|
+
body: serializedBody,
|
|
235
|
+
timeoutMs
|
|
236
|
+
};
|
|
237
|
+
await config.onRequest?.(hookRequestContext);
|
|
238
|
+
const startedAt = Date.now();
|
|
239
|
+
try {
|
|
240
|
+
const response = await fetchWithTimeout(url, init, timeoutMs);
|
|
241
|
+
const responseClone = response.clone();
|
|
242
|
+
const payload = await parsePayload(response);
|
|
243
|
+
const retryAfterMs = parseRetryAfterMs(
|
|
244
|
+
response.headers.get("Retry-After")
|
|
245
|
+
);
|
|
246
|
+
if (!response.ok || !payload?.success) {
|
|
247
|
+
const failure = payload && !payload.success ? payload : null;
|
|
248
|
+
const apiError = buildApiError({
|
|
249
|
+
requestId,
|
|
250
|
+
response,
|
|
251
|
+
failure
|
|
252
|
+
});
|
|
253
|
+
const willRetry = attempt < maxRetries && isRetryableStatus(response.status);
|
|
254
|
+
await config.onResponse?.({
|
|
255
|
+
...hookRequestContext,
|
|
256
|
+
durationMs: Date.now() - startedAt,
|
|
257
|
+
status: response.status,
|
|
258
|
+
response: responseClone,
|
|
259
|
+
error: apiError,
|
|
260
|
+
correlationId: apiError.correlationId ?? requestId,
|
|
261
|
+
policyTraceId: apiError.policyTraceId ?? null,
|
|
262
|
+
retryAfterMs,
|
|
263
|
+
willRetry
|
|
264
|
+
});
|
|
265
|
+
if (willRetry) {
|
|
266
|
+
lastError = apiError;
|
|
267
|
+
await delay(
|
|
268
|
+
computeRetryDelayMs({
|
|
269
|
+
attempt,
|
|
270
|
+
status: response.status,
|
|
271
|
+
retryAfterMs
|
|
272
|
+
})
|
|
273
|
+
);
|
|
274
|
+
continue;
|
|
275
|
+
}
|
|
276
|
+
throw apiError;
|
|
277
|
+
}
|
|
278
|
+
const successPayload = payload;
|
|
279
|
+
await config.onResponse?.({
|
|
280
|
+
...hookRequestContext,
|
|
281
|
+
durationMs: Date.now() - startedAt,
|
|
282
|
+
status: response.status,
|
|
283
|
+
response: responseClone,
|
|
284
|
+
correlationId: successPayload.correlationId ?? response.headers.get("x-lucern-correlation-id")?.trim() ?? requestId,
|
|
285
|
+
policyTraceId: successPayload.policyTraceId ?? response.headers.get("x-lucern-policy-trace-id")?.trim() ?? null,
|
|
286
|
+
idempotentReplay: successPayload.idempotentReplay,
|
|
287
|
+
retryAfterMs,
|
|
288
|
+
willRetry: false
|
|
289
|
+
});
|
|
290
|
+
return successPayload;
|
|
291
|
+
} catch (fetchError) {
|
|
292
|
+
if (fetchError instanceof LucernApiError) {
|
|
293
|
+
throw fetchError;
|
|
294
|
+
}
|
|
295
|
+
const willRetry = attempt < maxRetries;
|
|
296
|
+
await config.onResponse?.({
|
|
297
|
+
...hookRequestContext,
|
|
298
|
+
durationMs: Date.now() - startedAt,
|
|
299
|
+
error: fetchError,
|
|
300
|
+
correlationId: requestId,
|
|
301
|
+
policyTraceId: null,
|
|
302
|
+
willRetry
|
|
303
|
+
});
|
|
304
|
+
lastError = fetchError;
|
|
305
|
+
if (willRetry) {
|
|
306
|
+
await delay(computeRetryDelayMs({ attempt }));
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
throw lastError instanceof Error ? lastError : new Error("Platform API request failed after retries.");
|
|
311
|
+
}
|
|
312
|
+
return {
|
|
313
|
+
request
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// src/evidenceClient.ts
|
|
318
|
+
function createEvidenceClient(config = {}) {
|
|
319
|
+
const gateway = createGatewayRequestClient(config);
|
|
320
|
+
return {
|
|
321
|
+
async classifyEvidence(beliefId, evidenceId, classificationConfig, idempotencyKey) {
|
|
322
|
+
return gateway.request({
|
|
323
|
+
path: "/api/platform/v1/evidence/classify",
|
|
324
|
+
method: "POST",
|
|
325
|
+
body: {
|
|
326
|
+
beliefId,
|
|
327
|
+
evidenceId,
|
|
328
|
+
config: classificationConfig
|
|
329
|
+
},
|
|
330
|
+
idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
|
|
331
|
+
});
|
|
332
|
+
},
|
|
333
|
+
async classifyEvidenceBatch(beliefId, evidence, classificationConfig, idempotencyKey) {
|
|
334
|
+
return gateway.request({
|
|
335
|
+
path: "/api/platform/v1/evidence/classify-batch",
|
|
336
|
+
method: "POST",
|
|
337
|
+
body: {
|
|
338
|
+
beliefId,
|
|
339
|
+
evidence,
|
|
340
|
+
config: classificationConfig
|
|
341
|
+
},
|
|
342
|
+
idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export { createEvidenceClient };
|
|
349
|
+
//# sourceMappingURL=evidenceClient.js.map
|
|
350
|
+
//# sourceMappingURL=evidenceClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/coreClient.ts","../src/evidenceClient.ts"],"names":[],"mappings":";AAuDO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA,EACxB,IAAA;AAAA,EACA,MAAA;AAAA,EAC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AAA,YAAqB,KAAA,GACvB,SAAA,GACA,IAAI,MAAM,4CAA4C,CAAA;AAAA,EAC5D;AAEA,EAAA,OAAO;AAAA,IACL;AAAA,GACF;AACF;;;AC5aO,SAAS,oBAAA,CAAqB,MAAA,GAA+B,EAAC,EAAG;AACtE,EAAA,MAAM,OAAA,GAAU,2BAA2B,MAAM,CAAA;AAEjD,EAAA,OAAO;AAAA,IACL,MAAM,gBAAA,CACJ,QAAA,EACA,UAAA,EACA,sBACA,cAAA,EACA;AACA,MAAA,OAAO,QAAQ,OAAA,CAAgC;AAAA,QAC7C,IAAA,EAAM,oCAAA;AAAA,QACN,MAAA,EAAQ,MAAA;AAAA,QACR,IAAA,EAAM;AAAA,UACJ,QAAA;AAAA,UACA,UAAA;AAAA,UACA,MAAA,EAAQ;AAAA,SACV;AAAA,QACA,cAAA,EAAgB,kBAAkB,oBAAA;AAAqB,OACxD,CAAA;AAAA,IACH,CAAA;AAAA,IAEA,MAAM,qBAAA,CACJ,QAAA,EACA,QAAA,EACA,sBACA,cAAA,EACA;AACA,MAAA,OAAO,QAAQ,OAAA,CAAqC;AAAA,QAClD,IAAA,EAAM,0CAAA;AAAA,QACN,MAAA,EAAQ,MAAA;AAAA,QACR,IAAA,EAAM;AAAA,UACJ,QAAA;AAAA,UACA,QAAA;AAAA,UACA,MAAA,EAAQ;AAAA,SACV;AAAA,QACA,cAAA,EAAgB,kBAAkB,oBAAA;AAAqB,OACxD,CAAA;AAAA,IACH;AAAA,GACF;AACF","file":"evidenceClient.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 randomIdempotencyKey,\n} from \"./coreClient\";\n\ntype EvidenceClassificationRelation =\n | \"supports\"\n | \"contradicts\"\n | \"irrelevant\";\n\ntype ModelFallbackConfig = {\n modelKey: string;\n modelId: string;\n temperature: number;\n maxTokens: number;\n};\n\ntype ResolvedModelConfig = ModelFallbackConfig & {\n promptName: string;\n};\n\ntype TracingAdapter = {\n startGeneration(input: {\n name: string;\n userId?: string;\n promptName: string;\n model: string;\n input: unknown;\n }): Promise<{\n start: () => void;\n end: (output: unknown) => Promise<void>;\n error: (err: unknown) => Promise<void>;\n }>;\n};\n\ntype PromptResolver = (name: string) => Promise<string | null>;\n\ntype ModelResolver = (\n slotKey: string,\n fallback: ResolvedModelConfig\n) => Promise<ResolvedModelConfig>;\n\ntype ClassificationRuntimeAdapter = (input: {\n beliefId: string;\n evidenceId: string;\n belief: string;\n evidence: string;\n prompt: string;\n model: ResolvedModelConfig;\n}) => Promise<{\n relation: EvidenceClassificationRelation;\n rationale: string;\n}>;\n\n// Local mirror of the kernel adapter types so SDK DTS generation stays inside\n// packages/sdk rootDir. Source of truth:\n// packages/reasoning-kernel/src/adapters/evidenceClassifier.ts\nexport type SerializableClassifyEvidenceConfig = {\n promptName?: string;\n modelSlotKey?: string;\n modelFallback?: ModelFallbackConfig;\n edgeWeightPolicy?: {\n supports: number;\n contradicts: number;\n };\n statusTransition?: {\n onSupports: string;\n onContradicts: string;\n };\n writeLegacyTables?: boolean;\n};\n\nexport type ClassifyEvidenceConfig = SerializableClassifyEvidenceConfig & {\n trustDiscountPolicy?: (\n relation: Exclude<EvidenceClassificationRelation, \"irrelevant\">,\n rationale: string\n ) => number;\n tracing?: TracingAdapter;\n promptResolver?: PromptResolver;\n modelResolver?: ModelResolver;\n classifier?: ClassificationRuntimeAdapter;\n};\n\nexport type ClassifyEvidenceResult = {\n beliefId: string;\n evidenceId: string;\n relation: EvidenceClassificationRelation;\n rationale: string;\n usedFallback: boolean;\n edgeWeight?: number;\n promptName: string;\n model: ResolvedModelConfig;\n link?: {\n edgeGlobalId: string;\n linkId?: string;\n confidence: number;\n writeLegacyTables: boolean;\n };\n statusUpdate?: {\n previousStatus?: string;\n newStatus: string;\n historyWritten: boolean;\n };\n};\n\nexport type ClassifyEvidenceBatchItem = {\n evidenceId?: string;\n insightId?: string;\n nodeId?: string;\n text?: string;\n};\n\nexport type ClassifyEvidenceBatchResult = {\n items: ClassifyEvidenceResult[];\n summary: {\n supporting: number;\n contradicting: number;\n irrelevant: number;\n };\n};\n\nexport type { PlatformGatewaySuccess } from \"./coreClient\";\n\n/** Configuration for the evidence classification client. */\nexport type EvidenceClientConfig = GatewayClientConfig;\n\n/**\n * Serializable config accepted by the HTTP SDK surface.\n * Runtime-only ports stay inside the kernel adapter.\n */\nexport type EvidenceClassificationRequestConfig =\n SerializableClassifyEvidenceConfig;\n\n/**\n * Create the evidence classification client.\n *\n * This surface mirrors the promoted kernel primitive through the platform\n * gateway. Auth-scoped callers do not provide `createdBy`; the gateway derives\n * it from the authenticated principal.\n */\nexport function createEvidenceClient(config: EvidenceClientConfig = {}) {\n const gateway = createGatewayRequestClient(config);\n\n return {\n async classifyEvidence(\n beliefId: string,\n evidenceId: string,\n classificationConfig?: EvidenceClassificationRequestConfig,\n idempotencyKey?: string\n ) {\n return gateway.request<ClassifyEvidenceResult>({\n path: \"/api/platform/v1/evidence/classify\",\n method: \"POST\",\n body: {\n beliefId,\n evidenceId,\n config: classificationConfig,\n },\n idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),\n });\n },\n\n async classifyEvidenceBatch(\n beliefId: string,\n evidence: ClassifyEvidenceBatchItem[],\n classificationConfig?: EvidenceClassificationRequestConfig,\n idempotencyKey?: string\n ) {\n return gateway.request<ClassifyEvidenceBatchResult>({\n path: \"/api/platform/v1/evidence/classify-batch\",\n method: \"POST\",\n body: {\n beliefId,\n evidence,\n config: classificationConfig,\n },\n idempotencyKey: idempotencyKey ?? randomIdempotencyKey(),\n });\n },\n };\n}\n"]}
|
package/dist/gatewayFacades.d.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { JsonObject, GraphNeighborhoodResponse, GraphAnalyticsMetric, TopicRecord, TopicListResponse, TopicTreeResponse, TopicCoverageResponse } from './types.js';
|
|
2
2
|
import { GatewayClientConfig, PlatformGatewaySuccess } from './coreClient.js';
|
|
3
|
+
import { ModulateConfidenceInput } from './beliefsClient.js';
|
|
3
4
|
import { OntologyBindingInput } from './ontologyClient.js';
|
|
4
5
|
import { TopicCreateInput, TopicListInput, TopicUpdateInput, TopicTreeQuery, TopicCoverageQuery, TopicBulkCreateInput } from './topicsClient.js';
|
|
5
6
|
import './contracts/workflow-runtime.contract.js';
|
|
6
7
|
import './contracts/lens-workflow.contract.js';
|
|
7
8
|
import './contracts/lens-filter.contract.js';
|
|
9
|
+
import './opinion.js';
|
|
8
10
|
|
|
9
11
|
type GatewayRecord = Record<string, unknown>;
|
|
10
12
|
type GatewayList = GatewayRecord & {
|
|
@@ -85,8 +87,9 @@ type EvidenceLinkResult = GatewayRecord & {
|
|
|
85
87
|
edgeId?: string;
|
|
86
88
|
};
|
|
87
89
|
type BeliefCreateInput = {
|
|
88
|
-
topicId
|
|
90
|
+
topicId?: string;
|
|
89
91
|
text: string;
|
|
92
|
+
baseRate?: number;
|
|
90
93
|
rationale?: string;
|
|
91
94
|
worktreeId?: string;
|
|
92
95
|
pillar?: string;
|
|
@@ -114,13 +117,7 @@ type BeliefForkInput = {
|
|
|
114
117
|
forkReason?: string;
|
|
115
118
|
rationale?: string;
|
|
116
119
|
};
|
|
117
|
-
type BeliefConfidenceInput =
|
|
118
|
-
confidence: number;
|
|
119
|
-
trigger?: string;
|
|
120
|
-
rationale: string;
|
|
121
|
-
certainty?: number;
|
|
122
|
-
maxInlinePropagationTargets?: number;
|
|
123
|
-
};
|
|
120
|
+
type BeliefConfidenceInput = ModulateConfidenceInput;
|
|
124
121
|
type BeliefArchiveInput = {
|
|
125
122
|
reason?: string;
|
|
126
123
|
rationale?: string;
|
|
@@ -156,11 +153,12 @@ type EdgeTraverseInput = {
|
|
|
156
153
|
topicId?: string;
|
|
157
154
|
};
|
|
158
155
|
type EvidenceCreateInput = {
|
|
159
|
-
topicId
|
|
156
|
+
topicId?: string;
|
|
160
157
|
text: string;
|
|
161
158
|
source?: string;
|
|
162
159
|
targetId?: string;
|
|
163
160
|
weight?: number;
|
|
161
|
+
rationale: string;
|
|
164
162
|
metadata?: JsonObject;
|
|
165
163
|
title?: string;
|
|
166
164
|
content?: string;
|
|
@@ -197,7 +195,7 @@ type QuestionsListQuery = {
|
|
|
197
195
|
cursor?: string;
|
|
198
196
|
};
|
|
199
197
|
type QuestionCreateInput = {
|
|
200
|
-
topicId
|
|
198
|
+
topicId?: string;
|
|
201
199
|
text: string;
|
|
202
200
|
priority?: string;
|
|
203
201
|
linkedBeliefId?: string;
|
|
@@ -270,7 +268,10 @@ type WorktreeCreateInput = {
|
|
|
270
268
|
beliefIds?: string[];
|
|
271
269
|
autoShape?: boolean;
|
|
272
270
|
domainPackId?: string;
|
|
273
|
-
|
|
271
|
+
campaign?: number;
|
|
272
|
+
lane?: string;
|
|
273
|
+
laneOrderInCampaign?: number;
|
|
274
|
+
orderInLane?: number;
|
|
274
275
|
dependsOn?: string[];
|
|
275
276
|
blocks?: string[];
|
|
276
277
|
gate?: string;
|
|
@@ -282,6 +283,9 @@ type WorktreeCreateInput = {
|
|
|
282
283
|
type WorktreeListQuery = {
|
|
283
284
|
topicId?: string;
|
|
284
285
|
status?: string;
|
|
286
|
+
groupBy?: "campaign" | "lane" | "flat";
|
|
287
|
+
lane?: string;
|
|
288
|
+
campaign?: number;
|
|
285
289
|
limit?: number;
|
|
286
290
|
};
|
|
287
291
|
type WorktreeActivateInput = {
|
|
@@ -292,10 +296,10 @@ type WorktreeUpdateInput = {
|
|
|
292
296
|
objective?: string;
|
|
293
297
|
hypothesis?: string;
|
|
294
298
|
rationale?: string;
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
+
campaign?: number;
|
|
300
|
+
lane?: string;
|
|
301
|
+
laneOrderInCampaign?: number;
|
|
302
|
+
orderInLane?: number;
|
|
299
303
|
dependsOn?: string[];
|
|
300
304
|
blocks?: string[];
|
|
301
305
|
gate?: string;
|
|
@@ -401,6 +405,7 @@ declare function createBeliefsFacade(config?: GatewayClientConfig): {
|
|
|
401
405
|
archive(id: string, input?: BeliefArchiveInput, idempotencyKey?: string): Promise<PlatformGatewaySuccess<GatewayRecord>>;
|
|
402
406
|
lineage(id: string): Promise<PlatformGatewaySuccess<BeliefsLineageResult>>;
|
|
403
407
|
confidenceHistory(id: string): Promise<PlatformGatewaySuccess<GatewayRecord>>;
|
|
408
|
+
opinionHistory(id: string): Promise<PlatformGatewaySuccess<GatewayRecord>>;
|
|
404
409
|
createContract(id: string, input: BeliefContractInput, idempotencyKey?: string): Promise<PlatformGatewaySuccess<GatewayRecord>>;
|
|
405
410
|
bisect(id: string, input: BeliefBisectInput, idempotencyKey?: string): Promise<PlatformGatewaySuccess<GatewayRecord>>;
|
|
406
411
|
};
|
|
@@ -562,6 +567,11 @@ declare function createWebhooksFacade(config?: GatewayClientConfig): {
|
|
|
562
567
|
declare function createWorktreesFacade(config?: GatewayClientConfig): {
|
|
563
568
|
create(input: WorktreeCreateInput, idempotencyKey?: string): Promise<PlatformGatewaySuccess<GatewayRecord>>;
|
|
564
569
|
list(query: WorktreeListQuery): Promise<PlatformGatewaySuccess<WorktreesListResult>>;
|
|
570
|
+
listCampaigns(query?: {
|
|
571
|
+
topicId?: string;
|
|
572
|
+
status?: string;
|
|
573
|
+
limit?: number;
|
|
574
|
+
}): Promise<PlatformGatewaySuccess<GatewayRecord>>;
|
|
565
575
|
activate(input: WorktreeActivateInput, idempotencyKey?: string): Promise<PlatformGatewaySuccess<GatewayRecord>>;
|
|
566
576
|
update(input: WorktreeUpdateInput, idempotencyKey?: string): Promise<PlatformGatewaySuccess<GatewayRecord>>;
|
|
567
577
|
merge(input: WorktreeMergeInput, idempotencyKey?: string): Promise<PlatformGatewaySuccess<GatewayRecord>>;
|