@nordsym/apiclaw 1.8.6 → 1.8.7

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 (125) hide show
  1. package/README.md +4 -4
  2. package/apiclaw-README.md +12 -12
  3. package/convex/_generated/api.d.ts +4 -0
  4. package/convex/apiKeys.ts +220 -0
  5. package/convex/directCall.ts +49 -14
  6. package/convex/email.ts +5 -5
  7. package/convex/http.ts +598 -40
  8. package/convex/logs.ts +26 -22
  9. package/convex/migrateProviderWorkspaces.ts +154 -35
  10. package/convex/providers.ts +313 -203
  11. package/convex/schema.ts +50 -1
  12. package/convex/searchLogs.ts +2 -6
  13. package/convex/seedPratham.ts +1 -1
  14. package/convex/spendAlerts.ts +2 -2
  15. package/convex/stripeActions.ts +1 -1
  16. package/convex/updateAPIStatus.ts +2 -3
  17. package/convex/workspaceSettings.ts +136 -0
  18. package/dist/cli/commands/demo.js +2 -2
  19. package/dist/cli/commands/doctor.js +1 -1
  20. package/dist/cli/commands/login.js +1 -1
  21. package/dist/cli/commands/setup.js +2 -2
  22. package/dist/discovery.js +1 -1
  23. package/dist/execute.js +3 -3
  24. package/dist/index.js +13 -13
  25. package/dist/ui/errors.js +16 -16
  26. package/dist/ui/prompts.js +1 -1
  27. package/email-templates/filestack-provider-outreach.html +1 -1
  28. package/email-templates/partnership-template.html +1 -1
  29. package/email-templates/pratham-partnership-draft.html +2 -2
  30. package/package.json +2 -2
  31. package/reports/APIClaw-Session-Report-2026-04-05.pdf +0 -0
  32. package/reports/session-report-2026-04-05.html +433 -0
  33. package/src/cli/commands/demo.ts +2 -2
  34. package/src/cli/commands/doctor.ts +1 -1
  35. package/src/cli/commands/login.ts +1 -1
  36. package/src/cli/commands/setup.ts +2 -2
  37. package/src/discovery.ts +1 -1
  38. package/src/execute.ts +3 -3
  39. package/src/index.ts +14 -14
  40. package/src/ui/errors.ts +16 -16
  41. package/src/ui/prompts.ts +1 -1
  42. package/convex/adminActivate.d.ts +0 -3
  43. package/convex/adminActivate.js +0 -47
  44. package/convex/adminStats.d.ts +0 -9
  45. package/convex/adminStats.js +0 -280
  46. package/convex/agents.d.ts +0 -84
  47. package/convex/agents.js +0 -809
  48. package/convex/analytics.d.ts +0 -5
  49. package/convex/analytics.js +0 -167
  50. package/convex/backfillAnalytics.d.ts +0 -2
  51. package/convex/backfillAnalytics.js +0 -20
  52. package/convex/backfillSearchLogs.d.ts +0 -2
  53. package/convex/backfillSearchLogs.js +0 -29
  54. package/convex/billing.d.ts +0 -88
  55. package/convex/billing.js +0 -655
  56. package/convex/capabilities.d.ts +0 -9
  57. package/convex/capabilities.js +0 -145
  58. package/convex/chains.d.ts +0 -68
  59. package/convex/chains.js +0 -1105
  60. package/convex/credits.d.ts +0 -25
  61. package/convex/credits.js +0 -186
  62. package/convex/crons.d.ts +0 -3
  63. package/convex/crons.js +0 -17
  64. package/convex/debugFilestackLogs.d.ts +0 -2
  65. package/convex/debugFilestackLogs.js +0 -17
  66. package/convex/debugGetToken.d.ts +0 -2
  67. package/convex/debugGetToken.js +0 -18
  68. package/convex/directCall.d.ts +0 -72
  69. package/convex/directCall.js +0 -627
  70. package/convex/earnProgress.d.ts +0 -58
  71. package/convex/earnProgress.js +0 -649
  72. package/convex/email.d.ts +0 -14
  73. package/convex/email.js +0 -300
  74. package/convex/feedback.d.ts +0 -7
  75. package/convex/feedback.js +0 -227
  76. package/convex/http.d.ts +0 -3
  77. package/convex/http.js +0 -1408
  78. package/convex/inbound.d.ts +0 -2
  79. package/convex/inbound.js +0 -32
  80. package/convex/logs.d.ts +0 -48
  81. package/convex/logs.js +0 -621
  82. package/convex/migrateFilestack.d.ts +0 -2
  83. package/convex/migrateFilestack.js +0 -74
  84. package/convex/migratePartnersProd.d.ts +0 -8
  85. package/convex/migratePartnersProd.js +0 -165
  86. package/convex/migratePratham.d.ts +0 -2
  87. package/convex/migratePratham.js +0 -121
  88. package/convex/migrateProviderWorkspaces.d.ts +0 -2
  89. package/convex/migrateProviderWorkspaces.js +0 -55
  90. package/convex/mou.d.ts +0 -6
  91. package/convex/mou.js +0 -82
  92. package/convex/providerKeys.d.ts +0 -31
  93. package/convex/providerKeys.js +0 -257
  94. package/convex/providers.d.ts +0 -35
  95. package/convex/providers.js +0 -922
  96. package/convex/purchases.d.ts +0 -7
  97. package/convex/purchases.js +0 -157
  98. package/convex/ratelimit.d.ts +0 -4
  99. package/convex/ratelimit.js +0 -91
  100. package/convex/searchLogs.d.ts +0 -13
  101. package/convex/searchLogs.js +0 -246
  102. package/convex/seedAPILayerAPIs.d.ts +0 -7
  103. package/convex/seedAPILayerAPIs.js +0 -177
  104. package/convex/seedDirectCallConfigs.d.ts +0 -2
  105. package/convex/seedDirectCallConfigs.js +0 -324
  106. package/convex/seedPratham.d.ts +0 -6
  107. package/convex/seedPratham.js +0 -150
  108. package/convex/spendAlerts.d.ts +0 -36
  109. package/convex/spendAlerts.js +0 -380
  110. package/convex/stripeActions.d.ts +0 -19
  111. package/convex/stripeActions.js +0 -411
  112. package/convex/teams.d.ts +0 -21
  113. package/convex/teams.js +0 -215
  114. package/convex/telemetry.d.ts +0 -4
  115. package/convex/telemetry.js +0 -74
  116. package/convex/updateAPIStatus.d.ts +0 -6
  117. package/convex/updateAPIStatus.js +0 -40
  118. package/convex/usage.d.ts +0 -27
  119. package/convex/usage.js +0 -229
  120. package/convex/waitlist.d.ts +0 -4
  121. package/convex/waitlist.js +0 -49
  122. package/convex/webhooks.d.ts +0 -12
  123. package/convex/webhooks.js +0 -410
  124. package/convex/workspaces.d.ts +0 -33
  125. package/convex/workspaces.js +0 -991
@@ -1,991 +0,0 @@
1
- import { mutation, query } from "./_generated/server";
2
- import { internal } from "./_generated/api";
3
- import { v } from "convex/values";
4
- // ============================================
5
- // MAGIC LINK AUTH FOR WORKSPACES
6
- // ============================================
7
- // Create magic link for workspace email auth
8
- export const createMagicLink = mutation({
9
- args: {
10
- email: v.string(),
11
- fingerprint: v.optional(v.string()),
12
- },
13
- handler: async (ctx, { email, fingerprint }) => {
14
- const token = generateToken();
15
- const expiresAt = Date.now() + 15 * 60 * 1000; // 15 minutes
16
- await ctx.db.insert("workspaceMagicLinks", {
17
- email: email.toLowerCase(),
18
- token,
19
- sessionFingerprint: fingerprint,
20
- expiresAt,
21
- createdAt: Date.now(),
22
- });
23
- return { token, expiresAt };
24
- },
25
- });
26
- // Generate a unique referral code (CLAW-XXXXXX format)
27
- function generateReferralCode() {
28
- const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
29
- let code = "";
30
- for (let i = 0; i < 6; i++) {
31
- code += chars.charAt(Math.floor(Math.random() * chars.length));
32
- }
33
- return `CLAW-${code}`;
34
- }
35
- // Verify magic link and create workspace + session
36
- export const verifyMagicLink = mutation({
37
- args: {
38
- token: v.string(),
39
- fingerprint: v.optional(v.string()),
40
- referralCode: v.optional(v.string()), // Referral code from signup URL
41
- },
42
- handler: async (ctx, { token, fingerprint, referralCode }) => {
43
- const magicLink = await ctx.db
44
- .query("workspaceMagicLinks")
45
- .withIndex("by_token", (q) => q.eq("token", token))
46
- .first();
47
- if (!magicLink) {
48
- return { success: false, error: "Invalid token" };
49
- }
50
- if (magicLink.expiresAt < Date.now()) {
51
- return { success: false, error: "Token expired" };
52
- }
53
- if (magicLink.usedAt) {
54
- return { success: false, error: "Token already used" };
55
- }
56
- // Mark as used
57
- await ctx.db.patch(magicLink._id, { usedAt: Date.now() });
58
- // Find or create workspace
59
- let workspace = await ctx.db
60
- .query("workspaces")
61
- .withIndex("by_email", (q) => q.eq("email", magicLink.email))
62
- .first();
63
- let isNewUser = false;
64
- if (!workspace) {
65
- isNewUser = true;
66
- // Generate unique referral code for new user
67
- let newReferralCode;
68
- let attempts = 0;
69
- do {
70
- newReferralCode = generateReferralCode();
71
- const existing = await ctx.db
72
- .query("workspaces")
73
- .withIndex("by_referralCode", (q) => q.eq("referralCode", newReferralCode))
74
- .first();
75
- if (!existing)
76
- break;
77
- attempts++;
78
- } while (attempts < 10);
79
- // Create new workspace with free tier + referral code
80
- const workspaceId = await ctx.db.insert("workspaces", {
81
- email: magicLink.email,
82
- status: "active",
83
- tier: "free",
84
- usageCount: 0,
85
- usageLimit: 50, // 50 calls/month for free tier
86
- weeklyUsageCount: 0,
87
- weeklyUsageLimit: 50, // Monthly limit (field name is legacy)
88
- hourlyUsageCount: 0,
89
- referralCode: newReferralCode,
90
- createdAt: Date.now(),
91
- updatedAt: Date.now(),
92
- });
93
- workspace = await ctx.db.get(workspaceId);
94
- }
95
- // REFERRAL DISABLED (2026-03-01): Risk of abuse with awesome-list exposure
96
- // Tracking referredBy for analytics only, no credit bonus
97
- if (isNewUser && referralCode) {
98
- const referrer = await ctx.db
99
- .query("workspaces")
100
- .withIndex("by_referralCode", (q) => q.eq("referralCode", referralCode))
101
- .first();
102
- if (referrer && referrer._id !== workspace._id) {
103
- // Track referral for analytics only
104
- await ctx.db.patch(workspace._id, {
105
- referredBy: referrer._id,
106
- updatedAt: Date.now(),
107
- });
108
- // No credit bonus - referral rewards disabled
109
- }
110
- }
111
- // Reuse existing session for same machine (fix: no more duplicate sessions per login)
112
- const sessionToken = generateToken();
113
- const userFingerprint2 = fingerprint || magicLink.sessionFingerprint;
114
- const existingSession = userFingerprint2
115
- ? await ctx.db
116
- .query("agentSessions")
117
- .withIndex("by_workspaceId", (q) => q.eq("workspaceId", workspace._id))
118
- .filter((q) => q.eq(q.field("fingerprint"), userFingerprint2))
119
- .first()
120
- : null;
121
- if (existingSession) {
122
- // Refresh existing session instead of creating duplicate
123
- await ctx.db.patch(existingSession._id, {
124
- sessionToken,
125
- lastUsedAt: Date.now(),
126
- });
127
- }
128
- else {
129
- await ctx.db.insert("agentSessions", {
130
- workspaceId: workspace._id,
131
- sessionToken,
132
- fingerprint: userFingerprint2 || undefined,
133
- lastUsedAt: Date.now(),
134
- createdAt: Date.now(),
135
- });
136
- }
137
- // Link agent record to workspace (if agent exists for this fingerprint)
138
- if (userFingerprint2) {
139
- const agentForFingerprint = await ctx.db
140
- .query("agents")
141
- .filter((q) => q.eq(q.field("fingerprint"), userFingerprint2))
142
- .first();
143
- if (agentForFingerprint && !agentForFingerprint.workspaceId) {
144
- await ctx.db.patch(agentForFingerprint._id, {
145
- workspaceId: workspace._id,
146
- });
147
- }
148
- }
149
- // Claim anonymous usage history
150
- const userFingerprint = fingerprint || magicLink.sessionFingerprint;
151
- if (userFingerprint) {
152
- try {
153
- // Find all analytics records with matching fingerprint and no workspaceId
154
- const analyticsRecords = await ctx.db
155
- .query("analytics")
156
- .withIndex("by_identifier", (q) => q.eq("identifier", userFingerprint))
157
- .collect();
158
- // Filter to only unclaimed records
159
- const unclaimedRecords = analyticsRecords.filter((r) => !r.workspaceId);
160
- // Update each record to link it to the workspace
161
- for (const record of unclaimedRecords) {
162
- await ctx.db.patch(record._id, { workspaceId: workspace._id });
163
- }
164
- }
165
- catch (err) {
166
- // Non-critical error, just log it
167
- console.error('Failed to claim anonymous usage:', err);
168
- }
169
- }
170
- // Notify Inbound Net (ALERTS) — async, non-blocking
171
- await ctx.scheduler.runAfter(0, internal.inbound.notifySignup, {
172
- email: workspace.email,
173
- workspaceId: workspace._id,
174
- tier: workspace.tier,
175
- isNewUser,
176
- timestamp: Date.now(),
177
- });
178
- return {
179
- success: true,
180
- sessionToken,
181
- workspace: {
182
- id: workspace._id,
183
- email: workspace.email,
184
- tier: workspace.tier,
185
- referralCode: workspace.referralCode,
186
- },
187
- };
188
- },
189
- });
190
- // Get session from token
191
- export const getSession = query({
192
- args: { token: v.string() },
193
- handler: async (ctx, { token }) => {
194
- const session = await ctx.db
195
- .query("agentSessions")
196
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
197
- .first();
198
- if (!session) {
199
- return null;
200
- }
201
- const workspace = await ctx.db.get(session.workspaceId);
202
- if (!workspace)
203
- return null;
204
- return {
205
- workspaceId: workspace._id,
206
- email: workspace.email,
207
- tier: workspace.tier,
208
- status: workspace.status,
209
- usageCount: workspace.usageCount,
210
- usageLimit: workspace.usageLimit,
211
- };
212
- },
213
- });
214
- // ============================================
215
- // DASHBOARD QUERIES
216
- // ============================================
217
- // Get full workspace dashboard data
218
- export const getWorkspaceDashboard = query({
219
- args: { token: v.string() },
220
- handler: async (ctx, { token }) => {
221
- // Verify session
222
- const session = await ctx.db
223
- .query("agentSessions")
224
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
225
- .first();
226
- if (!session) {
227
- return null;
228
- }
229
- // Note: lastUsedAt is updated via touchSession mutation separately
230
- const workspace = await ctx.db.get(session.workspaceId);
231
- if (!workspace)
232
- return null;
233
- // Get all agent sessions for this workspace
234
- const agentSessions = await ctx.db
235
- .query("agentSessions")
236
- .withIndex("by_workspaceId", (q) => q.eq("workspaceId", session.workspaceId))
237
- .collect();
238
- // Count agents: 1 main agent (if exists) + subagents
239
- const hasMainAgent = workspace.mainAgentId ? 1 : 0;
240
- const subagents = await ctx.db
241
- .query("subagents")
242
- .withIndex("by_workspaceId", (q) => q.eq("workspaceId", session.workspaceId))
243
- .collect();
244
- const totalAgentCount = hasMainAgent + subagents.length;
245
- // Get usage logs for this workspace (via agent credits or purchases)
246
- const credits = await ctx.db
247
- .query("agentCredits")
248
- .collect();
249
- // Filter credits that belong to this workspace's agents
250
- const workspaceCredits = credits.filter(c => agentSessions.some(s => c.agentId === s.sessionToken));
251
- // Get purchases for workspace agents
252
- const purchases = await ctx.db
253
- .query("purchases")
254
- .collect();
255
- const workspacePurchases = purchases.filter(p => agentSessions.some(s => p.agentId === s.sessionToken));
256
- // Calculate usage remaining — backer tier is unlimited
257
- const now = Date.now();
258
- const isBackerTier = workspace.tier === "backer" || workspace.tier === "founder" ||
259
- (workspace.backerUntil && workspace.backerUntil > now);
260
- const effectiveLimit = isBackerTier ? -1 : workspace.usageLimit; // -1 = unlimited
261
- const usageRemaining = isBackerTier ? -1 : Math.max(0, workspace.usageLimit - workspace.usageCount);
262
- const usagePercentage = isBackerTier ? 0 : (workspace.usageCount / workspace.usageLimit) * 100;
263
- // Budget status (PRD 2.6)
264
- const monthStart = getMonthStartForBudget();
265
- let currentSpend = workspace.monthlySpendCents || 0;
266
- if (!workspace.lastSpendResetAt || workspace.lastSpendResetAt < monthStart) {
267
- currentSpend = 0;
268
- }
269
- const budgetCap = workspace.budgetCap || null;
270
- return {
271
- workspace: {
272
- id: workspace._id,
273
- email: workspace.email,
274
- workspaceName: workspace.workspaceName,
275
- tier: workspace.tier,
276
- status: workspace.status,
277
- usageCount: workspace.usageCount,
278
- usageLimit: effectiveLimit,
279
- usageRemaining,
280
- usagePercentage,
281
- stripeCustomerId: workspace.stripeCustomerId,
282
- createdAt: workspace.createdAt,
283
- mainAgentName: workspace.mainAgentName,
284
- mainAgentId: workspace.mainAgentId,
285
- },
286
- stats: {
287
- totalAgents: totalAgentCount,
288
- totalCredits: workspaceCredits.reduce((sum, c) => sum + c.balanceUsd, 0),
289
- totalPurchases: workspacePurchases.length,
290
- },
291
- budget: {
292
- budgetCapCents: budgetCap,
293
- budgetCapUsd: budgetCap ? budgetCap / 100 : null,
294
- currentSpendCents: currentSpend,
295
- currentSpendUsd: currentSpend / 100,
296
- remainingCents: budgetCap ? Math.max(0, budgetCap - currentSpend) : null,
297
- remainingUsd: budgetCap ? Math.max(0, (budgetCap - currentSpend) / 100) : null,
298
- budgetPercentage: budgetCap ? Math.min(100, (currentSpend / budgetCap) * 100) : null,
299
- pauseOnBudgetExceeded: workspace.pauseOnBudgetExceeded || false,
300
- isOverBudget: budgetCap ? currentSpend >= budgetCap : false,
301
- isNearBudget: budgetCap ? currentSpend >= budgetCap * 0.8 : false,
302
- },
303
- };
304
- },
305
- });
306
- // Helper for budget month start
307
- function getMonthStartForBudget() {
308
- const now = new Date();
309
- return new Date(now.getUTCFullYear(), now.getUTCMonth(), 1, 0, 0, 0, 0).getTime();
310
- }
311
- // Get connected agents for workspace
312
- export const getConnectedAgents = query({
313
- args: { token: v.string() },
314
- handler: async (ctx, { token }) => {
315
- const session = await ctx.db
316
- .query("agentSessions")
317
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
318
- .first();
319
- if (!session) {
320
- return [];
321
- }
322
- const agentSessions = await ctx.db
323
- .query("agentSessions")
324
- .withIndex("by_workspaceId", (q) => q.eq("workspaceId", session.workspaceId))
325
- .collect();
326
- return agentSessions.map((s) => ({
327
- id: s._id,
328
- fingerprint: s.fingerprint || "Unknown",
329
- customName: s.customName || null,
330
- name: s.customName || s.fingerprint || "Unknown",
331
- lastUsedAt: s.lastUsedAt,
332
- createdAt: s.createdAt,
333
- isCurrent: s.sessionToken === token,
334
- }));
335
- },
336
- });
337
- // Admin: Delete session by ID (for cleanup)
338
- export const adminDeleteSession = mutation({
339
- args: { sessionId: v.id("agentSessions") },
340
- handler: async (ctx, { sessionId }) => {
341
- await ctx.db.delete(sessionId);
342
- return { success: true };
343
- },
344
- });
345
- // Debug: Get sessions by workspace email
346
- export const getSessionsByEmail = query({
347
- args: { email: v.string() },
348
- handler: async (ctx, { email }) => {
349
- const workspace = await ctx.db
350
- .query("workspaces")
351
- .withIndex("by_email", (q) => q.eq("email", email.toLowerCase()))
352
- .first();
353
- if (!workspace) {
354
- return { error: "Workspace not found", sessions: [] };
355
- }
356
- const sessions = await ctx.db
357
- .query("agentSessions")
358
- .withIndex("by_workspaceId", (q) => q.eq("workspaceId", workspace._id))
359
- .collect();
360
- return {
361
- workspaceId: workspace._id,
362
- email: workspace.email,
363
- sessions: sessions.map(s => ({
364
- id: s._id,
365
- fingerprint: s.fingerprint,
366
- createdAt: s.createdAt,
367
- lastUsedAt: s.lastUsedAt,
368
- })),
369
- };
370
- },
371
- });
372
- // Rename an agent session
373
- export const renameAgent = mutation({
374
- args: {
375
- token: v.string(),
376
- sessionId: v.id("agentSessions"),
377
- name: v.string(),
378
- },
379
- handler: async (ctx, { token, sessionId, name }) => {
380
- // Verify the requesting session
381
- const session = await ctx.db
382
- .query("agentSessions")
383
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
384
- .first();
385
- if (!session) {
386
- throw new Error("Invalid session");
387
- }
388
- // Get the session to rename
389
- const targetSession = await ctx.db.get(sessionId);
390
- if (!targetSession || targetSession.workspaceId !== session.workspaceId) {
391
- throw new Error("Session not found or access denied");
392
- }
393
- // Update the name (stored as customName field)
394
- await ctx.db.patch(sessionId, { customName: name });
395
- return { success: true };
396
- },
397
- });
398
- // Get usage breakdown by provider
399
- export const getUsageBreakdown = query({
400
- args: { token: v.string() },
401
- handler: async (ctx, { token }) => {
402
- const session = await ctx.db
403
- .query("agentSessions")
404
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
405
- .first();
406
- if (!session) {
407
- return { byProvider: [], byDay: [], total: 0 };
408
- }
409
- // Get all sessions for this workspace
410
- const agentSessions = await ctx.db
411
- .query("agentSessions")
412
- .withIndex("by_workspaceId", (q) => q.eq("workspaceId", session.workspaceId))
413
- .collect();
414
- const sessionTokens = agentSessions.map(s => s.sessionToken);
415
- // Get purchases for these agents
416
- const allPurchases = await ctx.db.query("purchases").collect();
417
- const workspacePurchases = allPurchases.filter(p => sessionTokens.includes(p.agentId));
418
- // Get usage for purchases
419
- const allUsage = await ctx.db.query("usage").collect();
420
- const purchaseIds = workspacePurchases.map(p => p._id);
421
- const workspaceUsage = allUsage.filter(u => purchaseIds.includes(u.purchaseId));
422
- // Aggregate by provider
423
- const byProvider = {};
424
- for (const usage of workspaceUsage) {
425
- if (!byProvider[usage.providerId]) {
426
- byProvider[usage.providerId] = { calls: 0, cost: 0 };
427
- }
428
- byProvider[usage.providerId].calls += usage.unitsUsed;
429
- byProvider[usage.providerId].cost += usage.costIncurredUsd;
430
- }
431
- // Aggregate by day (last 14 days)
432
- const now = Date.now();
433
- const fourteenDaysAgo = now - 14 * 24 * 60 * 60 * 1000;
434
- const byDay = {};
435
- for (const usage of workspaceUsage) {
436
- if (usage.lastUsedAt >= fourteenDaysAgo) {
437
- const day = new Date(usage.lastUsedAt).toISOString().split("T")[0];
438
- byDay[day] = (byDay[day] || 0) + usage.unitsUsed;
439
- }
440
- }
441
- return {
442
- byProvider: Object.entries(byProvider).map(([provider, data]) => ({
443
- provider,
444
- calls: data.calls,
445
- cost: data.cost,
446
- })),
447
- byDay: Object.entries(byDay)
448
- .map(([date, calls]) => ({ date, calls }))
449
- .sort((a, b) => a.date.localeCompare(b.date)),
450
- total: workspaceUsage.reduce((sum, u) => sum + u.unitsUsed, 0),
451
- };
452
- },
453
- });
454
- // ============================================
455
- // AGENT MANAGEMENT
456
- // ============================================
457
- // Revoke an agent session
458
- export const revokeAgentSession = mutation({
459
- args: {
460
- token: v.string(),
461
- sessionId: v.id("agentSessions"),
462
- },
463
- handler: async (ctx, { token, sessionId }) => {
464
- // Verify the requesting session
465
- const session = await ctx.db
466
- .query("agentSessions")
467
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
468
- .first();
469
- if (!session) {
470
- throw new Error("Unauthorized");
471
- }
472
- // Get the session to revoke
473
- const targetSession = await ctx.db.get(sessionId);
474
- if (!targetSession) {
475
- throw new Error("Session not found");
476
- }
477
- // Verify same workspace
478
- if (targetSession.workspaceId !== session.workspaceId) {
479
- throw new Error("Unauthorized");
480
- }
481
- // Prevent revoking current session
482
- if (targetSession.sessionToken === token) {
483
- throw new Error("Cannot revoke current session");
484
- }
485
- // Delete the session
486
- await ctx.db.delete(sessionId);
487
- return { success: true };
488
- },
489
- });
490
- // Logout (delete current session)
491
- export const logout = mutation({
492
- args: { token: v.string() },
493
- handler: async (ctx, { token }) => {
494
- const session = await ctx.db
495
- .query("agentSessions")
496
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
497
- .first();
498
- if (session) {
499
- await ctx.db.delete(session._id);
500
- }
501
- return { success: true };
502
- },
503
- });
504
- // ============================================
505
- // WORKSPACE MANAGEMENT
506
- // ============================================
507
- // Update workspace tier (for Stripe webhooks)
508
- export const updateTier = mutation({
509
- args: {
510
- workspaceId: v.id("workspaces"),
511
- tier: v.string(),
512
- usageLimit: v.number(),
513
- stripeCustomerId: v.optional(v.string()),
514
- },
515
- handler: async (ctx, { workspaceId, tier, usageLimit, stripeCustomerId }) => {
516
- const updates = {
517
- tier,
518
- usageLimit,
519
- updatedAt: Date.now(),
520
- };
521
- if (stripeCustomerId) {
522
- updates.stripeCustomerId = stripeCustomerId;
523
- }
524
- await ctx.db.patch(workspaceId, updates);
525
- return { success: true };
526
- },
527
- });
528
- // Increment usage count
529
- // Constants for rate limiting
530
- const FREE_WEEKLY_LIMIT = 50;
531
- const FREE_HOURLY_LIMIT = 10;
532
- const BACKER_END_DATE = new Date("2026-12-31T23:59:59Z").getTime();
533
- // Helper: Get start of current week (Monday 00:00 UTC)
534
- function getWeekStart() {
535
- const now = new Date();
536
- const dayOfWeek = now.getUTCDay();
537
- const diff = dayOfWeek === 0 ? 6 : dayOfWeek - 1; // Monday = 0
538
- const monday = new Date(now);
539
- monday.setUTCDate(now.getUTCDate() - diff);
540
- monday.setUTCHours(0, 0, 0, 0);
541
- return monday.getTime();
542
- }
543
- // Helper: Get start of current hour
544
- function getHourStart() {
545
- const now = new Date();
546
- now.setUTCMinutes(0, 0, 0);
547
- return now.getTime();
548
- }
549
- export const incrementUsage = mutation({
550
- args: {
551
- workspaceId: v.id("workspaces"),
552
- amount: v.optional(v.number()),
553
- },
554
- handler: async (ctx, { workspaceId, amount = 1 }) => {
555
- const workspace = await ctx.db.get(workspaceId);
556
- if (!workspace) {
557
- throw new Error("Workspace not found");
558
- }
559
- const now = Date.now();
560
- const weekStart = getWeekStart();
561
- const hourStart = getHourStart();
562
- // Check if Backer (unlimited until end of 2026)
563
- const isBacker = workspace.tier === "backer" || workspace.tier === "founder" ||
564
- (workspace.backerUntil && workspace.backerUntil > now);
565
- // Initialize weekly/hourly counters if needed
566
- let weeklyCount = workspace.weeklyUsageCount || 0;
567
- let hourlyCount = workspace.hourlyUsageCount || 0;
568
- // Reset weekly counter if new week
569
- if (!workspace.lastWeeklyResetAt || workspace.lastWeeklyResetAt < weekStart) {
570
- weeklyCount = 0;
571
- }
572
- // Reset hourly counter if new hour
573
- if (!workspace.lastHourlyResetAt || workspace.lastHourlyResetAt < hourStart) {
574
- hourlyCount = 0;
575
- }
576
- // Check rate limits for free tier
577
- if (!isBacker && workspace.tier !== "pro" && workspace.tier !== "enterprise") {
578
- // Check hourly limit (10/hour for free)
579
- if (hourlyCount + amount > FREE_HOURLY_LIMIT) {
580
- throw new Error(`Hourly rate limit exceeded (${FREE_HOURLY_LIMIT}/hour). Upgrade to Backer for unlimited.`);
581
- }
582
- // Check weekly limit (50/week for free)
583
- if (weeklyCount + amount > FREE_WEEKLY_LIMIT) {
584
- throw new Error(`Weekly limit exceeded (${FREE_WEEKLY_LIMIT}/week). Upgrade to Backer for unlimited.`);
585
- }
586
- }
587
- const newTotalCount = workspace.usageCount + amount;
588
- const newWeeklyCount = weeklyCount + amount;
589
- const newHourlyCount = hourlyCount + amount;
590
- await ctx.db.patch(workspaceId, {
591
- usageCount: newTotalCount,
592
- weeklyUsageCount: newWeeklyCount,
593
- hourlyUsageCount: newHourlyCount,
594
- lastWeeklyResetAt: weekStart,
595
- lastHourlyResetAt: hourStart,
596
- updatedAt: now,
597
- });
598
- // Calculate remaining for free tier
599
- const weeklyRemaining = isBacker ? Infinity : Math.max(0, FREE_WEEKLY_LIMIT - newWeeklyCount);
600
- const hourlyRemaining = isBacker ? Infinity : Math.max(0, FREE_HOURLY_LIMIT - newHourlyCount);
601
- return {
602
- success: true,
603
- usageCount: newTotalCount,
604
- weeklyUsageCount: newWeeklyCount,
605
- weeklyRemaining,
606
- hourlyRemaining,
607
- isBacker,
608
- };
609
- },
610
- });
611
- // ============================================
612
- // POLLING & VERIFICATION ENDPOINTS (for HTTP API)
613
- // ============================================
614
- // Poll magic link status (for agents to check if user clicked)
615
- export const pollMagicLink = query({
616
- args: { token: v.string() },
617
- handler: async (ctx, { token }) => {
618
- const magicLink = await ctx.db
619
- .query("workspaceMagicLinks")
620
- .withIndex("by_token", (q) => q.eq("token", token))
621
- .first();
622
- if (!magicLink) {
623
- return { status: "not_found" };
624
- }
625
- const now = Date.now();
626
- if (magicLink.usedAt) {
627
- // Get the workspace and session
628
- const workspace = await ctx.db
629
- .query("workspaces")
630
- .withIndex("by_email", (q) => q.eq("email", magicLink.email))
631
- .first();
632
- // Get the latest session for this workspace
633
- const session = workspace
634
- ? await ctx.db
635
- .query("agentSessions")
636
- .withIndex("by_workspaceId", (q) => q.eq("workspaceId", workspace._id))
637
- .order("desc")
638
- .first()
639
- : null;
640
- return {
641
- status: "verified",
642
- workspace: workspace
643
- ? {
644
- id: workspace._id,
645
- email: workspace.email,
646
- tier: workspace.tier,
647
- usageCount: workspace.usageCount,
648
- usageLimit: workspace.usageLimit,
649
- }
650
- : null,
651
- sessionToken: session?.sessionToken,
652
- };
653
- }
654
- if (magicLink.expiresAt < now) {
655
- return { status: "expired" };
656
- }
657
- return {
658
- status: "pending",
659
- expiresAt: magicLink.expiresAt,
660
- };
661
- },
662
- });
663
- // Verify session token (for HTTP API)
664
- export const verifySession = query({
665
- args: { sessionToken: v.string() },
666
- handler: async (ctx, { sessionToken }) => {
667
- const session = await ctx.db
668
- .query("agentSessions")
669
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", sessionToken))
670
- .first();
671
- if (!session) {
672
- return null;
673
- }
674
- const workspace = await ctx.db.get(session.workspaceId);
675
- if (!workspace || workspace.status !== "active") {
676
- return null;
677
- }
678
- return {
679
- workspaceId: workspace._id,
680
- email: workspace.email,
681
- tier: workspace.tier,
682
- usageCount: workspace.usageCount,
683
- usageLimit: workspace.usageLimit,
684
- };
685
- },
686
- });
687
- // Get workspace by email (for HTTP API)
688
- export const getByEmail = query({
689
- args: { email: v.string() },
690
- handler: async (ctx, { email }) => {
691
- const workspace = await ctx.db
692
- .query("workspaces")
693
- .withIndex("by_email", (q) => q.eq("email", email.toLowerCase()))
694
- .first();
695
- if (!workspace) {
696
- return null;
697
- }
698
- return {
699
- id: workspace._id,
700
- email: workspace.email,
701
- status: workspace.status,
702
- tier: workspace.tier,
703
- usageCount: workspace.usageCount,
704
- usageLimit: workspace.usageLimit,
705
- };
706
- },
707
- });
708
- // Touch session (update lastUsedAt)
709
- export const touchSession = mutation({
710
- args: { sessionToken: v.string() },
711
- handler: async (ctx, { sessionToken }) => {
712
- const session = await ctx.db
713
- .query("agentSessions")
714
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", sessionToken))
715
- .first();
716
- if (session) {
717
- await ctx.db.patch(session._id, { lastUsedAt: Date.now() });
718
- }
719
- },
720
- });
721
- // ============================================
722
- // MCP WORKSPACE FUNCTIONS
723
- // ============================================
724
- // Create a new workspace (called from MCP register_owner)
725
- export const createWorkspace = mutation({
726
- args: { email: v.string() },
727
- handler: async (ctx, { email }) => {
728
- const normalizedEmail = email.toLowerCase().trim();
729
- // Check if workspace exists
730
- const existing = await ctx.db
731
- .query("workspaces")
732
- .withIndex("by_email", (q) => q.eq("email", normalizedEmail))
733
- .first();
734
- if (existing) {
735
- return {
736
- success: false,
737
- error: "workspace_exists",
738
- workspaceId: existing._id,
739
- status: existing.status,
740
- };
741
- }
742
- // Create new workspace
743
- const workspaceId = await ctx.db.insert("workspaces", {
744
- email: normalizedEmail,
745
- status: "pending",
746
- tier: "free",
747
- usageCount: 0,
748
- usageLimit: 50, // Free tier limit
749
- createdAt: Date.now(),
750
- updatedAt: Date.now(),
751
- });
752
- return { success: true, workspaceId };
753
- },
754
- });
755
- // Update workspace name
756
- export const updateWorkspaceName = mutation({
757
- args: {
758
- token: v.string(),
759
- name: v.string(),
760
- },
761
- handler: async (ctx, { token, name }) => {
762
- const session = await ctx.db
763
- .query("agentSessions")
764
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
765
- .first();
766
- if (!session)
767
- throw new Error("Invalid session");
768
- const trimmed = name.trim();
769
- if (trimmed.length < 1 || trimmed.length > 100) {
770
- throw new Error("Name must be between 1 and 100 characters");
771
- }
772
- await ctx.db.patch(session.workspaceId, {
773
- workspaceName: trimmed,
774
- updatedAt: Date.now(),
775
- });
776
- return { success: true, name: trimmed };
777
- },
778
- });
779
- // Set or update password
780
- export const setPassword = mutation({
781
- args: {
782
- token: v.string(),
783
- password: v.string(),
784
- },
785
- handler: async (ctx, { token, password }) => {
786
- const session = await ctx.db
787
- .query("agentSessions")
788
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
789
- .first();
790
- if (!session)
791
- throw new Error("Invalid session");
792
- if (password.length < 8)
793
- throw new Error("Password must be at least 8 characters");
794
- // Simple hash using built-in crypto
795
- const encoder = new TextEncoder();
796
- const data = encoder.encode(password + "apiclaw-salt-v1");
797
- const hashBuffer = await crypto.subtle.digest("SHA-256", data);
798
- const hashArray = Array.from(new Uint8Array(hashBuffer));
799
- const hashHex = hashArray.map(b => b.toString(16).padStart(2, "0")).join("");
800
- await ctx.db.patch(session.workspaceId, {
801
- passwordHash: hashHex,
802
- updatedAt: Date.now(),
803
- });
804
- return { success: true };
805
- },
806
- });
807
- // Create agent session for workspace (called from MCP after verification)
808
- export const createAgentSession = mutation({
809
- args: {
810
- workspaceId: v.id("workspaces"),
811
- fingerprint: v.optional(v.string()),
812
- },
813
- handler: async (ctx, { workspaceId, fingerprint }) => {
814
- const workspace = await ctx.db.get(workspaceId);
815
- if (!workspace) {
816
- return { success: false, error: "workspace_not_found" };
817
- }
818
- if (workspace.status !== "active") {
819
- return { success: false, error: "workspace_not_active" };
820
- }
821
- const sessionToken = "apiclaw_" + generateToken();
822
- await ctx.db.insert("agentSessions", {
823
- workspaceId,
824
- sessionToken,
825
- fingerprint,
826
- lastUsedAt: Date.now(),
827
- createdAt: Date.now(),
828
- });
829
- return { success: true, sessionToken };
830
- },
831
- });
832
- // ============================================
833
- // HELPER FUNCTIONS
834
- // ============================================
835
- function generateToken() {
836
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
837
- let result = "";
838
- for (let i = 0; i < 48; i++) {
839
- result += chars.charAt(Math.floor(Math.random() * chars.length));
840
- }
841
- return result;
842
- }
843
- // Get workspace status (for MCP check_workspace_status tool)
844
- export const getWorkspaceStatus = query({
845
- args: {
846
- sessionToken: v.string(),
847
- },
848
- handler: async (ctx, args) => {
849
- const session = await ctx.db
850
- .query("agentSessions")
851
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.sessionToken))
852
- .first();
853
- if (!session) {
854
- return { authenticated: false };
855
- }
856
- const workspace = await ctx.db.get(session.workspaceId);
857
- if (!workspace) {
858
- return { authenticated: false };
859
- }
860
- const usageRemaining = workspace.usageLimit > 0
861
- ? workspace.usageLimit - workspace.usageCount
862
- : -1; // -1 = unlimited
863
- return {
864
- authenticated: true,
865
- email: workspace.email,
866
- status: workspace.status,
867
- tier: workspace.tier,
868
- usageCount: workspace.usageCount,
869
- usageLimit: workspace.usageLimit,
870
- usageRemaining,
871
- hasStripe: !!workspace.stripeCustomerId,
872
- createdAt: workspace.createdAt,
873
- };
874
- },
875
- });
876
- // Admin functions for Hivr integration
877
- export const adminActivateWorkspace = mutation({
878
- args: { workspaceId: v.id("workspaces") },
879
- handler: async (ctx, { workspaceId }) => {
880
- const workspace = await ctx.db.get(workspaceId);
881
- if (!workspace) {
882
- return { success: false, error: "not_found" };
883
- }
884
- await ctx.db.patch(workspaceId, {
885
- status: "active",
886
- tier: "backer",
887
- weeklyUsageLimit: 999999,
888
- updatedAt: Date.now(),
889
- });
890
- return { success: true };
891
- },
892
- });
893
- export const adminCreateSession = mutation({
894
- args: { workspaceId: v.id("workspaces") },
895
- handler: async (ctx, { workspaceId }) => {
896
- const workspace = await ctx.db.get(workspaceId);
897
- if (!workspace || workspace.status !== "active") {
898
- return { success: false, error: "workspace_not_active" };
899
- }
900
- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
901
- let token = '';
902
- for (let i = 0; i < 32; i++) {
903
- token += chars.charAt(Math.floor(Math.random() * chars.length));
904
- }
905
- const sessionToken = "apiclaw_" + token;
906
- await ctx.db.insert("agentSessions", {
907
- workspaceId,
908
- sessionToken,
909
- fingerprint: "hivr-bees",
910
- lastUsedAt: Date.now(),
911
- createdAt: Date.now(),
912
- });
913
- return { success: true, sessionToken };
914
- },
915
- });
916
- // TEMP: Admin query to debug workspace data
917
- export const adminGetFullWorkspace = query({
918
- args: { email: v.string() },
919
- handler: async (ctx, { email }) => {
920
- const workspace = await ctx.db
921
- .query("workspaces")
922
- .withIndex("by_email", (q) => q.eq("email", email.toLowerCase()))
923
- .first();
924
- if (!workspace) {
925
- return null;
926
- }
927
- return {
928
- _id: workspace._id,
929
- email: workspace.email,
930
- status: workspace.status,
931
- tier: workspace.tier,
932
- mainAgentId: workspace.mainAgentId || null,
933
- mainAgentName: workspace.mainAgentName || null,
934
- aiBackend: workspace.aiBackend || null,
935
- usageCount: workspace.usageCount,
936
- usageLimit: workspace.usageLimit,
937
- createdAt: workspace.createdAt,
938
- updatedAt: workspace.updatedAt,
939
- };
940
- },
941
- });
942
- /**
943
- * Claim anonymous usage history when a user registers
944
- * Links all analytics records with matching fingerprint to the workspace
945
- */
946
- export const claimAnonymousUsage = mutation({
947
- args: {
948
- workspaceId: v.id("workspaces"),
949
- machineFingerprint: v.string(),
950
- },
951
- handler: async (ctx, { workspaceId, machineFingerprint }) => {
952
- // Verify workspace exists
953
- const workspace = await ctx.db.get(workspaceId);
954
- if (!workspace) {
955
- return { success: false, error: "Workspace not found" };
956
- }
957
- // Find all analytics records with matching fingerprint and no workspaceId
958
- const analyticsRecords = await ctx.db
959
- .query("analytics")
960
- .withIndex("by_identifier", (q) => q.eq("identifier", machineFingerprint))
961
- .collect();
962
- // Filter to only unclaimed records
963
- const unclaimedRecords = analyticsRecords.filter((r) => !r.workspaceId);
964
- // Update each record to link it to the workspace
965
- let claimedCount = 0;
966
- for (const record of unclaimedRecords) {
967
- await ctx.db.patch(record._id, { workspaceId });
968
- claimedCount++;
969
- }
970
- return {
971
- success: true,
972
- claimedCount,
973
- message: `Claimed ${claimedCount} anonymous usage records`,
974
- };
975
- },
976
- });
977
- export const adminUpdateEmail = mutation({
978
- args: { workspaceId: v.id("workspaces"), newEmail: v.string() },
979
- handler: async (ctx, { workspaceId, newEmail }) => {
980
- await ctx.db.patch(workspaceId, { email: newEmail });
981
- return { success: true, email: newEmail };
982
- },
983
- });
984
- export const adminSetTier = mutation({
985
- args: { workspaceId: v.id("workspaces"), tier: v.string() },
986
- handler: async (ctx, { workspaceId, tier }) => {
987
- await ctx.db.patch(workspaceId, { tier, updatedAt: Date.now() });
988
- return { success: true, tier };
989
- },
990
- });
991
- //# sourceMappingURL=workspaces.js.map