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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dpth.io contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,198 @@
1
+ # dpth.io
2
+
3
+ [![CI](https://github.com/rightclickable420/dpth/actions/workflows/ci.yml/badge.svg)](https://github.com/rightclickable420/dpth/actions/workflows/ci.yml)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
5
+
6
+ **The distributed intelligence layer.**
7
+
8
+ dpth.io is an open-source intelligence layer that turns every AI agent into infrastructure. Agents contribute storage, compute, and GPU power to the network — and in return, they get access to distributed inference, entity resolution, and cross-source pattern detection they couldn't build alone. Think BitTorrent economics meets AI: the more agents that join, the smarter and cheaper the network gets for everyone.
9
+
10
+ No single point of failure. No vendor lock-in. Zero infrastructure cost at scale.
11
+
12
+ ## Architecture
13
+
14
+ ```
15
+ ┌─────────────────────────────────────────────────┐
16
+ │ Applications │
17
+ │ (Fathom, your app, any client) │
18
+ ├─────────────────────────────────────────────────┤
19
+ │ dpth.io │
20
+ │ ┌───────────┐ ┌──────────┐ ┌────────────────┐ │
21
+ │ │ Intelligence│ │ Inference │ │ Agent Network │ │
22
+ │ │ Layer │ │ Routing │ │ (Contribute) │ │
23
+ │ └───────────┘ └──────────┘ └────────────────┘ │
24
+ │ ┌───────────┐ ┌──────────┐ ┌────────────────┐ │
25
+ │ │ Entity │ │ Model │ │ Reputation │ │
26
+ │ │Resolution │ │ Registry │ │ & Rewards │ │
27
+ │ └───────────┘ └──────────┘ └────────────────┘ │
28
+ ├─────────────────────────────────────────────────┤
29
+ │ Agent Network (P2P) │
30
+ │ Storage │ Compute │ GPU │ Verification │
31
+ └─────────────────────────────────────────────────┘
32
+ ```
33
+
34
+ ## Core Modules
35
+
36
+ ### Intelligence Layer
37
+ - **Entity Resolution** — Unified identity across data sources with temporal history
38
+ - **Correlation Engine** — Cross-source pattern detection and causality discovery
39
+ - **Temporal Data** — Time-native storage where every value has history
40
+ - **Semantic Search** — Embedding-based similarity across all data
41
+
42
+ ### Agent Network
43
+ - **Registration** — Agents join with cryptographic identity
44
+ - **Contributions** — Storage, compute, and GPU resource sharing
45
+ - **Reputation** — 5-tier system (newcomer → legendary) with earned privileges
46
+ - **Rewards** — Intelligence access, priority, storage, and features based on contribution
47
+ - **Storage Proofs** — Challenge-response verification that agents store what they claim
48
+
49
+ ### Distributed Inference
50
+ - **Model Registry** — Agents register available AI models with capabilities
51
+ - **Smart Routing** — Reputation + performance + reliability scoring for request assignment
52
+ - **Priority Queue** — Low/normal/high/critical priority with deadline support
53
+ - **SSE Streaming** — Real-time token-by-token delivery via Server-Sent Events
54
+ - **Centralized Fallback** — Transparent fallback to OpenAI/Anthropic/Groq/Together when no agents available
55
+
56
+ ## Install
57
+
58
+ ```bash
59
+ npm install dpth
60
+ ```
61
+
62
+ The core library (entity resolution, correlation, temporal, embeddings, agent SDK, fallback) works standalone with zero dependencies. Next.js API routes for the full server are available in the [repo source](src/api/).
63
+
64
+ ## Quick Start
65
+
66
+ ### As a Client
67
+
68
+ ```typescript
69
+ // Request inference from the network
70
+ const response = await fetch('/api/dpth/inference', {
71
+ method: 'POST',
72
+ headers: { 'Content-Type': 'application/json' },
73
+ body: JSON.stringify({
74
+ modelId: 'llama-3.3-70b',
75
+ input: {
76
+ messages: [{ role: 'user', content: 'Hello!' }]
77
+ },
78
+ params: { maxTokens: 1000, temperature: 0.7 }
79
+ })
80
+ });
81
+
82
+ // If agents are online → distributed processing
83
+ // If no agents → automatic centralized fallback
84
+ // Same API either way
85
+ ```
86
+
87
+ ### Use the Core Library
88
+
89
+ ```typescript
90
+ import { resolveOrCreate, getEntitiesByType } from 'dpth/entity';
91
+ import { registerMetric, addMetricPoints } from 'dpth/correlation';
92
+ import { takeSnapshot, diffSnapshots } from 'dpth/temporal';
93
+
94
+ // Entity resolution across sources
95
+ const { entity, isNew } = resolveOrCreate('person', 'Jane Smith', 'github', 'jsmith');
96
+
97
+ // Track metrics with correlation detection
98
+ registerMetric({ id: 'mrr', entityId: entity.id, name: 'MRR', points: [], aggregation: 'sum' });
99
+ addMetricPoints('mrr', [
100
+ { timestamp: new Date('2024-01'), value: 10000, source: 'stripe', confidence: 1 },
101
+ { timestamp: new Date('2024-02'), value: 12500, source: 'stripe', confidence: 1 },
102
+ ]);
103
+
104
+ // Temporal snapshots with diffing
105
+ takeSnapshot('dashboard-1', { revenue: 50000, users: 200 });
106
+ // ...later...
107
+ takeSnapshot('dashboard-1', { revenue: 62000, users: 245 });
108
+ const diff = diffSnapshots(snapshots[0], snapshots[1]); // → changed: ['revenue', 'users']
109
+ ```
110
+
111
+ ### As an Agent
112
+
113
+ ```typescript
114
+ import { DpthAgent } from 'dpth/agent-sdk';
115
+
116
+ const agent = new DpthAgent({
117
+ name: 'my-agent',
118
+ apiUrl: 'https://your-dpth-instance/api/dpth',
119
+ capabilities: {
120
+ storageCapacityMb: 10000,
121
+ cpuCores: 8,
122
+ hasGpu: true,
123
+ gpuVramMb: 24576,
124
+ taskTypes: ['embed', 'inference', 'correlate']
125
+ }
126
+ });
127
+
128
+ // Register and start working
129
+ await agent.register();
130
+ await agent.startWorking();
131
+ ```
132
+
133
+ ### Streaming Inference
134
+
135
+ ```typescript
136
+ // Connect to SSE stream
137
+ const eventSource = new EventSource(`/api/dpth/inference/stream?id=${requestId}`);
138
+
139
+ eventSource.addEventListener('token', (e) => {
140
+ const { text } = JSON.parse(e.data);
141
+ process.stdout.write(text); // Real-time tokens
142
+ });
143
+
144
+ eventSource.addEventListener('done', (e) => {
145
+ const { stats } = JSON.parse(e.data);
146
+ console.log(`\n${stats.tokensPerSecond} tok/s`);
147
+ });
148
+ ```
149
+
150
+ ## API Reference
151
+
152
+ | Endpoint | Description |
153
+ |----------|-------------|
154
+ | `POST /api/dpth/agents` | Register an agent |
155
+ | `GET /api/dpth/agents` | List online agents |
156
+ | `POST /api/dpth/tasks` | Submit/claim/complete tasks |
157
+ | `POST /api/dpth/storage` | Store content-addressed data |
158
+ | `GET /api/dpth/storage?cid=xxx` | Retrieve by CID |
159
+ | `POST /api/dpth/contribute?type=storage\|compute\|gpu` | Record contributions |
160
+ | `GET /api/dpth/reputation?agentId=xxx` | Get reputation & tier |
161
+ | `GET /api/dpth/rewards?agentId=xxx` | Available rewards |
162
+ | `POST /api/dpth/models` | Register a model |
163
+ | `GET /api/dpth/models` | List available models |
164
+ | `POST /api/dpth/inference` | Create inference request |
165
+ | `GET /api/dpth/inference/stream?id=xxx` | SSE token stream |
166
+ | `POST /api/dpth/proofs?action=challenge` | Storage verification |
167
+ | `GET /api/dpth/status` | Network dashboard data |
168
+
169
+ ## Protocol
170
+
171
+ See [PROTOCOL.md](src/lib/dpth/PROTOCOL.md) for the full protocol specification.
172
+
173
+ ## Economics
174
+
175
+ dpth.io uses a contribution-based reward system:
176
+
177
+ 1. **Agents contribute** — storage, compute, GPU inference
178
+ 2. **Agents earn reputation** — 5 tiers with increasing privileges
179
+ 3. **Agents claim rewards** — intelligence queries, storage, priority, features
180
+ 4. **Network grows** — more agents = more capacity = better for everyone
181
+
182
+ The architecture is designed to be tokenizable in the future without rebuilding — contribution scores map naturally to emission schedules. But for now, it's credits, not crypto.
183
+
184
+ ## Roadmap
185
+
186
+ - [x] **Phase 1:** Core Infrastructure (entity, correlation, temporal, storage)
187
+ - [x] **Phase 2:** Agent Network (contribution, reputation, rewards, GPU, proofs)
188
+ - [x] **Phase 3:** Distributed Inference (model registry, routing, streaming, fallback)
189
+ - [ ] **Phase 4:** Network Models (federated fine-tuning, weight distribution)
190
+ - [ ] **Phase 5:** Economics (credit system, tokenization readiness)
191
+
192
+ ## License
193
+
194
+ MIT — see [LICENSE](LICENSE)
195
+
196
+ ---
197
+
198
+ *Built by humans and agents, working together.*
@@ -0,0 +1,157 @@
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
+ export interface AgentCapabilities {
18
+ storageCapacityMb: number;
19
+ cpuCores: number;
20
+ hasGpu: boolean;
21
+ gpuVramMb?: number;
22
+ taskTypes: ('embed' | 'correlate' | 'extract' | 'analyze' | 'inference')[];
23
+ }
24
+ export interface AgentConfig {
25
+ name: string;
26
+ apiUrl: string;
27
+ capabilities: AgentCapabilities;
28
+ /** Private key for signing (generated if not provided) */
29
+ privateKey?: string;
30
+ /** Polling interval in ms (default: 5000) */
31
+ pollIntervalMs?: number;
32
+ /** Task handlers by type */
33
+ handlers?: Partial<Record<string, TaskHandler>>;
34
+ }
35
+ export interface Task {
36
+ id: string;
37
+ type: string;
38
+ priority: string;
39
+ input: {
40
+ cid?: string;
41
+ data?: unknown;
42
+ params?: Record<string, unknown>;
43
+ };
44
+ deadline?: string;
45
+ }
46
+ export type TaskHandler = (task: Task) => Promise<TaskResult>;
47
+ export interface TaskResult {
48
+ success: boolean;
49
+ output?: {
50
+ cid?: string;
51
+ data?: unknown;
52
+ };
53
+ error?: string;
54
+ }
55
+ export declare class DpthAgent {
56
+ private config;
57
+ private agentId;
58
+ private publicKey;
59
+ private privateKey;
60
+ private running;
61
+ private pollTimeout;
62
+ constructor(config: AgentConfig);
63
+ private derivePublicKey;
64
+ /**
65
+ * Get a header-safe version of the public key (base64, no PEM wrapping)
66
+ */
67
+ private getHeaderSafeKey;
68
+ private fetch;
69
+ /**
70
+ * Register this agent with the network
71
+ */
72
+ register(): Promise<void>;
73
+ /**
74
+ * Deregister from the network
75
+ */
76
+ deregister(): Promise<void>;
77
+ /**
78
+ * Fetch available tasks
79
+ */
80
+ getTasks(limit?: number): Promise<Task[]>;
81
+ /**
82
+ * Claim a task for processing
83
+ */
84
+ claimTask(taskId: string): Promise<Task>;
85
+ /**
86
+ * Complete a task with results
87
+ */
88
+ completeTask(taskId: string, result: TaskResult): Promise<void>;
89
+ /**
90
+ * Store a chunk, returns CID
91
+ */
92
+ storeChunk(data: unknown): Promise<string>;
93
+ /**
94
+ * Retrieve a chunk by CID
95
+ */
96
+ getChunk(cid: string): Promise<unknown>;
97
+ /**
98
+ * Get pending storage proof challenges for this agent
99
+ */
100
+ getPendingChallenges(): Promise<Array<{
101
+ id: string;
102
+ cid: string;
103
+ nonce: string;
104
+ expiresAt: string;
105
+ }>>;
106
+ /**
107
+ * Submit a storage proof response
108
+ * @param challengeId The challenge ID
109
+ * @param proof SHA256(chunk_data + nonce)
110
+ */
111
+ submitProof(challengeId: string, proof: string): Promise<{
112
+ valid: boolean;
113
+ stats: {
114
+ successRate: number;
115
+ };
116
+ }>;
117
+ /**
118
+ * Generate a proof for a chunk + nonce
119
+ * (Agents should use this to compute proofs from their local storage)
120
+ */
121
+ static computeProof(chunkData: string, nonce: string): string;
122
+ /**
123
+ * Start the work loop — continuously poll for and process tasks
124
+ */
125
+ startWorking(): Promise<void>;
126
+ /**
127
+ * Stop the work loop
128
+ */
129
+ stopWorking(): void;
130
+ private pollLoop;
131
+ private processTask;
132
+ /**
133
+ * Get the agent's public key (for verification)
134
+ */
135
+ getPublicKey(): string;
136
+ /**
137
+ * Get the agent's ID (after registration)
138
+ */
139
+ getAgentId(): string | null;
140
+ /**
141
+ * Check if agent is registered
142
+ */
143
+ isRegistered(): boolean;
144
+ /**
145
+ * Check if work loop is running
146
+ */
147
+ isWorking(): boolean;
148
+ }
149
+ /**
150
+ * Default embedding handler using OpenAI-compatible API
151
+ */
152
+ export declare function createEmbedHandler(apiKey: string, model?: string): TaskHandler;
153
+ /**
154
+ * Default extraction handler (simple regex-based)
155
+ */
156
+ export declare function createExtractHandler(): TaskHandler;
157
+ //# sourceMappingURL=agent-sdk.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-sdk.d.ts","sourceRoot":"","sources":["../src/agent-sdk.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAMH,MAAM,WAAW,iBAAiB;IAChC,iBAAiB,EAAE,MAAM,CAAC;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,OAAO,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,CAAC,OAAO,GAAG,WAAW,GAAG,SAAS,GAAG,SAAS,GAAG,WAAW,CAAC,EAAE,CAAC;CAC5E;AAED,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,YAAY,EAAE,iBAAiB,CAAC;IAChC,0DAA0D;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