@fulcrum-governance/sdk 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +42 -1
  2. package/README.md +299 -6
  3. package/dist/__tests__/clients.test.d.ts +1 -0
  4. package/dist/__tests__/clients.test.js +847 -0
  5. package/dist/clients/agent.d.ts +70 -0
  6. package/dist/clients/agent.js +127 -0
  7. package/dist/clients/approval.d.ts +67 -0
  8. package/dist/clients/approval.js +103 -0
  9. package/dist/clients/budget.d.ts +221 -0
  10. package/dist/clients/budget.js +181 -0
  11. package/dist/clients/checkpoint.d.ts +191 -0
  12. package/dist/clients/checkpoint.js +195 -0
  13. package/dist/clients/envelope.d.ts +73 -0
  14. package/dist/clients/envelope.js +95 -0
  15. package/dist/clients/eventstore.d.ts +87 -0
  16. package/dist/clients/eventstore.js +113 -0
  17. package/dist/clients/index.d.ts +15 -0
  18. package/dist/clients/index.js +35 -0
  19. package/dist/clients/metrics.d.ts +126 -0
  20. package/dist/clients/metrics.js +162 -0
  21. package/dist/clients/policy.d.ts +83 -0
  22. package/dist/clients/policy.js +102 -0
  23. package/dist/clients/tenant.d.ts +66 -0
  24. package/dist/clients/tenant.js +92 -0
  25. package/dist/index.d.ts +1 -0
  26. package/dist/index.js +25 -3
  27. package/dist/instrumentation/__tests__/autoGovern.test.d.ts +6 -0
  28. package/dist/instrumentation/__tests__/autoGovern.test.js +416 -0
  29. package/dist/instrumentation/__tests__/evaluator.test.d.ts +6 -0
  30. package/dist/instrumentation/__tests__/evaluator.test.js +712 -0
  31. package/dist/instrumentation/autoGovern.d.ts +57 -0
  32. package/dist/instrumentation/autoGovern.js +319 -0
  33. package/dist/instrumentation/evaluator.d.ts +50 -0
  34. package/dist/instrumentation/evaluator.js +218 -0
  35. package/dist/instrumentation/index.d.ts +28 -0
  36. package/dist/instrumentation/index.js +34 -0
  37. package/dist/instrumentation/types.d.ts +105 -0
  38. package/dist/instrumentation/types.js +20 -0
  39. package/package.json +4 -4
  40. package/proto/fulcrum/agent/v1/agent_service.proto +170 -0
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ /**
3
+ * EnvelopeClient - REST-based client for envelope management
4
+ *
5
+ * Works with the Fulcrum API for managing execution envelopes that wrap AI agent operations.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.EnvelopeClient = exports.EnvelopeClientError = void 0;
9
+ class EnvelopeClientError extends Error {
10
+ constructor(message, statusCode, response) {
11
+ super(message);
12
+ this.statusCode = statusCode;
13
+ this.response = response;
14
+ this.name = 'EnvelopeClientError';
15
+ }
16
+ }
17
+ exports.EnvelopeClientError = EnvelopeClientError;
18
+ class EnvelopeClient {
19
+ constructor(options) {
20
+ this.baseUrl = options.baseUrl.replace(/\/$/, '');
21
+ this.apiKey = options.apiKey;
22
+ this.timeout = options.timeout || 30000;
23
+ }
24
+ async request(method, path, body, params) {
25
+ const url = new URL(`${this.baseUrl}${path}`);
26
+ if (params) {
27
+ Object.entries(params).forEach(([key, value]) => {
28
+ if (value !== undefined && value !== null) {
29
+ url.searchParams.append(key, value);
30
+ }
31
+ });
32
+ }
33
+ const controller = new AbortController();
34
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
35
+ try {
36
+ const response = await fetch(url.toString(), {
37
+ method,
38
+ headers: {
39
+ 'Content-Type': 'application/json',
40
+ 'X-API-Key': this.apiKey,
41
+ },
42
+ body: body ? JSON.stringify(body) : undefined,
43
+ signal: controller.signal,
44
+ });
45
+ if (!response.ok) {
46
+ const error = await response.json().catch(() => ({}));
47
+ throw new EnvelopeClientError(error.message || `Request failed with status ${response.status}`, response.status, error);
48
+ }
49
+ return await response.json();
50
+ }
51
+ finally {
52
+ clearTimeout(timeoutId);
53
+ }
54
+ }
55
+ /**
56
+ * Create a new execution envelope.
57
+ */
58
+ async create(request) {
59
+ const response = await this.request('POST', '/v1/envelopes', request);
60
+ return response.envelope;
61
+ }
62
+ /**
63
+ * Get an envelope by ID.
64
+ */
65
+ async get(envelopeId) {
66
+ const response = await this.request('GET', `/v1/envelopes/${envelopeId}`);
67
+ return response.envelope;
68
+ }
69
+ /**
70
+ * Update the status of an envelope.
71
+ */
72
+ async updateStatus(request) {
73
+ const { envelope_id, ...body } = request;
74
+ const response = await this.request('PATCH', `/v1/envelopes/${envelope_id}/status`, body);
75
+ return response.envelope;
76
+ }
77
+ /**
78
+ * List envelopes with optional filters.
79
+ */
80
+ async list(request = {}) {
81
+ const params = {
82
+ limit: String(request.limit || 100),
83
+ offset: String(request.offset || 0),
84
+ };
85
+ if (request.tenant_id)
86
+ params.tenant_id = request.tenant_id;
87
+ if (request.workflow_id)
88
+ params.workflow_id = request.workflow_id;
89
+ if (request.status)
90
+ params.status = request.status;
91
+ const response = await this.request('GET', '/v1/envelopes', undefined, params);
92
+ return response.envelopes;
93
+ }
94
+ }
95
+ exports.EnvelopeClient = EnvelopeClient;
@@ -0,0 +1,87 @@
1
+ /**
2
+ * EventStoreClient - REST-based client for event store operations
3
+ *
4
+ * Works with the Fulcrum API for managing and querying execution events.
5
+ */
6
+ export interface StoredEvent {
7
+ event_id: string;
8
+ execution_id: string;
9
+ envelope_id: string;
10
+ tenant_id: string;
11
+ workflow_id: string;
12
+ event_type: string;
13
+ timestamp: string;
14
+ data: Record<string, unknown>;
15
+ metadata: Record<string, string>;
16
+ parent_event_id?: string;
17
+ trace_id?: string;
18
+ span_id?: string;
19
+ }
20
+ export interface EventStoreStats {
21
+ total_events: number;
22
+ events_by_type: Record<string, number>;
23
+ events_by_tenant: Record<string, number>;
24
+ oldest_event?: string;
25
+ newest_event?: string;
26
+ storage_size_bytes: number;
27
+ }
28
+ export interface PublishEventRequest {
29
+ execution_id: string;
30
+ envelope_id: string;
31
+ tenant_id: string;
32
+ workflow_id: string;
33
+ event_type: string;
34
+ data: Record<string, unknown>;
35
+ metadata?: Record<string, string>;
36
+ parent_event_id?: string;
37
+ trace_id?: string;
38
+ span_id?: string;
39
+ }
40
+ export interface QueryEventsRequest {
41
+ tenant_id?: string;
42
+ execution_ids?: string[];
43
+ envelope_ids?: string[];
44
+ workflow_ids?: string[];
45
+ event_types?: string[];
46
+ start_time?: string;
47
+ end_time?: string;
48
+ limit?: number;
49
+ offset?: number;
50
+ }
51
+ export declare class EventStoreClientError extends Error {
52
+ statusCode?: number | undefined;
53
+ response?: unknown | undefined;
54
+ constructor(message: string, statusCode?: number | undefined, response?: unknown | undefined);
55
+ }
56
+ export interface EventStoreClientOptions {
57
+ baseUrl: string;
58
+ apiKey: string;
59
+ timeout?: number;
60
+ }
61
+ export declare class EventStoreClient {
62
+ private baseUrl;
63
+ private apiKey;
64
+ private timeout;
65
+ constructor(options: EventStoreClientOptions);
66
+ private request;
67
+ /**
68
+ * Publish a single event to the event store.
69
+ */
70
+ publishEvent(request: PublishEventRequest): Promise<StoredEvent>;
71
+ /**
72
+ * Publish multiple events in a single batch.
73
+ */
74
+ publishEventBatch(events: PublishEventRequest[]): Promise<StoredEvent[]>;
75
+ /**
76
+ * Query events with various filters.
77
+ */
78
+ queryEvents(request: QueryEventsRequest): Promise<StoredEvent[]>;
79
+ /**
80
+ * Get all events for a specific execution.
81
+ */
82
+ getExecutionEvents(executionId: string, limit?: number, offset?: number): Promise<StoredEvent[]>;
83
+ /**
84
+ * Get event store statistics.
85
+ */
86
+ getStats(): Promise<EventStoreStats>;
87
+ }
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ /**
3
+ * EventStoreClient - REST-based client for event store operations
4
+ *
5
+ * Works with the Fulcrum API for managing and querying execution events.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.EventStoreClient = exports.EventStoreClientError = void 0;
9
+ class EventStoreClientError extends Error {
10
+ constructor(message, statusCode, response) {
11
+ super(message);
12
+ this.statusCode = statusCode;
13
+ this.response = response;
14
+ this.name = 'EventStoreClientError';
15
+ }
16
+ }
17
+ exports.EventStoreClientError = EventStoreClientError;
18
+ class EventStoreClient {
19
+ constructor(options) {
20
+ this.baseUrl = options.baseUrl.replace(/\/$/, '');
21
+ this.apiKey = options.apiKey;
22
+ this.timeout = options.timeout || 30000;
23
+ }
24
+ async request(method, path, body, params) {
25
+ const url = new URL(`${this.baseUrl}${path}`);
26
+ if (params) {
27
+ Object.entries(params).forEach(([key, value]) => {
28
+ if (value !== undefined && value !== null) {
29
+ url.searchParams.append(key, value);
30
+ }
31
+ });
32
+ }
33
+ const controller = new AbortController();
34
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
35
+ try {
36
+ const response = await fetch(url.toString(), {
37
+ method,
38
+ headers: {
39
+ 'Content-Type': 'application/json',
40
+ 'X-API-Key': this.apiKey,
41
+ },
42
+ body: body ? JSON.stringify(body) : undefined,
43
+ signal: controller.signal,
44
+ });
45
+ if (!response.ok) {
46
+ const error = await response.json().catch(() => ({}));
47
+ throw new EventStoreClientError(error.message || `Request failed with status ${response.status}`, response.status, error);
48
+ }
49
+ return await response.json();
50
+ }
51
+ finally {
52
+ clearTimeout(timeoutId);
53
+ }
54
+ }
55
+ /**
56
+ * Publish a single event to the event store.
57
+ */
58
+ async publishEvent(request) {
59
+ const response = await this.request('POST', '/v1/events', request);
60
+ return response.event;
61
+ }
62
+ /**
63
+ * Publish multiple events in a single batch.
64
+ */
65
+ async publishEventBatch(events) {
66
+ const response = await this.request('POST', '/v1/events/batch', { events });
67
+ return response.events;
68
+ }
69
+ /**
70
+ * Query events with various filters.
71
+ */
72
+ async queryEvents(request) {
73
+ const params = {
74
+ limit: String(request.limit || 100),
75
+ offset: String(request.offset || 0),
76
+ };
77
+ if (request.tenant_id)
78
+ params.tenant_id = request.tenant_id;
79
+ if (request.execution_ids)
80
+ params.execution_ids = request.execution_ids.join(',');
81
+ if (request.envelope_ids)
82
+ params.envelope_ids = request.envelope_ids.join(',');
83
+ if (request.workflow_ids)
84
+ params.workflow_ids = request.workflow_ids.join(',');
85
+ if (request.event_types)
86
+ params.event_types = request.event_types.join(',');
87
+ if (request.start_time)
88
+ params.start_time = request.start_time;
89
+ if (request.end_time)
90
+ params.end_time = request.end_time;
91
+ const response = await this.request('GET', '/v1/events', undefined, params);
92
+ return response.events;
93
+ }
94
+ /**
95
+ * Get all events for a specific execution.
96
+ */
97
+ async getExecutionEvents(executionId, limit = 100, offset = 0) {
98
+ const params = {
99
+ limit: String(limit),
100
+ offset: String(offset),
101
+ };
102
+ const response = await this.request('GET', `/v1/executions/${executionId}/events`, undefined, params);
103
+ return response.events;
104
+ }
105
+ /**
106
+ * Get event store statistics.
107
+ */
108
+ async getStats() {
109
+ const response = await this.request('GET', '/v1/events/stats');
110
+ return response.stats;
111
+ }
112
+ }
113
+ exports.EventStoreClient = EventStoreClient;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Fulcrum SDK REST Clients
3
+ *
4
+ * These clients provide REST-based access to Fulcrum Dashboard APIs
5
+ * for managing policies, approvals, budgets, checkpoints, and other resources.
6
+ */
7
+ export { PolicyClient, PolicyClientError, type Policy, type PolicyFilter, type CreatePolicyRequest, type UpdatePolicyRequest, type PolicyClientOptions, } from './policy';
8
+ export { ApprovalClient, ApprovalClientError, type Approval, type ApprovalFilter, type ApprovalDecision, type ApprovalClientOptions, } from './approval';
9
+ export { BudgetClient, BudgetClientError, type Budget, type BudgetSummary, type BudgetsResponse, type BudgetFilter, type CreateBudgetRequest, type UpdateBudgetRequest, type BudgetClientOptions, type BudgetScope, type BudgetPeriod, type BudgetAction, type BudgetStatus, type CostSummary, type SpendSummary, type SpendSummaryOptions, type SpendSummaryResponse, type GroupedSpendSummary, type SpendGroupBy, type BudgetStatusDetail, type PredictCostRequest, type CostPrediction, type ModelCostPrediction, } from './budget';
10
+ export { MetricsClient, MetricsClientError, type PublicMetrics, type CognitiveLayerMetrics, type AuditLogEntry, type AuditLogsResponse, type AuditLogPagination, type AuditLogActor, type AuditLogFilter, type ResourceType, type MetricsClientOptions, } from './metrics';
11
+ export { CheckpointClient, CheckpointClientError, type Checkpoint, type CheckpointMetadata, type CheckpointVersion, type CheckpointData, type CheckpointQuery, type CheckpointType, type ContextScope, type MergeStrategy, type ExecutionContext, type SaveCheckpointRequest, type SaveCheckpointResponse, type ListCheckpointsOptions, type ListCheckpointsResponse, type ListVersionsResponse, type UpdateContextRequest, type UpdateContextResponse, type CheckpointClientOptions, } from './checkpoint';
12
+ export { EventStoreClient, EventStoreClientError, type StoredEvent, type EventStoreStats, type PublishEventRequest, type QueryEventsRequest, type EventStoreClientOptions, } from './eventstore';
13
+ export { EnvelopeClient, EnvelopeClientError, type EnvelopeData, type EnvelopeStatus, type CreateEnvelopeRequest, type UpdateEnvelopeStatusRequest, type ListEnvelopesRequest, type EnvelopeClientOptions, } from './envelope';
14
+ export { TenantClient, TenantClientError, type ApiKey, type CreateApiKeyRequest, type CreateApiKeyResponse, type ListApiKeysRequest, type ListApiKeysResponse, type TenantClientOptions, } from './tenant';
15
+ export { AgentClient, type Agent, type CreateAgentRequest, type UpdateAgentRequest, type ListAgentsRequest, type ListAgentsResponse, } from './agent';
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ /**
3
+ * Fulcrum SDK REST Clients
4
+ *
5
+ * These clients provide REST-based access to Fulcrum Dashboard APIs
6
+ * for managing policies, approvals, budgets, checkpoints, and other resources.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.AgentClient = exports.TenantClientError = exports.TenantClient = exports.EnvelopeClientError = exports.EnvelopeClient = exports.EventStoreClientError = exports.EventStoreClient = exports.CheckpointClientError = exports.CheckpointClient = exports.MetricsClientError = exports.MetricsClient = exports.BudgetClientError = exports.BudgetClient = exports.ApprovalClientError = exports.ApprovalClient = exports.PolicyClientError = exports.PolicyClient = void 0;
10
+ var policy_1 = require("./policy");
11
+ Object.defineProperty(exports, "PolicyClient", { enumerable: true, get: function () { return policy_1.PolicyClient; } });
12
+ Object.defineProperty(exports, "PolicyClientError", { enumerable: true, get: function () { return policy_1.PolicyClientError; } });
13
+ var approval_1 = require("./approval");
14
+ Object.defineProperty(exports, "ApprovalClient", { enumerable: true, get: function () { return approval_1.ApprovalClient; } });
15
+ Object.defineProperty(exports, "ApprovalClientError", { enumerable: true, get: function () { return approval_1.ApprovalClientError; } });
16
+ var budget_1 = require("./budget");
17
+ Object.defineProperty(exports, "BudgetClient", { enumerable: true, get: function () { return budget_1.BudgetClient; } });
18
+ Object.defineProperty(exports, "BudgetClientError", { enumerable: true, get: function () { return budget_1.BudgetClientError; } });
19
+ var metrics_1 = require("./metrics");
20
+ Object.defineProperty(exports, "MetricsClient", { enumerable: true, get: function () { return metrics_1.MetricsClient; } });
21
+ Object.defineProperty(exports, "MetricsClientError", { enumerable: true, get: function () { return metrics_1.MetricsClientError; } });
22
+ var checkpoint_1 = require("./checkpoint");
23
+ Object.defineProperty(exports, "CheckpointClient", { enumerable: true, get: function () { return checkpoint_1.CheckpointClient; } });
24
+ Object.defineProperty(exports, "CheckpointClientError", { enumerable: true, get: function () { return checkpoint_1.CheckpointClientError; } });
25
+ var eventstore_1 = require("./eventstore");
26
+ Object.defineProperty(exports, "EventStoreClient", { enumerable: true, get: function () { return eventstore_1.EventStoreClient; } });
27
+ Object.defineProperty(exports, "EventStoreClientError", { enumerable: true, get: function () { return eventstore_1.EventStoreClientError; } });
28
+ var envelope_1 = require("./envelope");
29
+ Object.defineProperty(exports, "EnvelopeClient", { enumerable: true, get: function () { return envelope_1.EnvelopeClient; } });
30
+ Object.defineProperty(exports, "EnvelopeClientError", { enumerable: true, get: function () { return envelope_1.EnvelopeClientError; } });
31
+ var tenant_1 = require("./tenant");
32
+ Object.defineProperty(exports, "TenantClient", { enumerable: true, get: function () { return tenant_1.TenantClient; } });
33
+ Object.defineProperty(exports, "TenantClientError", { enumerable: true, get: function () { return tenant_1.TenantClientError; } });
34
+ var agent_1 = require("./agent");
35
+ Object.defineProperty(exports, "AgentClient", { enumerable: true, get: function () { return agent_1.AgentClient; } });
@@ -0,0 +1,126 @@
1
+ /**
2
+ * MetricsClient - REST-based client for observability and metrics operations
3
+ *
4
+ * Works with the Fulcrum Dashboard REST API for retrieving metrics and audit logs.
5
+ */
6
+ export interface CognitiveLayerMetrics {
7
+ semanticJudgeRequests: number;
8
+ semanticJudgeViolations: number;
9
+ oraclePredictions: number;
10
+ oracleSavings: number;
11
+ immunePoliciesGenerated: number;
12
+ }
13
+ export interface PublicMetrics {
14
+ lastUpdated: string;
15
+ policiesEvaluated24h: number;
16
+ avgLatencyMs: number;
17
+ budgetAlerts24h: number;
18
+ activeTenants: number;
19
+ blockedRequests24h: number;
20
+ cognitiveLayer: CognitiveLayerMetrics;
21
+ }
22
+ export type ResourceType = 'User' | 'Policy' | 'Budget' | 'APIKey' | 'Workflow' | 'Envelope' | 'Approval';
23
+ export interface AuditLogEntry {
24
+ id: string;
25
+ org_id: string;
26
+ timestamp: string;
27
+ actor_id: string;
28
+ actor_email: string;
29
+ action: string;
30
+ resource_type: ResourceType;
31
+ resource_id?: string;
32
+ resource_name?: string;
33
+ changes?: Record<string, {
34
+ old: unknown;
35
+ new: unknown;
36
+ }>;
37
+ ip_address?: string;
38
+ user_agent?: string;
39
+ status: 'success' | 'failure';
40
+ error_message?: string;
41
+ }
42
+ export interface AuditLogPagination {
43
+ page: number;
44
+ pageSize: number;
45
+ totalCount: number;
46
+ totalPages: number;
47
+ }
48
+ export interface AuditLogActor {
49
+ id: string;
50
+ email: string;
51
+ }
52
+ export interface AuditLogsResponse {
53
+ logs: AuditLogEntry[];
54
+ pagination: AuditLogPagination;
55
+ actors: AuditLogActor[];
56
+ }
57
+ export interface AuditLogFilter {
58
+ user_id?: string;
59
+ resource_type?: ResourceType;
60
+ start_date?: string;
61
+ end_date?: string;
62
+ search?: string;
63
+ page?: number;
64
+ page_size?: number;
65
+ }
66
+ export interface MetricsClientOptions {
67
+ baseUrl: string;
68
+ apiKey?: string;
69
+ timeoutMs?: number;
70
+ }
71
+ export declare class MetricsClient {
72
+ private baseUrl;
73
+ private apiKey?;
74
+ private timeoutMs;
75
+ constructor(options: MetricsClientOptions);
76
+ private request;
77
+ /**
78
+ * Get public metrics (no authentication required)
79
+ * Returns 24h aggregated metrics including cognitive layer stats
80
+ */
81
+ getPublicMetrics(): Promise<PublicMetrics>;
82
+ /**
83
+ * Get just the cognitive layer metrics
84
+ */
85
+ getCognitiveMetrics(): Promise<CognitiveLayerMetrics>;
86
+ /**
87
+ * Get average latency in milliseconds
88
+ */
89
+ getAverageLatency(): Promise<number>;
90
+ /**
91
+ * Get 24h policy evaluation count
92
+ */
93
+ getPolicyEvaluationCount(): Promise<number>;
94
+ /**
95
+ * Get audit logs with filtering and pagination
96
+ */
97
+ getAuditLogs(filter?: AuditLogFilter): Promise<AuditLogsResponse>;
98
+ /**
99
+ * Get only the audit log entries
100
+ */
101
+ listAuditLogs(filter?: AuditLogFilter): Promise<AuditLogEntry[]>;
102
+ /**
103
+ * Get audit logs for a specific resource type
104
+ */
105
+ getLogsByResourceType(resourceType: ResourceType, page?: number): Promise<AuditLogEntry[]>;
106
+ /**
107
+ * Get audit logs for a specific user
108
+ */
109
+ getLogsByUser(userId: string, page?: number): Promise<AuditLogEntry[]>;
110
+ /**
111
+ * Get audit logs within a date range
112
+ */
113
+ getLogsByDateRange(startDate: Date, endDate: Date, page?: number): Promise<AuditLogEntry[]>;
114
+ /**
115
+ * Search audit logs by text
116
+ */
117
+ searchAuditLogs(searchTerm: string, page?: number): Promise<AuditLogEntry[]>;
118
+ /**
119
+ * Get the list of unique actors from audit logs
120
+ */
121
+ getAuditLogActors(): Promise<AuditLogActor[]>;
122
+ }
123
+ export declare class MetricsClientError extends Error {
124
+ statusCode: number;
125
+ constructor(message: string, statusCode: number);
126
+ }
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ /**
3
+ * MetricsClient - REST-based client for observability and metrics operations
4
+ *
5
+ * Works with the Fulcrum Dashboard REST API for retrieving metrics and audit logs.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.MetricsClientError = exports.MetricsClient = void 0;
9
+ class MetricsClient {
10
+ constructor(options) {
11
+ this.baseUrl = options.baseUrl.replace(/\/$/, '');
12
+ this.apiKey = options.apiKey;
13
+ this.timeoutMs = options.timeoutMs || 5000;
14
+ }
15
+ async request(method, path, body) {
16
+ const controller = new AbortController();
17
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
18
+ try {
19
+ const headers = {
20
+ 'Content-Type': 'application/json',
21
+ };
22
+ if (this.apiKey) {
23
+ headers['Authorization'] = `Bearer ${this.apiKey}`;
24
+ }
25
+ const response = await fetch(`${this.baseUrl}${path}`, {
26
+ method,
27
+ headers,
28
+ body: body ? JSON.stringify(body) : undefined,
29
+ signal: controller.signal,
30
+ });
31
+ if (!response.ok) {
32
+ const errorData = (await response.json().catch(() => ({})));
33
+ throw new MetricsClientError(errorData.error || `Request failed with status ${response.status}`, response.status);
34
+ }
35
+ return (await response.json());
36
+ }
37
+ finally {
38
+ clearTimeout(timeout);
39
+ }
40
+ }
41
+ // =====================
42
+ // Public Metrics
43
+ // =====================
44
+ /**
45
+ * Get public metrics (no authentication required)
46
+ * Returns 24h aggregated metrics including cognitive layer stats
47
+ */
48
+ async getPublicMetrics() {
49
+ return this.request('GET', '/api/metrics/public');
50
+ }
51
+ /**
52
+ * Get just the cognitive layer metrics
53
+ */
54
+ async getCognitiveMetrics() {
55
+ const metrics = await this.getPublicMetrics();
56
+ return metrics.cognitiveLayer;
57
+ }
58
+ /**
59
+ * Get average latency in milliseconds
60
+ */
61
+ async getAverageLatency() {
62
+ const metrics = await this.getPublicMetrics();
63
+ return metrics.avgLatencyMs;
64
+ }
65
+ /**
66
+ * Get 24h policy evaluation count
67
+ */
68
+ async getPolicyEvaluationCount() {
69
+ const metrics = await this.getPublicMetrics();
70
+ return metrics.policiesEvaluated24h;
71
+ }
72
+ // =====================
73
+ // Audit Logs
74
+ // =====================
75
+ /**
76
+ * Get audit logs with filtering and pagination
77
+ */
78
+ async getAuditLogs(filter) {
79
+ const params = new URLSearchParams();
80
+ if (filter?.user_id)
81
+ params.append('user_id', filter.user_id);
82
+ if (filter?.resource_type)
83
+ params.append('resource_type', filter.resource_type);
84
+ if (filter?.start_date)
85
+ params.append('start_date', filter.start_date);
86
+ if (filter?.end_date)
87
+ params.append('end_date', filter.end_date);
88
+ if (filter?.search)
89
+ params.append('search', filter.search);
90
+ if (filter?.page)
91
+ params.append('page', String(filter.page));
92
+ if (filter?.page_size)
93
+ params.append('page_size', String(filter.page_size));
94
+ const query = params.toString();
95
+ const path = query ? `/api/audit-logs?${query}` : '/api/audit-logs';
96
+ return this.request('GET', path);
97
+ }
98
+ /**
99
+ * Get only the audit log entries
100
+ */
101
+ async listAuditLogs(filter) {
102
+ const response = await this.getAuditLogs(filter);
103
+ return response.logs;
104
+ }
105
+ /**
106
+ * Get audit logs for a specific resource type
107
+ */
108
+ async getLogsByResourceType(resourceType, page) {
109
+ const response = await this.getAuditLogs({
110
+ resource_type: resourceType,
111
+ page,
112
+ });
113
+ return response.logs;
114
+ }
115
+ /**
116
+ * Get audit logs for a specific user
117
+ */
118
+ async getLogsByUser(userId, page) {
119
+ const response = await this.getAuditLogs({
120
+ user_id: userId,
121
+ page,
122
+ });
123
+ return response.logs;
124
+ }
125
+ /**
126
+ * Get audit logs within a date range
127
+ */
128
+ async getLogsByDateRange(startDate, endDate, page) {
129
+ const response = await this.getAuditLogs({
130
+ start_date: startDate.toISOString(),
131
+ end_date: endDate.toISOString(),
132
+ page,
133
+ });
134
+ return response.logs;
135
+ }
136
+ /**
137
+ * Search audit logs by text
138
+ */
139
+ async searchAuditLogs(searchTerm, page) {
140
+ const response = await this.getAuditLogs({
141
+ search: searchTerm,
142
+ page,
143
+ });
144
+ return response.logs;
145
+ }
146
+ /**
147
+ * Get the list of unique actors from audit logs
148
+ */
149
+ async getAuditLogActors() {
150
+ const response = await this.getAuditLogs({ page_size: 1 });
151
+ return response.actors;
152
+ }
153
+ }
154
+ exports.MetricsClient = MetricsClient;
155
+ class MetricsClientError extends Error {
156
+ constructor(message, statusCode) {
157
+ super(message);
158
+ this.statusCode = statusCode;
159
+ this.name = 'MetricsClientError';
160
+ }
161
+ }
162
+ exports.MetricsClientError = MetricsClientError;