@nordsym/apiclaw 1.5.13 → 1.5.14

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 (68) hide show
  1. package/dist/bin.js +1 -1
  2. package/dist/cli/index.js +7 -0
  3. package/dist/convex/adminActivate.js +46 -0
  4. package/dist/convex/adminStats.js +41 -0
  5. package/dist/convex/agents.js +498 -0
  6. package/dist/convex/analytics.js +165 -0
  7. package/dist/convex/billing.js +654 -0
  8. package/dist/convex/capabilities.js +144 -0
  9. package/dist/convex/chains.js +1041 -0
  10. package/dist/convex/credits.js +185 -0
  11. package/dist/convex/crons.js +16 -0
  12. package/dist/convex/directCall.js +626 -0
  13. package/dist/convex/earnProgress.js +648 -0
  14. package/dist/convex/email.js +299 -0
  15. package/dist/convex/feedback.js +226 -0
  16. package/dist/convex/http.js +909 -0
  17. package/dist/convex/logs.js +486 -0
  18. package/dist/convex/mou.js +81 -0
  19. package/dist/convex/providerKeys.js +256 -0
  20. package/dist/convex/providers.js +755 -0
  21. package/dist/convex/purchases.js +156 -0
  22. package/dist/convex/ratelimit.js +90 -0
  23. package/dist/convex/schema.js +709 -0
  24. package/dist/convex/searchLogs.js +128 -0
  25. package/dist/convex/spendAlerts.js +379 -0
  26. package/dist/convex/stripeActions.js +410 -0
  27. package/dist/convex/teams.js +214 -0
  28. package/dist/convex/telemetry.js +73 -0
  29. package/dist/convex/usage.js +228 -0
  30. package/dist/convex/waitlist.js +48 -0
  31. package/dist/convex/webhooks.js +409 -0
  32. package/dist/convex/workspaces.js +879 -0
  33. package/dist/src/analytics.js +129 -0
  34. package/dist/src/bin.js +17 -0
  35. package/dist/src/capability-router.js +240 -0
  36. package/dist/src/chainExecutor.js +451 -0
  37. package/dist/src/chainResolver.js +518 -0
  38. package/dist/src/cli/commands/doctor.js +324 -0
  39. package/dist/src/cli/commands/mcp-install.js +255 -0
  40. package/dist/src/cli/commands/restore.js +259 -0
  41. package/dist/src/cli/commands/setup.js +205 -0
  42. package/dist/src/cli/commands/uninstall.js +188 -0
  43. package/dist/src/cli/index.js +111 -0
  44. package/dist/src/cli.js +302 -0
  45. package/dist/src/confirmation.js +240 -0
  46. package/dist/src/credentials.js +357 -0
  47. package/dist/src/credits.js +260 -0
  48. package/dist/src/crypto.js +66 -0
  49. package/dist/src/discovery.js +504 -0
  50. package/dist/src/enterprise/env.js +123 -0
  51. package/dist/src/enterprise/script-generator.js +460 -0
  52. package/dist/src/execute-dynamic.js +473 -0
  53. package/dist/src/execute.js +1727 -0
  54. package/dist/src/index.js +2062 -0
  55. package/dist/src/metered.js +80 -0
  56. package/dist/src/open-apis.js +276 -0
  57. package/dist/src/proxy.js +28 -0
  58. package/dist/src/session.js +86 -0
  59. package/dist/src/stripe.js +407 -0
  60. package/dist/src/telemetry.js +49 -0
  61. package/dist/src/types.js +2 -0
  62. package/dist/src/utils/backup.js +181 -0
  63. package/dist/src/utils/config.js +220 -0
  64. package/dist/src/utils/os.js +105 -0
  65. package/dist/src/utils/paths.js +159 -0
  66. package/package.json +1 -1
  67. package/src/bin.ts +1 -1
  68. package/src/cli/index.ts +8 -0
@@ -0,0 +1,128 @@
1
+ import { internalMutation, query } from "./_generated/server";
2
+ import { v } from "convex/values";
3
+ // Log a search query (uses existing searchLogs table schema)
4
+ export const logSearch = internalMutation({
5
+ args: {
6
+ query: v.string(),
7
+ resultsCount: v.number(),
8
+ matchedProviders: v.optional(v.array(v.string())),
9
+ sessionToken: v.optional(v.string()),
10
+ userAgent: v.optional(v.string()),
11
+ responseTimeMs: v.optional(v.number()),
12
+ },
13
+ handler: async (ctx, args) => {
14
+ // Try to get workspaceId from session token
15
+ let workspaceId = undefined;
16
+ let subagentId = undefined;
17
+ if (args.sessionToken) {
18
+ try {
19
+ const token = args.sessionToken;
20
+ const session = await ctx.db
21
+ .query("agentSessions")
22
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
23
+ .first();
24
+ if (session) {
25
+ workspaceId = session.workspaceId;
26
+ // No agentId in agentSessions, subagentId stays undefined
27
+ }
28
+ }
29
+ catch (e) {
30
+ // Ignore - just skip workspace linking
31
+ }
32
+ }
33
+ // Only log if we have a workspace (existing schema requires it)
34
+ if (workspaceId) {
35
+ await ctx.db.insert("searchLogs", {
36
+ workspaceId,
37
+ subagentId,
38
+ query: args.query,
39
+ resultCount: args.resultsCount,
40
+ hasResults: args.resultsCount > 0,
41
+ matchedProviders: args.matchedProviders,
42
+ responseTimeMs: args.responseTimeMs || 0,
43
+ timestamp: Date.now(),
44
+ });
45
+ }
46
+ // TODO: Also log anonymous searches somewhere (for product insights)
47
+ },
48
+ });
49
+ // Get top search queries (for analytics)
50
+ export const getTopQueries = query({
51
+ args: {
52
+ limit: v.optional(v.number()),
53
+ since: v.optional(v.number()), // timestamp
54
+ },
55
+ handler: async (ctx, args) => {
56
+ const limit = args.limit || 50;
57
+ const since = args.since || Date.now() - 7 * 24 * 60 * 60 * 1000; // Last 7 days
58
+ const logs = await ctx.db
59
+ .query("searchLogs")
60
+ .withIndex("by_timestamp")
61
+ .filter((q) => q.gte(q.field("timestamp"), since))
62
+ .collect();
63
+ // Aggregate by query
64
+ const queryCounts = {};
65
+ for (const log of logs) {
66
+ const q = log.query.toLowerCase().trim();
67
+ if (!q)
68
+ continue;
69
+ if (!queryCounts[q]) {
70
+ queryCounts[q] = { count: 0, avgResults: 0, totalResults: 0 };
71
+ }
72
+ queryCounts[q].count++;
73
+ queryCounts[q].totalResults += log.resultCount;
74
+ }
75
+ // Calculate averages and sort
76
+ const sorted = Object.entries(queryCounts)
77
+ .map(([query, data]) => ({
78
+ query,
79
+ count: data.count,
80
+ avgResults: Math.round(data.totalResults / data.count * 10) / 10,
81
+ noResults: data.totalResults === 0,
82
+ }))
83
+ .sort((a, b) => b.count - a.count)
84
+ .slice(0, limit);
85
+ return {
86
+ queries: sorted,
87
+ totalSearches: logs.length,
88
+ uniqueQueries: Object.keys(queryCounts).length,
89
+ period: {
90
+ since: new Date(since).toISOString(),
91
+ until: new Date().toISOString(),
92
+ },
93
+ };
94
+ },
95
+ });
96
+ // Get searches with no results (API gaps)
97
+ export const getZeroResultQueries = query({
98
+ args: {
99
+ limit: v.optional(v.number()),
100
+ since: v.optional(v.number()),
101
+ },
102
+ handler: async (ctx, args) => {
103
+ const limit = args.limit || 20;
104
+ const since = args.since || Date.now() - 7 * 24 * 60 * 60 * 1000;
105
+ const logs = await ctx.db
106
+ .query("searchLogs")
107
+ .withIndex("by_hasResults")
108
+ .filter((q) => q.and(q.eq(q.field("hasResults"), false), q.gte(q.field("timestamp"), since)))
109
+ .collect();
110
+ // Aggregate
111
+ const queryCounts = {};
112
+ for (const log of logs) {
113
+ const q = log.query.toLowerCase().trim();
114
+ if (!q)
115
+ continue;
116
+ queryCounts[q] = (queryCounts[q] || 0) + 1;
117
+ }
118
+ const sorted = Object.entries(queryCounts)
119
+ .map(([query, count]) => ({ query, count }))
120
+ .sort((a, b) => b.count - a.count)
121
+ .slice(0, limit);
122
+ return {
123
+ gaps: sorted,
124
+ totalZeroResults: logs.length,
125
+ message: "These queries returned no results - potential APIs to add",
126
+ };
127
+ },
128
+ });
@@ -0,0 +1,379 @@
1
+ import { v } from "convex/values";
2
+ import { mutation, query, action, internalMutation } from "./_generated/server";
3
+ // ============================================
4
+ // CONSTANTS
5
+ // ============================================
6
+ const ALERT_THRESHOLD = 0.8; // 80% of budget
7
+ const APP_URL = "https://apiclaw.nordsym.com";
8
+ const EMAIL_FROM = "APIClaw <noreply@apiclaw.nordsym.com>";
9
+ // ============================================
10
+ // HELPER: Get current month start
11
+ // ============================================
12
+ function getMonthStart() {
13
+ const now = new Date();
14
+ return new Date(now.getUTCFullYear(), now.getUTCMonth(), 1, 0, 0, 0, 0).getTime();
15
+ }
16
+ // ============================================
17
+ // MUTATIONS
18
+ // ============================================
19
+ /**
20
+ * Update workspace budget settings
21
+ */
22
+ export const updateBudgetSettings = mutation({
23
+ args: {
24
+ workspaceId: v.id("workspaces"),
25
+ budgetCap: v.optional(v.union(v.number(), v.null())), // in USD cents, null = unlimited
26
+ pauseOnBudgetExceeded: v.optional(v.boolean()),
27
+ },
28
+ handler: async (ctx, args) => {
29
+ const workspace = await ctx.db.get(args.workspaceId);
30
+ if (!workspace) {
31
+ throw new Error("Workspace not found");
32
+ }
33
+ const updates = {
34
+ updatedAt: Date.now(),
35
+ };
36
+ if (args.budgetCap !== undefined) {
37
+ updates.budgetCap = args.budgetCap;
38
+ // Reset alert when budget changes
39
+ updates.budgetAlertSentAt = undefined;
40
+ }
41
+ if (args.pauseOnBudgetExceeded !== undefined) {
42
+ updates.pauseOnBudgetExceeded = args.pauseOnBudgetExceeded;
43
+ }
44
+ await ctx.db.patch(args.workspaceId, updates);
45
+ return { success: true };
46
+ },
47
+ });
48
+ /**
49
+ * Record spend and check budget alerts
50
+ * Called after each successful API execution
51
+ * Returns budget status for response
52
+ */
53
+ export const recordSpend = mutation({
54
+ args: {
55
+ workspaceId: v.id("workspaces"),
56
+ amountCents: v.number(),
57
+ },
58
+ handler: async (ctx, args) => {
59
+ const workspace = await ctx.db.get(args.workspaceId);
60
+ if (!workspace) {
61
+ throw new Error("Workspace not found");
62
+ }
63
+ const monthStart = getMonthStart();
64
+ // Reset monthly spend if new month
65
+ let currentSpend = workspace.monthlySpendCents || 0;
66
+ if (!workspace.lastSpendResetAt || workspace.lastSpendResetAt < monthStart) {
67
+ currentSpend = 0;
68
+ }
69
+ // Add new spend
70
+ const newSpend = currentSpend + args.amountCents;
71
+ // Update workspace
72
+ await ctx.db.patch(args.workspaceId, {
73
+ monthlySpendCents: newSpend,
74
+ lastSpendResetAt: monthStart,
75
+ updatedAt: Date.now(),
76
+ });
77
+ // Check if we need to send alert
78
+ const budgetCap = workspace.budgetCap;
79
+ let shouldSendAlert = false;
80
+ let budgetExceeded = false;
81
+ if (budgetCap && budgetCap > 0) {
82
+ const threshold = budgetCap * ALERT_THRESHOLD;
83
+ const alertAlreadySentThisMonth = workspace.budgetAlertSentAt &&
84
+ workspace.budgetAlertSentAt >= monthStart;
85
+ // Check if at 80% and alert not yet sent
86
+ if (newSpend >= threshold && !alertAlreadySentThisMonth) {
87
+ shouldSendAlert = true;
88
+ await ctx.db.patch(args.workspaceId, {
89
+ budgetAlertSentAt: Date.now(),
90
+ });
91
+ }
92
+ // Check if budget exceeded
93
+ if (newSpend >= budgetCap) {
94
+ budgetExceeded = true;
95
+ }
96
+ }
97
+ return {
98
+ success: true,
99
+ currentSpendCents: newSpend,
100
+ budgetCapCents: budgetCap || null,
101
+ budgetPercentage: budgetCap ? (newSpend / budgetCap) * 100 : null,
102
+ shouldSendAlert,
103
+ budgetExceeded,
104
+ email: workspace.email,
105
+ };
106
+ },
107
+ });
108
+ /**
109
+ * Check budget before execution
110
+ * Returns { allowed: boolean, reason?: string }
111
+ */
112
+ export const checkBudget = query({
113
+ args: {
114
+ workspaceId: v.id("workspaces"),
115
+ estimatedCostCents: v.optional(v.number()),
116
+ },
117
+ handler: async (ctx, args) => {
118
+ const workspace = await ctx.db.get(args.workspaceId);
119
+ if (!workspace) {
120
+ return { allowed: false, reason: "Workspace not found" };
121
+ }
122
+ // No budget cap set = unlimited
123
+ if (!workspace.budgetCap || workspace.budgetCap <= 0) {
124
+ return { allowed: true };
125
+ }
126
+ // Check if pause on exceeded is enabled
127
+ if (!workspace.pauseOnBudgetExceeded) {
128
+ return { allowed: true };
129
+ }
130
+ const monthStart = getMonthStart();
131
+ let currentSpend = workspace.monthlySpendCents || 0;
132
+ // Reset if new month
133
+ if (!workspace.lastSpendResetAt || workspace.lastSpendResetAt < monthStart) {
134
+ currentSpend = 0;
135
+ }
136
+ const estimatedCost = args.estimatedCostCents || 0;
137
+ const projectedSpend = currentSpend + estimatedCost;
138
+ if (projectedSpend > workspace.budgetCap) {
139
+ const budgetCapUsd = (workspace.budgetCap / 100).toFixed(2);
140
+ const currentSpendUsd = (currentSpend / 100).toFixed(2);
141
+ return {
142
+ allowed: false,
143
+ reason: `Budget exceeded. Monthly cap: $${budgetCapUsd}, current spend: $${currentSpendUsd}. Adjust budget in workspace settings.`,
144
+ currentSpendCents: currentSpend,
145
+ budgetCapCents: workspace.budgetCap,
146
+ };
147
+ }
148
+ return {
149
+ allowed: true,
150
+ currentSpendCents: currentSpend,
151
+ budgetCapCents: workspace.budgetCap,
152
+ remainingCents: workspace.budgetCap - currentSpend,
153
+ };
154
+ },
155
+ });
156
+ /**
157
+ * Get budget status for workspace dashboard
158
+ */
159
+ export const getBudgetStatus = query({
160
+ args: {
161
+ workspaceId: v.id("workspaces"),
162
+ },
163
+ handler: async (ctx, args) => {
164
+ const workspace = await ctx.db.get(args.workspaceId);
165
+ if (!workspace) {
166
+ return null;
167
+ }
168
+ const monthStart = getMonthStart();
169
+ let currentSpend = workspace.monthlySpendCents || 0;
170
+ // Reset if new month
171
+ if (!workspace.lastSpendResetAt || workspace.lastSpendResetAt < monthStart) {
172
+ currentSpend = 0;
173
+ }
174
+ const budgetCap = workspace.budgetCap || null;
175
+ const budgetPercentage = budgetCap ? (currentSpend / budgetCap) * 100 : null;
176
+ return {
177
+ budgetCapCents: budgetCap,
178
+ budgetCapUsd: budgetCap ? budgetCap / 100 : null,
179
+ currentSpendCents: currentSpend,
180
+ currentSpendUsd: currentSpend / 100,
181
+ remainingCents: budgetCap ? Math.max(0, budgetCap - currentSpend) : null,
182
+ remainingUsd: budgetCap ? Math.max(0, (budgetCap - currentSpend) / 100) : null,
183
+ budgetPercentage: budgetPercentage ? Math.min(100, budgetPercentage) : null,
184
+ pauseOnBudgetExceeded: workspace.pauseOnBudgetExceeded || false,
185
+ isOverBudget: budgetCap ? currentSpend >= budgetCap : false,
186
+ isNearBudget: budgetCap ? currentSpend >= budgetCap * ALERT_THRESHOLD : false,
187
+ alertSentAt: workspace.budgetAlertSentAt || null,
188
+ };
189
+ },
190
+ });
191
+ /**
192
+ * Get budget status by session token (for dashboard)
193
+ */
194
+ export const getBudgetStatusByToken = query({
195
+ args: {
196
+ token: v.string(),
197
+ },
198
+ handler: async (ctx, args) => {
199
+ const session = await ctx.db
200
+ .query("agentSessions")
201
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
202
+ .first();
203
+ if (!session) {
204
+ return null;
205
+ }
206
+ const workspace = await ctx.db.get(session.workspaceId);
207
+ if (!workspace) {
208
+ return null;
209
+ }
210
+ const monthStart = getMonthStart();
211
+ let currentSpend = workspace.monthlySpendCents || 0;
212
+ if (!workspace.lastSpendResetAt || workspace.lastSpendResetAt < monthStart) {
213
+ currentSpend = 0;
214
+ }
215
+ const budgetCap = workspace.budgetCap || null;
216
+ return {
217
+ budgetCapCents: budgetCap,
218
+ budgetCapUsd: budgetCap ? budgetCap / 100 : null,
219
+ currentSpendCents: currentSpend,
220
+ currentSpendUsd: currentSpend / 100,
221
+ remainingCents: budgetCap ? Math.max(0, budgetCap - currentSpend) : null,
222
+ remainingUsd: budgetCap ? Math.max(0, (budgetCap - currentSpend) / 100) : null,
223
+ budgetPercentage: budgetCap ? Math.min(100, (currentSpend / budgetCap) * 100) : null,
224
+ pauseOnBudgetExceeded: workspace.pauseOnBudgetExceeded || false,
225
+ isOverBudget: budgetCap ? currentSpend >= budgetCap : false,
226
+ isNearBudget: budgetCap ? currentSpend >= budgetCap * ALERT_THRESHOLD : false,
227
+ };
228
+ },
229
+ });
230
+ // ============================================
231
+ // EMAIL ACTION
232
+ // ============================================
233
+ /**
234
+ * Send budget alert email (80% warning)
235
+ */
236
+ export const sendBudgetAlertEmail = action({
237
+ args: {
238
+ email: v.string(),
239
+ currentSpendCents: v.number(),
240
+ budgetCapCents: v.number(),
241
+ },
242
+ handler: async (ctx, args) => {
243
+ const RESEND_API_KEY = process.env.RESEND_API_KEY;
244
+ if (!RESEND_API_KEY) {
245
+ console.error("RESEND_API_KEY not configured");
246
+ return { success: false, error: "Email not configured" };
247
+ }
248
+ const currentSpendUsd = (args.currentSpendCents / 100).toFixed(2);
249
+ const budgetCapUsd = (args.budgetCapCents / 100).toFixed(2);
250
+ const percentageUsed = Math.round((args.currentSpendCents / args.budgetCapCents) * 100);
251
+ const settingsUrl = `${APP_URL}/dashboard/settings`;
252
+ // Build email HTML
253
+ let html = "<!DOCTYPE html><html><head><meta charset='utf-8'></head>";
254
+ html += "<body style='margin:0;padding:40px;background:#f5f5f5;font-family:Arial,sans-serif;'>";
255
+ html += "<table width='100%' cellpadding='0' cellspacing='0'><tr><td align='center'>";
256
+ html += "<table width='500' cellpadding='0' cellspacing='0' style='background:#fff;border-radius:12px;'>";
257
+ html += "<tr><td style='padding:32px;text-align:center;'>";
258
+ html += "<div style='font-size:48px;'>🦞</div>";
259
+ html += "<h1 style='margin:16px 0;color:#0a0a0a;'>APIClaw</h1>";
260
+ html += "<h2 style='margin:0 0 16px;font-size:20px;color:#f59e0b;'>⚠️ Budget Alert</h2>";
261
+ html += "<p style='margin:0 0 16px;color:#525252;font-size:16px;'>You've used <strong>" + percentageUsed + "%</strong> of your monthly budget.</p>";
262
+ html += "<div style='background:#fef3c7;border:1px solid #f59e0b;border-radius:8px;padding:16px;margin-bottom:24px;'>";
263
+ html += "<p style='margin:0;color:#92400e;font-size:14px;'><strong>Current spend:</strong> $" + currentSpendUsd + " / $" + budgetCapUsd + "</p>";
264
+ html += "</div>";
265
+ html += "<p style='margin:0 0 24px;color:#525252;font-size:14px;'>If your budget is exceeded, API calls will be paused until the next billing cycle (if pause is enabled).</p>";
266
+ html += "<a href='" + settingsUrl + "' style='display:inline-block;background:#ef4444;color:white;padding:14px 32px;border-radius:8px;text-decoration:none;font-weight:600;'>Adjust Budget</a>";
267
+ html += "</td></tr></table>";
268
+ html += "</td></tr></table></body></html>";
269
+ const textContent = `APIClaw Budget Alert\n\nYou've used ${percentageUsed}% of your monthly budget.\nCurrent spend: $${currentSpendUsd} / $${budgetCapUsd}\n\nAdjust your budget: ${settingsUrl}`;
270
+ const response = await fetch("https://api.resend.com/emails", {
271
+ method: "POST",
272
+ headers: {
273
+ "Authorization": "Bearer " + RESEND_API_KEY,
274
+ "Content-Type": "application/json",
275
+ },
276
+ body: JSON.stringify({
277
+ from: EMAIL_FROM,
278
+ to: args.email,
279
+ subject: "⚠️ APIClaw: 80% of Monthly Budget Used",
280
+ html: html,
281
+ text: textContent,
282
+ }),
283
+ });
284
+ if (!response.ok) {
285
+ const errorText = await response.text();
286
+ console.error("Failed to send budget alert email:", errorText);
287
+ return { success: false, error: errorText };
288
+ }
289
+ return { success: true };
290
+ },
291
+ });
292
+ /**
293
+ * Send budget exceeded email
294
+ */
295
+ export const sendBudgetExceededEmail = action({
296
+ args: {
297
+ email: v.string(),
298
+ currentSpendCents: v.number(),
299
+ budgetCapCents: v.number(),
300
+ isPaused: v.boolean(),
301
+ },
302
+ handler: async (ctx, args) => {
303
+ const RESEND_API_KEY = process.env.RESEND_API_KEY;
304
+ if (!RESEND_API_KEY) {
305
+ console.error("RESEND_API_KEY not configured");
306
+ return { success: false, error: "Email not configured" };
307
+ }
308
+ const currentSpendUsd = (args.currentSpendCents / 100).toFixed(2);
309
+ const budgetCapUsd = (args.budgetCapCents / 100).toFixed(2);
310
+ const settingsUrl = `${APP_URL}/dashboard/settings`;
311
+ const pauseMessage = args.isPaused
312
+ ? "API execution has been paused. Increase your budget or disable pause-on-exceed to continue."
313
+ : "Your agents can still make calls, but you're over budget.";
314
+ let html = "<!DOCTYPE html><html><head><meta charset='utf-8'></head>";
315
+ html += "<body style='margin:0;padding:40px;background:#f5f5f5;font-family:Arial,sans-serif;'>";
316
+ html += "<table width='100%' cellpadding='0' cellspacing='0'><tr><td align='center'>";
317
+ html += "<table width='500' cellpadding='0' cellspacing='0' style='background:#fff;border-radius:12px;'>";
318
+ html += "<tr><td style='padding:32px;text-align:center;'>";
319
+ html += "<div style='font-size:48px;'>🦞</div>";
320
+ html += "<h1 style='margin:16px 0;color:#0a0a0a;'>APIClaw</h1>";
321
+ html += "<h2 style='margin:0 0 16px;font-size:20px;color:#ef4444;'>🚨 Budget Exceeded</h2>";
322
+ html += "<p style='margin:0 0 16px;color:#525252;font-size:16px;'>Your monthly budget has been exceeded.</p>";
323
+ html += "<div style='background:#fee2e2;border:1px solid #ef4444;border-radius:8px;padding:16px;margin-bottom:24px;'>";
324
+ html += "<p style='margin:0;color:#991b1b;font-size:14px;'><strong>Current spend:</strong> $" + currentSpendUsd + " / $" + budgetCapUsd + "</p>";
325
+ html += "</div>";
326
+ html += "<p style='margin:0 0 24px;color:#525252;font-size:14px;'>" + pauseMessage + "</p>";
327
+ html += "<a href='" + settingsUrl + "' style='display:inline-block;background:#ef4444;color:white;padding:14px 32px;border-radius:8px;text-decoration:none;font-weight:600;'>Increase Budget</a>";
328
+ html += "</td></tr></table>";
329
+ html += "</td></tr></table></body></html>";
330
+ const response = await fetch("https://api.resend.com/emails", {
331
+ method: "POST",
332
+ headers: {
333
+ "Authorization": "Bearer " + RESEND_API_KEY,
334
+ "Content-Type": "application/json",
335
+ },
336
+ body: JSON.stringify({
337
+ from: EMAIL_FROM,
338
+ to: args.email,
339
+ subject: "🚨 APIClaw: Monthly Budget Exceeded",
340
+ html: html,
341
+ }),
342
+ });
343
+ if (!response.ok) {
344
+ const errorText = await response.text();
345
+ console.error("Failed to send budget exceeded email:", errorText);
346
+ return { success: false, error: errorText };
347
+ }
348
+ return { success: true };
349
+ },
350
+ });
351
+ // ============================================
352
+ // CRON: Monthly reset
353
+ // ============================================
354
+ /**
355
+ * Reset monthly spend for all workspaces (called by cron on 1st of month)
356
+ */
357
+ export const resetMonthlySpend = internalMutation({
358
+ args: {},
359
+ handler: async (ctx) => {
360
+ const monthStart = getMonthStart();
361
+ // Get all workspaces with spend tracking
362
+ const workspaces = await ctx.db
363
+ .query("workspaces")
364
+ .collect();
365
+ let resetCount = 0;
366
+ for (const workspace of workspaces) {
367
+ if (workspace.monthlySpendCents && workspace.monthlySpendCents > 0) {
368
+ await ctx.db.patch(workspace._id, {
369
+ monthlySpendCents: 0,
370
+ lastSpendResetAt: monthStart,
371
+ budgetAlertSentAt: undefined, // Reset alert flag for new month
372
+ updatedAt: Date.now(),
373
+ });
374
+ resetCount++;
375
+ }
376
+ }
377
+ return { resetCount };
378
+ },
379
+ });