@nordsym/apiclaw 1.3.11 → 1.3.13
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.
- package/PRD-HARDEN-SHELL.md +272 -0
- package/README.md +72 -0
- package/convex/_generated/api.d.ts +2 -0
- package/convex/billing.ts +18 -3
- package/convex/crons.ts +11 -0
- package/convex/earnProgress.ts +1 -1
- package/convex/logs.ts +107 -0
- package/convex/schema.ts +17 -2
- package/convex/spendAlerts.ts +442 -0
- package/convex/workspaces.ts +108 -48
- package/dist/execute.d.ts +5 -0
- package/dist/execute.d.ts.map +1 -1
- package/dist/execute.js +258 -123
- package/dist/execute.js.map +1 -1
- package/docs/PRD-ORGANIC-DISTRIBUTION.md +347 -0
- package/landing/package-lock.json +29 -5
- package/landing/package.json +2 -1
- package/landing/src/app/page.tsx +128 -74
- package/landing/src/app/security/page.tsx +381 -0
- package/landing/src/app/upgrade/page.tsx +10 -10
- package/landing/src/components/AITestimonials.tsx +189 -0
- package/landing/src/lib/stats.json +1 -1
- package/package.json +1 -1
- package/src/execute.ts +315 -119
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
import { v } from "convex/values";
|
|
2
|
+
import { mutation, query, action, internalMutation } from "./_generated/server";
|
|
3
|
+
import { Id } from "./_generated/dataModel";
|
|
4
|
+
import { internal } from "./_generated/api";
|
|
5
|
+
|
|
6
|
+
// ============================================
|
|
7
|
+
// CONSTANTS
|
|
8
|
+
// ============================================
|
|
9
|
+
|
|
10
|
+
const ALERT_THRESHOLD = 0.8; // 80% of budget
|
|
11
|
+
const APP_URL = "https://apiclaw.nordsym.com";
|
|
12
|
+
const EMAIL_FROM = "APIClaw <noreply@apiclaw.nordsym.com>";
|
|
13
|
+
|
|
14
|
+
// ============================================
|
|
15
|
+
// HELPER: Get current month start
|
|
16
|
+
// ============================================
|
|
17
|
+
|
|
18
|
+
function getMonthStart(): number {
|
|
19
|
+
const now = new Date();
|
|
20
|
+
return new Date(now.getUTCFullYear(), now.getUTCMonth(), 1, 0, 0, 0, 0).getTime();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// ============================================
|
|
24
|
+
// MUTATIONS
|
|
25
|
+
// ============================================
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Update workspace budget settings
|
|
29
|
+
*/
|
|
30
|
+
export const updateBudgetSettings = mutation({
|
|
31
|
+
args: {
|
|
32
|
+
workspaceId: v.id("workspaces"),
|
|
33
|
+
budgetCap: v.optional(v.union(v.number(), v.null())), // in USD cents, null = unlimited
|
|
34
|
+
pauseOnBudgetExceeded: v.optional(v.boolean()),
|
|
35
|
+
},
|
|
36
|
+
handler: async (ctx, args) => {
|
|
37
|
+
const workspace = await ctx.db.get(args.workspaceId);
|
|
38
|
+
if (!workspace) {
|
|
39
|
+
throw new Error("Workspace not found");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const updates: Record<string, unknown> = {
|
|
43
|
+
updatedAt: Date.now(),
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
if (args.budgetCap !== undefined) {
|
|
47
|
+
updates.budgetCap = args.budgetCap;
|
|
48
|
+
// Reset alert when budget changes
|
|
49
|
+
updates.budgetAlertSentAt = undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (args.pauseOnBudgetExceeded !== undefined) {
|
|
53
|
+
updates.pauseOnBudgetExceeded = args.pauseOnBudgetExceeded;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
await ctx.db.patch(args.workspaceId, updates);
|
|
57
|
+
|
|
58
|
+
return { success: true };
|
|
59
|
+
},
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Record spend and check budget alerts
|
|
64
|
+
* Called after each successful API execution
|
|
65
|
+
* Returns budget status for response
|
|
66
|
+
*/
|
|
67
|
+
export const recordSpend = mutation({
|
|
68
|
+
args: {
|
|
69
|
+
workspaceId: v.id("workspaces"),
|
|
70
|
+
amountCents: v.number(),
|
|
71
|
+
},
|
|
72
|
+
handler: async (ctx, args) => {
|
|
73
|
+
const workspace = await ctx.db.get(args.workspaceId);
|
|
74
|
+
if (!workspace) {
|
|
75
|
+
throw new Error("Workspace not found");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const monthStart = getMonthStart();
|
|
79
|
+
|
|
80
|
+
// Reset monthly spend if new month
|
|
81
|
+
let currentSpend = workspace.monthlySpendCents || 0;
|
|
82
|
+
if (!workspace.lastSpendResetAt || workspace.lastSpendResetAt < monthStart) {
|
|
83
|
+
currentSpend = 0;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Add new spend
|
|
87
|
+
const newSpend = currentSpend + args.amountCents;
|
|
88
|
+
|
|
89
|
+
// Update workspace
|
|
90
|
+
await ctx.db.patch(args.workspaceId, {
|
|
91
|
+
monthlySpendCents: newSpend,
|
|
92
|
+
lastSpendResetAt: monthStart,
|
|
93
|
+
updatedAt: Date.now(),
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
// Check if we need to send alert
|
|
97
|
+
const budgetCap = workspace.budgetCap;
|
|
98
|
+
let shouldSendAlert = false;
|
|
99
|
+
let budgetExceeded = false;
|
|
100
|
+
|
|
101
|
+
if (budgetCap && budgetCap > 0) {
|
|
102
|
+
const threshold = budgetCap * ALERT_THRESHOLD;
|
|
103
|
+
const alertAlreadySentThisMonth = workspace.budgetAlertSentAt &&
|
|
104
|
+
workspace.budgetAlertSentAt >= monthStart;
|
|
105
|
+
|
|
106
|
+
// Check if at 80% and alert not yet sent
|
|
107
|
+
if (newSpend >= threshold && !alertAlreadySentThisMonth) {
|
|
108
|
+
shouldSendAlert = true;
|
|
109
|
+
await ctx.db.patch(args.workspaceId, {
|
|
110
|
+
budgetAlertSentAt: Date.now(),
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Check if budget exceeded
|
|
115
|
+
if (newSpend >= budgetCap) {
|
|
116
|
+
budgetExceeded = true;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
success: true,
|
|
122
|
+
currentSpendCents: newSpend,
|
|
123
|
+
budgetCapCents: budgetCap || null,
|
|
124
|
+
budgetPercentage: budgetCap ? (newSpend / budgetCap) * 100 : null,
|
|
125
|
+
shouldSendAlert,
|
|
126
|
+
budgetExceeded,
|
|
127
|
+
email: workspace.email,
|
|
128
|
+
};
|
|
129
|
+
},
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Check budget before execution
|
|
134
|
+
* Returns { allowed: boolean, reason?: string }
|
|
135
|
+
*/
|
|
136
|
+
export const checkBudget = query({
|
|
137
|
+
args: {
|
|
138
|
+
workspaceId: v.id("workspaces"),
|
|
139
|
+
estimatedCostCents: v.optional(v.number()),
|
|
140
|
+
},
|
|
141
|
+
handler: async (ctx, args) => {
|
|
142
|
+
const workspace = await ctx.db.get(args.workspaceId);
|
|
143
|
+
if (!workspace) {
|
|
144
|
+
return { allowed: false, reason: "Workspace not found" };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// No budget cap set = unlimited
|
|
148
|
+
if (!workspace.budgetCap || workspace.budgetCap <= 0) {
|
|
149
|
+
return { allowed: true };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Check if pause on exceeded is enabled
|
|
153
|
+
if (!workspace.pauseOnBudgetExceeded) {
|
|
154
|
+
return { allowed: true };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const monthStart = getMonthStart();
|
|
158
|
+
let currentSpend = workspace.monthlySpendCents || 0;
|
|
159
|
+
|
|
160
|
+
// Reset if new month
|
|
161
|
+
if (!workspace.lastSpendResetAt || workspace.lastSpendResetAt < monthStart) {
|
|
162
|
+
currentSpend = 0;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const estimatedCost = args.estimatedCostCents || 0;
|
|
166
|
+
const projectedSpend = currentSpend + estimatedCost;
|
|
167
|
+
|
|
168
|
+
if (projectedSpend > workspace.budgetCap) {
|
|
169
|
+
const budgetCapUsd = (workspace.budgetCap / 100).toFixed(2);
|
|
170
|
+
const currentSpendUsd = (currentSpend / 100).toFixed(2);
|
|
171
|
+
return {
|
|
172
|
+
allowed: false,
|
|
173
|
+
reason: `Budget exceeded. Monthly cap: $${budgetCapUsd}, current spend: $${currentSpendUsd}. Adjust budget in workspace settings.`,
|
|
174
|
+
currentSpendCents: currentSpend,
|
|
175
|
+
budgetCapCents: workspace.budgetCap,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return {
|
|
180
|
+
allowed: true,
|
|
181
|
+
currentSpendCents: currentSpend,
|
|
182
|
+
budgetCapCents: workspace.budgetCap,
|
|
183
|
+
remainingCents: workspace.budgetCap - currentSpend,
|
|
184
|
+
};
|
|
185
|
+
},
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Get budget status for workspace dashboard
|
|
190
|
+
*/
|
|
191
|
+
export const getBudgetStatus = query({
|
|
192
|
+
args: {
|
|
193
|
+
workspaceId: v.id("workspaces"),
|
|
194
|
+
},
|
|
195
|
+
handler: async (ctx, args) => {
|
|
196
|
+
const workspace = await ctx.db.get(args.workspaceId);
|
|
197
|
+
if (!workspace) {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const monthStart = getMonthStart();
|
|
202
|
+
let currentSpend = workspace.monthlySpendCents || 0;
|
|
203
|
+
|
|
204
|
+
// Reset if new month
|
|
205
|
+
if (!workspace.lastSpendResetAt || workspace.lastSpendResetAt < monthStart) {
|
|
206
|
+
currentSpend = 0;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const budgetCap = workspace.budgetCap || null;
|
|
210
|
+
const budgetPercentage = budgetCap ? (currentSpend / budgetCap) * 100 : null;
|
|
211
|
+
|
|
212
|
+
return {
|
|
213
|
+
budgetCapCents: budgetCap,
|
|
214
|
+
budgetCapUsd: budgetCap ? budgetCap / 100 : null,
|
|
215
|
+
currentSpendCents: currentSpend,
|
|
216
|
+
currentSpendUsd: currentSpend / 100,
|
|
217
|
+
remainingCents: budgetCap ? Math.max(0, budgetCap - currentSpend) : null,
|
|
218
|
+
remainingUsd: budgetCap ? Math.max(0, (budgetCap - currentSpend) / 100) : null,
|
|
219
|
+
budgetPercentage: budgetPercentage ? Math.min(100, budgetPercentage) : null,
|
|
220
|
+
pauseOnBudgetExceeded: workspace.pauseOnBudgetExceeded || false,
|
|
221
|
+
isOverBudget: budgetCap ? currentSpend >= budgetCap : false,
|
|
222
|
+
isNearBudget: budgetCap ? currentSpend >= budgetCap * ALERT_THRESHOLD : false,
|
|
223
|
+
alertSentAt: workspace.budgetAlertSentAt || null,
|
|
224
|
+
};
|
|
225
|
+
},
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Get budget status by session token (for dashboard)
|
|
230
|
+
*/
|
|
231
|
+
export const getBudgetStatusByToken = query({
|
|
232
|
+
args: {
|
|
233
|
+
token: v.string(),
|
|
234
|
+
},
|
|
235
|
+
handler: async (ctx, args) => {
|
|
236
|
+
const session = await ctx.db
|
|
237
|
+
.query("agentSessions")
|
|
238
|
+
.withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
|
|
239
|
+
.first();
|
|
240
|
+
|
|
241
|
+
if (!session) {
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const workspace = await ctx.db.get(session.workspaceId);
|
|
246
|
+
if (!workspace) {
|
|
247
|
+
return null;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const monthStart = getMonthStart();
|
|
251
|
+
let currentSpend = workspace.monthlySpendCents || 0;
|
|
252
|
+
|
|
253
|
+
if (!workspace.lastSpendResetAt || workspace.lastSpendResetAt < monthStart) {
|
|
254
|
+
currentSpend = 0;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const budgetCap = workspace.budgetCap || null;
|
|
258
|
+
|
|
259
|
+
return {
|
|
260
|
+
budgetCapCents: budgetCap,
|
|
261
|
+
budgetCapUsd: budgetCap ? budgetCap / 100 : null,
|
|
262
|
+
currentSpendCents: currentSpend,
|
|
263
|
+
currentSpendUsd: currentSpend / 100,
|
|
264
|
+
remainingCents: budgetCap ? Math.max(0, budgetCap - currentSpend) : null,
|
|
265
|
+
remainingUsd: budgetCap ? Math.max(0, (budgetCap - currentSpend) / 100) : null,
|
|
266
|
+
budgetPercentage: budgetCap ? Math.min(100, (currentSpend / budgetCap) * 100) : null,
|
|
267
|
+
pauseOnBudgetExceeded: workspace.pauseOnBudgetExceeded || false,
|
|
268
|
+
isOverBudget: budgetCap ? currentSpend >= budgetCap : false,
|
|
269
|
+
isNearBudget: budgetCap ? currentSpend >= budgetCap * ALERT_THRESHOLD : false,
|
|
270
|
+
};
|
|
271
|
+
},
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
// ============================================
|
|
275
|
+
// EMAIL ACTION
|
|
276
|
+
// ============================================
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Send budget alert email (80% warning)
|
|
280
|
+
*/
|
|
281
|
+
export const sendBudgetAlertEmail = action({
|
|
282
|
+
args: {
|
|
283
|
+
email: v.string(),
|
|
284
|
+
currentSpendCents: v.number(),
|
|
285
|
+
budgetCapCents: v.number(),
|
|
286
|
+
},
|
|
287
|
+
handler: async (ctx, args) => {
|
|
288
|
+
const RESEND_API_KEY = process.env.RESEND_API_KEY;
|
|
289
|
+
if (!RESEND_API_KEY) {
|
|
290
|
+
console.error("RESEND_API_KEY not configured");
|
|
291
|
+
return { success: false, error: "Email not configured" };
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
const currentSpendUsd = (args.currentSpendCents / 100).toFixed(2);
|
|
295
|
+
const budgetCapUsd = (args.budgetCapCents / 100).toFixed(2);
|
|
296
|
+
const percentageUsed = Math.round((args.currentSpendCents / args.budgetCapCents) * 100);
|
|
297
|
+
const settingsUrl = `${APP_URL}/dashboard/settings`;
|
|
298
|
+
|
|
299
|
+
// Build email HTML
|
|
300
|
+
let html = "<!DOCTYPE html><html><head><meta charset='utf-8'></head>";
|
|
301
|
+
html += "<body style='margin:0;padding:40px;background:#f5f5f5;font-family:Arial,sans-serif;'>";
|
|
302
|
+
html += "<table width='100%' cellpadding='0' cellspacing='0'><tr><td align='center'>";
|
|
303
|
+
html += "<table width='500' cellpadding='0' cellspacing='0' style='background:#fff;border-radius:12px;'>";
|
|
304
|
+
html += "<tr><td style='padding:32px;text-align:center;'>";
|
|
305
|
+
html += "<div style='font-size:48px;'>🦞</div>";
|
|
306
|
+
html += "<h1 style='margin:16px 0;color:#0a0a0a;'>APIClaw</h1>";
|
|
307
|
+
html += "<h2 style='margin:0 0 16px;font-size:20px;color:#f59e0b;'>⚠️ Budget Alert</h2>";
|
|
308
|
+
html += "<p style='margin:0 0 16px;color:#525252;font-size:16px;'>You've used <strong>" + percentageUsed + "%</strong> of your monthly budget.</p>";
|
|
309
|
+
html += "<div style='background:#fef3c7;border:1px solid #f59e0b;border-radius:8px;padding:16px;margin-bottom:24px;'>";
|
|
310
|
+
html += "<p style='margin:0;color:#92400e;font-size:14px;'><strong>Current spend:</strong> $" + currentSpendUsd + " / $" + budgetCapUsd + "</p>";
|
|
311
|
+
html += "</div>";
|
|
312
|
+
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>";
|
|
313
|
+
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>";
|
|
314
|
+
html += "</td></tr></table>";
|
|
315
|
+
html += "</td></tr></table></body></html>";
|
|
316
|
+
|
|
317
|
+
const textContent = `APIClaw Budget Alert\n\nYou've used ${percentageUsed}% of your monthly budget.\nCurrent spend: $${currentSpendUsd} / $${budgetCapUsd}\n\nAdjust your budget: ${settingsUrl}`;
|
|
318
|
+
|
|
319
|
+
const response = await fetch("https://api.resend.com/emails", {
|
|
320
|
+
method: "POST",
|
|
321
|
+
headers: {
|
|
322
|
+
"Authorization": "Bearer " + RESEND_API_KEY,
|
|
323
|
+
"Content-Type": "application/json",
|
|
324
|
+
},
|
|
325
|
+
body: JSON.stringify({
|
|
326
|
+
from: EMAIL_FROM,
|
|
327
|
+
to: args.email,
|
|
328
|
+
subject: "⚠️ APIClaw: 80% of Monthly Budget Used",
|
|
329
|
+
html: html,
|
|
330
|
+
text: textContent,
|
|
331
|
+
}),
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
if (!response.ok) {
|
|
335
|
+
const errorText = await response.text();
|
|
336
|
+
console.error("Failed to send budget alert email:", errorText);
|
|
337
|
+
return { success: false, error: errorText };
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
return { success: true };
|
|
341
|
+
},
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Send budget exceeded email
|
|
346
|
+
*/
|
|
347
|
+
export const sendBudgetExceededEmail = action({
|
|
348
|
+
args: {
|
|
349
|
+
email: v.string(),
|
|
350
|
+
currentSpendCents: v.number(),
|
|
351
|
+
budgetCapCents: v.number(),
|
|
352
|
+
isPaused: v.boolean(),
|
|
353
|
+
},
|
|
354
|
+
handler: async (ctx, args) => {
|
|
355
|
+
const RESEND_API_KEY = process.env.RESEND_API_KEY;
|
|
356
|
+
if (!RESEND_API_KEY) {
|
|
357
|
+
console.error("RESEND_API_KEY not configured");
|
|
358
|
+
return { success: false, error: "Email not configured" };
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const currentSpendUsd = (args.currentSpendCents / 100).toFixed(2);
|
|
362
|
+
const budgetCapUsd = (args.budgetCapCents / 100).toFixed(2);
|
|
363
|
+
const settingsUrl = `${APP_URL}/dashboard/settings`;
|
|
364
|
+
|
|
365
|
+
const pauseMessage = args.isPaused
|
|
366
|
+
? "API execution has been paused. Increase your budget or disable pause-on-exceed to continue."
|
|
367
|
+
: "Your agents can still make calls, but you're over budget.";
|
|
368
|
+
|
|
369
|
+
let html = "<!DOCTYPE html><html><head><meta charset='utf-8'></head>";
|
|
370
|
+
html += "<body style='margin:0;padding:40px;background:#f5f5f5;font-family:Arial,sans-serif;'>";
|
|
371
|
+
html += "<table width='100%' cellpadding='0' cellspacing='0'><tr><td align='center'>";
|
|
372
|
+
html += "<table width='500' cellpadding='0' cellspacing='0' style='background:#fff;border-radius:12px;'>";
|
|
373
|
+
html += "<tr><td style='padding:32px;text-align:center;'>";
|
|
374
|
+
html += "<div style='font-size:48px;'>🦞</div>";
|
|
375
|
+
html += "<h1 style='margin:16px 0;color:#0a0a0a;'>APIClaw</h1>";
|
|
376
|
+
html += "<h2 style='margin:0 0 16px;font-size:20px;color:#ef4444;'>🚨 Budget Exceeded</h2>";
|
|
377
|
+
html += "<p style='margin:0 0 16px;color:#525252;font-size:16px;'>Your monthly budget has been exceeded.</p>";
|
|
378
|
+
html += "<div style='background:#fee2e2;border:1px solid #ef4444;border-radius:8px;padding:16px;margin-bottom:24px;'>";
|
|
379
|
+
html += "<p style='margin:0;color:#991b1b;font-size:14px;'><strong>Current spend:</strong> $" + currentSpendUsd + " / $" + budgetCapUsd + "</p>";
|
|
380
|
+
html += "</div>";
|
|
381
|
+
html += "<p style='margin:0 0 24px;color:#525252;font-size:14px;'>" + pauseMessage + "</p>";
|
|
382
|
+
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>";
|
|
383
|
+
html += "</td></tr></table>";
|
|
384
|
+
html += "</td></tr></table></body></html>";
|
|
385
|
+
|
|
386
|
+
const response = await fetch("https://api.resend.com/emails", {
|
|
387
|
+
method: "POST",
|
|
388
|
+
headers: {
|
|
389
|
+
"Authorization": "Bearer " + RESEND_API_KEY,
|
|
390
|
+
"Content-Type": "application/json",
|
|
391
|
+
},
|
|
392
|
+
body: JSON.stringify({
|
|
393
|
+
from: EMAIL_FROM,
|
|
394
|
+
to: args.email,
|
|
395
|
+
subject: "🚨 APIClaw: Monthly Budget Exceeded",
|
|
396
|
+
html: html,
|
|
397
|
+
}),
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
if (!response.ok) {
|
|
401
|
+
const errorText = await response.text();
|
|
402
|
+
console.error("Failed to send budget exceeded email:", errorText);
|
|
403
|
+
return { success: false, error: errorText };
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
return { success: true };
|
|
407
|
+
},
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
// ============================================
|
|
411
|
+
// CRON: Monthly reset
|
|
412
|
+
// ============================================
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Reset monthly spend for all workspaces (called by cron on 1st of month)
|
|
416
|
+
*/
|
|
417
|
+
export const resetMonthlySpend = internalMutation({
|
|
418
|
+
args: {},
|
|
419
|
+
handler: async (ctx) => {
|
|
420
|
+
const monthStart = getMonthStart();
|
|
421
|
+
|
|
422
|
+
// Get all workspaces with spend tracking
|
|
423
|
+
const workspaces = await ctx.db
|
|
424
|
+
.query("workspaces")
|
|
425
|
+
.collect();
|
|
426
|
+
|
|
427
|
+
let resetCount = 0;
|
|
428
|
+
for (const workspace of workspaces) {
|
|
429
|
+
if (workspace.monthlySpendCents && workspace.monthlySpendCents > 0) {
|
|
430
|
+
await ctx.db.patch(workspace._id, {
|
|
431
|
+
monthlySpendCents: 0,
|
|
432
|
+
lastSpendResetAt: monthStart,
|
|
433
|
+
budgetAlertSentAt: undefined, // Reset alert flag for new month
|
|
434
|
+
updatedAt: Date.now(),
|
|
435
|
+
});
|
|
436
|
+
resetCount++;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
return { resetCount };
|
|
441
|
+
},
|
|
442
|
+
});
|
package/convex/workspaces.ts
CHANGED
|
@@ -94,7 +94,10 @@ export const verifyMagicLink = mutation({
|
|
|
94
94
|
status: "active",
|
|
95
95
|
tier: "free",
|
|
96
96
|
usageCount: 0,
|
|
97
|
-
usageLimit: 50, //
|
|
97
|
+
usageLimit: 50, // Legacy field, now using weekly limits
|
|
98
|
+
weeklyUsageCount: 0,
|
|
99
|
+
weeklyUsageLimit: 50, // 50 calls/week for free tier
|
|
100
|
+
hourlyUsageCount: 0,
|
|
98
101
|
referralCode: newReferralCode!,
|
|
99
102
|
createdAt: Date.now(),
|
|
100
103
|
updatedAt: Date.now(),
|
|
@@ -102,56 +105,21 @@ export const verifyMagicLink = mutation({
|
|
|
102
105
|
workspace = await ctx.db.get(workspaceId);
|
|
103
106
|
}
|
|
104
107
|
|
|
105
|
-
//
|
|
108
|
+
// REFERRAL DISABLED (2026-03-01): Risk of abuse with awesome-list exposure
|
|
109
|
+
// Tracking referredBy for analytics only, no credit bonus
|
|
106
110
|
if (isNewUser && referralCode) {
|
|
107
|
-
// Find referrer by code
|
|
108
111
|
const referrer = await ctx.db
|
|
109
112
|
.query("workspaces")
|
|
110
113
|
.withIndex("by_referralCode", (q) => q.eq("referralCode", referralCode))
|
|
111
114
|
.first();
|
|
112
115
|
|
|
113
116
|
if (referrer && referrer._id !== workspace!._id) {
|
|
114
|
-
//
|
|
117
|
+
// Track referral for analytics only
|
|
115
118
|
await ctx.db.patch(workspace!._id, {
|
|
116
119
|
referredBy: referrer._id,
|
|
117
120
|
updatedAt: Date.now(),
|
|
118
121
|
});
|
|
119
|
-
|
|
120
|
-
// Get or create referrer's earn progress
|
|
121
|
-
let referrerProgress = await ctx.db
|
|
122
|
-
.query("earnProgress")
|
|
123
|
-
.withIndex("by_workspaceId", (q) => q.eq("workspaceId", referrer._id))
|
|
124
|
-
.first();
|
|
125
|
-
|
|
126
|
-
if (!referrerProgress) {
|
|
127
|
-
await ctx.db.insert("earnProgress", {
|
|
128
|
-
workspaceId: referrer._id,
|
|
129
|
-
firstDirectCall: false,
|
|
130
|
-
apisUsed: [],
|
|
131
|
-
apisUsedComplete: false,
|
|
132
|
-
agentListed: false,
|
|
133
|
-
apiListed: false,
|
|
134
|
-
byokSetup: false,
|
|
135
|
-
githubStarred: false,
|
|
136
|
-
twitterFollowed: false,
|
|
137
|
-
referralCount: 1,
|
|
138
|
-
totalEarned: 10,
|
|
139
|
-
createdAt: Date.now(),
|
|
140
|
-
updatedAt: Date.now(),
|
|
141
|
-
});
|
|
142
|
-
} else {
|
|
143
|
-
await ctx.db.patch(referrerProgress._id, {
|
|
144
|
-
referralCount: referrerProgress.referralCount + 1,
|
|
145
|
-
totalEarned: referrerProgress.totalEarned + 10,
|
|
146
|
-
updatedAt: Date.now(),
|
|
147
|
-
});
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
// Credit referrer with +10 API calls
|
|
151
|
-
await ctx.db.patch(referrer._id, {
|
|
152
|
-
usageLimit: referrer.usageLimit + 10,
|
|
153
|
-
updatedAt: Date.now(),
|
|
154
|
-
});
|
|
122
|
+
// No credit bonus - referral rewards disabled
|
|
155
123
|
}
|
|
156
124
|
}
|
|
157
125
|
|
|
@@ -258,6 +226,14 @@ export const getWorkspaceDashboard = query({
|
|
|
258
226
|
const usageRemaining = workspace.usageLimit - workspace.usageCount;
|
|
259
227
|
const usagePercentage = (workspace.usageCount / workspace.usageLimit) * 100;
|
|
260
228
|
|
|
229
|
+
// Budget status (PRD 2.6)
|
|
230
|
+
const monthStart = getMonthStartForBudget();
|
|
231
|
+
let currentSpend = workspace.monthlySpendCents || 0;
|
|
232
|
+
if (!workspace.lastSpendResetAt || workspace.lastSpendResetAt < monthStart) {
|
|
233
|
+
currentSpend = 0;
|
|
234
|
+
}
|
|
235
|
+
const budgetCap = workspace.budgetCap || null;
|
|
236
|
+
|
|
261
237
|
return {
|
|
262
238
|
workspace: {
|
|
263
239
|
id: workspace._id,
|
|
@@ -276,10 +252,28 @@ export const getWorkspaceDashboard = query({
|
|
|
276
252
|
totalCredits: workspaceCredits.reduce((sum, c) => sum + c.balanceUsd, 0),
|
|
277
253
|
totalPurchases: workspacePurchases.length,
|
|
278
254
|
},
|
|
255
|
+
budget: {
|
|
256
|
+
budgetCapCents: budgetCap,
|
|
257
|
+
budgetCapUsd: budgetCap ? budgetCap / 100 : null,
|
|
258
|
+
currentSpendCents: currentSpend,
|
|
259
|
+
currentSpendUsd: currentSpend / 100,
|
|
260
|
+
remainingCents: budgetCap ? Math.max(0, budgetCap - currentSpend) : null,
|
|
261
|
+
remainingUsd: budgetCap ? Math.max(0, (budgetCap - currentSpend) / 100) : null,
|
|
262
|
+
budgetPercentage: budgetCap ? Math.min(100, (currentSpend / budgetCap) * 100) : null,
|
|
263
|
+
pauseOnBudgetExceeded: workspace.pauseOnBudgetExceeded || false,
|
|
264
|
+
isOverBudget: budgetCap ? currentSpend >= budgetCap : false,
|
|
265
|
+
isNearBudget: budgetCap ? currentSpend >= budgetCap * 0.8 : false,
|
|
266
|
+
},
|
|
279
267
|
};
|
|
280
268
|
},
|
|
281
269
|
});
|
|
282
270
|
|
|
271
|
+
// Helper for budget month start
|
|
272
|
+
function getMonthStartForBudget(): number {
|
|
273
|
+
const now = new Date();
|
|
274
|
+
return new Date(now.getUTCFullYear(), now.getUTCMonth(), 1, 0, 0, 0, 0).getTime();
|
|
275
|
+
}
|
|
276
|
+
|
|
283
277
|
// Get connected agents for workspace
|
|
284
278
|
export const getConnectedAgents = query({
|
|
285
279
|
args: { token: v.string() },
|
|
@@ -537,6 +531,29 @@ export const updateTier = mutation({
|
|
|
537
531
|
});
|
|
538
532
|
|
|
539
533
|
// Increment usage count
|
|
534
|
+
// Constants for rate limiting
|
|
535
|
+
const FREE_WEEKLY_LIMIT = 50;
|
|
536
|
+
const FREE_HOURLY_LIMIT = 10;
|
|
537
|
+
const BACKER_END_DATE = new Date("2026-12-31T23:59:59Z").getTime();
|
|
538
|
+
|
|
539
|
+
// Helper: Get start of current week (Monday 00:00 UTC)
|
|
540
|
+
function getWeekStart(): number {
|
|
541
|
+
const now = new Date();
|
|
542
|
+
const dayOfWeek = now.getUTCDay();
|
|
543
|
+
const diff = dayOfWeek === 0 ? 6 : dayOfWeek - 1; // Monday = 0
|
|
544
|
+
const monday = new Date(now);
|
|
545
|
+
monday.setUTCDate(now.getUTCDate() - diff);
|
|
546
|
+
monday.setUTCHours(0, 0, 0, 0);
|
|
547
|
+
return monday.getTime();
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// Helper: Get start of current hour
|
|
551
|
+
function getHourStart(): number {
|
|
552
|
+
const now = new Date();
|
|
553
|
+
now.setUTCMinutes(0, 0, 0);
|
|
554
|
+
return now.getTime();
|
|
555
|
+
}
|
|
556
|
+
|
|
540
557
|
export const incrementUsage = mutation({
|
|
541
558
|
args: {
|
|
542
559
|
workspaceId: v.id("workspaces"),
|
|
@@ -548,22 +565,65 @@ export const incrementUsage = mutation({
|
|
|
548
565
|
throw new Error("Workspace not found");
|
|
549
566
|
}
|
|
550
567
|
|
|
551
|
-
const
|
|
568
|
+
const now = Date.now();
|
|
569
|
+
const weekStart = getWeekStart();
|
|
570
|
+
const hourStart = getHourStart();
|
|
571
|
+
|
|
572
|
+
// Check if Backer (unlimited until end of 2026)
|
|
573
|
+
const isBacker = workspace.tier === "backer" ||
|
|
574
|
+
(workspace.backerUntil && workspace.backerUntil > now);
|
|
575
|
+
|
|
576
|
+
// Initialize weekly/hourly counters if needed
|
|
577
|
+
let weeklyCount = workspace.weeklyUsageCount || 0;
|
|
578
|
+
let hourlyCount = workspace.hourlyUsageCount || 0;
|
|
552
579
|
|
|
553
|
-
//
|
|
554
|
-
if (
|
|
555
|
-
|
|
580
|
+
// Reset weekly counter if new week
|
|
581
|
+
if (!workspace.lastWeeklyResetAt || workspace.lastWeeklyResetAt < weekStart) {
|
|
582
|
+
weeklyCount = 0;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// Reset hourly counter if new hour
|
|
586
|
+
if (!workspace.lastHourlyResetAt || workspace.lastHourlyResetAt < hourStart) {
|
|
587
|
+
hourlyCount = 0;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// Check rate limits for free tier
|
|
591
|
+
if (!isBacker && workspace.tier !== "pro" && workspace.tier !== "enterprise") {
|
|
592
|
+
// Check hourly limit (10/hour for free)
|
|
593
|
+
if (hourlyCount + amount > FREE_HOURLY_LIMIT) {
|
|
594
|
+
throw new Error(`Hourly rate limit exceeded (${FREE_HOURLY_LIMIT}/hour). Upgrade to Backer for unlimited.`);
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// Check weekly limit (50/week for free)
|
|
598
|
+
if (weeklyCount + amount > FREE_WEEKLY_LIMIT) {
|
|
599
|
+
throw new Error(`Weekly limit exceeded (${FREE_WEEKLY_LIMIT}/week). Upgrade to Backer for unlimited.`);
|
|
600
|
+
}
|
|
556
601
|
}
|
|
557
602
|
|
|
603
|
+
const newTotalCount = workspace.usageCount + amount;
|
|
604
|
+
const newWeeklyCount = weeklyCount + amount;
|
|
605
|
+
const newHourlyCount = hourlyCount + amount;
|
|
606
|
+
|
|
558
607
|
await ctx.db.patch(workspaceId, {
|
|
559
|
-
usageCount:
|
|
560
|
-
|
|
608
|
+
usageCount: newTotalCount,
|
|
609
|
+
weeklyUsageCount: newWeeklyCount,
|
|
610
|
+
hourlyUsageCount: newHourlyCount,
|
|
611
|
+
lastWeeklyResetAt: weekStart,
|
|
612
|
+
lastHourlyResetAt: hourStart,
|
|
613
|
+
updatedAt: now,
|
|
561
614
|
});
|
|
562
615
|
|
|
616
|
+
// Calculate remaining for free tier
|
|
617
|
+
const weeklyRemaining = isBacker ? Infinity : Math.max(0, FREE_WEEKLY_LIMIT - newWeeklyCount);
|
|
618
|
+
const hourlyRemaining = isBacker ? Infinity : Math.max(0, FREE_HOURLY_LIMIT - newHourlyCount);
|
|
619
|
+
|
|
563
620
|
return {
|
|
564
621
|
success: true,
|
|
565
|
-
usageCount:
|
|
566
|
-
|
|
622
|
+
usageCount: newTotalCount,
|
|
623
|
+
weeklyUsageCount: newWeeklyCount,
|
|
624
|
+
weeklyRemaining,
|
|
625
|
+
hourlyRemaining,
|
|
626
|
+
isBacker,
|
|
567
627
|
};
|
|
568
628
|
},
|
|
569
629
|
});
|
package/dist/execute.d.ts
CHANGED
package/dist/execute.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execute.d.ts","sourceRoot":"","sources":["../src/execute.ts"],"names":[],"mappings":"AAAA;;GAEG;AAMH,UAAU,aAAa;IACrB,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"execute.d.ts","sourceRoot":"","sources":["../src/execute.ts"],"names":[],"mappings":"AAAA;;GAEG;AAMH,UAAU,aAAa;IACrB,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IAEd,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAiLD,UAAU,YAAY;IACpB,OAAO,EAAE,IAAI,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE;QACV,GAAG,EAAE,MAAM,CAAC;QACZ,MAAM,EAAE,MAAM,CAAC;QACf,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAChC,IAAI,CAAC,EAAE,OAAO,CAAC;KAChB,CAAC;IACF,aAAa,EAAE;QACb,OAAO,EAAE,OAAO,CAAC;QACjB,IAAI,EAAE,OAAO,CAAC;QACd,cAAc,CAAC,EAAE,MAAM,CAAC;KACzB,CAAC;IACF,KAAK,EAAE,MAAM,EAAE,CAAC;CACjB;AAyKD;;GAEG;AACH,wBAAgB,cAAc,CAC5B,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAC1B,YAAY,CA8Dd;AA8tBD,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,EAAE,CAE/D;AAGD,wBAAsB,uBAAuB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CASnF;AAGD,wBAAgB,qBAAqB,IAAI;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAA;CAAE,EAAE,CAKjF;AAGD,wBAAsB,cAAc,CAClC,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC3B,MAAM,CAAC,EAAE,MAAM,EACf,WAAW,CAAC,EAAE,MAAM,GACnB,OAAO,CAAC,aAAa,CAAC,CAkGxB"}
|