@nordsym/apiclaw 1.8.7 → 1.8.9

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 (156) hide show
  1. package/README.md +58 -30
  2. package/convex/adminActivate.d.ts +3 -0
  3. package/convex/adminActivate.d.ts.map +1 -1
  4. package/convex/adminActivate.js +46 -0
  5. package/convex/adminActivate.js.map +1 -1
  6. package/convex/adminActivate.ts +1 -2
  7. package/convex/adminStats.d.ts +9 -0
  8. package/convex/adminStats.d.ts.map +1 -1
  9. package/convex/adminStats.js +282 -0
  10. package/convex/adminStats.js.map +1 -1
  11. package/convex/adminStats.ts +5 -3
  12. package/convex/agents.d.ts +84 -0
  13. package/convex/agents.js +809 -0
  14. package/convex/analytics.d.ts +5 -0
  15. package/convex/analytics.js +167 -0
  16. package/convex/apiKeys.d.ts +6 -0
  17. package/convex/apiKeys.d.ts.map +1 -0
  18. package/convex/apiKeys.js +186 -0
  19. package/convex/apiKeys.js.map +1 -0
  20. package/convex/backfillAnalytics.d.ts +2 -0
  21. package/convex/backfillAnalytics.js +20 -0
  22. package/convex/backfillSearchLogs.d.ts +2 -0
  23. package/convex/backfillSearchLogs.js +29 -0
  24. package/convex/billing.d.ts +88 -0
  25. package/convex/billing.d.ts.map +1 -1
  26. package/convex/billing.js +643 -0
  27. package/convex/billing.js.map +1 -1
  28. package/convex/billing.ts +2 -14
  29. package/convex/capabilities.d.ts +9 -0
  30. package/convex/capabilities.js +145 -0
  31. package/convex/chains.d.ts +68 -0
  32. package/convex/chains.js +1105 -0
  33. package/convex/credits.d.ts +25 -0
  34. package/convex/credits.js +186 -0
  35. package/convex/crons.d.ts +3 -0
  36. package/convex/crons.js +17 -0
  37. package/convex/debugFilestackLogs.d.ts +2 -0
  38. package/convex/debugFilestackLogs.js +17 -0
  39. package/convex/debugGetToken.d.ts +2 -0
  40. package/convex/debugGetToken.js +18 -0
  41. package/convex/directCall.d.ts +72 -0
  42. package/convex/directCall.d.ts.map +1 -1
  43. package/convex/directCall.js +663 -0
  44. package/convex/directCall.js.map +1 -1
  45. package/convex/earnProgress.d.ts +58 -0
  46. package/convex/earnProgress.js +649 -0
  47. package/convex/email.d.ts +14 -0
  48. package/convex/email.js +300 -0
  49. package/convex/email.js.map +1 -1
  50. package/convex/feedback.d.ts +7 -0
  51. package/convex/feedback.js +227 -0
  52. package/convex/http.d.ts +3 -0
  53. package/convex/http.d.ts.map +1 -1
  54. package/convex/http.js +2135 -0
  55. package/convex/http.js.map +1 -1
  56. package/convex/http.ts +275 -3
  57. package/convex/inbound.d.ts +2 -0
  58. package/convex/inbound.js +32 -0
  59. package/convex/logs.d.ts +48 -0
  60. package/convex/logs.d.ts.map +1 -1
  61. package/convex/logs.js +623 -0
  62. package/convex/logs.js.map +1 -1
  63. package/convex/migrateFilestack.d.ts +2 -0
  64. package/convex/migrateFilestack.js +74 -0
  65. package/convex/migratePartnersProd.d.ts +8 -0
  66. package/convex/migratePartnersProd.js +165 -0
  67. package/convex/migratePratham.d.ts +2 -0
  68. package/convex/migratePratham.js +121 -0
  69. package/convex/migrateProviderWorkspaces.d.ts +13 -0
  70. package/convex/migrateProviderWorkspaces.d.ts.map +1 -1
  71. package/convex/migrateProviderWorkspaces.js +141 -0
  72. package/convex/migrateProviderWorkspaces.js.map +1 -1
  73. package/convex/mou.d.ts +6 -0
  74. package/convex/mou.js +82 -0
  75. package/convex/providerKeys.d.ts +31 -0
  76. package/convex/providerKeys.js +257 -0
  77. package/convex/providers.d.ts +35 -0
  78. package/convex/providers.d.ts.map +1 -1
  79. package/convex/providers.js +1027 -0
  80. package/convex/providers.js.map +1 -1
  81. package/convex/purchases.d.ts +7 -0
  82. package/convex/purchases.js +157 -0
  83. package/convex/ratelimit.d.ts +4 -0
  84. package/convex/ratelimit.js +91 -0
  85. package/convex/schema.ts +4 -4
  86. package/convex/searchLogs.d.ts +13 -0
  87. package/convex/searchLogs.d.ts.map +1 -1
  88. package/convex/searchLogs.js +241 -0
  89. package/convex/searchLogs.js.map +1 -1
  90. package/convex/seedAPILayerAPIs.d.ts +7 -0
  91. package/convex/seedAPILayerAPIs.js +177 -0
  92. package/convex/seedDirectCallConfigs.d.ts +2 -0
  93. package/convex/seedDirectCallConfigs.js +324 -0
  94. package/convex/seedPratham.d.ts +6 -0
  95. package/convex/seedPratham.d.ts.map +1 -1
  96. package/convex/seedPratham.js +149 -0
  97. package/convex/seedPratham.js.map +1 -1
  98. package/convex/seedPratham.ts +1 -2
  99. package/convex/spendAlerts.d.ts +36 -0
  100. package/convex/spendAlerts.js +380 -0
  101. package/convex/spendAlerts.js.map +1 -1
  102. package/convex/stripeActions.d.ts +19 -0
  103. package/convex/stripeActions.d.ts.map +1 -1
  104. package/convex/stripeActions.js +432 -0
  105. package/convex/stripeActions.js.map +1 -1
  106. package/convex/stripeActions.ts +25 -3
  107. package/convex/teams.d.ts +21 -0
  108. package/convex/teams.js +215 -0
  109. package/convex/telemetry.d.ts +4 -0
  110. package/convex/telemetry.js +74 -0
  111. package/convex/updateAPIStatus.d.ts +6 -0
  112. package/convex/updateAPIStatus.d.ts.map +1 -1
  113. package/convex/updateAPIStatus.js +39 -0
  114. package/convex/updateAPIStatus.js.map +1 -1
  115. package/convex/usage.d.ts +27 -0
  116. package/convex/usage.js +229 -0
  117. package/convex/waitlist.d.ts +4 -0
  118. package/convex/waitlist.js +49 -0
  119. package/convex/webhooks.d.ts +12 -0
  120. package/convex/webhooks.js +410 -0
  121. package/convex/workspaceSettings.d.ts +7 -0
  122. package/convex/workspaceSettings.d.ts.map +1 -0
  123. package/convex/workspaceSettings.js +128 -0
  124. package/convex/workspaceSettings.js.map +1 -0
  125. package/convex/workspaces.d.ts +33 -0
  126. package/convex/workspaces.d.ts.map +1 -1
  127. package/convex/workspaces.js +989 -0
  128. package/convex/workspaces.js.map +1 -1
  129. package/convex/workspaces.ts +18 -20
  130. package/dist/bin.js +0 -0
  131. package/dist/cli/commands/demo.js +1 -1
  132. package/dist/cli/commands/demo.js.map +1 -1
  133. package/dist/cli/commands/doctor.js.map +1 -1
  134. package/dist/cli/commands/login.js.map +1 -1
  135. package/dist/cli/commands/setup.js.map +1 -1
  136. package/dist/credentials.d.ts.map +1 -1
  137. package/dist/credentials.js +15 -0
  138. package/dist/credentials.js.map +1 -1
  139. package/dist/discovery.js.map +1 -1
  140. package/dist/execute.js.map +1 -1
  141. package/dist/index.js +1 -1
  142. package/dist/index.js.map +1 -1
  143. package/dist/mcp-analytics.js +1 -1
  144. package/dist/mcp-analytics.js.map +1 -1
  145. package/dist/open-apis.d.ts.map +1 -1
  146. package/dist/open-apis.js +94 -2
  147. package/dist/open-apis.js.map +1 -1
  148. package/dist/ui/errors.js.map +1 -1
  149. package/dist/ui/prompts.js.map +1 -1
  150. package/package.json +1 -1
  151. package/src/cli/commands/demo.ts +1 -1
  152. package/src/credentials.ts +16 -0
  153. package/src/index.ts +1 -1
  154. package/src/mcp-analytics.ts +1 -1
  155. package/src/open-apis.ts +114 -4
  156. package/src/types/convex-api.d.ts +20 -0
@@ -0,0 +1,663 @@
1
+ import { v } from "convex/values";
2
+ import { mutation, query } from "./_generated/server";
3
+ // ============================================
4
+ // MUTATIONS
5
+ // ============================================
6
+ /**
7
+ * Save/update provider's Direct Call configuration
8
+ */
9
+ export const saveDirectCallConfig = mutation({
10
+ args: {
11
+ id: v.optional(v.id("providerDirectCall")),
12
+ providerId: v.id("providers"),
13
+ apiId: v.optional(v.id("providerAPIs")),
14
+ baseUrl: v.string(),
15
+ authType: v.string(),
16
+ authHeader: v.string(),
17
+ authPrefix: v.string(),
18
+ encryptedMasterKey: v.string(),
19
+ rateLimitPerUser: v.number(),
20
+ rateLimitPerDay: v.number(),
21
+ pricePerRequest: v.number(),
22
+ },
23
+ handler: async (ctx, args) => {
24
+ const now = Date.now();
25
+ if (args.id) {
26
+ // Update existing
27
+ await ctx.db.patch(args.id, {
28
+ baseUrl: args.baseUrl,
29
+ authType: args.authType,
30
+ authHeader: args.authHeader,
31
+ authPrefix: args.authPrefix,
32
+ encryptedMasterKey: args.encryptedMasterKey,
33
+ rateLimitPerUser: args.rateLimitPerUser,
34
+ rateLimitPerDay: args.rateLimitPerDay,
35
+ pricePerRequest: args.pricePerRequest,
36
+ updatedAt: now,
37
+ });
38
+ return args.id;
39
+ }
40
+ // Create new
41
+ return await ctx.db.insert("providerDirectCall", {
42
+ providerId: args.providerId,
43
+ apiId: args.apiId,
44
+ baseUrl: args.baseUrl,
45
+ authType: args.authType,
46
+ authHeader: args.authHeader,
47
+ authPrefix: args.authPrefix,
48
+ encryptedMasterKey: args.encryptedMasterKey,
49
+ rateLimitPerUser: args.rateLimitPerUser,
50
+ rateLimitPerDay: args.rateLimitPerDay,
51
+ pricePerRequest: args.pricePerRequest,
52
+ status: "draft",
53
+ createdAt: now,
54
+ updatedAt: now,
55
+ });
56
+ },
57
+ });
58
+ /**
59
+ * Save Direct Call config with token auth (used by frontend)
60
+ */
61
+ export const saveConfig = mutation({
62
+ args: {
63
+ token: v.string(),
64
+ config: v.object({
65
+ apiId: v.string(),
66
+ baseUrl: v.string(),
67
+ authType: v.string(),
68
+ authHeader: v.string(),
69
+ authPrefix: v.string(),
70
+ masterApiKey: v.optional(v.string()),
71
+ rateLimitPerUser: v.number(),
72
+ rateLimitPerDay: v.number(),
73
+ pricePerRequest: v.number(),
74
+ status: v.string(),
75
+ allowCustomerKeys: v.optional(v.boolean()),
76
+ requireCustomerKeys: v.optional(v.boolean()),
77
+ }),
78
+ },
79
+ handler: async (ctx, args) => {
80
+ // Verify session (unified: agentSessions first, fallback to legacy sessions)
81
+ let providerId = null;
82
+ const agentSession = await ctx.db
83
+ .query("agentSessions")
84
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
85
+ .first();
86
+ if (agentSession) {
87
+ const provider = await ctx.db
88
+ .query("providers")
89
+ .withIndex("by_workspaceId", (q) => q.eq("workspaceId", agentSession.workspaceId))
90
+ .first();
91
+ if (!provider)
92
+ throw new Error("No provider linked to workspace");
93
+ providerId = provider._id;
94
+ }
95
+ else {
96
+ // Fallback: legacy sessions
97
+ const session = await ctx.db
98
+ .query("sessions")
99
+ .withIndex("by_token", (q) => q.eq("token", args.token))
100
+ .first();
101
+ if (!session || session.expiresAt < Date.now()) {
102
+ throw new Error("Invalid or expired session");
103
+ }
104
+ providerId = session.providerId;
105
+ }
106
+ const now = Date.now();
107
+ const { config } = args;
108
+ // Check if config already exists for this API
109
+ const existing = await ctx.db
110
+ .query("providerDirectCall")
111
+ .filter((q) => q.eq(q.field("apiId"), config.apiId))
112
+ .first();
113
+ if (existing) {
114
+ // Update existing
115
+ const updateData = {
116
+ baseUrl: config.baseUrl,
117
+ authType: config.authType,
118
+ authHeader: config.authHeader,
119
+ authPrefix: config.authPrefix,
120
+ rateLimitPerUser: config.rateLimitPerUser,
121
+ rateLimitPerDay: config.rateLimitPerDay,
122
+ pricePerRequest: config.pricePerRequest,
123
+ status: config.status,
124
+ allowCustomerKeys: config.allowCustomerKeys ?? true,
125
+ requireCustomerKeys: config.requireCustomerKeys ?? false,
126
+ updatedAt: now,
127
+ };
128
+ // Only update master key if provided (not empty)
129
+ if (config.masterApiKey) {
130
+ updateData.encryptedMasterKey = config.masterApiKey; // In prod: encrypt this
131
+ }
132
+ await ctx.db.patch(existing._id, updateData);
133
+ return existing._id;
134
+ }
135
+ // Create new config
136
+ return await ctx.db.insert("providerDirectCall", {
137
+ providerId,
138
+ apiId: config.apiId,
139
+ baseUrl: config.baseUrl,
140
+ authType: config.authType,
141
+ authHeader: config.authHeader,
142
+ authPrefix: config.authPrefix,
143
+ encryptedMasterKey: config.masterApiKey || "",
144
+ rateLimitPerUser: config.rateLimitPerUser,
145
+ rateLimitPerDay: config.rateLimitPerDay,
146
+ pricePerRequest: config.pricePerRequest,
147
+ status: config.status,
148
+ allowCustomerKeys: config.allowCustomerKeys ?? true,
149
+ requireCustomerKeys: config.requireCustomerKeys ?? false,
150
+ createdAt: now,
151
+ updatedAt: now,
152
+ });
153
+ },
154
+ });
155
+ /**
156
+ * Create/update an action for a Direct Call config
157
+ */
158
+ export const saveAction = mutation({
159
+ args: {
160
+ id: v.optional(v.id("providerActions")),
161
+ directCallId: v.id("providerDirectCall"),
162
+ name: v.string(),
163
+ displayName: v.string(),
164
+ description: v.string(),
165
+ method: v.string(),
166
+ path: v.string(),
167
+ params: v.array(v.object({
168
+ name: v.string(),
169
+ type: v.string(),
170
+ required: v.boolean(),
171
+ description: v.string(),
172
+ default: v.optional(v.any()),
173
+ in: v.string(),
174
+ })),
175
+ responseMapping: v.array(v.object({
176
+ name: v.string(),
177
+ path: v.string(),
178
+ })),
179
+ enabled: v.boolean(),
180
+ },
181
+ handler: async (ctx, args) => {
182
+ const now = Date.now();
183
+ if (args.id) {
184
+ // Update existing
185
+ await ctx.db.patch(args.id, {
186
+ name: args.name,
187
+ displayName: args.displayName,
188
+ description: args.description,
189
+ method: args.method,
190
+ path: args.path,
191
+ params: args.params,
192
+ responseMapping: args.responseMapping,
193
+ enabled: args.enabled,
194
+ updatedAt: now,
195
+ });
196
+ return args.id;
197
+ }
198
+ // Create new
199
+ return await ctx.db.insert("providerActions", {
200
+ directCallId: args.directCallId,
201
+ name: args.name,
202
+ displayName: args.displayName,
203
+ description: args.description,
204
+ method: args.method,
205
+ path: args.path,
206
+ params: args.params,
207
+ responseMapping: args.responseMapping,
208
+ enabled: args.enabled,
209
+ createdAt: now,
210
+ updatedAt: now,
211
+ });
212
+ },
213
+ });
214
+ /**
215
+ * Delete an action
216
+ */
217
+ export const deleteAction = mutation({
218
+ args: {
219
+ id: v.id("providerActions"),
220
+ },
221
+ handler: async (ctx, args) => {
222
+ await ctx.db.delete(args.id);
223
+ return { success: true };
224
+ },
225
+ });
226
+ /**
227
+ * Publish Direct Call - set status to live
228
+ * Also marks apiListed earn progress for the provider's workspace
229
+ */
230
+ export const publishDirectCall = mutation({
231
+ args: {
232
+ id: v.id("providerDirectCall"),
233
+ },
234
+ handler: async (ctx, args) => {
235
+ const now = Date.now();
236
+ // Get the direct call config to find the provider
237
+ const config = await ctx.db.get(args.id);
238
+ if (!config) {
239
+ throw new Error("Direct Call config not found");
240
+ }
241
+ await ctx.db.patch(args.id, {
242
+ status: "live",
243
+ publishedAt: now,
244
+ updatedAt: now,
245
+ });
246
+ // Try to mark apiListed for earn progress
247
+ // First, get the provider to find their session/workspace
248
+ const provider = await ctx.db.get(config.providerId);
249
+ if (provider) {
250
+ // Find workspace by provider email
251
+ const workspace = await ctx.db
252
+ .query("workspaces")
253
+ .withIndex("by_email", (q) => q.eq("email", provider.email))
254
+ .first();
255
+ if (workspace) {
256
+ // Update earn progress
257
+ const earnProgress = await ctx.db
258
+ .query("earnProgress")
259
+ .withIndex("by_workspaceId", (q) => q.eq("workspaceId", workspace._id))
260
+ .first();
261
+ if (earnProgress && !earnProgress.apiListed) {
262
+ const newTotal = calculateEarnTotal({ ...earnProgress, apiListed: true });
263
+ await ctx.db.patch(earnProgress._id, {
264
+ apiListed: true,
265
+ apiListedAt: now,
266
+ totalEarned: newTotal,
267
+ updatedAt: now,
268
+ });
269
+ // Add 10 calls to workspace limit
270
+ await ctx.db.patch(workspace._id, {
271
+ usageLimit: workspace.usageLimit + 10,
272
+ updatedAt: now,
273
+ });
274
+ }
275
+ else if (!earnProgress) {
276
+ // Create earn progress with apiListed
277
+ await ctx.db.insert("earnProgress", {
278
+ workspaceId: workspace._id,
279
+ firstDirectCall: false,
280
+ apisUsed: [],
281
+ apisUsedComplete: false,
282
+ agentListed: false,
283
+ apiListed: true,
284
+ apiListedAt: now,
285
+ byokSetup: false,
286
+ githubStarred: false,
287
+ twitterFollowed: false,
288
+ referralCount: 0,
289
+ totalEarned: 10,
290
+ createdAt: now,
291
+ updatedAt: now,
292
+ });
293
+ // Add 10 calls to workspace limit
294
+ await ctx.db.patch(workspace._id, {
295
+ usageLimit: workspace.usageLimit + 10,
296
+ updatedAt: now,
297
+ });
298
+ }
299
+ }
300
+ }
301
+ return { success: true, publishedAt: now };
302
+ },
303
+ });
304
+ // Helper to calculate earn total (duplicated to avoid circular import)
305
+ function calculateEarnTotal(progress) {
306
+ let total = 0;
307
+ if (progress.firstDirectCall)
308
+ total += 15;
309
+ if (progress.apisUsedComplete)
310
+ total += 10;
311
+ if (progress.agentListed)
312
+ total += 10;
313
+ if (progress.apiListed)
314
+ total += 10;
315
+ if (progress.byokSetup)
316
+ total += 5;
317
+ if (progress.githubStarred)
318
+ total += 10;
319
+ if (progress.twitterFollowed)
320
+ total += 5;
321
+ total += (progress.referralCount || 0) * 10;
322
+ return total;
323
+ }
324
+ /**
325
+ * Set Direct Call status (draft, testing, live)
326
+ */
327
+ export const setStatus = mutation({
328
+ args: {
329
+ id: v.id("providerDirectCall"),
330
+ status: v.string(),
331
+ },
332
+ handler: async (ctx, args) => {
333
+ const now = Date.now();
334
+ const update = {
335
+ status: args.status,
336
+ updatedAt: now,
337
+ };
338
+ if (args.status === "live") {
339
+ update.publishedAt = now;
340
+ }
341
+ await ctx.db.patch(args.id, update);
342
+ return { success: true };
343
+ },
344
+ });
345
+ // ============================================
346
+ // QUERIES
347
+ // ============================================
348
+ /**
349
+ * Get Direct Call config by providerId
350
+ */
351
+ export const getDirectCallConfig = query({
352
+ args: {
353
+ providerId: v.id("providers"),
354
+ },
355
+ handler: async (ctx, args) => {
356
+ return await ctx.db
357
+ .query("providerDirectCall")
358
+ .withIndex("by_providerId", (q) => q.eq("providerId", args.providerId))
359
+ .first();
360
+ },
361
+ });
362
+ /**
363
+ * Get Direct Call config by ID
364
+ */
365
+ export const getDirectCallConfigById = query({
366
+ args: {
367
+ id: v.id("providerDirectCall"),
368
+ },
369
+ handler: async (ctx, args) => {
370
+ return await ctx.db.get(args.id);
371
+ },
372
+ });
373
+ /**
374
+ * Get Direct Call config by API ID
375
+ */
376
+ export const getDirectCallConfigByApiId = query({
377
+ args: {
378
+ apiId: v.string(), // Accept string since that's what frontend passes
379
+ },
380
+ handler: async (ctx, args) => {
381
+ return await ctx.db
382
+ .query("providerDirectCall")
383
+ .filter((q) => q.eq(q.field("apiId"), args.apiId))
384
+ .first();
385
+ },
386
+ });
387
+ /**
388
+ * Get all actions for a Direct Call config
389
+ */
390
+ export const getActions = query({
391
+ args: {
392
+ directCallId: v.id("providerDirectCall"),
393
+ },
394
+ handler: async (ctx, args) => {
395
+ return await ctx.db
396
+ .query("providerActions")
397
+ .withIndex("by_directCallId", (q) => q.eq("directCallId", args.directCallId))
398
+ .collect();
399
+ },
400
+ });
401
+ /**
402
+ * Get single action by directCallId + name
403
+ */
404
+ export const getActionByName = query({
405
+ args: {
406
+ directCallId: v.id("providerDirectCall"),
407
+ name: v.string(),
408
+ },
409
+ handler: async (ctx, args) => {
410
+ return await ctx.db
411
+ .query("providerActions")
412
+ .withIndex("by_directCallId_name", (q) => q.eq("directCallId", args.directCallId).eq("name", args.name))
413
+ .first();
414
+ },
415
+ });
416
+ /**
417
+ * Get action by ID
418
+ */
419
+ export const getActionById = query({
420
+ args: {
421
+ id: v.id("providerActions"),
422
+ },
423
+ handler: async (ctx, args) => {
424
+ return await ctx.db.get(args.id);
425
+ },
426
+ });
427
+ /**
428
+ * DEBUG: Get all Direct Call configs
429
+ */
430
+ export const getAllConfigs = query({
431
+ args: {},
432
+ handler: async (ctx) => {
433
+ return await ctx.db.query("providerDirectCall").collect();
434
+ },
435
+ });
436
+ /**
437
+ * Get all live Direct Call configs (for public API discovery)
438
+ */
439
+ export const getLiveConfigs = query({
440
+ args: {},
441
+ handler: async (ctx) => {
442
+ return await ctx.db
443
+ .query("providerDirectCall")
444
+ .withIndex("by_status", (q) => q.eq("status", "live"))
445
+ .collect();
446
+ },
447
+ });
448
+ /**
449
+ * Get Direct Call config by API ID (for test console)
450
+ */
451
+ export const getConfig = query({
452
+ args: {
453
+ apiId: v.string(),
454
+ },
455
+ handler: async (ctx, args) => {
456
+ // Try as providerAPIs ID first
457
+ const config = await ctx.db
458
+ .query("providerDirectCall")
459
+ .withIndex("by_apiId")
460
+ .filter((q) => q.eq(q.field("apiId"), args.apiId))
461
+ .first();
462
+ return config;
463
+ },
464
+ });
465
+ /**
466
+ * Get Direct Call config by API slug (for MCP/agent execution)
467
+ * Looks up API by name, then gets the Direct Call config
468
+ */
469
+ export const getByApiSlug = query({
470
+ args: {
471
+ slug: v.string(),
472
+ },
473
+ handler: async (ctx, args) => {
474
+ // Normalize slug (lowercase, replace spaces/dashes)
475
+ const normalizedSlug = args.slug.toLowerCase().replace(/[\s-]/g, '_');
476
+ // Find API by name (case-insensitive match)
477
+ const apis = await ctx.db.query("providerAPIs").collect();
478
+ const api = apis.find(a => a.name.toLowerCase().replace(/[\s-]/g, '_') === normalizedSlug ||
479
+ a.name.toLowerCase() === args.slug.toLowerCase());
480
+ if (!api) {
481
+ return null;
482
+ }
483
+ // Get Direct Call config for this API
484
+ const config = await ctx.db
485
+ .query("providerDirectCall")
486
+ .withIndex("by_apiId")
487
+ .filter((q) => q.eq(q.field("apiId"), api._id))
488
+ .first();
489
+ if (!config || config.status !== 'live') {
490
+ return null;
491
+ }
492
+ return {
493
+ ...config,
494
+ apiName: api.name,
495
+ apiSlug: normalizedSlug,
496
+ };
497
+ },
498
+ });
499
+ // ============================================
500
+ // TEST ACTION
501
+ // ============================================
502
+ /**
503
+ * Test an action by calling the actual provider API
504
+ * For V1: Provider passes their own test key
505
+ */
506
+ export const testAction = mutation({
507
+ args: {
508
+ token: v.string(),
509
+ directCallId: v.id("providerDirectCall"),
510
+ actionId: v.id("providerActions"),
511
+ params: v.record(v.string(), v.any()),
512
+ testKey: v.optional(v.string()),
513
+ },
514
+ handler: async (ctx, args) => {
515
+ const startTime = Date.now();
516
+ // 1. Verify provider session (unified: agentSessions first, fallback to legacy)
517
+ let sessionProviderId = null;
518
+ const agentSession = await ctx.db
519
+ .query("agentSessions")
520
+ .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
521
+ .first();
522
+ if (agentSession) {
523
+ const provider = await ctx.db
524
+ .query("providers")
525
+ .withIndex("by_workspaceId", (q) => q.eq("workspaceId", agentSession.workspaceId))
526
+ .first();
527
+ if (provider)
528
+ sessionProviderId = provider._id;
529
+ }
530
+ else {
531
+ const session = await ctx.db
532
+ .query("sessions")
533
+ .withIndex("by_token", (q) => q.eq("token", args.token))
534
+ .first();
535
+ if (session && session.expiresAt >= Date.now()) {
536
+ sessionProviderId = session.providerId;
537
+ }
538
+ }
539
+ if (!sessionProviderId) {
540
+ return {
541
+ success: false,
542
+ error: "Unauthorized - invalid or expired session",
543
+ latencyMs: Date.now() - startTime,
544
+ };
545
+ }
546
+ // 2. Get directCallConfig
547
+ const config = await ctx.db.get(args.directCallId);
548
+ if (!config) {
549
+ return {
550
+ success: false,
551
+ error: "Direct Call config not found",
552
+ latencyMs: Date.now() - startTime,
553
+ };
554
+ }
555
+ // Verify ownership
556
+ if (config.providerId !== sessionProviderId) {
557
+ return {
558
+ success: false,
559
+ error: "Unauthorized - you don't own this config",
560
+ latencyMs: Date.now() - startTime,
561
+ };
562
+ }
563
+ // 3. Get action
564
+ const action = await ctx.db.get(args.actionId);
565
+ if (!action) {
566
+ return {
567
+ success: false,
568
+ error: "Action not found",
569
+ latencyMs: Date.now() - startTime,
570
+ };
571
+ }
572
+ // 4. Get API key (use testKey if provided, else use stored key)
573
+ // Note: For production, encryptedMasterKey would need server-side decryption
574
+ // For V1 test console, we use testKey directly
575
+ const apiKey = args.testKey || config.encryptedMasterKey;
576
+ if (!apiKey) {
577
+ return {
578
+ success: false,
579
+ error: "No API key provided. Add a test key or configure master key.",
580
+ latencyMs: Date.now() - startTime,
581
+ };
582
+ }
583
+ // 5. Build URL with path params
584
+ let path = action.path;
585
+ const queryParams = {};
586
+ const bodyParams = {};
587
+ for (const paramDef of action.params) {
588
+ const value = args.params[paramDef.name];
589
+ if (value === undefined || value === "")
590
+ continue;
591
+ if (paramDef.in === "path") {
592
+ // Replace {paramName} in path
593
+ path = path.replace(`{${paramDef.name}}`, String(value));
594
+ }
595
+ else if (paramDef.in === "query") {
596
+ queryParams[paramDef.name] = String(value);
597
+ }
598
+ else if (paramDef.in === "body") {
599
+ bodyParams[paramDef.name] = value;
600
+ }
601
+ }
602
+ // Build full URL
603
+ let url = config.baseUrl.replace(/\/$/, "") + path;
604
+ const queryString = new URLSearchParams(queryParams).toString();
605
+ if (queryString) {
606
+ url += (url.includes("?") ? "&" : "?") + queryString;
607
+ }
608
+ // 6. Build headers with auth
609
+ const headers = {
610
+ "Content-Type": "application/json",
611
+ "Accept": "application/json",
612
+ };
613
+ // Add auth header
614
+ if (config.authType !== "none" && apiKey) {
615
+ const authValue = config.authPrefix
616
+ ? `${config.authPrefix}${apiKey}`
617
+ : apiKey;
618
+ headers[config.authHeader] = authValue;
619
+ }
620
+ // 7. Build fetch options
621
+ const fetchOptions = {
622
+ method: action.method,
623
+ headers,
624
+ };
625
+ // Add body for non-GET requests
626
+ if (action.method !== "GET" && Object.keys(bodyParams).length > 0) {
627
+ fetchOptions.body = JSON.stringify(bodyParams);
628
+ }
629
+ // 8. Execute request
630
+ try {
631
+ const response = await fetch(url, fetchOptions);
632
+ const latencyMs = Date.now() - startTime;
633
+ // Try to parse response as JSON, fallback to text
634
+ let data;
635
+ const contentType = response.headers.get("content-type") || "";
636
+ if (contentType.includes("application/json")) {
637
+ try {
638
+ data = await response.json();
639
+ }
640
+ catch {
641
+ data = await response.text();
642
+ }
643
+ }
644
+ else {
645
+ data = await response.text();
646
+ }
647
+ return {
648
+ success: response.ok,
649
+ status: response.status,
650
+ data,
651
+ latencyMs,
652
+ };
653
+ }
654
+ catch (error) {
655
+ return {
656
+ success: false,
657
+ error: error instanceof Error ? error.message : "Request failed",
658
+ latencyMs: Date.now() - startTime,
659
+ };
660
+ }
661
+ },
662
+ });
663
+ //# sourceMappingURL=directCall.js.map