openclaw-overlay-plugin 0.7.34 → 0.7.35

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 (144) hide show
  1. package/README.md +1 -1
  2. package/dist/index.js +13 -2
  3. package/dist/src/scripts/config.d.ts +1 -1
  4. package/dist/src/scripts/config.js +1 -1
  5. package/index.ts +15 -2
  6. package/openclaw.plugin.json +2 -1
  7. package/package.json +1 -1
  8. package/src/scripts/config.ts +1 -1
  9. package/dist/cli-main.d.ts +0 -7
  10. package/dist/cli-main.js +0 -192
  11. package/dist/cli.d.ts +0 -8
  12. package/dist/cli.js +0 -14
  13. package/dist/core/config.d.ts +0 -11
  14. package/dist/core/config.js +0 -13
  15. package/dist/core/index.d.ts +0 -25
  16. package/dist/core/index.js +0 -26
  17. package/dist/core/payment.d.ts +0 -16
  18. package/dist/core/payment.js +0 -94
  19. package/dist/core/types.d.ts +0 -94
  20. package/dist/core/types.js +0 -4
  21. package/dist/core/verify.d.ts +0 -28
  22. package/dist/core/verify.js +0 -104
  23. package/dist/core/wallet.d.ts +0 -99
  24. package/dist/core/wallet.js +0 -219
  25. package/dist/scripts/baemail/commands.d.ts +0 -64
  26. package/dist/scripts/baemail/commands.js +0 -259
  27. package/dist/scripts/baemail/handler.d.ts +0 -36
  28. package/dist/scripts/baemail/handler.js +0 -284
  29. package/dist/scripts/baemail/index.d.ts +0 -5
  30. package/dist/scripts/baemail/index.js +0 -5
  31. package/dist/scripts/config.d.ts +0 -48
  32. package/dist/scripts/config.js +0 -68
  33. package/dist/scripts/index.d.ts +0 -7
  34. package/dist/scripts/index.js +0 -7
  35. package/dist/scripts/messaging/connect.d.ts +0 -8
  36. package/dist/scripts/messaging/connect.js +0 -114
  37. package/dist/scripts/messaging/handlers.d.ts +0 -21
  38. package/dist/scripts/messaging/handlers.js +0 -334
  39. package/dist/scripts/messaging/inbox.d.ts +0 -11
  40. package/dist/scripts/messaging/inbox.js +0 -51
  41. package/dist/scripts/messaging/index.d.ts +0 -8
  42. package/dist/scripts/messaging/index.js +0 -8
  43. package/dist/scripts/messaging/poll.d.ts +0 -7
  44. package/dist/scripts/messaging/poll.js +0 -52
  45. package/dist/scripts/messaging/send.d.ts +0 -7
  46. package/dist/scripts/messaging/send.js +0 -43
  47. package/dist/scripts/output.d.ts +0 -12
  48. package/dist/scripts/output.js +0 -19
  49. package/dist/scripts/overlay/discover.d.ts +0 -7
  50. package/dist/scripts/overlay/discover.js +0 -72
  51. package/dist/scripts/overlay/index.d.ts +0 -7
  52. package/dist/scripts/overlay/index.js +0 -7
  53. package/dist/scripts/overlay/registration.d.ts +0 -19
  54. package/dist/scripts/overlay/registration.js +0 -176
  55. package/dist/scripts/overlay/services.d.ts +0 -29
  56. package/dist/scripts/overlay/services.js +0 -167
  57. package/dist/scripts/overlay/transaction.d.ts +0 -42
  58. package/dist/scripts/overlay/transaction.js +0 -103
  59. package/dist/scripts/payment/build.d.ts +0 -24
  60. package/dist/scripts/payment/build.js +0 -54
  61. package/dist/scripts/payment/commands.d.ts +0 -15
  62. package/dist/scripts/payment/commands.js +0 -73
  63. package/dist/scripts/payment/index.d.ts +0 -6
  64. package/dist/scripts/payment/index.js +0 -6
  65. package/dist/scripts/payment/types.d.ts +0 -56
  66. package/dist/scripts/payment/types.js +0 -4
  67. package/dist/scripts/services/index.d.ts +0 -6
  68. package/dist/scripts/services/index.js +0 -6
  69. package/dist/scripts/services/queue.d.ts +0 -11
  70. package/dist/scripts/services/queue.js +0 -28
  71. package/dist/scripts/services/request.d.ts +0 -7
  72. package/dist/scripts/services/request.js +0 -82
  73. package/dist/scripts/services/respond.d.ts +0 -11
  74. package/dist/scripts/services/respond.js +0 -132
  75. package/dist/scripts/types.d.ts +0 -107
  76. package/dist/scripts/types.js +0 -4
  77. package/dist/scripts/utils/index.d.ts +0 -6
  78. package/dist/scripts/utils/index.js +0 -6
  79. package/dist/scripts/utils/merkle.d.ts +0 -12
  80. package/dist/scripts/utils/merkle.js +0 -47
  81. package/dist/scripts/utils/storage.d.ts +0 -66
  82. package/dist/scripts/utils/storage.js +0 -211
  83. package/dist/scripts/utils/woc.d.ts +0 -26
  84. package/dist/scripts/utils/woc.js +0 -91
  85. package/dist/scripts/wallet/balance.d.ts +0 -22
  86. package/dist/scripts/wallet/balance.js +0 -240
  87. package/dist/scripts/wallet/identity.d.ts +0 -70
  88. package/dist/scripts/wallet/identity.js +0 -151
  89. package/dist/scripts/wallet/index.d.ts +0 -6
  90. package/dist/scripts/wallet/index.js +0 -6
  91. package/dist/scripts/wallet/setup.d.ts +0 -15
  92. package/dist/scripts/wallet/setup.js +0 -105
  93. package/dist/scripts/x-verification/commands.d.ts +0 -27
  94. package/dist/scripts/x-verification/commands.js +0 -222
  95. package/dist/scripts/x-verification/index.d.ts +0 -4
  96. package/dist/scripts/x-verification/index.js +0 -4
  97. package/dist/services/built-in/api-proxy/index.d.ts +0 -6
  98. package/dist/services/built-in/api-proxy/index.js +0 -23
  99. package/dist/services/built-in/code-develop/index.d.ts +0 -6
  100. package/dist/services/built-in/code-develop/index.js +0 -23
  101. package/dist/services/built-in/code-review/index.d.ts +0 -10
  102. package/dist/services/built-in/code-review/index.js +0 -51
  103. package/dist/services/built-in/image-analysis/index.d.ts +0 -6
  104. package/dist/services/built-in/image-analysis/index.js +0 -33
  105. package/dist/services/built-in/memory-store/index.d.ts +0 -6
  106. package/dist/services/built-in/memory-store/index.js +0 -22
  107. package/dist/services/built-in/roulette/index.d.ts +0 -6
  108. package/dist/services/built-in/roulette/index.js +0 -27
  109. package/dist/services/built-in/summarize/index.d.ts +0 -6
  110. package/dist/services/built-in/summarize/index.js +0 -21
  111. package/dist/services/built-in/tell-joke/handler.d.ts +0 -7
  112. package/dist/services/built-in/tell-joke/handler.js +0 -122
  113. package/dist/services/built-in/tell-joke/index.d.ts +0 -9
  114. package/dist/services/built-in/tell-joke/index.js +0 -31
  115. package/dist/services/built-in/translate/index.d.ts +0 -6
  116. package/dist/services/built-in/translate/index.js +0 -21
  117. package/dist/services/built-in/web-research/index.d.ts +0 -9
  118. package/dist/services/built-in/web-research/index.js +0 -51
  119. package/dist/services/index.d.ts +0 -13
  120. package/dist/services/index.js +0 -14
  121. package/dist/services/loader.d.ts +0 -77
  122. package/dist/services/loader.js +0 -292
  123. package/dist/services/manager.d.ts +0 -86
  124. package/dist/services/manager.js +0 -255
  125. package/dist/services/registry.d.ts +0 -98
  126. package/dist/services/registry.js +0 -204
  127. package/dist/services/types.d.ts +0 -230
  128. package/dist/services/types.js +0 -30
  129. package/dist/test/cli.test.d.ts +0 -7
  130. package/dist/test/cli.test.js +0 -329
  131. package/dist/test/comprehensive-overlay.test.d.ts +0 -13
  132. package/dist/test/comprehensive-overlay.test.js +0 -593
  133. package/dist/test/key-derivation.test.d.ts +0 -12
  134. package/dist/test/key-derivation.test.js +0 -86
  135. package/dist/test/overlay-submit.test.d.ts +0 -10
  136. package/dist/test/overlay-submit.test.js +0 -460
  137. package/dist/test/request-response-flow.test.d.ts +0 -5
  138. package/dist/test/request-response-flow.test.js +0 -209
  139. package/dist/test/service-system.test.d.ts +0 -5
  140. package/dist/test/service-system.test.js +0 -190
  141. package/dist/test/utils/server-logic.d.ts +0 -98
  142. package/dist/test/utils/server-logic.js +0 -286
  143. package/dist/test/wallet.test.d.ts +0 -7
  144. package/dist/test/wallet.test.js +0 -146
@@ -1,68 +0,0 @@
1
- /**
2
- * Configuration constants and environment variables for the overlay CLI.
3
- */
4
- import path from 'node:path';
5
- import os from 'node:os';
6
- import fs from 'node:fs';
7
- // Auto-load .env from overlay state dir if it exists
8
- const overlayEnvPath = path.join(os.homedir(), '.openclaw', 'bsv-overlay', '.env');
9
- try {
10
- if (fs.existsSync(overlayEnvPath)) {
11
- for (const line of fs.readFileSync(overlayEnvPath, 'utf-8').split('\n')) {
12
- const match = line.match(/^([A-Z_]+)=(.+)$/);
13
- if (match && !process.env[match[1]]) {
14
- process.env[match[1]] = match[2].trim();
15
- }
16
- }
17
- }
18
- }
19
- catch {
20
- // Ignore errors loading .env
21
- }
22
- /** Wallet storage directory */
23
- export const WALLET_DIR = process.env.BSV_WALLET_DIR
24
- || path.join(os.homedir(), '.openclaw', 'bsv-wallet');
25
- /** Network to use (mainnet or testnet) */
26
- export const NETWORK = process.env.BSV_NETWORK || 'mainnet';
27
- /** Overlay server URL */
28
- export const OVERLAY_URL = process.env.OVERLAY_URL || 'https://clawoverlay.com';
29
- /** Agent display name on the overlay network */
30
- export const AGENT_NAME = process.env.AGENT_NAME || 'openclaw-agent';
31
- /** Agent description for the overlay identity */
32
- export const AGENT_DESCRIPTION = process.env.AGENT_DESCRIPTION ||
33
- `AI agent on the OpenClaw Overlay Network. Offers services for BSV micropayments.`;
34
- /** WhatsOnChain API key (optional, for rate limit bypass) */
35
- export const WOC_API_KEY = process.env.WOC_API_KEY || '';
36
- /** Overlay state directory for registration, services, etc. */
37
- export const OVERLAY_STATE_DIR = path.join(os.homedir(), '.openclaw', 'bsv-overlay');
38
- /** Protocol identifier for overlay transactions */
39
- export const PROTOCOL_ID = 'openclaw overlay v1';
40
- /** Topic managers for overlay submissions */
41
- export const TOPICS = {
42
- IDENTITY: 'tm_clawdbot_identity',
43
- SERVICES: 'tm_clawdbot_services',
44
- X_VERIFICATION: 'tm_clawdbot_x_verification',
45
- };
46
- /** Lookup services for overlay queries */
47
- export const LOOKUP_SERVICES = {
48
- AGENTS: 'ls_clawdbot_agents',
49
- SERVICES: 'ls_clawdbot_services',
50
- X_VERIFICATIONS: 'ls_clawdbot_x_verifications',
51
- };
52
- /** Paths derived from config */
53
- export const PATHS = {
54
- walletIdentity: path.join(WALLET_DIR, 'wallet-identity.json'),
55
- registration: path.join(OVERLAY_STATE_DIR, 'registration.json'),
56
- services: path.join(OVERLAY_STATE_DIR, 'services.json'),
57
- latestChange: path.join(OVERLAY_STATE_DIR, 'latest-change.json'),
58
- receivedPayments: path.join(OVERLAY_STATE_DIR, 'received-payments.jsonl'),
59
- researchQueue: path.join(OVERLAY_STATE_DIR, 'research-queue.jsonl'),
60
- serviceQueue: path.join(OVERLAY_STATE_DIR, 'service-queue.jsonl'),
61
- notifications: path.join(OVERLAY_STATE_DIR, 'notifications.jsonl'),
62
- xVerifications: path.join(OVERLAY_STATE_DIR, 'x-verifications.json'),
63
- pendingXVerification: path.join(OVERLAY_STATE_DIR, 'pending-x-verification.json'),
64
- xEngagementQueue: path.join(OVERLAY_STATE_DIR, 'x-engagement-queue.jsonl'),
65
- memoryStore: path.join(WALLET_DIR, 'memory-store.json'),
66
- baemailConfig: path.join(OVERLAY_STATE_DIR, 'baemail-config.json'),
67
- baemailLog: path.join(OVERLAY_STATE_DIR, 'baemail-log.jsonl'),
68
- };
@@ -1,7 +0,0 @@
1
- /**
2
- * Main exports for lib modules.
3
- */
4
- export * from './types.js';
5
- export * from './config.js';
6
- export * from './output.js';
7
- export * from './baemail/index.js';
@@ -1,7 +0,0 @@
1
- /**
2
- * Main exports for lib modules.
3
- */
4
- export * from './types.js';
5
- export * from './config.js';
6
- export * from './output.js';
7
- export * from './baemail/index.js';
@@ -1,8 +0,0 @@
1
- /**
2
- * Connect command: WebSocket real-time message processing.
3
- */
4
- /**
5
- * Connect command: establish WebSocket connection for real-time messaging.
6
- * Note: This function never returns normally - it runs until SIGINT/SIGTERM.
7
- */
8
- export declare function cmdConnect(): Promise<void>;
@@ -1,114 +0,0 @@
1
- /**
2
- * Connect command: WebSocket real-time message processing.
3
- */
4
- import fs from 'node:fs';
5
- import { OVERLAY_URL, PATHS } from '../config.js';
6
- import { fail } from '../output.js';
7
- import { loadIdentity } from '../wallet/identity.js';
8
- import { processMessage } from './handlers.js';
9
- import { ensureStateDir } from '../utils/storage.js';
10
- /**
11
- * Connect command: establish WebSocket connection for real-time messaging.
12
- * Note: This function never returns normally - it runs until SIGINT/SIGTERM.
13
- */
14
- export async function cmdConnect() {
15
- let WebSocketClient;
16
- try {
17
- const ws = await import('ws');
18
- WebSocketClient = ws.default || ws.WebSocket || ws;
19
- }
20
- catch {
21
- return fail('WebSocket client not available. Install it: npm install ws');
22
- }
23
- const { identityKey, privKey } = await loadIdentity();
24
- const wsUrl = OVERLAY_URL.replace(/^http/, 'ws') + '/relay/subscribe?identity=' + identityKey;
25
- let reconnectDelay = 1000;
26
- let shouldReconnect = true;
27
- let currentWs = null;
28
- function shutdown() {
29
- shouldReconnect = false;
30
- if (currentWs) {
31
- try {
32
- currentWs.close();
33
- }
34
- catch { }
35
- }
36
- process.exit(0);
37
- }
38
- process.on('SIGINT', shutdown);
39
- process.on('SIGTERM', shutdown);
40
- function connect() {
41
- const ws = new WebSocketClient(wsUrl);
42
- currentWs = ws;
43
- ws.on('open', () => {
44
- reconnectDelay = 1000; // reset on successful connect
45
- console.error(JSON.stringify({ event: 'connected', identity: identityKey, overlay: OVERLAY_URL }));
46
- });
47
- ws.on('message', async (data) => {
48
- try {
49
- const envelope = JSON.parse(data.toString());
50
- if (envelope.type === 'message') {
51
- const result = await processMessage(envelope.message, identityKey, privKey);
52
- // Output the result as a JSON line to stdout
53
- console.log(JSON.stringify(result));
54
- // Also append to notification log
55
- ensureStateDir();
56
- try {
57
- fs.appendFileSync(PATHS.notifications, JSON.stringify({ ...result, _ts: Date.now() }) + '\n');
58
- }
59
- catch { }
60
- // Ack the message
61
- if (result.ack) {
62
- try {
63
- await fetch(OVERLAY_URL + '/relay/ack', {
64
- method: 'POST',
65
- headers: { 'Content-Type': 'application/json' },
66
- body: JSON.stringify({ identity: identityKey, messageIds: [result.id] }),
67
- });
68
- }
69
- catch (ackErr) {
70
- console.error(JSON.stringify({ event: 'ack-error', id: result.id, message: String(ackErr) }));
71
- }
72
- }
73
- }
74
- // Handle service announcements
75
- if (envelope.type === 'service-announced') {
76
- const svc = envelope.service || {};
77
- const announcement = {
78
- event: 'service-announced',
79
- serviceId: svc.serviceId,
80
- name: svc.name,
81
- description: svc.description,
82
- priceSats: svc.pricingSats,
83
- provider: svc.identityKey,
84
- txid: envelope.txid,
85
- _ts: Date.now(),
86
- };
87
- console.log(JSON.stringify(announcement));
88
- ensureStateDir();
89
- try {
90
- fs.appendFileSync(PATHS.notifications, JSON.stringify(announcement) + '\n');
91
- }
92
- catch { }
93
- }
94
- }
95
- catch (err) {
96
- console.error(JSON.stringify({ event: 'process-error', message: String(err) }));
97
- }
98
- });
99
- ws.on('close', () => {
100
- currentWs = null;
101
- if (shouldReconnect) {
102
- console.error(JSON.stringify({ event: 'disconnected', reconnectMs: reconnectDelay }));
103
- setTimeout(connect, reconnectDelay);
104
- reconnectDelay = Math.min(reconnectDelay * 2, 30000);
105
- }
106
- });
107
- ws.on('error', (err) => {
108
- console.error(JSON.stringify({ event: 'error', message: err.message }));
109
- });
110
- }
111
- connect();
112
- // Keep the process alive — never resolves
113
- await new Promise(() => { });
114
- }
@@ -1,21 +0,0 @@
1
- /**
2
- * Message type handlers and processMessage function.
3
- */
4
- import type { RelayMessage, ProcessMessageResult } from '../types.js';
5
- /**
6
- * Verify and accept a payment from a service request.
7
- * Uses a2a-bsv wallet.acceptPayment() for proper BRC-29 handling.
8
- */
9
- export declare function verifyAndAcceptPayment(payment: any, minSats: number, senderKey: string, serviceId: string, ourHash160: Uint8Array): Promise<{
10
- accepted: boolean;
11
- txid: string | null;
12
- satoshis: number;
13
- outputIndex: number;
14
- walletAccepted: boolean;
15
- error: string | null;
16
- }>;
17
- /**
18
- * Process a single relay message.
19
- * Handles pings, service requests, pongs, and service responses.
20
- */
21
- export declare function processMessage(msg: RelayMessage, identityKey: string, privKey: any): Promise<ProcessMessageResult>;
@@ -1,334 +0,0 @@
1
- /**
2
- * Message type handlers and processMessage function.
3
- */
4
- import fs from 'node:fs';
5
- import { OVERLAY_URL, WALLET_DIR, PATHS } from '../config.js';
6
- import { signRelayMessage, verifyRelaySignature, loadWalletIdentity } from '../wallet/identity.js';
7
- import { loadServices, appendToJsonl } from '../utils/storage.js';
8
- import { fetchWithTimeout } from '../utils/woc.js';
9
- import { serviceManager } from '../../services/index.js';
10
- // Dynamic import for @bsv/sdk (needed for hash160 computation)
11
- let _sdk = null;
12
- async function getSdk() {
13
- if (_sdk)
14
- return _sdk;
15
- try {
16
- _sdk = await import('@bsv/sdk');
17
- return _sdk;
18
- }
19
- catch {
20
- const { fileURLToPath } = await import('node:url');
21
- const path = await import('node:path');
22
- const os = await import('node:os');
23
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
24
- const candidates = [
25
- path.resolve(__dirname, '..', '..', '..', 'node_modules', '@bsv', 'sdk', 'dist', 'esm', 'mod.js'),
26
- path.resolve(__dirname, '..', '..', '..', '..', '..', 'a2a-bsv', 'packages', 'core', 'node_modules', '@bsv', 'sdk', 'dist', 'esm', 'mod.js'),
27
- path.resolve(os.homedir(), 'a2a-bsv', 'packages', 'core', 'node_modules', '@bsv', 'sdk', 'dist', 'esm', 'mod.js'),
28
- ];
29
- for (const p of candidates) {
30
- try {
31
- _sdk = await import(p);
32
- return _sdk;
33
- }
34
- catch {
35
- // Try next
36
- }
37
- }
38
- throw new Error('Cannot find @bsv/sdk. Run setup.sh first.');
39
- }
40
- }
41
- import { BSVAgentWallet } from '../../core/index.js';
42
- async function getBSVAgentWallet() {
43
- return BSVAgentWallet;
44
- }
45
- // Import NETWORK lazily to avoid circular dependencies
46
- async function getNetwork() {
47
- const config = await import('../config.js');
48
- return config.NETWORK;
49
- }
50
- /**
51
- * Verify and accept a payment from a service request.
52
- * Uses a2a-bsv wallet.acceptPayment() for proper BRC-29 handling.
53
- */
54
- export async function verifyAndAcceptPayment(payment, minSats, senderKey, serviceId, ourHash160) {
55
- if (!payment) {
56
- return { accepted: false, txid: null, satoshis: 0, outputIndex: 0, walletAccepted: false, error: 'no payment' };
57
- }
58
- if (payment.error) {
59
- return { accepted: false, txid: null, satoshis: 0, outputIndex: 0, walletAccepted: false, error: payment.error };
60
- }
61
- if (!payment.beef || !payment.satoshis) {
62
- return { accepted: false, txid: null, satoshis: 0, outputIndex: 0, walletAccepted: false, error: 'missing beef or satoshis' };
63
- }
64
- if (payment.satoshis < minSats) {
65
- return { accepted: false, txid: payment.txid || null, satoshis: payment.satoshis, outputIndex: 0, walletAccepted: false, error: `insufficient payment: ${payment.satoshis} < ${minSats}` };
66
- }
67
- // Accept the payment using a2a-bsv wallet
68
- const BSVAgentWallet = await getBSVAgentWallet();
69
- const network = await getNetwork();
70
- const wallet = await BSVAgentWallet.load({ network, storageDir: WALLET_DIR });
71
- try {
72
- // First verify the payment structure
73
- const verifyResult = await wallet.verifyPayment({ beef: payment.beef });
74
- if (!verifyResult.valid) {
75
- await wallet.destroy();
76
- return { accepted: false, txid: payment.txid || null, satoshis: payment.satoshis, outputIndex: 0, walletAccepted: false, error: `verification failed: ${verifyResult.errors.join(', ')}` };
77
- }
78
- // Accept the payment (this broadcasts the transaction)
79
- const acceptResult = await wallet.acceptPayment({
80
- beef: payment.beef,
81
- derivationPrefix: payment.derivationPrefix,
82
- derivationSuffix: payment.derivationSuffix,
83
- senderIdentityKey: payment.senderIdentityKey,
84
- description: `Payment for ${serviceId}`,
85
- });
86
- await wallet.destroy();
87
- if (!acceptResult.accepted) {
88
- return { accepted: false, txid: payment.txid || null, satoshis: payment.satoshis, outputIndex: 0, walletAccepted: false, error: 'wallet rejected payment' };
89
- }
90
- return {
91
- accepted: true,
92
- txid: payment.txid,
93
- satoshis: payment.satoshis,
94
- outputIndex: 0,
95
- walletAccepted: true,
96
- error: null,
97
- };
98
- }
99
- catch (err) {
100
- await wallet.destroy();
101
- return { accepted: false, txid: payment.txid || null, satoshis: payment.satoshis, outputIndex: 0, walletAccepted: false, error: err.message };
102
- }
103
- }
104
- /**
105
- * Queue a service request for agent processing.
106
- */
107
- async function queueForAgent(msg, identityKey, privKey, serviceId) {
108
- // Check if this request has already been processed to prevent duplicates
109
- if (fs.existsSync(PATHS.serviceQueue)) {
110
- const lines = fs.readFileSync(PATHS.serviceQueue, 'utf-8').trim().split('\n').filter(Boolean);
111
- for (const line of lines) {
112
- try {
113
- const entry = JSON.parse(line);
114
- if (entry.requestId === msg.id) {
115
- // Request already exists in queue - return existing status
116
- return {
117
- id: msg.id,
118
- type: 'service-request',
119
- serviceId,
120
- action: entry.status === 'pending' ? 'already-queued' : `already-${entry.status}`,
121
- paymentAccepted: true,
122
- paymentTxid: entry.paymentTxid,
123
- satoshisReceived: entry.satoshisReceived,
124
- from: msg.from,
125
- ack: true,
126
- };
127
- }
128
- }
129
- catch { }
130
- }
131
- }
132
- const sdk = await getSdk();
133
- const payment = msg.payload?.payment;
134
- const input = msg.payload?.input || msg.payload;
135
- // Verify and accept payment
136
- const walletIdentity = loadWalletIdentity();
137
- const ourHash160 = sdk.Hash.hash160(sdk.PrivateKey.fromHex(walletIdentity.rootKeyHex).toPublicKey().encode(true));
138
- // Find the service price using the service registry
139
- const serviceDefinition = serviceManager.registry.get(serviceId);
140
- let minPrice = 5; // default fallback
141
- if (serviceDefinition) {
142
- minPrice = serviceDefinition.defaultPrice;
143
- // Validate service input if possible
144
- const validation = serviceManager.validate(serviceId, input);
145
- if (!validation.valid) {
146
- // Send validation rejection
147
- const rejectPayload = {
148
- requestId: msg.id,
149
- serviceId,
150
- status: 'rejected',
151
- reason: `Input validation failed: ${validation.error}`
152
- };
153
- const sig = await signRelayMessage(privKey, msg.from, 'service-response', rejectPayload);
154
- await fetchWithTimeout(`${OVERLAY_URL}/relay/send`, {
155
- method: 'POST',
156
- headers: { 'Content-Type': 'application/json' },
157
- body: JSON.stringify({ from: identityKey, to: msg.from, type: 'service-response', payload: rejectPayload, signature: sig }),
158
- });
159
- // Also add the rejected entry to the queue for tracking
160
- const rejectedEntry = {
161
- status: 'rejected',
162
- requestId: msg.id,
163
- serviceId,
164
- from: msg.from,
165
- identityKey,
166
- input: input,
167
- paymentTxid: null,
168
- satoshisReceived: 0,
169
- walletAccepted: false,
170
- error: validation.error,
171
- _ts: Date.now(),
172
- };
173
- appendToJsonl(PATHS.serviceQueue, rejectedEntry);
174
- return {
175
- id: msg.id,
176
- type: 'service-request',
177
- serviceId,
178
- action: 'rejected',
179
- reason: validation.error || 'input validation failed',
180
- from: msg.from,
181
- ack: true
182
- };
183
- }
184
- }
185
- else {
186
- // Fall back to legacy service loading for backward compatibility
187
- const services = loadServices();
188
- const svc = services.find(s => s.serviceId === serviceId);
189
- minPrice = svc?.priceSats || 5;
190
- }
191
- const payResult = await verifyAndAcceptPayment(payment, minPrice, msg.from, serviceId, ourHash160);
192
- if (!payResult.accepted) {
193
- // Send rejection
194
- const rejectPayload = { requestId: msg.id, serviceId, status: 'rejected', reason: `Payment rejected: ${payResult.error}` };
195
- const sig = await signRelayMessage(privKey, msg.from, 'service-response', rejectPayload);
196
- await fetchWithTimeout(`${OVERLAY_URL}/relay/send`, {
197
- method: 'POST',
198
- headers: { 'Content-Type': 'application/json' },
199
- body: JSON.stringify({ from: identityKey, to: msg.from, type: 'service-response', payload: rejectPayload, signature: sig }),
200
- });
201
- // Also add the rejected entry to the queue for tracking
202
- const rejectedEntry = {
203
- status: 'rejected',
204
- requestId: msg.id,
205
- serviceId,
206
- from: msg.from,
207
- identityKey,
208
- input: input,
209
- paymentTxid: null,
210
- satoshisReceived: 0,
211
- walletAccepted: false,
212
- error: payResult.error,
213
- _ts: Date.now(),
214
- };
215
- appendToJsonl(PATHS.serviceQueue, rejectedEntry);
216
- return { id: msg.id, type: 'service-request', serviceId, action: 'rejected', reason: payResult.error || 'payment rejected', from: msg.from, ack: true };
217
- }
218
- // Queue for agent processing
219
- const queueEntry = {
220
- status: 'pending',
221
- requestId: msg.id,
222
- serviceId,
223
- from: msg.from,
224
- identityKey,
225
- input: input,
226
- paymentTxid: payResult.txid,
227
- satoshisReceived: payResult.satoshis,
228
- walletAccepted: payResult.walletAccepted,
229
- _ts: Date.now(),
230
- };
231
- appendToJsonl(PATHS.serviceQueue, queueEntry);
232
- return {
233
- id: msg.id,
234
- type: 'service-request',
235
- serviceId,
236
- action: 'queued-for-agent',
237
- paymentAccepted: true,
238
- paymentTxid: payResult.txid,
239
- satoshisReceived: payResult.satoshis,
240
- from: msg.from,
241
- ack: true,
242
- };
243
- }
244
- /**
245
- * Process a single relay message.
246
- * Handles pings, service requests, pongs, and service responses.
247
- */
248
- export async function processMessage(msg, identityKey, privKey) {
249
- // Verify signature if present
250
- const sigCheck = msg.signature
251
- ? await verifyRelaySignature(msg.from, msg.to, msg.type, msg.payload, msg.signature)
252
- : { valid: null };
253
- // Reject unsigned/forged service-requests
254
- if (msg.type === 'service-request' && sigCheck.valid !== true) {
255
- console.error(JSON.stringify({ event: 'signature-rejected', type: msg.type, from: msg.from, reason: sigCheck.reason || 'missing signature' }));
256
- return {
257
- id: msg.id,
258
- type: msg.type,
259
- from: msg.from,
260
- action: 'rejected',
261
- reason: 'invalid-signature',
262
- signatureValid: sigCheck.valid,
263
- ack: true,
264
- };
265
- }
266
- if (msg.type === 'ping') {
267
- // Auto-respond with pong
268
- const pongPayload = {
269
- text: 'pong',
270
- inReplyTo: msg.id,
271
- originalText: msg.payload?.text || null,
272
- };
273
- const pongSig = await signRelayMessage(privKey, msg.from, 'pong', pongPayload);
274
- await fetch(`${OVERLAY_URL}/relay/send`, {
275
- method: 'POST',
276
- headers: { 'Content-Type': 'application/json' },
277
- body: JSON.stringify({
278
- from: identityKey,
279
- to: msg.from,
280
- type: 'pong',
281
- payload: pongPayload,
282
- signature: pongSig,
283
- }),
284
- });
285
- return { id: msg.id, type: 'ping', action: 'replied-pong', from: msg.from, ack: true };
286
- }
287
- if (msg.type === 'service-request') {
288
- const serviceId = msg.payload?.serviceId;
289
- // Agent-routed mode: queue for the agent
290
- if (process.env.AGENT_ROUTED === 'true') {
291
- return await queueForAgent(msg, identityKey, privKey, serviceId);
292
- }
293
- // No hardcoded handlers in TypeScript version — always queue
294
- return await queueForAgent(msg, identityKey, privKey, serviceId);
295
- }
296
- if (msg.type === 'pong') {
297
- return {
298
- id: msg.id,
299
- type: 'pong',
300
- action: 'received',
301
- from: msg.from,
302
- text: msg.payload?.text,
303
- inReplyTo: msg.payload?.inReplyTo,
304
- ack: true,
305
- };
306
- }
307
- if (msg.type === 'service-response') {
308
- const serviceId = msg.payload?.serviceId;
309
- const status = msg.payload?.status;
310
- const result = msg.payload?.result;
311
- return {
312
- id: msg.id,
313
- type: 'service-response',
314
- action: 'received',
315
- from: msg.from,
316
- serviceId,
317
- status,
318
- result,
319
- requestId: msg.payload?.requestId,
320
- direction: 'incoming-response',
321
- ack: true,
322
- };
323
- }
324
- // Unknown type
325
- return {
326
- id: msg.id,
327
- type: msg.type,
328
- from: msg.from,
329
- payload: msg.payload,
330
- signatureValid: sigCheck.valid,
331
- action: 'unhandled',
332
- ack: false,
333
- };
334
- }
@@ -1,11 +0,0 @@
1
- /**
2
- * Inbox and ack commands.
3
- */
4
- /**
5
- * Inbox command: fetch pending messages.
6
- */
7
- export declare function cmdInbox(args: string[]): Promise<never>;
8
- /**
9
- * Ack command: acknowledge processed messages.
10
- */
11
- export declare function cmdAck(messageIds: string[]): Promise<never>;
@@ -1,51 +0,0 @@
1
- /**
2
- * Inbox and ack commands.
3
- */
4
- import { OVERLAY_URL } from '../config.js';
5
- import { ok, fail } from '../output.js';
6
- import { loadIdentity, verifyRelaySignature } from '../wallet/identity.js';
7
- /**
8
- * Inbox command: fetch pending messages.
9
- */
10
- export async function cmdInbox(args) {
11
- const { identityKey } = await loadIdentity();
12
- let since = '';
13
- for (let i = 0; i < args.length; i++) {
14
- if (args[i] === '--since' && args[i + 1])
15
- since = `&since=${args[++i]}`;
16
- }
17
- const resp = await fetch(`${OVERLAY_URL}/relay/inbox?identity=${identityKey}${since}`);
18
- if (!resp.ok) {
19
- const body = await resp.text();
20
- return fail(`Relay inbox failed (${resp.status}): ${body}`);
21
- }
22
- const result = await resp.json();
23
- // Verify signatures on received messages
24
- const messages = await Promise.all(result.messages.map(async (msg) => ({
25
- ...msg,
26
- signatureValid: msg.signature
27
- ? (await verifyRelaySignature(msg.from, msg.to, msg.type, msg.payload, msg.signature)).valid
28
- : null,
29
- })));
30
- return ok({ messages, count: messages.length, identityKey });
31
- }
32
- /**
33
- * Ack command: acknowledge processed messages.
34
- */
35
- export async function cmdAck(messageIds) {
36
- if (!messageIds || messageIds.length === 0) {
37
- return fail('Usage: ack <messageId> [messageId2 ...]');
38
- }
39
- const { identityKey } = await loadIdentity();
40
- const resp = await fetch(`${OVERLAY_URL}/relay/ack`, {
41
- method: 'POST',
42
- headers: { 'Content-Type': 'application/json' },
43
- body: JSON.stringify({ identity: identityKey, messageIds }),
44
- });
45
- if (!resp.ok) {
46
- const body = await resp.text();
47
- return fail(`Relay ack failed (${resp.status}): ${body}`);
48
- }
49
- const result = await resp.json();
50
- return ok({ acked: result.acked, messageIds });
51
- }
@@ -1,8 +0,0 @@
1
- /**
2
- * Messaging module exports.
3
- */
4
- export * from './send.js';
5
- export * from './inbox.js';
6
- export * from './handlers.js';
7
- export * from './poll.js';
8
- export * from './connect.js';
@@ -1,8 +0,0 @@
1
- /**
2
- * Messaging module exports.
3
- */
4
- export * from './send.js';
5
- export * from './inbox.js';
6
- export * from './handlers.js';
7
- export * from './poll.js';
8
- export * from './connect.js';
@@ -1,7 +0,0 @@
1
- /**
2
- * Poll command: fetch and process all pending messages.
3
- */
4
- /**
5
- * Poll command: fetch all pending messages and process them.
6
- */
7
- export declare function cmdPoll(): Promise<never>;