@nordsym/apiclaw 2.2.0 → 2.3.0

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 (176) hide show
  1. package/README.md +15 -2
  2. package/dist/bin-http.js +0 -0
  3. package/dist/bin.bundled.js +79288 -0
  4. package/dist/gateway-client.d.ts.map +1 -1
  5. package/dist/gateway-client.js +24 -2
  6. package/dist/gateway-client.js.map +1 -1
  7. package/dist/index.bundled.js +61263 -0
  8. package/dist/index.js +2 -2
  9. package/dist/index.js.map +1 -1
  10. package/package.json +7 -2
  11. package/.claude/settings.local.json +0 -13
  12. package/.env.prod +0 -1
  13. package/apiclaw-README.md +0 -494
  14. package/convex/_generated/api.d.ts +0 -145
  15. package/convex/_generated/api.js +0 -23
  16. package/convex/_generated/dataModel.d.ts +0 -60
  17. package/convex/_generated/server.d.ts +0 -143
  18. package/convex/_generated/server.js +0 -93
  19. package/convex/_listWorkspaces.ts +0 -13
  20. package/convex/adminActivate.ts +0 -53
  21. package/convex/adminStats.ts +0 -306
  22. package/convex/agents.ts +0 -939
  23. package/convex/analytics.ts +0 -187
  24. package/convex/apiKeys.ts +0 -220
  25. package/convex/backfillAnalytics.ts +0 -272
  26. package/convex/backfillSearchLogs.ts +0 -35
  27. package/convex/billing.ts +0 -834
  28. package/convex/capabilities.ts +0 -157
  29. package/convex/chains.ts +0 -1318
  30. package/convex/credits.ts +0 -211
  31. package/convex/crons.ts +0 -65
  32. package/convex/debugFilestackLogs.ts +0 -16
  33. package/convex/debugGetToken.ts +0 -18
  34. package/convex/directCall.ts +0 -713
  35. package/convex/earnProgress.ts +0 -753
  36. package/convex/email.ts +0 -329
  37. package/convex/feedback.ts +0 -265
  38. package/convex/funnel.ts +0 -431
  39. package/convex/guards.ts +0 -174
  40. package/convex/http.ts +0 -3756
  41. package/convex/inbound.ts +0 -32
  42. package/convex/logs.ts +0 -701
  43. package/convex/migrateFilestack.ts +0 -81
  44. package/convex/migratePartnersProd.ts +0 -174
  45. package/convex/migratePratham.ts +0 -126
  46. package/convex/migrateProviderWorkspaces.ts +0 -175
  47. package/convex/mou.ts +0 -91
  48. package/convex/nurture.ts +0 -355
  49. package/convex/providerKeys.ts +0 -289
  50. package/convex/providers.ts +0 -1135
  51. package/convex/purchases.ts +0 -183
  52. package/convex/ratelimit.ts +0 -104
  53. package/convex/schema.ts +0 -926
  54. package/convex/searchLogs.ts +0 -265
  55. package/convex/seedAPILayerAPIs.ts +0 -191
  56. package/convex/seedDirectCallConfigs.ts +0 -336
  57. package/convex/seedPratham.ts +0 -149
  58. package/convex/spendAlerts.ts +0 -442
  59. package/convex/stripeActions.ts +0 -607
  60. package/convex/teams.ts +0 -243
  61. package/convex/telemetry.ts +0 -81
  62. package/convex/tsconfig.json +0 -25
  63. package/convex/updateAPIStatus.ts +0 -44
  64. package/convex/usage.ts +0 -260
  65. package/convex/usageReports.ts +0 -357
  66. package/convex/waitlist.ts +0 -55
  67. package/convex/webhooks.ts +0 -494
  68. package/convex/workspaceSettings.ts +0 -143
  69. package/convex/workspaces.ts +0 -1331
  70. package/convex.json +0 -3
  71. package/direct-test.mjs +0 -51
  72. package/email-templates/filestack-provider-outreach.html +0 -162
  73. package/email-templates/partnership-template.html +0 -116
  74. package/email-templates/pratham-draft-preview.txt +0 -57
  75. package/email-templates/pratham-partnership-draft.html +0 -141
  76. package/reports/APIClaw-Session-Report-2026-04-05.pdf +0 -0
  77. package/reports/pipeline/PIPELINE-REPORT.json +0 -153
  78. package/reports/pipeline/acquire_apisguru.json +0 -17
  79. package/reports/pipeline/capabilities.json +0 -38
  80. package/reports/pipeline/discover_azure_recursive.json +0 -1551
  81. package/reports/pipeline/discover_github.json +0 -25
  82. package/reports/pipeline/discover_github_repos.json +0 -49
  83. package/reports/pipeline/discover_swaggerhub.json +0 -24
  84. package/reports/pipeline/discover_well_known.json +0 -23
  85. package/reports/pipeline/fetch_specs.json +0 -19
  86. package/reports/pipeline/generate_providers.json +0 -14
  87. package/reports/pipeline/match_registry.json +0 -11
  88. package/reports/pipeline/parse_specs.json +0 -17
  89. package/reports/pipeline/promote_candidates.json +0 -34
  90. package/reports/pipeline/validate.json +0 -30
  91. package/reports/pipeline/validate_smoke_details.json +0 -3835
  92. package/reports/session-report-2026-04-05.html +0 -433
  93. package/seed-apis-direct.mjs +0 -106
  94. package/src/access-control.ts +0 -174
  95. package/src/adapters/base.ts +0 -364
  96. package/src/adapters/claude-desktop.ts +0 -41
  97. package/src/adapters/cline.ts +0 -88
  98. package/src/adapters/continue.ts +0 -91
  99. package/src/adapters/cursor.ts +0 -43
  100. package/src/adapters/custom.ts +0 -188
  101. package/src/adapters/detect.ts +0 -202
  102. package/src/adapters/index.ts +0 -47
  103. package/src/adapters/windsurf.ts +0 -44
  104. package/src/bin-http.ts +0 -45
  105. package/src/bin.ts +0 -34
  106. package/src/capability-router.ts +0 -331
  107. package/src/chainExecutor.ts +0 -730
  108. package/src/chainResolver.test.ts +0 -246
  109. package/src/chainResolver.ts +0 -658
  110. package/src/cli/commands/demo.ts +0 -109
  111. package/src/cli/commands/doctor.ts +0 -435
  112. package/src/cli/commands/index.ts +0 -9
  113. package/src/cli/commands/login.ts +0 -203
  114. package/src/cli/commands/mcp-install.ts +0 -373
  115. package/src/cli/commands/restore.ts +0 -333
  116. package/src/cli/commands/setup.ts +0 -297
  117. package/src/cli/commands/uninstall.ts +0 -240
  118. package/src/cli/index.ts +0 -148
  119. package/src/cli.ts +0 -370
  120. package/src/confirmation.ts +0 -296
  121. package/src/credentials.ts +0 -455
  122. package/src/credits.ts +0 -329
  123. package/src/crypto.ts +0 -75
  124. package/src/discovery.ts +0 -568
  125. package/src/enterprise/env.ts +0 -156
  126. package/src/enterprise/index.ts +0 -7
  127. package/src/enterprise/script-generator.ts +0 -481
  128. package/src/execute-dynamic.ts +0 -617
  129. package/src/execute.ts +0 -2386
  130. package/src/funnel-client.ts +0 -168
  131. package/src/funnel.test.ts +0 -187
  132. package/src/gateway-client.ts +0 -192
  133. package/src/hivr-whitelist.ts +0 -110
  134. package/src/http-api.ts +0 -286
  135. package/src/http-server-minimal.ts +0 -154
  136. package/src/index.ts +0 -2702
  137. package/src/intelligent-gateway.ts +0 -339
  138. package/src/mcp-analytics.ts +0 -156
  139. package/src/metered.ts +0 -149
  140. package/src/open-apis-generated.ts +0 -157
  141. package/src/open-apis.ts +0 -558
  142. package/src/postinstall.ts +0 -40
  143. package/src/product-whitelist.ts +0 -246
  144. package/src/proxy.ts +0 -36
  145. package/src/registration-guard.ts +0 -117
  146. package/src/session.ts +0 -129
  147. package/src/stripe.ts +0 -497
  148. package/src/telemetry.ts +0 -71
  149. package/src/test.ts +0 -135
  150. package/src/types/convex-api.d.ts +0 -20
  151. package/src/types/convex-api.ts +0 -21
  152. package/src/types.ts +0 -109
  153. package/src/ui/colors.ts +0 -219
  154. package/src/ui/errors.ts +0 -394
  155. package/src/ui/index.ts +0 -17
  156. package/src/ui/prompts.ts +0 -390
  157. package/src/ui/spinner.ts +0 -325
  158. package/src/utils/backup.ts +0 -224
  159. package/src/utils/config.ts +0 -318
  160. package/src/utils/os.ts +0 -124
  161. package/src/utils/paths.ts +0 -203
  162. package/src/webhook.ts +0 -107
  163. package/test-10-working.cjs +0 -97
  164. package/test-14-final.cjs +0 -96
  165. package/test-actual-handlers.ts +0 -92
  166. package/test-apilayer-all-14.ts +0 -249
  167. package/test-apilayer-fixed.ts +0 -248
  168. package/test-direct-endpoints.ts +0 -174
  169. package/test-exact-endpoints.ts +0 -144
  170. package/test-final.ts +0 -83
  171. package/test-full-routing.ts +0 -100
  172. package/test-handlers-correct.ts +0 -217
  173. package/test-numverify-key.ts +0 -41
  174. package/test-via-handlers.ts +0 -92
  175. package/test-worldnews.mjs +0 -26
  176. package/tsconfig.json +0 -20
package/convex/funnel.ts DELETED
@@ -1,431 +0,0 @@
1
- /**
2
- * APIClaw Funnel — canonical conversion truth
3
- *
4
- * Canon events (ordered):
5
- * install — package installed (postinstall hook, once per fingerprint)
6
- * first_run — MCP server first successful startup
7
- * register_owner — user called register_owner (OTP sent)
8
- * verify_code — user verified OTP, workspace active
9
- * first_call_api_success — workspace's first successful call_api (non-discover)
10
- *
11
- * Classification (source):
12
- * human — real user, reasonable UA, interactive MCP client
13
- * ci — CI/CD runner (CI env var family, GITHUB_ACTIONS, headless UAs)
14
- * bot — scanner/crawler (User-Agent matches crawler list)
15
- * internal — NordSym test traffic (fingerprint prefix, allowlisted emails)
16
- *
17
- * Truth metrics are built from (event=verify_code AND source=human) and
18
- * (event=first_call_api_success AND source=human). Vanity = install count.
19
- */
20
- import { mutation, query, internalMutation } from "./_generated/server";
21
- import { v } from "convex/values";
22
-
23
- export const FUNNEL_EVENTS = [
24
- "install",
25
- "first_run",
26
- "register_owner",
27
- "verify_code",
28
- "first_call_api_success",
29
- ] as const;
30
-
31
- export type FunnelEvent = (typeof FUNNEL_EVENTS)[number];
32
-
33
- // Diagnostic events — reasoning, errors, retries, drop-off causes.
34
- // Stored in the same table but excluded from the canonical funnel rollup.
35
- export const DIAGNOSTIC_EVENTS = [
36
- "register_owner_failed", // props: { reason: "invalid_email" | "email_send_failed" }
37
- "verify_code_failed", // props: { reason: "invalid" | "expired" | "attempts_exceeded" }
38
- "call_api_blocked", // props: { reason: "no_session" | "pending_verification" | "quota_exceeded" | "not_verified" }
39
- "call_api_error", // props: { provider, action, errorCode }
40
- "quota_hit", // props: { tier, limit }
41
- "gateway_retry", // props: { attempt, reason }
42
- ] as const;
43
-
44
- export type DiagnosticEvent = (typeof DIAGNOSTIC_EVENTS)[number];
45
- export type AnyEvent = FunnelEvent | DiagnosticEvent;
46
-
47
- const ALL_EVENTS = [...FUNNEL_EVENTS, ...DIAGNOSTIC_EVENTS] as readonly string[];
48
-
49
- export type Classification = "human" | "ci" | "bot" | "internal";
50
-
51
- // Keep these predicates pure and exported so tests can hit them directly.
52
- const CI_ENV_KEYS = [
53
- "CI",
54
- "GITHUB_ACTIONS",
55
- "GITLAB_CI",
56
- "CIRCLECI",
57
- "BUILDKITE",
58
- "JENKINS_URL",
59
- "TEAMCITY_VERSION",
60
- "TRAVIS",
61
- "BITBUCKET_BUILD_NUMBER",
62
- ];
63
-
64
- // UA substrings (lower-cased) that flag known bots/scanners.
65
- const BOT_UA_MARKERS = [
66
- "bot",
67
- "crawl",
68
- "spider",
69
- "scanner",
70
- "curl/",
71
- "wget/",
72
- "httpclient",
73
- "python-requests",
74
- "go-http-client",
75
- "okhttp",
76
- "java/",
77
- "httrack",
78
- "headlesschrome",
79
- "phantomjs",
80
- ];
81
-
82
- // Emails that are considered internal NordSym traffic.
83
- const INTERNAL_EMAIL_DOMAINS = ["nordsym.com", "apiclaw.cloud"];
84
- const INTERNAL_EMAIL_EXACT = ["gustav@nordsym.com", "gustavnordsync@gmail.com"];
85
-
86
- // Fingerprint prefix(es) used by internal test machines.
87
- const INTERNAL_FINGERPRINT_PREFIXES: string[] = [];
88
-
89
- export function classifySource(input: {
90
- userAgent?: string | null;
91
- envFlags?: Record<string, string | undefined>;
92
- email?: string | null;
93
- fingerprint?: string | null;
94
- forcedInternal?: boolean;
95
- }): Classification {
96
- if (input.forcedInternal) return "internal";
97
-
98
- const email = (input.email || "").toLowerCase().trim();
99
- if (email) {
100
- if (INTERNAL_EMAIL_EXACT.includes(email)) return "internal";
101
- const domain = email.split("@")[1] || "";
102
- if (INTERNAL_EMAIL_DOMAINS.includes(domain)) return "internal";
103
- }
104
-
105
- const fp = input.fingerprint || "";
106
- if (fp && INTERNAL_FINGERPRINT_PREFIXES.some((p) => fp.startsWith(p))) {
107
- return "internal";
108
- }
109
-
110
- const env = input.envFlags || {};
111
- for (const key of CI_ENV_KEYS) {
112
- const val = env[key];
113
- if (val && val !== "false" && val !== "0") return "ci";
114
- }
115
-
116
- const ua = (input.userAgent || "").toLowerCase();
117
- if (ua) {
118
- for (const m of BOT_UA_MARKERS) {
119
- if (ua.includes(m)) return "bot";
120
- }
121
- }
122
-
123
- return "human";
124
- }
125
-
126
- // Record a funnel event. Idempotent per (workspaceId|fingerprint, event) for
127
- // first-time events (install, first_run, first_call_api_success) via
128
- // dedupeKey. register_owner and verify_code can recur legitimately.
129
- export const recordEvent = mutation({
130
- args: {
131
- event: v.string(), // validated against FUNNEL_EVENTS below
132
- classification: v.string(),
133
- workspaceId: v.optional(v.id("workspaces")),
134
- fingerprint: v.optional(v.string()),
135
- sessionToken: v.optional(v.string()),
136
- email: v.optional(v.string()),
137
- userAgent: v.optional(v.string()),
138
- mcpClient: v.optional(v.string()),
139
- platform: v.optional(v.string()),
140
- version: v.optional(v.string()),
141
- dedupeKey: v.optional(v.string()), // if set, no-op when duplicate exists
142
- props: v.optional(v.any()),
143
- },
144
- handler: async (ctx, args) => {
145
- if (!ALL_EVENTS.includes(args.event)) {
146
- return { success: false, error: `unknown_event:${args.event}` };
147
- }
148
- const allowedClass: Classification[] = ["human", "ci", "bot", "internal"];
149
- if (!allowedClass.includes(args.classification as Classification)) {
150
- return { success: false, error: `unknown_classification:${args.classification}` };
151
- }
152
-
153
- if (args.dedupeKey) {
154
- const existing = await ctx.db
155
- .query("funnelEvents")
156
- .withIndex("by_dedupeKey", (q) => q.eq("dedupeKey", args.dedupeKey!))
157
- .first();
158
- if (existing) {
159
- return { success: true, deduped: true, id: existing._id };
160
- }
161
- }
162
-
163
- const id = await ctx.db.insert("funnelEvents", {
164
- event: args.event,
165
- classification: args.classification,
166
- workspaceId: args.workspaceId,
167
- fingerprint: args.fingerprint,
168
- sessionToken: args.sessionToken,
169
- email: args.email,
170
- userAgent: args.userAgent,
171
- mcpClient: args.mcpClient,
172
- platform: args.platform,
173
- version: args.version,
174
- dedupeKey: args.dedupeKey,
175
- props: args.props,
176
- timestamp: Date.now(),
177
- });
178
-
179
- return { success: true, deduped: false, id };
180
- },
181
- });
182
-
183
- // Internal variant callable from other Convex functions (e.g. verifyOTP).
184
- export const recordEventInternal = internalMutation({
185
- args: {
186
- event: v.string(),
187
- classification: v.string(),
188
- workspaceId: v.optional(v.id("workspaces")),
189
- fingerprint: v.optional(v.string()),
190
- email: v.optional(v.string()),
191
- dedupeKey: v.optional(v.string()),
192
- props: v.optional(v.any()),
193
- },
194
- handler: async (ctx, args) => {
195
- if (!ALL_EVENTS.includes(args.event)) return null;
196
- if (args.dedupeKey) {
197
- const existing = await ctx.db
198
- .query("funnelEvents")
199
- .withIndex("by_dedupeKey", (q) => q.eq("dedupeKey", args.dedupeKey!))
200
- .first();
201
- if (existing) return existing._id;
202
- }
203
- return await ctx.db.insert("funnelEvents", {
204
- ...args,
205
- timestamp: Date.now(),
206
- });
207
- },
208
- });
209
-
210
- // Roll up the canonical funnel for a time window. Default: last 7d, human only.
211
- export const getFunnel = query({
212
- args: {
213
- hoursBack: v.optional(v.number()),
214
- includeClassifications: v.optional(v.array(v.string())),
215
- },
216
- handler: async (ctx, args) => {
217
- const hoursBack = args.hoursBack ?? 24 * 7;
218
- const since = Date.now() - hoursBack * 3600000;
219
- const includes = args.includeClassifications ?? ["human"];
220
-
221
- const events = await ctx.db
222
- .query("funnelEvents")
223
- .withIndex("by_timestamp", (q) => q.gte("timestamp", since))
224
- .collect();
225
-
226
- const filtered = events.filter((e) => includes.includes(e.classification));
227
-
228
- const countsByEvent: Record<string, number> = {};
229
- const uniqByEvent: Record<string, Set<string>> = {};
230
- for (const e of FUNNEL_EVENTS) {
231
- countsByEvent[e] = 0;
232
- uniqByEvent[e] = new Set<string>();
233
- }
234
-
235
- for (const e of filtered) {
236
- countsByEvent[e.event] = (countsByEvent[e.event] || 0) + 1;
237
- const k = (e.workspaceId as string | undefined) || e.fingerprint || e._id;
238
- uniqByEvent[e.event].add(k);
239
- }
240
-
241
- // Classification breakdown across all events in window.
242
- const byClass: Record<string, number> = { human: 0, ci: 0, bot: 0, internal: 0 };
243
- for (const e of events) {
244
- byClass[e.classification] = (byClass[e.classification] || 0) + 1;
245
- }
246
-
247
- const funnel = FUNNEL_EVENTS.map((name) => ({
248
- event: name,
249
- count: countsByEvent[name],
250
- unique: uniqByEvent[name].size,
251
- }));
252
-
253
- // Conversion ratios (unique-based).
254
- const get = (n: string) => uniqByEvent[n]?.size || 0;
255
- const ratios = {
256
- install_to_first_run: safeRatio(get("first_run"), get("install")),
257
- first_run_to_register: safeRatio(get("register_owner"), get("first_run")),
258
- register_to_verify: safeRatio(get("verify_code"), get("register_owner")),
259
- verify_to_first_call: safeRatio(get("first_call_api_success"), get("verify_code")),
260
- install_to_verify: safeRatio(get("verify_code"), get("install")),
261
- install_to_first_call: safeRatio(get("first_call_api_success"), get("install")),
262
- };
263
-
264
- return {
265
- windowHours: hoursBack,
266
- includeClassifications: includes,
267
- totalEvents: filtered.length,
268
- funnel,
269
- ratios,
270
- classificationBreakdown: byClass,
271
- };
272
- },
273
- });
274
-
275
- function safeRatio(num: number, denom: number): number {
276
- if (!denom) return 0;
277
- return Math.round((num / denom) * 10000) / 10000;
278
- }
279
-
280
- // Weekly scorecard — the canonical KPI snapshot.
281
- // Returns truth metrics (human-only by default) with optional comparison
282
- // against the previous period of equal length.
283
- export const getScorecard = query({
284
- args: {
285
- hoursBack: v.optional(v.number()),
286
- classification: v.optional(v.string()), // "human" by default
287
- compare: v.optional(v.boolean()), // compare to prior equal window
288
- },
289
- handler: async (ctx, args) => {
290
- const windowH = args.hoursBack ?? 24 * 7;
291
- const cls = args.classification ?? "human";
292
- const now = Date.now();
293
- const since = now - windowH * 3600000;
294
- const priorSince = now - windowH * 2 * 3600000;
295
-
296
- const events = await ctx.db
297
- .query("funnelEvents")
298
- .withIndex("by_timestamp", (q) => q.gte("timestamp", args.compare ? priorSince : since))
299
- .collect();
300
-
301
- const window = events.filter((e) => e.timestamp >= since && e.classification === cls);
302
- const prior = args.compare
303
- ? events.filter(
304
- (e) =>
305
- e.timestamp >= priorSince &&
306
- e.timestamp < since &&
307
- e.classification === cls
308
- )
309
- : null;
310
-
311
- const metrics = computeMetrics(window);
312
- const priorMetrics = prior ? computeMetrics(prior) : null;
313
-
314
- // Diagnostic breakdown for the current window.
315
- const diagnostics: Record<string, Record<string, number>> = {};
316
- for (const e of window) {
317
- if (!DIAGNOSTIC_EVENTS.includes(e.event as DiagnosticEvent)) continue;
318
- const reason = ((e.props as any)?.reason ?? "unknown") as string;
319
- diagnostics[e.event] = diagnostics[e.event] || {};
320
- diagnostics[e.event][reason] = (diagnostics[e.event][reason] || 0) + 1;
321
- }
322
-
323
- return {
324
- windowHours: windowH,
325
- classification: cls,
326
- generatedAt: now,
327
- truth: {
328
- installs: metrics.unique.install,
329
- activatedOwners: metrics.unique.verify_code,
330
- activatedUsers: metrics.unique.first_call_api_success,
331
- },
332
- vanity: {
333
- installEvents: metrics.counts.install,
334
- },
335
- ratios: metrics.ratios,
336
- diagnostics,
337
- previous: priorMetrics
338
- ? {
339
- installs: priorMetrics.unique.install,
340
- activatedOwners: priorMetrics.unique.verify_code,
341
- activatedUsers: priorMetrics.unique.first_call_api_success,
342
- ratios: priorMetrics.ratios,
343
- }
344
- : null,
345
- };
346
- },
347
- });
348
-
349
- type FunnelBucket = {
350
- counts: Record<string, number>;
351
- unique: Record<string, number>;
352
- ratios: Record<string, number>;
353
- };
354
-
355
- function computeMetrics(events: { event: string; workspaceId?: any; fingerprint?: any; _id: any }[]): FunnelBucket {
356
- const counts: Record<string, number> = {};
357
- const uniq: Record<string, Set<string>> = {};
358
- for (const e of FUNNEL_EVENTS) {
359
- counts[e] = 0;
360
- uniq[e] = new Set<string>();
361
- }
362
- for (const e of events) {
363
- if (!FUNNEL_EVENTS.includes(e.event as FunnelEvent)) continue;
364
- counts[e.event]++;
365
- const k = (e.workspaceId as string | undefined) || (e.fingerprint as string | undefined) || String(e._id);
366
- uniq[e.event].add(k);
367
- }
368
- const u = (n: string) => uniq[n]?.size || 0;
369
- return {
370
- counts,
371
- unique: {
372
- install: u("install"),
373
- first_run: u("first_run"),
374
- register_owner: u("register_owner"),
375
- verify_code: u("verify_code"),
376
- first_call_api_success: u("first_call_api_success"),
377
- },
378
- ratios: {
379
- install_to_first_run: safeRatio(u("first_run"), u("install")),
380
- first_run_to_register: safeRatio(u("register_owner"), u("first_run")),
381
- register_to_verify: safeRatio(u("verify_code"), u("register_owner")),
382
- verify_to_first_call: safeRatio(u("first_call_api_success"), u("verify_code")),
383
- install_to_verify: safeRatio(u("verify_code"), u("install")),
384
- install_to_first_call: safeRatio(u("first_call_api_success"), u("install")),
385
- },
386
- };
387
- }
388
-
389
- // Diagnostics-only query — reasons for drop-off and errors.
390
- export const getDiagnostics = query({
391
- args: {
392
- hoursBack: v.optional(v.number()),
393
- classification: v.optional(v.string()),
394
- },
395
- handler: async (ctx, args) => {
396
- const windowH = args.hoursBack ?? 24 * 7;
397
- const since = Date.now() - windowH * 3600000;
398
- const cls = args.classification ?? "human";
399
-
400
- const events = await ctx.db
401
- .query("funnelEvents")
402
- .withIndex("by_timestamp", (q) => q.gte("timestamp", since))
403
- .collect();
404
-
405
- const filtered = events.filter(
406
- (e) => e.classification === cls && DIAGNOSTIC_EVENTS.includes(e.event as DiagnosticEvent)
407
- );
408
-
409
- const breakdown: Record<string, Record<string, number>> = {};
410
- for (const e of filtered) {
411
- breakdown[e.event] = breakdown[e.event] || {};
412
- const reason = ((e.props as any)?.reason ?? (e.props as any)?.errorCode ?? "unknown") as string;
413
- breakdown[e.event][reason] = (breakdown[e.event][reason] || 0) + 1;
414
- }
415
-
416
- return {
417
- windowHours: windowH,
418
- classification: cls,
419
- total: filtered.length,
420
- byEvent: breakdown,
421
- };
422
- },
423
- });
424
-
425
- // Quick listing for debugging.
426
- export const getRecent = query({
427
- args: { limit: v.optional(v.number()) },
428
- handler: async (ctx, { limit = 100 }) => {
429
- return await ctx.db.query("funnelEvents").order("desc").take(limit);
430
- },
431
- });
package/convex/guards.ts DELETED
@@ -1,174 +0,0 @@
1
- /**
2
- * Registration enforcement guards — single source of truth.
3
- *
4
- * Every call path that "should require registration" resolves through
5
- * requireVerifiedOwner. Free paths (discover_apis, catalog, docs) do NOT
6
- * call this. See Apiclaw-TOOLS.md for the enforcement matrix.
7
- */
8
- import { query } from "./_generated/server";
9
- import { v } from "convex/values";
10
- import type { Id } from "./_generated/dataModel";
11
-
12
- export type VerifiedOwner = {
13
- ok: true;
14
- workspaceId: Id<"workspaces">;
15
- email: string;
16
- tier: string;
17
- status: string;
18
- usageCount: number;
19
- usageLimit: number;
20
- usageRemaining: number;
21
- };
22
-
23
- export type OwnerDenial = {
24
- ok: false;
25
- reason:
26
- | "no_session"
27
- | "session_invalid"
28
- | "workspace_missing"
29
- | "not_verified" // status !== active OR email missing
30
- | "quota_exceeded";
31
- message: string;
32
- };
33
-
34
- // Resolve a verified-owner decision from a session token.
35
- // Pure read; no mutations. Returns a typed discriminated union so callers
36
- // must handle both branches explicitly.
37
- export async function resolveVerifiedOwner(
38
- ctx: any,
39
- sessionToken: string | null | undefined,
40
- opts?: { allowQuotaExceeded?: boolean }
41
- ): Promise<VerifiedOwner | OwnerDenial> {
42
- if (!sessionToken) {
43
- return {
44
- ok: false,
45
- reason: "no_session",
46
- message:
47
- "Registration required. Call register_owner({ email }) then verify_code({ email, code }).",
48
- };
49
- }
50
-
51
- const session = await ctx.db
52
- .query("agentSessions")
53
- .withIndex("by_sessionToken", (q: any) => q.eq("sessionToken", sessionToken))
54
- .first();
55
-
56
- if (!session) {
57
- return { ok: false, reason: "session_invalid", message: "Session not found or expired." };
58
- }
59
-
60
- const workspace = await ctx.db.get(session.workspaceId);
61
- if (!workspace) {
62
- return { ok: false, reason: "workspace_missing", message: "Workspace not found." };
63
- }
64
-
65
- if (workspace.status !== "active") {
66
- return {
67
- ok: false,
68
- reason: "not_verified",
69
- message: `Workspace status: ${workspace.status}. Verify your email to activate.`,
70
- };
71
- }
72
-
73
- if (!workspace.email) {
74
- return {
75
- ok: false,
76
- reason: "not_verified",
77
- message: "Workspace has no verified email. Run register_owner + verify_code.",
78
- };
79
- }
80
-
81
- const usageRemaining =
82
- workspace.usageLimit > 0 ? workspace.usageLimit - workspace.usageCount : -1;
83
-
84
- if (!opts?.allowQuotaExceeded && usageRemaining === 0) {
85
- return {
86
- ok: false,
87
- reason: "quota_exceeded",
88
- message: "Free tier quota exceeded. Upgrade at https://apiclaw.cloud/upgrade.",
89
- };
90
- }
91
-
92
- return {
93
- ok: true,
94
- workspaceId: session.workspaceId,
95
- email: workspace.email,
96
- tier: workspace.tier,
97
- status: workspace.status,
98
- usageCount: workspace.usageCount,
99
- usageLimit: workspace.usageLimit,
100
- usageRemaining,
101
- };
102
- }
103
-
104
- // Variant: verify by workspaceId directly (for API-key auth paths that already
105
- // resolved a workspace from sk-claw-* and just need to confirm it's active+verified).
106
- export async function resolveVerifiedOwnerByWorkspaceId(
107
- ctx: any,
108
- workspaceId: string | null | undefined,
109
- opts?: { allowQuotaExceeded?: boolean }
110
- ): Promise<VerifiedOwner | OwnerDenial> {
111
- if (!workspaceId) {
112
- return { ok: false, reason: "no_session", message: "No workspace resolved from API key." };
113
- }
114
- const workspace = await ctx.db.get(workspaceId as Id<"workspaces">);
115
- if (!workspace) {
116
- return { ok: false, reason: "workspace_missing", message: "Workspace not found." };
117
- }
118
- if (workspace.status !== "active") {
119
- return {
120
- ok: false,
121
- reason: "not_verified",
122
- message: `Workspace status: ${workspace.status}. Verify your email to activate.`,
123
- };
124
- }
125
- if (!workspace.email) {
126
- return { ok: false, reason: "not_verified", message: "Workspace has no verified email." };
127
- }
128
- const usageRemaining =
129
- workspace.usageLimit > 0 ? workspace.usageLimit - workspace.usageCount : -1;
130
- if (!opts?.allowQuotaExceeded && usageRemaining === 0) {
131
- return {
132
- ok: false,
133
- reason: "quota_exceeded",
134
- message: "Free tier quota exceeded. Upgrade at https://apiclaw.cloud/upgrade.",
135
- };
136
- }
137
- return {
138
- ok: true,
139
- workspaceId: workspaceId as Id<"workspaces">,
140
- email: workspace.email,
141
- tier: workspace.tier,
142
- status: workspace.status,
143
- usageCount: workspace.usageCount,
144
- usageLimit: workspace.usageLimit,
145
- usageRemaining,
146
- };
147
- }
148
-
149
- // Public query wrapper so HTTP handlers (which can only call queries/mutations)
150
- // can invoke the guard. Returns a JSON-safe shape.
151
- export const checkVerifiedOwnerByWorkspaceId = query({
152
- args: {
153
- workspaceId: v.optional(v.id("workspaces")),
154
- allowQuotaExceeded: v.optional(v.boolean()),
155
- },
156
- handler: async (ctx, args) => {
157
- return await resolveVerifiedOwnerByWorkspaceId(ctx, args.workspaceId, {
158
- allowQuotaExceeded: args.allowQuotaExceeded,
159
- });
160
- },
161
- });
162
-
163
- export const checkVerifiedOwner = query({
164
- args: {
165
- sessionToken: v.optional(v.string()),
166
- allowQuotaExceeded: v.optional(v.boolean()),
167
- },
168
- handler: async (ctx, args) => {
169
- const result = await resolveVerifiedOwner(ctx, args.sessionToken, {
170
- allowQuotaExceeded: args.allowQuotaExceeded,
171
- });
172
- return result;
173
- },
174
- });