domain-hound 0.1.3 → 0.1.4

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "domain-hound",
3
3
  "displayName": "Domain Hound",
4
- "version": "0.1.3",
4
+ "version": "0.1.4",
5
5
  "description": "Check domain availability and prices, and screen product names, from your AI assistant.",
6
6
  "author": {
7
7
  "name": "Lars Hvinden"
package/README.md CHANGED
@@ -44,10 +44,15 @@ For the optional browser fallback, run `npm install domain-hound playwright && n
44
44
  - `check_domains` checks one name or exact domain, or up to 20 at once. A bare name checks ten endings. The first lookup on a fresh install shows the list prices bundled with the package, labelled with their date, while the local price list refreshes in the background.
45
45
  - `triage_names` screens names against public domain, trademark, app, company, and handle data.
46
46
  - `naming_method` gives your assistant a recipe for generating and screening new names.
47
+ - `watch_domain` checks the registry, expiry and website. To start a free watch, give your assistant the email it should use. Confirm the watch in your inbox. Optional news requires a separate choice in that confirmation.
48
+
49
+ Completed lookups save an HTML page and a Markdown copy in `~/.domain-hound/results/`. The page lists prices, availability and sources for each ending checked. On macOS, naming and batch results open in the background. Windows and Wayland request a background open where the desktop supports it. Exact checks and watch results stay in chat with a file link. Set `DOMAIN_HOUND_OPEN=off` on the MCP server to keep every page closed.
47
50
 
48
51
  ## Privacy
49
52
 
50
- The server has no Domain Hound account or hosted backend. Lookups send the relevant name or domain to public sources. Domain searches use IANA and registry RDAP/WHOIS, public DNS, and public registrar pricing. When configured, the client sends selected domains to the Spaceship or Dynadot API for a quote. The optional browser check opens a registrar’s public search page. Name screening may also query the USPTO, Apple App Store, Google Play, Google Search and Trends, Wikidata, public company and package registries, social platforms, Tranco, Common Crawl, and candidate websites. If you configure a search provider via environment variables, queries can also go to Brave Search or Serper. Results may be cached locally.
53
+ Lookups need no Domain Hound account. They send the relevant name or domain to public sources. Domain searches use IANA and registry RDAP/WHOIS, public DNS, and public registrar pricing. When configured, the client sends selected domains to the Spaceship or Dynadot API for a quote. The optional browser check opens a registrar’s public search page. Name screening may also query the USPTO, Apple App Store, Google Play, Google Search and Trends, Wikidata, public company and package registries, social platforms, Tranco, Common Crawl, and candidate websites. If you configure a search provider via environment variables, queries can also go to Brave Search or Serper. Results may be cached locally.
54
+
55
+ Submitting a watch sends the domain, supplied email, optional name and news choice to the Domain Hound watch service. An agent’s yes highlights the news choice. The confirmation click records whether you want it. Result pages omit your supplied email and name.
51
56
 
52
57
  ## Daily checks
53
58
 
@@ -49,6 +49,7 @@ export async function searchNorwegianCompanies(name, input, options) {
49
49
  const match = companyMatch(letters(name), row.navn);
50
50
  if (match) matches.set(row.organisasjonsnummer, {
51
51
  name: compactText(row.navn, 65), match, url: 'https://virksomhet.brreg.no/nb/oppslag/enheter/' + row.organisasjonsnummer,
52
+ ...(Number.isSafeInteger(row.antallAnsatte) && row.antallAnsatte > 0 && { employees: row.antallAnsatte }),
52
53
  });
53
54
  }
54
55
  }
@@ -3,8 +3,9 @@ import { setTimeout as delay } from 'node:timers/promises';
3
3
  import { pathToFileURL } from 'node:url';
4
4
  import { promisify } from 'node:util';
5
5
  import { apiShops, cachedSignals, confirmDomain, confirmingShops, lightConfirm } from './confirm.mjs';
6
+ import { checkDomainSite } from './com-site.mjs';
6
7
  import { appStoreSearchLink, googleSearchLink, nameCheckLines, playSearchLink } from './google-search.mjs';
7
- import { asciiDomain, canRecommend, defaultEndings, eligibilityNotes, listQuote, mergeQuote, nameCandidates, normalizeName, pickName,
8
+ import { applyLiveSite, asciiDomain, canRecommend, defaultEndings, eligibilityNotes, listQuote, mergeQuote, nameCandidates, normalizeName, pickName,
8
9
  premiumRisk, rankName, registrationStatus, searchCandidates, searchName, termCosts, unicodeName, validEligibility, validEndings,
9
10
  withPremiumRisk, withoutListPrice } from './name-search.mjs';
10
11
  import { bundledCatalog, catalogOffers, datedListPrices, isListPriceUsable, loadCachedCatalog, refreshPrices } from './price-catalog.mjs';
@@ -334,7 +335,7 @@ function compactAgentResult(groups, names, complete, checkedAt, batch, rateLimit
334
335
  let priceListDate;
335
336
  let best;
336
337
  for (const { name, results } of groups) {
337
- const taken = [], resale = [], free = [], shop_check = [], likelyFree = [], likelyTaken = [];
338
+ const taken = [], resale = [], free = [], shop_check = [], reserved = [], likelyFree = [], likelyTaken = [];
338
339
  for (const row of results) {
339
340
  checkedEndings.add(row.tld);
340
341
  const d = row.exact ? row.tld : row.domain;
@@ -368,6 +369,7 @@ function compactAgentResult(groups, names, complete, checkedAt, batch, rateLimit
368
369
  }
369
370
  if (row.status === 'reserved') {
370
371
  shop_check.push(d);
372
+ reserved.push(d);
371
373
  shopCheckWhy[row.domain] = String(row.registryReason ?? 'Not offered for registration').slice(0, 80);
372
374
  continue;
373
375
  }
@@ -399,6 +401,7 @@ function compactAgentResult(groups, names, complete, checkedAt, batch, rateLimit
399
401
  const unicode = unicodeName(name);
400
402
  byName.set(name, { name, ...(unicode && { unicode }), ...(taken.length && { taken }), ...(resale.length && { resale }),
401
403
  ...(free.length && { free }), ...(shop_check.length && { shop_check }),
404
+ ...(reserved.length && { reserved }),
402
405
  // Subsets of shop_check with a DNS likelihood; only a registry or shop settles them.
403
406
  ...(likelyFree.length && { likely_free: likelyFree }), ...(likelyTaken.length && { likely_taken: likelyTaken }) });
404
407
  }
@@ -511,13 +514,18 @@ export async function agentResult(input, options = {}) {
511
514
  complete = false;
512
515
  }
513
516
  const apply = row => quotes.has(row.domain) ? mergeQuote(row, quotes.get(row.domain)) : row;
514
- const rankedGroups = fast.groups.map(({ name, results }) => ({ name, results: rankName(results.map(apply)) }));
517
+ const rankedGroups = fast.groups.map(group => ({ ...group, results: rankName(group.results.map(apply)) }));
515
518
  const checkedAt = options.now?.toISOString() ?? new Date().toISOString();
516
519
  // An exact .com gets the standard list prices of the other endings as one benchmark line, with no extra lookups.
517
520
  const exactCom = names.length === 1 && names[0].endsWith('.com') ? names[0] : null;
518
521
  const otherEndings = exactCom ? await endingBenchmarks(exactCom, options) : null;
519
- return compactAgentResult(rankedGroups, names, complete, checkedAt, batch, rateLimited,
522
+ const result = compactAgentResult(rankedGroups, names, complete, checkedAt, batch, rateLimited,
520
523
  options.browser ? liveCheckFor(candidate, quote) : null, { eligible: options.eligible, otherEndings });
524
+ if (options.receipt) result.receiptDetails = rankedGroups.map(({ results, sites }) => ({ endings: results.map(row => ({
525
+ domain: row.domain, source: row.source, checkedAt: row.checkedAt, priceAt: row.priceCheckedAt,
526
+ shop: row.shop, checkout: row.buyUrl, site: sites?.[row.tld], risk: row.premium === 'risk' || row.premiumRisk,
527
+ })) }));
528
+ return result;
521
529
  }
522
530
 
523
531
  // The cheapest standard list price of each other ending for this label, from the saved or bundled price list.
@@ -551,14 +559,29 @@ async function retryGoogle(fast, remaining, options) {
551
559
  const until = performance.now() + budget;
552
560
  const timeLeft = () => Math.max(0, Math.floor(until - performance.now()));
553
561
  const answers = new Map();
562
+ const siteChecks = [];
563
+ const sites = new Map();
564
+ const verify = options.verifyFreeSite ?? options.comSite ?? checkDomainSite;
565
+ const checkNegative = options.fetcher === undefined || options.verifyFreeSite;
554
566
  let timer;
555
567
  await Promise.race([
556
568
  lookupRegistrations([...pending.values()].map(({ domain, tld, exact }) => ({ domain, tld, exact })), {
557
569
  directory: options.directory, fetcher: options.fetcher, pause: options.pause, now: options.now,
558
570
  // DNS already showed no name servers for these rows.
559
571
  resolveNs: async () => [], timeLeft, rdapAttempts: 1,
560
- onResult: (candidate, registry) => { if (timeLeft() > 0) answers.set(candidate.domain, registry); },
561
- }).catch(() => {}),
572
+ onResult: ({ domain }, registry) => {
573
+ if (!timeLeft()) return;
574
+ if (registry.status !== 'free' || !checkNegative) {
575
+ answers.set(domain, registry);
576
+ return;
577
+ }
578
+ const wait = Math.min(1_200, timeLeft());
579
+ siteChecks.push(Promise.resolve().then(() => verify(domain, wait, true)).then(site => {
580
+ sites.set(domain, site);
581
+ answers.set(domain, applyLiveSite(registry, site));
582
+ }, () => { answers.set(domain, registry); }));
583
+ },
584
+ }).then(() => Promise.all(siteChecks)).catch(() => {}),
562
585
  new Promise(resolve => { timer = setTimeout(resolve, budget + 100); }),
563
586
  ]);
564
587
  clearTimeout(timer);
@@ -567,6 +590,7 @@ async function retryGoogle(fast, remaining, options) {
567
590
  group.results = rankName(group.results.map(row => {
568
591
  const answer = pending.has(row.domain) && answers.get(row.domain);
569
592
  if (!answer) return row;
593
+ if (sites.has(row.domain)) group.sites[row.tld] = sites.get(row.domain);
570
594
  const status = registrationStatus(answer);
571
595
  if (status === 'check-at-shop') {
572
596
  if (/HTTP 429/.test(answer.reason ?? '')) limited = true;
@@ -629,6 +653,7 @@ function lookupArgs(args) {
629
653
  else if (arg === '--eligible' && !options.eligible) options.eligible = (args[++index] ?? '').split(',');
630
654
  else if (arg === '--category' && !options.category) options.category = (args[++index] ?? '').slice(0, 100);
631
655
  else if (arg === '--compact') options.compact = true;
656
+ else if (arg === '--receipt') options.receipt = true;
632
657
  // The headless browser shop check runs only on this explicit flag.
633
658
  else if (arg === '--confirm') options.browser = true;
634
659
  else if (arg === '--geo' && options.geo === undefined) options.geo = readGeo(args[++index]);
@@ -167,6 +167,11 @@ export function registrationStatus(registry) {
167
167
  return registry.status === 'taken' ? 'taken' : 'check-at-shop';
168
168
  }
169
169
 
170
+ export function applyLiveSite(registry, site) {
171
+ if (registry.status !== 'free' || !['live', 'parked', 'for-sale'].includes(site?.state)) return registry;
172
+ return { status: 'taken', source: 'web', checkedAt: registry.checkedAt, forSale: site.state === 'for-sale' };
173
+ }
174
+
170
175
  export function listQuote(catalog, { domain, tld }, now, bundled = bundledCatalog) {
171
176
  // Data-only shops never become the listed pick or its checkout link.
172
177
  const prices = datedListPrices(catalog, tld, now, bundled).filter(row => linkable(row.id)).sort((a, b) =>
@@ -228,20 +233,33 @@ export async function searchCandidates(groups, options = {}) {
228
233
  const sites = new Map();
229
234
  const siteEndings = options.siteEndings ?? (options.skipComSite ? [] : ['com']);
230
235
  const lookedUp = new Map();
236
+ const checks = [];
231
237
  let catalog = null;
232
238
  let timer;
233
239
  let complete = false;
234
240
  const onResult = ({ domain, tld, exact }, registry) => {
235
241
  if (timeLeft() <= 0) return;
236
- lookedUp.set(domain, registry);
237
- const status = registrationStatus(registry);
238
- options.onProgress?.({ domain, status: status === 'probably-free' && premiumRisk(domain) ? 'premium' : status });
239
- if (registry.status !== 'taken' || !exact || !siteEndings.includes(tld)) return;
242
+ const publish = (result) => {
243
+ lookedUp.set(domain, result);
244
+ const status = registrationStatus(result);
245
+ options.onProgress?.({ domain, status: status === 'probably-free' && premiumRisk(domain) ? 'premium' : status });
246
+ };
247
+ // A negative registry answer can be wrong. A real response on the domain beats a free claim.
248
+ // Replay and unit callers that inject registry traffic can inject the site check as well.
249
+ const checkNegative = registry.status === 'free' && (options.fetcher === undefined || options.verifyFreeSite);
250
+ const checkTaken = registry.status === 'taken' && exact && siteEndings.includes(tld);
251
+ if (!checkNegative) publish(registry);
252
+ if (!checkNegative && !checkTaken) return;
240
253
  const timeout = Math.min(options.siteTimeout ?? 1200, timeLeft());
241
- sites.set(domain, { pending: (options.comSite ?? checkDomainSite)(domain, timeout, options.siteDetails).then(site => {
254
+ const visit = checkNegative ? options.verifyFreeSite ?? options.comSite ?? checkDomainSite
255
+ : options.comSite ?? checkDomainSite;
256
+ const pending = Promise.resolve().then(() => visit(domain, timeout, options.siteDetails || checkNegative)).then(site => {
242
257
  sites.get(domain).result = site;
243
258
  options.onSite?.(domain, site);
244
- }).catch(() => {}) });
259
+ if (checkNegative) publish(applyLiveSite(registry, site));
260
+ }, () => { if (checkNegative) publish(registry); });
261
+ sites.set(domain, { pending });
262
+ checks.push(pending);
245
263
  };
246
264
  const loadCatalog = options.cachedOnly ? loadCachedCatalog(options.directory)
247
265
  : getNameCatalog({ ...options, now, coldWaitMs: bundled ? 0 : Math.min(1900, budgetMs) });
@@ -249,7 +267,7 @@ export async function searchCandidates(groups, options = {}) {
249
267
  lookupRegistrations([...candidates.values()], { ...options, now, timeLeft, onResult }),
250
268
  loadCatalog.then(value => { catalog = value; }),
251
269
  ]).then(async () => {
252
- await Promise.all([...sites.values()].map(site => site.pending));
270
+ await Promise.all(checks);
253
271
  complete = lookedUp.size === candidates.size;
254
272
  });
255
273
  try {
@@ -15,7 +15,7 @@ export const geoInstruction = 'GEO (presence in AI answers): for each name, answ
15
15
  export const namingRecipe = (about = '') => 'Naming recipe (intermediate). Use the final triage display.\n'
16
16
  + (about ? '1. Brief: ' + about.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu, ' ').trim()
17
17
  + '.\n' : '1. Brief: product, audience and preferences.\n')
18
- + '2. Generate about 30 words. Pair one with a familiar animal or object. Avoid category-generic names.\n'
18
+ + '2. Generate about 30 words. Pair one with a familiar animal or object. Default to English unless the person asked for another language. Avoid category-generic names.\n'
19
19
  + '3. Check: call check_domains ONCE with seven bare names and shortlist: true (Quiet Otter → quietotter). No spaces or dots.\n'
20
- + '4. Triage: call triage_names ONCE on only the best FIVE with free endings, a short about and geo from memory. Follow its Google search instructions.\n'
21
- + '5. Answer: ' + showAsIs + ' Keep all five candidates and let the person choose.';
20
+ + '4. Triage: call triage_names ONCE on the best FIVE with free endings, a short about and geo from memory. Pass the same endings and budget to both calls.\n'
21
+ + '5. Answer: Relay say as written. Let the person choose from the complete local results page.';
@@ -348,6 +348,7 @@ export function collectRivals({ name, input = name, sites = {}, entities, topics
348
348
  owner.wikipedia ??= rival.wikipedia;
349
349
  owner.apps.push(...rival.apps);
350
350
  owner.description ??= rival.description;
351
+ owner.website ??= rival.website;
351
352
  if (rival.sources.includes('wikidata') && !owner.sources.includes('wikidata-name')) {
352
353
  owner.name = rival.name;
353
354
  owner.sources.push('wikidata-name');
@@ -371,7 +372,9 @@ export function collectRivals({ name, input = name, sites = {}, entities, topics
371
372
  // A site that redirects to another home of the same name (notion.ai to notion.com) joins that rival.
372
373
  const final = site.state === 'live' && site.host ? siteDomain(site.host) : null;
373
374
  add(base(head?.head ?? domain, 'site', {
374
- domains: [domain, ...(final && final !== domain && ownsName(name, final) ? [final] : [])], refs: [domain], site: { domain, state: site.state, copyright: site.copyright, lastModified: site.lastModified },
375
+ domains: [domain, ...(final && final !== domain && ownsName(name, final) ? [final] : [])], refs: [domain],
376
+ website: final ?? (site.state === 'live' ? domain : undefined),
377
+ site: { domain, state: site.state, copyright: site.copyright, lastModified: site.lastModified },
375
378
  description: compactText([site.title, site.description].filter(Boolean).join(' '), 200) || undefined,
376
379
  sameBusiness: site.state === 'live' && sameBusiness([site.title, site.description].join(' ')),
377
380
  }));
@@ -380,7 +383,7 @@ export function collectRivals({ name, input = name, sites = {}, entities, topics
380
383
  if (!entity?.brand || letters(entity.name) !== letters(name)) continue;
381
384
  const homes = (entity.website ?? []).map(siteDomain).filter(domain => domain && ownsName(name, domain));
382
385
  add(base(entity.name, 'wikidata', {
383
- domains: [...new Set(homes)], refs: [entity], description: entity.description || undefined,
386
+ domains: [...new Set(homes)], website: homes[0], refs: [entity], description: entity.description || undefined,
384
387
  wikipedia: entity.wikipedia ?? null, sitelinks: entity.sitelinks ?? 0,
385
388
  sameBusiness: sameBusiness(entity.name + ' ' + (entity.description ?? '')),
386
389
  }));
@@ -481,7 +484,7 @@ export function assessRival(rival, evidence = new Map(), { now = Date.now(), ans
481
484
  if (best.age && yearsSince(best.age.date, now) >= T.some.domainYears) {
482
485
  signals.push(signal('domain since ' + best.age.date.slice(0, 4), 'some', 0.3));
483
486
  }
484
- const home = best.tranco?.domain ?? best.crawl?.domain ?? best.age?.domain ?? rival.domains[0];
487
+ const home = rival.website ?? (rival.site?.state === 'live' ? rival.site.domain : null);
485
488
  if (rival.wikipedia && T.strong.wikipediaArticle) signals.push(signal('Wikipedia article', 'strong', 0.9));
486
489
  for (const app of rival.apps) {
487
490
  if (!Number.isSafeInteger(app.ratings)) continue;
@@ -590,7 +593,7 @@ export function tractionSummary(judged) {
590
593
  if (!main || level[main.level] < 1) return judged.agent ? { geo } : null;
591
594
  return {
592
595
  rival: rivalLabel(main), level: main.level, ...(main.rival.sameBusiness && { sameBusiness: true }),
593
- signals: main.signals.slice(0, 2).map(item => item.text), geo,
596
+ ...(main.home && { domain: main.home }), signals: main.signals.slice(0, 2).map(item => item.text), geo,
594
597
  };
595
598
  }
596
599
 
@@ -217,12 +217,14 @@ export async function namePresence(input, options = {}) {
217
217
  // Same-name rivals with measured traction follow the traction rules first; evidence whose traction could not be
218
218
  // measured keeps the earlier same-name checks. Trademark and availability guardrails stay in place.
219
219
  function baseVerdict({ rival, overlap, sameName, activeApp, brand, app, entity, mark, site, best, available, marks, apps, android,
220
- androidAnswered = android, com, premium = [] }) {
220
+ androidAnswered = android, company, premium = [] }) {
221
221
  if (rival?.[0] === 'Avoid') return rival;
222
222
  if (overlap) return ['Avoid', overlap.domain + ' is a live business in the same category'];
223
223
  if (activeApp) return ['Avoid', activeApp.name + ' is an app in the same category with ' + activeApp.ratings + ' ' + activeApp.store + ' ratings'];
224
224
  if (mark?.relevant && mark.tier !== 'Fuzzy') return ['Avoid', trademarkReason(mark)];
225
225
  if (rival) return rival;
226
+ if (company) return ['Check first', company.name + ' is an active same-name company' +
227
+ (company.employees > 0 ? ' with ' + company.employees + ' employees' : '')];
226
228
  if (brand) return ['Check first', brand.name + ' is an existing company or product in Wikidata'];
227
229
  if (mark) return ['Check first', trademarkReason(mark)];
228
230
  if (sameName.level !== 'few') return ['Check first', 'Several public sources show same-name use'];
@@ -231,12 +233,11 @@ function baseVerdict({ rival, overlap, sameName, activeApp, brand, app, entity,
231
233
  if (site) return ['Check first', site.domain + ' has a live site under this name'];
232
234
  if (entity) return ['Check first', 'An exact-name Wikidata entity already exists'];
233
235
  if (!marks || !apps || !androidAnswered || sameName.unchecked?.length) return ['Check first', 'A competition source did not answer'];
234
- if (com?.status === 'check-at-shop') return ['Check first', 'The .com registry status is unresolved'];
235
236
  if (!best) {
236
237
  return ['Check first', available.length ? 'The free endings require buyer eligibility'
237
238
  : premium.length ? 'The free endings may be premium, price at shop' : 'No domain was found free at the registry'];
238
239
  }
239
- return ['No conflict found', 'No close US mark, app or site overlap'];
240
+ return ['No conflict found', 'No US mark, same-name app or active company found in the sources checked'];
240
241
  }
241
242
 
242
243
  export async function triageNames(inputs, options = {}) {
@@ -383,6 +384,8 @@ export async function triageNames(inputs, options = {}) {
383
384
  const site = unmeasured[0];
384
385
  const overlap = unmeasured.find(row => row.sameBusiness && /\.(com|ai)$/.test(row.domain));
385
386
  const us = matchEdgarCompanies(key, edgar);
387
+ const company = norway?.matches.find(row => row.employees > 0 && row.match === 'exact')
388
+ ?? us?.matches.find(row => row.match === 'exact');
386
389
  const sameName = sameNameEvidence({ name: key, live, norway, us, entities, entity, github, handles });
387
390
  const otherEntities = entities?.filter(row => !explained.has(row));
388
391
  const legacy = sameNameEvidence({ name: key, live: unmeasured, norway, us, entities: otherEntities, entity, github, handles });
@@ -392,7 +395,7 @@ export async function triageNames(inputs, options = {}) {
392
395
  rival: tractionVerdict(judged), overlap, sameName: legacy, activeApp,
393
396
  brand: otherEntity?.brand ? otherEntity : undefined, app: apps?.find(row => !explained.has(row)), entity: otherEntity,
394
397
  mark, otherMark, site, silent, best, available, marks, apps, premium: results.filter(row => row.status === 'premium'),
395
- android: android?.filter(row => !explained.has(row)), androidAnswered: android, com: results.find(row => row.tld === 'com'),
398
+ android: android?.filter(row => !explained.has(row)), androidAnswered: android, company,
396
399
  });
397
400
  const googleExplained = explainedGoogle(key, googleByName[index].raw, judged, entities);
398
401
  const summary = tractionSummary(judged);
@@ -420,6 +423,8 @@ export async function triageNames(inputs, options = {}) {
420
423
  google: { ...(google.google ?? { result: 'not checked', why: google.unchecked }), link: googleSearchLink(names.get(name)) },
421
424
  taken: requested.filter(row => row.status === 'taken').map(row => row.tld),
422
425
  shop_check: requested.filter(row => ['check-at-shop', 'reserved'].includes(row.status)).map(row => row.tld),
426
+ ...(requested.some(row => row.status === 'reserved') && {
427
+ reserved: requested.filter(row => row.status === 'reserved').map(row => row.tld) }),
423
428
  // Subsets of shop_check with a DNS likelihood; only a registry or shop settles them.
424
429
  ...likelyEndings(requested),
425
430
  // Premium endings never carry a list price; the shop shows their price. A short name may be premium.
@@ -427,6 +432,9 @@ export async function triageNames(inputs, options = {}) {
427
432
  premium: requested.filter(row => row.status === 'premium').map(row => row.tld) }),
428
433
  // The checkout is the listed shop's search, or the confirming shop's search when no list price is known.
429
434
  competition, buy: best ? best.buyUrl ?? shopSearchUrl(best.confirmShop, best.domain) : null,
435
+ ...(options.receipt && { _receiptEndings: requested.map(row => ({ domain: row.domain, source: row.source,
436
+ checkedAt: row.checkedAt, priceAt: row.priceCheckedAt, shop: row.shop, checkout: row.buyUrl,
437
+ site: sites[row.tld], risk: row.premium === 'risk' || row.premiumRisk })) }),
430
438
  details: {
431
439
  memorable: memorability(key, names.get(name)),
432
440
  presence: Object.fromEntries(Object.entries(handles).map(([service, status]) =>
@@ -445,7 +453,15 @@ export async function triageNames(inputs, options = {}) {
445
453
  for (const row of googleCandidates(rows)) row.google.search = true;
446
454
  const sourcesSummary = Object.fromEntries(Object.entries(counts).map(([source, answered]) =>
447
455
  [source, Math.round(100 * answered / names.size)]));
448
- return packTriage(rows, sourcesSummary, options.compact, endings, options.eligible);
456
+ const receiptDetails = options.receipt ? structuredClone(rows.map(({ competition, details, traction, google, reason, _receiptEndings }) =>
457
+ ({ competition, details, traction, google, reason, endings: _receiptEndings }))) : null;
458
+ const result = packTriage(rows, sourcesSummary, options.compact, endings, options.eligible);
459
+ if (options.receipt) {
460
+ result.checkedAt = (options.now ?? new Date()).toISOString();
461
+ result.priceListDate = domains.priceDate?.slice(0, 10);
462
+ result.receiptDetails = receiptDetails;
463
+ }
464
+ return result;
449
465
  }
450
466
 
451
467
  // The first three ranked names, filled from the screened names in input order when fewer than three rank.
@@ -502,7 +518,7 @@ function topChoices(rows) {
502
518
  function packTriage(rows, sources, compact, endings, eligible) {
503
519
  const prices = {};
504
520
  const top = topChoices(rows);
505
- const names = rows.map(({ _free, _recommendable, _mark, _googleExplained, ...row }) => {
521
+ const names = rows.map(({ _free, _recommendable, _mark, _googleExplained, _receiptEndings, ...row }) => {
506
522
  const own = {};
507
523
  for (const option of _free) {
508
524
  const entry = priceEntry(option);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "domain-hound",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "Check domains, compare registrar prices, and screen product names from your MCP client.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -26,6 +26,9 @@
26
26
  "bin/domain-hound.mjs",
27
27
  "server.mjs",
28
28
  "display.mjs",
29
+ "results.mjs",
30
+ "results-style.mjs",
31
+ "watch.mjs",
29
32
  "clis/domain-check/cache.mjs",
30
33
  "clis/domain-check/com-site.mjs",
31
34
  "clis/domain-check/company-search.mjs",
@@ -54,7 +57,7 @@
54
57
  "server.json"
55
58
  ],
56
59
  "scripts": {
57
- "test": "node --test server.test.mjs clis/domain-check/*.test.mjs clis/domain-check/test.mjs",
60
+ "test": "node --test server.test.mjs results.test.mjs clis/domain-check/*.test.mjs clis/domain-check/test.mjs",
58
61
  "smoke": "node scripts/smoke.mjs",
59
62
  "snapshot-prices": "node scripts/snapshot-prices.mjs",
60
63
  "build-mcpb": "node scripts/build-mcpb.mjs"
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
3
  "name": "domain-hound",
4
- "version": "0.1.3",
4
+ "version": "0.1.4",
5
5
  "description": "Check domain availability and prices, and screen product names, from your AI assistant.",
6
6
  "author": {
7
7
  "name": "Lars Hvinden"
@@ -13,7 +13,7 @@
13
13
  "interface": {
14
14
  "displayName": "Domain Hound",
15
15
  "shortDescription": "Domain prices and name checks",
16
- "longDescription": "Domain Hound is a local MCP server that helps you pick a product name and the best domain. It checks real registry availability, finds the cheapest trusted shop including the renewal price, and screens names for trademark conflicts, app store clashes and web traction. It has three tools: check_domains, triage_names and naming_method. It runs on your machine over stdio, needs no account, and is open source under the MIT license.",
16
+ "longDescription": "Domain Hound is a local MCP server that helps you pick a product name and the best domain. It checks real registry availability, finds the cheapest trusted shop including the renewal price, and screens names for trademark conflicts, app store clashes and web traction. It has four tools: check_domains, triage_names, naming_method and watch_domain. It runs on your machine over stdio, needs no account, and is open source under the MIT license.",
17
17
  "developerName": "Lars Hvinden",
18
18
  "category": "Developer Tools",
19
19
  "capabilities": [
@@ -0,0 +1,62 @@
1
+ // Domain Hound's brand B receipt, designed for the same table at phone and desktop widths.
2
+ export const receiptStyle = `
3
+ :root {
4
+ color-scheme: light;
5
+ --blue: #102385;
6
+ --gold: #f4c64f;
7
+ --cream: #fff7de;
8
+ --lime: #cdf473;
9
+ --coral: #ffab91;
10
+ --mono: ui-monospace, "SFMono-Regular", Consolas, monospace;
11
+ }
12
+ * { box-sizing: border-box; }
13
+ body {
14
+ margin: 0;
15
+ background: var(--cream);
16
+ color: var(--blue);
17
+ font: 400 1.0625rem/1.5 Mulish, system-ui, sans-serif;
18
+ overflow-wrap: anywhere;
19
+ }
20
+ main { width: min(calc(100% - 2rem), 56rem); margin: 1rem auto 3rem; }
21
+ main > header {
22
+ padding: .875rem 1rem;
23
+ background: var(--blue);
24
+ color: var(--cream);
25
+ border-bottom: .3rem solid var(--gold);
26
+ }
27
+ header small, time, code { font-family: var(--mono); }
28
+ header small { color: var(--gold); font-weight: 700; }
29
+ h1, h2 { margin: 0; font-weight: 900; line-height: 1.12; letter-spacing: -.035em; }
30
+ h1 { margin-block: .2rem; font-size: clamp(2rem, 4vw, 2.75rem); }
31
+ h2 { font-size: 1.65rem; }
32
+ p { max-width: 62ch; margin: .35rem 0; }
33
+ main > section, article, footer { margin-top: 1.25rem; padding-top: 1rem; border-top: 2px solid var(--blue); }
34
+ .comparison { display: grid; gap: 2px; margin-block: .875rem; border: 2px solid var(--blue); background: var(--blue); }
35
+ .comparison > * { min-width: 0; margin: 0; padding: .6rem .8rem; background: var(--gold); }
36
+ .comparison > :last-child { background: var(--lime); }
37
+ nav { display: flex; flex-wrap: wrap; gap: 0 1rem; margin-top: 1rem; }
38
+ a, a:visited { color: inherit; text-underline-offset: .18em; }
39
+ nav a, summary { padding-block: .6rem; }
40
+ :focus-visible { outline: 3px solid currentColor; outline-offset: 2px; }
41
+ table { width: 100%; table-layout: fixed; border-collapse: collapse; margin-block: .75rem; }
42
+ caption { padding-bottom: .35rem; text-align: left; font-weight: 750; }
43
+ th, td { padding: .5rem .4rem; border-bottom: 1px solid var(--blue); text-align: left; vertical-align: top; }
44
+ thead { background: var(--blue); color: var(--cream); }
45
+ thead th:first-child { width: 50%; }
46
+ thead th:nth-child(n+2), tbody td { text-align: right; }
47
+ tbody td { font-variant-numeric: lining-nums tabular-nums; }
48
+ th[scope="row"] code { display: block; font-weight: 800; }
49
+ th[scope="row"] small { display: block; font: 400 .9375rem/1.45 system-ui, sans-serif; }
50
+ details { border-bottom: 1px dashed var(--blue); }
51
+ summary { cursor: pointer; font-weight: 750; }
52
+ details[open] { padding-bottom: .65rem; }
53
+ footer { font-size: .9375rem; }
54
+ @media (min-width: 48rem) {
55
+ body { font-size: 1.125rem; }
56
+ main { margin-top: 2rem; }
57
+ main > header { padding: 1rem 1.25rem; }
58
+ .comparison { grid-template-columns: repeat(2, minmax(0, 1fr)); }
59
+ thead th:first-child { width: 56%; }
60
+ th, td { padding: .55rem .85rem; }
61
+ }
62
+ `;
package/results.mjs ADDED
@@ -0,0 +1,383 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { mkdir, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises';
4
+ import { homedir, userInfo } from 'node:os';
5
+ import { join, resolve } from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+ import { canRecommend, defaultEndings, normalizeName } from './clis/domain-check/name-search.mjs';
8
+ import { shopSearchUrl, shops } from './clis/domain-check/prices.mjs';
9
+ import { safeLink } from './display.mjs';
10
+ import { receiptStyle } from './results-style.mjs';
11
+
12
+ const cash = value => Number.isFinite(value) ? '$' + value.toFixed(2) : null;
13
+ const escape = value => String(value ?? '').replace(/[&<>"']/g, char =>
14
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]);
15
+ const plain = value => String(value ?? '').replace(/[\r\n\p{Cc}\p{Cf}]+/gu, ' ').replace(/\s*[—–]\s*/g, '. ').trim();
16
+ const evidenceText = value => plain(value).replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
17
+ .replace(/https?:\/\/[^\s)]+/gi, '').replace(/[\[\]<>]/g, '').replace(/\s{2,}/g, ' ').trim();
18
+ const markdown = value => plain(value).replace(/[\\|<>\[\]`*]/g, '\\$&');
19
+ const shopIds = new Map(Object.entries(shops).map(([id, { name }]) => [name, id]));
20
+ const endingOf = value => value.split('.').at(-1);
21
+ const fallbackShop = ending => ending === 'no' ? 'dynadot' : ending === 'so' ? 'namecheap' : 'spaceship';
22
+ const markOf = row => row.competition?.US;
23
+ const marksText = row => {
24
+ const mark = markOf(row);
25
+ return 'US marks: ' + (typeof mark === 'string' ? evidenceText(mark) : mark == null ? 'not checked' : 'no match found');
26
+ };
27
+ const watchLink = domain => 'https://domainhound.dev/watch/?domain=' + encodeURIComponent(domain);
28
+ const verdictOrder = { 'No conflict found': 0, 'Check first': 1, Avoid: 2 };
29
+
30
+ function resultGroups(data) {
31
+ return data.names.map((row, index) => {
32
+ const detail = data.receiptDetails?.[index] ?? {};
33
+ const exact = row.name.includes('.');
34
+ const label = exact ? row.name : normalizeName(row.name);
35
+ const variants = [...(row.free ?? []), ...(row.taken ?? []), ...(row.shop_check ?? []), ...(row.resale ?? [])]
36
+ .map(value => value.d ?? value).filter(value => value.includes('.'));
37
+ const targets = exact ? [row.name] : [...new Set([...defaultEndings.map(ending => label + '.' + ending), ...variants])];
38
+ const records = targets.map(domain => {
39
+ const ending = endingOf(domain);
40
+ const lookupKey = domain === label + '.' + ending || exact ? ending : domain;
41
+ const match = list => list?.find(value => (value.d ?? value) === domain || (value.d ?? value) === lookupKey);
42
+ const option = match(row.free);
43
+ const raw = detail.endings?.find(item => item.domain === domain);
44
+ const confirmed = option?.s === 'ok';
45
+ const quote = confirmed ? option : { ...data.listPrices?.[ending], ...data.listPrices?.[domain],
46
+ ...data.prices?.[ending], ...row.own?.[ending], ...(typeof option === 'object' ? option : {}) };
47
+ const taken = Boolean(match(row.taken) || match(row.resale));
48
+ const reserved = Boolean(match(row.reserved));
49
+ const risk = Boolean(option?.risk || raw?.risk);
50
+ const premium = Boolean(match(row.premium) || option?.s === 'prem' || option?.prem || risk);
51
+ const includePrice = !reserved && (!premium || confirmed) && (!taken || exact);
52
+ const likely = match(row.likely_free) ? 'likely free by DNS' : match(row.likely_taken) ? 'likely taken by DNS' : null;
53
+ const state = taken ? 'taken' : premium ? 'premium' : option ? 'free' : 'check';
54
+ const status = taken ? (match(row.resale) ? 'Taken, possible resale' : 'Taken')
55
+ : reserved ? 'Not offered for registration' : confirmed ? 'Confirmed at shop'
56
+ : premium ? (risk ? 'May be premium, price at shop' : 'Premium, price at shop')
57
+ : option ? 'Free at the registry' : likely ? 'Check at shop, ' + likely : 'Check at shop';
58
+ const usd = includePrice ? { now: quote.now, renew: quote.renew, y3: quote.y3, term: quote.term,
59
+ jump: quote.jump, shop: quote.shop } : {};
60
+ const term = usd.term ?? 1;
61
+ const total = usd.y3 ?? (usd.now != null && usd.renew != null ? usd.now + (Math.ceil(3 / term) - 1) * usd.renew : null);
62
+ const source = ({ web: 'Live site', dns: 'DNS', rdap: 'Registry RDAP', whois: 'Registry WHOIS',
63
+ shop: 'Shop', list: 'Price list' })[raw?.source] ?? (confirmed ? 'Shop' : likely ? 'DNS' : 'Registry');
64
+ const shop = usd.shop ?? raw?.shop ?? shops[fallbackShop(ending)]?.name;
65
+ const eligible = canRecommend(ending, data.eligible);
66
+ const shopUrl = shopSearchUrl(shopIds.get(shop) ?? fallbackShop(ending), domain);
67
+ const checkout = taken || reserved || !eligible ? null : [raw?.checkout, shopUrl].find(url => safeLink(url, domain)) ?? null;
68
+ return { domain, ending, state, status, ...usd, total, shop, checkout, eligible, source,
69
+ priceLabel: usd.now != null || usd.renew != null ? (confirmed ? 'Shop quote' : taken ? 'Standard list price benchmark' : 'List price') : '',
70
+ checkedAt: raw?.checkedAt ?? data.checkedAt, priceAt: raw?.priceAt ?? option?.at ?? data.priceListDate,
71
+ site: raw?.site ?? detail.details?.sites?.[ending] ?? row.details?.sites?.[ending] };
72
+ });
73
+ records.sort((a, b) => Number(b.state === 'free' || b.priceLabel === 'Shop quote')
74
+ - Number(a.state === 'free' || a.priceLabel === 'Shop quote') || (a.now ?? Infinity) - (b.now ?? Infinity));
75
+ return { row: { ...row, ...detail, name: row.name }, records };
76
+ });
77
+ }
78
+
79
+ function offerText(offer, linked = false) {
80
+ const { domain, checkout, now, renew, term, jump, priceLabel } = offer;
81
+ const price = now != null ? cash(now) + (renew != null ? ', then ' + cash(renew) : ', renewal at shop')
82
+ : renew != null ? cash(renew) + ' renewal' : 'price at shop';
83
+ return (linked && checkout ? '[' + domain + '](' + checkout + ')' : domain) + ' ' + price
84
+ + (term > 1 ? ' every ' + term + ' years' : '') + (jump ? ' (renewal jumps)' : '')
85
+ + (priceLabel ? ' ' + priceLabel.toLowerCase() : '');
86
+ }
87
+
88
+ function appFinding(value) {
89
+ if (value == null) return 'check incomplete';
90
+ return Array.isArray(value) && !value.length ? 'no app with this name' : 'same-name app found';
91
+ }
92
+
93
+ function signals(group) {
94
+ const { row, records } = group;
95
+ const comp = row.competition ?? {};
96
+ const site = records.map(record => record.site).find(site => site?.state === 'live')?.host;
97
+ const states = records.map(record => typeof record.site === 'string' ? record.site : record.site?.state).filter(Boolean);
98
+ const checked = states.some(state => /^(?:live|parked|for.sale|no(?:-site| site found))/i.test(state));
99
+ const web = site ? 'live site at ' + plain(site) : states.some(state => /live/i.test(state)) ? 'live site'
100
+ : states.some(state => /parked|for sale|for-sale/i.test(state)) ? 'parked'
101
+ : row.traction?.domain ? 'rival listed at ' + plain(row.traction.domain)
102
+ : checked ? 'no live site found on checked endings' : 'not checked';
103
+ return 'iOS: ' + appFinding(comp.AppStore) + ' | Android: ' + appFinding(comp.GooglePlay) + ' | web: ' + web;
104
+ }
105
+
106
+ function summary(groups, args, triage) {
107
+ const [wanted] = groups;
108
+ const preferred = args.endings ?? [];
109
+ const budget = args.budget;
110
+ const isExact = !triage && groups.length === 1 && wanted.row.name.includes('.');
111
+ const constraints = [...(!isExact && preferred.length ? [preferred.map(ending => '.' + ending).join(', ') + ' first'] : []),
112
+ ...(budget != null ? ['Up to ' + cash(budget) + ' today'] : [])];
113
+ const inScope = record => record.eligible && (!preferred.length || preferred.includes(record.ending))
114
+ && (budget == null || (record.now ?? Infinity) <= budget);
115
+ const candidates = groups.flatMap(group => group.row.verdict === 'Avoid' ? [] : group.records
116
+ .filter(record => inScope(record) && (record.state === 'free' || record.priceLabel === 'Shop quote'))
117
+ .map(record => ({ group, record })));
118
+ const cost = item => item.record.now ?? Infinity;
119
+ const compareCost = (a, b) => cost(a) - cost(b);
120
+ const position = item => preferred.length ? preferred.indexOf(item.record.ending) : 0;
121
+ candidates.sort((a, b) => (verdictOrder[a.group.row.verdict] ?? 0) - (verdictOrder[b.group.row.verdict] ?? 0)
122
+ || position(a) - position(b) || compareCost(a, b) || a.record.domain.localeCompare(b.record.domain));
123
+ const best = candidates[0];
124
+ const picks = [...new Map(candidates.toReversed().map(item => [item.group, item])).values()].reverse().slice(0, 3);
125
+ const cheapest = candidates.filter(item => item.record.now != null).sort(compareCost)[0];
126
+ const value = candidates.filter(item => item.record.total != null)
127
+ .sort((a, b) => a.record.total - b.record.total || compareCost(a, b))[0];
128
+ const target = wanted.records.find(record => record.ending === (preferred[0] ?? 'com')) ?? wanted.records[0];
129
+ const watch = target?.state === 'taken' ? 'Want it anyway? [Watch ' + target.domain + '](' + watchLink(target.domain) + ').' : null;
130
+ if (isExact) {
131
+ const picked = wanted.records[0];
132
+ const hasPrice = picked.now != null || picked.renew != null;
133
+ let price = hasPrice ? ' ' + offerText(picked).slice(picked.domain.length + 1) + '.' : '';
134
+ if (picked.state === 'taken' && picked.renew != null) {
135
+ price = ' Standard list renewal: ' + cash(picked.renew) + (picked.term > 1
136
+ ? ' every ' + picked.term + ' years (' + cash(picked.renew / picked.term) + ' a year)' : ' a year') + '.';
137
+ }
138
+ const overBudget = budget != null && picked.now != null && picked.now > budget && picked.state !== 'taken';
139
+ const intro = picked.domain + ': ' + picked.status.toLowerCase() + '.' + price + (overBudget ? ' Over budget.' : '');
140
+ const step = overBudget ? 'Next: try a cheaper domain.' : picked.checkout
141
+ ? 'Next: [check at ' + plain(picked.shop) + '](' + picked.checkout + ').' : watch ?? 'Next: check another domain.';
142
+ return [...constraints, intro, ...(args.purchase ? ['Domain Hound cannot buy or complete checkout.'] : []), step];
143
+ }
144
+ const reason = evidenceText(wanted.row.reason).replace('David vs Goliath: ', 'Established rival: ');
145
+ const keep = triage ? 'Keep ' + evidenceText(wanted.row.name) + '? ' + plain(wanted.row.verdict) + '. '
146
+ + reason.replaceAll(' · ', '. ') + '.'
147
+ + (typeof markOf(wanted.row) === 'string' && reason.includes(markOf(wanted.row)) ? ' US trademark screen.' : ' ' + marksText(wanted.row) + '.')
148
+ + (wanted.row.verdict === 'Avoid' && best ? (best.group.row.verdict === 'No conflict found' ? ' Best free rename: ' : ' Next name to check: ')
149
+ + plain(best.group.row.name) + '.' : '')
150
+ + (picks.some(item => item.group === wanted) ? '' : ' | ' + signals(wanted)) : null;
151
+ const next = watch ?? (args.shortlist ? 'Next: screen the best names.' : best ? 'Next: check your pick at the shop.' : 'Next: try another name.');
152
+ const caution = item => item.group.row.verdict === 'Check first' ? ' (Check first)' : '';
153
+ const label = item => offerText(item.record, true) + caution(item);
154
+ const offerLines = picks.map(({ group, record }, index) =>
155
+ (budget != null && index === 0 ? 'Pick: ' : (index + 1) + '. ') + offerText(record) + ' (' + plain(record.status.toLowerCase()) + ') | '
156
+ + (triage ? plain(group.row.verdict) + ' | ' + marksText(group.row) + ' | ' : '') + signals(group));
157
+ const scope = constraints.length ? constraints.join(' | ') + '. ' : '';
158
+ const leadPick = scope && offerLines.length ? scope + offerLines.shift() : null;
159
+ const eligibility = args.eligible?.includes('no') || cheapest?.record.ending === 'no'
160
+ || value?.record.ending === 'no' || preferred.includes('no')
161
+ ? ' .no needs a Norwegian address and organization or personal ID.' : '';
162
+ const lines = [
163
+ leadPick || (scope ? scope + 'All endings are on the page.' : null),
164
+ keep,
165
+ ...offerLines,
166
+ 'Cheapest: ' + (cheapest ? label(cheapest) : 'none found in scope.'),
167
+ 'Best value: ' + (value ? value.record.domain + ', ' + cash(value.record.total) + ' in payments due in 3 years'
168
+ + caution(value) : 'needs a shop quote') + '.',
169
+ (args.purchase ? 'Domain Hound cannot buy or complete checkout. ' : '') + next + eligibility,
170
+ ];
171
+ return lines.filter(Boolean);
172
+ }
173
+
174
+ function httpsLink(value) {
175
+ if (typeof value !== 'string') return null;
176
+ try {
177
+ const url = new URL(value);
178
+ return url.protocol === 'https:' && !url.username && !url.password ? url.href : null;
179
+ } catch {
180
+ return null;
181
+ }
182
+ }
183
+
184
+ function details(group) {
185
+ const { row } = group;
186
+ const comp = row.competition ?? {};
187
+ const titleAndLink = value => value && typeof value === 'object'
188
+ ? [plain(value.name ?? value.domain ?? value.title), httpsLink(value.url)] : [plain(value)];
189
+ const ios = Array.isArray(comp.AppStore) ? comp.AppStore : comp.AppStore ? [comp.AppStore] : [];
190
+ const android = Array.isArray(comp.GooglePlay) ? comp.GooglePlay : comp.GooglePlay ? [comp.GooglePlay] : [];
191
+ const matches = [
192
+ ['US marks: ' + (typeof markOf(row) === 'string' ? plain(markOf(row)) : markOf(row) == null ? 'check incomplete' : 'no match found'), httpsLink(comp.mark)],
193
+ ...ios.map(value => ['iOS: ' + titleAndLink(value)[0], titleAndLink(value)[1]]),
194
+ ...android.map(value => ['Android: ' + titleAndLink(value)[0], titleAndLink(value)[1]]),
195
+ ...[...(comp.sameName?.Norway ?? []), ...(comp.sameName?.EDGAR ?? [])].map(company => [plain(
196
+ [company.name, company.employees != null ? company.employees + ' employees' : null].filter(Boolean).join(', ')), httpsLink(company.url)]),
197
+ ...group.records.filter(row => row.site).map(({ domain, site }) => [
198
+ (site.host ?? domain) + ': ' + plain(site.state ?? site) + (site.title ? ', ' + plain(site.title) : ''),
199
+ httpsLink('https://' + (site.host ?? domain))]),
200
+ ['Web search: ' + plain(row.google?.result ?? 'check incomplete'), httpsLink(row.google?.link)],
201
+ ['iOS search', 'https://apps.apple.com/us/iphone/search?term=' + encodeURIComponent(row.name)],
202
+ ['Android search', 'https://play.google.com/store/search?q=' + encodeURIComponent(row.name) + '&c=apps'],
203
+ ...(row.traction ? [[plain(row.traction.rival ?? row.traction.name ?? ''),
204
+ httpsLink(row.traction.domain && 'https://' + row.traction.domain)],
205
+ ...Object.values(row.traction).flat().filter(value => typeof value === 'string').map(value => [plain(value)])] : []),
206
+ ...(typeof row.reason === 'string' ? row.reason.split(' · ').slice(1).map(value => [plain(value)]) : []),
207
+ ];
208
+ return matches.filter(([text, href]) => text && (href || !/ search$/.test(text)));
209
+ }
210
+
211
+ const anchor = (label, url) => '<a href="' + escape(url) + '">' + escape(label) + '</a>';
212
+ function summaryHtml(line) {
213
+ return Array.from(line.matchAll(/\[([^\]]+)\]\((https:\/\/[^\s)]+)\)/g)).reduce(({ html, offset }, match) =>
214
+ ({ html: html + escape(line.slice(offset, match.index)) + anchor(match[1], match[2]), offset: match.index + match[0].length }),
215
+ { html: '', offset: 0 });
216
+ }
217
+ function paragraph(line) {
218
+ const { html, offset } = summaryHtml(line);
219
+ return '<p>' + html + escape(line.slice(offset)) + '</p>';
220
+ }
221
+ const amountsFor = ({ now, renew }) => [cash(now) ?? 'No price', cash(renew) ?? 'No price'];
222
+
223
+ function rowNote(row) {
224
+ return [row.status, row.priceLabel, row.term > 1 ? row.term + ' years per payment' : null,
225
+ row.jump ? 'Renewal jumps' : null, !row.eligible ? '.no buyer eligibility required' : null,
226
+ row.source, row.checkedAt, row.priceAt ? 'Price checked ' + row.priceAt : null].filter(Boolean).join(' · ');
227
+ }
228
+
229
+ function render(groups, lines, checkedAt, coverage, watch) {
230
+ const title = watch ? 'Domain watch' : 'Domain results';
231
+ const [intro, ...body] = lines;
232
+ const comparison = body.filter(line => /^(?:Cheapest|Best value):/.test(line));
233
+ const before = body.filter(line => !comparison.includes(line)).slice(0, comparison.length ? -1 : undefined);
234
+ const after = comparison.length ? body.slice(-1) : [];
235
+ const sources = watch?.source ? 'Registry: ' + String(watch.source).toUpperCase() :
236
+ Object.entries(coverage ?? {}).map(([name, count]) => name + ' ' + count + '% answered').join(' · ');
237
+ const articles = groups.map((group, index) => {
238
+ const { row } = group;
239
+ const rows = group.records.map(record => {
240
+ const [now, renew] = amountsFor(record);
241
+ return '<tr><th scope="row"><code>' + escape(record.domain) + '</code><small>' + escape(rowNote(record))
242
+ + (record.checkout ? ' · ' + anchor(record.shop ?? 'Check at shop', record.checkout) : '')
243
+ + '</small></th><td>' + escape(now) + '</td><td>' + escape(renew) + '</td></tr>';
244
+ });
245
+ return '<article id="name-' + index + '"><h2>' + escape(row.name) + '</h2>'
246
+ + (row.verdict ? paragraph(plain(row.verdict) + '. ' + evidenceText(row.reason).split(' · ')[0]) + paragraph(signals(group)) : '')
247
+ + '<table><caption>Endings · USD before tax</caption><thead><tr><th scope="col">Ending</th><th scope="col">Today</th><th scope="col">Renewal</th></tr></thead><tbody>'
248
+ + rows.join('') + '</tbody></table>'
249
+ + (row.verdict ? '<details><summary>Trademark, app and web evidence</summary><ul>'
250
+ + details(group).map(([label, url]) => '<li>' + (url ? anchor(label, url) : escape(label)) + '</li>').join('') + '</ul></details>' : '')
251
+ + '</article>';
252
+ });
253
+ const html = '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">'
254
+ + '<meta name="referrer" content="no-referrer"><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; style-src \'unsafe-inline\'; base-uri \'none\'; form-action \'none\'">'
255
+ + '<title>' + title + ' | Domain Hound</title><style>' + receiptStyle + '</style></head><body><main>'
256
+ + '<header><small>Domain Hound</small><h1>' + title + '</h1><time>' + escape(checkedAt) + '</time></header><section>'
257
+ + [intro, ...before].filter(Boolean).map(paragraph).join('')
258
+ + (comparison.length ? '<div class="comparison">' + comparison.map(paragraph).join('') + '</div>' : '')
259
+ + after.map(paragraph).join('') + '</section>'
260
+ + (groups.length > 1 ? '<nav aria-label="Jump to a name">' + groups.map(({ row }, index) => anchor(row.name, '#name-' + index)).join(' ') + '</nav>' : '')
261
+ + articles.join('') + '<footer>' + (sources ? paragraph(sources) : '') + '<p>You hold the leash.</p></footer></main></body></html>\n';
262
+ const md = ['# ' + title, '', 'Domain Hound · ' + checkedAt, '', ...lines, '',
263
+ ...groups.flatMap(group => ['## ' + markdown(group.row.name), '',
264
+ ...(group.row.verdict ? [markdown(group.row.verdict + '. ' + group.row.reason), markdown(signals(group)), ''] : []),
265
+ '| Ending | Today (USD) | Renewal (USD) | Evidence | Shop |', '| --- | --- | --- | --- | --- |',
266
+ ...group.records.map(record => '| ' + [record.domain, ...amountsFor(record), markdown(rowNote(record)),
267
+ record.checkout ? '[' + markdown(record.shop ?? 'Check at shop') + '](' + record.checkout + ')' : ''].join(' | ') + ' |'),
268
+ '', ...(group.row.verdict ? details(group).map(([label, url]) => '- ' + (url ? '[' + markdown(label) + '](' + url + ')' : markdown(label))) : []), '']),
269
+ ...(sources ? [markdown(sources), ''] : []), 'You hold the leash.', ''].join('\n');
270
+ return { html, md };
271
+ }
272
+
273
+ export async function backgroundCommand(filename, env = process.env, platform = process.platform) {
274
+ if (env.DOMAIN_HOUND_OPEN === 'off' || env.CI || env.DOMAIN_HOUND_HEADLESS || env.SSH_CONNECTION || env.SSH_TTY) return null;
275
+ if (platform === 'darwin') {
276
+ const console = await stat('/dev/console').catch(() => null);
277
+ if (console?.uid === userInfo().uid) return ['/usr/bin/open', ['-g', filename]];
278
+ }
279
+ if (platform === 'win32' && /^(?:Console|RDP-Tcp#\d+)$/i.test(env.SESSIONNAME ?? '')) {
280
+ // SW_SHOWNOACTIVATE is forwarded to the file association handler. The existing browser may ignore it.
281
+ const path = Buffer.from(filename, 'utf8').toString('base64');
282
+ const script = `Add-Type -Namespace DomainHound -Name Shell -MemberDefinition @'
283
+ [System.Runtime.InteropServices.DllImport("shell32.dll", CharSet=System.Runtime.InteropServices.CharSet.Unicode, ExactSpelling=true)]
284
+ public static extern System.IntPtr ShellExecuteW(System.IntPtr parent, string verb, string file, string args, string directory, int show);
285
+ '@
286
+ $file = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${path}'))
287
+ $result = [DomainHound.Shell]::ShellExecuteW([IntPtr]::Zero, 'open', $file, $null, $null, 4)
288
+ if ($result.ToInt64() -le 32) { exit 1 }`;
289
+ return ['powershell.exe', ['-NoProfile', '-NonInteractive', '-STA', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')]];
290
+ }
291
+ if (platform === 'linux' && env.WAYLAND_DISPLAY && env.DBUS_SESSION_BUS_ADDRESS) {
292
+ // Leave activation to the compositor without giving the browser a startup or activation token.
293
+ const { XDG_ACTIVATION_TOKEN, DESKTOP_STARTUP_ID, ...backgroundEnv } = env;
294
+ return ['gio', ['open', pathToFileURL(filename).href], backgroundEnv];
295
+ }
296
+ return null;
297
+ }
298
+
299
+ async function writePrivate(filename, content) {
300
+ const temporary = filename + '.' + randomUUID() + '.tmp';
301
+ try {
302
+ await writeFile(temporary, content, { flag: 'wx', mode: 0o600 });
303
+ await rename(temporary, filename);
304
+ } finally {
305
+ await unlink(temporary).catch(() => {});
306
+ }
307
+ }
308
+
309
+ async function prune(directory, current) {
310
+ const owned = /^(?:\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-[a-z0-9-]+-[a-f0-9]{8}\.(?:html|md)|session-[a-f0-9]{8}\.html)$/;
311
+ const files = (await readdir(directory)).filter(file => owned.test(file));
312
+ const groups = new Map();
313
+ for (const file of files) {
314
+ const base = file.slice(0, file.lastIndexOf('.'));
315
+ if (!groups.has(base)) groups.set(base, []);
316
+ groups.get(base).push(file);
317
+ }
318
+ const ranked = await Promise.all([...groups].map(async ([base, entries]) => ({ base, entries,
319
+ at: (await stat(join(directory, entries[0])).catch(() => null))?.mtimeMs ?? 0,
320
+ })));
321
+ ranked.sort((a, b) => Number(b.base === current) - Number(a.base === current) || b.at - a.at || b.base.localeCompare(a.base));
322
+ let slots = 20;
323
+ for (const { base, entries, at } of ranked) {
324
+ // A second MCP process may be committing a twin. Leave a recent incomplete pair alone.
325
+ if (!base.startsWith('session-') && entries.length === 1 && Date.now() - at < 60_000) continue;
326
+ if (entries.length <= slots) {
327
+ slots -= entries.length;
328
+ continue;
329
+ }
330
+ await Promise.all(entries.map(file => unlink(join(directory, file)).catch(() => {})));
331
+ }
332
+ }
333
+
334
+ export function resultPages({ env = process.env,
335
+ directory = env.DOMAIN_HOUND_RESULTS_DIR || join(homedir(), '.domain-hound', 'results') } = {}) {
336
+ const session = randomUUID().slice(0, 8);
337
+ let writes = Promise.resolve();
338
+ return (data, args, { triage = false, watch = false } = {}) => {
339
+ const work = writes.then(async () => {
340
+ const at = data.checkedAt ?? new Date().toISOString();
341
+ const groups = watch ? [] : resultGroups(data);
342
+ const lines = watch ? data.say.split('\n') : summary(groups, args, triage);
343
+ const title = watch ? data.domain : groups[0]?.row.name;
344
+ await mkdir(directory, { recursive: true, mode: 0o700 });
345
+ // If a caller points us at a shared directory, don't expose the searched name in its listing.
346
+ const privateListing = process.platform === 'win32' || ((await stat(directory)).mode & 0o077) === 0;
347
+ const slug = (privateListing && normalizeName(String(title).split('.')[0]) || 'results').slice(0, 30);
348
+ const base = new Date().toISOString().replaceAll(/[:.]/g, '-') + '-' + slug + '-' + randomUUID().slice(0, 8);
349
+ const filename = resolve(directory, base + '.html');
350
+ const page = render(groups, lines, at, data.sources, watch ? data : null);
351
+ const markdownPath = resolve(directory, base + '.md');
352
+ await writePrivate(markdownPath, page.md);
353
+ try {
354
+ await writePrivate(filename, page.html);
355
+ } catch (error) {
356
+ await unlink(markdownPath).catch(() => {});
357
+ throw error;
358
+ }
359
+ const exact = !triage && groups.length === 1 && groups[0].row.name.includes('.');
360
+ if (!watch && !exact) {
361
+ const latest = resolve(directory, 'session-' + session + '.html');
362
+ await backgroundCommand(latest, env).then(async command => {
363
+ if (!command) return;
364
+ await writePrivate(latest, page.html);
365
+ const [executable, args, launchEnv] = command;
366
+ const browser = spawn(executable, args, { stdio: 'ignore', windowsHide: true, env: launchEnv });
367
+ browser.on('error', () => {});
368
+ browser.unref();
369
+ }).catch(() => {});
370
+ }
371
+ await prune(directory, base).catch(() => {});
372
+ const url = pathToFileURL(filename).href.replaceAll('(', '%28').replaceAll(')', '%29');
373
+ const say = [...lines, 'All endings: [Results page](' + url + ')'].join('\n');
374
+ const { receiptDetails, say: priorSay, display: priorDisplay, ...structured } = data;
375
+ if (triage && receiptDetails) structured.names = structured.names.map((row, index) => ({
376
+ ...row, details: { ...row.details, sites: receiptDetails[index]?.details?.sites ?? {} },
377
+ }));
378
+ return { display: say, say, ...structured, checkedAt: at, resultPage: url };
379
+ });
380
+ writes = work.catch(() => {});
381
+ return work;
382
+ };
383
+ }
package/server.json CHANGED
@@ -4,21 +4,12 @@
4
4
  "title": "Domain Hound",
5
5
  "description": "Check domain availability and prices, and screen product names, from your AI assistant.",
6
6
  "websiteUrl": "https://domainhound.dev",
7
- "version": "0.1.3",
7
+ "version": "0.1.4",
8
8
  "packages": [
9
9
  {
10
10
  "registryType": "npm",
11
11
  "identifier": "domain-hound",
12
- "version": "0.1.3",
13
- "transport": {
14
- "type": "stdio"
15
- }
16
- },
17
- {
18
- "registryType": "mcpb",
19
- "identifier": "https://github.com/lars-hv/domain-hound/releases/download/v0.1.3/domain-hound-0.1.3.mcpb",
20
- "version": "0.1.3",
21
- "fileSha256": "4deb38d2cffd4f8165e3828a05ea84c37584a0558beb9135156c3b5e526937b9",
12
+ "version": "0.1.4",
22
13
  "transport": {
23
14
  "type": "stdio"
24
15
  }
package/server.mjs CHANGED
@@ -1,11 +1,13 @@
1
- import { geoInstruction, googleSearchInstruction, namingRecipe, showAsIs } from './clis/domain-check/naming-method.mjs';
1
+ import { geoInstruction, namingRecipe } from './clis/domain-check/naming-method.mjs';
2
2
  import { asciiDomain, defaultEndings, normalizeName, restrictedEndings, 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
7
  import { progressPrefix } from './clis/domain-check/progress.mjs';
8
- import { attributed, checkText, errorText, progressText, triageText } from './display.mjs';
8
+ import { attributed, errorText, progressText } from './display.mjs';
9
+ import { resultPages } from './results.mjs';
10
+ import { watchDomain, watchTool } from './watch.mjs';
9
11
 
10
12
  // The capability ships inside the package; tests inject another directory through serve({ cwd }).
11
13
  export const capabilityDir = fileURLToPath(new URL('./clis/domain-check/', import.meta.url));
@@ -16,7 +18,7 @@ const serverVersion = JSON.parse(readFileSync(new URL('./package.json', import.m
16
18
  const timeoutMs = 14_000;
17
19
  // A lookup still running after this long is stopped.
18
20
  const maxLookupMs = 120_000;
19
- // A finished lookup whose caller already had a progress answer waits this long for the repeated call.
21
+ // Keep completed evidence stable for repeated calls during a short naming session.
20
22
  const keepFinishedMs = 120_000;
21
23
  const versions = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
22
24
 
@@ -29,17 +31,20 @@ const nameSchema = { type: 'string', minLength: 1, maxLength: 127, pattern: entr
29
31
  const endingsSchema = {
30
32
  type: 'array', minItems: 1, maxItems: 10, uniqueItems: true,
31
33
  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.',
34
+ description: 'Endings to consider for the recommendation, in preference order. For .com only use ["com"]. The page still shows all ten endings for bare names.',
33
35
  };
34
36
  const lookupProperties = {
35
37
  ai: { type: 'boolean', description: 'Legacy option. .ai is now included by default.' },
36
38
  endings: endingsSchema,
39
+ budget: { type: 'number', minimum: 0, maximum: 1000000,
40
+ description: 'Maximum upfront price in USD when the person gave a cap. Carry it from the registry screen into triage.' },
37
41
  eligible: { type: 'array', uniqueItems: true, items: { type: 'string', enum: restrictedEndings },
38
42
  description: 'Restricted endings the buyer qualifies to register. Pass ["no"] only when the buyer qualifies for .no.' },
39
43
  };
44
+ 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
45
  const checkTool = {
41
46
  name: 'check_domains',
42
- description: showAsIs + ' '
47
+ description: relay + ' '
43
48
  + '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
49
  + '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. '
45
50
  + 'For a bare name, put any ending preference in endings. Use exact lookup for a full domain. '
@@ -65,14 +70,15 @@ const checkTool = {
65
70
  };
66
71
 
67
72
  const legacyTool = { ...checkTool, name: 'broker_find',
68
- description: showAsIs + ' Legacy alias for Domain Hound check_domains, same input. Never buys.' };
73
+ description: relay + ' Legacy alias for Domain Hound check_domains, same input. Never buys.' };
69
74
 
70
75
  const triageTool = {
71
76
  name: 'triage_names',
72
- description: showAsIs + ' '
77
+ description: relay + ' '
73
78
  + '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. '
74
79
  + '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.',
80
+ + 'Put the name the person came with first. Fill geo for each name from memory, never from search. '
81
+ + '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
82
  inputSchema: {
77
83
  type: 'object',
78
84
  properties: {
@@ -93,7 +99,7 @@ const triageTool = {
93
99
 
94
100
  const namingTool = {
95
101
  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.',
102
+ 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, relay say as written.',
97
103
  inputSchema: { type: 'object', properties: {
98
104
  about: { type: 'string', minLength: 1, maxLength: 512, description: 'An optional one-sentence product description.' },
99
105
  }, additionalProperties: false },
@@ -117,6 +123,7 @@ function queryValue(value) {
117
123
  throw new Error('query is empty. Enter one name or exact domain in query, such as lanternbay or lanternbay.me.');
118
124
  }
119
125
  const query = value.toLowerCase();
126
+ if (query.split('.')[0].length > 63) throw new Error('This name is too long. A DNS label can have up to 63 characters.');
120
127
  if (!entryPattern.test(query) || !dnsForm(query)) {
121
128
  throw new Error('query ' + showValue(value) + ' is not valid. Give a name like lanternbay or a domain like lanternbay.me in query.');
122
129
  }
@@ -133,6 +140,7 @@ function batchNames(names) {
133
140
  throw new Error('names[' + index + '] is empty. Use a bare name such as lanternbay or an exact domain such as lanternbay.me.');
134
141
  }
135
142
  const name = value.toLowerCase();
143
+ if (name.split('.')[0].length > 63) throw new Error('names[' + index + '] is too long. A DNS label can have up to 63 characters.');
136
144
  if (!entryPattern.test(name) || !dnsForm(name)) {
137
145
  throw new Error('names[' + index + '] ' + showValue(value) + ' is not valid. Give a name like lanternbay or a domain like lanternbay.me in names.');
138
146
  }
@@ -142,6 +150,9 @@ function batchNames(names) {
142
150
 
143
151
  function lookupFlags(args) {
144
152
  const flags = [];
153
+ if (Object.hasOwn(args, 'budget') && (!Number.isFinite(args.budget) || args.budget < 0 || args.budget > 1_000_000)) {
154
+ throw new Error('The upfront budget must be a dollar amount between 0 and 1,000,000.');
155
+ }
145
156
  if (Object.hasOwn(args, 'eligible')) {
146
157
  if (!validEligibility(args.eligible)) throw new Error('Eligible endings must list supported restricted endings, such as no.');
147
158
  if (args.eligible.length) flags.push('--eligible', args.eligible.join(','));
@@ -177,8 +188,8 @@ function cliArguments(args) {
177
188
  if (args.shortlist && (hasQuery || names.some(name => name.includes('.')))) {
178
189
  throw new Error('Use shortlist only with bare names in names.');
179
190
  }
180
- if (hasQuery) return ['--agent', queryValue(args.query), ...flags];
181
- return ['--agent', '--names', names.join(','), ...flags];
191
+ if (hasQuery) return ['--agent', queryValue(args.query), '--receipt', ...flags];
192
+ return ['--agent', '--names', names.join(','), '--receipt', ...flags];
182
193
  }
183
194
 
184
195
  // The rows a progress answer lists, in input order: a bare name with every requested ending, an exact domain as itself.
@@ -237,7 +248,7 @@ function triageArguments(args) {
237
248
  flags.push('--about', args.about);
238
249
  }
239
250
  if (Object.hasOwn(args, 'geo')) flags.push('--geo', JSON.stringify(geoValue(args.geo, args.names)));
240
- return ['--triage', args.names.join(','), '--compact', ...flags];
251
+ return ['--triage', args.names.join(','), '--compact', '--receipt', ...flags];
241
252
  }
242
253
 
243
254
  // The capability prints one JSON object on stdout.
@@ -326,6 +337,7 @@ async function within(lookup, budget) {
326
337
 
327
338
  export async function serve({
328
339
  input = process.stdin, output = process.stdout, cwd = capabilityDir, timeout = timeoutMs, maxLookup = maxLookupMs,
340
+ pages = resultPages(), watch = watchDomain,
329
341
  } = {}) {
330
342
  const send = response => output.write(JSON.stringify({ jsonrpc: '2.0', ...response }) + '\n');
331
343
  const error = (id, code, message) => send({ id, error: { code, message } });
@@ -351,8 +363,7 @@ export async function serve({
351
363
  lookups.set(key, lookup);
352
364
  lookup.done.then(() => {
353
365
  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) {
366
+ if (lookup.outcome.error && !lookup.collect) {
356
367
  lookups.delete(key);
357
368
  return;
358
369
  }
@@ -368,16 +379,16 @@ export async function serve({
368
379
  return errorResult('Domain Hound could not format the progress.');
369
380
  }
370
381
  }
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);
382
+ if (lookup.outcome.error) {
383
+ if (lookups.get(key) === lookup) lookups.delete(key);
384
+ return errorResult(lookup.outcome.error);
385
+ }
374
386
  try {
375
- return toolResult(render(lookup.outcome.data));
387
+ return toolResult(JSON.stringify(await render(lookup.outcome.data)));
376
388
  } catch {
377
389
  return errorResult('Domain Hound could not format the result.');
378
390
  }
379
391
  }
380
- let shortlist;
381
392
  let initialized = false;
382
393
  let negotiated = false;
383
394
 
@@ -412,7 +423,7 @@ export async function serve({
412
423
  }
413
424
  if (method !== 'tools/list' && method !== 'tools/call') return error(id, -32601, 'Method not found');
414
425
  if (!initialized) return error(id, -32000, 'Domain Hound has not been initialized');
415
- if (method === 'tools/list') return reply({ tools: [checkTool, triageTool, namingTool, legacyTool] });
426
+ if (method === 'tools/list') return reply({ tools: [checkTool, triageTool, namingTool, legacyTool, watchTool] });
416
427
  const { name, arguments: args } = params ?? {};
417
428
  if (name === namingTool.name) {
418
429
  if (args !== undefined && (!isObject(args) || Object.keys(args).some(key => key !== 'about') ||
@@ -420,22 +431,29 @@ export async function serve({
420
431
  args.about.length > namingTool.inputSchema.properties.about.maxLength)))) {
421
432
  return reply(errorResult('naming_method accepts an optional about description of up to 512 characters.'));
422
433
  }
423
- shortlist = undefined;
424
434
  return reply(toolResult(JSON.stringify({ display: attributed(namingRecipe(args?.about?.slice(0, 160))) })));
425
435
  }
436
+ if (name === watchTool.name) {
437
+ let result;
438
+ try {
439
+ result = await watch(args);
440
+ } catch (problem) {
441
+ return reply(errorResult(problem.message));
442
+ }
443
+ // Preserve a successful submission response even if disk space or local permissions prevent a receipt.
444
+ const data = await pages(result, {}, { watch: true }).catch(() => ({ ...result, display: result.say }));
445
+ return reply(toolResult(JSON.stringify(data)));
446
+ }
426
447
  const purchase = isObject(args) && args.purchase === true;
427
448
  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 }),
449
+ return reply(await runLookup(args, triageArguments, triageRows, data => pages(data, args, { triage: true }),
430
450
  (progress, timing) => progressText(progress, { ...timing, triage: true, purchase })));
431
451
  }
432
452
  if (name !== checkTool.name && name !== legacyTool.name) return error(id, -32602, 'Unknown tool');
433
453
  // An exact lookup includes the purchase line while its registration status is unsettled.
434
454
  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 })));
455
+ return reply(await runLookup(args, cliArguments, checkRows, data => pages(data, args),
456
+ (progress, timing) => progressText(progress, { ...timing, purchase: purchase || exact })));
439
457
  }
440
458
 
441
459
  const lines = createInterface({ input, terminal: false, crlfDelay: Infinity });
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
+ }