@nordsym/apiclaw 1.7.3 → 1.7.5

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