@nordsym/apiclaw 1.8.5 → 1.8.7

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 (145) hide show
  1. package/README.md +4 -4
  2. package/apiclaw-README.md +12 -12
  3. package/convex/_generated/api.d.ts +16 -0
  4. package/convex/analytics.d.ts.map +1 -1
  5. package/convex/analytics.js.map +1 -1
  6. package/convex/analytics.ts +1 -0
  7. package/convex/apiKeys.ts +220 -0
  8. package/convex/backfillAnalytics.d.ts.map +1 -0
  9. package/convex/backfillAnalytics.js.map +1 -0
  10. package/convex/backfillAnalytics.ts +22 -0
  11. package/convex/backfillSearchLogs.d.ts.map +1 -0
  12. package/convex/backfillSearchLogs.js.map +1 -0
  13. package/convex/backfillSearchLogs.ts +35 -0
  14. package/convex/debugFilestackLogs.d.ts.map +1 -0
  15. package/convex/debugFilestackLogs.js.map +1 -0
  16. package/convex/debugFilestackLogs.ts +16 -0
  17. package/convex/debugGetToken.d.ts.map +1 -0
  18. package/convex/debugGetToken.js.map +1 -0
  19. package/convex/debugGetToken.ts +18 -0
  20. package/convex/directCall.ts +49 -14
  21. package/convex/email.ts +5 -5
  22. package/convex/http.d.ts.map +1 -1
  23. package/convex/http.js.map +1 -1
  24. package/convex/http.ts +611 -49
  25. package/convex/logs.ts +26 -22
  26. package/convex/migrateFilestack.d.ts.map +1 -1
  27. package/convex/migrateFilestack.js.map +1 -1
  28. package/convex/migrateFilestack.ts +65 -101
  29. package/convex/migratePartnersProd.d.ts.map +1 -0
  30. package/convex/migratePartnersProd.js.map +1 -0
  31. package/convex/migratePartnersProd.ts +174 -0
  32. package/convex/migrateProviderWorkspaces.d.ts.map +1 -0
  33. package/convex/migrateProviderWorkspaces.js.map +1 -0
  34. package/convex/migrateProviderWorkspaces.ts +175 -0
  35. package/convex/providers.js.map +1 -1
  36. package/convex/providers.ts +313 -203
  37. package/convex/schema.ts +50 -1
  38. package/convex/searchLogs.d.ts.map +1 -1
  39. package/convex/searchLogs.js.map +1 -1
  40. package/convex/searchLogs.ts +11 -3
  41. package/convex/seedPratham.ts +1 -1
  42. package/convex/spendAlerts.ts +2 -2
  43. package/convex/stripeActions.ts +1 -1
  44. package/convex/updateAPIStatus.ts +2 -3
  45. package/convex/workspaceSettings.ts +136 -0
  46. package/dist/bin-http.js +0 -0
  47. package/dist/bin.js +0 -0
  48. package/dist/cli/commands/demo.js +2 -2
  49. package/dist/cli/commands/doctor.js +1 -1
  50. package/dist/cli/commands/login.js +1 -1
  51. package/dist/cli/commands/setup.js +2 -2
  52. package/dist/discovery.js +1 -1
  53. package/dist/execute.js +3 -3
  54. package/dist/index.js +13 -13
  55. package/dist/registry/apis.json +1 -1
  56. package/dist/ui/errors.js +16 -16
  57. package/dist/ui/prompts.js +1 -1
  58. package/email-templates/filestack-provider-outreach.html +1 -1
  59. package/email-templates/partnership-template.html +1 -1
  60. package/email-templates/pratham-partnership-draft.html +2 -2
  61. package/package.json +2 -2
  62. package/reports/APIClaw-Session-Report-2026-04-05.pdf +0 -0
  63. package/reports/session-report-2026-04-05.html +433 -0
  64. package/src/cli/commands/demo.ts +2 -2
  65. package/src/cli/commands/doctor.ts +1 -1
  66. package/src/cli/commands/login.ts +1 -1
  67. package/src/cli/commands/setup.ts +2 -2
  68. package/src/discovery.ts +1 -1
  69. package/src/execute.ts +3 -3
  70. package/src/index.ts +14 -14
  71. package/src/registry/apis.json +1 -1
  72. package/src/ui/errors.ts +16 -16
  73. package/src/ui/prompts.ts +1 -1
  74. package/convex/adminActivate.d.ts +0 -3
  75. package/convex/adminActivate.js +0 -47
  76. package/convex/adminStats.d.ts +0 -9
  77. package/convex/adminStats.js +0 -280
  78. package/convex/agents.d.ts +0 -84
  79. package/convex/agents.js +0 -809
  80. package/convex/analytics.d.ts +0 -5
  81. package/convex/analytics.js +0 -166
  82. package/convex/billing.d.ts +0 -88
  83. package/convex/billing.js +0 -655
  84. package/convex/capabilities.d.ts +0 -9
  85. package/convex/capabilities.js +0 -145
  86. package/convex/chains.d.ts +0 -68
  87. package/convex/chains.js +0 -1105
  88. package/convex/credits.d.ts +0 -25
  89. package/convex/credits.js +0 -186
  90. package/convex/crons.d.ts +0 -3
  91. package/convex/crons.js +0 -17
  92. package/convex/directCall.d.ts +0 -72
  93. package/convex/directCall.js +0 -627
  94. package/convex/earnProgress.d.ts +0 -58
  95. package/convex/earnProgress.js +0 -649
  96. package/convex/email.d.ts +0 -14
  97. package/convex/email.js +0 -300
  98. package/convex/feedback.d.ts +0 -7
  99. package/convex/feedback.js +0 -227
  100. package/convex/http.d.ts +0 -3
  101. package/convex/http.js +0 -1405
  102. package/convex/inbound.d.ts +0 -2
  103. package/convex/inbound.js +0 -32
  104. package/convex/logs.d.ts +0 -48
  105. package/convex/logs.js +0 -621
  106. package/convex/migrateFilestack.d.ts +0 -2
  107. package/convex/migrateFilestack.js +0 -113
  108. package/convex/migratePratham.d.ts +0 -2
  109. package/convex/migratePratham.js +0 -121
  110. package/convex/mou.d.ts +0 -6
  111. package/convex/mou.js +0 -82
  112. package/convex/providerKeys.d.ts +0 -31
  113. package/convex/providerKeys.js +0 -257
  114. package/convex/providers.d.ts +0 -35
  115. package/convex/providers.js +0 -922
  116. package/convex/purchases.d.ts +0 -7
  117. package/convex/purchases.js +0 -157
  118. package/convex/ratelimit.d.ts +0 -4
  119. package/convex/ratelimit.js +0 -91
  120. package/convex/searchLogs.d.ts +0 -13
  121. package/convex/searchLogs.js +0 -232
  122. package/convex/seedAPILayerAPIs.d.ts +0 -7
  123. package/convex/seedAPILayerAPIs.js +0 -177
  124. package/convex/seedDirectCallConfigs.d.ts +0 -2
  125. package/convex/seedDirectCallConfigs.js +0 -324
  126. package/convex/seedPratham.d.ts +0 -6
  127. package/convex/seedPratham.js +0 -150
  128. package/convex/spendAlerts.d.ts +0 -36
  129. package/convex/spendAlerts.js +0 -380
  130. package/convex/stripeActions.d.ts +0 -19
  131. package/convex/stripeActions.js +0 -411
  132. package/convex/teams.d.ts +0 -21
  133. package/convex/teams.js +0 -215
  134. package/convex/telemetry.d.ts +0 -4
  135. package/convex/telemetry.js +0 -74
  136. package/convex/updateAPIStatus.d.ts +0 -6
  137. package/convex/updateAPIStatus.js +0 -40
  138. package/convex/usage.d.ts +0 -27
  139. package/convex/usage.js +0 -229
  140. package/convex/waitlist.d.ts +0 -4
  141. package/convex/waitlist.js +0 -49
  142. package/convex/webhooks.d.ts +0 -12
  143. package/convex/webhooks.js +0 -410
  144. package/convex/workspaces.d.ts +0 -33
  145. package/convex/workspaces.js +0 -991
package/convex/logs.js DELETED
@@ -1,621 +0,0 @@
1
- import { v } from "convex/values";
2
- import { mutation, query } from "./_generated/server";
3
- // ============================================
4
- // MUTATIONS
5
- // ============================================
6
- /**
7
- * Create a log entry for an API call
8
- * Called after each Direct Call execution
9
- */
10
- export const createLog = mutation({
11
- args: {
12
- token: v.string(),
13
- provider: v.string(),
14
- action: v.string(),
15
- status: v.union(v.literal("success"), v.literal("error")),
16
- latencyMs: v.number(),
17
- errorMessage: v.optional(v.string()),
18
- subagentId: v.optional(v.string()), // from X-APIClaw-Subagent header
19
- },
20
- handler: async (ctx, args) => {
21
- // Verify session and get workspace
22
- const session = await ctx.db
23
- .query("agentSessions")
24
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
25
- .first();
26
- if (!session) {
27
- throw new Error("Invalid session token");
28
- }
29
- // Create log entry
30
- return await ctx.db.insert("apiLogs", {
31
- workspaceId: session.workspaceId,
32
- sessionToken: args.token,
33
- subagentId: args.subagentId,
34
- provider: args.provider,
35
- action: args.action,
36
- status: args.status,
37
- latencyMs: args.latencyMs,
38
- errorMessage: args.errorMessage,
39
- createdAt: Date.now(),
40
- });
41
- },
42
- });
43
- /**
44
- * Internal log creation (when workspaceId is already known)
45
- * Used by execute functions that have already verified the session
46
- */
47
- export const createLogInternal = mutation({
48
- args: {
49
- workspaceId: v.id("workspaces"),
50
- sessionToken: v.string(),
51
- provider: v.string(),
52
- action: v.string(),
53
- status: v.union(v.literal("success"), v.literal("error")),
54
- latencyMs: v.number(),
55
- errorMessage: v.optional(v.string()),
56
- subagentId: v.optional(v.string()), // from X-APIClaw-Subagent header
57
- },
58
- handler: async (ctx, args) => {
59
- return await ctx.db.insert("apiLogs", {
60
- workspaceId: args.workspaceId,
61
- sessionToken: args.sessionToken,
62
- subagentId: args.subagentId,
63
- provider: args.provider,
64
- action: args.action,
65
- status: args.status,
66
- latencyMs: args.latencyMs,
67
- errorMessage: args.errorMessage,
68
- createdAt: Date.now(),
69
- });
70
- },
71
- });
72
- /**
73
- * Log an inbound call to a provider's workspace
74
- * Called when someone uses an API that belongs to another workspace
75
- */
76
- export const logProviderCall = mutation({
77
- args: {
78
- provider: v.string(),
79
- action: v.string(),
80
- status: v.union(v.literal("success"), v.literal("error")),
81
- latencyMs: v.number(),
82
- callerWorkspaceId: v.string(),
83
- subagentId: v.optional(v.string()),
84
- errorMessage: v.optional(v.string()),
85
- },
86
- handler: async (ctx, args) => {
87
- // Map provider to workspace email (for providers with workspaces)
88
- const providerEmailMap = {
89
- apilayer: "pratham@apilayer.com",
90
- };
91
- const providerEmail = providerEmailMap[args.provider];
92
- let workspace = null;
93
- if (providerEmail) {
94
- workspace = await ctx.db
95
- .query("workspaces")
96
- .withIndex("by_email", (q) => q.eq("email", providerEmail))
97
- .first();
98
- }
99
- // Always log to global provider analytics (even without workspace)
100
- await ctx.db.insert("apiLogs", {
101
- workspaceId: workspace?._id || "global",
102
- sessionToken: "",
103
- provider: args.provider,
104
- action: args.action,
105
- status: args.status,
106
- latencyMs: args.latencyMs,
107
- direction: "provider-call",
108
- callerWorkspaceId: args.callerWorkspaceId,
109
- subagentId: args.subagentId,
110
- errorMessage: args.errorMessage,
111
- createdAt: Date.now(),
112
- });
113
- // If provider has workspace, also log as inbound to their workspace
114
- if (!workspace)
115
- return { logged: "global" };
116
- return await ctx.db.insert("apiLogs", {
117
- workspaceId: workspace._id,
118
- sessionToken: "",
119
- provider: args.provider,
120
- action: args.action,
121
- status: args.status,
122
- latencyMs: args.latencyMs,
123
- direction: "inbound",
124
- callerWorkspaceId: args.callerWorkspaceId,
125
- subagentId: args.subagentId,
126
- errorMessage: args.errorMessage,
127
- createdAt: Date.now(),
128
- });
129
- },
130
- });
131
- /**
132
- * Get analytics for a provider workspace (inbound calls to their APIs)
133
- * Used by API Analytics tab in workspace dashboard
134
- */
135
- export const getProviderAnalytics = query({
136
- args: {
137
- token: v.string(),
138
- hoursBack: v.optional(v.number()),
139
- },
140
- handler: async (ctx, { token, hoursBack = 168 }) => {
141
- const session = await ctx.db
142
- .query("agentSessions")
143
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
144
- .first();
145
- if (!session)
146
- return null;
147
- const since = Date.now() - hoursBack * 60 * 60 * 1000;
148
- // Get all logs for this workspace
149
- const allLogs = await ctx.db
150
- .query("apiLogs")
151
- .withIndex("by_workspaceId", (q) => q.eq("workspaceId", session.workspaceId))
152
- .collect();
153
- const periodLogs = allLogs.filter((l) => l.createdAt >= since);
154
- const inboundLogs = periodLogs.filter((l) => l.direction === "inbound");
155
- const outboundLogs = periodLogs.filter((l) => l.direction !== "inbound");
156
- // Daily buckets — separate calls and searches
157
- const byDay = {};
158
- periodLogs.forEach((l) => {
159
- const day = new Date(l.createdAt).toISOString().split("T")[0];
160
- if (!byDay[day])
161
- byDay[day] = { calls: 0, searches: 0 };
162
- if (l.action.startsWith("discovery:")) {
163
- byDay[day].searches++;
164
- }
165
- else {
166
- byDay[day].calls++;
167
- }
168
- });
169
- // By action (individual API endpoints, not just provider name)
170
- const byAction = {};
171
- periodLogs.forEach((l) => {
172
- const isDiscovery = l.action.startsWith("discovery:");
173
- const key = isDiscovery ? l.action : `${l.provider}:${l.action}`;
174
- const displayName = isDiscovery ? l.action.replace("discovery:", "Search: ") : l.action;
175
- if (!byAction[displayName])
176
- byAction[displayName] = { calls: 0, success: 0, type: isDiscovery ? "discovery" : "call" };
177
- byAction[displayName].calls++;
178
- if (l.status === "success")
179
- byAction[displayName].success++;
180
- });
181
- // Unique callers (for inbound)
182
- const uniqueCallers = new Set(inboundLogs.map((l) => l.callerWorkspaceId).filter(Boolean)).size;
183
- // Counts
184
- const callLogs = periodLogs.filter((l) => !l.action.startsWith("discovery:"));
185
- const discoveryLogs = periodLogs.filter((l) => l.action.startsWith("discovery:"));
186
- return {
187
- totalCalls: callLogs.length,
188
- totalDiscoveries: discoveryLogs.length,
189
- inboundCalls: inboundLogs.filter((l) => !l.action.startsWith("discovery:")).length,
190
- outboundCalls: outboundLogs.length,
191
- byDay: Object.entries(byDay)
192
- .map(([date, data]) => ({ date, calls: data.calls, searches: data.searches }))
193
- .sort((a, b) => a.date.localeCompare(b.date)),
194
- byAction: Object.entries(byAction)
195
- .map(([action, stats]) => ({ action, ...stats }))
196
- .sort((a, b) => b.calls - a.calls),
197
- successRate: periodLogs.length > 0
198
- ? (periodLogs.filter((l) => l.status === "success").length / periodLogs.length) * 100
199
- : 100,
200
- avgLatency: periodLogs.length > 0
201
- ? periodLogs.reduce((sum, l) => sum + l.latencyMs, 0) / periodLogs.length
202
- : 0,
203
- };
204
- },
205
- });
206
- // ============================================
207
- // HELPER: Get month start
208
- // ============================================
209
- function getMonthStart() {
210
- const now = new Date();
211
- return new Date(now.getUTCFullYear(), now.getUTCMonth(), 1, 0, 0, 0, 0).getTime();
212
- }
213
- /**
214
- * Combined log creation + spend tracking (PRD 2.6)
215
- * Creates log entry, tracks spend, returns budget status
216
- * Returns shouldSendAlert: true if 80% threshold crossed (caller should send email)
217
- */
218
- export const createLogWithSpend = mutation({
219
- args: {
220
- workspaceId: v.id("workspaces"),
221
- sessionToken: v.string(),
222
- provider: v.string(),
223
- action: v.string(),
224
- status: v.union(v.literal("success"), v.literal("error")),
225
- latencyMs: v.number(),
226
- costCents: v.number(), // Cost in USD cents
227
- errorMessage: v.optional(v.string()),
228
- subagentId: v.optional(v.string()),
229
- },
230
- handler: async (ctx, args) => {
231
- const now = Date.now();
232
- const monthStart = getMonthStart();
233
- // 1. Create log entry
234
- const logId = await ctx.db.insert("apiLogs", {
235
- workspaceId: args.workspaceId,
236
- sessionToken: args.sessionToken,
237
- subagentId: args.subagentId,
238
- provider: args.provider,
239
- action: args.action,
240
- status: args.status,
241
- latencyMs: args.latencyMs,
242
- errorMessage: args.errorMessage,
243
- createdAt: now,
244
- });
245
- // 2. Track spend if successful call with cost
246
- if (args.status === "success" && args.costCents > 0) {
247
- const workspace = await ctx.db.get(args.workspaceId);
248
- if (!workspace) {
249
- return { logId, spendTracked: false };
250
- }
251
- // Reset monthly spend if new month
252
- let currentSpend = workspace.monthlySpendCents || 0;
253
- if (!workspace.lastSpendResetAt || workspace.lastSpendResetAt < monthStart) {
254
- currentSpend = 0;
255
- }
256
- // Add new spend
257
- const newSpend = currentSpend + args.costCents;
258
- const budgetCap = workspace.budgetCap;
259
- // Update workspace
260
- await ctx.db.patch(args.workspaceId, {
261
- monthlySpendCents: newSpend,
262
- lastSpendResetAt: monthStart,
263
- updatedAt: now,
264
- });
265
- // Check if we need to send alert (80% threshold)
266
- let shouldSendAlert = false;
267
- let budgetExceeded = false;
268
- if (budgetCap && budgetCap > 0) {
269
- const threshold = budgetCap * 0.8;
270
- const alertAlreadySentThisMonth = workspace.budgetAlertSentAt &&
271
- workspace.budgetAlertSentAt >= monthStart;
272
- // Check if at 80% and alert not yet sent
273
- if (newSpend >= threshold && !alertAlreadySentThisMonth) {
274
- shouldSendAlert = true;
275
- await ctx.db.patch(args.workspaceId, {
276
- budgetAlertSentAt: now,
277
- });
278
- }
279
- // Check if budget exceeded
280
- if (newSpend >= budgetCap) {
281
- budgetExceeded = true;
282
- }
283
- }
284
- return {
285
- logId,
286
- spendTracked: true,
287
- currentSpendCents: newSpend,
288
- budgetCapCents: budgetCap || null,
289
- budgetPercentage: budgetCap ? Math.round((newSpend / budgetCap) * 100) : null,
290
- shouldSendAlert,
291
- budgetExceeded,
292
- email: workspace.email,
293
- };
294
- }
295
- return { logId, spendTracked: false };
296
- },
297
- });
298
- // ============================================
299
- // QUERIES
300
- // ============================================
301
- /**
302
- * Get logs for a workspace with pagination and filters
303
- */
304
- export const getLogs = query({
305
- args: {
306
- token: v.string(),
307
- limit: v.optional(v.number()),
308
- cursor: v.optional(v.number()), // createdAt timestamp for pagination
309
- status: v.optional(v.union(v.literal("success"), v.literal("error"), v.literal("all"))),
310
- provider: v.optional(v.string()),
311
- subagentId: v.optional(v.string()), // filter by subagent
312
- },
313
- handler: async (ctx, args) => {
314
- const limit = args.limit ?? 50;
315
- const status = args.status ?? "all";
316
- const provider = args.provider;
317
- const subagentId = args.subagentId;
318
- const cursor = args.cursor;
319
- // Verify session
320
- const session = await ctx.db
321
- .query("agentSessions")
322
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
323
- .first();
324
- if (!session) {
325
- return { logs: [], hasMore: false };
326
- }
327
- // Get logs for workspace
328
- let query = ctx.db
329
- .query("apiLogs")
330
- .withIndex("by_workspaceId_createdAt", (q) => q.eq("workspaceId", session.workspaceId))
331
- .order("desc");
332
- // Apply cursor (pagination)
333
- if (cursor) {
334
- query = query.filter((q) => q.lt(q.field("createdAt"), cursor));
335
- }
336
- // Collect more than limit to check hasMore
337
- const allLogs = await query.take(limit + 1);
338
- // Apply filters in-memory (Convex doesn't support complex compound filters)
339
- let filteredLogs = allLogs;
340
- if (status !== "all") {
341
- filteredLogs = filteredLogs.filter((log) => log.status === status);
342
- }
343
- if (provider && provider !== "all") {
344
- filteredLogs = filteredLogs.filter((log) => log.provider === provider);
345
- }
346
- // Filter by subagent
347
- if (subagentId) {
348
- if (subagentId === "main") {
349
- // Main agent calls (no subagentId)
350
- filteredLogs = filteredLogs.filter((log) => !log.subagentId);
351
- }
352
- else {
353
- filteredLogs = filteredLogs.filter((log) => log.subagentId === subagentId);
354
- }
355
- }
356
- const hasMore = filteredLogs.length > limit;
357
- const logs = filteredLogs.slice(0, limit);
358
- return {
359
- logs: logs.map((log) => ({
360
- id: log._id,
361
- provider: log.provider,
362
- action: log.action,
363
- status: log.status,
364
- latencyMs: log.latencyMs,
365
- errorMessage: log.errorMessage,
366
- subagentId: log.subagentId || null,
367
- createdAt: log.createdAt,
368
- })),
369
- hasMore,
370
- nextCursor: logs.length > 0 ? logs[logs.length - 1].createdAt : undefined,
371
- };
372
- },
373
- });
374
- /**
375
- * Get aggregated log stats for workspace
376
- */
377
- export const getLogStats = query({
378
- args: {
379
- token: v.string(),
380
- periodDays: v.optional(v.number()),
381
- },
382
- handler: async (ctx, args) => {
383
- const periodDays = args.periodDays ?? 7;
384
- // Verify session
385
- const session = await ctx.db
386
- .query("agentSessions")
387
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
388
- .first();
389
- if (!session) {
390
- return {
391
- totalCalls: 0,
392
- successCount: 0,
393
- errorCount: 0,
394
- successRate: 0,
395
- avgLatency: 0,
396
- byProvider: [],
397
- byDay: [],
398
- };
399
- }
400
- const now = Date.now();
401
- const periodStart = now - periodDays * 24 * 60 * 60 * 1000;
402
- // Get all logs for this workspace in the period
403
- const logs = await ctx.db
404
- .query("apiLogs")
405
- .withIndex("by_workspaceId_createdAt", (q) => q.eq("workspaceId", session.workspaceId))
406
- .filter((q) => q.gte(q.field("createdAt"), periodStart))
407
- .collect();
408
- const totalCalls = logs.length;
409
- const successCount = logs.filter((l) => l.status === "success").length;
410
- const errorCount = logs.filter((l) => l.status === "error").length;
411
- const successRate = totalCalls > 0 ? (successCount / totalCalls) * 100 : 0;
412
- const totalLatency = logs.reduce((sum, l) => sum + l.latencyMs, 0);
413
- const avgLatency = totalCalls > 0 ? Math.round(totalLatency / totalCalls) : 0;
414
- // Group by provider
415
- const byProviderMap = {};
416
- for (const log of logs) {
417
- if (!byProviderMap[log.provider]) {
418
- byProviderMap[log.provider] = { calls: 0, success: 0, error: 0, latency: 0 };
419
- }
420
- byProviderMap[log.provider].calls++;
421
- byProviderMap[log.provider].latency += log.latencyMs;
422
- if (log.status === "success") {
423
- byProviderMap[log.provider].success++;
424
- }
425
- else {
426
- byProviderMap[log.provider].error++;
427
- }
428
- }
429
- const byProvider = Object.entries(byProviderMap)
430
- .map(([provider, data]) => ({
431
- provider,
432
- calls: data.calls,
433
- successRate: data.calls > 0 ? (data.success / data.calls) * 100 : 0,
434
- avgLatency: data.calls > 0 ? Math.round(data.latency / data.calls) : 0,
435
- }))
436
- .sort((a, b) => b.calls - a.calls);
437
- // Group by day
438
- const byDayMap = {};
439
- for (const log of logs) {
440
- const day = new Date(log.createdAt).toISOString().split("T")[0];
441
- if (!byDayMap[day]) {
442
- byDayMap[day] = { calls: 0, success: 0, error: 0 };
443
- }
444
- byDayMap[day].calls++;
445
- if (log.status === "success") {
446
- byDayMap[day].success++;
447
- }
448
- else {
449
- byDayMap[day].error++;
450
- }
451
- }
452
- const byDay = Object.entries(byDayMap)
453
- .map(([date, data]) => ({
454
- date,
455
- calls: data.calls,
456
- success: data.success,
457
- error: data.error,
458
- }))
459
- .sort((a, b) => a.date.localeCompare(b.date));
460
- // Get unique providers and agents for filter dropdowns
461
- const providers = [...new Set(logs.map((l) => l.provider))].sort();
462
- const agents = [...new Set(logs.map((l) => l.subagentId || "main"))].sort();
463
- return {
464
- totalCalls,
465
- successCount,
466
- errorCount,
467
- successRate: Math.round(successRate * 10) / 10,
468
- avgLatency,
469
- byProvider,
470
- byDay,
471
- providers,
472
- agents,
473
- };
474
- },
475
- });
476
- /**
477
- * Get unique providers for filter dropdown
478
- */
479
- export const getProviders = query({
480
- args: {
481
- token: v.string(),
482
- },
483
- handler: async (ctx, args) => {
484
- // Verify session
485
- const session = await ctx.db
486
- .query("agentSessions")
487
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", args.token))
488
- .first();
489
- if (!session) {
490
- return [];
491
- }
492
- // Get all logs for this workspace
493
- const logs = await ctx.db
494
- .query("apiLogs")
495
- .withIndex("by_workspaceId", (q) => q.eq("workspaceId", session.workspaceId))
496
- .collect();
497
- // Get unique providers
498
- const providers = [...new Set(logs.map((l) => l.provider))].sort();
499
- return providers;
500
- },
501
- });
502
- /**
503
- * Get logs for a specific subagent
504
- */
505
- export const getBySubagent = query({
506
- args: {
507
- token: v.string(),
508
- subagentId: v.string(),
509
- limit: v.optional(v.number()),
510
- },
511
- handler: async (ctx, { token, subagentId, limit = 20 }) => {
512
- // Verify session
513
- const session = await ctx.db
514
- .query("agentSessions")
515
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
516
- .first();
517
- if (!session)
518
- return null;
519
- // Get API logs for this subagent
520
- const apiLogs = await ctx.db
521
- .query("apiLogs")
522
- .withIndex("by_subagentId", (q) => q.eq("subagentId", subagentId))
523
- .order("desc")
524
- .take(limit);
525
- // Get search logs for this subagent
526
- const searchLogs = await ctx.db
527
- .query("searchLogs")
528
- .filter((q) => q.eq(q.field("subagentId"), subagentId))
529
- .order("desc")
530
- .take(limit);
531
- // Merge and sort by timestamp
532
- const combined = [
533
- ...apiLogs.map(l => ({
534
- ...l,
535
- type: "direct_call",
536
- timestamp: l.createdAt
537
- })),
538
- ...searchLogs.map(l => ({
539
- ...l,
540
- type: "search",
541
- timestamp: l.timestamp
542
- })),
543
- ].sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));
544
- return combined.slice(0, limit);
545
- },
546
- });
547
- /**
548
- * Clear all logs for a workspace (admin cleanup)
549
- */
550
- export const clearWorkspaceLogs = mutation({
551
- args: {
552
- token: v.string(),
553
- },
554
- handler: async (ctx, { token }) => {
555
- const session = await ctx.db
556
- .query("agentSessions")
557
- .withIndex("by_sessionToken", (q) => q.eq("sessionToken", token))
558
- .first();
559
- if (!session)
560
- throw new Error("Invalid session");
561
- // Delete all apiLogs
562
- const apiLogs = await ctx.db
563
- .query("apiLogs")
564
- .withIndex("by_workspaceId", (q) => q.eq("workspaceId", session.workspaceId))
565
- .collect();
566
- for (const log of apiLogs) {
567
- await ctx.db.delete(log._id);
568
- }
569
- // Delete all searchLogs
570
- const searchLogs = await ctx.db
571
- .query("searchLogs")
572
- .withIndex("by_workspaceId", (q) => q.eq("workspaceId", session.workspaceId))
573
- .collect();
574
- for (const log of searchLogs) {
575
- await ctx.db.delete(log._id);
576
- }
577
- return {
578
- deleted: {
579
- apiLogs: apiLogs.length,
580
- searchLogs: searchLogs.length
581
- }
582
- };
583
- },
584
- });
585
- // Log proxy API calls from external agents (Hivr bees)
586
- export const createProxyLog = mutation({
587
- args: {
588
- workspaceId: v.id("workspaces"),
589
- provider: v.string(),
590
- action: v.string(),
591
- subagentId: v.optional(v.string()),
592
- sessionToken: v.optional(v.string()),
593
- },
594
- handler: async (ctx, { workspaceId, provider, action, subagentId, sessionToken }) => {
595
- const now = Date.now();
596
- await ctx.db.insert("apiLogs", {
597
- workspaceId,
598
- provider,
599
- action,
600
- subagentId: subagentId || "unknown",
601
- sessionToken: sessionToken || "proxy",
602
- status: "success",
603
- latencyMs: 0, // Proxy calls don't track latency
604
- createdAt: now,
605
- });
606
- // Update workspace lastActiveAt (main agent activity)
607
- await ctx.db.patch(workspaceId, { lastActiveAt: now });
608
- // If this is a subagent call, update that subagent's timestamp
609
- if (subagentId && subagentId !== "unknown" && subagentId !== "main") {
610
- const subagent = await ctx.db
611
- .query("subagents")
612
- .withIndex("by_workspaceId_subagentId", (q) => q.eq("workspaceId", workspaceId).eq("subagentId", subagentId))
613
- .first();
614
- if (subagent) {
615
- await ctx.db.patch(subagent._id, { lastActiveAt: now });
616
- }
617
- }
618
- return { success: true };
619
- },
620
- });
621
- //# sourceMappingURL=logs.js.map
@@ -1,2 +0,0 @@
1
- export declare const run: any;
2
- //# sourceMappingURL=migrateFilestack.d.ts.map