@nordsym/apiclaw 1.8.7 → 1.8.8

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