@nordsym/apiclaw 1.5.17 → 1.5.19

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 (228) hide show
  1. package/convex/http.js.map +1 -1
  2. package/convex/http.ts +516 -0
  3. package/dist/analytics.d.ts +0 -4
  4. package/dist/analytics.d.ts.map +1 -1
  5. package/dist/analytics.js +0 -1
  6. package/dist/analytics.js.map +1 -1
  7. package/dist/bin.js +1 -1
  8. package/dist/cli/commands/mcp-install.d.ts.map +1 -1
  9. package/dist/cli/commands/mcp-install.js +8 -87
  10. package/dist/cli/commands/mcp-install.js.map +1 -1
  11. package/dist/cli/index.js +0 -7
  12. package/dist/credentials.d.ts.map +1 -1
  13. package/dist/credentials.js +38 -43
  14. package/dist/credentials.js.map +1 -1
  15. package/dist/discovery.d.ts.map +1 -1
  16. package/dist/discovery.js +82 -191
  17. package/dist/discovery.js.map +1 -1
  18. package/dist/http-api.d.ts.map +1 -1
  19. package/dist/http-api.js +33 -17
  20. package/dist/http-api.js.map +1 -1
  21. package/dist/proxy.js +1 -1
  22. package/dist/proxy.js.map +1 -1
  23. package/landing/next-env.d.ts +0 -1
  24. package/landing/src/app/api/auth/magic-link/route.ts +1 -1
  25. package/landing/src/app/auth/verify/page.tsx +0 -6
  26. package/landing/src/app/dashboard/verify/page.tsx +0 -6
  27. package/landing/src/app/join/page.tsx +0 -6
  28. package/landing/src/app/layout.tsx +2 -2
  29. package/landing/src/app/login/page.tsx +1 -1
  30. package/landing/src/app/mou/[partnerId]/page.tsx +0 -6
  31. package/landing/src/app/page.tsx +18 -39
  32. package/landing/src/app/providers/dashboard/[apiId]/actions/[actionId]/edit/page.tsx +0 -6
  33. package/landing/src/app/providers/dashboard/[apiId]/actions/new/page.tsx +0 -5
  34. package/landing/src/app/providers/dashboard/[apiId]/actions/page.tsx +0 -5
  35. package/landing/src/app/providers/dashboard/[apiId]/direct-call/page.tsx +1 -6
  36. package/landing/src/app/providers/dashboard/[apiId]/page.tsx +0 -5
  37. package/landing/src/app/providers/dashboard/[apiId]/test/page.tsx +0 -5
  38. package/landing/src/app/providers/dashboard/layout.tsx +6 -6
  39. package/landing/src/app/providers/dashboard/login/page.tsx +1 -1
  40. package/landing/src/app/providers/dashboard/page.tsx +1 -1
  41. package/landing/src/app/providers/dashboard/verify/page.tsx +0 -6
  42. package/landing/src/app/providers/layout.tsx +1 -1
  43. package/landing/src/app/upgrade/page.tsx +0 -6
  44. package/landing/src/app/workspace/page.tsx +0 -6
  45. package/landing/src/components/HeroTabs.tsx +2 -2
  46. package/landing/src/components/{Workspace.tsx → ProviderDashboard.tsx} +2 -2
  47. package/landing/src/components/VideoDemo.tsx +10 -21
  48. package/landing/src/lib/mock-data.ts +1 -1
  49. package/landing/src/lib/stats.json +1 -1
  50. package/package.json +3 -8
  51. package/src/analytics.ts +0 -5
  52. package/src/bin.ts +1 -1
  53. package/src/cli/commands/mcp-install.ts +8 -90
  54. package/src/cli/index.ts +0 -8
  55. package/src/credentials.ts +39 -44
  56. package/src/discovery.ts +82 -191
  57. package/src/http-api.ts +34 -18
  58. package/src/proxy.ts +1 -1
  59. package/APILAYER_STATUS_2026-03-24.md +0 -38
  60. package/CHANGELOG-WHITELIST-V2.md +0 -269
  61. package/HIVR-WHITELIST-STATUS.md +0 -205
  62. package/HIVR-WHITELIST.md +0 -148
  63. package/TERMINOLOGY-AUDIT.md +0 -99
  64. package/TERMINOLOGY-FIXED.md +0 -74
  65. package/VIDEO-DEMO-GUIDE.md +0 -82
  66. package/WHITELIST-ARCHITECTURE.md +0 -379
  67. package/api/discover.ts +0 -71
  68. package/api/health.ts +0 -20
  69. package/convex/adminActivate.d.ts +0 -3
  70. package/convex/adminActivate.js +0 -47
  71. package/convex/adminStats.d.ts +0 -3
  72. package/convex/adminStats.js +0 -42
  73. package/convex/agents.d.ts +0 -54
  74. package/convex/agents.js +0 -499
  75. package/convex/analytics.d.ts +0 -5
  76. package/convex/analytics.js +0 -166
  77. package/convex/billing.d.ts +0 -88
  78. package/convex/billing.js +0 -655
  79. package/convex/capabilities.d.ts +0 -9
  80. package/convex/capabilities.js +0 -145
  81. package/convex/chains.d.ts +0 -67
  82. package/convex/chains.js +0 -1042
  83. package/convex/credits.d.ts +0 -25
  84. package/convex/credits.js +0 -186
  85. package/convex/crons.d.ts +0 -3
  86. package/convex/crons.js +0 -17
  87. package/convex/directCall.d.ts +0 -72
  88. package/convex/directCall.js +0 -627
  89. package/convex/earnProgress.d.ts +0 -58
  90. package/convex/earnProgress.js +0 -649
  91. package/convex/email.d.ts +0 -14
  92. package/convex/email.js +0 -300
  93. package/convex/feedback.d.ts +0 -7
  94. package/convex/feedback.js +0 -227
  95. package/convex/http.d.ts +0 -3
  96. package/convex/http.js +0 -910
  97. package/convex/logs.d.ts +0 -38
  98. package/convex/logs.js +0 -487
  99. package/convex/mou.d.ts +0 -6
  100. package/convex/mou.js +0 -82
  101. package/convex/providerKeys.d.ts +0 -31
  102. package/convex/providerKeys.js +0 -257
  103. package/convex/providers.d.ts +0 -29
  104. package/convex/providers.js +0 -756
  105. package/convex/purchases.d.ts +0 -7
  106. package/convex/purchases.js +0 -157
  107. package/convex/ratelimit.d.ts +0 -4
  108. package/convex/ratelimit.js +0 -91
  109. package/convex/searchLogs.d.ts +0 -4
  110. package/convex/searchLogs.js +0 -129
  111. package/convex/spendAlerts.d.ts +0 -36
  112. package/convex/spendAlerts.js +0 -380
  113. package/convex/stripeActions.d.ts +0 -19
  114. package/convex/stripeActions.js +0 -411
  115. package/convex/teams.d.ts +0 -21
  116. package/convex/teams.js +0 -215
  117. package/convex/telemetry.d.ts +0 -4
  118. package/convex/telemetry.js +0 -74
  119. package/convex/usage.d.ts +0 -27
  120. package/convex/usage.js +0 -229
  121. package/convex/waitlist.d.ts +0 -4
  122. package/convex/waitlist.js +0 -49
  123. package/convex/webhooks.d.ts +0 -12
  124. package/convex/webhooks.js +0 -410
  125. package/convex/workspaces.d.ts +0 -29
  126. package/convex/workspaces.js +0 -880
  127. package/direct-test.mjs +0 -51
  128. package/dist/access-control.d.ts +0 -45
  129. package/dist/access-control.d.ts.map +0 -1
  130. package/dist/access-control.js +0 -142
  131. package/dist/access-control.js.map +0 -1
  132. package/dist/chain-types.d.ts +0 -187
  133. package/dist/chain-types.d.ts.map +0 -1
  134. package/dist/chain-types.js +0 -33
  135. package/dist/chain-types.js.map +0 -1
  136. package/dist/convex/adminActivate.js +0 -46
  137. package/dist/convex/adminStats.js +0 -41
  138. package/dist/convex/agents.js +0 -498
  139. package/dist/convex/analytics.js +0 -165
  140. package/dist/convex/billing.js +0 -654
  141. package/dist/convex/capabilities.js +0 -144
  142. package/dist/convex/chains.js +0 -1041
  143. package/dist/convex/credits.js +0 -185
  144. package/dist/convex/crons.js +0 -16
  145. package/dist/convex/directCall.js +0 -626
  146. package/dist/convex/earnProgress.js +0 -648
  147. package/dist/convex/email.js +0 -299
  148. package/dist/convex/feedback.js +0 -226
  149. package/dist/convex/http.js +0 -909
  150. package/dist/convex/logs.js +0 -486
  151. package/dist/convex/mou.js +0 -81
  152. package/dist/convex/providerKeys.js +0 -256
  153. package/dist/convex/providers.js +0 -755
  154. package/dist/convex/purchases.js +0 -156
  155. package/dist/convex/ratelimit.js +0 -90
  156. package/dist/convex/schema.js +0 -709
  157. package/dist/convex/searchLogs.js +0 -128
  158. package/dist/convex/spendAlerts.js +0 -379
  159. package/dist/convex/stripeActions.js +0 -410
  160. package/dist/convex/teams.js +0 -214
  161. package/dist/convex/telemetry.js +0 -73
  162. package/dist/convex/usage.js +0 -228
  163. package/dist/convex/waitlist.js +0 -48
  164. package/dist/convex/webhooks.js +0 -409
  165. package/dist/convex/workspaces.js +0 -879
  166. package/dist/hivr-whitelist.d.ts +0 -18
  167. package/dist/hivr-whitelist.d.ts.map +0 -1
  168. package/dist/hivr-whitelist.js +0 -95
  169. package/dist/hivr-whitelist.js.map +0 -1
  170. package/dist/http-server-minimal.d.ts +0 -7
  171. package/dist/http-server-minimal.d.ts.map +0 -1
  172. package/dist/http-server-minimal.js +0 -126
  173. package/dist/http-server-minimal.js.map +0 -1
  174. package/dist/product-whitelist.d.ts +0 -37
  175. package/dist/product-whitelist.d.ts.map +0 -1
  176. package/dist/product-whitelist.js +0 -203
  177. package/dist/product-whitelist.js.map +0 -1
  178. package/dist/src/analytics.js +0 -129
  179. package/dist/src/bin.js +0 -17
  180. package/dist/src/capability-router.js +0 -240
  181. package/dist/src/chainExecutor.js +0 -451
  182. package/dist/src/chainResolver.js +0 -518
  183. package/dist/src/cli/commands/doctor.js +0 -324
  184. package/dist/src/cli/commands/mcp-install.js +0 -255
  185. package/dist/src/cli/commands/restore.js +0 -259
  186. package/dist/src/cli/commands/setup.js +0 -205
  187. package/dist/src/cli/commands/uninstall.js +0 -188
  188. package/dist/src/cli/index.js +0 -111
  189. package/dist/src/cli.js +0 -302
  190. package/dist/src/confirmation.js +0 -240
  191. package/dist/src/credentials.js +0 -357
  192. package/dist/src/credits.js +0 -260
  193. package/dist/src/crypto.js +0 -66
  194. package/dist/src/discovery.js +0 -504
  195. package/dist/src/enterprise/env.js +0 -123
  196. package/dist/src/enterprise/script-generator.js +0 -460
  197. package/dist/src/execute-dynamic.js +0 -473
  198. package/dist/src/execute.js +0 -1727
  199. package/dist/src/index.js +0 -2062
  200. package/dist/src/metered.js +0 -80
  201. package/dist/src/open-apis.js +0 -276
  202. package/dist/src/proxy.js +0 -28
  203. package/dist/src/session.js +0 -86
  204. package/dist/src/stripe.js +0 -407
  205. package/dist/src/telemetry.js +0 -49
  206. package/dist/src/types.js +0 -2
  207. package/dist/src/utils/backup.js +0 -181
  208. package/dist/src/utils/config.js +0 -220
  209. package/dist/src/utils/os.js +0 -105
  210. package/dist/src/utils/paths.js +0 -159
  211. package/landing/pages/api/discover.ts +0 -43
  212. package/landing/pages/api/health.ts +0 -20
  213. package/scripts/test-whitelist-v2.sh +0 -128
  214. package/src/access-control.ts +0 -174
  215. package/src/hivr-whitelist.ts +0 -110
  216. package/src/http-server-minimal.ts +0 -154
  217. package/src/product-whitelist.ts +0 -246
  218. package/test-actual-handlers.ts +0 -92
  219. package/test-apilayer-all-14.ts +0 -249
  220. package/test-apilayer-fixed.ts +0 -248
  221. package/test-direct-endpoints.ts +0 -174
  222. package/test-exact-endpoints.ts +0 -144
  223. package/test-final.ts +0 -83
  224. package/test-full-routing.ts +0 -100
  225. package/test-handlers-correct.ts +0 -217
  226. package/test-numverify-key.ts +0 -41
  227. package/test-via-handlers.ts +0 -92
  228. package/test-worldnews.mjs +0 -26
@@ -1,128 +0,0 @@
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
- });
@@ -1,379 +0,0 @@
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
- });