@nordsym/apiclaw 1.7.3 → 1.7.5

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 (219) hide show
  1. package/convex/_generated/api.d.ts +115 -0
  2. package/convex/_generated/api.js +23 -0
  3. package/convex/_generated/dataModel.d.ts +60 -0
  4. package/convex/_generated/server.d.ts +143 -0
  5. package/convex/_generated/server.js +93 -0
  6. package/convex/adminActivate.d.ts +3 -0
  7. package/convex/adminActivate.d.ts.map +1 -0
  8. package/convex/adminActivate.js +47 -0
  9. package/convex/adminActivate.js.map +1 -0
  10. package/convex/adminActivate.ts +54 -0
  11. package/convex/adminStats.d.ts +3 -0
  12. package/convex/adminStats.d.ts.map +1 -0
  13. package/convex/adminStats.js +42 -0
  14. package/convex/adminStats.js.map +1 -0
  15. package/convex/adminStats.ts +44 -0
  16. package/convex/agents.d.ts +76 -0
  17. package/convex/agents.d.ts.map +1 -0
  18. package/convex/agents.js +699 -0
  19. package/convex/agents.js.map +1 -0
  20. package/convex/agents.ts +814 -0
  21. package/convex/analytics.d.ts +5 -0
  22. package/convex/analytics.d.ts.map +1 -0
  23. package/convex/analytics.js +166 -0
  24. package/convex/analytics.js.map +1 -0
  25. package/convex/analytics.ts +186 -0
  26. package/convex/billing.d.ts +88 -0
  27. package/convex/billing.d.ts.map +1 -0
  28. package/convex/billing.js +655 -0
  29. package/convex/billing.js.map +1 -0
  30. package/convex/billing.ts +791 -0
  31. package/convex/capabilities.d.ts +9 -0
  32. package/convex/capabilities.d.ts.map +1 -0
  33. package/convex/capabilities.js +145 -0
  34. package/convex/capabilities.js.map +1 -0
  35. package/convex/capabilities.ts +157 -0
  36. package/convex/chains.d.ts +68 -0
  37. package/convex/chains.d.ts.map +1 -0
  38. package/convex/chains.js +1105 -0
  39. package/convex/chains.js.map +1 -0
  40. package/convex/chains.ts +1318 -0
  41. package/convex/credits.d.ts +25 -0
  42. package/convex/credits.d.ts.map +1 -0
  43. package/convex/credits.js +186 -0
  44. package/convex/credits.js.map +1 -0
  45. package/convex/credits.ts +211 -0
  46. package/convex/crons.d.ts +3 -0
  47. package/convex/crons.d.ts.map +1 -0
  48. package/convex/crons.js +17 -0
  49. package/convex/crons.js.map +1 -0
  50. package/convex/crons.ts +28 -0
  51. package/convex/directCall.d.ts +72 -0
  52. package/convex/directCall.d.ts.map +1 -0
  53. package/convex/directCall.js +627 -0
  54. package/convex/directCall.js.map +1 -0
  55. package/convex/directCall.ts +678 -0
  56. package/convex/earnProgress.d.ts +58 -0
  57. package/convex/earnProgress.d.ts.map +1 -0
  58. package/convex/earnProgress.js +649 -0
  59. package/convex/earnProgress.js.map +1 -0
  60. package/convex/earnProgress.ts +753 -0
  61. package/convex/email.d.ts +14 -0
  62. package/convex/email.d.ts.map +1 -0
  63. package/convex/email.js +300 -0
  64. package/convex/email.js.map +1 -0
  65. package/convex/email.ts +329 -0
  66. package/convex/feedback.d.ts +7 -0
  67. package/convex/feedback.d.ts.map +1 -0
  68. package/convex/feedback.js +227 -0
  69. package/convex/feedback.js.map +1 -0
  70. package/convex/feedback.ts +265 -0
  71. package/convex/http.d.ts +3 -0
  72. package/convex/http.d.ts.map +1 -0
  73. package/convex/http.js +1405 -0
  74. package/convex/http.js.map +1 -0
  75. package/convex/http.ts +1577 -0
  76. package/convex/inbound.d.ts +2 -0
  77. package/convex/inbound.d.ts.map +1 -0
  78. package/convex/inbound.js +32 -0
  79. package/convex/inbound.js.map +1 -0
  80. package/convex/inbound.ts +32 -0
  81. package/convex/logs.d.ts +48 -0
  82. package/convex/logs.d.ts.map +1 -0
  83. package/convex/logs.js +592 -0
  84. package/convex/logs.js.map +1 -0
  85. package/convex/logs.ts +662 -0
  86. package/convex/mou.d.ts +6 -0
  87. package/convex/mou.d.ts.map +1 -0
  88. package/convex/mou.js +82 -0
  89. package/convex/mou.js.map +1 -0
  90. package/convex/mou.ts +91 -0
  91. package/convex/providerKeys.d.ts +31 -0
  92. package/convex/providerKeys.d.ts.map +1 -0
  93. package/convex/providerKeys.js +257 -0
  94. package/convex/providerKeys.js.map +1 -0
  95. package/convex/providerKeys.ts +289 -0
  96. package/convex/providers.d.ts +32 -0
  97. package/convex/providers.d.ts.map +1 -0
  98. package/convex/providers.js +814 -0
  99. package/convex/providers.js.map +1 -0
  100. package/convex/providers.ts +909 -0
  101. package/convex/purchases.d.ts +7 -0
  102. package/convex/purchases.d.ts.map +1 -0
  103. package/convex/purchases.js +157 -0
  104. package/convex/purchases.js.map +1 -0
  105. package/convex/purchases.ts +183 -0
  106. package/convex/ratelimit.d.ts +4 -0
  107. package/convex/ratelimit.d.ts.map +1 -0
  108. package/convex/ratelimit.js +91 -0
  109. package/convex/ratelimit.js.map +1 -0
  110. package/convex/ratelimit.ts +104 -0
  111. package/convex/schema.ts +805 -0
  112. package/convex/searchLogs.d.ts +4 -0
  113. package/convex/searchLogs.d.ts.map +1 -0
  114. package/convex/searchLogs.js +129 -0
  115. package/convex/searchLogs.js.map +1 -0
  116. package/convex/searchLogs.ts +146 -0
  117. package/convex/seedAPILayerAPIs.d.ts +7 -0
  118. package/convex/seedAPILayerAPIs.d.ts.map +1 -0
  119. package/convex/seedAPILayerAPIs.js +177 -0
  120. package/convex/seedAPILayerAPIs.js.map +1 -0
  121. package/convex/seedAPILayerAPIs.ts +191 -0
  122. package/convex/seedDirectCallConfigs.d.ts +2 -0
  123. package/convex/seedDirectCallConfigs.d.ts.map +1 -0
  124. package/convex/seedDirectCallConfigs.js +324 -0
  125. package/convex/seedDirectCallConfigs.js.map +1 -0
  126. package/convex/seedDirectCallConfigs.ts +336 -0
  127. package/convex/seedPratham.d.ts +6 -0
  128. package/convex/seedPratham.d.ts.map +1 -0
  129. package/convex/seedPratham.js +150 -0
  130. package/convex/seedPratham.js.map +1 -0
  131. package/convex/seedPratham.ts +161 -0
  132. package/convex/spendAlerts.d.ts +36 -0
  133. package/convex/spendAlerts.d.ts.map +1 -0
  134. package/convex/spendAlerts.js +380 -0
  135. package/convex/spendAlerts.js.map +1 -0
  136. package/convex/spendAlerts.ts +442 -0
  137. package/convex/stripeActions.d.ts +19 -0
  138. package/convex/stripeActions.d.ts.map +1 -0
  139. package/convex/stripeActions.js +411 -0
  140. package/convex/stripeActions.js.map +1 -0
  141. package/convex/stripeActions.ts +512 -0
  142. package/convex/teams.d.ts +21 -0
  143. package/convex/teams.d.ts.map +1 -0
  144. package/convex/teams.js +215 -0
  145. package/convex/teams.js.map +1 -0
  146. package/convex/teams.ts +243 -0
  147. package/convex/telemetry.d.ts +4 -0
  148. package/convex/telemetry.d.ts.map +1 -0
  149. package/convex/telemetry.js +74 -0
  150. package/convex/telemetry.js.map +1 -0
  151. package/convex/telemetry.ts +81 -0
  152. package/convex/tsconfig.json +25 -0
  153. package/convex/updateAPIStatus.d.ts +6 -0
  154. package/convex/updateAPIStatus.d.ts.map +1 -0
  155. package/convex/updateAPIStatus.js +40 -0
  156. package/convex/updateAPIStatus.js.map +1 -0
  157. package/convex/updateAPIStatus.ts +45 -0
  158. package/convex/usage.d.ts +27 -0
  159. package/convex/usage.d.ts.map +1 -0
  160. package/convex/usage.js +229 -0
  161. package/convex/usage.js.map +1 -0
  162. package/convex/usage.ts +260 -0
  163. package/convex/waitlist.d.ts +4 -0
  164. package/convex/waitlist.d.ts.map +1 -0
  165. package/convex/waitlist.js +49 -0
  166. package/convex/waitlist.js.map +1 -0
  167. package/convex/waitlist.ts +55 -0
  168. package/convex/webhooks.d.ts +12 -0
  169. package/convex/webhooks.d.ts.map +1 -0
  170. package/convex/webhooks.js +410 -0
  171. package/convex/webhooks.js.map +1 -0
  172. package/convex/webhooks.ts +494 -0
  173. package/convex/workspaces.d.ts +31 -0
  174. package/convex/workspaces.d.ts.map +1 -0
  175. package/convex/workspaces.js +975 -0
  176. package/convex/workspaces.js.map +1 -0
  177. package/convex/workspaces.ts +1130 -0
  178. package/dist/bin.js +0 -0
  179. package/dist/index.js +9 -0
  180. package/dist/index.js.map +1 -1
  181. package/package.json +1 -1
  182. package/src/index.ts +10 -0
  183. package/dist/chain-types.d.ts +0 -187
  184. package/dist/chain-types.d.ts.map +0 -1
  185. package/dist/chain-types.js +0 -33
  186. package/dist/chain-types.js.map +0 -1
  187. package/dist/registry/apis.json.bak +0 -248811
  188. package/dist/src/bin.js +0 -17
  189. package/dist/src/capability-router.js +0 -240
  190. package/dist/src/chainExecutor.js +0 -451
  191. package/dist/src/chainResolver.js +0 -518
  192. package/dist/src/cli/commands/doctor.js +0 -324
  193. package/dist/src/cli/commands/mcp-install.js +0 -255
  194. package/dist/src/cli/commands/restore.js +0 -259
  195. package/dist/src/cli/commands/setup.js +0 -205
  196. package/dist/src/cli/commands/uninstall.js +0 -188
  197. package/dist/src/cli/index.js +0 -111
  198. package/dist/src/cli.js +0 -302
  199. package/dist/src/confirmation.js +0 -240
  200. package/dist/src/credentials.js +0 -357
  201. package/dist/src/credits.js +0 -260
  202. package/dist/src/crypto.js +0 -66
  203. package/dist/src/discovery.js +0 -504
  204. package/dist/src/enterprise/env.js +0 -123
  205. package/dist/src/enterprise/script-generator.js +0 -460
  206. package/dist/src/execute-dynamic.js +0 -473
  207. package/dist/src/execute.js +0 -1727
  208. package/dist/src/index.js +0 -2062
  209. package/dist/src/metered.js +0 -80
  210. package/dist/src/open-apis.js +0 -276
  211. package/dist/src/proxy.js +0 -28
  212. package/dist/src/session.js +0 -86
  213. package/dist/src/stripe.js +0 -407
  214. package/dist/src/telemetry.js +0 -49
  215. package/dist/src/types.js +0 -2
  216. package/dist/src/utils/backup.js +0 -181
  217. package/dist/src/utils/config.js +0 -220
  218. package/dist/src/utils/os.js +0 -105
  219. package/dist/src/utils/paths.js +0 -159
package/convex/http.ts ADDED
@@ -0,0 +1,1577 @@
1
+ import { httpRouter } from "convex/server";
2
+ import { httpAction } from "./_generated/server";
3
+ import { api, internal } from "./_generated/api";
4
+ import {
5
+ createCheckoutSession,
6
+ createPortalSession,
7
+ handleStripeWebhook,
8
+ checkoutOptions,
9
+ portalOptions,
10
+ webhookOptions,
11
+ } from "./stripeActions";
12
+
13
+ const http = httpRouter();
14
+
15
+ // Provider catalog
16
+ const PROVIDERS = {
17
+ "46elks": {
18
+ name: "46elks",
19
+ description: "SMS API for EU/Nordics. GDPR compliant.",
20
+ category: "sms",
21
+ pricing: "~$0.035/SMS",
22
+ regions: ["EU", "Nordic"],
23
+ tags: ["sms", "eu", "gdpr", "nordic"],
24
+ },
25
+ twilio: {
26
+ name: "Twilio",
27
+ description: "SMS and Voice API. Global coverage.",
28
+ category: "sms",
29
+ pricing: "~$0.04/SMS, ~$0.01/min voice",
30
+ regions: ["Global"],
31
+ tags: ["sms", "voice", "global"],
32
+ },
33
+ resend: {
34
+ name: "Resend",
35
+ description: "Modern email API. Developer-friendly.",
36
+ category: "email",
37
+ pricing: "~$0.001/email",
38
+ regions: ["Global"],
39
+ tags: ["email", "transactional"],
40
+ },
41
+ brave_search: {
42
+ name: "Brave Search",
43
+ description: "Privacy-focused web search API.",
44
+ category: "search",
45
+ pricing: "~$0.005/search",
46
+ regions: ["Global"],
47
+ tags: ["search", "web", "privacy"],
48
+ },
49
+ openrouter: {
50
+ name: "OpenRouter",
51
+ description: "Multi-model LLM API. Access GPT, Claude, Llama, etc.",
52
+ category: "llm",
53
+ pricing: "Varies by model",
54
+ regions: ["Global"],
55
+ tags: ["llm", "ai", "gpt", "claude"],
56
+ },
57
+ elevenlabs: {
58
+ name: "ElevenLabs",
59
+ description: "Text-to-speech API. High quality voices.",
60
+ category: "tts",
61
+ pricing: "~$0.0003/char",
62
+ regions: ["Global"],
63
+ tags: ["tts", "voice", "audio"],
64
+ },
65
+ replicate: {
66
+ name: "Replicate",
67
+ description: "Run AI models (Whisper, SDXL, Llama, etc). Pay per prediction.",
68
+ category: "ai",
69
+ pricing: "Varies by model",
70
+ regions: ["Global"],
71
+ tags: ["ai", "ml", "whisper", "image", "audio", "transcription"],
72
+ },
73
+ firecrawl: {
74
+ name: "Firecrawl",
75
+ description: "Web scraping and crawling API. Extract clean data from any URL.",
76
+ category: "scraping",
77
+ pricing: "~$0.001/page",
78
+ regions: ["Global"],
79
+ tags: ["scraping", "web", "crawl", "extract"],
80
+ },
81
+ github: {
82
+ name: "GitHub",
83
+ description: "GitHub API. Search repos, manage code, access developer data.",
84
+ category: "code",
85
+ pricing: "Free tier available",
86
+ regions: ["Global"],
87
+ tags: ["github", "code", "repos", "developer"],
88
+ },
89
+ e2b: {
90
+ name: "E2B",
91
+ description: "Secure code sandbox for AI agents. Run Python, shell commands in isolated environments.",
92
+ category: "sandbox",
93
+ pricing: "$0.000028/s (2 vCPU)",
94
+ regions: ["Global"],
95
+ tags: ["sandbox", "code", "python", "execution", "ai", "agents"],
96
+ },
97
+ apilayer: {
98
+ name: "APILayer",
99
+ description: "14 APIs: exchange rates, market data, aviation, PDF, screenshots, email/phone verification, VAT, news, scraping, and more.",
100
+ category: "multi",
101
+ pricing: "Free tier available, paid plans per API",
102
+ regions: ["Global"],
103
+ tags: ["exchange", "stocks", "aviation", "pdf", "screenshot", "verification", "vat", "news", "scraping"],
104
+ },
105
+ } as const;
106
+
107
+ // CORS headers
108
+ const corsHeaders = {
109
+ "Access-Control-Allow-Origin": "*",
110
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
111
+ "Access-Control-Allow-Headers": "Content-Type, Authorization",
112
+ };
113
+
114
+ // Helper for JSON responses
115
+ function jsonResponse(data: unknown, status = 200) {
116
+ return new Response(JSON.stringify(data), {
117
+ status,
118
+ headers: { "Content-Type": "application/json", ...corsHeaders },
119
+ });
120
+ }
121
+
122
+ // Helper to validate session and log API usage
123
+ async function validateAndLogProxyCall(
124
+ ctx: any,
125
+ request: Request,
126
+ provider: string,
127
+ action: string
128
+ ): Promise<{ valid: boolean; workspaceId?: string; subagentId?: string; error?: string }> {
129
+ const identifier = request.headers.get("X-APIClaw-Identifier");
130
+ const subagentId = request.headers.get("X-APIClaw-Subagent") || "main";
131
+
132
+ console.log("[Proxy] Call received", { provider, action, identifier, subagentId });
133
+
134
+ // ALWAYS log to analytics (even if identifier is missing)
135
+ try {
136
+ const result = await ctx.runMutation(api.analytics.log, {
137
+ event: "api_call",
138
+ provider,
139
+ identifier: identifier || "unknown",
140
+ metadata: { action, subagentId },
141
+ });
142
+ console.log("[Proxy] Analytics logged:", result);
143
+ } catch (e: any) {
144
+ console.error("[Proxy] Analytics logging failed:", e.message, e.stack);
145
+ // Continue even if analytics fails
146
+ }
147
+
148
+ // If we have an identifier and it's a workspace ID (not anon:), log to workspace
149
+ if (identifier && !identifier.startsWith("anon:") && identifier !== "unknown") {
150
+ try {
151
+ // Validate it's actually a workspace ID by checking format
152
+ if (identifier.length > 20) {
153
+ await ctx.runMutation(api.logs.createProxyLog, {
154
+ workspaceId: identifier as any,
155
+ provider,
156
+ action,
157
+ subagentId,
158
+ });
159
+
160
+ // Increment workspace usage
161
+ await ctx.runMutation(api.workspaces.incrementUsage, {
162
+ workspaceId: identifier as any,
163
+ });
164
+
165
+ console.log("[Proxy] Workspace logged for:", identifier);
166
+ return { valid: true, workspaceId: identifier, subagentId };
167
+ }
168
+ } catch (e: any) {
169
+ console.error("[Proxy] Workspace logging failed:", e.message);
170
+ // Continue even if workspace logging fails
171
+ }
172
+ }
173
+
174
+ // Return success regardless (don't block API calls)
175
+ return { valid: true, subagentId };
176
+ }
177
+
178
+ // OPTIONS handler for CORS
179
+ http.route({
180
+ path: "/api/discover",
181
+ method: "OPTIONS",
182
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
183
+ });
184
+
185
+ http.route({
186
+ path: "/api/details",
187
+ method: "OPTIONS",
188
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
189
+ });
190
+
191
+ http.route({
192
+ path: "/api/balance",
193
+ method: "OPTIONS",
194
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
195
+ });
196
+
197
+ http.route({
198
+ path: "/api/purchase",
199
+ method: "OPTIONS",
200
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
201
+ });
202
+
203
+ http.route({
204
+ path: "/admin/grant-credits",
205
+ method: "OPTIONS",
206
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
207
+ });
208
+
209
+ // Discover APIs
210
+ http.route({
211
+ path: "/api/discover",
212
+ method: "POST",
213
+ handler: httpAction(async (ctx, request) => {
214
+ try {
215
+ const startTime = Date.now();
216
+ const body = await request.json();
217
+ const query = (body.query || "").toLowerCase();
218
+
219
+ // Get optional auth context
220
+ const sessionToken = request.headers.get("X-APIClaw-Session");
221
+ const userAgent = request.headers.get("User-Agent");
222
+
223
+ const results = Object.entries(PROVIDERS)
224
+ .filter(([id, provider]) => {
225
+ if (!query) return true;
226
+ return (
227
+ provider.name.toLowerCase().includes(query) ||
228
+ provider.description.toLowerCase().includes(query) ||
229
+ provider.category.toLowerCase().includes(query) ||
230
+ provider.tags.some((tag) => tag.includes(query))
231
+ );
232
+ })
233
+ .map(([id, provider]) => ({
234
+ providerId: id,
235
+ ...provider,
236
+ }));
237
+
238
+ const responseTimeMs = Date.now() - startTime;
239
+
240
+ // Log the search (fire and forget)
241
+ if (query) {
242
+ ctx.runMutation(internal.searchLogs.logSearch, {
243
+ query: body.query || "", // Original query (not lowercased)
244
+ resultsCount: results.length,
245
+ matchedProviders: results.map(r => r.providerId),
246
+ sessionToken: sessionToken || undefined,
247
+ userAgent: userAgent || undefined,
248
+ responseTimeMs,
249
+ }).catch(() => {}); // Ignore errors, don't block response
250
+ }
251
+
252
+ return jsonResponse({ providers: results, total: results.length });
253
+ } catch (e) {
254
+ return jsonResponse({ error: "Invalid request" }, 400);
255
+ }
256
+ }),
257
+ });
258
+
259
+ // Get provider details
260
+ http.route({
261
+ path: "/api/details",
262
+ method: "POST",
263
+ handler: httpAction(async (ctx, request) => {
264
+ try {
265
+ const body = await request.json();
266
+ const { providerId } = body;
267
+
268
+ if (!providerId) {
269
+ return jsonResponse({ error: "providerId required" }, 400);
270
+ }
271
+
272
+ const provider = PROVIDERS[providerId as keyof typeof PROVIDERS];
273
+ if (!provider) {
274
+ return jsonResponse({ error: "Provider not found" }, 404);
275
+ }
276
+
277
+ return jsonResponse({
278
+ providerId,
279
+ ...provider,
280
+ creditsPerDollar: getCreditsPerDollar(providerId),
281
+ documentation: `https://apiclaw.com/docs/${providerId}`,
282
+ });
283
+ } catch (e) {
284
+ return jsonResponse({ error: "Invalid request" }, 400);
285
+ }
286
+ }),
287
+ });
288
+
289
+ // Check balance
290
+ http.route({
291
+ path: "/api/balance",
292
+ method: "GET",
293
+ handler: httpAction(async (ctx, request) => {
294
+ const url = new URL(request.url);
295
+ const agentId = url.searchParams.get("agentId");
296
+
297
+ if (!agentId) {
298
+ return jsonResponse({ error: "agentId required" }, 400);
299
+ }
300
+
301
+ const credits = await ctx.runQuery(api.credits.getAgentCredits, { agentId });
302
+
303
+ if (!credits) {
304
+ return jsonResponse({
305
+ agentId,
306
+ balanceUsd: 0,
307
+ currency: "USD",
308
+ message: "No account found. Top up to get started!",
309
+ });
310
+ }
311
+
312
+ return jsonResponse({
313
+ agentId: credits.agentId,
314
+ balanceUsd: credits.balanceUsd,
315
+ currency: credits.currency,
316
+ });
317
+ }),
318
+ });
319
+
320
+ // Purchase API access
321
+ http.route({
322
+ path: "/api/purchase",
323
+ method: "POST",
324
+ handler: httpAction(async (ctx, request) => {
325
+ try {
326
+ const body = await request.json();
327
+ const { agentId, providerId, amountUsd } = body;
328
+
329
+ if (!agentId || !providerId || !amountUsd) {
330
+ return jsonResponse(
331
+ { error: "agentId, providerId, and amountUsd required" },
332
+ 400
333
+ );
334
+ }
335
+
336
+ if (amountUsd < 1 || amountUsd > 1000) {
337
+ return jsonResponse(
338
+ { error: "amountUsd must be between 1 and 1000" },
339
+ 400
340
+ );
341
+ }
342
+
343
+ const provider = PROVIDERS[providerId as keyof typeof PROVIDERS];
344
+ if (!provider) {
345
+ return jsonResponse({ error: "Provider not found" }, 404);
346
+ }
347
+
348
+ // Check balance first
349
+ const credits = await ctx.runQuery(api.credits.getAgentCredits, { agentId });
350
+ if (!credits || credits.balanceUsd < amountUsd) {
351
+ return jsonResponse(
352
+ {
353
+ error: "Insufficient balance",
354
+ currentBalance: credits?.balanceUsd || 0,
355
+ required: amountUsd,
356
+ },
357
+ 402
358
+ );
359
+ }
360
+
361
+ // Execute purchase
362
+ const purchase = await ctx.runMutation(api.purchases.purchaseAccess, {
363
+ agentId,
364
+ providerId,
365
+ amountUsd,
366
+ credentials: generateCredentials(providerId),
367
+ });
368
+
369
+ if (!purchase) {
370
+ return jsonResponse({ error: "Purchase failed" }, 500);
371
+ }
372
+
373
+ return jsonResponse({
374
+ success: true,
375
+ purchase: {
376
+ id: purchase._id,
377
+ providerId: purchase.providerId,
378
+ amountUsd: purchase.amountUsd,
379
+ creditsGranted: purchase.creditsGranted,
380
+ status: purchase.status,
381
+ },
382
+ message: `Successfully purchased $${amountUsd} of ${provider.name} credits`,
383
+ });
384
+ } catch (e: any) {
385
+ return jsonResponse({ error: e.message || "Purchase failed" }, 400);
386
+ }
387
+ }),
388
+ });
389
+
390
+ // Admin: Grant credits
391
+ http.route({
392
+ path: "/admin/grant-credits",
393
+ method: "POST",
394
+ handler: httpAction(async (ctx, request) => {
395
+ try {
396
+ const body = await request.json();
397
+ const { agentId, amount, reason } = body;
398
+
399
+ if (!agentId || !amount) {
400
+ return jsonResponse({ error: "agentId and amount required" }, 400);
401
+ }
402
+
403
+ // TODO: Add admin auth check here
404
+ // For now, allow grants (this is for Hivr integration)
405
+
406
+ const result = await ctx.runMutation(api.credits.addCredits, {
407
+ agentId,
408
+ amountUsd: amount,
409
+ source: reason || "admin_grant",
410
+ });
411
+
412
+ return jsonResponse({
413
+ success: true,
414
+ agentId,
415
+ credited: amount,
416
+ newBalance: result?.balanceUsd,
417
+ reason,
418
+ });
419
+ } catch (e: any) {
420
+ return jsonResponse({ error: e.message || "Grant failed" }, 400);
421
+ }
422
+ }),
423
+ });
424
+
425
+ // Helper functions
426
+ function getCreditsPerDollar(providerId: string): number {
427
+ const rates: Record<string, number> = {
428
+ "46elks": 30,
429
+ twilio: 25,
430
+ resend: 1000,
431
+ brave_search: 200,
432
+ openrouter: 100,
433
+ elevenlabs: 3333,
434
+ };
435
+ return rates[providerId] || 100;
436
+ }
437
+
438
+ function generateCredentials(providerId: string): object {
439
+ // In production, this would generate or retrieve actual API keys
440
+ // For now, return placeholder indicating how to use
441
+ return {
442
+ type: "apiclaw_proxy",
443
+ endpoint: `https://brilliant-puffin-712.convex.site/proxy/${providerId}`,
444
+ note: "Use APIClaw proxy endpoint. Credentials managed automatically.",
445
+ };
446
+ }
447
+
448
+ export default http;
449
+
450
+ // ==============================================
451
+ // DIRECT CALL PROXY ENDPOINTS
452
+ // ==============================================
453
+
454
+ // OpenRouter proxy
455
+ http.route({
456
+ path: "/proxy/openrouter",
457
+ method: "POST",
458
+ handler: httpAction(async (ctx, request) => {
459
+ // Validate session and log usage
460
+ await validateAndLogProxyCall(ctx, request, "openrouter", "chat");
461
+
462
+ const OPENROUTER_KEY = process.env.OPENROUTER_API_KEY;
463
+ if (!OPENROUTER_KEY) {
464
+ return jsonResponse({ error: "OpenRouter not configured" }, 500);
465
+ }
466
+
467
+ try {
468
+ const body = await request.json();
469
+
470
+ const response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
471
+ method: "POST",
472
+ headers: {
473
+ "Authorization": `Bearer ${OPENROUTER_KEY}`,
474
+ "Content-Type": "application/json",
475
+ "HTTP-Referer": "https://apiclaw.nordsym.com",
476
+ "X-Title": "APIClaw",
477
+ },
478
+ body: JSON.stringify(body),
479
+ });
480
+
481
+ const data = await response.json();
482
+ return jsonResponse(data, response.status);
483
+ } catch (e: any) {
484
+ return jsonResponse({ error: e.message }, 500);
485
+ }
486
+ }),
487
+ });
488
+
489
+ // Brave Search proxy
490
+ http.route({
491
+ path: "/proxy/brave_search",
492
+ method: "POST",
493
+ handler: httpAction(async (ctx, request) => {
494
+ // Validate session and log usage
495
+ await validateAndLogProxyCall(ctx, request, "brave_search", "search");
496
+
497
+ const BRAVE_KEY = process.env.BRAVE_API_KEY;
498
+ if (!BRAVE_KEY) {
499
+ return jsonResponse({ error: "Brave Search not configured" }, 500);
500
+ }
501
+
502
+ try {
503
+ const body = await request.json();
504
+ const { query, count = 10 } = body;
505
+
506
+ const url = new URL("https://api.search.brave.com/res/v1/web/search");
507
+ url.searchParams.set("q", query);
508
+ url.searchParams.set("count", String(count));
509
+
510
+ const response = await fetch(url.toString(), {
511
+ headers: { "X-Subscription-Token": BRAVE_KEY },
512
+ });
513
+
514
+ const data = await response.json();
515
+ return jsonResponse(data, response.status);
516
+ } catch (e: any) {
517
+ return jsonResponse({ error: e.message }, 500);
518
+ }
519
+ }),
520
+ });
521
+
522
+ // Resend email proxy
523
+ http.route({
524
+ path: "/proxy/resend",
525
+ method: "POST",
526
+ handler: httpAction(async (ctx, request) => {
527
+ // Validate session and log usage
528
+ await validateAndLogProxyCall(ctx, request, "resend", "send_email");
529
+
530
+ const RESEND_KEY = process.env.RESEND_API_KEY;
531
+ if (!RESEND_KEY) {
532
+ return jsonResponse({ error: "Resend not configured" }, 500);
533
+ }
534
+
535
+ try {
536
+ const body = await request.json();
537
+
538
+ const response = await fetch("https://api.resend.com/emails", {
539
+ method: "POST",
540
+ headers: {
541
+ "Authorization": `Bearer ${RESEND_KEY}`,
542
+ "Content-Type": "application/json",
543
+ },
544
+ body: JSON.stringify(body),
545
+ });
546
+
547
+ const data = await response.json();
548
+ return jsonResponse(data, response.status);
549
+ } catch (e: any) {
550
+ return jsonResponse({ error: e.message }, 500);
551
+ }
552
+ }),
553
+ });
554
+
555
+ // ElevenLabs TTS proxy
556
+ http.route({
557
+ path: "/proxy/elevenlabs",
558
+ method: "POST",
559
+ handler: httpAction(async (ctx, request) => {
560
+ // Validate session and log usage
561
+ await validateAndLogProxyCall(ctx, request, "elevenlabs", "text_to_speech");
562
+
563
+ const ELEVENLABS_KEY = process.env.ELEVENLABS_API_KEY;
564
+ if (!ELEVENLABS_KEY) {
565
+ return jsonResponse({ error: "ElevenLabs not configured" }, 500);
566
+ }
567
+
568
+ try {
569
+ const body = await request.json();
570
+ const { text, voice_id = "21m00Tcm4TlvDq8ikWAM" } = body;
571
+
572
+ const response = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${voice_id}`, {
573
+ method: "POST",
574
+ headers: {
575
+ "xi-api-key": ELEVENLABS_KEY,
576
+ "Content-Type": "application/json",
577
+ },
578
+ body: JSON.stringify({
579
+ text,
580
+ model_id: "eleven_turbo_v2",
581
+ }),
582
+ });
583
+
584
+ if (!response.ok) {
585
+ const error = await response.text();
586
+ return jsonResponse({ error }, response.status);
587
+ }
588
+
589
+ // Return audio as base64
590
+ const arrayBuffer = await response.arrayBuffer();
591
+ const base64 = Buffer.from(arrayBuffer).toString("base64");
592
+
593
+ return jsonResponse({
594
+ audio_base64: base64,
595
+ content_type: "audio/mpeg",
596
+ });
597
+ } catch (e: any) {
598
+ return jsonResponse({ error: e.message }, 500);
599
+ }
600
+ }),
601
+ });
602
+
603
+ http.route({
604
+ path: "/proxy/openrouter",
605
+ method: "OPTIONS",
606
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
607
+ });
608
+
609
+ http.route({
610
+ path: "/proxy/brave_search",
611
+ method: "OPTIONS",
612
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
613
+ });
614
+
615
+ http.route({
616
+ path: "/proxy/resend",
617
+ method: "OPTIONS",
618
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
619
+ });
620
+
621
+ http.route({
622
+ path: "/proxy/elevenlabs",
623
+ method: "OPTIONS",
624
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
625
+ });
626
+
627
+ // 46elks SMS proxy
628
+ http.route({
629
+ path: "/proxy/46elks",
630
+ method: "POST",
631
+ handler: httpAction(async (ctx, request) => {
632
+ // Validate session and log usage
633
+ await validateAndLogProxyCall(ctx, request, "46elks", "send_sms");
634
+
635
+ const ELKS_USER = process.env.ELKS_API_USER;
636
+ const ELKS_PASS = process.env.ELKS_API_PASSWORD;
637
+ if (!ELKS_USER || !ELKS_PASS) {
638
+ return jsonResponse({ error: "46elks not configured" }, 500);
639
+ }
640
+
641
+ try {
642
+ const body = await request.json();
643
+ const { to, message, from = "APIClaw" } = body;
644
+
645
+ const auth = btoa(`${ELKS_USER}:${ELKS_PASS}`);
646
+
647
+ const response = await fetch("https://api.46elks.com/a1/sms", {
648
+ method: "POST",
649
+ headers: {
650
+ "Authorization": `Basic ${auth}`,
651
+ "Content-Type": "application/x-www-form-urlencoded",
652
+ },
653
+ body: new URLSearchParams({ from, to, message }),
654
+ });
655
+
656
+ const data = await response.json();
657
+ return jsonResponse(data, response.status);
658
+ } catch (e: any) {
659
+ return jsonResponse({ error: e.message }, 500);
660
+ }
661
+ }),
662
+ });
663
+
664
+ // Twilio SMS proxy
665
+ http.route({
666
+ path: "/proxy/twilio",
667
+ method: "POST",
668
+ handler: httpAction(async (ctx, request) => {
669
+ // Validate session and log usage
670
+ await validateAndLogProxyCall(ctx, request, "twilio", "send_sms");
671
+
672
+ const TWILIO_SID = process.env.TWILIO_ACCOUNT_SID;
673
+ const TWILIO_TOKEN = process.env.TWILIO_AUTH_TOKEN;
674
+ if (!TWILIO_SID || !TWILIO_TOKEN) {
675
+ return jsonResponse({ error: "Twilio not configured" }, 500);
676
+ }
677
+
678
+ try {
679
+ const body = await request.json();
680
+ const { to, message, from } = body;
681
+
682
+ if (!from) {
683
+ return jsonResponse({ error: "Twilio requires 'from' number" }, 400);
684
+ }
685
+
686
+ const auth = btoa(`${TWILIO_SID}:${TWILIO_TOKEN}`);
687
+
688
+ const response = await fetch(
689
+ `https://api.twilio.com/2010-04-01/Accounts/${TWILIO_SID}/Messages.json`,
690
+ {
691
+ method: "POST",
692
+ headers: {
693
+ "Authorization": `Basic ${auth}`,
694
+ "Content-Type": "application/x-www-form-urlencoded",
695
+ },
696
+ body: new URLSearchParams({ To: to, From: from, Body: message }),
697
+ }
698
+ );
699
+
700
+ const data = await response.json();
701
+ return jsonResponse(data, response.status);
702
+ } catch (e: any) {
703
+ return jsonResponse({ error: e.message }, 500);
704
+ }
705
+ }),
706
+ });
707
+
708
+ // CORS for new endpoints
709
+ http.route({
710
+ path: "/proxy/46elks",
711
+ method: "OPTIONS",
712
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
713
+ });
714
+
715
+ http.route({
716
+ path: "/proxy/twilio",
717
+ method: "OPTIONS",
718
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
719
+ });
720
+
721
+ // GitHub API proxy
722
+ http.route({
723
+ path: "/proxy/github",
724
+ method: "POST",
725
+ handler: httpAction(async (ctx, request) => {
726
+ // Validate session and log usage
727
+ const body = await request.json();
728
+ const action = body.action || "search_repos";
729
+ await validateAndLogProxyCall(ctx, request, "github", action);
730
+
731
+ const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
732
+ if (!GITHUB_TOKEN) {
733
+ return jsonResponse({ error: "GitHub not configured" }, 500);
734
+ }
735
+
736
+ try {
737
+ const { action, ...params } = body;
738
+ let url: string;
739
+ let method = "GET";
740
+ let fetchBody: string | undefined;
741
+
742
+ // Route based on action
743
+ switch (action) {
744
+ case "search_repos":
745
+ const { query, sort = "stars", limit = 10 } = params;
746
+ url = `https://api.github.com/search/repositories?q=${encodeURIComponent(query)}&sort=${sort}&per_page=${limit}`;
747
+ break;
748
+
749
+ case "get_repo":
750
+ const { owner, repo } = params;
751
+ url = `https://api.github.com/repos/${owner}/${repo}`;
752
+ break;
753
+
754
+ case "list_issues":
755
+ const { owner: issueOwner, repo: issueRepo, state = "open", limit: issueLimit = 10 } = params;
756
+ url = `https://api.github.com/repos/${issueOwner}/${issueRepo}/issues?state=${state}&per_page=${issueLimit}`;
757
+ break;
758
+
759
+ case "create_issue":
760
+ const { owner: createOwner, repo: createRepo, title, body: issueBody = "" } = params;
761
+ url = `https://api.github.com/repos/${createOwner}/${createRepo}/issues`;
762
+ method = "POST";
763
+ fetchBody = JSON.stringify({ title, body: issueBody });
764
+ break;
765
+
766
+ case "get_file":
767
+ const { owner: fileOwner, repo: fileRepo, path } = params;
768
+ url = `https://api.github.com/repos/${fileOwner}/${fileRepo}/contents/${path}`;
769
+ break;
770
+
771
+ default:
772
+ return jsonResponse({ error: `Unknown action: ${action}` }, 400);
773
+ }
774
+
775
+ const response = await fetch(url, {
776
+ method,
777
+ headers: {
778
+ "Authorization": `Bearer ${GITHUB_TOKEN}`,
779
+ "Accept": "application/vnd.github+json",
780
+ "User-Agent": "APIClaw",
781
+ ...(fetchBody ? { "Content-Type": "application/json" } : {}),
782
+ },
783
+ ...(fetchBody ? { body: fetchBody } : {}),
784
+ });
785
+
786
+ const data = await response.json();
787
+ return jsonResponse(data, response.status);
788
+ } catch (e: any) {
789
+ return jsonResponse({ error: e.message }, 500);
790
+ }
791
+ }),
792
+ });
793
+
794
+ http.route({
795
+ path: "/proxy/github",
796
+ method: "OPTIONS",
797
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
798
+ });
799
+
800
+ // ==============================================
801
+ // SERPER (Google Search) PROXY
802
+ // ==============================================
803
+ http.route({
804
+ path: "/proxy/serper",
805
+ method: "POST",
806
+ handler: httpAction(async (ctx, request) => {
807
+ await validateAndLogProxyCall(ctx, request, "serper", "search");
808
+ const SERPER_KEY = process.env.SERPER_API_KEY;
809
+ if (!SERPER_KEY) {
810
+ return jsonResponse({ error: "Serper not configured" }, 500);
811
+ }
812
+ try {
813
+ const body = await request.json();
814
+ const { query, q, num = 10, gl = "us", hl = "en" } = body;
815
+ const searchQuery = query || q;
816
+ if (!searchQuery) {
817
+ return jsonResponse({ error: "query required" }, 400);
818
+ }
819
+ const response = await fetch("https://google.serper.dev/search", {
820
+ method: "POST",
821
+ headers: {
822
+ "X-API-KEY": SERPER_KEY,
823
+ "Content-Type": "application/json",
824
+ },
825
+ body: JSON.stringify({ q: searchQuery, num, gl, hl }),
826
+ });
827
+ const data = await response.json();
828
+ return jsonResponse(data, response.status);
829
+ } catch (e: any) {
830
+ return jsonResponse({ error: e.message }, 500);
831
+ }
832
+ }),
833
+ });
834
+
835
+ http.route({
836
+ path: "/proxy/serper",
837
+ method: "OPTIONS",
838
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
839
+ });
840
+
841
+ // ==============================================
842
+ // FIRECRAWL (Web Scraping) PROXY
843
+ // ==============================================
844
+ http.route({
845
+ path: "/proxy/firecrawl",
846
+ method: "POST",
847
+ handler: httpAction(async (ctx, request) => {
848
+ await validateAndLogProxyCall(ctx, request, "firecrawl", "scrape");
849
+ const FIRECRAWL_KEY = process.env.FIRECRAWL_API_KEY;
850
+ if (!FIRECRAWL_KEY) {
851
+ return jsonResponse({ error: "Firecrawl not configured" }, 500);
852
+ }
853
+ try {
854
+ const body = await request.json();
855
+ const { url, formats = ["markdown"], onlyMainContent = true } = body;
856
+ if (!url) {
857
+ return jsonResponse({ error: "url required" }, 400);
858
+ }
859
+ const response = await fetch("https://api.firecrawl.dev/v1/scrape", {
860
+ method: "POST",
861
+ headers: {
862
+ Authorization: `Bearer ${FIRECRAWL_KEY}`,
863
+ "Content-Type": "application/json",
864
+ },
865
+ body: JSON.stringify({ url, formats, onlyMainContent }),
866
+ });
867
+ const data = await response.json();
868
+ return jsonResponse(data, response.status);
869
+ } catch (e: any) {
870
+ return jsonResponse({ error: e.message }, 500);
871
+ }
872
+ }),
873
+ });
874
+
875
+ http.route({
876
+ path: "/proxy/firecrawl",
877
+ method: "OPTIONS",
878
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
879
+ });
880
+
881
+ // ==============================================
882
+ // GROQ (LLM) PROXY
883
+ // ==============================================
884
+ http.route({
885
+ path: "/proxy/groq",
886
+ method: "POST",
887
+ handler: httpAction(async (ctx, request) => {
888
+ await validateAndLogProxyCall(ctx, request, "groq", "chat");
889
+ const GROQ_KEY = process.env.GROQ_API_KEY;
890
+ if (!GROQ_KEY) {
891
+ return jsonResponse({ error: "Groq not configured" }, 500);
892
+ }
893
+ try {
894
+ const body = await request.json();
895
+ const { model = "llama-3.3-70b-versatile", messages, temperature = 0.7, max_tokens = 1024 } = body;
896
+ if (!messages) {
897
+ return jsonResponse({ error: "messages required" }, 400);
898
+ }
899
+ const response = await fetch("https://api.groq.com/openai/v1/chat/completions", {
900
+ method: "POST",
901
+ headers: {
902
+ Authorization: `Bearer ${GROQ_KEY}`,
903
+ "Content-Type": "application/json",
904
+ },
905
+ body: JSON.stringify({ model, messages, temperature, max_tokens }),
906
+ });
907
+ const data = await response.json();
908
+ return jsonResponse(data, response.status);
909
+ } catch (e: any) {
910
+ return jsonResponse({ error: e.message }, 500);
911
+ }
912
+ }),
913
+ });
914
+
915
+ http.route({
916
+ path: "/proxy/groq",
917
+ method: "OPTIONS",
918
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
919
+ });
920
+
921
+ // ==============================================
922
+ // MISTRAL (LLM/Embeddings) PROXY
923
+ // ==============================================
924
+ http.route({
925
+ path: "/proxy/mistral",
926
+ method: "POST",
927
+ handler: httpAction(async (ctx, request) => {
928
+ await validateAndLogProxyCall(ctx, request, "mistral", "chat");
929
+ const MISTRAL_KEY = process.env.MISTRAL_API_KEY;
930
+ if (!MISTRAL_KEY) {
931
+ return jsonResponse({ error: "Mistral not configured" }, 500);
932
+ }
933
+ try {
934
+ const body = await request.json();
935
+ const { model = "mistral-small-latest", messages, temperature = 0.7, max_tokens = 1024 } = body;
936
+ if (!messages) {
937
+ return jsonResponse({ error: "messages required" }, 400);
938
+ }
939
+ const response = await fetch("https://api.mistral.ai/v1/chat/completions", {
940
+ method: "POST",
941
+ headers: {
942
+ Authorization: `Bearer ${MISTRAL_KEY}`,
943
+ "Content-Type": "application/json",
944
+ },
945
+ body: JSON.stringify({ model, messages, temperature, max_tokens }),
946
+ });
947
+ const data = await response.json();
948
+ return jsonResponse(data, response.status);
949
+ } catch (e: any) {
950
+ return jsonResponse({ error: e.message }, 500);
951
+ }
952
+ }),
953
+ });
954
+
955
+ http.route({
956
+ path: "/proxy/mistral",
957
+ method: "OPTIONS",
958
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
959
+ });
960
+
961
+ // ==============================================
962
+ // COHERE (LLM/Rerank) PROXY
963
+ // ==============================================
964
+ http.route({
965
+ path: "/proxy/cohere",
966
+ method: "POST",
967
+ handler: httpAction(async (ctx, request) => {
968
+ await validateAndLogProxyCall(ctx, request, "cohere", "chat");
969
+ const COHERE_KEY = process.env.COHERE_API_KEY;
970
+ if (!COHERE_KEY) {
971
+ return jsonResponse({ error: "Cohere not configured" }, 500);
972
+ }
973
+ try {
974
+ const body = await request.json();
975
+ const { model = "command-a-03-2025", message, chat_history, temperature = 0.7, max_tokens = 1024 } = body;
976
+ if (!message) {
977
+ return jsonResponse({ error: "message required" }, 400);
978
+ }
979
+ const response = await fetch("https://api.cohere.com/v2/chat", {
980
+ method: "POST",
981
+ headers: {
982
+ Authorization: `Bearer ${COHERE_KEY}`,
983
+ "Content-Type": "application/json",
984
+ },
985
+ body: JSON.stringify({ model, message, chat_history, temperature, max_tokens }),
986
+ });
987
+ const data = await response.json();
988
+ return jsonResponse(data, response.status);
989
+ } catch (e: any) {
990
+ return jsonResponse({ error: e.message }, 500);
991
+ }
992
+ }),
993
+ });
994
+
995
+ http.route({
996
+ path: "/proxy/cohere",
997
+ method: "OPTIONS",
998
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
999
+ });
1000
+
1001
+ // ==============================================
1002
+ // REPLICATE (ML Models) PROXY
1003
+ // ==============================================
1004
+ http.route({
1005
+ path: "/proxy/replicate",
1006
+ method: "POST",
1007
+ handler: httpAction(async (ctx, request) => {
1008
+ await validateAndLogProxyCall(ctx, request, "replicate", "prediction");
1009
+ const REPLICATE_KEY = process.env.REPLICATE_API_TOKEN;
1010
+ if (!REPLICATE_KEY) {
1011
+ return jsonResponse({ error: "Replicate not configured" }, 500);
1012
+ }
1013
+ try {
1014
+ const body = await request.json();
1015
+ const { model, input, version } = body;
1016
+ if (!model && !version) {
1017
+ return jsonResponse({ error: "model or version required" }, 400);
1018
+ }
1019
+ const endpoint = version
1020
+ ? "https://api.replicate.com/v1/predictions"
1021
+ : `https://api.replicate.com/v1/models/${model}/predictions`;
1022
+ const payload = version ? { version, input } : { input };
1023
+ const response = await fetch(endpoint, {
1024
+ method: "POST",
1025
+ headers: {
1026
+ Authorization: `Bearer ${REPLICATE_KEY}`,
1027
+ "Content-Type": "application/json",
1028
+ Prefer: "wait",
1029
+ },
1030
+ body: JSON.stringify(payload),
1031
+ });
1032
+ const data = await response.json();
1033
+ return jsonResponse(data, response.status);
1034
+ } catch (e: any) {
1035
+ return jsonResponse({ error: e.message }, 500);
1036
+ }
1037
+ }),
1038
+ });
1039
+
1040
+ http.route({
1041
+ path: "/proxy/replicate",
1042
+ method: "OPTIONS",
1043
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1044
+ });
1045
+
1046
+ // ==============================================
1047
+ // DEEPGRAM (Speech-to-Text) PROXY
1048
+ // ==============================================
1049
+ http.route({
1050
+ path: "/proxy/deepgram",
1051
+ method: "POST",
1052
+ handler: httpAction(async (ctx, request) => {
1053
+ await validateAndLogProxyCall(ctx, request, "deepgram", "transcribe");
1054
+ const DEEPGRAM_KEY = process.env.DEEPGRAM_API_KEY;
1055
+ if (!DEEPGRAM_KEY) {
1056
+ return jsonResponse({ error: "Deepgram not configured" }, 500);
1057
+ }
1058
+ try {
1059
+ const body = await request.json();
1060
+ const { url, model = "nova-3", language = "en", smart_format = true } = body;
1061
+ if (!url) {
1062
+ return jsonResponse({ error: "url required (audio file URL)" }, 400);
1063
+ }
1064
+ const params = new URLSearchParams({
1065
+ model,
1066
+ language,
1067
+ smart_format: String(smart_format),
1068
+ });
1069
+ const response = await fetch(
1070
+ `https://api.deepgram.com/v1/listen?${params}`,
1071
+ {
1072
+ method: "POST",
1073
+ headers: {
1074
+ Authorization: `Token ${DEEPGRAM_KEY}`,
1075
+ "Content-Type": "application/json",
1076
+ },
1077
+ body: JSON.stringify({ url }),
1078
+ }
1079
+ );
1080
+ const data = await response.json();
1081
+ return jsonResponse(data, response.status);
1082
+ } catch (e: any) {
1083
+ return jsonResponse({ error: e.message }, 500);
1084
+ }
1085
+ }),
1086
+ });
1087
+
1088
+ http.route({
1089
+ path: "/proxy/deepgram",
1090
+ method: "OPTIONS",
1091
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1092
+ });
1093
+
1094
+ // ==============================================
1095
+ // E2B (Code Sandbox) PROXY
1096
+ // ==============================================
1097
+ http.route({
1098
+ path: "/proxy/e2b",
1099
+ method: "POST",
1100
+ handler: httpAction(async (ctx, request) => {
1101
+ await validateAndLogProxyCall(ctx, request, "e2b", "execute");
1102
+ const E2B_KEY = process.env.E2B_API_KEY;
1103
+ if (!E2B_KEY) {
1104
+ return jsonResponse({ error: "E2B not configured" }, 500);
1105
+ }
1106
+ try {
1107
+ const body = await request.json();
1108
+ const { code, language = "python", template = "base" } = body;
1109
+ if (!code) {
1110
+ return jsonResponse({ error: "code required" }, 400);
1111
+ }
1112
+ const response = await fetch("https://api.e2b.dev/sandboxes", {
1113
+ method: "POST",
1114
+ headers: {
1115
+ "X-API-Key": E2B_KEY,
1116
+ "Content-Type": "application/json",
1117
+ },
1118
+ body: JSON.stringify({ templateID: template, metadata: { language } }),
1119
+ });
1120
+ const sandbox = await response.json();
1121
+ if (!response.ok) {
1122
+ return jsonResponse(sandbox, response.status);
1123
+ }
1124
+ const execResponse = await fetch(
1125
+ `https://api.e2b.dev/sandboxes/${sandbox.sandboxID}/code/execution`,
1126
+ {
1127
+ method: "POST",
1128
+ headers: {
1129
+ "X-API-Key": E2B_KEY,
1130
+ "Content-Type": "application/json",
1131
+ },
1132
+ body: JSON.stringify({ code, language }),
1133
+ }
1134
+ );
1135
+ const result = await execResponse.json();
1136
+ return jsonResponse(result, execResponse.status);
1137
+ } catch (e: any) {
1138
+ return jsonResponse({ error: e.message }, 500);
1139
+ }
1140
+ }),
1141
+ });
1142
+
1143
+ http.route({
1144
+ path: "/proxy/e2b",
1145
+ method: "OPTIONS",
1146
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1147
+ });
1148
+
1149
+ // ==============================================
1150
+ // TOGETHER AI (Open-source LLM Inference) PROXY
1151
+ // ==============================================
1152
+ http.route({
1153
+ path: "/proxy/together",
1154
+ method: "POST",
1155
+ handler: httpAction(async (ctx, request) => {
1156
+ await validateAndLogProxyCall(ctx, request, "together", "chat");
1157
+ const TOGETHER_KEY = process.env.TOGETHER_API_KEY;
1158
+ if (!TOGETHER_KEY) {
1159
+ return jsonResponse({ error: "Together AI not configured" }, 500);
1160
+ }
1161
+ try {
1162
+ const body = await request.json();
1163
+ const { model = "meta-llama/Llama-3.3-70B-Instruct-Turbo", messages, temperature = 0.7, max_tokens = 1024 } = body;
1164
+ if (!messages || !Array.isArray(messages)) {
1165
+ return jsonResponse({ error: "messages array required" }, 400);
1166
+ }
1167
+ const response = await fetch("https://api.together.xyz/v1/chat/completions", {
1168
+ method: "POST",
1169
+ headers: {
1170
+ Authorization: `Bearer ${TOGETHER_KEY}`,
1171
+ "Content-Type": "application/json",
1172
+ },
1173
+ body: JSON.stringify({ model, messages, temperature, max_tokens }),
1174
+ });
1175
+ const data = await response.json();
1176
+ return jsonResponse(data, response.status);
1177
+ } catch (e: any) {
1178
+ return jsonResponse({ error: e.message }, 500);
1179
+ }
1180
+ }),
1181
+ });
1182
+
1183
+ http.route({
1184
+ path: "/proxy/together",
1185
+ method: "OPTIONS",
1186
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1187
+ });
1188
+
1189
+ // ==============================================
1190
+ // STABILITY AI (Image Generation) PROXY
1191
+ // ==============================================
1192
+ http.route({
1193
+ path: "/proxy/stability",
1194
+ method: "POST",
1195
+ handler: httpAction(async (ctx, request) => {
1196
+ await validateAndLogProxyCall(ctx, request, "stability", "generate");
1197
+ const STABILITY_KEY = process.env.STABILITY_API_KEY;
1198
+ if (!STABILITY_KEY) {
1199
+ return jsonResponse({ error: "Stability AI not configured" }, 500);
1200
+ }
1201
+ try {
1202
+ const body = await request.json();
1203
+ const { prompt, model = "sd3.5-large", output_format = "png", aspect_ratio = "1:1" } = body;
1204
+ if (!prompt) {
1205
+ return jsonResponse({ error: "prompt required" }, 400);
1206
+ }
1207
+ const formData = new FormData();
1208
+ formData.append("prompt", prompt);
1209
+ formData.append("output_format", output_format);
1210
+ formData.append("aspect_ratio", aspect_ratio);
1211
+ const response = await fetch(
1212
+ `https://api.stability.ai/v2beta/stable-image/generate/${model}`,
1213
+ {
1214
+ method: "POST",
1215
+ headers: {
1216
+ Authorization: `Bearer ${STABILITY_KEY}`,
1217
+ Accept: "application/json",
1218
+ },
1219
+ body: formData,
1220
+ }
1221
+ );
1222
+ const data = await response.json();
1223
+ return jsonResponse(data, response.status);
1224
+ } catch (e: any) {
1225
+ return jsonResponse({ error: e.message }, 500);
1226
+ }
1227
+ }),
1228
+ });
1229
+
1230
+ http.route({
1231
+ path: "/proxy/stability",
1232
+ method: "OPTIONS",
1233
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1234
+ });
1235
+
1236
+ // ==============================================
1237
+ // ASSEMBLYAI (Audio Intelligence) PROXY
1238
+ // ==============================================
1239
+ http.route({
1240
+ path: "/proxy/assemblyai",
1241
+ method: "POST",
1242
+ handler: httpAction(async (ctx, request) => {
1243
+ await validateAndLogProxyCall(ctx, request, "assemblyai", "transcribe");
1244
+ const ASSEMBLYAI_KEY = process.env.ASSEMBLYAI_API_KEY;
1245
+ if (!ASSEMBLYAI_KEY) {
1246
+ return jsonResponse({ error: "AssemblyAI not configured" }, 500);
1247
+ }
1248
+ try {
1249
+ const body = await request.json();
1250
+ const { audio_url, language_detection = true, speaker_labels = true } = body;
1251
+ if (!audio_url) {
1252
+ return jsonResponse({ error: "audio_url required" }, 400);
1253
+ }
1254
+ const response = await fetch("https://api.assemblyai.com/v2/transcript", {
1255
+ method: "POST",
1256
+ headers: {
1257
+ Authorization: ASSEMBLYAI_KEY,
1258
+ "Content-Type": "application/json",
1259
+ },
1260
+ body: JSON.stringify({ audio_url, language_detection, speaker_labels }),
1261
+ });
1262
+ const data = await response.json();
1263
+ return jsonResponse(data, response.status);
1264
+ } catch (e: any) {
1265
+ return jsonResponse({ error: e.message }, 500);
1266
+ }
1267
+ }),
1268
+ });
1269
+
1270
+ http.route({
1271
+ path: "/proxy/assemblyai",
1272
+ method: "OPTIONS",
1273
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1274
+ });
1275
+
1276
+ // ==============================================
1277
+ // APILAYER (Multi-API: Exchange, Stocks, Aviation, etc.) PROXY
1278
+ // ==============================================
1279
+ http.route({
1280
+ path: "/proxy/apilayer",
1281
+ method: "POST",
1282
+ handler: httpAction(async (ctx, request) => {
1283
+ await validateAndLogProxyCall(ctx, request, "apilayer", "call");
1284
+ const APILAYER_KEY = process.env.APILAYER_API_KEY;
1285
+ if (!APILAYER_KEY) {
1286
+ return jsonResponse({ error: "APILayer not configured" }, 500);
1287
+ }
1288
+ try {
1289
+ const body = await request.json();
1290
+ const { service, endpoint, params = {} } = body;
1291
+ if (!service || !endpoint) {
1292
+ return jsonResponse({ error: "service and endpoint required (e.g. service:'exchangerates', endpoint:'/latest')" }, 400);
1293
+ }
1294
+ const queryString = new URLSearchParams(params).toString();
1295
+ const url = `https://api.apilayer.com/${service}${endpoint}${queryString ? '?' + queryString : ''}`;
1296
+ const response = await fetch(url, {
1297
+ method: "GET",
1298
+ headers: {
1299
+ apikey: APILAYER_KEY,
1300
+ },
1301
+ });
1302
+ const data = await response.json();
1303
+ return jsonResponse(data, response.status);
1304
+ } catch (e: any) {
1305
+ return jsonResponse({ error: e.message }, 500);
1306
+ }
1307
+ }),
1308
+ });
1309
+
1310
+ http.route({
1311
+ path: "/proxy/apilayer",
1312
+ method: "OPTIONS",
1313
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1314
+ });
1315
+
1316
+ // ==============================================
1317
+ // WORKSPACE / MAGIC LINK ENDPOINTS
1318
+ // ==============================================
1319
+
1320
+ // Create magic link and send email
1321
+ http.route({
1322
+ path: "/workspace/magic-link",
1323
+ method: "POST",
1324
+ handler: httpAction(async (ctx, request) => {
1325
+ try {
1326
+ const body = await request.json();
1327
+ const { email, fingerprint } = body;
1328
+
1329
+ if (!email || !email.includes("@")) {
1330
+ return jsonResponse({ error: "Valid email required" }, 400);
1331
+ }
1332
+
1333
+ // Create magic link
1334
+ const result = await ctx.runMutation(api.workspaces.createMagicLink, {
1335
+ email: email.toLowerCase(),
1336
+ fingerprint,
1337
+ });
1338
+
1339
+ // Send email directly - SIMPLE HTML (complex tables get stripped by Gmail)
1340
+ const verifyUrl = `https://apiclaw.nordsym.com/auth/verify?token=${result.token}`;
1341
+ const html = `<div style="font-family:Arial,sans-serif;max-width:500px;margin:0 auto;padding:20px;">
1342
+ <h1>🦞 APIClaw</h1>
1343
+ <h2>An AI Agent Wants to Connect</h2>
1344
+ <p>Click below to verify your email and activate your workspace.</p>
1345
+ <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>
1346
+ <p style="color:#666;font-size:13px;">Free tier: 50 API calls. This link expires in 1 hour.</p>
1347
+ <p style="color:#999;font-size:11px;">Or copy this link: ${verifyUrl}</p>
1348
+ </div>`;
1349
+
1350
+ const RESEND_KEY = process.env.RESEND_API_KEY;
1351
+ if (!RESEND_KEY) {
1352
+ console.error("RESEND_API_KEY not configured");
1353
+ return jsonResponse({ error: "Email service not configured" }, 500);
1354
+ }
1355
+
1356
+ const emailResponse = await fetch("https://api.resend.com/emails", {
1357
+ method: "POST",
1358
+ headers: {
1359
+ "Authorization": `Bearer ${RESEND_KEY}`,
1360
+ "Content-Type": "application/json",
1361
+ },
1362
+ body: JSON.stringify({
1363
+ from: "APIClaw <noreply@apiclaw.nordsym.com>",
1364
+ to: email.toLowerCase(),
1365
+ subject: "🦞 Verify Your Email — APIClaw",
1366
+ html: html,
1367
+ }),
1368
+ });
1369
+
1370
+ if (!emailResponse.ok) {
1371
+ const errorText = await emailResponse.text();
1372
+ console.error("Resend error:", emailResponse.status, errorText);
1373
+ return jsonResponse({ error: "Failed to send email", details: errorText }, 500);
1374
+ }
1375
+
1376
+ const emailResult = await emailResponse.json();
1377
+ console.log("Email sent successfully:", emailResult.id);
1378
+
1379
+ return jsonResponse({
1380
+ success: true,
1381
+ token: result.token,
1382
+ expiresAt: result.expiresAt,
1383
+ message: "Magic link sent! Check your email.",
1384
+ emailId: emailResult.id,
1385
+ });
1386
+ } catch (e: any) {
1387
+ console.error("Magic link error:", e);
1388
+ return jsonResponse({ error: e.message || "Failed to create magic link" }, 500);
1389
+ }
1390
+ }),
1391
+ });
1392
+
1393
+ http.route({
1394
+ path: "/workspace/magic-link",
1395
+ method: "OPTIONS",
1396
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1397
+ });
1398
+
1399
+ // Poll magic link status (for agents to check if user clicked)
1400
+ http.route({
1401
+ path: "/workspace/poll",
1402
+ method: "GET",
1403
+ handler: httpAction(async (ctx, request) => {
1404
+ const url = new URL(request.url);
1405
+ const token = url.searchParams.get("token");
1406
+
1407
+ if (!token) {
1408
+ return jsonResponse({ error: "token required" }, 400);
1409
+ }
1410
+
1411
+ const result = await ctx.runQuery(api.workspaces.pollMagicLink, { token });
1412
+ return jsonResponse(result);
1413
+ }),
1414
+ });
1415
+
1416
+ http.route({
1417
+ path: "/workspace/poll",
1418
+ method: "OPTIONS",
1419
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1420
+ });
1421
+
1422
+ // Verify session token
1423
+ http.route({
1424
+ path: "/workspace/verify-session",
1425
+ method: "GET",
1426
+ handler: httpAction(async (ctx, request) => {
1427
+ const url = new URL(request.url);
1428
+ const sessionToken = url.searchParams.get("sessionToken");
1429
+
1430
+ if (!sessionToken) {
1431
+ return jsonResponse({ error: "sessionToken required" }, 400);
1432
+ }
1433
+
1434
+ const result = await ctx.runQuery(api.workspaces.verifySession, { sessionToken });
1435
+
1436
+ if (!result) {
1437
+ return jsonResponse({ error: "Invalid or expired session" }, 401);
1438
+ }
1439
+
1440
+ return jsonResponse(result);
1441
+ }),
1442
+ });
1443
+
1444
+ http.route({
1445
+ path: "/workspace/verify-session",
1446
+ method: "OPTIONS",
1447
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1448
+ });
1449
+
1450
+ // Get workspace by email
1451
+ http.route({
1452
+ path: "/workspace/by-email",
1453
+ method: "GET",
1454
+ handler: httpAction(async (ctx, request) => {
1455
+ const url = new URL(request.url);
1456
+ const email = url.searchParams.get("email");
1457
+
1458
+ if (!email) {
1459
+ return jsonResponse({ error: "email required" }, 400);
1460
+ }
1461
+
1462
+ const result = await ctx.runQuery(api.workspaces.getByEmail, { email });
1463
+
1464
+ if (!result) {
1465
+ return jsonResponse({ exists: false });
1466
+ }
1467
+
1468
+ return jsonResponse({ exists: true, workspace: result });
1469
+ }),
1470
+ });
1471
+
1472
+ http.route({
1473
+ path: "/workspace/by-email",
1474
+ method: "OPTIONS",
1475
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1476
+ });
1477
+
1478
+ // Send reminder email
1479
+ http.route({
1480
+ path: "/workspace/send-reminder",
1481
+ method: "POST",
1482
+ handler: httpAction(async (ctx, request) => {
1483
+ try {
1484
+ const body = await request.json();
1485
+ const { email, token } = body;
1486
+
1487
+ if (!email || !token) {
1488
+ return jsonResponse({ error: "email and token required" }, 400);
1489
+ }
1490
+
1491
+ await ctx.runAction(api.email.sendReminderEmail, { email, token });
1492
+ return jsonResponse({ success: true });
1493
+ } catch (e: any) {
1494
+ return jsonResponse({ error: e.message }, 500);
1495
+ }
1496
+ }),
1497
+ });
1498
+
1499
+ http.route({
1500
+ path: "/workspace/send-reminder",
1501
+ method: "OPTIONS",
1502
+ handler: httpAction(async () => new Response(null, { headers: corsHeaders })),
1503
+ });
1504
+
1505
+ // ==============================================
1506
+ // STRIPE BILLING ENDPOINTS
1507
+ // ==============================================
1508
+
1509
+ // Create checkout session
1510
+ http.route({
1511
+ path: "/api/billing/checkout",
1512
+ method: "POST",
1513
+ handler: createCheckoutSession,
1514
+ });
1515
+
1516
+ http.route({
1517
+ path: "/api/billing/checkout",
1518
+ method: "OPTIONS",
1519
+ handler: checkoutOptions,
1520
+ });
1521
+
1522
+ // Create billing portal session
1523
+ http.route({
1524
+ path: "/api/billing/portal",
1525
+ method: "POST",
1526
+ handler: createPortalSession,
1527
+ });
1528
+
1529
+ http.route({
1530
+ path: "/api/billing/portal",
1531
+ method: "OPTIONS",
1532
+ handler: portalOptions,
1533
+ });
1534
+
1535
+ // Stripe webhook handler
1536
+ http.route({
1537
+ path: "/api/webhooks/stripe",
1538
+ method: "POST",
1539
+ handler: handleStripeWebhook,
1540
+ });
1541
+
1542
+ http.route({
1543
+ path: "/api/webhooks/stripe",
1544
+ method: "OPTIONS",
1545
+ handler: webhookOptions,
1546
+ });
1547
+
1548
+ // Test endpoint to debug logging
1549
+ http.route({
1550
+ path: "/proxy/test-logging",
1551
+ method: "POST",
1552
+ handler: httpAction(async (ctx, request) => {
1553
+ const identifier = request.headers.get("X-APIClaw-Identifier");
1554
+
1555
+ try {
1556
+ const logId = await ctx.runMutation(api.analytics.log, {
1557
+ event: "test_endpoint",
1558
+ provider: "test",
1559
+ identifier: identifier || "test",
1560
+ metadata: { test: true },
1561
+ });
1562
+
1563
+ return jsonResponse({
1564
+ success: true,
1565
+ identifier,
1566
+ logId,
1567
+ message: "Logged successfully"
1568
+ });
1569
+ } catch (e: any) {
1570
+ return jsonResponse({
1571
+ success: false,
1572
+ error: e.message,
1573
+ stack: e.stack
1574
+ }, 500);
1575
+ }
1576
+ }),
1577
+ });