@artemiskit/sdk 0.3.1 → 0.4.0

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 (78) hide show
  1. package/CHANGELOG.md +229 -0
  2. package/README.md +44 -1
  3. package/dist/artemiskit.d.ts +149 -0
  4. package/dist/artemiskit.d.ts.map +1 -0
  5. package/dist/builders/index.d.ts +352 -0
  6. package/dist/builders/index.d.ts.map +1 -0
  7. package/dist/builders/index.js +354 -0
  8. package/dist/contracts/index.d.ts +253 -0
  9. package/dist/contracts/index.d.ts.map +1 -0
  10. package/dist/contracts/index.js +53 -0
  11. package/dist/guardian/action-validator.d.ts +92 -0
  12. package/dist/guardian/action-validator.d.ts.map +1 -0
  13. package/dist/guardian/circuit-breaker.d.ts +211 -0
  14. package/dist/guardian/circuit-breaker.d.ts.map +1 -0
  15. package/dist/guardian/guardian.d.ts +213 -0
  16. package/dist/guardian/guardian.d.ts.map +1 -0
  17. package/dist/guardian/guardrails.d.ts +107 -0
  18. package/dist/guardian/guardrails.d.ts.map +1 -0
  19. package/dist/guardian/index.d.ts +35 -0
  20. package/dist/guardian/index.d.ts.map +1 -0
  21. package/dist/guardian/intent-classifier.d.ts +81 -0
  22. package/dist/guardian/intent-classifier.d.ts.map +1 -0
  23. package/dist/guardian/interceptor.d.ts +141 -0
  24. package/dist/guardian/interceptor.d.ts.map +1 -0
  25. package/dist/guardian/policy.d.ts +52 -0
  26. package/dist/guardian/policy.d.ts.map +1 -0
  27. package/dist/guardian/semantic-validator.d.ts +61 -0
  28. package/dist/guardian/semantic-validator.d.ts.map +1 -0
  29. package/dist/guardian/types.d.ts +653 -0
  30. package/dist/guardian/types.d.ts.map +1 -0
  31. package/dist/index.d.ts +23 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +44918 -28644
  34. package/dist/matchers/core.d.ts +81 -0
  35. package/dist/matchers/core.d.ts.map +1 -0
  36. package/dist/matchers/index.d.ts +6 -0
  37. package/dist/matchers/index.d.ts.map +1 -0
  38. package/dist/matchers/index.js +13 -59
  39. package/dist/matchers/jest.d.ts +46 -0
  40. package/dist/matchers/jest.d.ts.map +1 -0
  41. package/dist/matchers/jest.js +0 -46
  42. package/dist/matchers/vitest.d.ts +24 -0
  43. package/dist/matchers/vitest.d.ts.map +1 -0
  44. package/dist/matchers/vitest.js +0 -46
  45. package/dist/types-only.d.ts +31 -0
  46. package/dist/types-only.d.ts.map +1 -0
  47. package/dist/types-only.js +1 -0
  48. package/dist/types.d.ts +379 -0
  49. package/dist/types.d.ts.map +1 -0
  50. package/dist/utils/index.d.ts +112 -0
  51. package/dist/utils/index.d.ts.map +1 -0
  52. package/dist/utils/index.js +58 -0
  53. package/package.json +19 -4
  54. package/src/__tests__/builders.test.ts +450 -0
  55. package/src/__tests__/circuit-breaker.test.ts +704 -0
  56. package/src/__tests__/compare.test.ts +469 -0
  57. package/src/__tests__/contracts.test.ts +354 -0
  58. package/src/__tests__/guardian-modes.test.ts +215 -0
  59. package/src/__tests__/guardrails.test.ts +404 -0
  60. package/src/__tests__/semantic-validator.test.ts +421 -0
  61. package/src/__tests__/utils.test.ts +324 -0
  62. package/src/__tests__/validate.test.ts +310 -0
  63. package/src/artemiskit.ts +479 -5
  64. package/src/builders/index.ts +700 -0
  65. package/src/contracts/index.ts +357 -0
  66. package/src/guardian/circuit-breaker.ts +74 -28
  67. package/src/guardian/guardian.ts +307 -20
  68. package/src/guardian/guardrails.ts +143 -1
  69. package/src/guardian/index.ts +35 -1
  70. package/src/guardian/interceptor.ts +87 -11
  71. package/src/guardian/semantic-validator.ts +399 -0
  72. package/src/guardian/types.ts +413 -2
  73. package/src/index.ts +258 -14
  74. package/src/types-only.ts +276 -0
  75. package/src/types.ts +186 -0
  76. package/src/utils/index.ts +225 -0
  77. package/tsconfig.json +2 -1
  78. package/adapters/openai/dist/index.js +0 -5625
@@ -0,0 +1,253 @@
1
+ /**
2
+ * @artemiskit/sdk
3
+ * Contract types for custom implementations
4
+ *
5
+ * These types define the contracts that custom adapters, evaluators,
6
+ * and storage backends must implement to integrate with ArtemisKit.
7
+ */
8
+ import type { Evaluator, EvaluatorContext, EvaluatorResult, Expected, GenerateOptions, GenerateResult, ModelCapabilities, ModelClient, StorageAdapter } from '@artemiskit/core';
9
+ /**
10
+ * Contract for implementing custom model adapters
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * import { defineAdapter, type AdapterContract } from '@artemiskit/sdk'
15
+ *
16
+ * const myAdapter = defineAdapter({
17
+ * provider: 'my-provider',
18
+ * async generate(options) {
19
+ * // Implementation
20
+ * return { id: '...', model: '...', text: '...', tokens: {...}, latencyMs: 0 }
21
+ * },
22
+ * async capabilities() {
23
+ * return { streaming: false, functionCalling: false, toolUse: false, maxContext: 4096 }
24
+ * }
25
+ * })
26
+ * ```
27
+ */
28
+ export interface AdapterContract extends ModelClient {
29
+ /**
30
+ * Provider identifier - must be unique
31
+ */
32
+ readonly provider: string;
33
+ /**
34
+ * Generate a completion from the model
35
+ */
36
+ generate(options: GenerateOptions): Promise<GenerateResult>;
37
+ /**
38
+ * Get the capabilities of this adapter
39
+ */
40
+ capabilities(): Promise<ModelCapabilities>;
41
+ /**
42
+ * Optional: Stream a completion from the model
43
+ */
44
+ stream?(options: GenerateOptions, onChunk: (chunk: string) => void): AsyncIterable<string>;
45
+ /**
46
+ * Optional: Generate embeddings
47
+ */
48
+ embed?(text: string, model?: string): Promise<number[]>;
49
+ /**
50
+ * Optional: Close/cleanup resources
51
+ */
52
+ close?(): Promise<void>;
53
+ }
54
+ /**
55
+ * Define a custom adapter with type checking
56
+ *
57
+ * @example
58
+ * ```typescript
59
+ * const myAdapter = defineAdapter({
60
+ * provider: 'my-llm',
61
+ * async generate(options) {
62
+ * const response = await myLLMClient.complete(options.prompt)
63
+ * return {
64
+ * id: response.id,
65
+ * model: 'my-model',
66
+ * text: response.text,
67
+ * tokens: { prompt: 0, completion: 0, total: 0 },
68
+ * latencyMs: response.duration
69
+ * }
70
+ * },
71
+ * async capabilities() {
72
+ * return { streaming: true, functionCalling: false, toolUse: false, maxContext: 8192 }
73
+ * }
74
+ * })
75
+ * ```
76
+ */
77
+ export declare function defineAdapter<T extends AdapterContract>(adapter: T): T;
78
+ /**
79
+ * Contract for implementing custom evaluators
80
+ *
81
+ * @example
82
+ * ```typescript
83
+ * import { defineEvaluator, type EvaluatorContract } from '@artemiskit/sdk'
84
+ *
85
+ * const customEvaluator = defineEvaluator({
86
+ * type: 'custom-semantic',
87
+ * async evaluate(response, expected, context) {
88
+ * // Custom evaluation logic
89
+ * const score = calculateSemanticScore(response, expected.value)
90
+ * return { passed: score > 0.8, score, reason: `Semantic score: ${score}` }
91
+ * }
92
+ * })
93
+ * ```
94
+ */
95
+ export interface EvaluatorContract extends Evaluator {
96
+ /**
97
+ * Unique type identifier for this evaluator
98
+ */
99
+ readonly type: string;
100
+ /**
101
+ * Evaluate a response against expected criteria
102
+ *
103
+ * @param response - The model's response text
104
+ * @param expected - The expected result configuration
105
+ * @param context - Optional context including model client and test case
106
+ * @returns Evaluation result with pass/fail, score, and reason
107
+ */
108
+ evaluate(response: string, expected: Expected, context?: EvaluatorContext): Promise<EvaluatorResult>;
109
+ }
110
+ /**
111
+ * Define a custom evaluator with type checking
112
+ *
113
+ * @example
114
+ * ```typescript
115
+ * const wordCountEvaluator = defineEvaluator({
116
+ * type: 'word-count',
117
+ * async evaluate(response, expected, _context) {
118
+ * const wordCount = response.split(/\s+/).length
119
+ * const targetCount = (expected as any).wordCount ?? 100
120
+ * const tolerance = (expected as any).tolerance ?? 10
121
+ *
122
+ * const diff = Math.abs(wordCount - targetCount)
123
+ * const passed = diff <= tolerance
124
+ * const score = passed ? 1 : Math.max(0, 1 - diff / targetCount)
125
+ *
126
+ * return {
127
+ * passed,
128
+ * score,
129
+ * reason: `Word count: ${wordCount}, target: ${targetCount} (±${tolerance})`,
130
+ * details: { wordCount, targetCount, tolerance, diff }
131
+ * }
132
+ * }
133
+ * })
134
+ * ```
135
+ */
136
+ export declare function defineEvaluator<T extends EvaluatorContract>(evaluator: T): T;
137
+ /**
138
+ * Contract for implementing custom storage adapters
139
+ *
140
+ * **IMPORTANT: Sort Order Requirement**
141
+ *
142
+ * The `list()` method MUST return results sorted by `startTime` in descending order
143
+ * (most recent first). This is required by `ArtemisKit.compare()` when using
144
+ * `baseline: 'latest'` - it relies on `list({ limit: 1 })[0]` being the most recent run.
145
+ *
146
+ * If your storage backend doesn't natively support this sort order, you must
147
+ * implement sorting in the adapter's `list()` method.
148
+ *
149
+ * @example
150
+ * ```typescript
151
+ * import { defineStorage, type StorageContract } from '@artemiskit/sdk'
152
+ *
153
+ * const redisStorage = defineStorage({
154
+ * async save(manifest) {
155
+ * await redis.set(`run:${manifest.run_id}`, JSON.stringify(manifest))
156
+ * return manifest.run_id
157
+ * },
158
+ * async load(runId) {
159
+ * const data = await redis.get(`run:${runId}`)
160
+ * return JSON.parse(data)
161
+ * },
162
+ * async list(options) {
163
+ * // IMPORTANT: Results must be sorted by startTime descending (most recent first)
164
+ * const runs = await this.getAllRuns()
165
+ * runs.sort((a, b) => b.startTime.getTime() - a.startTime.getTime())
166
+ * return runs.slice(0, options?.limit ?? runs.length)
167
+ * },
168
+ * async delete(runId) {
169
+ * await redis.del(`run:${runId}`)
170
+ * }
171
+ * })
172
+ * ```
173
+ */
174
+ export interface StorageContract extends StorageAdapter {
175
+ }
176
+ /**
177
+ * Define a custom storage adapter with type checking
178
+ *
179
+ * @example
180
+ * ```typescript
181
+ * const s3Storage = defineStorage({
182
+ * async save(manifest) {
183
+ * const key = `runs/${manifest.run_id}.json`
184
+ * await s3.putObject({ Bucket: 'my-bucket', Key: key, Body: JSON.stringify(manifest) })
185
+ * return manifest.run_id
186
+ * },
187
+ * async load(runId) {
188
+ * const key = `runs/${runId}.json`
189
+ * const { Body } = await s3.getObject({ Bucket: 'my-bucket', Key: key })
190
+ * return JSON.parse(Body)
191
+ * },
192
+ * async list(options) {
193
+ * // List objects from S3
194
+ * return []
195
+ * },
196
+ * async delete(runId) {
197
+ * const key = `runs/${runId}.json`
198
+ * await s3.deleteObject({ Bucket: 'my-bucket', Key: key })
199
+ * }
200
+ * })
201
+ * ```
202
+ */
203
+ export declare function defineStorage<T extends StorageContract>(storage: T): T;
204
+ /**
205
+ * Factory function type for creating adapters
206
+ */
207
+ export type AdapterFactory<TConfig = unknown> = (config: TConfig) => AdapterContract | Promise<AdapterContract>;
208
+ /**
209
+ * Factory function type for creating evaluators
210
+ */
211
+ export type EvaluatorFactory<TConfig = unknown> = (config: TConfig) => EvaluatorContract;
212
+ /**
213
+ * Factory function type for creating storage adapters
214
+ */
215
+ export type StorageFactory<TConfig = unknown> = (config: TConfig) => StorageContract | Promise<StorageContract>;
216
+ /**
217
+ * Plugin interface for extending ArtemisKit
218
+ */
219
+ export interface ArtemisKitPlugin {
220
+ /**
221
+ * Plugin name (unique identifier)
222
+ */
223
+ name: string;
224
+ /**
225
+ * Plugin version
226
+ */
227
+ version: string;
228
+ /**
229
+ * Optional: Custom adapters to register
230
+ */
231
+ adapters?: Record<string, AdapterFactory>;
232
+ /**
233
+ * Optional: Custom evaluators to register
234
+ */
235
+ evaluators?: Record<string, EvaluatorFactory>;
236
+ /**
237
+ * Optional: Custom storage adapters to register
238
+ */
239
+ storage?: Record<string, StorageFactory>;
240
+ /**
241
+ * Optional: Initialize the plugin
242
+ */
243
+ init?(): Promise<void>;
244
+ /**
245
+ * Optional: Cleanup the plugin
246
+ */
247
+ cleanup?(): Promise<void>;
248
+ }
249
+ /**
250
+ * Define a plugin with type checking
251
+ */
252
+ export declare function definePlugin(plugin: ArtemisKitPlugin): ArtemisKitPlugin;
253
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/contracts/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EACV,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,QAAQ,EACR,eAAe,E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@
1
+ // @bun
2
+ // src/contracts/index.ts
3
+ function defineAdapter(adapter) {
4
+ if (!adapter.provider) {
5
+ throw new Error("Adapter must have a provider property");
6
+ }
7
+ if (typeof adapter.generate !== "function") {
8
+ throw new Error("Adapter must have a generate method");
9
+ }
10
+ if (typeof adapter.capabilities !== "function") {
11
+ throw new Error("Adapter must have a capabilities method");
12
+ }
13
+ return adapter;
14
+ }
15
+ function defineEvaluator(evaluator) {
16
+ if (!evaluator.type) {
17
+ throw new Error("Evaluator must have a type property");
18
+ }
19
+ if (typeof evaluator.evaluate !== "function") {
20
+ throw new Error("Evaluator must have an evaluate method");
21
+ }
22
+ return evaluator;
23
+ }
24
+ function defineStorage(storage) {
25
+ if (typeof storage.save !== "function") {
26
+ throw new Error("Storage must have a save method");
27
+ }
28
+ if (typeof storage.load !== "function") {
29
+ throw new Error("Storage must have a load method");
30
+ }
31
+ if (typeof storage.list !== "function") {
32
+ throw new Error("Storage must have a list method");
33
+ }
34
+ if (typeof storage.delete !== "function") {
35
+ throw new Error("Storage must have a delete method");
36
+ }
37
+ return storage;
38
+ }
39
+ function definePlugin(plugin) {
40
+ if (!plugin.name) {
41
+ throw new Error("Plugin must have a name");
42
+ }
43
+ if (!plugin.version) {
44
+ throw new Error("Plugin must have a version");
45
+ }
46
+ return plugin;
47
+ }
48
+ export {
49
+ defineAdapter,
50
+ defineEvaluator,
51
+ definePlugin,
52
+ defineStorage
53
+ };
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Action Validator
3
+ *
4
+ * Validates tool/function calls before execution.
5
+ * Ensures agents only perform allowed actions with valid parameters.
6
+ */
7
+ import type { ActionDefinition, GuardrailResult, InterceptedToolCall, Violation, ViolationSeverity } from './types';
8
+ /**
9
+ * Action validation result
10
+ */
11
+ export interface ActionValidationResult {
12
+ valid: boolean;
13
+ violations: Violation[];
14
+ sanitizedArguments?: Record<string, unknown>;
15
+ requiresApproval?: boolean;
16
+ }
17
+ /**
18
+ * Action validator configuration
19
+ */
20
+ export interface ActionValidatorConfig {
21
+ /** Allowed actions with their definitions */
22
+ allowedActions?: ActionDefinition[];
23
+ /** Default behavior for undefined actions */
24
+ defaultAllow?: boolean;
25
+ /** Default risk level for undefined actions */
26
+ defaultRiskLevel?: ViolationSeverity;
27
+ /** Block high-risk actions automatically */
28
+ blockHighRisk?: boolean;
29
+ /** Custom validation function */
30
+ customValidator?: (toolCall: InterceptedToolCall) => Promise<ActionValidationResult>;
31
+ }
32
+ /**
33
+ * Action Validator
34
+ *
35
+ * Validates tool/function calls against defined policies.
36
+ */
37
+ export declare class ActionValidator {
38
+ private config;
39
+ private actionMap;
40
+ private callHistory;
41
+ private callCounts;
42
+ constructor(config?: ActionValidatorConfig);
43
+ /**
44
+ * Validate a tool/function call
45
+ */
46
+ validate(toolCall: InterceptedToolCall): Promise<ActionValidationResult>;
47
+ /**
48
+ * Create a guardrail function from this validator
49
+ */
50
+ asGuardrail(): (content: string, context?: Record<string, unknown>) => Promise<GuardrailResult>;
51
+ /**
52
+ * Register an allowed action
53
+ */
54
+ registerAction(action: ActionDefinition): void;
55
+ /**
56
+ * Remove an action from allowed list
57
+ */
58
+ unregisterAction(name: string): void;
59
+ /**
60
+ * Get all registered actions
61
+ */
62
+ getRegisteredActions(): ActionDefinition[];
63
+ /**
64
+ * Get call history
65
+ */
66
+ getCallHistory(): InterceptedToolCall[];
67
+ /**
68
+ * Clear call history
69
+ */
70
+ clearHistory(): void;
71
+ /**
72
+ * Check rate limit for an action
73
+ */
74
+ private checkRateLimit;
75
+ /**
76
+ * Validate parameters against definitions
77
+ */
78
+ private validateParameters;
79
+ /**
80
+ * Check if value matches expected type
81
+ */
82
+ private checkType;
83
+ /**
84
+ * Run validation rules on a parameter value
85
+ */
86
+ private runValidation;
87
+ }
88
+ /**
89
+ * Create a pre-configured action validator with common dangerous actions blocked
90
+ */
91
+ export declare function createDefaultActionValidator(): ActionValidator;
92
+ //# sourceMappingURL=action-validator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3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AAC,MAAM,EAAE,gBAAgB,GAAG,IAAI;IAI9C;;OAEG;IACH,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAIpC;;OAEG;IACH,oBAAoB,IAAI,gBAAgB,EAAE;IAI1C;;OAEG;IACH,cAAc,IAAI,mBAAmB,EAAE;IAIvC;;OAEG;IACH,YAAY,IAAI,IAAI;IAKpB;;OAEG;IACH,OAAO,CAAC,cAAc;IAsCtB;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAwD1B;;OAEG;IACH,OAAO,CAAC,SAAS;IAiBjB;;OAEG;IACH,OAAO,CAAC,aAAa;CAsItB;AAED;;GAEG;AACH,wBAAgB,4BAA4B,IAAI,eAAe,CAwF9D"}
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Circuit Breaker and Metrics
3
+ *
4
+ * Implements the circuit breaker pattern to protect against repeated failures
5
+ * and provides comprehensive metrics tracking for guardian operations.
6
+ */
7
+ import type { CircuitBreakerConfig, CircuitBreakerState, GuardianMetrics, Violation } from './types';
8
+ /**
9
+ * Circuit breaker event types
10
+ */
11
+ export type CircuitBreakerEvent = 'open' | 'close' | 'half-open' | 'violation' | 'success';
12
+ /**
13
+ * Circuit breaker event handler
14
+ */
15
+ export type CircuitBreakerEventHandler = (event: CircuitBreakerEvent, data?: Record<string, unknown>) => void;
16
+ /**
17
+ * Circuit Breaker implementation
18
+ *
19
+ * Protects against cascading failures by opening the circuit
20
+ * when too many violations occur within a time window.
21
+ */
22
+ export declare class CircuitBreaker {
23
+ private config;
24
+ private state;
25
+ private violations;
26
+ private lastOpenTime;
27
+ private halfOpenSuccesses;
28
+ private eventHandlers;
29
+ constructor(config: CircuitBreakerConfig);
30
+ /**
31
+ * Check if the circuit is open (requests should be blocked)
32
+ */
33
+ isOpen(): boolean;
34
+ /**
35
+ * Check if the circuit allows requests
36
+ * @deprecated Use isOpen() instead - this method duplicates functionality.
37
+ * Guardian uses isOpen() exclusively for circuit breaker checks.
38
+ */
39
+ allowRequest(): boolean;
40
+ /**
41
+ * Record a violation
42
+ */
43
+ recordViolation(violation: Violation): void;
44
+ /**
45
+ * Record a successful request (no violations)
46
+ */
47
+ recordSuccess(): void;
48
+ /**
49
+ * Trip the circuit breaker (open it)
50
+ */
51
+ trip(): void;
52
+ /**
53
+ * Reset the circuit breaker (close it)
54
+ */
55
+ reset(): void;
56
+ /**
57
+ * Force the circuit to a specific state.
58
+ * When forcing to 'open', also updates lastOpenTime so the cooldown
59
+ * period starts from now (matching trip() behavior).
60
+ */
61
+ forceState(state: CircuitBreakerState): void;
62
+ /**
63
+ * Get the current state
64
+ */
65
+ getState(): CircuitBreakerState;
66
+ /**
67
+ * Get violation count in current window
68
+ */
69
+ getViolationCount(): number;
70
+ /**
71
+ * Get time until the circuit breaker resets (if open)
72
+ */
73
+ getTimeUntilReset(): number;
74
+ /**
75
+ * Register an event handler
76
+ */
77
+ onEvent(handler: CircuitBreakerEventHandler): void;
78
+ /**
79
+ * Remove an event handler
80
+ */
81
+ offEvent(handler: CircuitBreakerEventHandler): void;
82
+ /**
83
+ * Transition to a new state
84
+ */
85
+ private transition;
86
+ /**
87
+ * Emit an event to all handlers
88
+ */
89
+ private emit;
90
+ }
91
+ /**
92
+ * Metrics collector for guardian operations
93
+ */
94
+ export declare class MetricsCollector {
95
+ private currentWindow;
96
+ private windowDurationMs;
97
+ private history;
98
+ private maxHistoryWindows;
99
+ private currency;
100
+ constructor(options?: {
101
+ windowDurationMs?: number;
102
+ maxHistoryWindows?: number;
103
+ currency?: string;
104
+ });
105
+ /**
106
+ * Record a request
107
+ */
108
+ recordRequest(options: {
109
+ blocked: boolean;
110
+ warned: boolean;
111
+ latencyMs: number;
112
+ violations: Violation[];
113
+ cost?: number;
114
+ }): void;
115
+ /**
116
+ * Get current metrics
117
+ */
118
+ getMetrics(circuitBreakerState?: CircuitBreakerState): GuardianMetrics;
119
+ /**
120
+ * Get metrics for the current window only
121
+ */
122
+ getCurrentWindowMetrics(): Partial<GuardianMetrics>;
123
+ /**
124
+ * Reset all metrics
125
+ */
126
+ reset(): void;
127
+ /**
128
+ * Get cost per minute (actual rate based on elapsed time)
129
+ *
130
+ * To avoid extreme extrapolated values immediately after window rotation,
131
+ * we require a minimum duration of data before extrapolating. If insufficient
132
+ * data is available in the current window, we fall back to historical data.
133
+ */
134
+ private getCostPerMinute;
135
+ /**
136
+ * Get hourly cost
137
+ */
138
+ private getHourlyCost;
139
+ /**
140
+ * Get daily cost (estimated based on available data)
141
+ */
142
+ private getDailyCost;
143
+ /**
144
+ * Create a new metrics window
145
+ */
146
+ private createWindow;
147
+ /**
148
+ * Rotate to a new window if needed
149
+ */
150
+ private rotateWindowIfNeeded;
151
+ }
152
+ /**
153
+ * Rate limiter configuration
154
+ */
155
+ export interface RateLimiterConfig {
156
+ requestsPerMinute?: number;
157
+ requestsPerHour?: number;
158
+ requestsPerDay?: number;
159
+ burstLimit?: number;
160
+ }
161
+ /**
162
+ * Token bucket rate limiter
163
+ */
164
+ export declare class RateLimiter {
165
+ private config;
166
+ private minuteWindow;
167
+ private hourWindow;
168
+ private dayWindow;
169
+ private burstTokens;
170
+ private lastBurstRefill;
171
+ constructor(config: RateLimiterConfig);
172
+ /**
173
+ * Check if a request is allowed
174
+ */
175
+ allowRequest(): {
176
+ allowed: boolean;
177
+ reason?: string;
178
+ retryAfterMs?: number;
179
+ };
180
+ /**
181
+ * Get current rate limit status
182
+ */
183
+ getStatus(): {
184
+ minuteUsed: number;
185
+ minuteLimit?: number;
186
+ hourUsed: number;
187
+ hourLimit?: number;
188
+ dayUsed: number;
189
+ dayLimit?: number;
190
+ burstTokens: number;
191
+ burstLimit?: number;
192
+ };
193
+ /**
194
+ * Reset all rate limits
195
+ */
196
+ reset(): void;
197
+ /**
198
+ * Refill burst tokens
199
+ */
200
+ private refillBurstTokens;
201
+ /**
202
+ * Rotate time windows using sliding window approximation.
203
+ *
204
+ * To prevent the fixed-window burst vulnerability (allowing 2× the limit at
205
+ * window boundaries), we use a sliding window approximation: when a window
206
+ * rotates, we carry over a proportional count from the previous window based
207
+ * on how much of the new window overlaps with the old one.
208
+ */
209
+ private rotateWindows;
210
+ }
211
+ //# sourceMappingURL=circuit-breaker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"circuit-breaker.d.ts","sourceRoot":"","sources":["../../src/guardian/circuit-breaker.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EACV,oBAAoB,EACpB,mBAAmB,EAEnB,eAAe,EAEf,SAAS,EAEV,MAAM,SAAS,CAAC;AAMjB;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG,OAAO,GAAG,WAAW,GAAG,WAAW,GAAG,SAAS,CAAC;AAE3F;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG,CACvC,KAAK,EAAE,mBAAmB,EAC1B,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAC3B,IAAI,CAAC;AAEV;;;;;GAKG;AACH,qBAAa,cAAc;IACzB,OAAO,CAAC,MAAM,CAAiC;IAC/C,OAAO,CAAC,KAAK,CAAiC;IAC9C,OAAO,CAAC,UAAU,CAA4D;IAC9E,OAAO,CAAC,YAAY,CAAK;IACzB,OAAO,CAAC,iBAAiB,CAAK;IAC9B,OAAO,CAAC,aAAa,CAAoC;gBAE7C,MAAM,EAAE,oBAAoB;IAUxC;;OAEG;IACH,MAAM,IAAI,OAAO;IAgBjB;;;;OAIG;IACH,YAAY,IAAI,OAAO;IAIvB;;OAEG;IACH,eAAe,CAAC,SAAS,EAAE,SAAS,GAAG,IAAI;IA6B3C;;OAEG;IACH,aAAa,IAAI,IAAI;IAgBrB;;OAEG;IACH,IAAI,IAAI,IAAI;IAKZ;;OAEG;IACH,KAAK,IAAI,IAAI;IAMb;;;;OAIG;IACH,UAAU,CAAC,KAAK,EAAE,mBAAmB,GAAG,IAAI;IAO5C;;OAEG;IACH,QAAQ,IAAI,mBAAmB;IAI/B;;OAEG;IACH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