@kya-os/checkpoint-shared 1.0.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,62 @@
1
+ # @kya-os/checkpoint-shared
2
+
3
+ ## 1.0.0 — 2026-05-15
4
+
5
+ E-tracks Phase D — package rename. **BREAKING.**
6
+
7
+ ### BREAKING CHANGES
8
+
9
+ - **Package renamed** from `@kya-os/agentshield-shared` to
10
+ `@kya-os/checkpoint-shared` per architect Q1 + Rename-2 (#2483). 0-day
11
+ hard cutover; the legacy `@kya-os/agentshield-shared@0.3.2` is published
12
+ with npm's `deprecated` field pointing here. Migrate by swapping the
13
+ import path:
14
+ `from '@kya-os/agentshield-shared'` → `from '@kya-os/checkpoint-shared'`.
15
+ - **Workspace dep on `@kya-os/checkpoint-rules`** unchanged (that package
16
+ was already named under the `checkpoint-*` namespace).
17
+
18
+ ### Migration
19
+
20
+ ```diff
21
+ - "@kya-os/agentshield-shared": "^0.3.2"
22
+ + "@kya-os/checkpoint-shared": "^1.0.0"
23
+ ```
24
+
25
+ ```diff
26
+ - import type { DetectionResult } from '@kya-os/agentshield-shared';
27
+ + import type { DetectionResult } from '@kya-os/checkpoint-shared';
28
+ ```
29
+
30
+ No other API changes in this release. All exports — Vocab-1 schemas,
31
+ EngineInfoSchema, canonical-signer module (Sign-1), wire types — preserved
32
+ verbatim under the new package name.
33
+
34
+ ## 0.3.2 — 2026-05-13
35
+
36
+ Phase 0.1 — Engine self-identification. **Non-breaking** for existing
37
+ 0.3.1 consumers (the `engine` field on `DetectionResult` is optional).
38
+
39
+ ### Added
40
+
41
+ - `EngineInfoSchema` — Zod schema for the per-request engine
42
+ attribution shape: `{ name, version, rulesetHash, buildSha }`.
43
+ - Optional `engine?: EngineInfo` field on `DetectionResultSchema` and
44
+ the matching TS type. Detections emitted by 0.3.2+ producers carry
45
+ this field; the dashboard reads it to attribute traffic to the
46
+ engine cohort that produced the verdict.
47
+
48
+ ### Why now
49
+
50
+ Closes the customer-visible loop on the Phase 0.1 work (PRs #2460
51
+ foundation, #2465 DB ingest, #2470 worker emit, #2471 dashboard
52
+ session-detail, #2478 installation-health). Internally complete on
53
+ 2026-05-13; this bump makes it consumable on npm.
54
+
55
+ ### Migration
56
+
57
+ None. Existing consumers see `engine === undefined` until they
58
+ upgrade their detection producer. Producers SHOULD start stamping
59
+ `engine` on every result (see PR #2460 review for the per-runtime
60
+ attribution-string conventions).
61
+
62
+ Refs Release-0.1 (#2497).
package/README.md ADDED
@@ -0,0 +1,112 @@
1
+ # @kya-os/checkpoint-shared
2
+
3
+ Shared types, schemas, and constants for AgentShield - the single source of truth for all TypeScript type definitions.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @kya-os/checkpoint-shared
9
+ # or
10
+ pnpm add @kya-os/checkpoint-shared
11
+ # or
12
+ yarn add @kya-os/checkpoint-shared
13
+ ```
14
+
15
+ ## Overview
16
+
17
+ This package provides:
18
+
19
+ - **Type Definitions**: Core TypeScript types for detection, agents, and configuration
20
+ - **Zod Schemas**: Runtime validation schemas for all types
21
+ - **Constants**: Known agent patterns, headers, and IP ranges
22
+ - **API Types**: Request/response schemas for API communication
23
+ - **Event Types**: Behavioral and real-time event definitions
24
+
25
+ ## Usage
26
+
27
+ ### Import Types
28
+
29
+ ```typescript
30
+ import {
31
+ DetectionInput,
32
+ DetectionResult,
33
+ AgentShieldConfig,
34
+ AgentType,
35
+ ConfidenceLevel,
36
+ } from '@kya-os/checkpoint-shared';
37
+ ```
38
+
39
+ ### Use Zod Schemas for Validation
40
+
41
+ ```typescript
42
+ import { DetectionInputSchema } from '@kya-os/checkpoint-shared';
43
+
44
+ // Validate input
45
+ const input = DetectionInputSchema.parse({
46
+ userAgent: 'Mozilla/5.0...',
47
+ ipAddress: '192.168.1.1',
48
+ headers: {
49
+ 'User-Agent': 'Mozilla/5.0...',
50
+ },
51
+ });
52
+ ```
53
+
54
+ ### Access Constants
55
+
56
+ ```typescript
57
+ import {
58
+ KNOWN_AGENT_PATTERNS,
59
+ CLOUD_PROVIDER_RANGES,
60
+ AI_AGENT_HEADERS,
61
+ } from '@kya-os/checkpoint-shared';
62
+
63
+ // Use predefined patterns
64
+ const openAIPattern = KNOWN_AGENT_PATTERNS.find((p) => p.type === 'openai');
65
+ ```
66
+
67
+ ## Type Categories
68
+
69
+ ### Core Types
70
+
71
+ - `DetectionInput` - Input data for agent detection
72
+ - `DetectionResult` - Result from detection engine
73
+ - `AgentInfo` - Information about detected agents
74
+ - `ConfidenceLevel` - Confidence levels (low, medium, high, very_high)
75
+
76
+ ### Configuration Types
77
+
78
+ - `AgentShieldConfig` - Main configuration object
79
+ - `ExpressMiddlewareOptions` - Express.js middleware configuration
80
+ - `NextMiddlewareOptions` - Next.js middleware configuration
81
+
82
+ ### Event Types
83
+
84
+ - `BehavioralData` - Mouse, keyboard, scroll events
85
+ - `RealtimeEvent` - Real-time detection events
86
+ - `DetectionEvent` - Specific detection event data
87
+
88
+ ### API Types
89
+
90
+ - `DetectionRequest` - API request format
91
+ - `DetectionResponse` - API response format
92
+ - `ApiResponse<T>` - Generic API response wrapper
93
+
94
+ ## Development
95
+
96
+ ```bash
97
+ # Install dependencies
98
+ pnpm install
99
+
100
+ # Build the package
101
+ pnpm build
102
+
103
+ # Type check
104
+ pnpm type-check
105
+
106
+ # Watch mode
107
+ pnpm dev
108
+ ```
109
+
110
+ ## License
111
+
112
+ MIT OR Apache-2.0
@@ -0,0 +1,318 @@
1
+ interface DetectionResult {
2
+ category: AgentCategory;
3
+ confidence: ConfidenceLevel;
4
+ agent?: AgentInfo;
5
+ }
6
+ type AgentCategory = 'human' | 'bot' | 'agent';
7
+ type ConfidenceLevel = 'low' | 'medium' | 'high' | 'very_high';
8
+ interface AgentInfo {
9
+ name: string;
10
+ version?: string;
11
+ url?: string;
12
+ company?: string;
13
+ }
14
+ type BeaconEventType = 'pageview' | 'pageunload' | 'heartbeat' | 'custom' | 'error' | 'performance';
15
+ interface BeaconEvent {
16
+ type: BeaconEventType;
17
+ data: BeaconCollectorData;
18
+ metadata: BeaconMetadata;
19
+ }
20
+ interface BeaconMetadata {
21
+ sessionId: string;
22
+ timestamp: number;
23
+ eventName?: string;
24
+ [key: string]: unknown;
25
+ }
26
+ interface BeaconCollectorData {
27
+ userAgent?: string;
28
+ language?: string;
29
+ platform?: string;
30
+ screenResolution?: string;
31
+ viewport?: string;
32
+ cookiesEnabled?: boolean;
33
+ doNotTrack?: boolean;
34
+ timezone?: string;
35
+ referrer?: string;
36
+ url?: string;
37
+ title?: string;
38
+ vendor?: string;
39
+ pageLoadTime?: number;
40
+ domContentLoadedTime?: number;
41
+ firstPaintTime?: number;
42
+ firstContentfulPaintTime?: number;
43
+ connectionType?: string;
44
+ sessionId?: string;
45
+ timestamp?: number;
46
+ [key: string]: unknown;
47
+ }
48
+ interface BeaconBatch {
49
+ projectId: string;
50
+ events: BeaconEvent[];
51
+ sessionId: string;
52
+ batchId: string;
53
+ timestamp: number;
54
+ }
55
+ interface BatchEvent {
56
+ id: string;
57
+ event: BeaconEvent;
58
+ timestamp: number;
59
+ retryCount: number;
60
+ hash: string;
61
+ priority: 'low' | 'normal' | 'high' | 'critical';
62
+ }
63
+ interface BeaconConfig {
64
+ projectId: string;
65
+ environment?: 'development' | 'staging' | 'production' | string;
66
+ tags?: Record<string, string | number | boolean>;
67
+ enabled?: boolean;
68
+ debug?: boolean;
69
+ logLevel?: 'error' | 'warn' | 'info' | 'debug';
70
+ respectDoNotTrack?: boolean;
71
+ anonymizeIp?: boolean;
72
+ sessionTimeout?: number;
73
+ sessionCookieName?: string;
74
+ batchSize?: number;
75
+ flushInterval?: number;
76
+ maxQueueSize?: number;
77
+ retryAttempts?: number;
78
+ retryDelay?: number;
79
+ useWorker?: boolean;
80
+ workerUrl?: string;
81
+ workerConfig?: WorkerConfig;
82
+ }
83
+ interface TransportConfig {
84
+ batchSize: number;
85
+ flushInterval: number;
86
+ maxRetries: number;
87
+ retryDelayBase: number;
88
+ offlineQueueSize: number;
89
+ useCompression: boolean;
90
+ compressionThreshold: number;
91
+ networkAdaptation: boolean;
92
+ dedupWindow: number;
93
+ }
94
+ interface WorkerConfig {
95
+ enabled?: boolean;
96
+ url?: string;
97
+ heartbeatInterval?: number;
98
+ maxUnhealthyCount?: number;
99
+ maxRetries?: number;
100
+ retryDelay?: number;
101
+ restartDelay?: number;
102
+ messageTimeout?: number;
103
+ compressionThreshold?: number;
104
+ allowFallback?: boolean;
105
+ crossOriginIsolated?: boolean;
106
+ maxRestartAttempts?: number;
107
+ terminationTimeout?: number;
108
+ taskTimeout?: number;
109
+ fallbackDelay?: number;
110
+ enableFallback?: boolean;
111
+ }
112
+ interface TransportOptions {
113
+ immediate?: boolean;
114
+ priority?: 'low' | 'normal' | 'high' | 'critical';
115
+ retry?: boolean;
116
+ timeout?: number;
117
+ }
118
+ interface TransportResponse {
119
+ success: boolean;
120
+ timestamp: number;
121
+ batchId?: string;
122
+ error?: string;
123
+ }
124
+ type TransportState = 'idle' | 'sending' | 'offline' | 'paused' | 'error';
125
+ interface TransportMetrics {
126
+ eventsSent: number;
127
+ eventsFailed: number;
128
+ eventsQueued: number;
129
+ batchesSent: number;
130
+ batchesFailed: number;
131
+ bytesTransferred: number;
132
+ compressionRatio?: number;
133
+ averageLatency?: number;
134
+ lastSuccessTimestamp?: number;
135
+ lastErrorTimestamp?: number;
136
+ }
137
+ type ConnectionType = 'bluetooth' | 'cellular' | 'ethernet' | 'none' | 'wifi' | 'wimax' | 'other' | 'unknown';
138
+ interface NetworkInfo {
139
+ type?: string;
140
+ effectiveType?: string;
141
+ downlink?: number;
142
+ rtt?: number;
143
+ saveData?: boolean;
144
+ }
145
+ type MessagePriority = 'low' | 'normal' | 'high' | 'critical';
146
+ type WorkerErrorType = 'initialization' | 'runtime' | 'communication' | 'timeout' | 'memory' | 'unknown';
147
+ type WorkerAction = 'process' | 'init' | 'terminate' | 'pause' | 'resume' | 'status' | 'health';
148
+ type WorkerMessageType = 'request' | 'response' | 'error' | 'heartbeat' | 'status';
149
+ interface WorkerMessage {
150
+ id: string;
151
+ type: 'request' | 'response' | 'error' | 'heartbeat' | 'status';
152
+ action?: string;
153
+ payload?: unknown;
154
+ timestamp: number;
155
+ compressed?: boolean;
156
+ priority?: MessagePriority;
157
+ correlationId?: string;
158
+ }
159
+ type WorkerState = 'idle' | 'initializing' | 'ready' | 'processing' | 'error' | 'terminating' | 'terminated';
160
+ type WorkerHealthStatus = 'healthy' | 'degraded' | 'unhealthy' | 'unknown';
161
+ interface WorkerMetrics {
162
+ tasksProcessed: number;
163
+ tasksFailed: number;
164
+ averageProcessingTime: number;
165
+ memoryUsage?: number;
166
+ cpuUsage?: number;
167
+ healthStatus: WorkerHealthStatus;
168
+ lastHealthCheck: number;
169
+ restartCount: number;
170
+ errorRate: number;
171
+ }
172
+ interface WorkerError {
173
+ type: string;
174
+ message: string;
175
+ stack?: string;
176
+ timestamp: number;
177
+ recoverable: boolean;
178
+ }
179
+ interface WorkerCapabilities {
180
+ workerAPI: boolean;
181
+ sharedArrayBuffer: boolean;
182
+ transferableObjects: boolean;
183
+ offscreenCanvas: boolean;
184
+ webAssembly: boolean;
185
+ atomics: boolean;
186
+ bigInt: boolean;
187
+ csp: {
188
+ workerSrc: boolean;
189
+ scriptSrc: boolean;
190
+ blobUrls: boolean;
191
+ inlineWorkers: boolean;
192
+ };
193
+ performance: {
194
+ memory: boolean;
195
+ measureUserAgentSpecificMemory: boolean;
196
+ };
197
+ }
198
+ interface WorkerTask {
199
+ id: string;
200
+ type: string;
201
+ data: unknown;
202
+ priority: 'low' | 'normal' | 'high' | 'critical';
203
+ createdAt: number;
204
+ startedAt?: number;
205
+ completedAt?: number;
206
+ error?: WorkerError;
207
+ maxRetries?: number;
208
+ retries?: number;
209
+ timeout?: number;
210
+ }
211
+ interface FallbackOptions {
212
+ useRequestIdleCallback: boolean;
213
+ idleTimeout: number;
214
+ chunkSize: number;
215
+ throttleMs: number;
216
+ maxExecutionTime: number;
217
+ }
218
+ interface ResourceUsage {
219
+ memoryUsage: number;
220
+ cpuUsage: number;
221
+ taskCount: number;
222
+ activeWorkers: number;
223
+ pendingTasks: number;
224
+ completedTasks: number;
225
+ failedTasks: number;
226
+ averageTaskDuration: number;
227
+ memory?: number;
228
+ cpu?: number;
229
+ tasks?: number;
230
+ }
231
+ interface WorkerPoolConfig {
232
+ maxWorkers: number;
233
+ minWorkers: number;
234
+ workerIdleTimeout: number;
235
+ taskQueueSize: number;
236
+ resourceLimits: Record<string, unknown>;
237
+ autoScale?: boolean;
238
+ scaleUpThreshold?: number;
239
+ scaleDownThreshold?: number;
240
+ }
241
+ type BeaconWorkerMessageType = 'init' | 'collect' | 'flush' | 'config' | 'status' | 'error';
242
+ type ProtocolVersion = '1.0' | '1.1' | '2.0';
243
+ interface BeaconWorkerMessage {
244
+ type: BeaconWorkerMessageType;
245
+ data?: unknown;
246
+ payload?: unknown;
247
+ messageId: string;
248
+ timestamp: number;
249
+ id?: string;
250
+ }
251
+ interface CircuitBreakerConfig {
252
+ threshold: number;
253
+ timeout: number;
254
+ resetTimeout: number;
255
+ }
256
+ type CircuitBreakerState = 'closed' | 'open' | 'half-open';
257
+ interface RetryStrategy {
258
+ maxAttempts: number;
259
+ baseDelay: number;
260
+ maxDelay: number;
261
+ factor: number;
262
+ jitter: boolean;
263
+ }
264
+ interface OfflineQueueEntry {
265
+ id: string;
266
+ events: BeaconEvent[];
267
+ timestamp: number;
268
+ expiresAt: number;
269
+ retryCount: number;
270
+ size: number;
271
+ }
272
+ declare function validateBeaconEvent(event: unknown): event is BeaconEvent;
273
+ declare function validateBeaconConfig(config: unknown): config is BeaconConfig;
274
+ declare function validateBeaconBatch(batch: unknown): batch is BeaconBatch;
275
+ declare function parseBeaconConfig(input: unknown): BeaconConfig;
276
+ declare const Guards: {
277
+ isBeaconEvent: typeof validateBeaconEvent;
278
+ isBeaconConfig: typeof validateBeaconConfig;
279
+ isBeaconBatch: typeof validateBeaconBatch;
280
+ isWorkerMessage(msg: unknown): msg is WorkerMessage;
281
+ isWorkerError(err: unknown): err is WorkerError;
282
+ isWorkerCapabilities(cap: unknown): cap is WorkerCapabilities;
283
+ };
284
+ declare function parseWorkerConfig(input: unknown): WorkerConfig;
285
+ declare function parseWorkerMessage(input: unknown): WorkerMessage;
286
+ declare function parseWorkerError(input: unknown): WorkerError;
287
+ declare function parseWorkerCapabilities(input: unknown): WorkerCapabilities;
288
+ declare function parseWorkerTask(input: unknown): WorkerTask;
289
+ declare function parseFallbackOptions(input: unknown): FallbackOptions;
290
+ declare function parseRetryStrategy(input: unknown): RetryStrategy;
291
+ declare function parseCircuitBreakerConfig(input: unknown): CircuitBreakerConfig;
292
+ declare function parseOfflineQueueEntry(input: unknown): OfflineQueueEntry;
293
+ declare function parseResourceUsage(input: unknown): ResourceUsage;
294
+ declare function parseWorkerPoolConfig(input: unknown): WorkerPoolConfig;
295
+ declare function parseBeaconWorkerMessage(input: unknown): BeaconWorkerMessage;
296
+ declare const DEFAULT_CONFIG: {
297
+ readonly batchSize: 10;
298
+ readonly flushInterval: 5000;
299
+ readonly sessionTimeout: 1800000;
300
+ readonly sessionCookieName: "_as_beacon_session";
301
+ readonly retryAttempts: 3;
302
+ readonly retryDelay: 2000;
303
+ };
304
+ declare const ERROR_TYPES: {
305
+ readonly NETWORK: "network";
306
+ readonly VALIDATION: "validation";
307
+ readonly TIMEOUT: "timeout";
308
+ readonly UNKNOWN: "unknown";
309
+ };
310
+ declare const RULE_CACHE: {
311
+ readonly DEFAULT_DURATION: 3600000;
312
+ readonly MAX_DURATION: 86400000;
313
+ readonly MIN_DURATION: 60000;
314
+ readonly STORAGE_KEY: "agentshield_rules";
315
+ readonly TIMESTAMP_KEY: "agentshield_rules_timestamp";
316
+ };
317
+
318
+ export { type AgentCategory, type AgentInfo, type BatchEvent, type BeaconBatch, type BeaconCollectorData, type BeaconConfig, type BeaconEvent, type BeaconEventType, type BeaconMetadata, type BeaconWorkerMessage, type BeaconWorkerMessageType, type CircuitBreakerConfig, type CircuitBreakerState, type ConfidenceLevel, type ConnectionType, DEFAULT_CONFIG, type DetectionResult, ERROR_TYPES, type FallbackOptions, Guards, type MessagePriority, type NetworkInfo, type OfflineQueueEntry, type ProtocolVersion, RULE_CACHE, type ResourceUsage, type RetryStrategy, type TransportConfig, type TransportMetrics, type TransportOptions, type TransportResponse, type TransportState, type WorkerAction, type WorkerCapabilities, type WorkerConfig, type WorkerError, type WorkerErrorType, type WorkerHealthStatus, type WorkerMessage, type WorkerMessageType, type WorkerMetrics, type WorkerPoolConfig, type WorkerState, type WorkerTask, parseBeaconConfig, parseBeaconWorkerMessage, parseCircuitBreakerConfig, parseFallbackOptions, parseOfflineQueueEntry, parseResourceUsage, parseRetryStrategy, parseWorkerCapabilities, parseWorkerConfig, parseWorkerError, parseWorkerMessage, parseWorkerPoolConfig, parseWorkerTask, validateBeaconBatch, validateBeaconConfig, validateBeaconEvent };