openrich 0.0.0-stage → 0.1.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 (65) hide show
  1. package/.env.example +23 -0
  2. package/LICENSE +21 -0
  3. package/README.md +410 -2
  4. package/assets/logo.svg +41 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +144 -0
  7. package/dist/env.d.ts +5 -0
  8. package/dist/env.js +24 -0
  9. package/dist/eval.d.ts +30 -0
  10. package/dist/eval.js +78 -0
  11. package/dist/mcp/client.d.ts +31 -0
  12. package/dist/mcp/client.js +94 -0
  13. package/dist/mcp/oauth.d.ts +13 -0
  14. package/dist/mcp/oauth.js +93 -0
  15. package/dist/mcp/server.d.ts +87 -0
  16. package/dist/mcp/server.js +125 -0
  17. package/dist/merge.d.ts +7 -0
  18. package/dist/merge.js +39 -0
  19. package/dist/providers/devplatforms.d.ts +34 -0
  20. package/dist/providers/devplatforms.js +612 -0
  21. package/dist/providers/finders.d.ts +38 -0
  22. package/dist/providers/finders.js +708 -0
  23. package/dist/providers/freetier.d.ts +9 -0
  24. package/dist/providers/freetier.js +254 -0
  25. package/dist/providers/github.d.ts +8 -0
  26. package/dist/providers/github.js +109 -0
  27. package/dist/providers/identity.d.ts +5 -0
  28. package/dist/providers/identity.js +62 -0
  29. package/dist/providers/index.d.ts +10 -0
  30. package/dist/providers/index.js +68 -0
  31. package/dist/providers/knowledge.d.ts +52 -0
  32. package/dist/providers/knowledge.js +302 -0
  33. package/dist/providers/pattern.d.ts +6 -0
  34. package/dist/providers/pattern.js +99 -0
  35. package/dist/providers/registries.d.ts +36 -0
  36. package/dist/providers/registries.js +396 -0
  37. package/dist/providers/research.d.ts +30 -0
  38. package/dist/providers/research.js +471 -0
  39. package/dist/providers/signals.d.ts +15 -0
  40. package/dist/providers/signals.js +116 -0
  41. package/dist/providers/smtp.d.ts +25 -0
  42. package/dist/providers/smtp.js +97 -0
  43. package/dist/providers/social.d.ts +37 -0
  44. package/dist/providers/social.js +657 -0
  45. package/dist/providers/verifiers.d.ts +47 -0
  46. package/dist/providers/verifiers.js +455 -0
  47. package/dist/providers/websearch.d.ts +32 -0
  48. package/dist/providers/websearch.js +346 -0
  49. package/dist/router.d.ts +31 -0
  50. package/dist/router.js +214 -0
  51. package/dist/server.d.ts +2 -0
  52. package/dist/server.js +52 -0
  53. package/dist/store.d.ts +32 -0
  54. package/dist/store.js +95 -0
  55. package/dist/types.d.ts +82 -0
  56. package/dist/types.js +1 -0
  57. package/dist/util/http.d.ts +19 -0
  58. package/dist/util/http.js +34 -0
  59. package/dist/util/match.d.ts +23 -0
  60. package/dist/util/match.js +72 -0
  61. package/dist/util/names.d.ts +11 -0
  62. package/dist/util/names.js +56 -0
  63. package/dist/util/patterns.d.ts +14 -0
  64. package/dist/util/patterns.js +61 -0
  65. package/package.json +55 -4
@@ -0,0 +1,346 @@
1
+ import { HttpError, QuotaExceeded } from "../util/http.js";
2
+ import { CLAIMED, mentionsCompany, sameName } from "../util/match.js";
3
+ import { McpClient, McpError } from "../mcp/client.js";
4
+ /**
5
+ * AI web-search APIs that find a person's public profile (mostly LinkedIn) and, with the paid tiers,
6
+ * contact fields. They search the web; they are not a people database we copy.
7
+ * - parallel-search: Parallel's hosted MCP web_search, free with no account (rate limited, for personal use)
8
+ * - parallel-entity / parallel-task: Parallel API ($5 free credit/month with a card on file)
9
+ * - exa-people / exa-websets: Exa API ($10 free credit/month, no card)
10
+ */
11
+ const company = (q) => q.company ?? q.domain ?? '';
12
+ const needsNameCompany = (q) => Boolean(q.name && q.lastName && (q.company || q.domain));
13
+ /** "Garry Tan - President & CEO - Y Combinator | LinkedIn" -> name + headline parts. */
14
+ export function parseLinkedinTitle(title) {
15
+ const t = title.replace(/\s*\|\s*LinkedIn\s*$/i, '').trim();
16
+ const parts = t.split(/\s+[-–—|]\s+/).map((x) => x.trim()).filter(Boolean);
17
+ if (parts.length === 0)
18
+ return null;
19
+ return { name: parts[0], headline: parts.slice(1) };
20
+ }
21
+ /** linkedin.com/in/<slug> profile URL, normalised; null for posts, companies, jobs. */
22
+ export function linkedinProfile(url) {
23
+ const m = url.match(/^https?:\/\/(?:[a-z]{2,3}\.)?(?:www\.)?linkedin\.com\/in\/([^/?#]+)/i);
24
+ return m ? `https://www.linkedin.com/in/${decodeURIComponent(m[1]).toLowerCase()}` : null;
25
+ }
26
+ /** "San Francisco, California, United States Contact Info" style line in a LinkedIn page excerpt. */
27
+ function locationFrom(text) {
28
+ const m = text.match(/(?:^|\n)\s*([A-Z][\w .'-]+(?:, [A-Z][\w .'-]+){1,3})\s+Contact Info/);
29
+ return m ? m[1].trim() : null;
30
+ }
31
+ /** Findings from one LinkedIn search hit, at the given confidence and evidence. */
32
+ function linkedinFindings(q, li, headline, text, source, conf, evidence) {
33
+ const out = [{ field: 'linkedin', value: li, source, confidence: conf, evidence }];
34
+ if (headline)
35
+ out.push({ field: 'title', value: headline, source, confidence: conf - 0.15, evidence: 'LinkedIn headline' });
36
+ const loc = locationFrom(text);
37
+ if (loc)
38
+ out.push({ field: 'location', value: loc, source, confidence: conf - 0.1 });
39
+ return out;
40
+ }
41
+ /** One LinkedIn search hit, when the name on it is the person's and the company is on it too (claimed). */
42
+ export function fromLinkedinHit(q, url, title, text, source, base) {
43
+ const li = linkedinProfile(url);
44
+ const parsed = parseLinkedinTitle(title);
45
+ if (!li || !parsed || !sameName(parsed.name, q.name))
46
+ return [];
47
+ if (!mentionsCompany(`${title}\n${text}`, q))
48
+ return [];
49
+ return linkedinFindings(q, li, parsed.headline.join(' - '), text, source, Math.min(base, CLAIMED), 'name + company on profile');
50
+ }
51
+ /** Name-only matches are weaker still: kept only when the results hold exactly one profile with that name. */
52
+ export const NAME_ONLY_UNIQUE = 0.5;
53
+ /**
54
+ * Pick the person's LinkedIn profile from search hits (the query already named the company).
55
+ * 1. a hit with the name and the company on it: claimed (0.7)
56
+ * 2. else, if exactly one distinct profile carries the name: name only, unique (0.5)
57
+ * 3. else (no match, or two namesakes): nothing
58
+ */
59
+ export function pickLinkedin(q, hits, source, base) {
60
+ const named = new Map();
61
+ for (const h of hits) {
62
+ const got = fromLinkedinHit(q, h.url, h.title, h.text, source, base);
63
+ if (got.length)
64
+ return got;
65
+ const li = linkedinProfile(h.url);
66
+ const parsed = parseLinkedinTitle(h.title);
67
+ if (li && parsed && sameName(parsed.name, q.name) && !named.has(li))
68
+ named.set(li, { ...h, headline: parsed.headline.join(' - ') });
69
+ }
70
+ if (named.size !== 1)
71
+ return [];
72
+ const [[li, h]] = [...named];
73
+ return linkedinFindings(q, li, h.headline, h.text, source, NAME_ONLY_UNIQUE, 'name only, the one profile with that name in the results');
74
+ }
75
+ // ---------------------------------------------------------------- Parallel
76
+ const PARALLEL_MCP = 'https://mcp.parallel.ai/mcp';
77
+ const PARALLEL_API = 'https://api.parallel.ai';
78
+ /** Parallel errors: 402 no credit, 429 rate limit -> stop for the period. */
79
+ async function parallelJson(ctx, path, init = {}) {
80
+ const res = await ctx.fetch(`${PARALLEL_API}${path}`, {
81
+ ...init,
82
+ headers: { 'x-api-key': ctx.env.PARALLEL_API_KEY, 'content-type': 'application/json', ...(init.headers ?? {}) },
83
+ signal: init.signal ?? AbortSignal.timeout(init.timeoutMs ?? 30000),
84
+ });
85
+ if (res.status === 402 || res.status === 429)
86
+ throw new QuotaExceeded(`parallel HTTP ${res.status}`);
87
+ const text = await res.text();
88
+ if (!res.ok)
89
+ throw new HttpError(res.status, text, res.url);
90
+ return text ? JSON.parse(text) : null;
91
+ }
92
+ export const parallelSearchProvider = {
93
+ id: 'parallel-search',
94
+ kind: 'free',
95
+ description: "Parallel web search via its hosted MCP (free, no account; uses PARALLEL_API_KEY if set). Finds the LinkedIn profile. PARALLEL_KEYLESS=off disables keyless use",
96
+ provides: ['linkedin', 'title', 'location'],
97
+ enabled: (env) => Boolean(env.PARALLEL_API_KEY) || env.PARALLEL_KEYLESS !== 'off',
98
+ needs: needsNameCompany,
99
+ async run(q, ctx) {
100
+ const mcp = new McpClient(PARALLEL_MCP, ctx.env.PARALLEL_API_KEY ?? '', ctx.fetch);
101
+ let r;
102
+ try {
103
+ r = await mcp.callTool('web_search', {
104
+ objective: `Find the LinkedIn profile and current job title of ${q.name}, who works at ${company(q)}`,
105
+ search_queries: [`${q.name} ${q.company ?? q.domain} LinkedIn`, `${q.name} ${q.domain ?? q.company}`],
106
+ });
107
+ }
108
+ catch (e) {
109
+ if (e instanceof McpError && e.status === 429)
110
+ throw new QuotaExceeded('parallel keyless MCP rate limited');
111
+ throw e;
112
+ }
113
+ if (r.isError)
114
+ throw new Error(`parallel web_search: ${r.text.slice(0, 200)}`);
115
+ const results = r.data?.results ?? [];
116
+ return pickLinkedin(q, results.map((it) => ({ url: String(it.url ?? ''), title: String(it.title ?? ''), text: (it.excerpts ?? []).join('\n') })), 'parallel-search', 0.8);
117
+ },
118
+ };
119
+ export const parallelEntityProvider = {
120
+ id: 'parallel-entity',
121
+ kind: 'free-tier',
122
+ description: 'Parallel Entity Search, people ($0.005/lookup from $5 free credit/month, card on file; 1-3 s)',
123
+ provides: ['linkedin', 'title', 'bio'],
124
+ keyEnv: 'PARALLEL_API_KEY',
125
+ quota: { limit: 1000, period: 'month' },
126
+ needs: needsNameCompany,
127
+ async run(q, ctx) {
128
+ const d = await parallelJson(ctx, '/v1beta/findall/entity-search', {
129
+ method: 'POST',
130
+ body: JSON.stringify({ entity_type: 'people', objective: `${q.name}, who works at ${company(q)}`, match_limit: 5 }),
131
+ });
132
+ for (const e of d?.entities ?? []) {
133
+ if (!sameName(e.name, q.name))
134
+ continue;
135
+ const desc = String(e.description ?? '');
136
+ const atCompany = mentionsCompany(desc, q);
137
+ if (!atCompany)
138
+ continue;
139
+ const out = [];
140
+ const li = linkedinProfile(String(e.url ?? ''));
141
+ if (li)
142
+ out.push({ field: 'linkedin', value: li, source: 'parallel-entity', confidence: 0.8 });
143
+ else if (e.url)
144
+ out.push({ field: 'profile', value: String(e.url), source: 'parallel-entity', confidence: 0.7 });
145
+ if (desc)
146
+ out.push({ field: 'bio', value: desc.slice(0, 300), source: 'parallel-entity', confidence: 0.6 });
147
+ return out;
148
+ }
149
+ return [];
150
+ },
151
+ };
152
+ /** Task API basis confidence -> our confidence, per field. AI-found emails stay below 0.8 so a verifier can confirm them. */
153
+ const TASK_CONF = {
154
+ high: { email: 0.7, other: 0.85 },
155
+ medium: { email: 0.45, other: 0.65 },
156
+ low: { email: 0, other: 0.35 },
157
+ };
158
+ export const parallelTaskProvider = {
159
+ id: 'parallel-task',
160
+ kind: 'free-tier',
161
+ description: 'Parallel Task API, base processor: web research for email, LinkedIn, title, location ($0.01/run from $5 free credit/month; ~1 min)',
162
+ provides: ['email', 'linkedin', 'title', 'company', 'location'],
163
+ keyEnv: 'PARALLEL_API_KEY',
164
+ quota: { limit: 500, period: 'month' },
165
+ needs: (q) => needsNameCompany(q) && !q.email,
166
+ async run(q, ctx) {
167
+ const schema = {
168
+ type: 'object',
169
+ properties: {
170
+ work_email: { type: 'string', description: `Work email address of the person at ${company(q)}, only if published on the web; empty if not found` },
171
+ linkedin_url: { type: 'string', description: 'URL of the personal LinkedIn profile (linkedin.com/in/...); empty if not found' },
172
+ job_title: { type: 'string', description: 'Current job title at the company' },
173
+ company: { type: 'string', description: 'Current employer name' },
174
+ location: { type: 'string', description: 'City and country where the person is based' },
175
+ },
176
+ required: ['work_email', 'linkedin_url', 'job_title', 'company', 'location'],
177
+ additionalProperties: false,
178
+ };
179
+ const run = await parallelJson(ctx, '/v1/tasks/runs', {
180
+ method: 'POST',
181
+ body: JSON.stringify({
182
+ processor: 'base',
183
+ input: { full_name: q.name, company: q.company ?? '', company_domain: q.domain ?? '' },
184
+ task_spec: { output_schema: { type: 'json', json_schema: schema } },
185
+ }),
186
+ });
187
+ const id = run?.run_id;
188
+ if (!id)
189
+ return [];
190
+ let res = null;
191
+ for (let i = 0; i < 4 && !res; i++) {
192
+ const r = await ctx.fetch(`${PARALLEL_API}/v1/tasks/runs/${id}/result?timeout=60`, {
193
+ headers: { 'x-api-key': ctx.env.PARALLEL_API_KEY },
194
+ signal: AbortSignal.timeout(70000),
195
+ });
196
+ if (r.status === 408)
197
+ continue; // still running
198
+ if (r.status === 404)
199
+ return []; // run failed (not billed)
200
+ if (r.status === 402 || r.status === 429)
201
+ throw new QuotaExceeded(`parallel HTTP ${r.status}`);
202
+ if (!r.ok)
203
+ throw new HttpError(r.status, await r.text(), r.url);
204
+ res = await r.json();
205
+ }
206
+ if (!res) {
207
+ ctx.log('parallel-task: gave up waiting for result');
208
+ return [];
209
+ }
210
+ return taskFindings(q, res.output);
211
+ },
212
+ };
213
+ export function taskFindings(q, output) {
214
+ const c = output?.content ?? {};
215
+ const basis = new Map((output?.basis ?? []).map((b) => [b.field, String(b.confidence ?? 'medium')]));
216
+ const conf = (field, kind) => TASK_CONF[basis.get(field) ?? 'medium']?.[kind] ?? 0.4;
217
+ const out = [];
218
+ const add = (field, key, v, kind = 'other') => {
219
+ const x = typeof v === 'string' ? v.trim() : '';
220
+ const c2 = conf(key, kind);
221
+ if (x && c2 > 0)
222
+ out.push({ field, value: x, source: 'parallel-task', confidence: c2, evidence: `basis ${basis.get(key) ?? 'n/a'}` });
223
+ };
224
+ const em = String(c.work_email ?? '').toLowerCase();
225
+ if (/^[^@\s]+@[^@\s]+\.[a-z]{2,}$/.test(em)) {
226
+ if (!q.domain || em.endsWith(`@${q.domain}`))
227
+ add('email', 'work_email', em, 'email');
228
+ }
229
+ const li = linkedinProfile(String(c.linkedin_url ?? ''));
230
+ if (li)
231
+ add('linkedin', 'linkedin_url', li);
232
+ add('title', 'job_title', c.job_title);
233
+ add('company', 'company', c.company);
234
+ add('location', 'location', c.location);
235
+ return out;
236
+ }
237
+ // ---------------------------------------------------------------- Exa
238
+ const EXA = 'https://api.exa.ai';
239
+ async function exaJson(ctx, path, init = {}, timeoutMs = 20000) {
240
+ const res = await ctx.fetch(`${EXA}${path}`, {
241
+ ...init,
242
+ headers: { 'x-api-key': ctx.env.EXA_API_KEY, 'content-type': 'application/json', ...(init.headers ?? {}) },
243
+ signal: init.signal ?? AbortSignal.timeout(timeoutMs),
244
+ });
245
+ if (res.status === 402 || res.status === 429)
246
+ throw new QuotaExceeded(`exa HTTP ${res.status}`);
247
+ const text = await res.text();
248
+ if (!res.ok)
249
+ throw new HttpError(res.status, text, res.url);
250
+ return text ? JSON.parse(text) : null;
251
+ }
252
+ export const exaPeopleProvider = {
253
+ id: 'exa-people',
254
+ kind: 'free-tier',
255
+ description: 'Exa people search, lite ($0.004/search from $10 free credit/month, no card): LinkedIn profile, title, location',
256
+ provides: ['linkedin', 'title', 'location', 'photo'],
257
+ keyEnv: 'EXA_API_KEY',
258
+ quota: { limit: 2000, period: 'month' },
259
+ needs: needsNameCompany,
260
+ async run(q, ctx) {
261
+ const d = await exaJson(ctx, '/search', {
262
+ method: 'POST',
263
+ body: JSON.stringify({ query: `${q.name} ${company(q)}`, category: 'people', type: 'lite', numResults: 5, contents: { text: { maxCharacters: 1500 } } }),
264
+ });
265
+ const results = d?.results ?? [];
266
+ const got = pickLinkedin(q, results.map((r) => {
267
+ const person = (r.entities ?? []).find((e) => e?.type === 'person')?.properties ?? null;
268
+ return { url: String(r.url ?? ''), title: String(r.title ?? ''), text: [r.text, person && JSON.stringify(person)].filter(Boolean).join('\n') };
269
+ }), 'exa-people', 0.85);
270
+ const li = got.find((f) => f.field === 'linkedin')?.value;
271
+ const image = results.find((r) => li && linkedinProfile(String(r.url ?? '')) === li)?.image;
272
+ if (image)
273
+ got.push({ field: 'photo', value: String(image), source: 'exa-people', confidence: 0.6 });
274
+ return got;
275
+ },
276
+ };
277
+ export const exaWebsetsProvider = {
278
+ id: 'exa-websets',
279
+ kind: 'free-tier',
280
+ description: 'Exa Websets: find the person + email enrichment (~$0.03-0.05 per hit incl. $0.02/email, from $10 free credit/month; async ~1 min)',
281
+ provides: ['email', 'linkedin', 'title', 'location'],
282
+ keyEnv: 'EXA_API_KEY',
283
+ quota: { limit: 150, period: 'month' },
284
+ chargesOnMiss: true,
285
+ needs: (q) => needsNameCompany(q) && !q.email,
286
+ async run(q, ctx) {
287
+ const ws = await exaJson(ctx, '/websets/v0/websets', {
288
+ method: 'POST',
289
+ body: JSON.stringify({
290
+ search: {
291
+ query: `${q.name} at ${company(q)}`,
292
+ count: 1,
293
+ entity: { type: 'person' },
294
+ criteria: [{ description: `The person is ${q.name} and currently works at ${company(q)}` }],
295
+ },
296
+ enrichments: [{ description: `Work email address of this person at ${company(q)}`, format: 'email' }],
297
+ }),
298
+ });
299
+ const id = ws?.id;
300
+ if (!id)
301
+ return [];
302
+ try {
303
+ for (let i = 0; i < 30; i++) {
304
+ await new Promise((r) => setTimeout(r, i < 5 ? 2000 : 4000));
305
+ const w = await exaJson(ctx, `/websets/v0/websets/${id}?expand=items`);
306
+ const items = w?.items ?? [];
307
+ const pending = items.some((it) => (it.enrichments ?? []).some((e) => e.status === 'pending'));
308
+ if (w?.status !== 'idle' || pending)
309
+ continue;
310
+ for (const it of items) {
311
+ const p = it.properties?.person ?? {};
312
+ if (!sameName(p.name, q.name))
313
+ continue;
314
+ const out = [];
315
+ const li = linkedinProfile(String(it.properties?.url ?? ''));
316
+ if (li)
317
+ out.push({ field: 'linkedin', value: li, source: 'exa-websets', confidence: 0.8 });
318
+ if (p.position)
319
+ out.push({ field: 'title', value: String(p.position), source: 'exa-websets', confidence: 0.7 });
320
+ if (p.location)
321
+ out.push({ field: 'location', value: String(p.location), source: 'exa-websets', confidence: 0.65 });
322
+ for (const e of it.enrichments ?? []) {
323
+ for (const v of e.result ?? []) {
324
+ const em = String(v).toLowerCase().trim();
325
+ if (!/^[^@\s]+@[^@\s]+$/.test(em))
326
+ continue;
327
+ const atDomain = !q.domain || em.endsWith(`@${q.domain}`);
328
+ out.push({ field: atDomain ? 'email' : 'personal_email', value: em, source: 'exa-websets', confidence: atDomain ? 0.75 : 0.5, evidence: 'Exa contact enrichment' });
329
+ }
330
+ }
331
+ return out;
332
+ }
333
+ return [];
334
+ }
335
+ ctx.log('exa-websets: gave up waiting');
336
+ return [];
337
+ }
338
+ finally {
339
+ // Do not leave one-person websets piling up in the account.
340
+ await ctx.fetch(`${EXA}/websets/v0/websets/${id}`, { method: 'DELETE', headers: { 'x-api-key': ctx.env.EXA_API_KEY }, signal: AbortSignal.timeout(10000) }).catch(() => { });
341
+ }
342
+ },
343
+ };
344
+ export const WEBSEARCH_FREE = [parallelSearchProvider];
345
+ /** In waterfall order: cheap and fast profile finders first, slower email research last. */
346
+ export const WEBSEARCH_FREE_TIER = [exaPeopleProvider, parallelEntityProvider, parallelTaskProvider, exaWebsetsProvider];
@@ -0,0 +1,31 @@
1
+ import { Store } from './store.ts';
2
+ import type { EnrichResult, Field, PersonQuery, Provider } from './types.ts';
3
+ export interface RouterOptions {
4
+ providers?: Provider[];
5
+ store?: Store;
6
+ env?: Record<string, string | undefined>;
7
+ fetch?: typeof fetch;
8
+ log?: (msg: string) => void;
9
+ /** A field counts as "found" at or above this confidence. */
10
+ threshold?: number;
11
+ /** Fields worth spending free-tier quota on. */
12
+ want?: Field[];
13
+ /** Allow free-tier (keyed, metered) providers. Default true. */
14
+ freeTier?: boolean;
15
+ /** Only use these provider ids. */
16
+ only?: string[];
17
+ /** Ignore cached results (still writes the cache). */
18
+ fresh?: boolean;
19
+ /** Max time per request for free sources (default 6000, env ENRICH_TIMEOUT_MS). */
20
+ perRequestMs?: number;
21
+ /** Max total time for free sources in one lookup (default 10000, env ENRICH_FREE_BUDGET_MS). */
22
+ freeBudgetMs?: number;
23
+ }
24
+ /** Cache row id for whole-lookup results (provider rows use the provider id). */
25
+ export declare const LOOKUP_CACHE = "lookup";
26
+ export declare function isEnabled(p: Provider, env: Record<string, string | undefined>): boolean;
27
+ /**
28
+ * The router: run free providers first, feed what they find (email, GitHub login) back in as new
29
+ * inputs, and only call the user's free-tier APIs while a wanted field is still below threshold.
30
+ */
31
+ export declare function enrich(input: PersonQuery, opts?: RouterOptions): Promise<EnrichResult>;
package/dist/router.js ADDED
@@ -0,0 +1,214 @@
1
+ import { merge } from "./merge.js";
2
+ import { DEFAULT_PROVIDERS } from "./providers/index.js";
3
+ import { Store } from "./store.js";
4
+ import { QuotaExceeded } from "./util/http.js";
5
+ import { normalizeQuery } from "./util/names.js";
6
+ import { detectPattern } from "./util/patterns.js";
7
+ /** Cache row id for whole-lookup results (provider rows use the provider id). */
8
+ export const LOOKUP_CACHE = 'lookup';
9
+ const DEFAULT_WANT = ['email', 'title', 'company', 'linkedin'];
10
+ function cacheKey(q) {
11
+ const k = ['name', 'domain', 'company', 'email', 'github'];
12
+ return JSON.stringify([...k.map((x) => q[x]?.toLowerCase() ?? ''), q.usernames ?? [], q.emailCandidates ?? []]);
13
+ }
14
+ /** Inputs that can grow during a lookup; a free provider that found nothing may run again when they change. */
15
+ function inputSig(q) {
16
+ return JSON.stringify([q.email ?? '', q.github ?? '', q.usernames ?? [], q.emailCandidates ?? []]);
17
+ }
18
+ export function isEnabled(p, env) {
19
+ if (p.enabled)
20
+ return p.enabled(env);
21
+ return !p.keyEnv || Boolean(env[p.keyEnv]);
22
+ }
23
+ /** Candidate handles for username-based sources: GitHub login, X handle, personal-email local part. */
24
+ function usernamesFrom(q, best) {
25
+ const out = new Set();
26
+ if (q.github)
27
+ out.add(q.github);
28
+ const tw = best.twitter?.value.match(/(?:twitter|x)\.com\/([A-Za-z0-9_]{1,15})/i)?.[1];
29
+ if (tw)
30
+ out.add(tw);
31
+ const pe = best.personal_email?.value.split('@')[0];
32
+ if (pe && /^[a-z0-9._-]{3,}$/i.test(pe) && !/^(info|hello|contact|mail|me)$/i.test(pe))
33
+ out.add(pe);
34
+ return [...out];
35
+ }
36
+ /** Unconfirmed email values, best first (for verifier providers). */
37
+ function emailCandidates(findings, threshold) {
38
+ const { best, alternatives } = merge(findings.filter((f) => f.field === 'email'));
39
+ return [best.email, ...(alternatives.email ?? [])]
40
+ .filter((e) => Boolean(e) && e.confidence < threshold)
41
+ .slice(0, 3)
42
+ .map((e) => e.value.toLowerCase());
43
+ }
44
+ /**
45
+ * The router: run free providers first, feed what they find (email, GitHub login) back in as new
46
+ * inputs, and only call the user's free-tier APIs while a wanted field is still below threshold.
47
+ */
48
+ export async function enrich(input, opts = {}) {
49
+ const env = opts.env ?? process.env;
50
+ const store = opts.store ?? new Store();
51
+ const threshold = opts.threshold ?? 0.8;
52
+ const want = opts.want ?? DEFAULT_WANT;
53
+ const all = (opts.providers ?? DEFAULT_PROVIDERS).filter((p) => !opts.only || opts.only.includes(p.id));
54
+ const ctx = { fetch: opts.fetch ?? fetch, env, log: opts.log ?? (() => { }), store };
55
+ const started = Date.now();
56
+ const q = normalizeQuery(input);
57
+ // Whole-lookup cache: the same question with the same sources on answers from disk, in milliseconds.
58
+ // Keyed on the original query (not on inputs found mid-lookup), plus the enabled sources and settings,
59
+ // so adding a key or changing the wanted fields runs a fresh lookup.
60
+ const lookupKey = JSON.stringify([
61
+ cacheKey(q), opts.freeTier !== false, threshold, want,
62
+ all.filter((p) => isEnabled(p, env)).map((p) => p.id),
63
+ ]);
64
+ if (!opts.fresh) {
65
+ const t0 = Date.now();
66
+ const hit = store.getCache(LOOKUP_CACHE, lookupKey);
67
+ if (hit) {
68
+ return { query: q, ...merge(hit), trace: [{ provider: LOOKUP_CACHE, status: 'cached', ms: Date.now() - t0, note: `${hit.length} findings` }] };
69
+ }
70
+ }
71
+ const findings = [];
72
+ if (q.email)
73
+ findings.push({ field: 'email', value: q.email, source: 'input', confidence: 0.5 });
74
+ const trace = [];
75
+ const ran = new Set();
76
+ /** For free providers that found nothing: the inputs they ran with, so they can retry on new inputs. */
77
+ const missedWith = new Map();
78
+ /** Email candidates a verifier already checked (valid ones become findings; others must not be re-checked). */
79
+ const checked = new Set();
80
+ // Speed limits for free sources: each request gets perRequestMs; all free work in one lookup gets freeBudgetMs.
81
+ // A late source is dropped (and its requests aborted) instead of holding up the answer.
82
+ const perRequestMs = opts.perRequestMs ?? Number(env.ENRICH_TIMEOUT_MS || 6000);
83
+ const freeBudgetMs = opts.freeBudgetMs ?? Number(env.ENRICH_FREE_BUDGET_MS || 10000);
84
+ const stop = new AbortController();
85
+ const freeDeadline = Date.now() + freeBudgetMs;
86
+ const budgetTimer = setTimeout(() => stop.abort(new Error('free-source time budget used')), freeBudgetMs);
87
+ budgetTimer.unref?.();
88
+ const baseFetch = ctx.fetch;
89
+ const freeFetch = Object.assign(((url, init = {}) => {
90
+ const signals = [AbortSignal.timeout(perRequestMs), stop.signal];
91
+ if (init.signal)
92
+ signals.push(init.signal);
93
+ return baseFetch(url, { ...init, signal: AbortSignal.any(signals) });
94
+ }), { base: baseFetch.base ?? baseFetch });
95
+ const freeCtx = { ...ctx, fetch: freeFetch };
96
+ const runs = new Map();
97
+ const runOne = async (p) => {
98
+ ran.add(p.id);
99
+ runs.set(p.id, (runs.get(p.id) ?? 0) + 1);
100
+ const t0 = Date.now();
101
+ const sig = inputSig(q);
102
+ const input = { ...q };
103
+ const key = cacheKey(input);
104
+ const cached = opts.fresh ? null : store.getCache(p.id, key);
105
+ if (cached) {
106
+ if (p.kind === 'free' && !cached.length)
107
+ missedWith.set(p.id, sig);
108
+ else
109
+ missedWith.delete(p.id);
110
+ findings.push(...cached);
111
+ trace.push({ provider: p.id, status: 'cached', ms: 0, note: `${cached.length} findings` });
112
+ return;
113
+ }
114
+ try {
115
+ if (p.verifies && input.emailCandidates?.[0])
116
+ checked.add(input.emailCandidates[0]);
117
+ const got = (await p.run(input, p.kind === 'free' ? freeCtx : ctx)).filter((f) => f.value && f.value.trim());
118
+ findings.push(...got);
119
+ store.setCache(p.id, key, got);
120
+ if (p.quota && (got.length || p.chargesOnMiss))
121
+ store.useQuota(p.id, p.quota);
122
+ if (p.kind === 'free' && !got.length)
123
+ missedWith.set(p.id, sig);
124
+ else
125
+ missedWith.delete(p.id);
126
+ trace.push({ provider: p.id, status: got.length ? 'hit' : 'miss', ms: Date.now() - t0, at: Date.now() - started, note: `${got.length} findings` });
127
+ }
128
+ catch (e) {
129
+ if (e instanceof QuotaExceeded && p.quota)
130
+ store.markExhausted(p.id, p.quota);
131
+ const late = p.kind === 'free' && stop.signal.aborted;
132
+ trace.push({ provider: p.id, status: 'error', ms: Date.now() - t0, at: Date.now() - started, note: late ? 'dropped: free-source time budget used' : e.message.slice(0, 200) });
133
+ }
134
+ };
135
+ /** Feed confident discoveries back in as inputs (email, GitHub login, handles, unconfirmed emails). */
136
+ const refresh = () => {
137
+ const { best } = merge(findings);
138
+ if (!q.email && best.email && best.email.confidence >= threshold)
139
+ q.email = best.email.value.toLowerCase();
140
+ if (!q.github && best.github && best.github.confidence >= threshold)
141
+ q.github = best.github.value.replace(/.*github\.com\//i, '');
142
+ q.usernames = usernamesFrom(q, best);
143
+ q.emailCandidates = q.email ? [] : emailCandidates(findings, threshold).filter((e) => !checked.has(e));
144
+ return best;
145
+ };
146
+ /**
147
+ * Free stage, no rounds: every free source starts as soon as its inputs exist, and when any source
148
+ * finishes, newly unlocked sources start at once. Wall time = the longest chain, not a sum of rounds.
149
+ * A source that found nothing runs again only if it opted in (retryOnNewInputs) and its inputs changed.
150
+ */
151
+ const running = new Map();
152
+ const freeStage = async () => {
153
+ const launch = () => {
154
+ if (Date.now() >= freeDeadline)
155
+ return;
156
+ refresh();
157
+ const sig = inputSig(q);
158
+ for (const p of all) {
159
+ if (p.kind !== 'free' || running.has(p.id) || !isEnabled(p, env))
160
+ continue;
161
+ // Guard: at most 3 runs of one source per lookup, whatever its inputs do.
162
+ const again = ran.has(p.id) && p.retryOnNewInputs && (runs.get(p.id) ?? 0) < 3 && missedWith.has(p.id) && missedWith.get(p.id) !== sig;
163
+ if ((ran.has(p.id) && !again) || !p.needs(q))
164
+ continue;
165
+ running.set(p.id, runOne(p).finally(() => { running.delete(p.id); launch(); }));
166
+ }
167
+ };
168
+ launch();
169
+ while (running.size)
170
+ await Promise.race(running.values());
171
+ };
172
+ await freeStage();
173
+ for (let i = 0; i < 60 && opts.freeTier !== false; i++) {
174
+ const best = refresh();
175
+ const missing = (f) => want.includes(f) && (best[f]?.confidence ?? 0) < threshold;
176
+ const next = all.find((p) => {
177
+ if (p.kind !== 'free-tier' || ran.has(p.id) || !p.needs(q) || !p.provides.some(missing))
178
+ return false;
179
+ // A verifier is only worth a credit when there is an unchecked guess to confirm.
180
+ if (p.verifies && !q.emailCandidates?.length)
181
+ return false;
182
+ if (!isEnabled(p, env))
183
+ return false;
184
+ if (p.quota && store.quotaLeft(p.id, p.quota) <= 0) {
185
+ ran.add(p.id);
186
+ trace.push({ provider: p.id, status: 'skipped', ms: 0, note: 'free quota used up this period' });
187
+ return false;
188
+ }
189
+ return true;
190
+ });
191
+ if (!next)
192
+ break;
193
+ await runOne(next);
194
+ await freeStage(); // what it found (e.g. an email) may unlock free sources (Gravatar, OpenPGP, ...)
195
+ }
196
+ clearTimeout(budgetTimer);
197
+ for (const p of all) {
198
+ if (!ran.has(p.id) && p.kind === 'free-tier' && !isEnabled(p, env)) {
199
+ trace.push({ provider: p.id, status: 'skipped', ms: 0, note: `no key (${p.keyEnv})` });
200
+ }
201
+ }
202
+ const merged = merge(findings);
203
+ // Learn the domain's email pattern from a confirmed (not guessed) address.
204
+ const e = merged.best.email;
205
+ if (e && e.confidence >= threshold && q.firstName && q.lastName && q.domain && e.sources.some((s) => s !== 'guess' && s !== 'input')) {
206
+ if (e.value.endsWith(`@${q.domain}`)) {
207
+ const p = detectPattern(e.value, q.firstName, q.lastName);
208
+ if (p)
209
+ store.learnPattern(q.domain, p);
210
+ }
211
+ }
212
+ store.setCache(LOOKUP_CACHE, lookupKey, findings);
213
+ return { query: normalizeQuery(input), ...merged, trace };
214
+ }
@@ -0,0 +1,2 @@
1
+ /** POST /enrich {name, domain, company, email, github, freeTier?} -> EnrichResult. GET /providers. POST /mcp (MCP). Binds to localhost. */
2
+ export declare function serve(port?: number, host?: string): import("http").Server<typeof import("http").IncomingMessage, typeof import("http").ServerResponse>;
package/dist/server.js ADDED
@@ -0,0 +1,52 @@
1
+ import { createServer } from 'node:http';
2
+ import { enrich, isEnabled } from "./router.js";
3
+ import { DEFAULT_PROVIDERS } from "./providers/index.js";
4
+ import { Store } from "./store.js";
5
+ import { createHandler } from "./mcp/server.js";
6
+ /** POST /enrich {name, domain, company, email, github, freeTier?} -> EnrichResult. GET /providers. POST /mcp (MCP). Binds to localhost. */
7
+ export function serve(port = 8787, host = '127.0.0.1') {
8
+ const store = new Store();
9
+ const mcp = createHandler({ store });
10
+ const server = createServer(async (req, res) => {
11
+ const send = (code, body) => {
12
+ res.writeHead(code, { 'content-type': 'application/json' });
13
+ res.end(JSON.stringify(body, null, 2));
14
+ };
15
+ try {
16
+ if (req.method === 'GET' && req.url === '/providers') {
17
+ return send(200, DEFAULT_PROVIDERS.map((p) => ({ id: p.id, kind: p.kind, provides: p.provides, enabled: isEnabled(p, process.env), quota: p.quota ?? null, quotaLeft: p.quota ? store.quotaLeft(p.id, p.quota) : null })));
18
+ }
19
+ if (req.method === 'POST' && req.url === '/enrich') {
20
+ let raw = '';
21
+ for await (const chunk of req)
22
+ raw += chunk;
23
+ const body = JSON.parse(raw || '{}');
24
+ const { freeTier, ...q } = body;
25
+ return send(200, await enrich(q, { store, freeTier: freeTier !== false }));
26
+ }
27
+ if (req.url === '/mcp') {
28
+ // MCP Streamable HTTP, JSON replies only (no server-initiated messages, so no SSE stream).
29
+ if (req.method !== 'POST') {
30
+ res.writeHead(405, { allow: 'POST' }).end();
31
+ return;
32
+ }
33
+ let raw = '';
34
+ for await (const chunk of req)
35
+ raw += chunk;
36
+ const msg = JSON.parse(raw || 'null');
37
+ const out = Array.isArray(msg) ? (await Promise.all(msg.map(mcp))).filter(Boolean) : await mcp(msg);
38
+ if (!out || (Array.isArray(out) && !out.length)) {
39
+ res.writeHead(202).end();
40
+ return;
41
+ }
42
+ return send(200, out);
43
+ }
44
+ send(404, { error: 'not found' });
45
+ }
46
+ catch (e) {
47
+ send(400, { error: e.message });
48
+ }
49
+ });
50
+ server.listen(port, host, () => console.log(`openrich listening on http://${host}:${port}`));
51
+ return server;
52
+ }