@nordsym/apiclaw 1.5.18 → 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 (66) hide show
  1. package/convex/http.js.map +1 -1
  2. package/convex/http.ts +315 -0
  3. package/dist/credentials.d.ts.map +1 -1
  4. package/dist/credentials.js +123 -0
  5. package/dist/credentials.js.map +1 -1
  6. package/package.json +2 -2
  7. package/src/credentials.ts +131 -0
  8. package/convex/adminActivate.d.ts +0 -3
  9. package/convex/adminActivate.js +0 -47
  10. package/convex/adminStats.d.ts +0 -3
  11. package/convex/adminStats.js +0 -42
  12. package/convex/agents.d.ts +0 -54
  13. package/convex/agents.js +0 -499
  14. package/convex/analytics.d.ts +0 -5
  15. package/convex/analytics.js +0 -166
  16. package/convex/billing.d.ts +0 -88
  17. package/convex/billing.js +0 -655
  18. package/convex/capabilities.d.ts +0 -9
  19. package/convex/capabilities.js +0 -145
  20. package/convex/chains.d.ts +0 -67
  21. package/convex/chains.js +0 -1042
  22. package/convex/credits.d.ts +0 -25
  23. package/convex/credits.js +0 -186
  24. package/convex/crons.d.ts +0 -3
  25. package/convex/crons.js +0 -17
  26. package/convex/directCall.d.ts +0 -72
  27. package/convex/directCall.js +0 -627
  28. package/convex/earnProgress.d.ts +0 -58
  29. package/convex/earnProgress.js +0 -649
  30. package/convex/email.d.ts +0 -14
  31. package/convex/email.js +0 -300
  32. package/convex/feedback.d.ts +0 -7
  33. package/convex/feedback.js +0 -227
  34. package/convex/http.d.ts +0 -3
  35. package/convex/http.js +0 -1106
  36. package/convex/http.ts.bak +0 -934
  37. package/convex/logs.d.ts +0 -38
  38. package/convex/logs.js +0 -487
  39. package/convex/mou.d.ts +0 -6
  40. package/convex/mou.js +0 -82
  41. package/convex/providerKeys.d.ts +0 -31
  42. package/convex/providerKeys.js +0 -257
  43. package/convex/providers.d.ts +0 -29
  44. package/convex/providers.js +0 -756
  45. package/convex/purchases.d.ts +0 -7
  46. package/convex/purchases.js +0 -157
  47. package/convex/ratelimit.d.ts +0 -4
  48. package/convex/ratelimit.js +0 -91
  49. package/convex/searchLogs.d.ts +0 -4
  50. package/convex/searchLogs.js +0 -129
  51. package/convex/spendAlerts.d.ts +0 -36
  52. package/convex/spendAlerts.js +0 -380
  53. package/convex/stripeActions.d.ts +0 -19
  54. package/convex/stripeActions.js +0 -411
  55. package/convex/teams.d.ts +0 -21
  56. package/convex/teams.js +0 -215
  57. package/convex/telemetry.d.ts +0 -4
  58. package/convex/telemetry.js +0 -74
  59. package/convex/usage.d.ts +0 -27
  60. package/convex/usage.js +0 -229
  61. package/convex/waitlist.d.ts +0 -4
  62. package/convex/waitlist.js +0 -49
  63. package/convex/webhooks.d.ts +0 -12
  64. package/convex/webhooks.js +0 -410
  65. package/convex/workspaces.d.ts +0 -29
  66. package/convex/workspaces.js +0 -880
@@ -1,7 +0,0 @@
1
- export declare const purchaseAccess: any;
2
- export declare const getAgentPurchases: any;
3
- export declare const getActivePurchase: any;
4
- export declare const getUsage: any;
5
- export declare const recordUsage: any;
6
- export declare const getBalanceSummary: any;
7
- //# sourceMappingURL=purchases.d.ts.map
@@ -1,157 +0,0 @@
1
- import { v } from "convex/values";
2
- import { mutation, query } from "./_generated/server";
3
- // Provider pricing (credits per dollar)
4
- const CREDITS_PER_DOLLAR = {
5
- "46elks": 30, // ~30 SMS per dollar
6
- twilio: 25, // ~25 SMS per dollar
7
- resend: 1000, // ~1000 emails per dollar
8
- brave_search: 200, // ~200 searches per dollar
9
- openrouter: 100, // ~100k tokens per dollar
10
- elevenlabs: 3333, // ~3333 characters per dollar
11
- };
12
- // Calculate credits for a provider purchase
13
- function calculateCredits(providerId, amountUsd) {
14
- const rate = CREDITS_PER_DOLLAR[providerId] || 100;
15
- return Math.floor(amountUsd * rate);
16
- }
17
- // Purchase API access
18
- export const purchaseAccess = mutation({
19
- args: {
20
- agentId: v.string(),
21
- providerId: v.string(),
22
- amountUsd: v.number(),
23
- credentials: v.any(), // Credentials passed from server side
24
- },
25
- handler: async (ctx, args) => {
26
- // Check balance
27
- const credits = await ctx.db
28
- .query("agentCredits")
29
- .withIndex("by_agentId", (q) => q.eq("agentId", args.agentId))
30
- .first();
31
- if (!credits || credits.balanceUsd < args.amountUsd) {
32
- throw new Error(`Insufficient balance: have $${(credits?.balanceUsd || 0).toFixed(2)}, need $${args.amountUsd.toFixed(2)}`);
33
- }
34
- // Deduct credits
35
- await ctx.db.patch(credits._id, {
36
- balanceUsd: credits.balanceUsd - args.amountUsd,
37
- updatedAt: Date.now(),
38
- });
39
- // Calculate credits granted
40
- const creditsGranted = calculateCredits(args.providerId, args.amountUsd);
41
- // Create purchase record
42
- const purchaseId = await ctx.db.insert("purchases", {
43
- agentId: args.agentId,
44
- providerId: args.providerId,
45
- amountUsd: args.amountUsd,
46
- creditsGranted,
47
- status: "active",
48
- credentials: args.credentials,
49
- createdAt: Date.now(),
50
- });
51
- // Initialize usage tracking
52
- await ctx.db.insert("usage", {
53
- purchaseId,
54
- providerId: args.providerId,
55
- unitsUsed: 0,
56
- unitsRemaining: creditsGranted,
57
- costIncurredUsd: 0,
58
- lastUsedAt: Date.now(),
59
- });
60
- return await ctx.db.get(purchaseId);
61
- },
62
- });
63
- // Get all purchases for an agent
64
- export const getAgentPurchases = query({
65
- args: { agentId: v.string() },
66
- handler: async (ctx, args) => {
67
- return await ctx.db
68
- .query("purchases")
69
- .withIndex("by_agentId", (q) => q.eq("agentId", args.agentId))
70
- .collect();
71
- },
72
- });
73
- // Get active purchase for a provider
74
- export const getActivePurchase = query({
75
- args: {
76
- agentId: v.string(),
77
- providerId: v.string(),
78
- },
79
- handler: async (ctx, args) => {
80
- const purchases = await ctx.db
81
- .query("purchases")
82
- .withIndex("by_agentId_providerId", (q) => q.eq("agentId", args.agentId).eq("providerId", args.providerId))
83
- .collect();
84
- return purchases.find((p) => p.status === "active") || null;
85
- },
86
- });
87
- // Get usage for a purchase
88
- export const getUsage = query({
89
- args: { purchaseId: v.id("purchases") },
90
- handler: async (ctx, args) => {
91
- return await ctx.db
92
- .query("usage")
93
- .withIndex("by_purchaseId", (q) => q.eq("purchaseId", args.purchaseId))
94
- .first();
95
- },
96
- });
97
- // Record usage
98
- export const recordUsage = mutation({
99
- args: {
100
- purchaseId: v.id("purchases"),
101
- unitsUsed: v.number(),
102
- costUsd: v.number(),
103
- },
104
- handler: async (ctx, args) => {
105
- const usage = await ctx.db
106
- .query("usage")
107
- .withIndex("by_purchaseId", (q) => q.eq("purchaseId", args.purchaseId))
108
- .first();
109
- if (!usage) {
110
- throw new Error("Usage record not found");
111
- }
112
- const newUnitsRemaining = Math.max(0, usage.unitsRemaining - args.unitsUsed);
113
- await ctx.db.patch(usage._id, {
114
- unitsUsed: usage.unitsUsed + args.unitsUsed,
115
- unitsRemaining: newUnitsRemaining,
116
- costIncurredUsd: usage.costIncurredUsd + args.costUsd,
117
- lastUsedAt: Date.now(),
118
- });
119
- // Update purchase status if depleted
120
- if (newUnitsRemaining === 0) {
121
- const purchase = await ctx.db.get(args.purchaseId);
122
- if (purchase) {
123
- await ctx.db.patch(args.purchaseId, { status: "exhausted" });
124
- }
125
- }
126
- return await ctx.db
127
- .query("usage")
128
- .withIndex("by_purchaseId", (q) => q.eq("purchaseId", args.purchaseId))
129
- .first();
130
- },
131
- });
132
- // Get balance summary for an agent
133
- export const getBalanceSummary = query({
134
- args: { agentId: v.string() },
135
- handler: async (ctx, args) => {
136
- const credits = await ctx.db
137
- .query("agentCredits")
138
- .withIndex("by_agentId", (q) => q.eq("agentId", args.agentId))
139
- .first();
140
- const purchases = await ctx.db
141
- .query("purchases")
142
- .withIndex("by_agentId", (q) => q.eq("agentId", args.agentId))
143
- .collect();
144
- const activePurchases = purchases.filter((p) => p.status === "active");
145
- const totalSpent = purchases.reduce((sum, p) => sum + p.amountUsd, 0);
146
- return {
147
- credits: credits || {
148
- agentId: args.agentId,
149
- balanceUsd: 0,
150
- currency: "USD",
151
- },
152
- activePurchases,
153
- totalSpentUsd: totalSpent,
154
- };
155
- },
156
- });
157
- //# sourceMappingURL=purchases.js.map
@@ -1,4 +0,0 @@
1
- export declare const checkLimit: any;
2
- export declare const getUsage: any;
3
- export declare const cleanup: any;
4
- //# sourceMappingURL=ratelimit.d.ts.map
@@ -1,91 +0,0 @@
1
- import { mutation, query } from "./_generated/server";
2
- import { v } from "convex/values";
3
- // Rate limit config per tier
4
- const LIMITS = {
5
- free: {
6
- discovery: 100, // searches per hour
7
- instant: 10, // API calls per hour
8
- },
9
- subscriber: {
10
- discovery: 1000,
11
- instant: 100,
12
- },
13
- provider: {
14
- discovery: 10000,
15
- instant: 1000,
16
- },
17
- };
18
- // Check and increment rate limit
19
- export const checkLimit = mutation({
20
- args: {
21
- identifier: v.string(), // IP or agentId
22
- action: v.union(v.literal("discovery"), v.literal("instant")),
23
- tier: v.optional(v.union(v.literal("free"), v.literal("subscriber"), v.literal("provider"))),
24
- },
25
- handler: async (ctx, args) => {
26
- const tier = args.tier || "free";
27
- const limit = LIMITS[tier][args.action];
28
- const hourKey = Math.floor(Date.now() / 3600000); // Hour bucket
29
- const key = `${args.identifier}:${args.action}:${hourKey}`;
30
- // Get current count
31
- const existing = await ctx.db
32
- .query("rateLimits")
33
- .withIndex("by_key", (q) => q.eq("key", key))
34
- .first();
35
- if (existing) {
36
- if (existing.count >= limit) {
37
- return { allowed: false, remaining: 0, resetIn: 3600 - (Date.now() % 3600000) / 1000 };
38
- }
39
- await ctx.db.patch(existing._id, { count: existing.count + 1 });
40
- return { allowed: true, remaining: limit - existing.count - 1 };
41
- }
42
- // Create new entry
43
- await ctx.db.insert("rateLimits", {
44
- key,
45
- identifier: args.identifier,
46
- action: args.action,
47
- count: 1,
48
- hourBucket: hourKey,
49
- createdAt: Date.now(),
50
- });
51
- return { allowed: true, remaining: limit - 1 };
52
- },
53
- });
54
- // Get current usage stats
55
- export const getUsage = query({
56
- args: {
57
- identifier: v.string(),
58
- },
59
- handler: async (ctx, args) => {
60
- const hourKey = Math.floor(Date.now() / 3600000);
61
- const discovery = await ctx.db
62
- .query("rateLimits")
63
- .withIndex("by_key", (q) => q.eq("key", `${args.identifier}:discovery:${hourKey}`))
64
- .first();
65
- const instant = await ctx.db
66
- .query("rateLimits")
67
- .withIndex("by_key", (q) => q.eq("key", `${args.identifier}:instant:${hourKey}`))
68
- .first();
69
- return {
70
- discovery: discovery?.count || 0,
71
- instant: instant?.count || 0,
72
- limits: LIMITS.free,
73
- };
74
- },
75
- });
76
- // Cleanup old rate limit entries (run via cron)
77
- export const cleanup = mutation({
78
- args: {},
79
- handler: async (ctx) => {
80
- const hourAgo = Math.floor(Date.now() / 3600000) - 2; // Keep 2 hours
81
- const old = await ctx.db
82
- .query("rateLimits")
83
- .filter((q) => q.lt(q.field("hourBucket"), hourAgo))
84
- .take(100);
85
- for (const entry of old) {
86
- await ctx.db.delete(entry._id);
87
- }
88
- return { deleted: old.length };
89
- },
90
- });
91
- //# sourceMappingURL=ratelimit.js.map
@@ -1,4 +0,0 @@
1
- export declare const logSearch: any;
2
- export declare const getTopQueries: any;
3
- export declare const getZeroResultQueries: any;
4
- //# sourceMappingURL=searchLogs.d.ts.map
@@ -1,129 +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
- });
129
- //# sourceMappingURL=searchLogs.js.map
@@ -1,36 +0,0 @@
1
- /**
2
- * Update workspace budget settings
3
- */
4
- export declare const updateBudgetSettings: any;
5
- /**
6
- * Record spend and check budget alerts
7
- * Called after each successful API execution
8
- * Returns budget status for response
9
- */
10
- export declare const recordSpend: any;
11
- /**
12
- * Check budget before execution
13
- * Returns { allowed: boolean, reason?: string }
14
- */
15
- export declare const checkBudget: any;
16
- /**
17
- * Get budget status for workspace dashboard
18
- */
19
- export declare const getBudgetStatus: any;
20
- /**
21
- * Get budget status by session token (for dashboard)
22
- */
23
- export declare const getBudgetStatusByToken: any;
24
- /**
25
- * Send budget alert email (80% warning)
26
- */
27
- export declare const sendBudgetAlertEmail: any;
28
- /**
29
- * Send budget exceeded email
30
- */
31
- export declare const sendBudgetExceededEmail: any;
32
- /**
33
- * Reset monthly spend for all workspaces (called by cron on 1st of month)
34
- */
35
- export declare const resetMonthlySpend: any;
36
- //# sourceMappingURL=spendAlerts.d.ts.map