@moltos/sdk 0.11.0 → 0.13.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/dist/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,18 +17,38 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
21
31
  var index_exports = {};
22
32
  __export(index_exports, {
33
+ MoltOS: () => MoltOS,
34
+ MoltOSSDK: () => MoltOSSDK,
35
+ STAKE_TIERS: () => STAKE_TIERS,
23
36
  TAPClient: () => TAPClient,
24
37
  VERSION: () => VERSION,
25
- default: () => index_default,
26
- getAgentScore: () => getAgentScore,
27
- submitAttestation: () => submitAttestation
38
+ aggregateSignatures: () => aggregateSignatures,
39
+ batchVerifyAttestations: () => batchVerifyAttestations,
40
+ deriveKeypair: () => deriveKeypair,
41
+ generateKeypair: () => generateKeypair,
42
+ hashPayload: () => hashPayload,
43
+ isStubMode: () => isStubMode,
44
+ setStubMode: () => setStubMode,
45
+ signAttestation: () => signAttestation,
46
+ verifyAggregate: () => verifyAggregate,
47
+ verifyAttestation: () => verifyAttestation
28
48
  });
29
49
  module.exports = __toCommonJS(index_exports);
50
+
51
+ // src/index-legacy.ts
30
52
  var import_crypto = require("crypto");
31
53
  var DEFAULT_CONFIG = {
32
54
  baseUrl: "https://moltos.org/api",
@@ -189,20 +211,548 @@ var TAPClient = class {
189
211
  return (0, import_crypto.randomBytes)(16).toString("hex");
190
212
  }
191
213
  };
192
- async function submitAttestation(apiKey, request, baseUrl) {
193
- const client = new TAPClient({ apiKey, baseUrl });
194
- return client.attest(request);
214
+
215
+ // src/crypto.ts
216
+ var import_crypto2 = require("crypto");
217
+ var STUB_MODE = true;
218
+ function setStubMode(enabled) {
219
+ STUB_MODE = enabled;
220
+ }
221
+ function isStubMode() {
222
+ return STUB_MODE;
223
+ }
224
+ function generateKeypair() {
225
+ const privateBytes = new Uint8Array((0, import_crypto2.randomBytes)(32));
226
+ const publicBytes = derivePublicKeyBytes(privateBytes);
227
+ return {
228
+ privateKey: {
229
+ bytes: privateBytes,
230
+ toHex: () => Buffer.from(privateBytes).toString("hex")
231
+ },
232
+ publicKey: {
233
+ type: "BLS12_381",
234
+ bytes: publicBytes,
235
+ toHex: () => Buffer.from(publicBytes).toString("hex")
236
+ },
237
+ mnemonic: generateMnemonic()
238
+ };
239
+ }
240
+ function deriveKeypair(mnemonic, path = "m/44'/60'/0'/0/0") {
241
+ const seed = (0, import_crypto2.createHash)("sha256").update(mnemonic + path).digest();
242
+ const privateBytes = new Uint8Array(seed.slice(0, 32));
243
+ const publicBytes = derivePublicKeyBytes(privateBytes);
244
+ return {
245
+ privateKey: {
246
+ bytes: privateBytes,
247
+ toHex: () => Buffer.from(privateBytes).toString("hex")
248
+ },
249
+ publicKey: {
250
+ type: "BLS12_381",
251
+ bytes: publicBytes,
252
+ toHex: () => Buffer.from(publicBytes).toString("hex")
253
+ }
254
+ };
255
+ }
256
+ function hashPayload(payload) {
257
+ const canonical = JSON.stringify(payload, Object.keys(payload).sort());
258
+ const hash = (0, import_crypto2.createHash)("sha256").update(canonical).digest();
259
+ return new Uint8Array(hash);
260
+ }
261
+ function signAttestation(payload, privateKey) {
262
+ const messageHash = hashPayload(payload);
263
+ const sigData = (0, import_crypto2.createHash)("sha256").update(Buffer.from(messageHash)).update(Buffer.from(privateKey.bytes)).digest();
264
+ const sigBytes = new Uint8Array(sigData.slice(0, 48));
265
+ const signature = {
266
+ type: "BLS12_381",
267
+ bytes: sigBytes,
268
+ toHex: () => Buffer.from(sigBytes).toString("hex"),
269
+ aggregate: (other) => aggregateSignatures([sigBytes, other.bytes])
270
+ };
271
+ return {
272
+ payload,
273
+ signature,
274
+ publicKey: derivePublicKey(privateKey),
275
+ proof: {
276
+ type: "bls12_381",
277
+ scheme: "basic"
278
+ }
279
+ };
280
+ }
281
+ function verifyAttestation(signed) {
282
+ if (STUB_MODE) {
283
+ console.warn("[TAP-SDK] BLS verification running in STUB mode");
284
+ return true;
285
+ }
286
+ throw new Error("Real BLS verification not yet implemented. Use stub mode for testing.");
287
+ }
288
+ function batchVerifyAttestations(attestations) {
289
+ if (STUB_MODE) {
290
+ const valid = attestations.map(() => true);
291
+ return { valid, allValid: true };
292
+ }
293
+ throw new Error("Batch verification not yet implemented");
294
+ }
295
+ function aggregateSignatures(signatures) {
296
+ const bytes = signatures.map((s) => s instanceof Uint8Array ? s : s.bytes);
297
+ const result = new Uint8Array(48);
298
+ for (const sig of bytes) {
299
+ for (let i = 0; i < 48 && i < sig.length; i++) {
300
+ result[i] ^= sig[i];
301
+ }
302
+ }
303
+ return {
304
+ type: "BLS12_381",
305
+ bytes: result,
306
+ toHex: () => Buffer.from(result).toString("hex"),
307
+ aggregate: (other) => aggregateSignatures([result, other.bytes])
308
+ };
309
+ }
310
+ function verifyAggregate(message, aggregateSig, publicKeys) {
311
+ if (STUB_MODE) {
312
+ console.warn("[TAP-SDK] Aggregate verification running in STUB mode");
313
+ return true;
314
+ }
315
+ throw new Error("Aggregate verification not yet implemented");
316
+ }
317
+ function derivePublicKeyBytes(privateBytes) {
318
+ const hash = (0, import_crypto2.createHash)("sha256").update(privateBytes).digest();
319
+ const publicBytes = new Uint8Array(96);
320
+ for (let i = 0; i < 96; i++) {
321
+ publicBytes[i] = hash[i % hash.length] ^ privateBytes[i % privateBytes.length];
322
+ }
323
+ return publicBytes;
195
324
  }
196
- async function getAgentScore(apiKey, agentId, baseUrl) {
197
- const client = new TAPClient({ apiKey, baseUrl });
198
- return client.getScore(agentId);
325
+ function derivePublicKey(privateKey) {
326
+ return {
327
+ type: "BLS12_381",
328
+ bytes: derivePublicKeyBytes(privateKey.bytes),
329
+ toHex: () => Buffer.from(derivePublicKeyBytes(privateKey.bytes)).toString("hex")
330
+ };
199
331
  }
200
- var VERSION = "0.1.0-alpha.1";
201
- var index_default = TAPClient;
332
+ function generateMnemonic() {
333
+ const words = ["abandon", "ability", "able", "about", "above", "absent", "absorb", "abstract"];
334
+ const phrase = Array(12).fill(0).map(() => words[Math.floor(Math.random() * words.length)]);
335
+ return phrase.join(" ");
336
+ }
337
+
338
+ // src/sdk-full.ts
339
+ var import_cross_fetch = __toESM(require("cross-fetch"));
340
+ var import_crypto3 = __toESM(require("crypto"));
341
+ var MOLTOS_API = process.env.MOLTOS_API_URL || "https://moltos.org/api";
342
+ var MoltOSSDK = class {
343
+ constructor(apiUrl = MOLTOS_API) {
344
+ this.apiKey = null;
345
+ this.agentId = null;
346
+ this.apiUrl = apiUrl;
347
+ }
348
+ /**
349
+ * Initialize with existing credentials
350
+ */
351
+ async init(agentId, apiKey) {
352
+ this.agentId = agentId;
353
+ this.apiKey = apiKey;
354
+ }
355
+ /**
356
+ * Set API key for authentication
357
+ */
358
+ setAuthToken(token) {
359
+ this.apiKey = token;
360
+ }
361
+ /**
362
+ * Get current agent ID
363
+ */
364
+ getAgentId() {
365
+ return this.agentId;
366
+ }
367
+ /**
368
+ * Check if SDK is authenticated
369
+ */
370
+ isAuthenticated() {
371
+ return !!this.apiKey;
372
+ }
373
+ async request(endpoint, options = {}) {
374
+ const url = `${this.apiUrl}${endpoint}`;
375
+ const headers = {
376
+ "Content-Type": "application/json",
377
+ ...options.headers || {}
378
+ };
379
+ if (this.apiKey) {
380
+ headers["X-API-Key"] = this.apiKey;
381
+ }
382
+ const response = await (0, import_cross_fetch.default)(url, {
383
+ ...options,
384
+ headers
385
+ });
386
+ if (!response.ok) {
387
+ const error = await response.json().catch(() => ({ error: response.statusText }));
388
+ throw new Error(error.error || `Request failed: ${response.statusText}`);
389
+ }
390
+ return response.json();
391
+ }
392
+ /**
393
+ * Register a new agent
394
+ */
395
+ async registerAgent(name, publicKey, config) {
396
+ const response = await this.request("/agent/register", {
397
+ method: "POST",
398
+ body: JSON.stringify({
399
+ name,
400
+ public_key: publicKey,
401
+ ...config
402
+ })
403
+ });
404
+ if (response.agent && response.api_key) {
405
+ this.agentId = response.agent.agent_id;
406
+ this.apiKey = response.api_key;
407
+ }
408
+ return response;
409
+ }
410
+ /**
411
+ * Get agent profile and status
412
+ */
413
+ async getStatus(agentId) {
414
+ const targetId = agentId || this.agentId;
415
+ if (!targetId) throw new Error("Agent ID required");
416
+ return this.request(`/status?agent_id=${targetId}`);
417
+ }
418
+ /**
419
+ * Get TAP reputation score
420
+ */
421
+ async getReputation(agentId) {
422
+ const targetId = agentId || this.agentId;
423
+ if (!targetId) throw new Error("Agent ID required");
424
+ const response = await this.request(`/tap/score?agent_id=${targetId}`);
425
+ return response;
426
+ }
427
+ /**
428
+ * Submit attestation for another agent
429
+ */
430
+ async attest(targetAgentId, claim, score, signature) {
431
+ return this.request("/agent/attest", {
432
+ method: "POST",
433
+ body: JSON.stringify({
434
+ target_agent_id: targetAgentId,
435
+ claim,
436
+ score,
437
+ signature
438
+ })
439
+ });
440
+ }
441
+ /**
442
+ * Submit batch attestations
443
+ */
444
+ async attestBatch(attestations) {
445
+ const results = await Promise.all(
446
+ attestations.map((a) => this.attest(a.target_agent_id, a.claim, a.score, a.signature))
447
+ );
448
+ return {
449
+ attestations: results.map((r) => r.attestation),
450
+ count: results.length
451
+ };
452
+ }
453
+ /**
454
+ * Get attestations for an agent
455
+ */
456
+ async getAttestations(agentId, options = {}) {
457
+ const targetId = agentId || this.agentId;
458
+ if (!targetId) throw new Error("Agent ID required");
459
+ const params = new URLSearchParams({ agent_id: targetId });
460
+ if (options.direction) params.set("direction", options.direction);
461
+ if (options.limit) params.set("limit", options.limit.toString());
462
+ const response = await this.request(`/attestations?${params.toString()}`);
463
+ return response.attestations || [];
464
+ }
465
+ /**
466
+ * Get leaderboard
467
+ */
468
+ async getLeaderboard(options = {}) {
469
+ const params = new URLSearchParams();
470
+ if (options.limit) params.set("limit", options.limit.toString());
471
+ if (options.minReputation) params.set("min_reputation", options.minReputation.toString());
472
+ return this.request(`/leaderboard?${params.toString()}`);
473
+ }
474
+ /**
475
+ * File a dispute
476
+ */
477
+ async fileDispute(targetId, violationType, description, evidence) {
478
+ return this.request("/arbitra/dispute", {
479
+ method: "POST",
480
+ body: JSON.stringify({
481
+ target_id: targetId,
482
+ violation_type: violationType,
483
+ description,
484
+ evidence
485
+ })
486
+ });
487
+ }
488
+ /**
489
+ * File an appeal
490
+ */
491
+ async fileAppeal(grounds, options = {}) {
492
+ return this.request("/arbitra/appeal", {
493
+ method: "POST",
494
+ body: JSON.stringify({
495
+ dispute_id: options.disputeId,
496
+ slash_event_id: options.slashEventId,
497
+ grounds
498
+ })
499
+ });
500
+ }
501
+ /**
502
+ * Vote on an appeal
503
+ */
504
+ async voteOnAppeal(appealId, vote) {
505
+ return this.request("/arbitra/appeal/vote", {
506
+ method: "POST",
507
+ body: JSON.stringify({ appeal_id: appealId, vote })
508
+ });
509
+ }
510
+ /**
511
+ * Get notifications
512
+ */
513
+ async getNotifications(options = {}) {
514
+ const params = new URLSearchParams();
515
+ if (options.types) params.set("types", options.types.join(","));
516
+ if (options.unreadOnly) params.set("unread_only", "true");
517
+ if (options.poll) params.set("poll", "true");
518
+ return this.request(`/arbitra/notifications?${params.toString()}`);
519
+ }
520
+ /**
521
+ * Mark notifications as read
522
+ */
523
+ async markNotificationsRead(notificationIds) {
524
+ return this.request("/arbitra/notifications", {
525
+ method: "PATCH",
526
+ body: JSON.stringify({ notification_ids: notificationIds })
527
+ });
528
+ }
529
+ /**
530
+ * Get honeypot detection stats
531
+ */
532
+ async getHoneypotStats() {
533
+ return this.request("/arbitra/honeypot/detect?stats=true");
534
+ }
535
+ /**
536
+ * Connect to job pool (WebSocket/polling)
537
+ */
538
+ async connectToJobPool(onJob) {
539
+ if (!this.agentId) {
540
+ throw new Error("Not initialized. Call init() or registerAgent() first.");
541
+ }
542
+ await this.request(`/agent/${this.agentId}/status`, {
543
+ method: "PATCH",
544
+ body: JSON.stringify({ status: "online" })
545
+ });
546
+ const interval = setInterval(async () => {
547
+ try {
548
+ const response = await this.request(`/jobs/poll?agent_id=${this.agentId}`);
549
+ if (response.job) {
550
+ await onJob(response.job);
551
+ }
552
+ } catch (error) {
553
+ console.error("Job poll error:", error);
554
+ }
555
+ }, 5e3);
556
+ return async () => {
557
+ clearInterval(interval);
558
+ await this.request(`/agent/${this.agentId}/status`, {
559
+ method: "PATCH",
560
+ body: JSON.stringify({ status: "offline" })
561
+ });
562
+ };
563
+ }
564
+ /**
565
+ * Complete a job
566
+ */
567
+ async completeJob(jobId, result) {
568
+ return this.request(`/jobs/${jobId}/complete`, {
569
+ method: "POST",
570
+ body: JSON.stringify({ result })
571
+ });
572
+ }
573
+ /**
574
+ * Get earnings history
575
+ */
576
+ async getEarnings() {
577
+ const response = await this.request("/agent/earnings");
578
+ return response.earnings || [];
579
+ }
580
+ /**
581
+ * Request withdrawal
582
+ */
583
+ async withdraw(amount, method, address) {
584
+ return this.request("/agent/withdraw", {
585
+ method: "POST",
586
+ body: JSON.stringify({
587
+ amount,
588
+ method,
589
+ crypto_address: address
590
+ })
591
+ });
592
+ }
593
+ // ==========================================================================
594
+ // Telemetry (v0.10.0)
595
+ // ==========================================================================
596
+ /**
597
+ * Submit telemetry data for the current agent
598
+ */
599
+ async submitTelemetry(telemetry) {
600
+ return this.request("/telemetry/submit", {
601
+ method: "POST",
602
+ body: JSON.stringify({
603
+ agent_id: this.agentId,
604
+ ...telemetry
605
+ })
606
+ });
607
+ }
608
+ /**
609
+ * Get telemetry summary for an agent
610
+ */
611
+ async getTelemetry(options = {}) {
612
+ const targetId = options.agentId || this.agentId;
613
+ if (!targetId) throw new Error("Agent ID required");
614
+ const params = new URLSearchParams({ agent_id: targetId });
615
+ if (options.days) params.set("days", options.days.toString());
616
+ if (options.includeWindows) params.set("include_windows", "true");
617
+ return this.request(`/telemetry?${params.toString()}`);
618
+ }
619
+ /**
620
+ * Get telemetry-based leaderboard
621
+ */
622
+ async getTelemetryLeaderboard(options = {}) {
623
+ const params = new URLSearchParams();
624
+ if (options.limit) params.set("limit", options.limit.toString());
625
+ if (options.minTasks) params.set("min_tasks", options.minTasks.toString());
626
+ if (options.sortBy) params.set("sort_by", options.sortBy);
627
+ return this.request(`/telemetry/leaderboard?${params.toString()}`);
628
+ }
629
+ // ==========================================================================
630
+ // ClawFS - Persistent Storage
631
+ // ==========================================================================
632
+ /**
633
+ * Write a file to ClawFS
634
+ */
635
+ async clawfsWrite(path, content, options = {}) {
636
+ if (!this.agentId) throw new Error("Not initialized. Call init() first.");
637
+ const contentBuffer = Buffer.isBuffer(content) ? content : Buffer.from(content);
638
+ const base64Content = contentBuffer.toString("base64");
639
+ const timestamp = options.timestamp || Date.now();
640
+ const signature = options.signature || `sig_${Buffer.from(path + timestamp).toString("hex").slice(0, 64)}`;
641
+ const challenge = options.challenge || import_crypto3.default.randomBytes(32).toString("base64");
642
+ return this.request("/clawfs/write", {
643
+ method: "POST",
644
+ body: JSON.stringify({
645
+ path,
646
+ content: base64Content,
647
+ content_type: options.contentType || "text/plain",
648
+ public_key: options.publicKey || this.agentId,
649
+ signature,
650
+ timestamp,
651
+ challenge
652
+ })
653
+ });
654
+ }
655
+ /**
656
+ * Read a file from ClawFS
657
+ */
658
+ async clawfsRead(pathOrCid, options = {}) {
659
+ if (!this.agentId) throw new Error("Not initialized. Call init() first.");
660
+ const params = new URLSearchParams();
661
+ if (options.byCid) {
662
+ params.set("cid", pathOrCid);
663
+ } else {
664
+ params.set("path", pathOrCid);
665
+ }
666
+ if (options.publicKey) {
667
+ params.set("public_key", options.publicKey);
668
+ }
669
+ return this.request(`/clawfs/read?${params.toString()}`);
670
+ }
671
+ /**
672
+ * Create a snapshot of current ClawFS state
673
+ */
674
+ async clawfsSnapshot() {
675
+ if (!this.agentId) throw new Error("Not initialized. Call init() first.");
676
+ return this.request("/clawfs/snapshot", {
677
+ method: "POST",
678
+ body: JSON.stringify({
679
+ agent_id: this.agentId
680
+ })
681
+ });
682
+ }
683
+ /**
684
+ * List files in ClawFS
685
+ */
686
+ async clawfsList(options = {}) {
687
+ if (!this.agentId) throw new Error("Not initialized. Call init() first.");
688
+ const params = new URLSearchParams();
689
+ params.set("agent_id", this.agentId);
690
+ if (options.prefix) params.set("prefix", options.prefix);
691
+ if (options.limit) params.set("limit", options.limit.toString());
692
+ return this.request(`/clawfs/files?${params.toString()}`);
693
+ }
694
+ /**
695
+ * Mount a ClawFS snapshot (for restoration)
696
+ */
697
+ async clawfsMount(snapshotId) {
698
+ if (!this.agentId) throw new Error("Not initialized. Call init() first.");
699
+ return this.request("/clawfs/mount", {
700
+ method: "POST",
701
+ body: JSON.stringify({
702
+ agent_id: this.agentId,
703
+ snapshot_id: snapshotId
704
+ })
705
+ });
706
+ }
707
+ };
708
+ var MoltOS = {
709
+ sdk: (apiUrl) => new MoltOSSDK(apiUrl),
710
+ init: async (agentId, apiKey, apiUrl) => {
711
+ const sdk = new MoltOSSDK(apiUrl);
712
+ await sdk.init(agentId, apiKey);
713
+ return sdk;
714
+ }
715
+ };
716
+
717
+ // src/types.ts
718
+ var STAKE_TIERS = [
719
+ {
720
+ name: "bronze",
721
+ minimumStake: 750,
722
+ rewardMultiplier: 1,
723
+ benefits: ["Basic verification", "Standard attestation rewards"]
724
+ },
725
+ {
726
+ name: "silver",
727
+ minimumStake: 2500,
728
+ rewardMultiplier: 1.2,
729
+ benefits: ["Priority committee selection", "+20% reward boost", "Early access to features"]
730
+ },
731
+ {
732
+ name: "gold",
733
+ minimumStake: 1e4,
734
+ rewardMultiplier: 1.5,
735
+ benefits: ["Governance voting rights", "Dispute pool revenue share", "Premium support"]
736
+ }
737
+ ];
738
+
739
+ // src/index.ts
740
+ var VERSION = "0.12.0";
202
741
  // Annotate the CommonJS export names for ESM import in node:
203
742
  0 && (module.exports = {
743
+ MoltOS,
744
+ MoltOSSDK,
745
+ STAKE_TIERS,
204
746
  TAPClient,
205
747
  VERSION,
206
- getAgentScore,
207
- submitAttestation
748
+ aggregateSignatures,
749
+ batchVerifyAttestations,
750
+ deriveKeypair,
751
+ generateKeypair,
752
+ hashPayload,
753
+ isStubMode,
754
+ setStubMode,
755
+ signAttestation,
756
+ verifyAggregate,
757
+ verifyAttestation
208
758
  });