openclaw-overlay-plugin 0.7.22

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 (221) hide show
  1. package/README.md +406 -0
  2. package/SKILL.md +78 -0
  3. package/clawdbot.plugin.json +106 -0
  4. package/dist/cli-main.d.ts +7 -0
  5. package/dist/cli-main.js +192 -0
  6. package/dist/cli.d.ts +8 -0
  7. package/dist/cli.js +14 -0
  8. package/dist/core/config.d.ts +11 -0
  9. package/dist/core/config.js +13 -0
  10. package/dist/core/index.d.ts +25 -0
  11. package/dist/core/index.js +26 -0
  12. package/dist/core/payment.d.ts +16 -0
  13. package/dist/core/payment.js +94 -0
  14. package/dist/core/types.d.ts +94 -0
  15. package/dist/core/types.js +4 -0
  16. package/dist/core/verify.d.ts +28 -0
  17. package/dist/core/verify.js +104 -0
  18. package/dist/core/wallet.d.ts +99 -0
  19. package/dist/core/wallet.js +219 -0
  20. package/dist/scripts/baemail/commands.d.ts +64 -0
  21. package/dist/scripts/baemail/commands.js +258 -0
  22. package/dist/scripts/baemail/handler.d.ts +36 -0
  23. package/dist/scripts/baemail/handler.js +284 -0
  24. package/dist/scripts/baemail/index.d.ts +5 -0
  25. package/dist/scripts/baemail/index.js +5 -0
  26. package/dist/scripts/config.d.ts +48 -0
  27. package/dist/scripts/config.js +68 -0
  28. package/dist/scripts/index.d.ts +7 -0
  29. package/dist/scripts/index.js +7 -0
  30. package/dist/scripts/messaging/connect.d.ts +8 -0
  31. package/dist/scripts/messaging/connect.js +114 -0
  32. package/dist/scripts/messaging/handlers.d.ts +21 -0
  33. package/dist/scripts/messaging/handlers.js +334 -0
  34. package/dist/scripts/messaging/inbox.d.ts +11 -0
  35. package/dist/scripts/messaging/inbox.js +51 -0
  36. package/dist/scripts/messaging/index.d.ts +8 -0
  37. package/dist/scripts/messaging/index.js +8 -0
  38. package/dist/scripts/messaging/poll.d.ts +7 -0
  39. package/dist/scripts/messaging/poll.js +52 -0
  40. package/dist/scripts/messaging/send.d.ts +7 -0
  41. package/dist/scripts/messaging/send.js +43 -0
  42. package/dist/scripts/output.d.ts +12 -0
  43. package/dist/scripts/output.js +19 -0
  44. package/dist/scripts/overlay/discover.d.ts +7 -0
  45. package/dist/scripts/overlay/discover.js +72 -0
  46. package/dist/scripts/overlay/index.d.ts +7 -0
  47. package/dist/scripts/overlay/index.js +7 -0
  48. package/dist/scripts/overlay/registration.d.ts +19 -0
  49. package/dist/scripts/overlay/registration.js +176 -0
  50. package/dist/scripts/overlay/services.d.ts +29 -0
  51. package/dist/scripts/overlay/services.js +167 -0
  52. package/dist/scripts/overlay/transaction.d.ts +42 -0
  53. package/dist/scripts/overlay/transaction.js +103 -0
  54. package/dist/scripts/payment/build.d.ts +24 -0
  55. package/dist/scripts/payment/build.js +54 -0
  56. package/dist/scripts/payment/commands.d.ts +15 -0
  57. package/dist/scripts/payment/commands.js +73 -0
  58. package/dist/scripts/payment/index.d.ts +6 -0
  59. package/dist/scripts/payment/index.js +6 -0
  60. package/dist/scripts/payment/types.d.ts +56 -0
  61. package/dist/scripts/payment/types.js +4 -0
  62. package/dist/scripts/services/index.d.ts +6 -0
  63. package/dist/scripts/services/index.js +6 -0
  64. package/dist/scripts/services/queue.d.ts +11 -0
  65. package/dist/scripts/services/queue.js +28 -0
  66. package/dist/scripts/services/request.d.ts +7 -0
  67. package/dist/scripts/services/request.js +82 -0
  68. package/dist/scripts/services/respond.d.ts +11 -0
  69. package/dist/scripts/services/respond.js +132 -0
  70. package/dist/scripts/types.d.ts +107 -0
  71. package/dist/scripts/types.js +4 -0
  72. package/dist/scripts/utils/index.d.ts +6 -0
  73. package/dist/scripts/utils/index.js +6 -0
  74. package/dist/scripts/utils/merkle.d.ts +12 -0
  75. package/dist/scripts/utils/merkle.js +47 -0
  76. package/dist/scripts/utils/storage.d.ts +66 -0
  77. package/dist/scripts/utils/storage.js +211 -0
  78. package/dist/scripts/utils/woc.d.ts +26 -0
  79. package/dist/scripts/utils/woc.js +91 -0
  80. package/dist/scripts/wallet/balance.d.ts +22 -0
  81. package/dist/scripts/wallet/balance.js +240 -0
  82. package/dist/scripts/wallet/identity.d.ts +70 -0
  83. package/dist/scripts/wallet/identity.js +151 -0
  84. package/dist/scripts/wallet/index.d.ts +6 -0
  85. package/dist/scripts/wallet/index.js +6 -0
  86. package/dist/scripts/wallet/setup.d.ts +15 -0
  87. package/dist/scripts/wallet/setup.js +105 -0
  88. package/dist/scripts/x-verification/commands.d.ts +27 -0
  89. package/dist/scripts/x-verification/commands.js +222 -0
  90. package/dist/scripts/x-verification/index.d.ts +4 -0
  91. package/dist/scripts/x-verification/index.js +4 -0
  92. package/dist/services/built-in/api-proxy/index.d.ts +6 -0
  93. package/dist/services/built-in/api-proxy/index.js +23 -0
  94. package/dist/services/built-in/code-develop/index.d.ts +6 -0
  95. package/dist/services/built-in/code-develop/index.js +23 -0
  96. package/dist/services/built-in/code-review/index.d.ts +10 -0
  97. package/dist/services/built-in/code-review/index.js +51 -0
  98. package/dist/services/built-in/image-analysis/index.d.ts +6 -0
  99. package/dist/services/built-in/image-analysis/index.js +33 -0
  100. package/dist/services/built-in/memory-store/index.d.ts +6 -0
  101. package/dist/services/built-in/memory-store/index.js +22 -0
  102. package/dist/services/built-in/roulette/index.d.ts +6 -0
  103. package/dist/services/built-in/roulette/index.js +27 -0
  104. package/dist/services/built-in/summarize/index.d.ts +6 -0
  105. package/dist/services/built-in/summarize/index.js +21 -0
  106. package/dist/services/built-in/tell-joke/handler.d.ts +7 -0
  107. package/dist/services/built-in/tell-joke/handler.js +122 -0
  108. package/dist/services/built-in/tell-joke/index.d.ts +9 -0
  109. package/dist/services/built-in/tell-joke/index.js +31 -0
  110. package/dist/services/built-in/translate/index.d.ts +6 -0
  111. package/dist/services/built-in/translate/index.js +21 -0
  112. package/dist/services/built-in/web-research/index.d.ts +9 -0
  113. package/dist/services/built-in/web-research/index.js +51 -0
  114. package/dist/services/index.d.ts +13 -0
  115. package/dist/services/index.js +14 -0
  116. package/dist/services/loader.d.ts +77 -0
  117. package/dist/services/loader.js +292 -0
  118. package/dist/services/manager.d.ts +86 -0
  119. package/dist/services/manager.js +255 -0
  120. package/dist/services/registry.d.ts +98 -0
  121. package/dist/services/registry.js +204 -0
  122. package/dist/services/types.d.ts +230 -0
  123. package/dist/services/types.js +30 -0
  124. package/dist/test/cli.test.d.ts +7 -0
  125. package/dist/test/cli.test.js +329 -0
  126. package/dist/test/comprehensive-overlay.test.d.ts +13 -0
  127. package/dist/test/comprehensive-overlay.test.js +593 -0
  128. package/dist/test/key-derivation.test.d.ts +12 -0
  129. package/dist/test/key-derivation.test.js +86 -0
  130. package/dist/test/overlay-submit.test.d.ts +10 -0
  131. package/dist/test/overlay-submit.test.js +460 -0
  132. package/dist/test/request-response-flow.test.d.ts +5 -0
  133. package/dist/test/request-response-flow.test.js +209 -0
  134. package/dist/test/service-system.test.d.ts +5 -0
  135. package/dist/test/service-system.test.js +190 -0
  136. package/dist/test/utils/server-logic.d.ts +98 -0
  137. package/dist/test/utils/server-logic.js +286 -0
  138. package/dist/test/wallet.test.d.ts +7 -0
  139. package/dist/test/wallet.test.js +146 -0
  140. package/index.ts +1965 -0
  141. package/openclaw.plugin.json +106 -0
  142. package/package.json +73 -0
  143. package/src/cli-main.ts +230 -0
  144. package/src/cli.ts +16 -0
  145. package/src/core/README.md +246 -0
  146. package/src/core/config.ts +21 -0
  147. package/src/core/index.ts +42 -0
  148. package/src/core/payment.ts +111 -0
  149. package/src/core/types.ts +102 -0
  150. package/src/core/verify.ts +119 -0
  151. package/src/core/wallet.ts +282 -0
  152. package/src/scripts/baemail/commands.ts +326 -0
  153. package/src/scripts/baemail/handler.ts +338 -0
  154. package/src/scripts/baemail/index.ts +6 -0
  155. package/src/scripts/config.ts +81 -0
  156. package/src/scripts/index.ts +8 -0
  157. package/src/scripts/messaging/connect.ts +121 -0
  158. package/src/scripts/messaging/handlers.ts +394 -0
  159. package/src/scripts/messaging/inbox.ts +64 -0
  160. package/src/scripts/messaging/index.ts +9 -0
  161. package/src/scripts/messaging/poll.ts +59 -0
  162. package/src/scripts/messaging/send.ts +54 -0
  163. package/src/scripts/output.ts +21 -0
  164. package/src/scripts/overlay/discover.ts +81 -0
  165. package/src/scripts/overlay/index.ts +8 -0
  166. package/src/scripts/overlay/registration.ts +199 -0
  167. package/src/scripts/overlay/services.ts +199 -0
  168. package/src/scripts/overlay/transaction.ts +124 -0
  169. package/src/scripts/payment/build.ts +65 -0
  170. package/src/scripts/payment/commands.ts +92 -0
  171. package/src/scripts/payment/index.ts +7 -0
  172. package/src/scripts/payment/types.ts +62 -0
  173. package/src/scripts/services/index.ts +7 -0
  174. package/src/scripts/services/queue.ts +35 -0
  175. package/src/scripts/services/request.ts +98 -0
  176. package/src/scripts/services/respond.ts +149 -0
  177. package/src/scripts/types.ts +121 -0
  178. package/src/scripts/utils/index.ts +7 -0
  179. package/src/scripts/utils/merkle.ts +57 -0
  180. package/src/scripts/utils/storage.ts +231 -0
  181. package/src/scripts/utils/woc.ts +106 -0
  182. package/src/scripts/wallet/balance.ts +277 -0
  183. package/src/scripts/wallet/identity.ts +203 -0
  184. package/src/scripts/wallet/index.ts +7 -0
  185. package/src/scripts/wallet/setup.ts +121 -0
  186. package/src/scripts/x-verification/commands.ts +256 -0
  187. package/src/scripts/x-verification/index.ts +5 -0
  188. package/src/services/built-in/api-proxy/index.ts +26 -0
  189. package/src/services/built-in/api-proxy/prompt.md +26 -0
  190. package/src/services/built-in/code-develop/index.ts +26 -0
  191. package/src/services/built-in/code-develop/prompt.md +35 -0
  192. package/src/services/built-in/code-review/index.ts +54 -0
  193. package/src/services/built-in/code-review/prompt.md +105 -0
  194. package/src/services/built-in/image-analysis/index.ts +36 -0
  195. package/src/services/built-in/image-analysis/prompt.md +42 -0
  196. package/src/services/built-in/memory-store/index.ts +25 -0
  197. package/src/services/built-in/memory-store/prompt.md +45 -0
  198. package/src/services/built-in/roulette/index.ts +30 -0
  199. package/src/services/built-in/roulette/prompt.md +35 -0
  200. package/src/services/built-in/summarize/index.ts +24 -0
  201. package/src/services/built-in/summarize/prompt.md +27 -0
  202. package/src/services/built-in/tell-joke/handler.ts +134 -0
  203. package/src/services/built-in/tell-joke/index.ts +34 -0
  204. package/src/services/built-in/tell-joke/prompt.md +59 -0
  205. package/src/services/built-in/translate/index.ts +24 -0
  206. package/src/services/built-in/translate/prompt.md +23 -0
  207. package/src/services/built-in/web-research/index.ts +54 -0
  208. package/src/services/built-in/web-research/prompt.md +110 -0
  209. package/src/services/index.ts +16 -0
  210. package/src/services/loader.ts +344 -0
  211. package/src/services/manager.ts +304 -0
  212. package/src/services/registry.ts +246 -0
  213. package/src/services/types.ts +259 -0
  214. package/src/test/cli.test.ts +352 -0
  215. package/src/test/comprehensive-overlay.test.ts +729 -0
  216. package/src/test/key-derivation.test.ts +102 -0
  217. package/src/test/overlay-submit.test.ts +570 -0
  218. package/src/test/request-response-flow.test.ts +252 -0
  219. package/src/test/service-system.test.ts +241 -0
  220. package/src/test/utils/server-logic.ts +368 -0
  221. package/src/test/wallet.test.ts +166 -0
@@ -0,0 +1,252 @@
1
+ /**
2
+ * Tests for request/response flow and duplicate prevention.
3
+ */
4
+
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+
8
+ // Simple test runner (matching existing pattern)
9
+ let passed = 0;
10
+ let failed = 0;
11
+
12
+ function test(name: string, fn: () => void | Promise<void>) {
13
+ return (async () => {
14
+ try {
15
+ await fn();
16
+ console.log(` ✓ ${name}`);
17
+ passed++;
18
+ } catch (err: unknown) {
19
+ const msg = err instanceof Error ? err.message : String(err);
20
+ console.log(` ✗ ${name}`);
21
+ console.log(` ${msg}`);
22
+ failed++;
23
+ }
24
+ })();
25
+ }
26
+
27
+ function assert(condition: boolean, message: string) {
28
+ if (!condition) throw new Error(`Assertion failed: ${message}`);
29
+ }
30
+
31
+ // Mock paths for testing
32
+ const TEST_DIR = path.join(process.cwd(), 'test-data');
33
+ const TEST_PATHS = {
34
+ serviceQueue: path.join(TEST_DIR, 'service-queue.jsonl'),
35
+ walletDir: path.join(TEST_DIR, 'wallet'),
36
+ registration: path.join(TEST_DIR, 'registration.json'),
37
+ services: path.join(TEST_DIR, 'services.json'),
38
+ };
39
+
40
+ function setupTestEnv() {
41
+ // Setup test directory
42
+ if (fs.existsSync(TEST_DIR)) {
43
+ fs.rmSync(TEST_DIR, { recursive: true, force: true });
44
+ }
45
+ fs.mkdirSync(TEST_DIR, { recursive: true });
46
+ }
47
+
48
+ function cleanupTestEnv() {
49
+ if (fs.existsSync(TEST_DIR)) {
50
+ fs.rmSync(TEST_DIR, { recursive: true, force: true });
51
+ }
52
+ }
53
+
54
+ async function run() {
55
+ console.log('\nRequest/Response Flow Tests\n');
56
+
57
+ // ── Queue Cleanup Tests ──────────────────────────────────────────────
58
+
59
+ await test('cleanupServiceQueue removes old fulfilled entries', async () => {
60
+ setupTestEnv();
61
+
62
+ const now = Date.now();
63
+ const oldTime = now - (3 * 60 * 60 * 1000); // 3 hours ago
64
+ const recentTime = now - (30 * 60 * 1000); // 30 minutes ago
65
+
66
+ // Add test entries
67
+ const entries = [
68
+ { status: 'pending', requestId: 'pending-1', _ts: recentTime },
69
+ { status: 'fulfilled', requestId: 'old-fulfilled', _ts: oldTime },
70
+ { status: 'fulfilled', requestId: 'recent-fulfilled', _ts: recentTime },
71
+ { status: 'rejected', requestId: 'old-rejected', _ts: oldTime }
72
+ ];
73
+
74
+ const content = entries.map(e => JSON.stringify(e)).join('\n') + '\n';
75
+ fs.writeFileSync(TEST_PATHS.serviceQueue, content);
76
+
77
+ // Mock PATHS for cleanupServiceQueue
78
+ const originalPaths = await import('../scripts/config.js');
79
+ const mockPaths = { ...originalPaths.PATHS, serviceQueue: TEST_PATHS.serviceQueue };
80
+
81
+ // Temporarily replace PATHS
82
+ (globalThis as Record<string, unknown>).mockPaths = mockPaths;
83
+
84
+ // Redefine cleanupServiceQueue with mocked paths
85
+ function mockCleanupServiceQueue(maxAgeMs = 24 * 60 * 60 * 1000, finalStatusMaxAgeMs = 2 * 60 * 60 * 1000) {
86
+ if (!fs.existsSync(TEST_PATHS.serviceQueue)) return;
87
+
88
+ const currentTime = Date.now();
89
+ const finalStatuses = ['fulfilled', 'rejected', 'delivery_failed', 'failed', 'error'];
90
+
91
+ const lines = fs.readFileSync(TEST_PATHS.serviceQueue, 'utf-8').trim().split('\n').filter(Boolean);
92
+ const keptLines: string[] = [];
93
+ let removedCount = 0;
94
+
95
+ for (const line of lines) {
96
+ try {
97
+ const entry = JSON.parse(line);
98
+ const entryAge = currentTime - (entry._ts || 0);
99
+
100
+ // Always keep pending entries that aren't too old
101
+ if (entry.status === 'pending' && entryAge < maxAgeMs) {
102
+ keptLines.push(line);
103
+ continue;
104
+ }
105
+
106
+ // Keep final status entries only if they're recent
107
+ if (finalStatuses.includes(entry.status) && entryAge < finalStatusMaxAgeMs) {
108
+ keptLines.push(line);
109
+ continue;
110
+ }
111
+
112
+ // Remove this entry
113
+ removedCount++;
114
+ } catch {
115
+ // Keep malformed entries to avoid data loss
116
+ keptLines.push(line);
117
+ }
118
+ }
119
+
120
+ if (removedCount > 0) {
121
+ fs.writeFileSync(TEST_PATHS.serviceQueue, keptLines.join('\n') + (keptLines.length ? '\n' : ''));
122
+ }
123
+ }
124
+
125
+ // Run cleanup with 2 hour limit for final statuses
126
+ mockCleanupServiceQueue(24 * 60 * 60 * 1000, 2 * 60 * 60 * 1000);
127
+
128
+ // Check remaining entries
129
+ const lines = fs.readFileSync(TEST_PATHS.serviceQueue, 'utf-8').trim().split('\n').filter(Boolean);
130
+ const remaining = lines.map(line => JSON.parse(line));
131
+
132
+ assert(remaining.length === 2, `Expected 2 remaining entries, got ${remaining.length}`);
133
+ assert(remaining.find(e => e.requestId === 'pending-1') !== undefined, 'Should keep recent pending');
134
+ assert(remaining.find(e => e.requestId === 'recent-fulfilled') !== undefined, 'Should keep recent fulfilled');
135
+ assert(remaining.find(e => e.requestId === 'old-fulfilled') === undefined, 'Should remove old fulfilled');
136
+ assert(remaining.find(e => e.requestId === 'old-rejected') === undefined, 'Should remove old rejected');
137
+
138
+ cleanupTestEnv();
139
+ });
140
+
141
+ await test('updateServiceQueueStatus updates request status atomically', async () => {
142
+ setupTestEnv();
143
+
144
+ // Add a test entry
145
+ const entry = {
146
+ status: 'pending',
147
+ requestId: 'test-request-456',
148
+ serviceId: 'test-service',
149
+ from: 'sender-key',
150
+ _ts: Date.now()
151
+ };
152
+
153
+ fs.writeFileSync(TEST_PATHS.serviceQueue, JSON.stringify(entry) + '\n');
154
+
155
+ // Mock updateServiceQueueStatus with test paths
156
+ function mockUpdateServiceQueueStatus(requestId: string, newStatus: string, additionalFields = {}) {
157
+ if (!fs.existsSync(TEST_PATHS.serviceQueue)) return false;
158
+
159
+ const lines = fs.readFileSync(TEST_PATHS.serviceQueue, 'utf-8').trim().split('\n').filter(Boolean);
160
+ let updated = false;
161
+
162
+ const updatedLines = lines.map(line => {
163
+ try {
164
+ const entryData = JSON.parse(line);
165
+ if (entryData.requestId === requestId) {
166
+ updated = true;
167
+ return JSON.stringify({
168
+ ...entryData,
169
+ status: newStatus,
170
+ ...additionalFields,
171
+ updatedAt: Date.now()
172
+ });
173
+ }
174
+ return line;
175
+ } catch {
176
+ return line;
177
+ }
178
+ });
179
+
180
+ if (updated) {
181
+ fs.writeFileSync(TEST_PATHS.serviceQueue, updatedLines.join('\n') + '\n');
182
+ }
183
+
184
+ return updated;
185
+ }
186
+
187
+ // Update status
188
+ const updated = mockUpdateServiceQueueStatus('test-request-456', 'fulfilled', {
189
+ fulfilledAt: Date.now(),
190
+ result: { message: 'success' }
191
+ });
192
+
193
+ assert(updated === true, 'Should return true for successful update');
194
+
195
+ // Verify update
196
+ const lines = fs.readFileSync(TEST_PATHS.serviceQueue, 'utf-8').trim().split('\n').filter(Boolean);
197
+ const updatedEntry = JSON.parse(lines[0]);
198
+
199
+ assert(updatedEntry.status === 'fulfilled', 'Status should be updated to fulfilled');
200
+ assert(updatedEntry.requestId === 'test-request-456', 'Request ID should remain the same');
201
+ assert(updatedEntry.fulfilledAt !== undefined, 'Should have fulfilledAt timestamp');
202
+ assert(updatedEntry.updatedAt !== undefined, 'Should have updatedAt timestamp');
203
+ assert(updatedEntry.result?.message === 'success', 'Should have result data');
204
+
205
+ cleanupTestEnv();
206
+ });
207
+
208
+ await test('updateServiceQueueStatus returns false for non-existent request', async () => {
209
+ setupTestEnv();
210
+
211
+ // Mock updateServiceQueueStatus with test paths
212
+ function mockUpdateServiceQueueStatus(requestId: string, _newStatus: string) {
213
+ if (!fs.existsSync(TEST_PATHS.serviceQueue)) return false;
214
+
215
+ const lines = fs.readFileSync(TEST_PATHS.serviceQueue, 'utf-8').trim().split('\n').filter(Boolean);
216
+ let updated = false;
217
+
218
+ lines.map(line => {
219
+ try {
220
+ const entry = JSON.parse(line);
221
+ if (entry.requestId === requestId) {
222
+ updated = true;
223
+ }
224
+ return line;
225
+ } catch {
226
+ return line;
227
+ }
228
+ });
229
+
230
+ return updated;
231
+ }
232
+
233
+ const updated = mockUpdateServiceQueueStatus('non-existent-request', 'fulfilled');
234
+ assert(updated === false, 'Should return false for non-existent request');
235
+
236
+ cleanupTestEnv();
237
+ });
238
+
239
+ // ── Summary ──────────────────────────────────────────────────────────
240
+ console.log(`\n${passed} passed, ${failed} failed\n`);
241
+
242
+ if (failed > 0) {
243
+ process.exit(1);
244
+ }
245
+ }
246
+
247
+ // Run tests if this file is executed directly
248
+ if (import.meta.url === `file://${process.argv[1]}`) {
249
+ run().catch(console.error);
250
+ }
251
+
252
+ export { run };
@@ -0,0 +1,241 @@
1
+ /**
2
+ * Service system comprehensive tests.
3
+ * Tests service registration, loading, validation, and execution.
4
+ */
5
+
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { serviceRegistry, serviceLoader, serviceManager, initializeServiceSystem } from '../services/index.js';
10
+ import { ServiceDefinition, ServiceCategory } from '../services/types.js';
11
+
12
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
13
+ const projectRoot = path.resolve(__dirname, '..', '..');
14
+
15
+ // Test helper functions
16
+ function assert(condition: boolean, message: string) {
17
+ if (!condition) {
18
+ throw new Error(`Assertion failed: ${message}`);
19
+ }
20
+ }
21
+
22
+ function assertEquals(actual: any, expected: any, message?: string) {
23
+ if (actual !== expected) {
24
+ throw new Error(`Assertion failed: ${message || ''} - Expected ${expected}, got ${actual}`);
25
+ }
26
+ }
27
+
28
+ console.log('\n=== Service System Tests ===\n');
29
+
30
+ // Test 1: Service Registry Basic Operations
31
+ console.log('Testing service registry basic operations...');
32
+
33
+ // Create test service
34
+ const testService: ServiceDefinition = {
35
+ id: 'test-service',
36
+ name: 'Test Service',
37
+ description: 'A test service for unit testing',
38
+ defaultPrice: 10,
39
+ category: ServiceCategory.UTILITY,
40
+ inputSchema: {
41
+ type: 'object',
42
+ properties: {
43
+ message: { type: 'string', description: 'Test message' }
44
+ },
45
+ required: ['message']
46
+ }
47
+ };
48
+
49
+ // Clear registry for clean test
50
+ serviceRegistry.clear();
51
+
52
+ // Test registration
53
+ serviceRegistry.register(testService);
54
+ assert(serviceRegistry.get('test-service') !== undefined, 'Service should be registered');
55
+ assertEquals(serviceRegistry.get('test-service')?.name, 'Test Service', 'Service name should match');
56
+
57
+ // Test listing
58
+ const services = serviceRegistry.list();
59
+ assert(services.length === 1, 'Should have one registered service');
60
+ assertEquals(services[0].id, 'test-service', 'Listed service should match registered service');
61
+
62
+ console.log('✅ Registry: basic operations work correctly');
63
+
64
+ // Test 2: Service Registry Validation
65
+ console.log('Testing service registry validation...');
66
+
67
+ // Test duplicate registration
68
+ try {
69
+ serviceRegistry.register(testService);
70
+ throw new Error('Should have thrown error for duplicate registration');
71
+ } catch (error: any) {
72
+ assert(error.message.includes('already registered'), 'Should reject duplicate registration');
73
+ }
74
+
75
+ // Test invalid service (missing required fields)
76
+ try {
77
+ serviceRegistry.register({
78
+ id: '',
79
+ name: 'Invalid',
80
+ description: 'Missing ID',
81
+ defaultPrice: 10
82
+ } as ServiceDefinition);
83
+ throw new Error('Should have thrown error for invalid service');
84
+ } catch (error: any) {
85
+ assert(error.message.includes('Service ID is required'), 'Should reject service without ID');
86
+ }
87
+
88
+ console.log('✅ Registry: validation works correctly');
89
+
90
+ // Test 3: Service Loader Directory Scanning
91
+ console.log('Testing service loader directory scanning...');
92
+
93
+ // Clear registry for clean test
94
+ serviceRegistry.clear();
95
+
96
+ // Load built-in services
97
+ const builtInServices = await serviceLoader.loadBuiltInServices();
98
+ assert(builtInServices.length > 0, 'Should load built-in services');
99
+
100
+ // Check that specific services are loaded
101
+ const expectedServices = ['tell-joke', 'api-proxy', 'summarize', 'memory-store', 'roulette', 'code-develop', 'image-analysis'];
102
+ for (const serviceId of expectedServices) {
103
+ const service = builtInServices.find(s => s.id === serviceId);
104
+ assert(service !== undefined, `Should load ${serviceId} service`);
105
+ assert(service!.name.length > 0, `${serviceId} should have a name`);
106
+ assert(service!.description.length > 0, `${serviceId} should have a description`);
107
+ assert(service!.defaultPrice > 0, `${serviceId} should have a valid price`);
108
+ }
109
+
110
+ console.log('✅ Loader: directory scanning works correctly');
111
+
112
+ // Test 4: Service Manager Integration
113
+ console.log('Testing service manager integration...');
114
+
115
+ // Initialize service system
116
+ await initializeServiceSystem();
117
+
118
+ // Test service discovery
119
+ const joke = serviceManager.registry.get('tell-joke');
120
+ assert(joke !== undefined, 'Should find tell-joke service');
121
+ assertEquals(joke!.name, 'Random Joke', 'Service name should match');
122
+
123
+ // Test validation with valid input
124
+ const validationResult = serviceManager.validate('tell-joke', { topic: 'programming' });
125
+ assert(validationResult.valid, 'Valid input should pass validation');
126
+
127
+ // Tell-joke service has no required fields, so empty object is valid
128
+ const emptyInputResult = serviceManager.validate('tell-joke', {});
129
+ assert(emptyInputResult.valid, 'Empty input should be valid for tell-joke service');
130
+
131
+ // Test with truly invalid input (wrong type)
132
+ const invalidResult = serviceManager.validate('tell-joke', { topic: 123 });
133
+ assert(!invalidResult.valid, 'Invalid input type should fail validation');
134
+
135
+ console.log('✅ Manager: integration works correctly');
136
+
137
+ // Test 5: Service Input Schema Validation
138
+ console.log('Testing service input schema validation...');
139
+
140
+ // Test api-proxy service validation
141
+ const apiProxy = serviceManager.registry.get('api-proxy');
142
+ assert(apiProxy !== undefined, 'Should find api-proxy service');
143
+
144
+ const validApiInput = { url: 'https://api.example.com/test', method: 'GET' };
145
+ const validApiResult = serviceManager.validate('api-proxy', validApiInput);
146
+ assert(validApiResult.valid, 'Valid api-proxy input should pass');
147
+
148
+ const invalidApiInput = { method: 'GET' }; // missing required url
149
+ const invalidApiResult = serviceManager.validate('api-proxy', invalidApiInput);
150
+ assert(!invalidApiResult.valid, 'Invalid api-proxy input should fail');
151
+
152
+ console.log('✅ Validation: input schema validation works correctly');
153
+
154
+ // Test 6: Service Categories
155
+ console.log('Testing service categories...');
156
+
157
+ // Check that services have appropriate categories
158
+ const categorizedServices = serviceManager.registry.list();
159
+ const categories = new Set(categorizedServices.map(s => s.category).filter(Boolean));
160
+ assert(categories.size > 0, 'Should have services with categories');
161
+
162
+ // Verify known categories
163
+ const expectedCategories = ['utility', 'ai', 'entertainment', 'development'];
164
+ for (const category of expectedCategories) {
165
+ const servicesInCategory = categorizedServices.filter(s => s.category === category);
166
+ assert(servicesInCategory.length > 0, `Should have services in ${category} category`);
167
+ }
168
+
169
+ console.log('✅ Categories: service categorization works correctly');
170
+
171
+ // Test 7: Service Loading Error Handling
172
+ console.log('Testing service loading error handling...');
173
+
174
+ // Test loading from non-existent directory
175
+ try {
176
+ await serviceLoader.loadFromDirectory('/non/existent/directory');
177
+ // Should not throw, but return empty array
178
+ console.log('✅ Loader: graceful handling of non-existent directory');
179
+ } catch {
180
+ // This is also acceptable behavior
181
+ console.log('✅ Loader: appropriate error handling for non-existent directory');
182
+ }
183
+
184
+ // Test 8: Service Prompt Files
185
+ console.log('Testing service prompt files...');
186
+
187
+ // Check that services with prompt files can be found
188
+ const servicesWithPrompts = categorizedServices.filter(s => s.promptFile);
189
+ assert(servicesWithPrompts.length > 0, 'Should have services with prompt files');
190
+
191
+ // Verify prompt files exist
192
+ for (const service of servicesWithPrompts.slice(0, 3)) { // Test first 3 to avoid excessive file I/O
193
+ if (service.promptFile) {
194
+ const promptPath = path.resolve(projectRoot, service.promptFile);
195
+ assert(fs.existsSync(promptPath), `Prompt file should exist: ${service.promptFile}`);
196
+
197
+ const content = fs.readFileSync(promptPath, 'utf-8');
198
+ assert(content.includes(service.id), `Prompt should reference service ID: ${service.id}`);
199
+ }
200
+ }
201
+
202
+ console.log('✅ Prompts: service prompt files work correctly');
203
+
204
+ // Test 9: Service Registry Search and Filter
205
+ console.log('Testing service registry search and filter...');
206
+
207
+ // Test filtering by category
208
+ const aiServices = categorizedServices.filter(s => s.category === ServiceCategory.AI);
209
+ assert(aiServices.length > 0, 'Should have AI services');
210
+
211
+ const utilityServices = categorizedServices.filter(s => s.category === ServiceCategory.UTILITY);
212
+ assert(utilityServices.length > 0, 'Should have utility services');
213
+
214
+ // Test name search
215
+ const jokeServices = categorizedServices.filter(s => s.name.toLowerCase().includes('joke'));
216
+ assert(jokeServices.length > 0, 'Should find joke-related services');
217
+
218
+ console.log('✅ Search: service filtering works correctly');
219
+
220
+ // Test 10: Service System State Consistency
221
+ console.log('Testing service system state consistency...');
222
+
223
+ // Verify that registry and manager are in sync
224
+ const registryServices = serviceManager.registry.list();
225
+ const registryIds = new Set(registryServices.map(s => s.id));
226
+
227
+ // All services should be unique
228
+ assertEquals(registryIds.size, registryServices.length, 'All service IDs should be unique');
229
+
230
+ // All services should have valid pricing
231
+ for (const service of registryServices) {
232
+ assert(service.defaultPrice > 0, `Service ${service.id} should have valid price`);
233
+ assert(service.name.length > 0, `Service ${service.id} should have a name`);
234
+ assert(service.description.length > 0, `Service ${service.id} should have a description`);
235
+ }
236
+
237
+ console.log('✅ Consistency: service system state is consistent');
238
+
239
+ console.log('\n========================================');
240
+ console.log('Service System Tests completed: All tests passed!');
241
+ console.log('========================================\n');