@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
@@ -1,473 +0,0 @@
1
- /**
2
- * APIClaw Dynamic Executor
3
- * Executes provider-configured actions via self-service Direct Call
4
- */
5
- import { decryptKey, validateBaseUrl } from './crypto.js';
6
- // Convex HTTP API
7
- const CONVEX_URL = process.env.NEXT_PUBLIC_CONVEX_URL || 'https://brilliant-puffin-712.eu-west-1.convex.cloud';
8
- async function convexQuery(path, args) {
9
- try {
10
- const res = await fetch(`${CONVEX_URL}/api/query`, {
11
- method: 'POST',
12
- headers: { 'Content-Type': 'application/json' },
13
- body: JSON.stringify({ path, args }),
14
- });
15
- if (!res.ok) {
16
- console.error(`Convex query failed: ${res.status}`);
17
- return null;
18
- }
19
- const data = await res.json();
20
- return (data && typeof data === 'object' && 'value' in data) ? data.value : data;
21
- }
22
- catch (error) {
23
- console.error('Convex query error:', error);
24
- return null;
25
- }
26
- }
27
- async function convexMutation(path, args) {
28
- try {
29
- const res = await fetch(`${CONVEX_URL}/api/mutation`, {
30
- method: 'POST',
31
- headers: { 'Content-Type': 'application/json' },
32
- body: JSON.stringify({ path, args }),
33
- });
34
- return res.ok;
35
- }
36
- catch (error) {
37
- console.error('Convex mutation error:', error);
38
- return false;
39
- }
40
- }
41
- /**
42
- * Check if a provider has dynamic (self-service) config
43
- */
44
- export async function hasDynamicConfig(providerId) {
45
- const config = await getProviderConfig(providerId);
46
- return config !== null && config.status === 'live';
47
- }
48
- /**
49
- * Fetch provider direct call configuration from Convex
50
- */
51
- export async function getProviderConfig(providerId) {
52
- // First try by API slug (for agent execution by name)
53
- const bySlug = await convexQuery('directCall:getByApiSlug', { slug: providerId });
54
- // Check for error response from Convex (not a real config)
55
- const bySlugAny = bySlug;
56
- if (bySlug && !(bySlugAny.status === 'error' || bySlugAny.errorMessage)) {
57
- return bySlug;
58
- }
59
- // Only try direct provider ID lookup if it looks like a Convex ID (starts with valid prefix)
60
- // Convex IDs typically look like: k97xxx...
61
- if (providerId.match(/^[a-z][a-z0-9]{2,}/)) {
62
- const byId = await convexQuery('directCall:getDirectCallConfig', { providerId });
63
- const byIdAny = byId;
64
- if (byId && !(byIdAny.status === 'error' || byIdAny.errorMessage)) {
65
- return byId;
66
- }
67
- }
68
- return null;
69
- }
70
- /**
71
- * Fetch action configuration from Convex
72
- */
73
- export async function getActionConfig(providerId, actionName) {
74
- // First get the direct call config to get directCallId
75
- const config = await getProviderConfig(providerId);
76
- if (!config)
77
- return null;
78
- return convexQuery('directCall:getActionByName', {
79
- directCallId: config._id,
80
- name: actionName
81
- });
82
- }
83
- /**
84
- * Check if a dynamic action requires confirmation (for costly actions)
85
- * Returns action config if confirmation required, null otherwise
86
- */
87
- export async function getDynamicConfirmationConfig(providerId, actionName) {
88
- const action = await getActionConfig(providerId, actionName);
89
- if (!action) {
90
- return { required: false };
91
- }
92
- if (action.requiresConfirmation) {
93
- return {
94
- required: true,
95
- action,
96
- estimatedCost: action.estimatedCost
97
- };
98
- }
99
- return { required: false };
100
- }
101
- /**
102
- * Get user's current usage for rate limiting
103
- */
104
- export async function getUserUsage(userId, providerId) {
105
- const usage = await convexQuery('usage:getUserUsage', { userId, providerId });
106
- return usage || { minute: 0, day: 0 };
107
- }
108
- /**
109
- * Build the full URL with path and query parameters
110
- */
111
- export function buildUrl(baseUrl, path, params, paramDefs) {
112
- let finalPath = path;
113
- const queryParams = new URLSearchParams();
114
- for (const paramDef of paramDefs) {
115
- const value = params[paramDef.name] ?? paramDef.default;
116
- if (value === undefined)
117
- continue;
118
- const stringValue = typeof value === 'object' ? JSON.stringify(value) : String(value);
119
- if (paramDef.in === 'path') {
120
- // Replace path parameter: /users/{id} -> /users/123
121
- finalPath = finalPath.replace(`{${paramDef.name}}`, encodeURIComponent(stringValue));
122
- }
123
- else if (paramDef.in === 'query') {
124
- queryParams.set(paramDef.name, stringValue);
125
- }
126
- }
127
- // Ensure baseUrl doesn't end with slash and path starts with slash
128
- const cleanBase = baseUrl.replace(/\/$/, '');
129
- const cleanPath = finalPath.startsWith('/') ? finalPath : `/${finalPath}`;
130
- const queryString = queryParams.toString();
131
- return queryString ? `${cleanBase}${cleanPath}?${queryString}` : `${cleanBase}${cleanPath}`;
132
- }
133
- /**
134
- * Build request body from parameters
135
- */
136
- export function buildBody(params, paramDefs) {
137
- const bodyParams = {};
138
- for (const paramDef of paramDefs) {
139
- if (paramDef.in === 'body') {
140
- const value = params[paramDef.name] ?? paramDef.default;
141
- if (value !== undefined) {
142
- bodyParams[paramDef.name] = value;
143
- }
144
- }
145
- }
146
- if (Object.keys(bodyParams).length === 0) {
147
- return undefined;
148
- }
149
- return JSON.stringify(bodyParams);
150
- }
151
- /**
152
- * Build authentication headers based on auth type
153
- */
154
- export function buildAuthHeaders(config, decryptedKey) {
155
- const headers = {
156
- 'Content-Type': 'application/json',
157
- 'User-Agent': 'APIClaw/1.0',
158
- };
159
- const headerName = config.authHeader || 'Authorization';
160
- const prefix = config.authPrefix || '';
161
- switch (config.authType) {
162
- case 'bearer':
163
- headers[headerName] = prefix ? `${prefix} ${decryptedKey}` : `Bearer ${decryptedKey}`;
164
- break;
165
- case 'basic':
166
- // Assume decryptedKey is "username:password"
167
- const base64 = Buffer.from(decryptedKey).toString('base64');
168
- headers[headerName] = `Basic ${base64}`;
169
- break;
170
- case 'api_key':
171
- // Custom header with the key directly
172
- headers[headerName] = prefix ? `${prefix} ${decryptedKey}` : decryptedKey;
173
- break;
174
- case 'none':
175
- // No auth header needed
176
- break;
177
- }
178
- return headers;
179
- }
180
- /**
181
- * Extract value from object using simple JSONPath-like expression
182
- * Supports: $.field, $.field.nested, $.array[0], $.array[*].field
183
- */
184
- export function extractJsonPath(data, path) {
185
- if (!path.startsWith('$')) {
186
- return undefined;
187
- }
188
- const parts = path.slice(1).split('.').filter(Boolean);
189
- let current = data;
190
- for (const part of parts) {
191
- if (current === null || current === undefined) {
192
- return undefined;
193
- }
194
- // Handle array index: field[0] or field[*]
195
- const arrayMatch = part.match(/^(\w+)\[(\d+|\*)\]$/);
196
- if (arrayMatch) {
197
- const [, field, index] = arrayMatch;
198
- if (typeof current !== 'object')
199
- return undefined;
200
- current = current[field];
201
- if (!Array.isArray(current))
202
- return undefined;
203
- if (index === '*') {
204
- // Return all elements (will need further processing)
205
- continue;
206
- }
207
- else {
208
- current = current[parseInt(index)];
209
- }
210
- }
211
- else {
212
- if (typeof current !== 'object')
213
- return undefined;
214
- current = current[part];
215
- }
216
- }
217
- return current;
218
- }
219
- /**
220
- * Map response data using configured response mappings
221
- */
222
- export function mapResponse(data, responseMapping) {
223
- if (!responseMapping || responseMapping.length === 0) {
224
- // No mapping configured, return raw data
225
- return { raw: data };
226
- }
227
- const result = {};
228
- for (const mapping of responseMapping) {
229
- const value = extractJsonPath(data, mapping.path);
230
- if (value !== undefined) {
231
- result[mapping.name] = value;
232
- }
233
- }
234
- return result;
235
- }
236
- /**
237
- * Log usage to Convex
238
- */
239
- export async function logUsage(params) {
240
- await convexMutation('usage:logUsage', params);
241
- }
242
- /**
243
- * Main function: Execute a dynamically configured action
244
- */
245
- export async function executeDynamicAction(providerId, actionName, params, userId, customerKey) {
246
- const startTime = Date.now();
247
- // 1. Get provider config
248
- const config = await getProviderConfig(providerId);
249
- if (!config) {
250
- return {
251
- success: false,
252
- provider: providerId,
253
- action: actionName,
254
- error: 'Provider not found'
255
- };
256
- }
257
- if (config.status !== 'live') {
258
- return {
259
- success: false,
260
- provider: providerId,
261
- action: actionName,
262
- error: 'Provider not available (not live)'
263
- };
264
- }
265
- // 2. Validate base URL (SSRF prevention)
266
- const urlValidation = validateBaseUrl(config.baseUrl);
267
- if (!urlValidation.valid) {
268
- return {
269
- success: false,
270
- provider: providerId,
271
- action: actionName,
272
- error: `Invalid provider URL: ${urlValidation.error}`
273
- };
274
- }
275
- // 3. Check rate limits
276
- const usage = await getUserUsage(userId, providerId);
277
- if (usage.minute >= config.rateLimitPerUser) {
278
- return {
279
- success: false,
280
- provider: providerId,
281
- action: actionName,
282
- error: 'Rate limit exceeded (per minute)'
283
- };
284
- }
285
- if (usage.day >= config.rateLimitPerDay) {
286
- return {
287
- success: false,
288
- provider: providerId,
289
- action: actionName,
290
- error: 'Rate limit exceeded (daily)'
291
- };
292
- }
293
- // 4. Get action config
294
- const action = await getActionConfig(providerId, actionName);
295
- if (!action) {
296
- return {
297
- success: false,
298
- provider: providerId,
299
- action: actionName,
300
- error: 'Action not found'
301
- };
302
- }
303
- if (!action.enabled) {
304
- return {
305
- success: false,
306
- provider: providerId,
307
- action: actionName,
308
- error: 'Action is disabled'
309
- };
310
- }
311
- // 5. Validate required parameters
312
- for (const paramDef of action.params) {
313
- if (paramDef.required && params[paramDef.name] === undefined && paramDef.default === undefined) {
314
- return {
315
- success: false,
316
- provider: providerId,
317
- action: actionName,
318
- error: `Missing required parameter: ${paramDef.name}`
319
- };
320
- }
321
- }
322
- // 6. Resolve API key (customer key takes priority over master key)
323
- let apiKey;
324
- let usingCustomerKey = false;
325
- // Check if provider requires customer keys (like CoAccept)
326
- const requiresCustomerKey = config.requireCustomerKeys === true;
327
- const allowsCustomerKey = config.allowCustomerKeys !== false; // Default true
328
- if (customerKey && allowsCustomerKey) {
329
- // Customer provided their own key - use it, skip usage tracking
330
- apiKey = customerKey;
331
- usingCustomerKey = true;
332
- }
333
- else if (requiresCustomerKey) {
334
- // Provider requires customer key but none provided
335
- return {
336
- success: false,
337
- provider: providerId,
338
- action: actionName,
339
- error: 'This provider requires your own API key. Pass it via customer_key parameter.'
340
- };
341
- }
342
- else if (config.encryptedMasterKey) {
343
- // Use provider's master key - track usage for billing
344
- try {
345
- apiKey = decryptKey(config.encryptedMasterKey);
346
- }
347
- catch (error) {
348
- console.error('Failed to decrypt provider key:', error);
349
- return {
350
- success: false,
351
- provider: providerId,
352
- action: actionName,
353
- error: 'Provider configuration error'
354
- };
355
- }
356
- }
357
- else {
358
- // No key available
359
- return {
360
- success: false,
361
- provider: providerId,
362
- action: actionName,
363
- error: 'No API key available. Provide your own key via customer_key parameter.'
364
- };
365
- }
366
- // 7. Build request
367
- const url = buildUrl(config.baseUrl, action.path, params, action.params);
368
- const headers = buildAuthHeaders(config, apiKey);
369
- const body = action.method === 'GET' ? undefined : buildBody(params, action.params);
370
- // 8. Execute request
371
- let response;
372
- try {
373
- response = await fetch(url, {
374
- method: action.method,
375
- headers,
376
- body,
377
- });
378
- }
379
- catch (error) {
380
- const latencyMs = Date.now() - startTime;
381
- // Only log usage when using master key (for billing)
382
- if (!usingCustomerKey) {
383
- await logUsage({
384
- userId,
385
- providerId,
386
- actionName,
387
- timestamp: Date.now(),
388
- success: false,
389
- latencyMs,
390
- creditsUsed: 0
391
- });
392
- }
393
- return {
394
- success: false,
395
- provider: providerId,
396
- action: actionName,
397
- error: `Network error: ${error instanceof Error ? error.message : 'Unknown error'}`,
398
- latencyMs
399
- };
400
- }
401
- const latencyMs = Date.now() - startTime;
402
- // 9. Parse response
403
- let data;
404
- try {
405
- const contentType = response.headers.get('content-type');
406
- if (contentType?.includes('application/json')) {
407
- data = await response.json();
408
- }
409
- else {
410
- data = await response.text();
411
- }
412
- }
413
- catch {
414
- data = null;
415
- }
416
- // 10. Log usage (only when using master key for billing)
417
- if (!usingCustomerKey) {
418
- await logUsage({
419
- userId,
420
- providerId,
421
- actionName,
422
- timestamp: Date.now(),
423
- success: response.ok,
424
- latencyMs,
425
- creditsUsed: response.ok ? config.pricePerRequest : 0
426
- });
427
- }
428
- // 11. Handle error response
429
- if (!response.ok) {
430
- let errorMessage = `HTTP ${response.status}`;
431
- if (data && typeof data === 'object') {
432
- const errorObj = data;
433
- errorMessage = errorObj.message ||
434
- errorObj.error ||
435
- errorObj.detail ||
436
- errorMessage;
437
- }
438
- return {
439
- success: false,
440
- provider: providerId,
441
- action: actionName,
442
- error: errorMessage,
443
- latencyMs
444
- };
445
- }
446
- // 12. Map response and return
447
- const mappedData = mapResponse(data, action.responseMapping);
448
- return {
449
- success: true,
450
- provider: providerId,
451
- action: actionName,
452
- data: mappedData,
453
- cost: config.pricePerRequest,
454
- latencyMs
455
- };
456
- }
457
- /**
458
- * List available actions for a dynamic provider
459
- */
460
- export async function listDynamicActions(providerId) {
461
- const config = await getProviderConfig(providerId);
462
- if (!config || config.status !== 'live') {
463
- return [];
464
- }
465
- const actions = await convexQuery('directCall:getActions', {
466
- directCallId: config._id
467
- });
468
- if (!actions)
469
- return [];
470
- return actions
471
- .filter(a => a.enabled)
472
- .map(a => a.name);
473
- }