domain-hound 0.1.3 → 0.1.5

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/server.mjs CHANGED
@@ -1,11 +1,14 @@
1
- import { geoInstruction, googleSearchInstruction, namingRecipe, showAsIs } from './clis/domain-check/naming-method.mjs';
2
- import { asciiDomain, defaultEndings, normalizeName, restrictedEndings, validEligibility } from './clis/domain-check/name-search.mjs';
1
+ import { geoInstruction, namingRecipe } from './clis/domain-check/naming-method.mjs';
2
+ import { asciiDomain, defaultEndings, domainEnding, normalizeName, requestEndings, restrictedEndings, supportedEndings, validEligibility } from './clis/domain-check/name-search.mjs';
3
3
  import { spawn } from 'node:child_process';
4
4
  import { readFileSync } from 'node:fs';
5
5
  import { createInterface } from 'node:readline';
6
6
  import { fileURLToPath, pathToFileURL } from 'node:url';
7
+ import { checkSocialHandles, handlePriorities, pendingHandleRows, requestPlatforms } from './clis/domain-check/handles.mjs';
7
8
  import { progressPrefix } from './clis/domain-check/progress.mjs';
8
- import { attributed, checkText, errorText, progressText, triageText } from './display.mjs';
9
+ import { attributed, errorText, progressText } from './display.mjs';
10
+ import { resultPages } from './results.mjs';
11
+ import { watchDomain, watchTool } from './watch.mjs';
9
12
 
10
13
  // The capability ships inside the package; tests inject another directory through serve({ cwd }).
11
14
  export const capabilityDir = fileURLToPath(new URL('./clis/domain-check/', import.meta.url));
@@ -16,7 +19,7 @@ const serverVersion = JSON.parse(readFileSync(new URL('./package.json', import.m
16
19
  const timeoutMs = 14_000;
17
20
  // A lookup still running after this long is stopped.
18
21
  const maxLookupMs = 120_000;
19
- // A finished lookup whose caller already had a progress answer waits this long for the repeated call.
22
+ // Keep completed evidence stable for repeated calls during a short naming session.
20
23
  const keepFinishedMs = 120_000;
21
24
  const versions = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
22
25
 
@@ -24,24 +27,39 @@ const versions = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
24
27
  // spaces, punctuation and symbols without needing a Unicode-aware regular expression in the client.
25
28
  const letter = 'A-Za-z0-9\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u1FFF\\u3040-\\uD7FF\\uF900-\\uFDCF';
26
29
  const entryPattern = new RegExp('^[' + letter + '](?:[' + letter + '-]{0,61}[' + letter + '])?'
27
- + '(?:\\.(?:[A-Za-z]{2,63}|[xX][nN]--[A-Za-z0-9](?:[A-Za-z0-9-]{0,57}[A-Za-z0-9])?))?$');
30
+ + '(?:\\.(?:[cC][oO]\\.[uU][kK]|[A-Za-z]{2,63}|[xX][nN]--[A-Za-z0-9](?:[A-Za-z0-9-]{0,57}[A-Za-z0-9])?))?$');
28
31
  const nameSchema = { type: 'string', minLength: 1, maxLength: 127, pattern: entryPattern.source };
29
32
  const endingsSchema = {
30
- type: 'array', minItems: 1, maxItems: 10, uniqueItems: true,
31
- items: { type: 'string', enum: defaultEndings },
32
- description: 'Optional preferences in display order. Bare names always check and show all ten default endings, including .ai. Omit when no preference was given.',
33
+ type: 'array', minItems: 1, maxItems: supportedEndings.length, uniqueItems: true,
34
+ items: { type: 'string', enum: supportedEndings },
35
+ description: 'Endings to consider for the recommendation, in preference order. For .com only use ["com"]. The page still shows all fourteen default endings for bare names. '
36
+ + 'On request only (add them here when the person asks or names a country): ' + requestEndings.map(ending => '.' + ending).join(', ') + '.',
33
37
  };
38
+ const countryEnding = {
39
+ SH: 'sh', GG: 'gg', SE: 'se', DK: 'dk', DE: 'de', GB: 'co.uk', UK: 'co.uk', EU: 'eu',
40
+ };
41
+ const europeanCountries = new Set('AT BE BG HR CY CZ EE FI FR GR HU IE IT LV LT LU MT NL PL PT RO SK SI ES IS LI NO'.split(' '));
42
+ function regionalEnding(country) {
43
+ const code = country?.toUpperCase();
44
+ return Object.hasOwn(countryEnding, code) ? countryEnding[code] : europeanCountries.has(code) ? 'eu' : null;
45
+ }
46
+ const selectedEndings = args => [...new Set([...(args.endings ?? []), regionalEnding(args.country), ...defaultEndings].filter(Boolean))];
34
47
  const lookupProperties = {
48
+ country: { type: 'string', pattern: '^[A-Za-z]{2}$', description: 'Buyer country code if supplied, such as SE, DK, DE or GB for .co.uk. Do not infer it from language alone.' },
35
49
  ai: { type: 'boolean', description: 'Legacy option. .ai is now included by default.' },
36
50
  endings: endingsSchema,
51
+ budget: { type: 'number', minimum: 0, maximum: 1000000,
52
+ description: 'Maximum upfront price in USD when the person gave a cap. Carry it from the registry screen into triage.' },
37
53
  eligible: { type: 'array', uniqueItems: true, items: { type: 'string', enum: restrictedEndings },
38
- description: 'Restricted endings the buyer qualifies to register. Pass ["no"] only when the buyer qualifies for .no.' },
54
+ description: 'Restricted endings the buyer qualifies to register. Pass no or eu only when the buyer qualifies for that ending.' },
39
55
  };
56
+ const relay = 'Relay `say` as written. You may add advice, but no domain, price or verdict that is not in it. Keep advice consistent with the tool verdict. The complete local results page has all checked endings.';
40
57
  const checkTool = {
41
58
  name: 'check_domains',
42
- description: showAsIs + ' '
59
+ description: relay + ' '
43
60
  + 'For any request to buy or register, pass purchase: true and explicitly say “Domain Hound cannot buy or complete checkout,” even when the domain is taken. '
44
- + 'Input: query for one name or exact domain ({"query":"lanternbay.me"}), or names for 1 to 20 names in one call ({"names":["lanternbay","lanternbay.me"]}). A bare name checks ten endings, including .ai. '
61
+ + 'Use to check domain availability and prices, whether a domain is taken, or to find a domain for a startup name. '
62
+ + 'Input: query for one name or exact domain ({"query":"lanternbay.me"}), or names for 1 to 20 names in one call ({"names":["lanternbay","lanternbay.me"]}). A bare name checks fourteen endings, including .ai, .net and .org. '
45
63
  + 'For a bare name, put any ending preference in endings. Use exact lookup for a full domain. '
46
64
  + 'For a batch, make one call and report check-at-shop endings as returned. Recheck only when the person asks. '
47
65
  + 'Set confirm true only when the person asks for a live shop check (slower). '
@@ -65,14 +83,15 @@ const checkTool = {
65
83
  };
66
84
 
67
85
  const legacyTool = { ...checkTool, name: 'broker_find',
68
- description: showAsIs + ' Legacy alias for Domain Hound check_domains, same input. Never buys.' };
86
+ description: relay + ' Legacy alias for Domain Hound check_domains, same input. Never buys.' };
69
87
 
70
88
  const triageTool = {
71
89
  name: 'triage_names',
72
- description: showAsIs + ' '
73
- + 'Use to screen 1 to 20 product names, or once with a bare name when asked whether an existing name is safe: {"names":["Quiet Otter","Hush Room"],"about":"book quiet meeting rooms"}. Checks same-name rivals and their traction, live US marks, iOS and Android apps, handles and every domain ending, including .ai. '
90
+ description: relay + ' '
91
+ + 'Use to screen 1 to 20 product names, or once with a bare name when asked whether an existing name is safe or whether an app name or handle is taken: {"names":["Quiet Otter","Hush Room"],"about":"book quiet meeting rooms"}. Checks every domain ending, including .ai, for all names; same-name rivals and their traction, live US marks, iOS and Android apps, and public company results for the first five names. Social handles for the top three run after the result and can be collected with the same call. Put the strongest names first. '
74
92
  + 'Verdicts weigh each same-name rival by its traction: a strong rival (David vs Goliath) or a same-business rival with traction means Avoid; small or dormant same-name uses are notes that never lower the verdict. '
75
- + 'Fill geo for every name from your own memory before calling. ' + googleSearchInstruction + ' Let the person choose.',
93
+ + 'Put the name the person came with first. Fill geo for each name from memory, never from search. '
94
+ + 'The tool checks Google itself. If you check a gap using built-in search, use it for context and keep the evidence-backed results unchanged. Let the person choose.',
76
95
  inputSchema: {
77
96
  type: 'object',
78
97
  properties: {
@@ -80,6 +99,10 @@ const triageTool = {
80
99
  names: { type: 'array', minItems: 1, maxItems: 20, items: { type: 'string', minLength: 1, maxLength: 100 },
81
100
  description: '1 to 20 bare names without endings, e.g. ["Quiet Otter","Hush Room"].' },
82
101
  purchase: { type: 'boolean', description: 'True when the person asks to buy or register a domain.' },
102
+ companyType: { type: 'string', enum: Object.keys(handlePriorities),
103
+ description: 'Use developer, consumer, b2b or media when it fits, to highlight the handles that matter.' },
104
+ additionalHandles: { type: 'array', uniqueItems: true, items: { type: 'string', enum: requestPlatforms.map(platform => platform.id) },
105
+ description: 'Extra check links only when requested. Snapchat, Reddit, Twitch, Threads, Pinterest or Discord.' },
83
106
  category: { type: 'string', minLength: 1, maxLength: 100, description: 'Category for relevant trademark classes and competitors. Use travel, software, finance, retail, health, education, food or media.' },
84
107
  about: { type: 'string', minLength: 1, maxLength: 160, description: 'A short description of what your product does, to identify overlapping sites and apps.' },
85
108
  geo: { type: 'object', maxProperties: 20,
@@ -93,7 +116,7 @@ const triageTool = {
93
116
 
94
117
  const namingTool = {
95
118
  name: 'naming_method',
96
- description: 'Get the Domain Hound naming recipe for new names. For an existing name, use triage_names. The recipe and preliminary check are intermediate. For the final triage result, copy the tool display as written.',
119
+ description: 'Use to find a startup or product name: get the Domain Hound naming recipe for new names. For an existing name, use triage_names. The recipe and preliminary check are intermediate. For the final triage result, relay say as written.',
97
120
  inputSchema: { type: 'object', properties: {
98
121
  about: { type: 'string', minLength: 1, maxLength: 512, description: 'An optional one-sentence product description.' },
99
122
  }, additionalProperties: false },
@@ -117,6 +140,7 @@ function queryValue(value) {
117
140
  throw new Error('query is empty. Enter one name or exact domain in query, such as lanternbay or lanternbay.me.');
118
141
  }
119
142
  const query = value.toLowerCase();
143
+ if (query.split('.')[0].length > 63) throw new Error('This name is too long. A DNS label can have up to 63 characters.');
120
144
  if (!entryPattern.test(query) || !dnsForm(query)) {
121
145
  throw new Error('query ' + showValue(value) + ' is not valid. Give a name like lanternbay or a domain like lanternbay.me in query.');
122
146
  }
@@ -133,6 +157,7 @@ function batchNames(names) {
133
157
  throw new Error('names[' + index + '] is empty. Use a bare name such as lanternbay or an exact domain such as lanternbay.me.');
134
158
  }
135
159
  const name = value.toLowerCase();
160
+ if (name.split('.')[0].length > 63) throw new Error('names[' + index + '] is too long. A DNS label can have up to 63 characters.');
136
161
  if (!entryPattern.test(name) || !dnsForm(name)) {
137
162
  throw new Error('names[' + index + '] ' + showValue(value) + ' is not valid. Give a name like lanternbay or a domain like lanternbay.me in names.');
138
163
  }
@@ -142,6 +167,9 @@ function batchNames(names) {
142
167
 
143
168
  function lookupFlags(args) {
144
169
  const flags = [];
170
+ if (Object.hasOwn(args, 'budget') && (!Number.isFinite(args.budget) || args.budget < 0 || args.budget > 1_000_000)) {
171
+ throw new Error('The upfront budget must be a dollar amount between 0 and 1,000,000.');
172
+ }
145
173
  if (Object.hasOwn(args, 'eligible')) {
146
174
  if (!validEligibility(args.eligible)) throw new Error('Eligible endings must list supported restricted endings, such as no.');
147
175
  if (args.eligible.length) flags.push('--eligible', args.eligible.join(','));
@@ -153,13 +181,18 @@ function lookupFlags(args) {
153
181
  }
154
182
  // The headless browser runs only on this explicit request.
155
183
  if (args.confirm === true) flags.push('--confirm');
184
+ if (Object.hasOwn(args, 'country') && (typeof args.country !== 'string' || !/^[A-Za-z]{2}$/.test(args.country))) {
185
+ throw new Error('Use a two-letter country code.');
186
+ }
156
187
  if (Object.hasOwn(args, 'endings')) {
157
188
  const endings = args.endings;
158
- if (!Array.isArray(endings) || endings.length < 1 || endings.length > 10 ||
189
+ if (!Array.isArray(endings) || endings.length < 1 || endings.length > supportedEndings.length ||
159
190
  new Set(endings).size !== endings.length || endings.some(ending => !endingsSchema.items.enum.includes(ending))) {
160
191
  throw new Error('Choose supported domain endings.');
161
192
  }
162
193
  }
194
+ const extra = selectedEndings(args).filter(ending => !defaultEndings.includes(ending));
195
+ if (extra.length) flags.push('--endings', [...defaultEndings, ...extra].join(','));
163
196
  return flags;
164
197
  }
165
198
 
@@ -177,20 +210,20 @@ function cliArguments(args) {
177
210
  if (args.shortlist && (hasQuery || names.some(name => name.includes('.')))) {
178
211
  throw new Error('Use shortlist only with bare names in names.');
179
212
  }
180
- if (hasQuery) return ['--agent', queryValue(args.query), ...flags];
181
- return ['--agent', '--names', names.join(','), ...flags];
213
+ if (hasQuery) return ['--agent', queryValue(args.query), '--receipt', ...flags];
214
+ return ['--agent', '--names', names.join(','), '--receipt', ...flags];
182
215
  }
183
216
 
184
217
  // The rows a progress answer lists, in input order: a bare name with every requested ending, an exact domain as itself.
185
218
  function checkRows(args) {
186
219
  const names = (Object.hasOwn(args, 'query') ? [queryValue(args.query)] : batchNames(args.names)).map(dnsForm);
187
- const endings = [...new Set([...(args.endings ?? []), ...defaultEndings])];
220
+ const endings = selectedEndings(args);
188
221
  return [...new Set(names)].map(name => name.includes('.')
189
222
  ? { name, domains: [name] } : { name, domains: endings.map(ending => name + '.' + ending) });
190
223
  }
191
224
 
192
225
  function triageRows(args) {
193
- const endings = [...new Set([...(args.endings ?? []), ...defaultEndings])];
226
+ const endings = selectedEndings(args);
194
227
  const seen = new Set();
195
228
  return args.names.flatMap(name => {
196
229
  const label = normalizeName(name);
@@ -224,6 +257,13 @@ function triageArguments(args) {
224
257
  throw new Error('names[' + bad + '] is not valid. Supply 1 to 20 bare names of up to 100 characters, without commas or domain endings.');
225
258
  }
226
259
  const flags = lookupFlags(args);
260
+ const { companyType, additionalHandles } = args;
261
+ if (companyType !== undefined && !Object.hasOwn(handlePriorities, companyType)) throw new Error('Choose a supported company type.');
262
+ if (additionalHandles !== undefined && (!Array.isArray(additionalHandles) ||
263
+ new Set(additionalHandles).size !== additionalHandles.length ||
264
+ additionalHandles.some(id => !requestPlatforms.some(platform => platform.id === id)))) {
265
+ throw new Error('Choose supported extra handle platforms.');
266
+ }
227
267
  if (Object.hasOwn(args, 'category')) {
228
268
  if (typeof args.category !== 'string' || !args.category.trim() || args.category.length > 100) {
229
269
  throw new Error('Use up to 100 characters for the product category.');
@@ -237,7 +277,7 @@ function triageArguments(args) {
237
277
  flags.push('--about', args.about);
238
278
  }
239
279
  if (Object.hasOwn(args, 'geo')) flags.push('--geo', JSON.stringify(geoValue(args.geo, args.names)));
240
- return ['--triage', args.names.join(','), '--compact', ...flags];
280
+ return ['--triage', args.names.join(','), '--compact', '--receipt', ...flags];
241
281
  }
242
282
 
243
283
  // The capability prints one JSON object on stdout.
@@ -278,7 +318,7 @@ function startLookup(args, cwd, maxMs) {
278
318
  const lookup = { started: performance.now(), progress: { answers: new Map(), stage: null }, finished: false,
279
319
  collect: false, outcome: null };
280
320
  const child = spawn(process.execPath, ['index.mjs', ...args], {
281
- cwd, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, DOMAIN_HOUND_PROGRESS: '1' },
321
+ cwd, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, DOMAIN_HOUND_PROGRESS: '1', DOMAIN_HOUND_DEFER_HANDLES: args[0] === '--triage' ? '1' : '' },
282
322
  });
283
323
  lookup.child = child;
284
324
  const chunks = [];
@@ -324,13 +364,27 @@ async function within(lookup, budget) {
324
364
  return finished;
325
365
  }
326
366
 
367
+ function pendingTriage(progress, rows) {
368
+ return {
369
+ pending: true,
370
+ checkedAt: new Date().toISOString(),
371
+ names: rows.map(({ name, domains }) => {
372
+ const endings = state => domains.filter(domain => progress.answers.get(domain) === state).map(domainEnding);
373
+ return { name, taken: endings('taken'), premium: endings('premium'), reserved: endings('reserved'),
374
+ free: endings('probably-free').map(d => ({ d })), shop_check: endings('check-at-shop') };
375
+ }),
376
+ };
377
+ }
378
+
327
379
  export async function serve({
328
380
  input = process.stdin, output = process.stdout, cwd = capabilityDir, timeout = timeoutMs, maxLookup = maxLookupMs,
381
+ pages = resultPages(), watch = watchDomain, socialLookup = checkSocialHandles,
329
382
  } = {}) {
330
383
  const send = response => output.write(JSON.stringify({ jsonrpc: '2.0', ...response }) + '\n');
331
384
  const error = (id, code, message) => send({ id, error: { code, message } });
332
385
  const pending = new Set();
333
386
  const lookups = new Map();
387
+ const background = new Set();
334
388
 
335
389
  // Join the running or finished lookup for the same input, or start one. Answer within the budget with the
336
390
  // result, or with the progress so far while the lookup keeps running for a repeated call to collect.
@@ -351,8 +405,7 @@ export async function serve({
351
405
  lookups.set(key, lookup);
352
406
  lookup.done.then(() => {
353
407
  if (lookups.get(key) !== lookup) return;
354
- // A result nobody was told to collect is delivered by the calls already waiting on it.
355
- if (!lookup.collect) {
408
+ if (lookup.outcome.error && !lookup.collect) {
356
409
  lookups.delete(key);
357
410
  return;
358
411
  }
@@ -362,22 +415,22 @@ export async function serve({
362
415
  if (!await within(lookup, timeout - (performance.now() - started))) {
363
416
  lookup.collect = true;
364
417
  try {
365
- return toolResult(renderProgress(lookup.progress, {
418
+ return toolResult(await renderProgress(lookup.progress, {
366
419
  rows, elapsedMs: performance.now() - lookup.started, budgetMs: timeout }));
367
420
  } catch {
368
421
  return errorResult('Domain Hound could not format the progress.');
369
422
  }
370
423
  }
371
- // The repeated call collected the finished result; the next call starts a fresh lookup.
372
- if (lookups.get(key) === lookup) lookups.delete(key);
373
- if (lookup.outcome.error) return errorResult(lookup.outcome.error);
424
+ if (lookup.outcome.error) {
425
+ if (lookups.get(key) === lookup) lookups.delete(key);
426
+ return errorResult(lookup.outcome.error);
427
+ }
374
428
  try {
375
- return toolResult(render(lookup.outcome.data));
429
+ return toolResult(JSON.stringify(await render(lookup.outcome.data, lookup)));
376
430
  } catch {
377
431
  return errorResult('Domain Hound could not format the result.');
378
432
  }
379
433
  }
380
- let shortlist;
381
434
  let initialized = false;
382
435
  let negotiated = false;
383
436
 
@@ -412,7 +465,7 @@ export async function serve({
412
465
  }
413
466
  if (method !== 'tools/list' && method !== 'tools/call') return error(id, -32601, 'Method not found');
414
467
  if (!initialized) return error(id, -32000, 'Domain Hound has not been initialized');
415
- if (method === 'tools/list') return reply({ tools: [checkTool, triageTool, namingTool, legacyTool] });
468
+ if (method === 'tools/list') return reply({ tools: [checkTool, triageTool, namingTool, legacyTool, watchTool] });
416
469
  const { name, arguments: args } = params ?? {};
417
470
  if (name === namingTool.name) {
418
471
  if (args !== undefined && (!isObject(args) || Object.keys(args).some(key => key !== 'about') ||
@@ -420,22 +473,77 @@ export async function serve({
420
473
  args.about.length > namingTool.inputSchema.properties.about.maxLength)))) {
421
474
  return reply(errorResult('naming_method accepts an optional about description of up to 512 characters.'));
422
475
  }
423
- shortlist = undefined;
424
476
  return reply(toolResult(JSON.stringify({ display: attributed(namingRecipe(args?.about?.slice(0, 160))) })));
425
477
  }
478
+ if (name === watchTool.name) {
479
+ let result;
480
+ try {
481
+ result = await watch(args);
482
+ } catch (problem) {
483
+ return reply(errorResult(problem.message));
484
+ }
485
+ // Preserve a successful submission response even if disk space or local permissions prevent a receipt.
486
+ const data = await pages(result, {}, { watch: true }).catch(() => ({ ...result, display: result.say }));
487
+ return reply(toolResult(JSON.stringify(data)));
488
+ }
426
489
  const purchase = isObject(args) && args.purchase === true;
427
490
  if (name === triageTool.name) {
428
- const prior = shortlist && Date.now() - shortlist.at < 120_000 ? shortlist.data : undefined;
429
- return reply(await runLookup(args, triageArguments, triageRows, data => triageText(data, prior, { purchase, preferred: args.endings }),
430
- (progress, timing) => progressText(progress, { ...timing, triage: true, purchase })));
491
+ let collect;
492
+ const result = await runLookup(args, triageArguments, triageRows, (data, lookup) => {
493
+ const { handleTargets, ...evidence } = data;
494
+ if (!handleTargets?.length) return pages(evidence, args, { triage: true });
495
+ const extraPlatforms = args.additionalHandles ?? [];
496
+ const key = JSON.stringify(extraPlatforms.slice().sort());
497
+ lookup.handleChecks ??= new Map();
498
+ let check = lookup.handleChecks.get(key);
499
+ if (!check) {
500
+ check = { rows: null, started: false };
501
+ lookup.handleChecks.set(key, check);
502
+ }
503
+ const targets = new Map(handleTargets.map(({ name, index }) => [index, name]));
504
+ const entries = evidence.names.flatMap((row, index) => {
505
+ const target = targets.get(index);
506
+ if (!target) return [];
507
+ const rows = check.rows?.get(target) ?? pendingHandleRows(target, extraPlatforms);
508
+ return [[row.name, rows]];
509
+ });
510
+ const handleRows = new Map(entries);
511
+ evidence.receiptDetails = evidence.receiptDetails.map((detail, index) => ({
512
+ ...detail, handles: handleRows.get(evidence.names[index].name),
513
+ }));
514
+ evidence.handles = Object.fromEntries(entries.map(([name, rows]) => [name, {
515
+ taken: rows.filter(row => row.state === 'taken').map(row => row.platform),
516
+ not_found: rows.filter(row => row.state === 'not-found').map(row => row.platform),
517
+ check: rows.filter(row => row.state === 'check').map(row => row.platform),
518
+ }]));
519
+ if (!check.rows) evidence.handlesPending = true;
520
+ collect = () => {
521
+ if (check.started) return;
522
+ check.started = true;
523
+ const rows = [...new Set(targets.values())].map(name => ({ name, variants: true }));
524
+ const task = socialLookup(rows, { extraPlatforms, freshRun: true })
525
+ .then(answers => { check.rows = answers; }, () => {
526
+ check.rows = new Map(rows.map(({ name }) => [name,
527
+ pendingHandleRows(name, extraPlatforms).map(row => ({ ...row, why: 'no clear answer in time' }))]));
528
+ }).finally(() => background.delete(task));
529
+ background.add(task);
530
+ };
531
+ return pages(evidence, args, { triage: true });
532
+ }, async (progress, timing) => {
533
+ const summary = progressText(progress, { ...timing, triage: true, purchase });
534
+ if (!progress.answers.size) return summary;
535
+ const { resultPage } = await pages(pendingTriage(progress, timing.rows), args, { triage: true });
536
+ return JSON.stringify({ ...JSON.parse(summary), resultPage });
537
+ });
538
+ reply(result);
539
+ if (!result.isError) collect?.();
540
+ return;
431
541
  }
432
542
  if (name !== checkTool.name && name !== legacyTool.name) return error(id, -32602, 'Unknown tool');
433
543
  // An exact lookup includes the purchase line while its registration status is unsettled.
434
544
  const exact = isObject(args) && typeof args.query === 'string' && args.query.includes('.');
435
- return reply(await runLookup(args, cliArguments, checkRows, data => {
436
- if (args.shortlist) shortlist = { at: Date.now(), data };
437
- return checkText(data, args.shortlist, { purchase, preferred: args.endings });
438
- }, (progress, timing) => progressText(progress, { ...timing, purchase: purchase || exact })));
545
+ return reply(await runLookup(args, cliArguments, checkRows, data => pages(data, args),
546
+ (progress, timing) => progressText(progress, { ...timing, purchase: purchase || exact })));
439
547
  }
440
548
 
441
549
  const lines = createInterface({ input, terminal: false, crlfDelay: Infinity });
@@ -444,6 +552,7 @@ export async function serve({
444
552
  pending.add(response);
445
553
  }
446
554
  await Promise.all(pending);
555
+ await Promise.all(background);
447
556
  // The client has gone, so nobody can collect a lookup that is still running.
448
557
  for (const lookup of lookups.values()) if (!lookup.finished) lookup.child.kill('SIGKILL');
449
558
  await Promise.all([...lookups.values()].map(lookup => lookup.done));
package/watch.mjs ADDED
@@ -0,0 +1,93 @@
1
+ import { checkDomainSite } from './clis/domain-check/com-site.mjs';
2
+ import { asciiDomain, defaultEndings } from './clis/domain-check/name-search.mjs';
3
+ import { lookupRegistrations } from './clis/domain-check/registry.mjs';
4
+
5
+ export const newsQuestion = 'Domain Hound can also email you news about itself and other developer tools from its maker, BrightBoard AS, at most twice a month. It is optional and your watch works either way. Do you want that?';
6
+ const endpoint = 'https://domainhound-alerts.domainhound.workers.dev/watch';
7
+ const consentTextVersion = 'news-v1';
8
+
9
+ export const watchTool = {
10
+ name: 'watch_domain',
11
+ description: 'Check a specific domain’s registry, expiry and website and start a free release watch at the person’s request. '
12
+ + 'Use the email and optional name they gave for this submission. If the email is missing, ask once and never guess. '
13
+ + 'Before submitting, ask exactly: “' + newsQuestion + '” Pass news: true only on an explicit yes, or false if they decline or skip it. '
14
+ + 'This highlights a choice in the confirmation email. Only the email confirmation can start news. Relay say as written.',
15
+ annotations: { title: 'Watch a domain', readOnlyHint: false, destructiveHint: false, openWorldHint: true },
16
+ inputSchema: {
17
+ type: 'object',
18
+ properties: {
19
+ domain: { type: 'string', maxLength: 127, description: 'The exact domain, like example.com.' },
20
+ email: { type: 'string', maxLength: 254, description: 'The email address the person provided. Omit to preview.' },
21
+ name: { type: 'string', maxLength: 80, description: 'Optional name provided by the person.' },
22
+ news: { type: 'boolean', description: 'True only after an explicit yes to the optional news question.' },
23
+ },
24
+ required: ['domain'],
25
+ additionalProperties: false,
26
+ },
27
+ };
28
+
29
+ export async function watchDomain(input, { fetcher = globalThis.fetch, registry = lookupRegistrations,
30
+ siteCheck = checkDomainSite, now = new Date() } = {}) {
31
+ if (!input || typeof input !== 'object' || Array.isArray(input)
32
+ || Object.keys(input).some(key => !Object.hasOwn(watchTool.inputSchema.properties, key))) {
33
+ throw Error('Enter the exact domain you want to watch.');
34
+ }
35
+ const domain = typeof input.domain === 'string' && input.domain.length <= 127 && asciiDomain(input.domain.trim());
36
+ const ending = domain && domain.split('.').at(-1);
37
+ if (!domain || !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.[a-z]+$/.test(domain) || !defaultEndings.includes(ending)) {
38
+ throw Error('Enter a supported domain to watch, such as example.com.');
39
+ }
40
+ if (input.news !== undefined && typeof input.news !== 'boolean') throw Error('Optional news must be true or false.');
41
+ if (input.name !== undefined && (typeof input.name !== 'string' || input.name.length > 80 || /[\p{Cc}\p{Cf}]/u.test(input.name))) {
42
+ throw Error('Use up to 80 characters for the optional name.');
43
+ }
44
+ const email = typeof input.email === 'string' ? input.email.trim().toLowerCase() : null;
45
+ if (Object.hasOwn(input, 'email') && (!email || email.length > 254 ||
46
+ !/^[^\s@<>()[\]",;:\\]{1,64}@(?:[a-z0-9-]+\.)+[a-z]{2,63}$/.test(email))) {
47
+ throw Error('Enter the email address for the watch.');
48
+ }
49
+ const watchUrl = 'https://domainhound.dev/watch/?domain=' + encodeURIComponent(domain);
50
+ const started = performance.now();
51
+ const [[registration], site] = await Promise.all([
52
+ registry([{ domain, tld: ending }], { timeLeft: () => Math.max(0, 4800 - (performance.now() - started)),
53
+ now, dnsFirst: false, readExpiry: true, rdapAttempts: 1 }).catch(() => []),
54
+ siteCheck(domain, 2200, true).catch(() => null),
55
+ ]);
56
+ const siteState = ['live', 'parked', 'for-sale'].includes(site?.state) ? site.state : 'no live site found';
57
+ const status = registration?.status === 'taken' || siteState === 'live' || siteState === 'parked' || siteState === 'for-sale'
58
+ ? 'taken' : registration?.status === 'free' ? 'free' : 'unverified';
59
+ const expiryValue = registration?.expires;
60
+ const expiry = expiryValue && Number.isFinite(Date.parse(expiryValue)) ? expiryValue.slice(0, 10) : null;
61
+ const odds = status === 'free' ? 'The registry lists it as free. Check the price at a shop.'
62
+ : status === 'unverified' ? 'Release odds are unknown.'
63
+ : siteState === 'live' ? 'Low near-term odds. The site is live.'
64
+ : 'Release odds are unknown. Owners can renew after expiry.';
65
+ const lines = [domain + ': ' + status + ' | web: ' + siteState + ' | ' + (expiry ? 'expires ' + expiry : 'expiry unknown'), odds];
66
+ let submission = 'needs-email';
67
+ if (!email) {
68
+ lines.push('Ask for the email address once.', newsQuestion,
69
+ '[Start the free watch](' + watchUrl + '). You confirm by email.');
70
+ } else if (input.news === undefined) {
71
+ submission = 'needs-news-choice';
72
+ lines.push(newsQuestion);
73
+ } else {
74
+ let response;
75
+ try {
76
+ response = await fetcher(endpoint, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(5000),
77
+ headers: { 'content-type': 'application/json' },
78
+ body: JSON.stringify({ domain, email, ...(input.name?.trim() && { name: input.name.trim() }),
79
+ ...(input.news === true && { news: 'yes' }), source: 'agent', consentTextVersion }) });
80
+ } catch { /* A timeout may occur after the worker has already accepted the request. */ }
81
+ const accepted = response?.status === 202 && (await response.json().catch(() => null))?.ok === true;
82
+ if (accepted) {
83
+ submission = 'accepted';
84
+ lines.push('Check your inbox to start watching. Choose “Confirm watch only” or “Confirm watch + news”. Already watching? Your watch stays on.');
85
+ } else {
86
+ submission = response?.status === 429 ? 'rate-limited' : 'unconfirmed';
87
+ lines.push(response?.status === 429 ? 'Too many tries. Wait a minute.' : 'Signup could not be verified. Check your inbox before trying again.',
88
+ '[Open the watch page](' + watchUrl + ').');
89
+ }
90
+ }
91
+ return { domain, status, expiry, site: siteState, odds, watchUrl, submission, checkedAt: now.toISOString(),
92
+ source: registration?.source ?? null, newsConsentTextVersion: consentTextVersion, say: lines.join('\n') };
93
+ }