@crewhaus/tool-kyc 0.7.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.
package/dist/index.js ADDED
@@ -0,0 +1,821 @@
1
+ /**
2
+ * @crewhaus/tool-kyc — checking who you are about to pay or invoice.
3
+ *
4
+ * Three tools, one rule they all obey:
5
+ *
6
+ * **found / not-found / could-not-check are THREE outcomes, and the third
7
+ * one says why.**
8
+ *
9
+ * That is not a nicety. VIES is a proxy to twenty-seven member states' own
10
+ * systems and several of them are down at any given moment; GLEIF and EDGAR
11
+ * rate-limit; a corporate proxy answers 403. Every one of those is a
12
+ * *could-not-check*, and a tool that reports them as "not valid" makes a
13
+ * harness get an invoice's VAT treatment wrong because a government server was
14
+ * being rebooted. So there is no `valid: boolean` anywhere in this package —
15
+ * a boolean has two values, this has three, and the collapse always goes the
16
+ * same way.
17
+ *
18
+ * The second rule, for `SanctionsScreen`: it returns signals and evidence,
19
+ * never a verdict. `@crewhaus/tool-money`'s controls already set that
20
+ * precedent for this domain — `refundAbuseSignals` returns ratios and says a
21
+ * person decides, and returns `null` rather than infinity when the denominator
22
+ * is zero. A sanctions match is a legal determination with legal consequences;
23
+ * the tool surfaces candidates, the basis for each, and the list versions it
24
+ * used, and stops there.
25
+ *
26
+ * Nothing here moves money, and nothing here can. No schema accepts a bank
27
+ * credential, a card number or a payment-provider key, and the only bytes that
28
+ * leave the process are a VAT id or a company identifier going to a public
29
+ * register. `index.test.ts` asserts both over every schema in the package.
30
+ */
31
+ import { readFileSync, statSync } from "node:fs";
32
+ import { buildTool } from "@crewhaus/tool-builder";
33
+ import { z } from "zod";
34
+ import { LEI_PATTERN, leiChecksumValid, normalizeEdgar, normalizeGleif, padCik, tickerIndex, } from "./lib/entity";
35
+ import { canonicalizeName, rankNames, round6 } from "./lib/names";
36
+ import { DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS, ORIGINS, getJson, json, parseInstant, safeLabel, startDeadline, } from "./lib/net";
37
+ import { checkSnapshot, screenSubjects, } from "./lib/screen";
38
+ import { checkSyntax, hmrcErrorMeaning, mapHmrcResponse, mapViesResponse, parseVatId, } from "./lib/vat";
39
+ import { resolveSafe } from "./paths";
40
+ export { _setKycFetch, ORIGINS } from "./lib/net";
41
+ const LIMITS = {
42
+ subjects: 500,
43
+ lists: 16,
44
+ entriesPerList: 100_000,
45
+ snapshotBytes: 64 * 1024 * 1024,
46
+ candidates: 50,
47
+ searchResults: 25,
48
+ };
49
+ const NETWORK_TOOL = {
50
+ readOnly: true,
51
+ concurrencySafe: true,
52
+ // Pillar 3 sink-side: these cross a network boundary, so they declare it and
53
+ // lower external. The destinations are four constants, but "we only talk to
54
+ // VIES" is not a reason to hide that bytes leave the process.
55
+ scope: "external",
56
+ ioCapability: "network",
57
+ };
58
+ const timeoutField = z
59
+ .number()
60
+ .int()
61
+ .positive()
62
+ .max(MAX_TIMEOUT_MS)
63
+ .optional()
64
+ .describe(`deadline for the whole call in ms; default ${DEFAULT_TIMEOUT_MS}`);
65
+ const nowField = z
66
+ .string()
67
+ .max(64)
68
+ .optional()
69
+ .describe("ISO-8601 with an offset; overrides the clock, for replays and tests");
70
+ function nowMsFrom(value) {
71
+ return value === undefined ? Date.now() : parseInstant(value, "now");
72
+ }
73
+ /**
74
+ * Whether asking again later could plausibly help.
75
+ *
76
+ * `refused` and `unauthorized` are not retryable — something structural is in
77
+ * the way, and a harness that retries them just burns its deadline.
78
+ */
79
+ function retryable(kind) {
80
+ return kind === "rateLimited" || kind === "transport" || kind === "status";
81
+ }
82
+ // ---------------------------------------------------------------------------
83
+ // VatIdValidate
84
+ // ---------------------------------------------------------------------------
85
+ export const vatIdValidate = buildTool({
86
+ name: "VatIdValidate",
87
+ description: "Check an EU, Northern Irish or UK VAT number: its country's own format first, then VIES or HMRC for whether it is actually registered, with the consultation number when a requester id is supplied. Use it before zero-rating an intra-community supply or paying an invoice that claims a VAT number. It reports THREE outcomes — registered, not registered, and could-not-check with the reason — because VIES is a proxy to member states' systems that are routinely down, and reading an outage as 'not valid' gets the invoice wrong. A registered number means the number exists, not that it belongs to whoever sent you the invoice.",
88
+ inputSchema: z
89
+ .object({
90
+ vatId: z
91
+ .string()
92
+ .min(2)
93
+ .max(32)
94
+ .describe("with or without the country prefix; spaces and dots are ignored"),
95
+ country: z
96
+ .string()
97
+ .length(2)
98
+ .optional()
99
+ .describe("two-letter code, when the id is written without a prefix"),
100
+ requesterVatId: z
101
+ .string()
102
+ .min(2)
103
+ .max(32)
104
+ .optional()
105
+ .describe("your own VAT id; the register issues a consultation number — the receipt an auditor asks for — only on this two-party call"),
106
+ syntaxOnly: z
107
+ .boolean()
108
+ .optional()
109
+ .describe("check the format and do not dial anything; registration then reads as unchecked"),
110
+ timeoutMs: timeoutField,
111
+ now: nowField,
112
+ })
113
+ .strict(),
114
+ ...NETWORK_TOOL,
115
+ execute: async (input, ctx) => {
116
+ const parsed = parseVatId(input.vatId, input.country);
117
+ if (!parsed.ok)
118
+ return `VatIdValidate could not read "${input.vatId}": ${parsed.reason}`;
119
+ const syntax = checkSyntax(parsed);
120
+ const checkedAt = new Date(nowMsFrom(input.now)).toISOString();
121
+ const base = {
122
+ vatId: syntax.canonical,
123
+ country: syntax.country,
124
+ countryName: syntax.countryName,
125
+ syntax,
126
+ checkedAt,
127
+ notes: [
128
+ "registration is not identity: the register confirms the number exists and who holds it, not that the party invoicing you is that holder",
129
+ "outcome is one of found, notFound or unavailable — there is no boolean here, because could-not-check is not a kind of invalid",
130
+ ],
131
+ };
132
+ if (!syntax.wellFormed) {
133
+ // A local answer, and a real one: an id that cannot exist in the
134
+ // country's own grammar is not registered anywhere. The result names the
135
+ // pattern so a caller can see WHY, because this table is ours and a
136
+ // country can change its format.
137
+ return json({
138
+ ...base,
139
+ outcome: "notFound",
140
+ basis: syntax.reason,
141
+ register: "syntax",
142
+ dialled: false,
143
+ });
144
+ }
145
+ if (input.syntaxOnly === true) {
146
+ // The same shape an outage produces, deliberately: "the format is fine
147
+ // and nobody has checked whether it is registered" is the same fact
148
+ // about the world as "the member state did not answer", and a caller
149
+ // should not have to handle it twice.
150
+ return json({
151
+ ...base,
152
+ outcome: "unavailable",
153
+ basis: "syntaxOnly was set, so no register was asked — the format is well-formed and nothing has checked whether it is registered",
154
+ register: "none",
155
+ dialled: false,
156
+ retryable: true,
157
+ });
158
+ }
159
+ const requester = input.requesterVatId === undefined ? undefined : parseVatId(input.requesterVatId);
160
+ if (requester !== undefined && !requester.ok) {
161
+ return `VatIdValidate could not read requesterVatId "${input.requesterVatId}": ${requester.reason}`;
162
+ }
163
+ if (requester?.ok === true) {
164
+ // The two registers issue their receipt to their OWN kind of requester:
165
+ // HMRC takes a GB VRN, VIES takes a member state's number. Sending the
166
+ // wrong one means the number part is read as if it belonged to the other
167
+ // register — which answers about somebody else's VAT registration, or
168
+ // fails in a way that reads like the SUBJECT's id being wrong. Refused
169
+ // here, before anything is dialled.
170
+ const targetIsGb = syntax.country === "GB";
171
+ const requesterIsGb = requester.country.code === "GB";
172
+ if (targetIsGb !== requesterIsGb) {
173
+ return `VatIdValidate will not use requesterVatId ${requester.canonical} for ${syntax.canonical}: ${targetIsGb
174
+ ? "HMRC issues a consultation number only to a GB requester"
175
+ : "VIES issues a consultation number only to a requester registered in a member state, and GB is no longer one"}. Drop requesterVatId to get the registration answer without a consultation number.`;
176
+ }
177
+ }
178
+ const deadline = startDeadline(input.timeoutMs ?? DEFAULT_TIMEOUT_MS, ctx?.signal);
179
+ try {
180
+ const answer = syntax.country === "GB"
181
+ ? await askHmrc(syntax.number, requester?.ok === true ? requester.number : undefined, deadline.signal)
182
+ : await askVies(syntax.country, syntax.number, requester?.ok === true ? requester : undefined, deadline.signal);
183
+ return json({
184
+ ...base,
185
+ ...answer.answer,
186
+ register: answer.register,
187
+ sourceUrl: answer.sourceUrl,
188
+ dialled: true,
189
+ });
190
+ }
191
+ finally {
192
+ deadline.cancel();
193
+ }
194
+ },
195
+ });
196
+ /** A transport-level failure is always `unavailable`, never a verdict. */
197
+ function unavailableFrom(result, register) {
198
+ return {
199
+ outcome: "unavailable",
200
+ basis: `${register} could not be read: ${result.message}`,
201
+ retryable: retryable(result.kind),
202
+ ...(result.status === undefined ? {} : { code: `HTTP ${result.status}` }),
203
+ };
204
+ }
205
+ async function askVies(country, number, requester, signal) {
206
+ const twoParty = requester !== undefined;
207
+ const url = twoParty
208
+ ? `${ORIGINS.vies}/taxation_customs/vies/rest-api/check-vat-number`
209
+ : `${ORIGINS.vies}/taxation_customs/vies/rest-api/ms/${country}/vat/${number}`;
210
+ const result = await getJson(url, {
211
+ signal,
212
+ ...(twoParty
213
+ ? {
214
+ postJson: {
215
+ countryCode: country,
216
+ vatNumber: number,
217
+ requesterMemberStateCode: requester?.country.code,
218
+ requesterNumber: requester?.number,
219
+ },
220
+ }
221
+ : {}),
222
+ });
223
+ if (!result.ok) {
224
+ return { answer: unavailableFrom(result, "VIES"), register: "vies", sourceUrl: safeLabel(url) };
225
+ }
226
+ return {
227
+ answer: mapViesResponse(result.value, twoParty),
228
+ register: "vies",
229
+ sourceUrl: safeLabel(url),
230
+ };
231
+ }
232
+ async function askHmrc(number, requesterNumber, signal) {
233
+ const path = requesterNumber === undefined
234
+ ? `/organisations/vat/check-vat-number/lookup/${number}`
235
+ : `/organisations/vat/check-vat-number/lookup/${number}/${requesterNumber}`;
236
+ const url = `${ORIGINS.hmrc}${path}`;
237
+ // HMRC versions its APIs through the Accept header and answers 406 without
238
+ // one. It is not a credential — every caller sends the same string.
239
+ const result = await getJson(url, { signal, accept: "application/vnd.hmrc.1.0+json" });
240
+ if (!result.ok) {
241
+ if (result.kind === "notFound") {
242
+ return {
243
+ answer: {
244
+ outcome: "notFound",
245
+ basis: hmrcErrorMeaning("NOT_FOUND", result.status),
246
+ code: "NOT_FOUND",
247
+ },
248
+ register: "hmrc",
249
+ sourceUrl: safeLabel(url),
250
+ };
251
+ }
252
+ return { answer: unavailableFrom(result, "HMRC"), register: "hmrc", sourceUrl: safeLabel(url) };
253
+ }
254
+ return {
255
+ answer: mapHmrcResponse(result.value, requesterNumber !== undefined),
256
+ register: "hmrc",
257
+ sourceUrl: safeLabel(url),
258
+ };
259
+ }
260
+ // ---------------------------------------------------------------------------
261
+ // EntityRegistryLookup
262
+ // ---------------------------------------------------------------------------
263
+ const REGISTRIES = ["gleif", "sec-edgar"];
264
+ export const entityRegistryLookup = buildTool({
265
+ name: "EntityRegistryLookup",
266
+ description: "Look one company up in GLEIF and SEC EDGAR by LEI, CIK, ticker or name, and return one row per register with its own source URL and retrieval time. Use it to check a counterparty exists and is who the invoice says. The rows are NOT merged into one confident record: the registers disagree about legal names, and GLEIF's two statuses answer different questions — a LAPSED LEI usually means an unpaid renewal, not a dissolved company. The result shows the differences and lets the caller judge them, and a register that could not be read is reported as could-not-check, never as 'no such company'.",
267
+ inputSchema: z
268
+ .object({
269
+ lei: z.string().min(20).max(20).optional().describe("ISO 17442 legal entity identifier"),
270
+ cik: z.string().min(1).max(12).optional().describe("SEC central index key, padded or not"),
271
+ ticker: z
272
+ .string()
273
+ .min(1)
274
+ .max(16)
275
+ .optional()
276
+ .describe("exchange ticker, resolved via EDGAR's own map"),
277
+ name: z
278
+ .string()
279
+ .min(2)
280
+ .max(256)
281
+ .optional()
282
+ .describe("legal name; discloses the name to the register, unlike an id lookup"),
283
+ registries: z
284
+ .array(z.enum(REGISTRIES))
285
+ .min(1)
286
+ .max(REGISTRIES.length)
287
+ .optional()
288
+ .describe("default: both"),
289
+ limit: z
290
+ .number()
291
+ .int()
292
+ .positive()
293
+ .max(LIMITS.searchResults)
294
+ .optional()
295
+ .describe("results per register for a name search; default 5"),
296
+ timeoutMs: timeoutField,
297
+ now: nowField,
298
+ })
299
+ .strict(),
300
+ ...NETWORK_TOOL,
301
+ execute: async (input, ctx) => {
302
+ if (input.lei === undefined &&
303
+ input.cik === undefined &&
304
+ input.ticker === undefined &&
305
+ input.name === undefined) {
306
+ return "EntityRegistryLookup needs at least one of lei, cik, ticker or name — there is nothing to look up";
307
+ }
308
+ if (input.lei !== undefined && !leiChecksumValid(input.lei.toUpperCase())) {
309
+ // Refused before dialling. GLEIF answers 404 for a mistyped LEI, and a
310
+ // 404 reads like "this company has no LEI record", which is a different
311
+ // and much more interesting claim than "you typed it wrong".
312
+ return `EntityRegistryLookup will not look up "${input.lei}": it is not a valid LEI — ${LEI_PATTERN.test(input.lei.toUpperCase())
313
+ ? "the ISO 7064 check digits do not match, so a character is wrong"
314
+ : "an LEI is 18 alphanumerics then 2 check digits"}`;
315
+ }
316
+ const wanted = input.registries ?? [...REGISTRIES];
317
+ const limit = input.limit ?? 5;
318
+ const retrievedAt = new Date(nowMsFrom(input.now)).toISOString();
319
+ const deadline = startDeadline(input.timeoutMs ?? DEFAULT_TIMEOUT_MS, ctx?.signal);
320
+ try {
321
+ const rows = [];
322
+ if (wanted.includes("gleif")) {
323
+ rows.push(...(await readGleif(input, limit, retrievedAt, deadline.signal)));
324
+ }
325
+ if (wanted.includes("sec-edgar")) {
326
+ rows.push(...(await readEdgar(input, retrievedAt, deadline.signal)));
327
+ }
328
+ return json({
329
+ query: {
330
+ ...(input.lei === undefined ? {} : { lei: input.lei.toUpperCase() }),
331
+ ...(input.cik === undefined ? {} : { cik: input.cik }),
332
+ ...(input.ticker === undefined ? {} : { ticker: input.ticker.toUpperCase() }),
333
+ ...(input.name === undefined ? {} : { name: input.name }),
334
+ },
335
+ registries: rows,
336
+ comparison: await compareRows(rows),
337
+ note: "one row per register, not merged. Where two registers disagree the disagreement is the finding, and GLEIF's entityStatus and registrationStatus answer different questions — a LAPSED registration is usually an unpaid renewal fee, not a dissolved company.",
338
+ });
339
+ }
340
+ finally {
341
+ deadline.cancel();
342
+ }
343
+ },
344
+ });
345
+ /**
346
+ * A failed read of a URL that IS a record about the subject.
347
+ *
348
+ * Only for those. A 404 on `lei-records/<LEI>` or on `submissions/CIK…json`
349
+ * really is the register saying it holds no such record, but a 404 on an INDEX
350
+ * — EDGAR's ticker map, GLEIF's search endpoint — is the file having moved,
351
+ * and passing it through here turns a broken fetch into a finding about a
352
+ * counterparty nobody looked up. Those two callers use `indexFailedRow`.
353
+ */
354
+ function failedRow(registry, result, sourceUrl, retrievedAt, notFoundReason) {
355
+ if (result.kind === "notFound") {
356
+ return { registry, outcome: "notFound", sourceUrl, retrievedAt, reason: notFoundReason };
357
+ }
358
+ return {
359
+ registry,
360
+ outcome: "unavailable",
361
+ sourceUrl,
362
+ retrievedAt,
363
+ reason: result.message,
364
+ retryable: retryable(result.kind),
365
+ };
366
+ }
367
+ /**
368
+ * A failed read of an INDEX the lookup goes THROUGH, never of a record.
369
+ *
370
+ * Every kind maps to `unavailable`, including `notFound`, because none of them
371
+ * is evidence about the subject: the question was never put. The genuine
372
+ * negative — the map does not carry this ticker, the search matched no name —
373
+ * arrives as a 200 with nothing in it, and is reported by the caller.
374
+ */
375
+ function indexFailedRow(registry, result, sourceUrl, retrievedAt, what) {
376
+ return {
377
+ registry,
378
+ outcome: "unavailable",
379
+ sourceUrl,
380
+ retrievedAt,
381
+ reason: `${what} could not be read, so nothing was looked up: ${result.message}`,
382
+ retryable: retryable(result.kind),
383
+ };
384
+ }
385
+ async function readGleif(input, limit, retrievedAt, signal) {
386
+ if (input.lei !== undefined) {
387
+ const url = `${ORIGINS.gleif}/api/v1/lei-records/${input.lei.toUpperCase()}`;
388
+ const result = await getJson(url, { signal });
389
+ if (!result.ok) {
390
+ return [failedRow("gleif", result, url, retrievedAt, "GLEIF holds no record for this LEI")];
391
+ }
392
+ const data = result.value["data"];
393
+ const record = normalizeGleif(data?.["attributes"]);
394
+ return [
395
+ record === null
396
+ ? {
397
+ registry: "gleif",
398
+ outcome: "unavailable",
399
+ sourceUrl: url,
400
+ retrievedAt,
401
+ reason: "GLEIF answered 200 with a body this tool could not read as an LEI record",
402
+ retryable: false,
403
+ }
404
+ : { registry: "gleif", outcome: "found", sourceUrl: url, retrievedAt, record },
405
+ ];
406
+ }
407
+ if (input.name === undefined) {
408
+ return [
409
+ {
410
+ registry: "gleif",
411
+ outcome: "unavailable",
412
+ sourceUrl: `${ORIGINS.gleif}/api/v1/lei-records`,
413
+ retrievedAt,
414
+ reason: "GLEIF is searchable by LEI or by legal name, and neither was supplied — a CIK or a ticker means nothing to it",
415
+ retryable: false,
416
+ },
417
+ ];
418
+ }
419
+ const url = new URL(`${ORIGINS.gleif}/api/v1/lei-records`);
420
+ url.searchParams.set("filter[entity.legalName]", input.name);
421
+ url.searchParams.set("page[size]", String(limit));
422
+ // The query IS the evidence for a search row, so the source URL keeps it
423
+ // rather than going through `safeLabel`. That rule exists to keep a searched
424
+ // name out of a message it does not belong in; here the name is already in
425
+ // this same document, under `query`, so stripping it would cost
426
+ // reproducibility and buy nothing.
427
+ const searchUrl = url.toString();
428
+ const result = await getJson(searchUrl, { signal });
429
+ if (!result.ok) {
430
+ return [indexFailedRow("gleif", result, searchUrl, retrievedAt, "GLEIF's legal-name search")];
431
+ }
432
+ const data = result.value["data"];
433
+ const list = Array.isArray(data) ? data : [];
434
+ if (list.length === 0) {
435
+ return [
436
+ {
437
+ registry: "gleif",
438
+ outcome: "notFound",
439
+ sourceUrl: searchUrl,
440
+ retrievedAt,
441
+ reason: `GLEIF has no LEI record whose legal name matches "${input.name}" — which is common and ordinary: an LEI is only required of parties to certain financial transactions`,
442
+ },
443
+ ];
444
+ }
445
+ const records = list
446
+ .map((item) => normalizeGleif(item["attributes"]))
447
+ .filter((record) => record !== null);
448
+ if (records.length === 0) {
449
+ // GLEIF answered with hits and none of them parsed. Returning the empty
450
+ // array made the register VANISH from `registries` — not found, not
451
+ // notFound, not unavailable, no row at all — and the comparison then said
452
+ // "no register returned a record", which reads like GLEIF had nothing to
453
+ // say about the company rather than like this tool could not read it.
454
+ return [
455
+ {
456
+ registry: "gleif",
457
+ outcome: "unavailable",
458
+ sourceUrl: searchUrl,
459
+ retrievedAt,
460
+ reason: `GLEIF returned ${list.length} hit${list.length === 1 ? "" : "s"} in a shape this tool could not read as LEI records`,
461
+ retryable: false,
462
+ },
463
+ ];
464
+ }
465
+ return records.map((record) => ({
466
+ registry: "gleif",
467
+ outcome: "found",
468
+ sourceUrl: searchUrl,
469
+ retrievedAt,
470
+ record,
471
+ }));
472
+ }
473
+ async function readEdgar(input, retrievedAt, signal) {
474
+ let cik = input.cik === undefined ? null : padCik(input.cik);
475
+ let resolvedVia;
476
+ if (input.cik !== undefined && cik === null) {
477
+ return [
478
+ {
479
+ registry: "sec-edgar",
480
+ outcome: "unavailable",
481
+ sourceUrl: ORIGINS.edgarData,
482
+ retrievedAt,
483
+ reason: `"${input.cik}" is not a CIK: it is up to ten digits, optionally prefixed CIK and zero-padded`,
484
+ retryable: false,
485
+ },
486
+ ];
487
+ }
488
+ if (cik === null && (input.ticker !== undefined || input.name !== undefined)) {
489
+ const mapUrl = `${ORIGINS.edgarFiles}/files/company_tickers.json`;
490
+ const map = await getJson(mapUrl, { signal });
491
+ if (!map.ok) {
492
+ return [indexFailedRow("sec-edgar", map, mapUrl, retrievedAt, "EDGAR's ticker→CIK map")];
493
+ }
494
+ const index = tickerIndex(map.value);
495
+ if (input.ticker !== undefined) {
496
+ const hit = index.get(input.ticker.toUpperCase());
497
+ if (hit === undefined) {
498
+ return [
499
+ {
500
+ registry: "sec-edgar",
501
+ outcome: "notFound",
502
+ sourceUrl: mapUrl,
503
+ retrievedAt,
504
+ reason: `EDGAR's ticker map has no "${input.ticker.toUpperCase()}" — the map covers companies that file with the SEC, so a foreign or private issuer is absent from it`,
505
+ },
506
+ ];
507
+ }
508
+ cik = hit.cik;
509
+ resolvedVia = `ticker ${input.ticker.toUpperCase()} → CIK ${hit.cik} via EDGAR's own company_tickers.json`;
510
+ }
511
+ else if (input.name !== undefined) {
512
+ // EDGAR has no name-search API that answers JSON, so the ticker map's
513
+ // titles are the honest substitute — and the shortlist is ranked by
514
+ // tool-text, not by a substring test that would match "Apple" to
515
+ // "Pineapple Holdings". It only covers listed filers, and the row says so.
516
+ const titles = [...index.entries()];
517
+ const [best] = await rankNames(input.name, titles.map(([, value]) => value.title), 0.8, 1);
518
+ if (best === undefined) {
519
+ return [
520
+ {
521
+ registry: "sec-edgar",
522
+ outcome: "notFound",
523
+ sourceUrl: mapUrl,
524
+ retrievedAt,
525
+ reason: `no company in EDGAR's ticker map has a name close to "${input.name}" — that map lists listed filers only, so this is not evidence the company does not exist`,
526
+ },
527
+ ];
528
+ }
529
+ const entry = titles[best.index];
530
+ cik = entry?.[1].cik ?? null;
531
+ resolvedVia = `name "${input.name}" → "${entry?.[1].title ?? ""}" (score ${round6(best.score)}) via EDGAR's company_tickers.json, which lists listed filers only`;
532
+ }
533
+ }
534
+ if (cik === null) {
535
+ return [
536
+ {
537
+ registry: "sec-edgar",
538
+ outcome: "unavailable",
539
+ sourceUrl: ORIGINS.edgarData,
540
+ retrievedAt,
541
+ reason: "EDGAR is searchable by CIK, ticker or name, and none of those was supplied",
542
+ retryable: false,
543
+ },
544
+ ];
545
+ }
546
+ const url = `${ORIGINS.edgarData}/submissions/CIK${cik}.json`;
547
+ const result = await getJson(url, { signal });
548
+ if (!result.ok) {
549
+ return [failedRow("sec-edgar", result, url, retrievedAt, `EDGAR has no filer with CIK ${cik}`)];
550
+ }
551
+ const record = normalizeEdgar(result.value);
552
+ if (record === null) {
553
+ return [
554
+ {
555
+ registry: "sec-edgar",
556
+ outcome: "unavailable",
557
+ sourceUrl: url,
558
+ retrievedAt,
559
+ reason: "EDGAR answered 200 with a body this tool could not read as a submissions document",
560
+ retryable: false,
561
+ },
562
+ ];
563
+ }
564
+ return [
565
+ {
566
+ registry: "sec-edgar",
567
+ outcome: "found",
568
+ sourceUrl: url,
569
+ retrievedAt,
570
+ record,
571
+ ...(resolvedVia === undefined ? {} : { reason: resolvedVia }),
572
+ },
573
+ ];
574
+ }
575
+ /**
576
+ * What the registers disagree about.
577
+ *
578
+ * Deliberately a comparison and not a merge. The name score is computed the
579
+ * same way `SanctionsScreen` computes one — through `tool-text` — and it is
580
+ * reported with its basis, not turned into "same company: yes".
581
+ */
582
+ async function compareRows(rows) {
583
+ const found = rows.filter((row) => row.outcome === "found" && row.record !== undefined);
584
+ if (found.length === 0)
585
+ return { legalNames: [], note: "no register returned a record" };
586
+ const legalNames = found.map((row) => ({
587
+ registry: row.registry,
588
+ legalName: row.record?.legalName ?? "",
589
+ otherNames: row.record?.otherNames ?? [],
590
+ status: row.record?.status ?? {},
591
+ }));
592
+ // One row per REGISTER, and the FIRST row each register returned: a name
593
+ // search can return five GLEIF hits, and comparing two of those against each
594
+ // other would report a cross-register agreement that was never computed.
595
+ // Building this with a Map keeps the LAST hit, which is the least relevant
596
+ // one — the registers return their best match first.
597
+ const perRegistry = [];
598
+ for (const row of found) {
599
+ if (perRegistry.some((kept) => kept.registry === row.registry))
600
+ continue;
601
+ perRegistry.push(row);
602
+ }
603
+ if (perRegistry.length === 1) {
604
+ return {
605
+ legalNames,
606
+ note: "only one register answered, so there is nothing to compare it against",
607
+ };
608
+ }
609
+ const first = perRegistry[0]?.record?.legalName ?? "";
610
+ const second = perRegistry[1]?.record?.legalName ?? "";
611
+ const a = await canonicalizeName(first, { dropLegalSuffixes: true });
612
+ const b = await canonicalizeName(second, { dropLegalSuffixes: true });
613
+ const [hit] = await rankNames(a.canonical, [b.canonical], 0, 1);
614
+ // A former name that matches THE OTHER register turns "these look like two
615
+ // companies" into "this one was renamed", which is the whole reason former
616
+ // names are carried through the normalizers.
617
+ //
618
+ // Which register it came from is load-bearing. Comparing every former name
619
+ // against BOTH current names let a register explain the disagreement by
620
+ // agreeing with itself: GLEIF carries "Siemens AG" as an other-name of
621
+ // "SIEMENS AKTIENGESELLSCHAFT", that pair scores 1.0, and the result then
622
+ // told the caller the gap to EDGAR's "SIEMENS ENERGY AG" was a rename — of
623
+ // a different company. Same shape as comparing two GLEIF hits and calling it
624
+ // cross-register, one level down.
625
+ const formerNames = [
626
+ // `compare` is the OTHER register's current name in each case.
627
+ ...(perRegistry[0]?.record?.otherNames ?? []).map((name) => ({ name, compare: b.canonical })),
628
+ ...(perRegistry[1]?.record?.otherNames ?? []).map((name) => ({ name, compare: a.canonical })),
629
+ ];
630
+ const formerHits = await Promise.all(formerNames.map(async ({ name, compare }) => {
631
+ const canonical = await canonicalizeName(name, { dropLegalSuffixes: true });
632
+ const [best] = await rankNames(canonical.canonical, [compare], 0.9, 1);
633
+ return best === undefined ? null : name;
634
+ }));
635
+ const explained = formerHits.filter((name) => name !== null);
636
+ return {
637
+ legalNames,
638
+ nameAgreement: {
639
+ score: round6(hit?.score ?? 0),
640
+ basis: `${perRegistry[0]?.registry} "${first}" vs ${perRegistry[1]?.registry} "${second}", compared after dropping legal forms (${[...a.droppedSuffixes, ...b.droppedSuffixes].join(", ") || "none"}) — @crewhaus/tool-text Jaro-Winkler`,
641
+ ...(explained.length === 0
642
+ ? {}
643
+ : {
644
+ explainedByFormerName: explained,
645
+ note: "a former name on one register matches the other register's current name, so a low score here is a rename rather than two companies",
646
+ }),
647
+ },
648
+ note: "the registers are not merged: nothing here decides which spelling or which status is correct",
649
+ };
650
+ }
651
+ // ---------------------------------------------------------------------------
652
+ // SanctionsScreen
653
+ // ---------------------------------------------------------------------------
654
+ const aliasSchema = z
655
+ .object({
656
+ name: z.string().min(1).max(512),
657
+ quality: z
658
+ .enum(["strong", "weak"])
659
+ .optional()
660
+ .describe("the publisher's own mark; weak aliases are scored and reported separately"),
661
+ })
662
+ .strict();
663
+ const entrySchema = z
664
+ .object({
665
+ id: z.string().min(1).max(128),
666
+ name: z.string().min(1).max(512),
667
+ kind: z.enum(["person", "entity", "vessel", "aircraft", "unknown"]).optional(),
668
+ aliases: z.array(aliasSchema).max(512).optional(),
669
+ countries: z.array(z.string().max(128)).max(64).optional(),
670
+ datesOfBirth: z.array(z.string().max(64)).max(64).optional(),
671
+ programs: z.array(z.string().max(128)).max(64).optional(),
672
+ remarks: z.string().max(8192).optional(),
673
+ })
674
+ .strict();
675
+ /**
676
+ * A list snapshot, with its provenance REQUIRED.
677
+ *
678
+ * `version`, `publishedAt` and `retrievedAt` are not optional and never will
679
+ * be. A screening result whose list cannot say what it was is not a cheaper
680
+ * result, it is one nobody can defend a year later — and "no candidates
681
+ * found" is precisely the answer that gets relied on.
682
+ */
683
+ const snapshotSchema = z
684
+ .object({
685
+ source: z.string().min(1).max(200).describe("publisher and list, e.g. 'OFAC SDN'"),
686
+ version: z.string().min(1).max(200).describe("the publisher's own version or issue id"),
687
+ publishedAt: z.string().min(1).max(64).describe("ISO-8601 with an offset"),
688
+ retrievedAt: z.string().min(1).max(64).describe("ISO-8601 with an offset"),
689
+ sourceUrl: z.string().max(2048).optional(),
690
+ entries: z.array(entrySchema).min(1).max(LIMITS.entriesPerList),
691
+ })
692
+ .strict();
693
+ export const sanctionsScreen = buildTool({
694
+ name: "SanctionsScreen",
695
+ description: "Screen names against sanctions-list snapshots the operator holds, and return candidates with the basis for each and the version of every list read. Use it before onboarding or paying a counterparty. It returns SIGNALS AND EVIDENCE, NEVER A VERDICT: a sanctions match is a legal determination a person makes, and the score is the least reliable part of the answer — the lists carry transliterations and aliases their own publishers mark as weak. Scoring is local, so no counterparty name leaves the machine, and a list that cannot say which version it is gets refused rather than screened against.",
696
+ inputSchema: z
697
+ .object({
698
+ subjects: z
699
+ .array(z
700
+ .object({
701
+ id: z.string().min(1).max(128),
702
+ name: z.string().min(1).max(512),
703
+ aliases: z.array(z.string().min(1).max(512)).max(64).optional(),
704
+ kind: z.enum(["person", "entity"]).optional(),
705
+ country: z.string().max(128).optional().describe("corroboration only; never scored"),
706
+ dateOfBirth: z
707
+ .string()
708
+ .max(64)
709
+ .optional()
710
+ .describe("corroboration only; never scored"),
711
+ })
712
+ .strict())
713
+ .min(1)
714
+ .max(LIMITS.subjects),
715
+ lists: z.array(snapshotSchema).max(LIMITS.lists).optional().describe("snapshots inline"),
716
+ listFiles: z
717
+ .array(z.string().min(1).max(1024))
718
+ .max(LIMITS.lists)
719
+ .optional()
720
+ .describe("workspace-relative paths to snapshots in the same JSON shape"),
721
+ threshold: z
722
+ .number()
723
+ .min(0)
724
+ .max(1)
725
+ .optional()
726
+ .describe("report candidates at or above this score; default 0.65"),
727
+ limit: z
728
+ .number()
729
+ .int()
730
+ .positive()
731
+ .max(LIMITS.candidates)
732
+ .optional()
733
+ .describe("candidates per subject; default 10"),
734
+ includeWeakAliases: z
735
+ .boolean()
736
+ .optional()
737
+ .describe("score the publisher's weak aliases too, reported apart; default true"),
738
+ maxAgeDays: z
739
+ .number()
740
+ .int()
741
+ .min(0)
742
+ .max(3650)
743
+ .optional()
744
+ .describe("refuse a list published longer ago than this; default 30, 0 disables the check"),
745
+ now: nowField,
746
+ })
747
+ .strict(),
748
+ readOnly: true,
749
+ concurrencySafe: true,
750
+ // No network and no ioCapability: this reads a local snapshot and compares
751
+ // strings. Screening a counterparty through a remote API would disclose who
752
+ // you are about to pay to somebody who did not need to know, so there is no
753
+ // endpoint here to disclose it to.
754
+ execute: async (input) => {
755
+ const nowMs = nowMsFrom(input.now);
756
+ const snapshots = [...(input.lists ?? [])];
757
+ for (const file of input.listFiles ?? []) {
758
+ const at = resolveSafe("SanctionsScreen", file);
759
+ let size;
760
+ try {
761
+ size = statSync(at.real).size;
762
+ }
763
+ catch {
764
+ // A refusal in the package's own words, with the path as the caller
765
+ // wrote it. The raw ENOENT carries an absolute path from this machine,
766
+ // which is both unreadable and more than the caller asked for.
767
+ return `SanctionsScreen refused ${at.rel}: there is no such file in the workspace`;
768
+ }
769
+ if (size > LIMITS.snapshotBytes) {
770
+ return `SanctionsScreen refused ${at.rel}: it is ${size} bytes, over the ${LIMITS.snapshotBytes}-byte limit`;
771
+ }
772
+ let document;
773
+ try {
774
+ document = JSON.parse(readFileSync(at.real, "utf-8"));
775
+ }
776
+ catch (err) {
777
+ return `SanctionsScreen refused ${at.rel}: it is not JSON (${err.message})`;
778
+ }
779
+ const parsed = snapshotSchema.safeParse(document);
780
+ if (!parsed.success) {
781
+ // The same schema the inline lists go through. A file missing its
782
+ // version fails here, by name, rather than being screened against.
783
+ return `SanctionsScreen refused ${at.rel}: ${parsed.error.issues
784
+ .slice(0, 4)
785
+ .map((issue) => `${issue.path.join(".") || "(root)"} ${issue.message}`)
786
+ .join("; ")}`;
787
+ }
788
+ snapshots.push(parsed.data);
789
+ }
790
+ if (snapshots.length === 0) {
791
+ return "SanctionsScreen needs at least one list: pass lists inline or listFiles. Screening against nothing would report no candidates for every subject, which reads exactly like a clean screen.";
792
+ }
793
+ if (snapshots.length > LIMITS.lists) {
794
+ return `SanctionsScreen takes at most ${LIMITS.lists} lists in one call; ${snapshots.length} were supplied`;
795
+ }
796
+ const maxAgeDays = input.maxAgeDays ?? 30;
797
+ const ages = [];
798
+ for (const snapshot of snapshots) {
799
+ const checked = checkSnapshot(snapshot, nowMs, maxAgeDays);
800
+ if ("reason" in checked) {
801
+ // One unusable list refuses the WHOLE screen. Screening against the
802
+ // other three and reporting "no candidates" would be an answer with a
803
+ // hole in it that nothing in the output would show.
804
+ return `SanctionsScreen refused the whole screen because of ${checked.list}: ${checked.reason}`;
805
+ }
806
+ ages.push(checked.ageDays);
807
+ }
808
+ const policy = {
809
+ threshold: input.threshold ?? 0.65,
810
+ limit: input.limit ?? 10,
811
+ includeWeakAliases: input.includeWeakAliases ?? true,
812
+ };
813
+ return json(await screenSubjects(input.subjects, snapshots, ages, policy, nowMs));
814
+ },
815
+ });
816
+ /** Every tool this package registers, in the order a catalog should list them. */
817
+ export const KYC_TOOLS = Object.freeze([
818
+ entityRegistryLookup,
819
+ sanctionsScreen,
820
+ vatIdValidate,
821
+ ]);