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