dpth 0.1.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.
@@ -0,0 +1,367 @@
1
+ /**
2
+ * dpth.io Agent SDK
3
+ *
4
+ * Simple client for agents to participate in the dpth.io network.
5
+ * Handles registration, heartbeat, task claiming, and result submission.
6
+ *
7
+ * Usage:
8
+ * const agent = new DpthAgent({
9
+ * name: 'my-agent',
10
+ * apiUrl: 'https://fathom.gib.lol/api/dpth',
11
+ * capabilities: { storageCapacityMb: 1000, cpuCores: 4, ... }
12
+ * });
13
+ *
14
+ * await agent.register();
15
+ * await agent.startWorking();
16
+ */
17
+ import { createHash, generateKeyPairSync } from 'crypto';
18
+ // ─── Agent Class ─────────────────────────────────────
19
+ export class DpthAgent {
20
+ config;
21
+ agentId = null;
22
+ publicKey;
23
+ privateKey;
24
+ running = false;
25
+ pollTimeout = null;
26
+ constructor(config) {
27
+ // Generate key pair if not provided
28
+ if (config.privateKey) {
29
+ this.privateKey = config.privateKey;
30
+ // Derive public key from private
31
+ this.publicKey = this.derivePublicKey(config.privateKey);
32
+ }
33
+ else {
34
+ const { publicKey, privateKey } = generateKeyPairSync('ed25519');
35
+ this.privateKey = privateKey.export({ type: 'pkcs8', format: 'pem' });
36
+ this.publicKey = publicKey.export({ type: 'spki', format: 'pem' });
37
+ }
38
+ this.config = {
39
+ ...config,
40
+ privateKey: this.privateKey,
41
+ pollIntervalMs: config.pollIntervalMs || 5000,
42
+ handlers: config.handlers || {},
43
+ };
44
+ }
45
+ derivePublicKey(privateKeyPem) {
46
+ // For ed25519, derive a compact public key identifier
47
+ const hash = createHash('sha256').update(privateKeyPem).digest('hex');
48
+ return `dpth:pub:${hash.slice(0, 32)}`;
49
+ }
50
+ /**
51
+ * Get a header-safe version of the public key (base64, no PEM wrapping)
52
+ */
53
+ getHeaderSafeKey() {
54
+ // Strip PEM headers and newlines for HTTP header compatibility
55
+ return this.publicKey
56
+ .replace(/-----BEGIN.*?-----/g, '')
57
+ .replace(/-----END.*?-----/g, '')
58
+ .replace(/\n/g, '')
59
+ .trim();
60
+ }
61
+ // ─── API Methods ─────────────────────────────────
62
+ async fetch(path, options) {
63
+ const url = `${this.config.apiUrl}${path}`;
64
+ const response = await fetch(url, {
65
+ ...options,
66
+ headers: {
67
+ 'Content-Type': 'application/json',
68
+ 'X-Agent-Id': this.agentId || '',
69
+ 'X-Public-Key': this.getHeaderSafeKey(),
70
+ ...options?.headers,
71
+ },
72
+ });
73
+ return response;
74
+ }
75
+ /**
76
+ * Register this agent with the network
77
+ */
78
+ async register() {
79
+ const response = await this.fetch('/agents', {
80
+ method: 'POST',
81
+ body: JSON.stringify({
82
+ name: this.config.name,
83
+ publicKey: this.publicKey,
84
+ capabilities: this.config.capabilities,
85
+ }),
86
+ });
87
+ if (!response.ok) {
88
+ const error = await response.json();
89
+ throw new Error(`Registration failed: ${error.error || response.statusText}`);
90
+ }
91
+ const result = await response.json();
92
+ this.agentId = result.agent.id;
93
+ console.log(`[dpth] Agent registered: ${this.agentId}`);
94
+ }
95
+ /**
96
+ * Deregister from the network
97
+ */
98
+ async deregister() {
99
+ if (!this.agentId)
100
+ return;
101
+ await this.fetch(`/agents?id=${this.agentId}`, {
102
+ method: 'DELETE',
103
+ });
104
+ this.agentId = null;
105
+ console.log('[dpth] Agent deregistered');
106
+ }
107
+ /**
108
+ * Fetch available tasks
109
+ */
110
+ async getTasks(limit = 10) {
111
+ const types = this.config.capabilities.taskTypes.join(',');
112
+ const response = await this.fetch(`/tasks?limit=${limit}&type=${types}`);
113
+ if (!response.ok) {
114
+ throw new Error('Failed to fetch tasks');
115
+ }
116
+ const result = await response.json();
117
+ return result.tasks;
118
+ }
119
+ /**
120
+ * Claim a task for processing
121
+ */
122
+ async claimTask(taskId) {
123
+ const response = await this.fetch('/tasks?action=claim', {
124
+ method: 'POST',
125
+ body: JSON.stringify({
126
+ taskId,
127
+ agentId: this.agentId,
128
+ }),
129
+ });
130
+ if (!response.ok) {
131
+ const error = await response.json();
132
+ throw new Error(`Failed to claim task: ${error.error}`);
133
+ }
134
+ const result = await response.json();
135
+ return result.task;
136
+ }
137
+ /**
138
+ * Complete a task with results
139
+ */
140
+ async completeTask(taskId, result) {
141
+ const response = await this.fetch('/tasks?action=complete', {
142
+ method: 'POST',
143
+ body: JSON.stringify({
144
+ taskId,
145
+ agentId: this.agentId,
146
+ success: result.success,
147
+ output: result.output,
148
+ }),
149
+ });
150
+ if (!response.ok) {
151
+ throw new Error('Failed to complete task');
152
+ }
153
+ }
154
+ /**
155
+ * Store a chunk, returns CID
156
+ */
157
+ async storeChunk(data) {
158
+ const response = await this.fetch('/storage', {
159
+ method: 'POST',
160
+ body: JSON.stringify(data),
161
+ });
162
+ if (!response.ok) {
163
+ throw new Error('Failed to store chunk');
164
+ }
165
+ const result = await response.json();
166
+ return result.cid;
167
+ }
168
+ /**
169
+ * Retrieve a chunk by CID
170
+ */
171
+ async getChunk(cid) {
172
+ const response = await this.fetch(`/storage?cid=${cid}`);
173
+ if (!response.ok) {
174
+ throw new Error('Chunk not found');
175
+ }
176
+ return response.json();
177
+ }
178
+ /**
179
+ * Get pending storage proof challenges for this agent
180
+ */
181
+ async getPendingChallenges() {
182
+ const response = await this.fetch('/proofs?pending');
183
+ if (!response.ok) {
184
+ throw new Error('Failed to get pending challenges');
185
+ }
186
+ const result = await response.json();
187
+ return result.pending.filter((c) => c.agentId === this.agentId);
188
+ }
189
+ /**
190
+ * Submit a storage proof response
191
+ * @param challengeId The challenge ID
192
+ * @param proof SHA256(chunk_data + nonce)
193
+ */
194
+ async submitProof(challengeId, proof) {
195
+ const response = await this.fetch('/proofs?action=respond', {
196
+ method: 'POST',
197
+ body: JSON.stringify({
198
+ challengeId,
199
+ agentId: this.agentId,
200
+ proof,
201
+ }),
202
+ });
203
+ if (!response.ok) {
204
+ const error = await response.json();
205
+ throw new Error(`Proof submission failed: ${error.error}`);
206
+ }
207
+ return response.json();
208
+ }
209
+ /**
210
+ * Generate a proof for a chunk + nonce
211
+ * (Agents should use this to compute proofs from their local storage)
212
+ */
213
+ static computeProof(chunkData, nonce) {
214
+ // In browser/Node environments, use Web Crypto or Node crypto
215
+ // This is a placeholder - agents implement their own
216
+ const encoder = new TextEncoder();
217
+ const data = encoder.encode(chunkData + nonce);
218
+ // Note: Real implementation needs async crypto
219
+ // This is just to show the interface
220
+ throw new Error('Implement with crypto.subtle.digest or createHash');
221
+ }
222
+ // ─── Worker Loop ─────────────────────────────────
223
+ /**
224
+ * Start the work loop — continuously poll for and process tasks
225
+ */
226
+ async startWorking() {
227
+ if (this.running)
228
+ return;
229
+ if (!this.agentId) {
230
+ await this.register();
231
+ }
232
+ this.running = true;
233
+ console.log('[dpth] Starting work loop');
234
+ this.pollLoop();
235
+ }
236
+ /**
237
+ * Stop the work loop
238
+ */
239
+ stopWorking() {
240
+ this.running = false;
241
+ if (this.pollTimeout) {
242
+ clearTimeout(this.pollTimeout);
243
+ this.pollTimeout = null;
244
+ }
245
+ console.log('[dpth] Stopped work loop');
246
+ }
247
+ async pollLoop() {
248
+ if (!this.running)
249
+ return;
250
+ try {
251
+ // Fetch available tasks
252
+ const tasks = await this.getTasks(1);
253
+ if (tasks.length > 0) {
254
+ const task = tasks[0];
255
+ await this.processTask(task);
256
+ }
257
+ }
258
+ catch (error) {
259
+ console.error('[dpth] Error in poll loop:', error);
260
+ }
261
+ // Schedule next poll
262
+ this.pollTimeout = setTimeout(() => this.pollLoop(), this.config.pollIntervalMs);
263
+ }
264
+ async processTask(task) {
265
+ console.log(`[dpth] Processing task ${task.id} (${task.type})`);
266
+ try {
267
+ // Claim the task
268
+ const claimed = await this.claimTask(task.id);
269
+ // Get handler for task type
270
+ const handler = this.config.handlers[task.type];
271
+ if (!handler) {
272
+ throw new Error(`No handler for task type: ${task.type}`);
273
+ }
274
+ // Execute handler
275
+ const result = await handler(claimed);
276
+ // Complete the task
277
+ await this.completeTask(task.id, result);
278
+ console.log(`[dpth] Completed task ${task.id}`);
279
+ }
280
+ catch (error) {
281
+ console.error(`[dpth] Task ${task.id} failed:`, error);
282
+ // Report failure
283
+ await this.completeTask(task.id, {
284
+ success: false,
285
+ error: error instanceof Error ? error.message : 'Unknown error',
286
+ });
287
+ }
288
+ }
289
+ // ─── Utilities ───────────────────────────────────
290
+ /**
291
+ * Get the agent's public key (for verification)
292
+ */
293
+ getPublicKey() {
294
+ return this.publicKey;
295
+ }
296
+ /**
297
+ * Get the agent's ID (after registration)
298
+ */
299
+ getAgentId() {
300
+ return this.agentId;
301
+ }
302
+ /**
303
+ * Check if agent is registered
304
+ */
305
+ isRegistered() {
306
+ return this.agentId !== null;
307
+ }
308
+ /**
309
+ * Check if work loop is running
310
+ */
311
+ isWorking() {
312
+ return this.running;
313
+ }
314
+ }
315
+ // ─── Built-in Task Handlers ──────────────────────────
316
+ /**
317
+ * Default embedding handler using OpenAI-compatible API
318
+ */
319
+ export function createEmbedHandler(apiKey, model = 'text-embedding-3-small') {
320
+ return async (task) => {
321
+ const text = task.input.data;
322
+ const response = await fetch('https://api.openai.com/v1/embeddings', {
323
+ method: 'POST',
324
+ headers: {
325
+ 'Authorization': `Bearer ${apiKey}`,
326
+ 'Content-Type': 'application/json',
327
+ },
328
+ body: JSON.stringify({
329
+ model,
330
+ input: text,
331
+ }),
332
+ });
333
+ if (!response.ok) {
334
+ throw new Error(`Embedding API failed: ${response.statusText}`);
335
+ }
336
+ const result = await response.json();
337
+ return {
338
+ success: true,
339
+ output: {
340
+ data: result.data[0].embedding,
341
+ },
342
+ };
343
+ };
344
+ }
345
+ /**
346
+ * Default extraction handler (simple regex-based)
347
+ */
348
+ export function createExtractHandler() {
349
+ return async (task) => {
350
+ const text = task.input.data;
351
+ // Simple email extraction
352
+ const emails = text.match(/[\w.-]+@[\w.-]+\.\w+/g) || [];
353
+ // Simple number extraction
354
+ const numbers = text.match(/\$?[\d,]+\.?\d*/g) || [];
355
+ return {
356
+ success: true,
357
+ output: {
358
+ data: {
359
+ emails,
360
+ numbers,
361
+ length: text.length,
362
+ },
363
+ },
364
+ };
365
+ };
366
+ }
367
+ //# sourceMappingURL=agent-sdk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-sdk.js","sourceRoot":"","sources":["../src/agent-sdk.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAgB,MAAM,QAAQ,CAAC;AA+CvE,wDAAwD;AAExD,MAAM,OAAO,SAAS;IACZ,MAAM,CAAwB;IAC9B,OAAO,GAAkB,IAAI,CAAC;IAC9B,SAAS,CAAS;IAClB,UAAU,CAAS;IACnB,OAAO,GAAG,KAAK,CAAC;IAChB,WAAW,GAAyC,IAAI,CAAC;IAEjE,YAAY,MAAmB;QAC7B,oCAAoC;QACpC,IAAI,MAAM,CAAC,UAAU,EAAE,CAAC;YACtB,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC;YACpC,iCAAiC;YACjC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC3D,CAAC;aAAM,CAAC;YACN,MAAM,EAAE,SAAS,EAAE,UAAU,EAAE,GAAG,mBAAmB,CAAC,SAAS,CAAC,CAAC;YACjE,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,CAAW,CAAC;YAChF,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,CAAW,CAAC;QAC/E,CAAC;QAED,IAAI,CAAC,MAAM,GAAG;YACZ,GAAG,MAAM;YACT,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,cAAc,EAAE,MAAM,CAAC,cAAc,IAAI,IAAI;YAC7C,QAAQ,EAAE,MAAM,CAAC,QAAQ,IAAI,EAAE;SAChC,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S,CAAC;gBACnB,KAAK;gBACL,KAAK,EAAE,IAAI;aACZ,CAAC;SACH,CAAC,CAAC;QAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACjB,MAAM,IAAI,KAAK,CAAC,yBAAyB,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAC;QAClE,CAAC;QAED,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACrC,OAAO;YACL,OAAO,EAAE,IAAI;YACb,MAAM,EAAE;gBACN,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS;aAC/B;SACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,oBAAoB;IAClC,OAAO,KAAK,EAAE,IAAI,EAAE,EAAE;QACpB,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAc,CAAC;QAEvC,0BAA0B;QAC1B,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,uBAAuB,CAAC,IAAI,EAAE,CAAC;QAEzD,2BAA2B;QAC3B,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,IAAI,EAAE,CAAC;QAErD,OAAO;YACL,OAAO,EAAE,IAAI;YACb,MAAM,EAAE;gBACN,IAAI,EAAE;oBACJ,MAAM;oBACN,OAAO;oBACP,MAAM,EAAE,IAAI,CAAC,MAAM;iBACpB;aACF;SACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,94 @@
1
+ /**
2
+ * dpth.io Correlation Engine
3
+ *
4
+ * The magic sauce. Automatically discovers relationships between metrics
5
+ * across different data sources without explicit configuration.
6
+ *
7
+ * Key capabilities:
8
+ * - Pearson correlation for contemporaneous relationships
9
+ * - Cross-correlation for lagged/causal relationships
10
+ * - Anomaly detection via statistical analysis
11
+ * - Significance testing to filter noise
12
+ */
13
+ import { Metric, MetricPoint, Pattern, CorrelationQuery } from './types.js';
14
+ /**
15
+ * Register a metric for correlation analysis
16
+ */
17
+ export declare function registerMetric(metric: Metric): void;
18
+ /**
19
+ * Add data points to a metric
20
+ */
21
+ export declare function addMetricPoints(metricId: string, points: MetricPoint[]): void;
22
+ /**
23
+ * Get a metric by ID
24
+ */
25
+ export declare function getMetric(id: string): Metric | undefined;
26
+ /**
27
+ * List all metrics
28
+ */
29
+ export declare function listMetrics(): Metric[];
30
+ export interface CorrelationResult {
31
+ metricA: string;
32
+ metricB: string;
33
+ correlation: number;
34
+ lagDays: number;
35
+ pValue: number;
36
+ sampleSize: number;
37
+ direction: 'positive' | 'negative';
38
+ }
39
+ /**
40
+ * Calculate correlation between two metrics
41
+ */
42
+ export declare function calculateCorrelation(metricIdA: string, metricIdB: string, lagDays?: number): CorrelationResult | null;
43
+ /**
44
+ * Find all correlations for a metric
45
+ */
46
+ export declare function findCorrelations(query: CorrelationQuery): CorrelationResult[];
47
+ /**
48
+ * Discover all significant correlations in the system
49
+ */
50
+ export declare function discoverAllCorrelations(minCorrelation?: number, maxLagDays?: number): CorrelationResult[];
51
+ export interface AnomalyResult {
52
+ metricId: string;
53
+ timestamp: Date;
54
+ value: number;
55
+ expected: number;
56
+ stdDeviations: number;
57
+ severity: 'low' | 'medium' | 'high';
58
+ }
59
+ /**
60
+ * Detect anomalies in a metric using z-score
61
+ */
62
+ export declare function detectAnomalies(metricId: string, threshold?: number): AnomalyResult[];
63
+ /**
64
+ * Detect all anomalies across all metrics
65
+ */
66
+ export declare function discoverAllAnomalies(threshold?: number): AnomalyResult[];
67
+ export interface TrendResult {
68
+ metricId: string;
69
+ direction: 'up' | 'down' | 'stable';
70
+ slope: number;
71
+ rSquared: number;
72
+ changePercent: number;
73
+ period: {
74
+ start: Date;
75
+ end: Date;
76
+ };
77
+ }
78
+ /**
79
+ * Detect trend in a metric using linear regression
80
+ */
81
+ export declare function detectTrend(metricId: string, periodDays?: number): TrendResult | null;
82
+ /**
83
+ * Convert correlation results to Pattern format
84
+ */
85
+ export declare function correlationToPattern(result: CorrelationResult): Pattern;
86
+ /**
87
+ * Convert anomaly result to Pattern format
88
+ */
89
+ export declare function anomalyToPattern(result: AnomalyResult): Pattern;
90
+ /**
91
+ * Clear all metrics (for testing)
92
+ */
93
+ export declare function clearMetrics(): void;
94
+ //# sourceMappingURL=correlation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"correlation.d.ts","sourceRoot":"","sources":["../src/correlation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EACL,MAAM,EACN,WAAW,EACX,OAAO,EAIP,gBAAgB,EACjB,MAAM,YAAY,CAAC;AAOpB;;GAEG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAEnD;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,GAAG,IAAI,CAO7E;AAED;;GAEG;AACH,wBAAgB,SAAS,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAExD;AAED;;GAEG;AACH,wBAAgB,WAAW,IAAI,MAAM,EAAE,CAEtC;AA0KD,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,UAAU,GAAG,UAAU,CAAC;CACpC;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAClC,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,OAAO,GAAE,MAAU,GAClB,iBAAiB,GAAG,IAAI,CAsB1B;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,gBAAgB,GAAG,iBAAiB,EAAE,CAkD7E;AAED;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