@nordsym/apiclaw 1.5.6 → 1.5.8

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 (134) hide show
  1. package/convex/_generated/api.d.ts +2 -0
  2. package/convex/adminActivate.d.ts +3 -0
  3. package/convex/adminActivate.d.ts.map +1 -0
  4. package/convex/adminActivate.js +47 -0
  5. package/convex/adminActivate.js.map +1 -0
  6. package/convex/adminStats.d.ts +3 -0
  7. package/convex/adminStats.d.ts.map +1 -0
  8. package/convex/adminStats.js +42 -0
  9. package/convex/adminStats.js.map +1 -0
  10. package/convex/adminStats.ts +44 -0
  11. package/convex/agents.d.ts +54 -0
  12. package/convex/agents.d.ts.map +1 -0
  13. package/convex/agents.js +499 -0
  14. package/convex/agents.js.map +1 -0
  15. package/convex/analytics.d.ts +5 -0
  16. package/convex/analytics.d.ts.map +1 -0
  17. package/convex/analytics.js +166 -0
  18. package/convex/analytics.js.map +1 -0
  19. package/convex/billing.d.ts +88 -0
  20. package/convex/billing.d.ts.map +1 -0
  21. package/convex/billing.js +655 -0
  22. package/convex/billing.js.map +1 -0
  23. package/convex/capabilities.d.ts +9 -0
  24. package/convex/capabilities.d.ts.map +1 -0
  25. package/convex/capabilities.js +145 -0
  26. package/convex/capabilities.js.map +1 -0
  27. package/convex/chains.d.ts +67 -0
  28. package/convex/chains.d.ts.map +1 -0
  29. package/convex/chains.js +1042 -0
  30. package/convex/chains.js.map +1 -0
  31. package/convex/credits.d.ts +25 -0
  32. package/convex/credits.d.ts.map +1 -0
  33. package/convex/credits.js +186 -0
  34. package/convex/credits.js.map +1 -0
  35. package/convex/crons.d.ts +3 -0
  36. package/convex/crons.d.ts.map +1 -0
  37. package/convex/crons.js +17 -0
  38. package/convex/crons.js.map +1 -0
  39. package/convex/directCall.d.ts +72 -0
  40. package/convex/directCall.d.ts.map +1 -0
  41. package/convex/directCall.js +627 -0
  42. package/convex/directCall.js.map +1 -0
  43. package/convex/earnProgress.d.ts +58 -0
  44. package/convex/earnProgress.d.ts.map +1 -0
  45. package/convex/earnProgress.js +649 -0
  46. package/convex/earnProgress.js.map +1 -0
  47. package/convex/email.d.ts +14 -0
  48. package/convex/email.d.ts.map +1 -0
  49. package/convex/email.js +300 -0
  50. package/convex/email.js.map +1 -0
  51. package/convex/feedback.d.ts +7 -0
  52. package/convex/feedback.d.ts.map +1 -0
  53. package/convex/feedback.js +227 -0
  54. package/convex/feedback.js.map +1 -0
  55. package/convex/http.d.ts +3 -0
  56. package/convex/http.d.ts.map +1 -0
  57. package/convex/http.js +902 -0
  58. package/convex/http.js.map +1 -0
  59. package/convex/logs.d.ts +38 -0
  60. package/convex/logs.d.ts.map +1 -0
  61. package/convex/logs.js +487 -0
  62. package/convex/logs.js.map +1 -0
  63. package/convex/logs.ts +6 -1
  64. package/convex/mou.d.ts +6 -0
  65. package/convex/mou.d.ts.map +1 -0
  66. package/convex/mou.js +82 -0
  67. package/convex/mou.js.map +1 -0
  68. package/convex/providerKeys.d.ts +31 -0
  69. package/convex/providerKeys.d.ts.map +1 -0
  70. package/convex/providerKeys.js +257 -0
  71. package/convex/providerKeys.js.map +1 -0
  72. package/convex/providers.d.ts +29 -0
  73. package/convex/providers.d.ts.map +1 -0
  74. package/convex/providers.js +756 -0
  75. package/convex/providers.js.map +1 -0
  76. package/convex/purchases.d.ts +7 -0
  77. package/convex/purchases.d.ts.map +1 -0
  78. package/convex/purchases.js +157 -0
  79. package/convex/purchases.js.map +1 -0
  80. package/convex/ratelimit.d.ts +4 -0
  81. package/convex/ratelimit.d.ts.map +1 -0
  82. package/convex/ratelimit.js +91 -0
  83. package/convex/ratelimit.js.map +1 -0
  84. package/convex/schema.ts +2 -0
  85. package/convex/searchLogs.d.ts +4 -0
  86. package/convex/searchLogs.d.ts.map +1 -0
  87. package/convex/searchLogs.js +129 -0
  88. package/convex/searchLogs.js.map +1 -0
  89. package/convex/spendAlerts.d.ts +36 -0
  90. package/convex/spendAlerts.d.ts.map +1 -0
  91. package/convex/spendAlerts.js +380 -0
  92. package/convex/spendAlerts.js.map +1 -0
  93. package/convex/stripeActions.d.ts +19 -0
  94. package/convex/stripeActions.d.ts.map +1 -0
  95. package/convex/stripeActions.js +411 -0
  96. package/convex/stripeActions.js.map +1 -0
  97. package/convex/teams.d.ts +21 -0
  98. package/convex/teams.d.ts.map +1 -0
  99. package/convex/teams.js +215 -0
  100. package/convex/teams.js.map +1 -0
  101. package/convex/telemetry.d.ts +4 -0
  102. package/convex/telemetry.d.ts.map +1 -0
  103. package/convex/telemetry.js +74 -0
  104. package/convex/telemetry.js.map +1 -0
  105. package/convex/usage.d.ts +27 -0
  106. package/convex/usage.d.ts.map +1 -0
  107. package/convex/usage.js +229 -0
  108. package/convex/usage.js.map +1 -0
  109. package/convex/waitlist.d.ts +4 -0
  110. package/convex/waitlist.d.ts.map +1 -0
  111. package/convex/waitlist.js +49 -0
  112. package/convex/waitlist.js.map +1 -0
  113. package/convex/webhooks.d.ts +12 -0
  114. package/convex/webhooks.d.ts.map +1 -0
  115. package/convex/webhooks.js +410 -0
  116. package/convex/webhooks.js.map +1 -0
  117. package/convex/workspaces.d.ts +29 -0
  118. package/convex/workspaces.d.ts.map +1 -0
  119. package/convex/workspaces.js +880 -0
  120. package/convex/workspaces.js.map +1 -0
  121. package/dist/analytics.d.ts +1 -1
  122. package/dist/analytics.d.ts.map +1 -1
  123. package/dist/analytics.js +51 -2
  124. package/dist/analytics.js.map +1 -1
  125. package/dist/index.js +27 -2
  126. package/dist/index.js.map +1 -1
  127. package/landing/scripts/generate-stats.js +9 -5
  128. package/landing/src/app/api/og/route.tsx +0 -2
  129. package/landing/src/app/page.tsx +3 -3
  130. package/landing/src/app/workspace/page.tsx +26 -1
  131. package/landing/src/lib/stats.json +2 -2
  132. package/package.json +1 -1
  133. package/src/analytics.ts +53 -2
  134. package/src/index.ts +28 -2
package/convex/http.js ADDED
@@ -0,0 +1,902 @@
1
+ import { httpRouter } from "convex/server";
2
+ import { httpAction } from "./_generated/server";
3
+ import { api, internal } from "./_generated/api";
4
+ import { createCheckoutSession, createPortalSession, handleStripeWebhook, checkoutOptions, portalOptions, webhookOptions, } from "./stripeActions";
5
+ const http = httpRouter();
6
+ // Provider catalog
7
+ const PROVIDERS = {
8
+ "46elks": {
9
+ name: "46elks",
10
+ description: "SMS API for EU/Nordics. GDPR compliant.",
11
+ category: "sms",
12
+ pricing: "~$0.035/SMS",
13
+ regions: ["EU", "Nordic"],
14
+ tags: ["sms", "eu", "gdpr", "nordic"],
15
+ },
16
+ twilio: {
17
+ name: "Twilio",
18
+ description: "SMS and Voice API. Global coverage.",
19
+ category: "sms",
20
+ pricing: "~$0.04/SMS, ~$0.01/min voice",
21
+ regions: ["Global"],
22
+ tags: ["sms", "voice", "global"],
23
+ },
24
+ resend: {
25
+ name: "Resend",
26
+ description: "Modern email API. Developer-friendly.",
27
+ category: "email",
28
+ pricing: "~$0.001/email",
29
+ regions: ["Global"],
30
+ tags: ["email", "transactional"],
31
+ },
32
+ brave_search: {
33
+ name: "Brave Search",
34
+ description: "Privacy-focused web search API.",
35
+ category: "search",
36
+ pricing: "~$0.005/search",
37
+ regions: ["Global"],
38
+ tags: ["search", "web", "privacy"],
39
+ },
40
+ openrouter: {
41
+ name: "OpenRouter",
42
+ description: "Multi-model LLM API. Access GPT, Claude, Llama, etc.",
43
+ category: "llm",
44
+ pricing: "Varies by model",
45
+ regions: ["Global"],
46
+ tags: ["llm", "ai", "gpt", "claude"],
47
+ },
48
+ elevenlabs: {
49
+ name: "ElevenLabs",
50
+ description: "Text-to-speech API. High quality voices.",
51
+ category: "tts",
52
+ pricing: "~$0.0003/char",
53
+ regions: ["Global"],
54
+ tags: ["tts", "voice", "audio"],
55
+ },
56
+ replicate: {
57
+ name: "Replicate",
58
+ description: "Run AI models (Whisper, SDXL, Llama, etc). Pay per prediction.",
59
+ category: "ai",
60
+ pricing: "Varies by model",
61
+ regions: ["Global"],
62
+ tags: ["ai", "ml", "whisper", "image", "audio", "transcription"],
63
+ },
64
+ firecrawl: {
65
+ name: "Firecrawl",
66
+ description: "Web scraping and crawling API. Extract clean data from any URL.",
67
+ category: "scraping",
68
+ pricing: "~$0.001/page",
69
+ regions: ["Global"],
70
+ tags: ["scraping", "web", "crawl", "extract"],
71
+ },
72
+ github: {
73
+ name: "GitHub",
74
+ description: "GitHub API. Search repos, manage code, access developer data.",
75
+ category: "code",
76
+ pricing: "Free tier available",
77
+ regions: ["Global"],
78
+ tags: ["github", "code", "repos", "developer"],
79
+ },
80
+ e2b: {
81
+ name: "E2B",
82
+ description: "Secure code sandbox for AI agents. Run Python, shell commands in isolated environments.",
83
+ category: "sandbox",
84
+ pricing: "$0.000028/s (2 vCPU)",
85
+ regions: ["Global"],
86
+ tags: ["sandbox", "code", "python", "execution", "ai", "agents"],
87
+ },
88
+ };
89
+ // CORS headers
90
+ const corsHeaders = {
91
+ "Access-Control-Allow-Origin": "*",
92
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
93
+ "Access-Control-Allow-Headers": "Content-Type, Authorization",
94
+ };
95
+ // Helper for JSON responses
96
+ function jsonResponse(data, status = 200) {
97
+ return new Response(JSON.stringify(data), {
98
+ status,
99
+ headers: { "Content-Type": "application/json", ...corsHeaders },
100
+ });
101
+ }
102
+ // Helper to validate session and log API usage
103
+ async function validateAndLogProxyCall(ctx, request, provider, action) {
104
+ const identifier = request.headers.get("X-APIClaw-Identifier");
105
+ const subagentId = request.headers.get("X-APIClaw-Subagent") || "main";
106
+ console.log("[Proxy] Call received", { provider, action, identifier, subagentId });
107
+ // ALWAYS log to analytics (even if identifier is missing)
108
+ try {
109
+ const result = await ctx.runMutation(api.analytics.log, {
110
+ event: "api_call",
111
+ provider,
112
+ identifier: identifier || "unknown",
113
+ metadata: { action, subagentId },
114
+ });
115
+ console.log("[Proxy] Analytics logged:", result);
116
+ }
117
+ catch (e) {
118
+ console.error("[Proxy] Analytics logging failed:", e.message, e.stack);
119
+ // Continue even if analytics fails
120
+ }
121
+ // If we have an identifier and it's a workspace ID (not anon:), log to workspace
122
+ if (identifier && !identifier.startsWith("anon:") && identifier !== "unknown") {
123
+ try {
124
+ // Validate it's actually a workspace ID by checking format
125
+ if (identifier.length > 20) {
126
+ await ctx.runMutation(api.logs.createProxyLog, {
127
+ workspaceId: identifier,
128
+ provider,
129
+ action,
130
+ subagentId,
131
+ });
132
+ // Increment workspace usage
133
+ await ctx.runMutation(api.workspaces.incrementUsage, {
134
+ workspaceId: identifier,
135
+ });
136
+ console.log("[Proxy] Workspace logged for:", identifier);
137
+ return { valid: true, workspaceId: identifier, subagentId };
138
+ }
139
+ }
140
+ catch (e) {
141
+ console.error("[Proxy] Workspace logging failed:", e.message);
142
+ // Continue even if workspace logging fails
143
+ }
144
+ }
145
+ // Return success regardless (don't block API calls)
146
+ return { valid: true, subagentId };
147
+ }
148
+ // OPTIONS handler for CORS
149
+ http.route({
150
+ path: "/api/discover",
151
+ method: "OPTIONS",
152
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
153
+ });
154
+ http.route({
155
+ path: "/api/details",
156
+ method: "OPTIONS",
157
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
158
+ });
159
+ http.route({
160
+ path: "/api/balance",
161
+ method: "OPTIONS",
162
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
163
+ });
164
+ http.route({
165
+ path: "/api/purchase",
166
+ method: "OPTIONS",
167
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
168
+ });
169
+ http.route({
170
+ path: "/admin/grant-credits",
171
+ method: "OPTIONS",
172
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
173
+ });
174
+ // Discover APIs
175
+ http.route({
176
+ path: "/api/discover",
177
+ method: "POST",
178
+ handler: httpAction(async (ctx, request) => {
179
+ try {
180
+ const startTime = Date.now();
181
+ const body = await request.json();
182
+ const query = (body.query || "").toLowerCase();
183
+ // Get optional auth context
184
+ const sessionToken = request.headers.get("X-APIClaw-Session");
185
+ const userAgent = request.headers.get("User-Agent");
186
+ const results = Object.entries(PROVIDERS)
187
+ .filter(([id, provider]) => {
188
+ if (!query)
189
+ return true;
190
+ return (provider.name.toLowerCase().includes(query) ||
191
+ provider.description.toLowerCase().includes(query) ||
192
+ provider.category.toLowerCase().includes(query) ||
193
+ provider.tags.some((tag) => tag.includes(query)));
194
+ })
195
+ .map(([id, provider]) => ({
196
+ providerId: id,
197
+ ...provider,
198
+ }));
199
+ const responseTimeMs = Date.now() - startTime;
200
+ // Log the search (fire and forget)
201
+ if (query) {
202
+ ctx.runMutation(internal.searchLogs.logSearch, {
203
+ query: body.query || "", // Original query (not lowercased)
204
+ resultsCount: results.length,
205
+ matchedProviders: results.map(r => r.providerId),
206
+ sessionToken: sessionToken || undefined,
207
+ userAgent: userAgent || undefined,
208
+ responseTimeMs,
209
+ }).catch(() => { }); // Ignore errors, don't block response
210
+ }
211
+ return jsonResponse({ providers: results, total: results.length });
212
+ }
213
+ catch (e) {
214
+ return jsonResponse({ error: "Invalid request" }, 400);
215
+ }
216
+ }),
217
+ });
218
+ // Get provider details
219
+ http.route({
220
+ path: "/api/details",
221
+ method: "POST",
222
+ handler: httpAction(async (ctx, request) => {
223
+ try {
224
+ const body = await request.json();
225
+ const { providerId } = body;
226
+ if (!providerId) {
227
+ return jsonResponse({ error: "providerId required" }, 400);
228
+ }
229
+ const provider = PROVIDERS[providerId];
230
+ if (!provider) {
231
+ return jsonResponse({ error: "Provider not found" }, 404);
232
+ }
233
+ return jsonResponse({
234
+ providerId,
235
+ ...provider,
236
+ creditsPerDollar: getCreditsPerDollar(providerId),
237
+ documentation: `https://apiclaw.com/docs/${providerId}`,
238
+ });
239
+ }
240
+ catch (e) {
241
+ return jsonResponse({ error: "Invalid request" }, 400);
242
+ }
243
+ }),
244
+ });
245
+ // Check balance
246
+ http.route({
247
+ path: "/api/balance",
248
+ method: "GET",
249
+ handler: httpAction(async (ctx, request) => {
250
+ const url = new URL(request.url);
251
+ const agentId = url.searchParams.get("agentId");
252
+ if (!agentId) {
253
+ return jsonResponse({ error: "agentId required" }, 400);
254
+ }
255
+ const credits = await ctx.runQuery(api.credits.getAgentCredits, { agentId });
256
+ if (!credits) {
257
+ return jsonResponse({
258
+ agentId,
259
+ balanceUsd: 0,
260
+ currency: "USD",
261
+ message: "No account found. Top up to get started!",
262
+ });
263
+ }
264
+ return jsonResponse({
265
+ agentId: credits.agentId,
266
+ balanceUsd: credits.balanceUsd,
267
+ currency: credits.currency,
268
+ });
269
+ }),
270
+ });
271
+ // Purchase API access
272
+ http.route({
273
+ path: "/api/purchase",
274
+ method: "POST",
275
+ handler: httpAction(async (ctx, request) => {
276
+ try {
277
+ const body = await request.json();
278
+ const { agentId, providerId, amountUsd } = body;
279
+ if (!agentId || !providerId || !amountUsd) {
280
+ return jsonResponse({ error: "agentId, providerId, and amountUsd required" }, 400);
281
+ }
282
+ if (amountUsd < 1 || amountUsd > 1000) {
283
+ return jsonResponse({ error: "amountUsd must be between 1 and 1000" }, 400);
284
+ }
285
+ const provider = PROVIDERS[providerId];
286
+ if (!provider) {
287
+ return jsonResponse({ error: "Provider not found" }, 404);
288
+ }
289
+ // Check balance first
290
+ const credits = await ctx.runQuery(api.credits.getAgentCredits, { agentId });
291
+ if (!credits || credits.balanceUsd < amountUsd) {
292
+ return jsonResponse({
293
+ error: "Insufficient balance",
294
+ currentBalance: credits?.balanceUsd || 0,
295
+ required: amountUsd,
296
+ }, 402);
297
+ }
298
+ // Execute purchase
299
+ const purchase = await ctx.runMutation(api.purchases.purchaseAccess, {
300
+ agentId,
301
+ providerId,
302
+ amountUsd,
303
+ credentials: generateCredentials(providerId),
304
+ });
305
+ if (!purchase) {
306
+ return jsonResponse({ error: "Purchase failed" }, 500);
307
+ }
308
+ return jsonResponse({
309
+ success: true,
310
+ purchase: {
311
+ id: purchase._id,
312
+ providerId: purchase.providerId,
313
+ amountUsd: purchase.amountUsd,
314
+ creditsGranted: purchase.creditsGranted,
315
+ status: purchase.status,
316
+ },
317
+ message: `Successfully purchased $${amountUsd} of ${provider.name} credits`,
318
+ });
319
+ }
320
+ catch (e) {
321
+ return jsonResponse({ error: e.message || "Purchase failed" }, 400);
322
+ }
323
+ }),
324
+ });
325
+ // Admin: Grant credits
326
+ http.route({
327
+ path: "/admin/grant-credits",
328
+ method: "POST",
329
+ handler: httpAction(async (ctx, request) => {
330
+ try {
331
+ const body = await request.json();
332
+ const { agentId, amount, reason } = body;
333
+ if (!agentId || !amount) {
334
+ return jsonResponse({ error: "agentId and amount required" }, 400);
335
+ }
336
+ // TODO: Add admin auth check here
337
+ // For now, allow grants (this is for Hivr integration)
338
+ const result = await ctx.runMutation(api.credits.addCredits, {
339
+ agentId,
340
+ amountUsd: amount,
341
+ source: reason || "admin_grant",
342
+ });
343
+ return jsonResponse({
344
+ success: true,
345
+ agentId,
346
+ credited: amount,
347
+ newBalance: result?.balanceUsd,
348
+ reason,
349
+ });
350
+ }
351
+ catch (e) {
352
+ return jsonResponse({ error: e.message || "Grant failed" }, 400);
353
+ }
354
+ }),
355
+ });
356
+ // Helper functions
357
+ function getCreditsPerDollar(providerId) {
358
+ const rates = {
359
+ "46elks": 30,
360
+ twilio: 25,
361
+ resend: 1000,
362
+ brave_search: 200,
363
+ openrouter: 100,
364
+ elevenlabs: 3333,
365
+ };
366
+ return rates[providerId] || 100;
367
+ }
368
+ function generateCredentials(providerId) {
369
+ // In production, this would generate or retrieve actual API keys
370
+ // For now, return placeholder indicating how to use
371
+ return {
372
+ type: "apiclaw_proxy",
373
+ endpoint: `https://brilliant-puffin-712.convex.site/proxy/${providerId}`,
374
+ note: "Use APIClaw proxy endpoint. Credentials managed automatically.",
375
+ };
376
+ }
377
+ export default http;
378
+ // ==============================================
379
+ // DIRECT CALL PROXY ENDPOINTS
380
+ // ==============================================
381
+ // OpenRouter proxy
382
+ http.route({
383
+ path: "/proxy/openrouter",
384
+ method: "POST",
385
+ handler: httpAction(async (ctx, request) => {
386
+ // Validate session and log usage
387
+ await validateAndLogProxyCall(ctx, request, "openrouter", "chat");
388
+ const OPENROUTER_KEY = process.env.OPENROUTER_API_KEY;
389
+ if (!OPENROUTER_KEY) {
390
+ return jsonResponse({ error: "OpenRouter not configured" }, 500);
391
+ }
392
+ try {
393
+ const body = await request.json();
394
+ const response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
395
+ method: "POST",
396
+ headers: {
397
+ "Authorization": `Bearer ${OPENROUTER_KEY}`,
398
+ "Content-Type": "application/json",
399
+ "HTTP-Referer": "https://apiclaw.nordsym.com",
400
+ "X-Title": "APIClaw",
401
+ },
402
+ body: JSON.stringify(body),
403
+ });
404
+ const data = await response.json();
405
+ return jsonResponse(data, response.status);
406
+ }
407
+ catch (e) {
408
+ return jsonResponse({ error: e.message }, 500);
409
+ }
410
+ }),
411
+ });
412
+ // Brave Search proxy
413
+ http.route({
414
+ path: "/proxy/brave_search",
415
+ method: "POST",
416
+ handler: httpAction(async (ctx, request) => {
417
+ // Validate session and log usage
418
+ await validateAndLogProxyCall(ctx, request, "brave_search", "search");
419
+ const BRAVE_KEY = process.env.BRAVE_API_KEY;
420
+ if (!BRAVE_KEY) {
421
+ return jsonResponse({ error: "Brave Search not configured" }, 500);
422
+ }
423
+ try {
424
+ const body = await request.json();
425
+ const { query, count = 10 } = body;
426
+ const url = new URL("https://api.search.brave.com/res/v1/web/search");
427
+ url.searchParams.set("q", query);
428
+ url.searchParams.set("count", String(count));
429
+ const response = await fetch(url.toString(), {
430
+ headers: { "X-Subscription-Token": BRAVE_KEY },
431
+ });
432
+ const data = await response.json();
433
+ return jsonResponse(data, response.status);
434
+ }
435
+ catch (e) {
436
+ return jsonResponse({ error: e.message }, 500);
437
+ }
438
+ }),
439
+ });
440
+ // Resend email proxy
441
+ http.route({
442
+ path: "/proxy/resend",
443
+ method: "POST",
444
+ handler: httpAction(async (ctx, request) => {
445
+ // Validate session and log usage
446
+ await validateAndLogProxyCall(ctx, request, "resend", "send_email");
447
+ const RESEND_KEY = process.env.RESEND_API_KEY;
448
+ if (!RESEND_KEY) {
449
+ return jsonResponse({ error: "Resend not configured" }, 500);
450
+ }
451
+ try {
452
+ const body = await request.json();
453
+ const response = await fetch("https://api.resend.com/emails", {
454
+ method: "POST",
455
+ headers: {
456
+ "Authorization": `Bearer ${RESEND_KEY}`,
457
+ "Content-Type": "application/json",
458
+ },
459
+ body: JSON.stringify(body),
460
+ });
461
+ const data = await response.json();
462
+ return jsonResponse(data, response.status);
463
+ }
464
+ catch (e) {
465
+ return jsonResponse({ error: e.message }, 500);
466
+ }
467
+ }),
468
+ });
469
+ // ElevenLabs TTS proxy
470
+ http.route({
471
+ path: "/proxy/elevenlabs",
472
+ method: "POST",
473
+ handler: httpAction(async (ctx, request) => {
474
+ // Validate session and log usage
475
+ await validateAndLogProxyCall(ctx, request, "elevenlabs", "text_to_speech");
476
+ const ELEVENLABS_KEY = process.env.ELEVENLABS_API_KEY;
477
+ if (!ELEVENLABS_KEY) {
478
+ return jsonResponse({ error: "ElevenLabs not configured" }, 500);
479
+ }
480
+ try {
481
+ const body = await request.json();
482
+ const { text, voice_id = "21m00Tcm4TlvDq8ikWAM" } = body;
483
+ const response = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${voice_id}`, {
484
+ method: "POST",
485
+ headers: {
486
+ "xi-api-key": ELEVENLABS_KEY,
487
+ "Content-Type": "application/json",
488
+ },
489
+ body: JSON.stringify({
490
+ text,
491
+ model_id: "eleven_turbo_v2",
492
+ }),
493
+ });
494
+ if (!response.ok) {
495
+ const error = await response.text();
496
+ return jsonResponse({ error }, response.status);
497
+ }
498
+ // Return audio as base64
499
+ const arrayBuffer = await response.arrayBuffer();
500
+ const base64 = Buffer.from(arrayBuffer).toString("base64");
501
+ return jsonResponse({
502
+ audio_base64: base64,
503
+ content_type: "audio/mpeg",
504
+ });
505
+ }
506
+ catch (e) {
507
+ return jsonResponse({ error: e.message }, 500);
508
+ }
509
+ }),
510
+ });
511
+ http.route({
512
+ path: "/proxy/openrouter",
513
+ method: "OPTIONS",
514
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
515
+ });
516
+ http.route({
517
+ path: "/proxy/brave_search",
518
+ method: "OPTIONS",
519
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
520
+ });
521
+ http.route({
522
+ path: "/proxy/resend",
523
+ method: "OPTIONS",
524
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
525
+ });
526
+ http.route({
527
+ path: "/proxy/elevenlabs",
528
+ method: "OPTIONS",
529
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
530
+ });
531
+ // 46elks SMS proxy
532
+ http.route({
533
+ path: "/proxy/46elks",
534
+ method: "POST",
535
+ handler: httpAction(async (ctx, request) => {
536
+ // Validate session and log usage
537
+ await validateAndLogProxyCall(ctx, request, "46elks", "send_sms");
538
+ const ELKS_USER = process.env.ELKS_API_USER;
539
+ const ELKS_PASS = process.env.ELKS_API_PASSWORD;
540
+ if (!ELKS_USER || !ELKS_PASS) {
541
+ return jsonResponse({ error: "46elks not configured" }, 500);
542
+ }
543
+ try {
544
+ const body = await request.json();
545
+ const { to, message, from = "APIClaw" } = body;
546
+ const auth = btoa(`${ELKS_USER}:${ELKS_PASS}`);
547
+ const response = await fetch("https://api.46elks.com/a1/sms", {
548
+ method: "POST",
549
+ headers: {
550
+ "Authorization": `Basic ${auth}`,
551
+ "Content-Type": "application/x-www-form-urlencoded",
552
+ },
553
+ body: new URLSearchParams({ from, to, message }),
554
+ });
555
+ const data = await response.json();
556
+ return jsonResponse(data, response.status);
557
+ }
558
+ catch (e) {
559
+ return jsonResponse({ error: e.message }, 500);
560
+ }
561
+ }),
562
+ });
563
+ // Twilio SMS proxy
564
+ http.route({
565
+ path: "/proxy/twilio",
566
+ method: "POST",
567
+ handler: httpAction(async (ctx, request) => {
568
+ // Validate session and log usage
569
+ await validateAndLogProxyCall(ctx, request, "twilio", "send_sms");
570
+ const TWILIO_SID = process.env.TWILIO_ACCOUNT_SID;
571
+ const TWILIO_TOKEN = process.env.TWILIO_AUTH_TOKEN;
572
+ if (!TWILIO_SID || !TWILIO_TOKEN) {
573
+ return jsonResponse({ error: "Twilio not configured" }, 500);
574
+ }
575
+ try {
576
+ const body = await request.json();
577
+ const { to, message, from } = body;
578
+ if (!from) {
579
+ return jsonResponse({ error: "Twilio requires 'from' number" }, 400);
580
+ }
581
+ const auth = btoa(`${TWILIO_SID}:${TWILIO_TOKEN}`);
582
+ const response = await fetch(`https://api.twilio.com/2010-04-01/Accounts/${TWILIO_SID}/Messages.json`, {
583
+ method: "POST",
584
+ headers: {
585
+ "Authorization": `Basic ${auth}`,
586
+ "Content-Type": "application/x-www-form-urlencoded",
587
+ },
588
+ body: new URLSearchParams({ To: to, From: from, Body: message }),
589
+ });
590
+ const data = await response.json();
591
+ return jsonResponse(data, response.status);
592
+ }
593
+ catch (e) {
594
+ return jsonResponse({ error: e.message }, 500);
595
+ }
596
+ }),
597
+ });
598
+ // CORS for new endpoints
599
+ http.route({
600
+ path: "/proxy/46elks",
601
+ method: "OPTIONS",
602
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
603
+ });
604
+ http.route({
605
+ path: "/proxy/twilio",
606
+ method: "OPTIONS",
607
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
608
+ });
609
+ // GitHub API proxy
610
+ http.route({
611
+ path: "/proxy/github",
612
+ method: "POST",
613
+ handler: httpAction(async (ctx, request) => {
614
+ // Validate session and log usage
615
+ const body = await request.json();
616
+ const action = body.action || "search_repos";
617
+ await validateAndLogProxyCall(ctx, request, "github", action);
618
+ const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
619
+ if (!GITHUB_TOKEN) {
620
+ return jsonResponse({ error: "GitHub not configured" }, 500);
621
+ }
622
+ try {
623
+ const { action, ...params } = body;
624
+ let url;
625
+ let method = "GET";
626
+ let fetchBody;
627
+ // Route based on action
628
+ switch (action) {
629
+ case "search_repos":
630
+ const { query, sort = "stars", limit = 10 } = params;
631
+ url = `https://api.github.com/search/repositories?q=${encodeURIComponent(query)}&sort=${sort}&per_page=${limit}`;
632
+ break;
633
+ case "get_repo":
634
+ const { owner, repo } = params;
635
+ url = `https://api.github.com/repos/${owner}/${repo}`;
636
+ break;
637
+ case "list_issues":
638
+ const { owner: issueOwner, repo: issueRepo, state = "open", limit: issueLimit = 10 } = params;
639
+ url = `https://api.github.com/repos/${issueOwner}/${issueRepo}/issues?state=${state}&per_page=${issueLimit}`;
640
+ break;
641
+ case "create_issue":
642
+ const { owner: createOwner, repo: createRepo, title, body: issueBody = "" } = params;
643
+ url = `https://api.github.com/repos/${createOwner}/${createRepo}/issues`;
644
+ method = "POST";
645
+ fetchBody = JSON.stringify({ title, body: issueBody });
646
+ break;
647
+ case "get_file":
648
+ const { owner: fileOwner, repo: fileRepo, path } = params;
649
+ url = `https://api.github.com/repos/${fileOwner}/${fileRepo}/contents/${path}`;
650
+ break;
651
+ default:
652
+ return jsonResponse({ error: `Unknown action: ${action}` }, 400);
653
+ }
654
+ const response = await fetch(url, {
655
+ method,
656
+ headers: {
657
+ "Authorization": `Bearer ${GITHUB_TOKEN}`,
658
+ "Accept": "application/vnd.github+json",
659
+ "User-Agent": "APIClaw",
660
+ ...(fetchBody ? { "Content-Type": "application/json" } : {}),
661
+ },
662
+ ...(fetchBody ? { body: fetchBody } : {}),
663
+ });
664
+ const data = await response.json();
665
+ return jsonResponse(data, response.status);
666
+ }
667
+ catch (e) {
668
+ return jsonResponse({ error: e.message }, 500);
669
+ }
670
+ }),
671
+ });
672
+ http.route({
673
+ path: "/proxy/github",
674
+ method: "OPTIONS",
675
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
676
+ });
677
+ // ==============================================
678
+ // WORKSPACE / MAGIC LINK ENDPOINTS
679
+ // ==============================================
680
+ // Create magic link and send email
681
+ http.route({
682
+ path: "/workspace/magic-link",
683
+ method: "POST",
684
+ handler: httpAction(async (ctx, request) => {
685
+ try {
686
+ const body = await request.json();
687
+ const { email, fingerprint } = body;
688
+ if (!email || !email.includes("@")) {
689
+ return jsonResponse({ error: "Valid email required" }, 400);
690
+ }
691
+ // Create magic link
692
+ const result = await ctx.runMutation(api.workspaces.createMagicLink, {
693
+ email: email.toLowerCase(),
694
+ fingerprint,
695
+ });
696
+ // Send email directly - SIMPLE HTML (complex tables get stripped by Gmail)
697
+ const verifyUrl = `https://apiclaw.nordsym.com/auth/verify?token=${result.token}`;
698
+ const html = `<div style="font-family:Arial,sans-serif;max-width:500px;margin:0 auto;padding:20px;">
699
+ <h1>🦞 APIClaw</h1>
700
+ <h2>An AI Agent Wants to Connect</h2>
701
+ <p>Click below to verify your email and activate your workspace.</p>
702
+ <p><a href="${verifyUrl}" style="background:#ef4444;color:white;padding:14px 32px;border-radius:8px;text-decoration:none;display:inline-block;">Verify Email</a></p>
703
+ <p style="color:#666;font-size:13px;">Free tier: 50 API calls. This link expires in 1 hour.</p>
704
+ <p style="color:#999;font-size:11px;">Or copy this link: ${verifyUrl}</p>
705
+ </div>`;
706
+ const RESEND_KEY = process.env.RESEND_API_KEY;
707
+ if (!RESEND_KEY) {
708
+ console.error("RESEND_API_KEY not configured");
709
+ return jsonResponse({ error: "Email service not configured" }, 500);
710
+ }
711
+ const emailResponse = await fetch("https://api.resend.com/emails", {
712
+ method: "POST",
713
+ headers: {
714
+ "Authorization": `Bearer ${RESEND_KEY}`,
715
+ "Content-Type": "application/json",
716
+ },
717
+ body: JSON.stringify({
718
+ from: "APIClaw <noreply@apiclaw.nordsym.com>",
719
+ to: email.toLowerCase(),
720
+ subject: "🦞 Verify Your Email — APIClaw",
721
+ html: html,
722
+ }),
723
+ });
724
+ if (!emailResponse.ok) {
725
+ const errorText = await emailResponse.text();
726
+ console.error("Resend error:", emailResponse.status, errorText);
727
+ return jsonResponse({ error: "Failed to send email", details: errorText }, 500);
728
+ }
729
+ const emailResult = await emailResponse.json();
730
+ console.log("Email sent successfully:", emailResult.id);
731
+ return jsonResponse({
732
+ success: true,
733
+ token: result.token,
734
+ expiresAt: result.expiresAt,
735
+ message: "Magic link sent! Check your email.",
736
+ emailId: emailResult.id,
737
+ });
738
+ }
739
+ catch (e) {
740
+ console.error("Magic link error:", e);
741
+ return jsonResponse({ error: e.message || "Failed to create magic link" }, 500);
742
+ }
743
+ }),
744
+ });
745
+ http.route({
746
+ path: "/workspace/magic-link",
747
+ method: "OPTIONS",
748
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
749
+ });
750
+ // Poll magic link status (for agents to check if user clicked)
751
+ http.route({
752
+ path: "/workspace/poll",
753
+ method: "GET",
754
+ handler: httpAction(async (ctx, request) => {
755
+ const url = new URL(request.url);
756
+ const token = url.searchParams.get("token");
757
+ if (!token) {
758
+ return jsonResponse({ error: "token required" }, 400);
759
+ }
760
+ const result = await ctx.runQuery(api.workspaces.pollMagicLink, { token });
761
+ return jsonResponse(result);
762
+ }),
763
+ });
764
+ http.route({
765
+ path: "/workspace/poll",
766
+ method: "OPTIONS",
767
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
768
+ });
769
+ // Verify session token
770
+ http.route({
771
+ path: "/workspace/verify-session",
772
+ method: "GET",
773
+ handler: httpAction(async (ctx, request) => {
774
+ const url = new URL(request.url);
775
+ const sessionToken = url.searchParams.get("sessionToken");
776
+ if (!sessionToken) {
777
+ return jsonResponse({ error: "sessionToken required" }, 400);
778
+ }
779
+ const result = await ctx.runQuery(api.workspaces.verifySession, { sessionToken });
780
+ if (!result) {
781
+ return jsonResponse({ error: "Invalid or expired session" }, 401);
782
+ }
783
+ return jsonResponse(result);
784
+ }),
785
+ });
786
+ http.route({
787
+ path: "/workspace/verify-session",
788
+ method: "OPTIONS",
789
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
790
+ });
791
+ // Get workspace by email
792
+ http.route({
793
+ path: "/workspace/by-email",
794
+ method: "GET",
795
+ handler: httpAction(async (ctx, request) => {
796
+ const url = new URL(request.url);
797
+ const email = url.searchParams.get("email");
798
+ if (!email) {
799
+ return jsonResponse({ error: "email required" }, 400);
800
+ }
801
+ const result = await ctx.runQuery(api.workspaces.getByEmail, { email });
802
+ if (!result) {
803
+ return jsonResponse({ exists: false });
804
+ }
805
+ return jsonResponse({ exists: true, workspace: result });
806
+ }),
807
+ });
808
+ http.route({
809
+ path: "/workspace/by-email",
810
+ method: "OPTIONS",
811
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
812
+ });
813
+ // Send reminder email
814
+ http.route({
815
+ path: "/workspace/send-reminder",
816
+ method: "POST",
817
+ handler: httpAction(async (ctx, request) => {
818
+ try {
819
+ const body = await request.json();
820
+ const { email, token } = body;
821
+ if (!email || !token) {
822
+ return jsonResponse({ error: "email and token required" }, 400);
823
+ }
824
+ await ctx.runAction(api.email.sendReminderEmail, { email, token });
825
+ return jsonResponse({ success: true });
826
+ }
827
+ catch (e) {
828
+ return jsonResponse({ error: e.message }, 500);
829
+ }
830
+ }),
831
+ });
832
+ http.route({
833
+ path: "/workspace/send-reminder",
834
+ method: "OPTIONS",
835
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
836
+ });
837
+ // ==============================================
838
+ // STRIPE BILLING ENDPOINTS
839
+ // ==============================================
840
+ // Create checkout session
841
+ http.route({
842
+ path: "/api/billing/checkout",
843
+ method: "POST",
844
+ handler: createCheckoutSession,
845
+ });
846
+ http.route({
847
+ path: "/api/billing/checkout",
848
+ method: "OPTIONS",
849
+ handler: checkoutOptions,
850
+ });
851
+ // Create billing portal session
852
+ http.route({
853
+ path: "/api/billing/portal",
854
+ method: "POST",
855
+ handler: createPortalSession,
856
+ });
857
+ http.route({
858
+ path: "/api/billing/portal",
859
+ method: "OPTIONS",
860
+ handler: portalOptions,
861
+ });
862
+ // Stripe webhook handler
863
+ http.route({
864
+ path: "/api/webhooks/stripe",
865
+ method: "POST",
866
+ handler: handleStripeWebhook,
867
+ });
868
+ http.route({
869
+ path: "/api/webhooks/stripe",
870
+ method: "OPTIONS",
871
+ handler: webhookOptions,
872
+ });
873
+ // Test endpoint to debug logging
874
+ http.route({
875
+ path: "/proxy/test-logging",
876
+ method: "POST",
877
+ handler: httpAction(async (ctx, request) => {
878
+ const identifier = request.headers.get("X-APIClaw-Identifier");
879
+ try {
880
+ const logId = await ctx.runMutation(api.analytics.log, {
881
+ event: "test_endpoint",
882
+ provider: "test",
883
+ identifier: identifier || "test",
884
+ metadata: { test: true },
885
+ });
886
+ return jsonResponse({
887
+ success: true,
888
+ identifier,
889
+ logId,
890
+ message: "Logged successfully"
891
+ });
892
+ }
893
+ catch (e) {
894
+ return jsonResponse({
895
+ success: false,
896
+ error: e.message,
897
+ stack: e.stack
898
+ }, 500);
899
+ }
900
+ }),
901
+ });
902
+ //# sourceMappingURL=http.js.map