@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,494 @@
1
+ import { v } from "convex/values";
2
+ import { mutation, query, action, internalAction, internalQuery, internalMutation } from "./_generated/server";
3
+ import { internal } from "./_generated/api";
4
+ import { Doc, Id } from "./_generated/dataModel";
5
+
6
+ // Event types available for webhooks
7
+ export const WEBHOOK_EVENTS = [
8
+ "usage.threshold.80",
9
+ "usage.threshold.100",
10
+ "api.error",
11
+ "agent.connected",
12
+ "agent.revoked",
13
+ ] as const;
14
+
15
+ // Generate a random secret for webhook signature verification
16
+ function generateSecret(): string {
17
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
18
+ let result = "whsec_";
19
+ for (let i = 0; i < 32; i++) {
20
+ result += chars.charAt(Math.floor(Math.random() * chars.length));
21
+ }
22
+ return result;
23
+ }
24
+
25
+ // ============================================
26
+ // QUERIES
27
+ // ============================================
28
+
29
+ export const getWebhooks = query({
30
+ args: { token: v.string() },
31
+ handler: async (ctx, args) => {
32
+ // Verify session
33
+ const session = await ctx.db
34
+ .query("agentSessions")
35
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
36
+ .first();
37
+
38
+ if (!session) {
39
+ return { error: "Invalid session" };
40
+ }
41
+
42
+ // Get webhooks for workspace
43
+ const webhooks = await ctx.db
44
+ .query("webhooks")
45
+ .withIndex("by_workspaceId", (q) => q.eq("workspaceId", session.workspaceId))
46
+ .collect();
47
+
48
+ // Return webhooks without exposing full secret
49
+ return {
50
+ webhooks: webhooks.map((wh) => ({
51
+ id: wh._id,
52
+ url: wh.url,
53
+ events: wh.events,
54
+ enabled: wh.enabled,
55
+ lastTriggeredAt: wh.lastTriggeredAt,
56
+ lastStatus: wh.lastStatus,
57
+ failCount: wh.failCount,
58
+ createdAt: wh.createdAt,
59
+ // Only show hint of secret
60
+ secretHint: wh.secret.slice(0, 10) + "..." + wh.secret.slice(-4),
61
+ })),
62
+ };
63
+ },
64
+ });
65
+
66
+ // ============================================
67
+ // MUTATIONS
68
+ // ============================================
69
+
70
+ export const createWebhook = mutation({
71
+ args: {
72
+ token: v.string(),
73
+ url: v.string(),
74
+ events: v.array(v.string()),
75
+ },
76
+ handler: async (ctx, args) => {
77
+ // Verify session
78
+ const session = await ctx.db
79
+ .query("agentSessions")
80
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
81
+ .first();
82
+
83
+ if (!session) {
84
+ return { error: "Invalid session" };
85
+ }
86
+
87
+ // Validate URL
88
+ try {
89
+ new URL(args.url);
90
+ } catch {
91
+ return { error: "Invalid URL format" };
92
+ }
93
+
94
+ // Validate URL is HTTPS
95
+ if (!args.url.startsWith("https://")) {
96
+ return { error: "Webhook URL must use HTTPS" };
97
+ }
98
+
99
+ // Validate events
100
+ const validEvents = args.events.filter((e) =>
101
+ WEBHOOK_EVENTS.includes(e as typeof WEBHOOK_EVENTS[number])
102
+ );
103
+
104
+ if (validEvents.length === 0) {
105
+ return { error: "At least one valid event is required" };
106
+ }
107
+
108
+ // Check webhook limit (max 5 per workspace)
109
+ const existingWebhooks = await ctx.db
110
+ .query("webhooks")
111
+ .withIndex("by_workspaceId", (q) => q.eq("workspaceId", session.workspaceId))
112
+ .collect();
113
+
114
+ if (existingWebhooks.length >= 5) {
115
+ return { error: "Maximum 5 webhooks per workspace" };
116
+ }
117
+
118
+ // Check for duplicate URL
119
+ const duplicate = existingWebhooks.find((wh) => wh.url === args.url);
120
+ if (duplicate) {
121
+ return { error: "A webhook with this URL already exists" };
122
+ }
123
+
124
+ // Generate secret
125
+ const secret = generateSecret();
126
+
127
+ // Create webhook
128
+ const webhookId = await ctx.db.insert("webhooks", {
129
+ workspaceId: session.workspaceId,
130
+ url: args.url,
131
+ events: validEvents,
132
+ secret,
133
+ enabled: true,
134
+ failCount: 0,
135
+ createdAt: Date.now(),
136
+ });
137
+
138
+ return {
139
+ success: true,
140
+ webhookId,
141
+ secret, // Return secret only once on creation
142
+ };
143
+ },
144
+ });
145
+
146
+ export const updateWebhook = mutation({
147
+ args: {
148
+ token: v.string(),
149
+ webhookId: v.id("webhooks"),
150
+ enabled: v.optional(v.boolean()),
151
+ events: v.optional(v.array(v.string())),
152
+ },
153
+ handler: async (ctx, args) => {
154
+ // Verify session
155
+ const session = await ctx.db
156
+ .query("agentSessions")
157
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
158
+ .first();
159
+
160
+ if (!session) {
161
+ return { error: "Invalid session" };
162
+ }
163
+
164
+ // Get webhook
165
+ const webhook = await ctx.db.get(args.webhookId);
166
+
167
+ if (!webhook || webhook.workspaceId !== session.workspaceId) {
168
+ return { error: "Webhook not found" };
169
+ }
170
+
171
+ // Build update object
172
+ const updates: Partial<{
173
+ enabled: boolean;
174
+ events: string[];
175
+ }> = {};
176
+
177
+ if (args.enabled !== undefined) {
178
+ updates.enabled = args.enabled;
179
+ }
180
+
181
+ if (args.events !== undefined) {
182
+ const validEvents = args.events.filter((e) =>
183
+ WEBHOOK_EVENTS.includes(e as typeof WEBHOOK_EVENTS[number])
184
+ );
185
+ if (validEvents.length === 0) {
186
+ return { error: "At least one valid event is required" };
187
+ }
188
+ updates.events = validEvents;
189
+ }
190
+
191
+ // Update webhook
192
+ await ctx.db.patch(args.webhookId, updates);
193
+
194
+ return { success: true };
195
+ },
196
+ });
197
+
198
+ export const deleteWebhook = mutation({
199
+ args: {
200
+ token: v.string(),
201
+ webhookId: v.id("webhooks"),
202
+ },
203
+ handler: async (ctx, args) => {
204
+ // Verify session
205
+ const session = await ctx.db
206
+ .query("agentSessions")
207
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
208
+ .first();
209
+
210
+ if (!session) {
211
+ return { error: "Invalid session" };
212
+ }
213
+
214
+ // Get webhook
215
+ const webhook = await ctx.db.get(args.webhookId);
216
+
217
+ if (!webhook || webhook.workspaceId !== session.workspaceId) {
218
+ return { error: "Webhook not found" };
219
+ }
220
+
221
+ // Delete webhook
222
+ await ctx.db.delete(args.webhookId);
223
+
224
+ return { success: true };
225
+ },
226
+ });
227
+
228
+ export const regenerateSecret = mutation({
229
+ args: {
230
+ token: v.string(),
231
+ webhookId: v.id("webhooks"),
232
+ },
233
+ handler: async (ctx, args) => {
234
+ // Verify session
235
+ const session = await ctx.db
236
+ .query("agentSessions")
237
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
238
+ .first();
239
+
240
+ if (!session) {
241
+ return { error: "Invalid session" };
242
+ }
243
+
244
+ // Get webhook
245
+ const webhook = await ctx.db.get(args.webhookId);
246
+
247
+ if (!webhook || webhook.workspaceId !== session.workspaceId) {
248
+ return { error: "Webhook not found" };
249
+ }
250
+
251
+ // Generate new secret
252
+ const newSecret = generateSecret();
253
+
254
+ // Update webhook
255
+ await ctx.db.patch(args.webhookId, { secret: newSecret });
256
+
257
+ return {
258
+ success: true,
259
+ secret: newSecret, // Return new secret
260
+ };
261
+ },
262
+ });
263
+
264
+ // ============================================
265
+ // ACTIONS (for HTTP calls)
266
+ // ============================================
267
+
268
+ export const testWebhook = action({
269
+ args: {
270
+ token: v.string(),
271
+ webhookId: v.id("webhooks"),
272
+ },
273
+ returns: v.union(
274
+ v.object({ error: v.string() }),
275
+ v.object({ success: v.literal(true), status: v.number(), message: v.string() }),
276
+ v.object({ success: v.literal(false), status: v.optional(v.number()), message: v.string() })
277
+ ),
278
+ handler: async (ctx, args): Promise<
279
+ | { error: string }
280
+ | { success: true; status: number; message: string }
281
+ | { success: false; status?: number; message: string }
282
+ > => {
283
+ // Get webhook from database
284
+ const queryResult = await ctx.runQuery(internal.webhooks.getWebhookInternal, {
285
+ token: args.token,
286
+ webhookId: args.webhookId,
287
+ });
288
+
289
+ if (!queryResult || "error" in queryResult) {
290
+ return { error: queryResult?.error || "Webhook not found" };
291
+ }
292
+
293
+ const webhook = queryResult.webhook;
294
+
295
+ // Create test payload
296
+ const payload = {
297
+ event: "test",
298
+ workspace: webhook.workspaceId,
299
+ timestamp: new Date().toISOString(),
300
+ data: {
301
+ message: "This is a test webhook from APIClaw",
302
+ webhookId: args.webhookId,
303
+ },
304
+ };
305
+
306
+ // Sign the payload
307
+ const signature = await signPayload(JSON.stringify(payload), webhook.secret);
308
+
309
+ try {
310
+ const response = await fetch(webhook.url, {
311
+ method: "POST",
312
+ headers: {
313
+ "Content-Type": "application/json",
314
+ "X-APIClaw-Signature": signature,
315
+ "X-APIClaw-Event": "test",
316
+ "X-APIClaw-Timestamp": payload.timestamp,
317
+ },
318
+ body: JSON.stringify(payload),
319
+ });
320
+
321
+ if (response.ok) {
322
+ return {
323
+ success: true as const,
324
+ status: response.status,
325
+ message: "Webhook delivered successfully",
326
+ };
327
+ } else {
328
+ return {
329
+ success: false as const,
330
+ status: response.status,
331
+ message: `Webhook returned status ${response.status}`,
332
+ };
333
+ }
334
+ } catch (error) {
335
+ return {
336
+ success: false as const,
337
+ message: error instanceof Error ? error.message : "Failed to deliver webhook",
338
+ };
339
+ }
340
+ },
341
+ });
342
+
343
+ // Internal action to trigger webhooks (called from other parts of the system)
344
+ export const triggerWebhooks = internalAction({
345
+ args: {
346
+ workspaceId: v.id("workspaces"),
347
+ event: v.string(),
348
+ data: v.any(),
349
+ },
350
+ returns: v.object({ triggered: v.number(), total: v.optional(v.number()) }),
351
+ handler: async (ctx, args): Promise<{ triggered: number; total?: number }> => {
352
+ // Get all enabled webhooks for this workspace that subscribe to this event
353
+ const webhooksResult = await ctx.runQuery(internal.webhooks.getWebhooksForEvent, {
354
+ workspaceId: args.workspaceId,
355
+ event: args.event,
356
+ });
357
+
358
+ if (!webhooksResult || webhooksResult.length === 0) {
359
+ return { triggered: 0 };
360
+ }
361
+
362
+ const payload = {
363
+ event: args.event,
364
+ workspace: args.workspaceId,
365
+ timestamp: new Date().toISOString(),
366
+ data: args.data,
367
+ };
368
+
369
+ const payloadString = JSON.stringify(payload);
370
+ let successCount = 0;
371
+
372
+ // Send to each webhook
373
+ for (const webhook of webhooksResult) {
374
+ const signature = await signPayload(payloadString, webhook.secret);
375
+
376
+ try {
377
+ const response = await fetch(webhook.url, {
378
+ method: "POST",
379
+ headers: {
380
+ "Content-Type": "application/json",
381
+ "X-APIClaw-Signature": signature,
382
+ "X-APIClaw-Event": args.event,
383
+ "X-APIClaw-Timestamp": payload.timestamp,
384
+ },
385
+ body: payloadString,
386
+ });
387
+
388
+ // Update webhook status
389
+ await ctx.runMutation(internal.webhooks.updateWebhookStatus, {
390
+ webhookId: webhook._id,
391
+ success: response.ok,
392
+ });
393
+
394
+ if (response.ok) {
395
+ successCount++;
396
+ }
397
+ } catch {
398
+ // Update webhook with failure
399
+ await ctx.runMutation(internal.webhooks.updateWebhookStatus, {
400
+ webhookId: webhook._id,
401
+ success: false,
402
+ });
403
+ }
404
+ }
405
+
406
+ return { triggered: successCount, total: webhooksResult.length };
407
+ },
408
+ });
409
+
410
+ // ============================================
411
+ // INTERNAL QUERIES/MUTATIONS (for actions)
412
+ // ============================================
413
+
414
+ export const getWebhookInternal = internalQuery({
415
+ args: {
416
+ token: v.string(),
417
+ webhookId: v.id("webhooks"),
418
+ },
419
+ handler: async (ctx, args): Promise<{ error: string } | { webhook: Doc<"webhooks"> }> => {
420
+ // Verify session
421
+ const session = await ctx.db
422
+ .query("agentSessions")
423
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
424
+ .first();
425
+
426
+ if (!session) {
427
+ return { error: "Invalid session" };
428
+ }
429
+
430
+ // Get webhook
431
+ const webhook = await ctx.db.get(args.webhookId);
432
+
433
+ if (!webhook || webhook.workspaceId !== session.workspaceId) {
434
+ return { error: "Webhook not found" };
435
+ }
436
+
437
+ return { webhook };
438
+ },
439
+ });
440
+
441
+ export const getWebhooksForEvent = internalQuery({
442
+ args: {
443
+ workspaceId: v.id("workspaces"),
444
+ event: v.string(),
445
+ },
446
+ handler: async (ctx, args): Promise<Doc<"webhooks">[]> => {
447
+ const webhooks = await ctx.db
448
+ .query("webhooks")
449
+ .withIndex("by_workspaceId", (q) => q.eq("workspaceId", args.workspaceId))
450
+ .collect();
451
+
452
+ // Filter for enabled webhooks that subscribe to this event
453
+ return webhooks.filter(
454
+ (wh) => wh.enabled && wh.events.includes(args.event)
455
+ );
456
+ },
457
+ });
458
+
459
+ export const updateWebhookStatus = internalMutation({
460
+ args: {
461
+ webhookId: v.id("webhooks"),
462
+ success: v.boolean(),
463
+ },
464
+ handler: async (ctx, args) => {
465
+ const webhook = await ctx.db.get(args.webhookId);
466
+ if (!webhook) return;
467
+
468
+ await ctx.db.patch(args.webhookId, {
469
+ lastTriggeredAt: Date.now(),
470
+ lastStatus: args.success ? "success" : "failed",
471
+ failCount: args.success ? 0 : webhook.failCount + 1,
472
+ });
473
+
474
+ // Disable webhook after 5 consecutive failures
475
+ if (!args.success && webhook.failCount + 1 >= 5) {
476
+ await ctx.db.patch(args.webhookId, { enabled: false });
477
+ }
478
+ },
479
+ });
480
+
481
+ // ============================================
482
+ // HELPERS
483
+ // ============================================
484
+
485
+ async function signPayload(payload: string, secret: string): Promise<string> {
486
+ // Simple HMAC-like signature using SHA-256
487
+ // In a production environment, use proper crypto
488
+ const encoder = new TextEncoder();
489
+ const data = encoder.encode(payload + secret);
490
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
491
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
492
+ const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
493
+ return `sha256=${hashHex}`;
494
+ }
@@ -0,0 +1,31 @@
1
+ export declare const createMagicLink: any;
2
+ export declare const verifyMagicLink: any;
3
+ export declare const getSession: any;
4
+ export declare const getWorkspaceDashboard: any;
5
+ export declare const getConnectedAgents: any;
6
+ export declare const adminDeleteSession: any;
7
+ export declare const getSessionsByEmail: any;
8
+ export declare const renameAgent: any;
9
+ export declare const getUsageBreakdown: any;
10
+ export declare const revokeAgentSession: any;
11
+ export declare const logout: any;
12
+ export declare const updateTier: any;
13
+ export declare const incrementUsage: any;
14
+ export declare const pollMagicLink: any;
15
+ export declare const verifySession: any;
16
+ export declare const getByEmail: any;
17
+ export declare const touchSession: any;
18
+ export declare const createWorkspace: any;
19
+ export declare const updateWorkspaceName: any;
20
+ export declare const setPassword: any;
21
+ export declare const createAgentSession: any;
22
+ export declare const getWorkspaceStatus: any;
23
+ export declare const adminActivateWorkspace: any;
24
+ export declare const adminCreateSession: any;
25
+ export declare const adminGetFullWorkspace: any;
26
+ /**
27
+ * Claim anonymous usage history when a user registers
28
+ * Links all analytics records with matching fingerprint to the workspace
29
+ */
30
+ export declare const claimAnonymousUsage: any;
31
+ //# sourceMappingURL=workspaces.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workspaces.d.ts","sourceRoot":"","sources":["workspaces.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,eAAe,KAmB1B,CAAC;AAaH,eAAO,MAAM,eAAe,KA0K1B,CAAC;AAGH,eAAO,MAAM,UAAU,KAwBrB,CAAC;AAOH,eAAO,MAAM,qBAAqB,KAqGhC,CAAC;AASH,eAAO,MAAM,kBAAkB,KA2B7B,CAAC;AAGH,eAAO,MAAM,kBAAkB,KAM7B,CAAC;AAGH,eAAO,MAAM,kBAAkB,KA4B7B,CAAC;AAGH,eAAO,MAAM,WAAW,KA4BtB,CAAC;AAGH,eAAO,MAAM,iBAAiB,KA+D5B,CAAC;AAOH,eAAO,MAAM,kBAAkB,KAqC7B,CAAC;AAGH,eAAO,MAAM,MAAM,KAcjB,CAAC;AAOH,eAAO,MAAM,UAAU,KAqBrB,CAAC;AA0BH,eAAO,MAAM,cAAc,KAwEzB,CAAC;AAOH,eAAO,MAAM,aAAa,KAsDxB,CAAC;AAGH,eAAO,MAAM,aAAa,KAyBxB,CAAC;AAGH,eAAO,MAAM,UAAU,KAqBrB,CAAC;AAGH,eAAO,MAAM,YAAY,KAYvB,CAAC;AAOH,eAAO,MAAM,eAAe,KAiC1B,CAAC;AAGH,eAAO,MAAM,mBAAmB,KAwB9B,CAAC;AAGH,eAAO,MAAM,WAAW,KA4BtB,CAAC;AAGH,eAAO,MAAM,kBAAkB,KA2B7B,CAAC;AAgBH,eAAO,MAAM,kBAAkB,KAmC7B,CAAC;AAGH,eAAO,MAAM,sBAAsB,KAiBjC,CAAC;AAEH,eAAO,MAAM,kBAAkB,KAyB7B,CAAC;AAGH,eAAO,MAAM,qBAAqB,KA0BhC,CAAC;AAEH;;;GAGG;AACH,eAAO,MAAM,mBAAmB,KAkC9B,CAAC"}