@nordsym/apiclaw 1.7.2 → 1.7.4

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