@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,814 @@
1
+ import { v } from "convex/values";
2
+ import { mutation, query, internalMutation, internalAction } from "./_generated/server";
3
+
4
+ // ============================================
5
+ // AGENT NAME GENERATION
6
+ // ============================================
7
+
8
+ const ADJECTIVES = [
9
+ "Crimson", "Azure", "Golden", "Silver", "Obsidian",
10
+ "Emerald", "Sapphire", "Violet", "Amber", "Jade",
11
+ "Scarlet", "Cobalt", "Onyx", "Ruby", "Pearl",
12
+ "Shadow", "Storm", "Frost", "Blaze", "Thunder",
13
+ "Swift", "Silent", "Bright", "Dark", "Wild",
14
+ "Noble", "Fierce", "Cosmic", "Quantum", "Neural",
15
+ ];
16
+
17
+ const NOUNS = [
18
+ "Phoenix", "Falcon", "Dragon", "Wolf", "Raven",
19
+ "Serpent", "Tiger", "Hawk", "Panther", "Lynx",
20
+ "Cipher", "Vector", "Prism", "Nexus", "Core",
21
+ "Agent", "Oracle", "Sentinel", "Phantom", "Vanguard",
22
+ "Forge", "Spark", "Pulse", "Echo", "Byte",
23
+ "Matrix", "Vertex", "Helix", "Nova", "Zenith",
24
+ ];
25
+
26
+ function generateAgentName(): string {
27
+ const adj = ADJECTIVES[Math.floor(Math.random() * ADJECTIVES.length)];
28
+ const noun = NOUNS[Math.floor(Math.random() * NOUNS.length)];
29
+ return `${adj} ${noun}`;
30
+ }
31
+
32
+ function generateUUID(): string {
33
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
34
+ const r = Math.random() * 16 | 0;
35
+ const v = c === 'x' ? r : (r & 0x3 | 0x8);
36
+ return v.toString(16);
37
+ });
38
+ }
39
+
40
+ // ============================================
41
+ // MAIN AGENT QUERIES
42
+ // ============================================
43
+
44
+ /**
45
+ * Get main agent info for a workspace
46
+ */
47
+ export const getMainAgent = query({
48
+ args: { token: v.string() },
49
+ handler: async (ctx, { token }) => {
50
+ const session = await ctx.db
51
+ .query("agentSessions")
52
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
53
+ .first();
54
+
55
+ if (!session) {
56
+ return null;
57
+ }
58
+
59
+ const workspace = await ctx.db.get(session.workspaceId);
60
+ if (!workspace) {
61
+ return null;
62
+ }
63
+
64
+ return {
65
+ workspaceId: workspace._id,
66
+ email: workspace.email,
67
+ mainAgentId: workspace.mainAgentId || null,
68
+ mainAgentName: workspace.mainAgentName || null,
69
+ aiBackend: workspace.aiBackend || null,
70
+ usageCount: workspace.usageCount,
71
+ createdAt: workspace.createdAt,
72
+ };
73
+ },
74
+ });
75
+
76
+ /**
77
+ * Rename the main agent
78
+ */
79
+ export const renameMainAgent = mutation({
80
+ args: {
81
+ token: v.string(),
82
+ name: v.string(),
83
+ },
84
+ handler: async (ctx, { token, name }) => {
85
+ const session = await ctx.db
86
+ .query("agentSessions")
87
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
88
+ .first();
89
+
90
+ if (!session) {
91
+ throw new Error("Invalid session");
92
+ }
93
+
94
+ const workspace = await ctx.db.get(session.workspaceId);
95
+ if (!workspace) {
96
+ throw new Error("Workspace not found");
97
+ }
98
+
99
+ // Validate name length
100
+ const trimmedName = name.trim();
101
+ if (trimmedName.length < 2 || trimmedName.length > 50) {
102
+ throw new Error("Name must be between 2 and 50 characters");
103
+ }
104
+
105
+ await ctx.db.patch(workspace._id, {
106
+ mainAgentName: trimmedName,
107
+ updatedAt: Date.now(),
108
+ });
109
+
110
+ return { success: true, name: trimmedName };
111
+ },
112
+ });
113
+
114
+ /**
115
+ * Initialize main agent (auto-generate name and ID if not set)
116
+ * Called on first API call
117
+ */
118
+ export const ensureMainAgent = mutation({
119
+ args: { workspaceId: v.id("workspaces") },
120
+ handler: async (ctx, { workspaceId }) => {
121
+ const workspace = await ctx.db.get(workspaceId);
122
+ if (!workspace) {
123
+ throw new Error("Workspace not found");
124
+ }
125
+
126
+ // Already initialized
127
+ if (workspace.mainAgentId && workspace.mainAgentName) {
128
+ return {
129
+ mainAgentId: workspace.mainAgentId,
130
+ mainAgentName: workspace.mainAgentName,
131
+ created: false,
132
+ };
133
+ }
134
+
135
+ const mainAgentId = workspace.mainAgentId || generateUUID();
136
+ const mainAgentName = workspace.mainAgentName || generateAgentName();
137
+
138
+ await ctx.db.patch(workspaceId, {
139
+ mainAgentId,
140
+ mainAgentName,
141
+ updatedAt: Date.now(),
142
+ });
143
+
144
+ return {
145
+ mainAgentId,
146
+ mainAgentName,
147
+ created: true,
148
+ };
149
+ },
150
+ });
151
+
152
+ // ============================================
153
+ // SUBAGENT QUERIES
154
+ // ============================================
155
+
156
+ /**
157
+ * Get all subagents for a workspace
158
+ */
159
+ export const getSubagents = query({
160
+ args: {
161
+ token: v.string(),
162
+ limit: v.optional(v.number()),
163
+ },
164
+ handler: async (ctx, { token, limit = 50 }) => {
165
+ const session = await ctx.db
166
+ .query("agentSessions")
167
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
168
+ .first();
169
+
170
+ if (!session) {
171
+ return { subagents: [], total: 0 };
172
+ }
173
+
174
+ const subagents = await ctx.db
175
+ .query("subagents")
176
+ .withIndex("by_workspaceId", (q) => q.eq("workspaceId", session.workspaceId))
177
+ .order("desc")
178
+ .take(limit);
179
+
180
+ // Sort by lastActiveAt descending
181
+ const sorted = subagents.sort((a, b) => b.lastActiveAt - a.lastActiveAt);
182
+
183
+ return {
184
+ subagents: sorted.map((s) => ({
185
+ id: s._id,
186
+ subagentId: s.subagentId,
187
+ name: s.name || s.subagentId,
188
+ callCount: s.callCount,
189
+ firstSeenAt: s.firstSeenAt,
190
+ lastActiveAt: s.lastActiveAt,
191
+ })),
192
+ total: subagents.length,
193
+ };
194
+ },
195
+ });
196
+
197
+ /**
198
+ * Get stats for a specific subagent
199
+ */
200
+ export const getSubagentStats = query({
201
+ args: {
202
+ token: v.string(),
203
+ subagentId: v.string(),
204
+ },
205
+ handler: async (ctx, { token, subagentId }) => {
206
+ const session = await ctx.db
207
+ .query("agentSessions")
208
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
209
+ .first();
210
+
211
+ if (!session) {
212
+ return null;
213
+ }
214
+
215
+ const subagent = await ctx.db
216
+ .query("subagents")
217
+ .withIndex("by_workspaceId_subagentId", (q) =>
218
+ q.eq("workspaceId", session.workspaceId).eq("subagentId", subagentId)
219
+ )
220
+ .first();
221
+
222
+ if (!subagent) {
223
+ return null;
224
+ }
225
+
226
+ // Get recent logs for this subagent
227
+ const logs = await ctx.db
228
+ .query("apiLogs")
229
+ .withIndex("by_subagentId", (q) => q.eq("subagentId", subagentId))
230
+ .order("desc")
231
+ .take(100);
232
+
233
+ const successCount = logs.filter((l) => l.status === "success").length;
234
+ const errorCount = logs.filter((l) => l.status === "error").length;
235
+ const avgLatency = logs.length > 0
236
+ ? Math.round(logs.reduce((sum, l) => sum + l.latencyMs, 0) / logs.length)
237
+ : 0;
238
+
239
+ // Group by provider
240
+ const byProvider: Record<string, number> = {};
241
+ for (const log of logs) {
242
+ byProvider[log.provider] = (byProvider[log.provider] || 0) + 1;
243
+ }
244
+
245
+ return {
246
+ subagentId: subagent.subagentId,
247
+ name: subagent.name || subagent.subagentId,
248
+ callCount: subagent.callCount,
249
+ successCount,
250
+ errorCount,
251
+ successRate: logs.length > 0 ? Math.round((successCount / logs.length) * 100) : 0,
252
+ avgLatency,
253
+ firstSeenAt: subagent.firstSeenAt,
254
+ lastActiveAt: subagent.lastActiveAt,
255
+ byProvider: Object.entries(byProvider)
256
+ .map(([provider, count]) => ({ provider, count }))
257
+ .sort((a, b) => b.count - a.count),
258
+ };
259
+ },
260
+ });
261
+
262
+ /**
263
+ * Rename a subagent
264
+ */
265
+ export const renameSubagent = mutation({
266
+ args: {
267
+ token: v.string(),
268
+ subagentId: v.string(),
269
+ name: v.string(),
270
+ },
271
+ handler: async (ctx, { token, subagentId, name }) => {
272
+ const session = await ctx.db
273
+ .query("agentSessions")
274
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
275
+ .first();
276
+
277
+ if (!session) {
278
+ throw new Error("Invalid session");
279
+ }
280
+
281
+ const subagent = await ctx.db
282
+ .query("subagents")
283
+ .withIndex("by_workspaceId_subagentId", (q) =>
284
+ q.eq("workspaceId", session.workspaceId).eq("subagentId", subagentId)
285
+ )
286
+ .first();
287
+
288
+ if (!subagent) {
289
+ throw new Error("Subagent not found");
290
+ }
291
+
292
+ const trimmedName = name.trim();
293
+ if (trimmedName.length < 1 || trimmedName.length > 100) {
294
+ throw new Error("Name must be between 1 and 100 characters");
295
+ }
296
+
297
+ await ctx.db.patch(subagent._id, { name: trimmedName });
298
+
299
+ return { success: true, name: trimmedName };
300
+ },
301
+ });
302
+
303
+ /**
304
+ * Track a subagent call (upsert subagent record)
305
+ * Called when X-APIClaw-Subagent header is present
306
+ */
307
+ export const trackSubagentCall = mutation({
308
+ args: {
309
+ workspaceId: v.id("workspaces"),
310
+ subagentId: v.string(),
311
+ },
312
+ handler: async (ctx, { workspaceId, subagentId }) => {
313
+ const now = Date.now();
314
+
315
+ // Find existing subagent record
316
+ const existing = await ctx.db
317
+ .query("subagents")
318
+ .withIndex("by_workspaceId_subagentId", (q) =>
319
+ q.eq("workspaceId", workspaceId).eq("subagentId", subagentId)
320
+ )
321
+ .first();
322
+
323
+ if (existing) {
324
+ // Increment call count
325
+ await ctx.db.patch(existing._id, {
326
+ callCount: existing.callCount + 1,
327
+ lastActiveAt: now,
328
+ });
329
+ return { id: existing._id, created: false };
330
+ }
331
+
332
+ // Create new subagent record
333
+ const id = await ctx.db.insert("subagents", {
334
+ workspaceId,
335
+ subagentId,
336
+ callCount: 1,
337
+ firstSeenAt: now,
338
+ lastActiveAt: now,
339
+ });
340
+
341
+ return { id, created: true };
342
+ },
343
+ });
344
+
345
+ // ============================================
346
+ // AGGREGATE STATS
347
+ // ============================================
348
+
349
+ // ============================================
350
+ // AGENT REGISTRATION & AI BACKEND TRACKING
351
+ // ============================================
352
+
353
+ /**
354
+ * Pre-register a task agent (subagent)
355
+ * Allows agents to be registered before they make their first call
356
+ */
357
+ export const registerTaskAgent = mutation({
358
+ args: {
359
+ token: v.string(),
360
+ subagentId: v.string(),
361
+ name: v.optional(v.string()),
362
+ description: v.optional(v.string()),
363
+ },
364
+ handler: async (ctx, { token, subagentId, name, description }) => {
365
+ const session = await ctx.db
366
+ .query("agentSessions")
367
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
368
+ .first();
369
+
370
+ if (!session) {
371
+ throw new Error("Invalid session");
372
+ }
373
+
374
+ // Validate subagentId
375
+ const trimmedId = subagentId.trim();
376
+ if (trimmedId.length < 1 || trimmedId.length > 100) {
377
+ throw new Error("Subagent ID must be between 1 and 100 characters");
378
+ }
379
+
380
+ const now = Date.now();
381
+
382
+ // Check if already exists
383
+ const existing = await ctx.db
384
+ .query("subagents")
385
+ .withIndex("by_workspaceId_subagentId", (q) =>
386
+ q.eq("workspaceId", session.workspaceId).eq("subagentId", trimmedId)
387
+ )
388
+ .first();
389
+
390
+ if (existing) {
391
+ // Update existing record
392
+ await ctx.db.patch(existing._id, {
393
+ name: name || existing.name,
394
+ description: description || existing.description,
395
+ isRegistered: true,
396
+ lastActiveAt: now,
397
+ });
398
+ return { id: existing._id, created: false };
399
+ }
400
+
401
+ // Create new subagent record
402
+ const id = await ctx.db.insert("subagents", {
403
+ workspaceId: session.workspaceId,
404
+ subagentId: trimmedId,
405
+ name: name,
406
+ description: description,
407
+ callCount: 0,
408
+ isRegistered: true,
409
+ firstSeenAt: now,
410
+ lastActiveAt: now,
411
+ });
412
+
413
+ return { id, created: true };
414
+ },
415
+ });
416
+
417
+ /**
418
+ * Update AI backend for workspace or subagent
419
+ * Called when X-APIClaw-AI-Backend header is present
420
+ */
421
+ export const updateAIBackend = mutation({
422
+ args: {
423
+ workspaceId: v.id("workspaces"),
424
+ subagentId: v.optional(v.string()),
425
+ aiBackend: v.string(),
426
+ },
427
+ handler: async (ctx, { workspaceId, subagentId, aiBackend }) => {
428
+ const now = Date.now();
429
+
430
+ if (subagentId) {
431
+ // Update subagent's AI backend
432
+ const subagent = await ctx.db
433
+ .query("subagents")
434
+ .withIndex("by_workspaceId_subagentId", (q) =>
435
+ q.eq("workspaceId", workspaceId).eq("subagentId", subagentId)
436
+ )
437
+ .first();
438
+
439
+ if (subagent) {
440
+ await ctx.db.patch(subagent._id, {
441
+ aiBackend,
442
+ lastActiveAt: now,
443
+ });
444
+ }
445
+ } else {
446
+ // Update workspace's main agent AI backend
447
+ await ctx.db.patch(workspaceId, {
448
+ aiBackend,
449
+ aiBackendLastSeen: now,
450
+ updatedAt: now,
451
+ });
452
+ }
453
+
454
+ return { success: true };
455
+ },
456
+ });
457
+
458
+ // ============================================
459
+ // AGGREGATE STATS
460
+ // ============================================
461
+
462
+ /**
463
+ * Get agent overview for workspace (main + subagents summary)
464
+ */
465
+ export const getAgentOverview = query({
466
+ args: { token: v.string() },
467
+ handler: async (ctx, { token }) => {
468
+ const session = await ctx.db
469
+ .query("agentSessions")
470
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
471
+ .first();
472
+
473
+ if (!session) {
474
+ return null;
475
+ }
476
+
477
+ const workspace = await ctx.db.get(session.workspaceId);
478
+ if (!workspace) {
479
+ return null;
480
+ }
481
+
482
+ // Get all subagents
483
+ const subagents = await ctx.db
484
+ .query("subagents")
485
+ .withIndex("by_workspaceId", (q) => q.eq("workspaceId", session.workspaceId))
486
+ .collect();
487
+
488
+ // Calculate totals
489
+ const totalSubagentCalls = subagents.reduce((sum, s) => sum + s.callCount, 0);
490
+ const mainAgentCalls = workspace.usageCount - totalSubagentCalls;
491
+
492
+ // Get most active subagents (top 5)
493
+ const topSubagents = subagents
494
+ .sort((a, b) => b.callCount - a.callCount)
495
+ .slice(0, 5)
496
+ .map((s) => ({
497
+ subagentId: s.subagentId,
498
+ name: s.name || s.subagentId,
499
+ callCount: s.callCount,
500
+ lastActiveAt: s.lastActiveAt,
501
+ }));
502
+
503
+ return {
504
+ mainAgent: {
505
+ id: workspace.mainAgentId || null,
506
+ name: workspace.mainAgentName || "Unnamed Agent",
507
+ callCount: Math.max(0, mainAgentCalls), // Ensure non-negative
508
+ },
509
+ subagents: {
510
+ total: subagents.length,
511
+ totalCalls: totalSubagentCalls,
512
+ topActive: topSubagents,
513
+ },
514
+ totalCalls: workspace.usageCount,
515
+ };
516
+ },
517
+ });
518
+
519
+ /**
520
+ * Delete a subagent
521
+ */
522
+ export const deleteSubagent = mutation({
523
+ args: {
524
+ token: v.string(),
525
+ subagentId: v.string(),
526
+ },
527
+ handler: async (ctx, { token, subagentId }) => {
528
+ const session = await ctx.db
529
+ .query("agentSessions")
530
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
531
+ .first();
532
+
533
+ if (!session) {
534
+ throw new Error("Invalid session");
535
+ }
536
+
537
+ const subagent = await ctx.db
538
+ .query("subagents")
539
+ .withIndex("by_workspaceId_subagentId", (q) =>
540
+ q.eq("workspaceId", session.workspaceId).eq("subagentId", subagentId)
541
+ )
542
+ .first();
543
+
544
+ if (!subagent) {
545
+ throw new Error("Subagent not found");
546
+ }
547
+
548
+ await ctx.db.delete(subagent._id);
549
+ return { success: true };
550
+ },
551
+ });
552
+
553
+ /**
554
+ * Update subagent stats (call count, last active)
555
+ * Internal helper for tracking
556
+ */
557
+ export const updateSubagentStats = mutation({
558
+ args: {
559
+ token: v.string(),
560
+ subagentId: v.string(),
561
+ incrementCalls: v.optional(v.number()),
562
+ },
563
+ handler: async (ctx, { token, subagentId, incrementCalls = 1 }) => {
564
+ const session = await ctx.db
565
+ .query("agentSessions")
566
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
567
+ .first();
568
+
569
+ if (!session) {
570
+ throw new Error("Invalid session");
571
+ }
572
+
573
+ const subagent = await ctx.db
574
+ .query("subagents")
575
+ .withIndex("by_workspaceId_subagentId", (q) =>
576
+ q.eq("workspaceId", session.workspaceId).eq("subagentId", subagentId)
577
+ )
578
+ .first();
579
+
580
+ if (!subagent) {
581
+ throw new Error("Subagent not found");
582
+ }
583
+
584
+ await ctx.db.patch(subagent._id, {
585
+ callCount: (subagent.callCount || 0) + incrementCalls,
586
+ lastActiveAt: Date.now(),
587
+ });
588
+
589
+ return { success: true, newCallCount: (subagent.callCount || 0) + incrementCalls };
590
+ },
591
+ });
592
+
593
+ // ============================================
594
+ // AGENT IDENTITY (agents table — NOT agentSessions)
595
+ // An agent = unique (fingerprint, mcpClient) pair
596
+ // ============================================
597
+
598
+ function generateSessionToken(): string {
599
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
600
+ let result = "";
601
+ for (let i = 0; i < 48; i++) {
602
+ result += chars.charAt(Math.floor(Math.random() * chars.length));
603
+ }
604
+ return result;
605
+ }
606
+
607
+ function generateReferralCode(): string {
608
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
609
+ let code = "CLAW-";
610
+ for (let i = 0; i < 6; i++) {
611
+ code += chars.charAt(Math.floor(Math.random() * chars.length));
612
+ }
613
+ return code;
614
+ }
615
+
616
+ /**
617
+ * Ensure agent exists for this (fingerprint, mcpClient) pair.
618
+ * Auto-provisions a free-tier workspace if none exists.
619
+ * Called on every MCP server startup.
620
+ */
621
+ export const ensureAgent = mutation({
622
+ args: {
623
+ fingerprint: v.string(),
624
+ mcpClient: v.string(),
625
+ platform: v.optional(v.string()),
626
+ },
627
+ handler: async (ctx, { fingerprint, mcpClient, platform }) => {
628
+ const now = Date.now();
629
+
630
+ // 1. Check if agent already exists
631
+ const existing = await ctx.db
632
+ .query("agents")
633
+ .withIndex("by_fingerprint_client", (q) =>
634
+ q.eq("fingerprint", fingerprint).eq("mcpClient", mcpClient)
635
+ )
636
+ .first();
637
+
638
+ if (existing) {
639
+ // Update last active + platform
640
+ await ctx.db.patch(existing._id, {
641
+ lastActiveAt: now,
642
+ ...(platform ? { platform } : {}),
643
+ });
644
+
645
+ // Find session for this workspace
646
+ const session = await ctx.db
647
+ .query("agentSessions")
648
+ .withIndex("by_workspaceId", (q) => q.eq("workspaceId", existing.workspaceId))
649
+ .first();
650
+
651
+ return {
652
+ agentId: existing._id,
653
+ workspaceId: existing.workspaceId,
654
+ sessionToken: session?.sessionToken || null,
655
+ isNew: false,
656
+ };
657
+ }
658
+
659
+ // 2. No agent exists — check if there's a workspace for this fingerprint (from another mcpClient)
660
+ const siblingAgent = await ctx.db
661
+ .query("agents")
662
+ .filter((q) => q.eq(q.field("fingerprint"), fingerprint))
663
+ .first();
664
+
665
+ let workspaceId;
666
+
667
+ if (siblingAgent) {
668
+ // Reuse existing workspace (same machine, different client)
669
+ workspaceId = siblingAgent.workspaceId;
670
+ } else {
671
+ // 3. No workspace at all — auto-provision free tier
672
+ workspaceId = await ctx.db.insert("workspaces", {
673
+ email: "", // no email yet — added when user registers
674
+ status: "active",
675
+ tier: "free",
676
+ usageCount: 0,
677
+ usageLimit: 50,
678
+ weeklyUsageCount: 0,
679
+ weeklyUsageLimit: 50,
680
+ hourlyUsageCount: 0,
681
+ referralCode: generateReferralCode(),
682
+ createdAt: now,
683
+ updatedAt: now,
684
+ });
685
+ }
686
+
687
+ // 4. Create agent record
688
+ const agentId = await ctx.db.insert("agents", {
689
+ fingerprint,
690
+ mcpClient,
691
+ workspaceId,
692
+ name: generateAgentName(),
693
+ platform: platform || undefined,
694
+ callCount: 0,
695
+ firstSeenAt: now,
696
+ lastActiveAt: now,
697
+ });
698
+
699
+ // 5. Create session
700
+ const sessionToken = generateSessionToken();
701
+ await ctx.db.insert("agentSessions", {
702
+ workspaceId,
703
+ sessionToken,
704
+ fingerprint,
705
+ lastUsedAt: now,
706
+ createdAt: now,
707
+ });
708
+
709
+ return {
710
+ agentId,
711
+ workspaceId,
712
+ sessionToken,
713
+ isNew: true,
714
+ };
715
+ },
716
+ });
717
+
718
+ /**
719
+ * Link email to an existing workspace (called by register_owner + verifyMagicLink)
720
+ */
721
+ export const linkEmailToWorkspace = mutation({
722
+ args: {
723
+ fingerprint: v.string(),
724
+ email: v.string(),
725
+ },
726
+ handler: async (ctx, { fingerprint, email }) => {
727
+ // Find agent by fingerprint → get workspace
728
+ const agent = await ctx.db
729
+ .query("agents")
730
+ .filter((q) => q.eq(q.field("fingerprint"), fingerprint))
731
+ .first();
732
+
733
+ if (agent) {
734
+ const workspace = await ctx.db.get(agent.workspaceId);
735
+ if (workspace && (!workspace.email || workspace.email === "")) {
736
+ // Add email to existing workspace
737
+ await ctx.db.patch(workspace._id, {
738
+ email,
739
+ updatedAt: Date.now(),
740
+ });
741
+ return { workspaceId: workspace._id, linked: true };
742
+ }
743
+ }
744
+
745
+ return { workspaceId: null, linked: false };
746
+ },
747
+ });
748
+
749
+ /**
750
+ * Increment call count for an agent
751
+ */
752
+ export const incrementAgentCalls = mutation({
753
+ args: { agentId: v.id("agents") },
754
+ handler: async (ctx, { agentId }) => {
755
+ const agent = await ctx.db.get(agentId);
756
+ if (!agent) return;
757
+
758
+ await ctx.db.patch(agentId, {
759
+ callCount: agent.callCount + 1,
760
+ lastActiveAt: Date.now(),
761
+ });
762
+ },
763
+ });
764
+
765
+ /**
766
+ * Get all agents for a workspace (for dashboard "My Agents")
767
+ */
768
+ export const getWorkspaceAgents = query({
769
+ args: { token: v.string() },
770
+ handler: async (ctx, { token }) => {
771
+ const session = await ctx.db
772
+ .query("agentSessions")
773
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
774
+ .first();
775
+
776
+ if (!session) return [];
777
+
778
+ const agents = await ctx.db
779
+ .query("agents")
780
+ .withIndex("by_workspaceId", (q) => q.eq("workspaceId", session.workspaceId))
781
+ .collect();
782
+
783
+ return agents.map((a) => ({
784
+ id: a._id,
785
+ fingerprint: a.fingerprint,
786
+ mcpClient: a.mcpClient,
787
+ name: a.name,
788
+ hostname: a.fingerprint.split(":")[0],
789
+ aiBackend: a.aiBackend,
790
+ platform: a.platform,
791
+ callCount: a.callCount,
792
+ firstSeenAt: a.firstSeenAt,
793
+ lastActiveAt: a.lastActiveAt,
794
+ }));
795
+ },
796
+ });
797
+
798
+ /**
799
+ * Get total agent count (for landing page / admin)
800
+ */
801
+ export const getTotalAgentCount = query({
802
+ args: {},
803
+ handler: async (ctx) => {
804
+ const agents = await ctx.db.query("agents").collect();
805
+ const byClient: Record<string, number> = {};
806
+ for (const a of agents) {
807
+ byClient[a.mcpClient] = (byClient[a.mcpClient] || 0) + 1;
808
+ }
809
+ return {
810
+ total: agents.length,
811
+ byClient,
812
+ };
813
+ },
814
+ });