domain-hound 0.1.1 → 0.1.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "domain-hound",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Check domains, compare registrar prices, and screen product names from your MCP client.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -39,12 +39,13 @@
39
39
  "clis/domain-check/price-catalog.mjs",
40
40
  "clis/domain-check/price-snapshot.json",
41
41
  "clis/domain-check/prices.mjs",
42
+ "clis/domain-check/progress.mjs",
42
43
  "clis/domain-check/registry.mjs",
43
- "clis/domain-check/spaceship-feed.mjs",
44
44
  "clis/domain-check/terms.json",
45
45
  "clis/domain-check/traction.mjs",
46
46
  "clis/domain-check/triage-sources.mjs",
47
47
  "clis/domain-check/triage.mjs",
48
+ "assets/",
48
49
  ".claude-plugin/plugin.json",
49
50
  ".claude-plugin/marketplace.json",
50
51
  ".agents/plugins/marketplace.json",
@@ -55,7 +56,8 @@
55
56
  "scripts": {
56
57
  "test": "node --test server.test.mjs clis/domain-check/*.test.mjs clis/domain-check/test.mjs",
57
58
  "smoke": "node scripts/smoke.mjs",
58
- "snapshot-prices": "node scripts/snapshot-prices.mjs"
59
+ "snapshot-prices": "node scripts/snapshot-prices.mjs",
60
+ "build-mcpb": "node scripts/build-mcpb.mjs"
59
61
  },
60
62
  "dependencies": {
61
63
  "parse5": "^7.3.0"
package/plugin.json CHANGED
@@ -1,14 +1,32 @@
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.1",
5
- "description": "Check domains, compare registrar prices, and screen product names.",
6
- "author": { "name": "Lars Hvinden" },
4
+ "version": "0.1.3",
5
+ "description": "Check domain availability and prices, and screen product names, from your AI assistant.",
6
+ "author": {
7
+ "name": "Lars Hvinden"
8
+ },
7
9
  "homepage": "https://domainhound.dev",
8
10
  "license": "MIT",
9
11
  "extensions": {
10
12
  "com.openai": {
11
- "interface": { "displayName": "Domain Hound" }
13
+ "interface": {
14
+ "displayName": "Domain Hound",
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.",
17
+ "developerName": "Lars Hvinden",
18
+ "category": "Developer Tools",
19
+ "capabilities": [
20
+ "Check domain availability",
21
+ "Compare registrar prices",
22
+ "Screen product names"
23
+ ],
24
+ "websiteURL": "https://domainhound.dev",
25
+ "privacyPolicyURL": "https://domainhound.dev/privacy/",
26
+ "supportURL": "https://github.com/lars-hv/domain-hound/issues",
27
+ "logo": "./assets/icon-1024.png",
28
+ "composerIcon": "./assets/icon-512.png"
29
+ }
12
30
  }
13
31
  }
14
32
  }
package/server.json CHANGED
@@ -2,15 +2,26 @@
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
3
  "name": "dev.domainhound/domain-hound",
4
4
  "title": "Domain Hound",
5
- "description": "Check domains, compare registrar prices, and screen product names.",
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.1",
7
+ "version": "0.1.3",
8
8
  "packages": [
9
9
  {
10
10
  "registryType": "npm",
11
11
  "identifier": "domain-hound",
12
- "version": "0.1.1",
13
- "transport": { "type": "stdio" }
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",
22
+ "transport": {
23
+ "type": "stdio"
24
+ }
14
25
  }
15
26
  ]
16
27
  }
package/server.mjs CHANGED
@@ -1,27 +1,35 @@
1
1
  import { geoInstruction, googleSearchInstruction, namingRecipe, showAsIs } from './clis/domain-check/naming-method.mjs';
2
- import { normalizeName, restrictedEndings, validEligibility } from './clis/domain-check/name-search.mjs';
3
- import { execFile } from 'node:child_process';
2
+ import { asciiDomain, defaultEndings, normalizeName, restrictedEndings, validEligibility } from './clis/domain-check/name-search.mjs';
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 { promisify } from 'node:util';
8
- import { attributed, checkText, errorText, triageText } from './display.mjs';
7
+ import { progressPrefix } from './clis/domain-check/progress.mjs';
8
+ import { attributed, checkText, errorText, progressText, triageText } from './display.mjs';
9
9
 
10
- const runFile = promisify(execFile);
11
10
  // The capability ships inside the package; tests inject another directory through serve({ cwd }).
12
11
  export const capabilityDir = fileURLToPath(new URL('./clis/domain-check/', import.meta.url));
13
12
  // One version for the server, package and manifests; the release workflow checks the tag against it.
14
13
  const serverVersion = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version;
15
- const timeoutMs = 14_950;
16
- const timeoutMessage = 'Domain Hound timed out after 15 seconds.';
14
+ // Each call answers within this budget, leaving a second under the clients' 15-second limit for formatting and
15
+ // transport. A lookup that needs longer keeps running, and a repeated call with the same input collects it.
16
+ const timeoutMs = 14_000;
17
+ // A lookup still running after this long is stopped.
18
+ const maxLookupMs = 120_000;
19
+ // A finished lookup whose caller already had a progress answer waits this long for the repeated call.
20
+ const keepFinishedMs = 120_000;
17
21
  const versions = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
18
22
 
19
- const entryPattern = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.(?:[A-Za-z]{2,63}|[xX][nN]--[A-Za-z0-9](?:[A-Za-z0-9-]{0,57}[A-Za-z0-9])?))?$/;
23
+ // Letters may be non-ASCII (æøå, é): such a name or domain is checked as its punycode form. The ranges skip
24
+ // spaces, punctuation and symbols without needing a Unicode-aware regular expression in the client.
25
+ const letter = 'A-Za-z0-9\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u1FFF\\u3040-\\uD7FF\\uF900-\\uFDCF';
26
+ 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])?))?$');
20
28
  const nameSchema = { type: 'string', minLength: 1, maxLength: 127, pattern: entryPattern.source };
21
29
  const endingsSchema = {
22
30
  type: 'array', minItems: 1, maxItems: 10, uniqueItems: true,
23
- items: { type: 'string', enum: ['com', 'dev', 'app', 'me', 'si', 'co', 'io', 'no', 'so', 'ai'] },
24
- description: 'Optional filter. All ten endings, including .ai, are checked by default.',
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.',
25
33
  };
26
34
  const lookupProperties = {
27
35
  ai: { type: 'boolean', description: 'Legacy option. .ai is now included by default.' },
@@ -31,20 +39,25 @@ const lookupProperties = {
31
39
  };
32
40
  const checkTool = {
33
41
  name: 'check_domains',
34
- description: 'Use Domain Hound to check domains. Two input forms: query for one name or exact domain, e.g. {"query":"oakenroom.me"} or {"query":"oakenroom"}; names for a batch of up to 20 bare names, exact domains or both, e.g. {"names":["oakenroom","quietbook","oakenroom.me"]}. A dot means an exact domain; a bare name checks all ten endings, including .ai. For a single exact-domain question, call once with query and answer from that result. For a list, make one names call and report the results as returned. An unconfirmed result is enough for an availability answer. An exact quote for a favorite is a separate request. '
35
- + 'Returns display (ready-to-copy Markdown that accounts for every requested name), then complete, shared checkedAt and priceListDate, optional best (confirmed, with buyUrl), and per name taken, resale, free (cheapest first) and shop_check. Read first payment, minimum term and renewal inline or in listPrices keyed by ending; shopCheckWhy gives the reason an ending needs a shop check. The legend and shop buyUrlTemplate values explain the fields and links. '
36
- + showAsIs + ' For an exact lookup, copy the entire display including the purchase line. If asked to buy or register, explicitly say you cannot buy domains or complete checkout, including when the domain is taken. Give the price and checkout link only when an offer exists. If a domain is taken, say it is taken. Suggest free endings already in that result. Look up alternatives only if the person asks for alternatives. '
37
- + 'Returns every option; let the person choose. Never buys. For naming help, call naming_method first when generating new names. Use triage_names alone to screen an existing name for conflicts. When shortlist is true, pass a single DNS label per name (Quiet Otter becomes quietotter).',
42
+ description: showAsIs + ' '
43
+ + '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. '
45
+ + 'For a bare name, put any ending preference in endings. Use exact lookup for a full domain. '
46
+ + 'For a batch, make one call and report check-at-shop endings as returned. Recheck only when the person asks. '
47
+ + 'Set confirm true only when the person asks for a live shop check (slower). '
48
+ + 'Prices are list prices unless marked confirmed at a shop; premium names show the shop price or "premium, price at shop". For new names, call naming_method first; to screen an existing name, use triage_names. With shortlist true, pass one DNS label per name (Quiet Otter becomes quietotter).',
38
49
  inputSchema: {
39
50
  type: 'object',
40
51
  properties: {
41
52
  ...lookupProperties,
42
53
  query: { ...nameSchema,
43
- description: 'One name or exact domain, e.g. "oakenroom.me" or "oakenroom". Supply either query or names.' },
54
+ description: 'One name or exact domain, e.g. "lanternbay.me" or "lanternbay". Supply either query or names.' },
44
55
  names: { type: 'array', minItems: 1, maxItems: 20,
45
56
  items: nameSchema,
46
- description: '1 to 20 bare names, exact domains or both, e.g. ["oakenroom","quietbook","oakenroom.me"]. Use one DNS label for a bare name, with no spaces or dots. A dot means an exact domain. Supply either names or query.' },
57
+ description: '1 to 20 bare names, exact domains or both, e.g. ["lanternbay","quietbook","lanternbay.me"]. Use one DNS label for a bare name, with no spaces or dots. A dot means an exact domain. Supply either names or query.' },
47
58
  shortlist: { type: 'boolean', description: 'Use true for the preliminary bare-name batch specified by naming_method.' },
59
+ purchase: { type: 'boolean', description: 'Pass true when asked to buy or register, even for an exact domain that may be taken. State the checkout limitation from the display in the answer.' },
60
+ confirm: { type: 'boolean', description: 'True only when the person explicitly asks for a live shop check. Uses an optional headless browser and is slower.' },
48
61
  },
49
62
  additionalProperties: false,
50
63
  oneOf: [{ required: ['query'] }, { required: ['names'] }],
@@ -52,21 +65,21 @@ const checkTool = {
52
65
  };
53
66
 
54
67
  const legacyTool = { ...checkTool, name: 'broker_find',
55
- description: 'Legacy alias for the Domain Hound check_domains tool. Same input forms: {"query":"oakenroom.me"} or {"names":["oakenroom","oakenroom.me"]}. ' + showAsIs + ' Returns every option; let the person choose.' };
68
+ description: showAsIs + ' Legacy alias for Domain Hound check_domains, same input. Never buys.' };
56
69
 
57
70
  const triageTool = {
58
71
  name: 'triage_names',
59
- description: 'If asked whether an existing name is safe, call Domain Hound triage_names directly once with that bare name. Use this tool to screen 1 to 20 product names, e.g. {"names":["Quiet Otter","Hush Room"],"about":"book quiet meeting rooms"}. Checks same-name competitors, live US marks, iOS and Android apps, handles, memorability and every domain ending, including .ai. '
60
- + 'Returns top (up to three ranked names), sources (coverage) and display (ready-to-copy Markdown with the top picks first and one row per name with its verdict and reason exactly, every free ending with today\'s payment and renewal, and a checkout link for the cheapest), then per name verdict, reason, free (endings free at the registry, cheapest first), own (this name\'s prices where they differ), taken, shop_check, buy (checkout link for the cheapest free ending) and competition evidence; prices holds the standard price per ending (now = payment today for term years, renew = renewal). '
61
- + 'Show the cheapest eligible one-year price in each candidate row. Restricted endings such as .no remain listed with their eligibility note and are excluded from cheapest and Best value unless the buyer qualifies. Best value requires a known renewal at most twice the first payment. '
62
- + 'Verdicts weigh each same-name rival by its SEO and GEO traction: a strong rival (David vs Goliath) or a same-business rival with traction means Avoid, another business with some traction means Check first, and small or dormant same-name uses are notes after the reason that never lower the verdict. '
63
- + 'Fill geo for every name from your own memory before calling. ' + googleSearchInstruction + ' Copy the full display in the answer. Update only the Google result. Keep the verdict, reason, same-name notes, and each source on its own line with its direct link. Keep the cheapest eligible payment in every row even when prices match. Use the exact labels Google, App Store (iOS), and Google Play (Android). Do not omit or paraphrase rows. In a dense batch, account for every name in the structured results. Let the person choose.',
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. '
74
+ + '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.',
64
76
  inputSchema: {
65
77
  type: 'object',
66
78
  properties: {
67
79
  ...lookupProperties,
68
80
  names: { type: 'array', minItems: 1, maxItems: 20, items: { type: 'string', minLength: 1, maxLength: 100 },
69
81
  description: '1 to 20 bare names without endings, e.g. ["Quiet Otter","Hush Room"].' },
82
+ purchase: { type: 'boolean', description: 'True when the person asks to buy or register a domain.' },
70
83
  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.' },
71
84
  about: { type: 'string', minLength: 1, maxLength: 160, description: 'A short description of what your product does, to identify overlapping sites and apps.' },
72
85
  geo: { type: 'object', maxProperties: 20,
@@ -80,26 +93,32 @@ const triageTool = {
80
93
 
81
94
  const namingTool = {
82
95
  name: 'naming_method',
83
- description: 'Get the Domain Hound naming recipe when asked to generate new product name ideas. For an existing name, use triage_names directly. Start with the final triage display; the recipe and the name batch are intermediate. '
84
- + googleSearchInstruction,
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.',
85
97
  inputSchema: { type: 'object', properties: {
86
- about: { type: 'string', minLength: 1, maxLength: 160, description: 'An optional brief product description.' },
98
+ about: { type: 'string', minLength: 1, maxLength: 512, description: 'An optional one-sentence product description.' },
87
99
  }, additionalProperties: false },
88
100
  };
89
101
 
90
102
  const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
91
- const textResult = (text, isError = false) => ({ content: [{ type: 'text', text }], isError });
92
- const errorResult = message => textResult(errorText(message), true);
103
+ // The person sees one text block: the display. The structured result repeats the display first, then the fields.
104
+ function toolResult(json, isError = false) {
105
+ const structured = JSON.parse(json);
106
+ return { content: [{ type: 'text', text: structured.display }], structuredContent: structured, isError };
107
+ }
108
+ const errorResult = message => toolResult(errorText(message), true);
93
109
 
94
110
  const showValue = value => JSON.stringify(String(value).slice(0, 40));
95
111
 
112
+ // The DNS form of a valid entry: a bare name as one label, an exact domain as itself, both in punycode when needed.
113
+ const dnsForm = value => value.includes('.') ? asciiDomain(value) : normalizeName(value);
114
+
96
115
  function queryValue(value) {
97
116
  if (typeof value !== 'string' || !value.trim()) {
98
- throw new Error('query is empty. Enter one name or exact domain in query, such as oakenroom or oakenroom.me.');
117
+ throw new Error('query is empty. Enter one name or exact domain in query, such as lanternbay or lanternbay.me.');
99
118
  }
100
119
  const query = value.toLowerCase();
101
- if (!entryPattern.test(query)) {
102
- throw new Error('query ' + showValue(value) + ' is not valid. Give a name like oakenroom or a domain like oakenroom.me in query.');
120
+ if (!entryPattern.test(query) || !dnsForm(query)) {
121
+ throw new Error('query ' + showValue(value) + ' is not valid. Give a name like lanternbay or a domain like lanternbay.me in query.');
103
122
  }
104
123
  return query;
105
124
  }
@@ -111,11 +130,11 @@ function batchNames(names) {
111
130
  }
112
131
  return names.map((value, index) => {
113
132
  if (typeof value !== 'string' || !value.trim()) {
114
- throw new Error('names[' + index + '] is empty. Use a bare name such as oakenroom or an exact domain such as oakenroom.me.');
133
+ throw new Error('names[' + index + '] is empty. Use a bare name such as lanternbay or an exact domain such as lanternbay.me.');
115
134
  }
116
135
  const name = value.toLowerCase();
117
- if (!entryPattern.test(name)) {
118
- throw new Error('names[' + index + '] ' + showValue(value) + ' is not valid. Give a name like oakenroom or a domain like oakenroom.me in names.');
136
+ if (!entryPattern.test(name) || !dnsForm(name)) {
137
+ throw new Error('names[' + index + '] ' + showValue(value) + ' is not valid. Give a name like lanternbay or a domain like lanternbay.me in names.');
119
138
  }
120
139
  return name;
121
140
  });
@@ -129,13 +148,17 @@ function lookupFlags(args) {
129
148
  }
130
149
  if (Object.hasOwn(args, 'ai') && typeof args.ai !== 'boolean') throw new Error('ai must be a boolean.');
131
150
  if (args.ai) flags.push('--ai');
151
+ for (const flag of ['purchase', 'confirm']) {
152
+ if (Object.hasOwn(args, flag) && typeof args[flag] !== 'boolean') throw new Error(flag + ' must be a boolean.');
153
+ }
154
+ // The headless browser runs only on this explicit request.
155
+ if (args.confirm === true) flags.push('--confirm');
132
156
  if (Object.hasOwn(args, 'endings')) {
133
157
  const endings = args.endings;
134
158
  if (!Array.isArray(endings) || endings.length < 1 || endings.length > 10 ||
135
159
  new Set(endings).size !== endings.length || endings.some(ending => !endingsSchema.items.enum.includes(ending))) {
136
160
  throw new Error('Choose supported domain endings.');
137
161
  }
138
- flags.push('--endings', endings.join(','));
139
162
  }
140
163
  return flags;
141
164
  }
@@ -158,6 +181,25 @@ function cliArguments(args) {
158
181
  return ['--agent', '--names', names.join(','), ...flags];
159
182
  }
160
183
 
184
+ // The rows a progress answer lists, in input order: a bare name with every requested ending, an exact domain as itself.
185
+ function checkRows(args) {
186
+ const names = (Object.hasOwn(args, 'query') ? [queryValue(args.query)] : batchNames(args.names)).map(dnsForm);
187
+ const endings = [...new Set([...(args.endings ?? []), ...defaultEndings])];
188
+ return [...new Set(names)].map(name => name.includes('.')
189
+ ? { name, domains: [name] } : { name, domains: endings.map(ending => name + '.' + ending) });
190
+ }
191
+
192
+ function triageRows(args) {
193
+ const endings = [...new Set([...(args.endings ?? []), ...defaultEndings])];
194
+ const seen = new Set();
195
+ return args.names.flatMap(name => {
196
+ const label = normalizeName(name);
197
+ if (!label || seen.has(label)) return [];
198
+ seen.add(label);
199
+ return [{ name: name.trim(), domains: endings.map(ending => label + '.' + ending) }];
200
+ });
201
+ }
202
+
161
203
  // GEO is the client's own recollection per name: "known: <what it is>" or "unknown", never a search result.
162
204
  function geoValue(geo, names) {
163
205
  const valid = isObject(geo) && Object.keys(geo).length <= 20 && Object.entries(geo).every(([name, text]) =>
@@ -198,17 +240,11 @@ function triageArguments(args) {
198
240
  return ['--triage', args.names.join(','), '--compact', ...flags];
199
241
  }
200
242
 
201
- async function runBroker(args, cwd, timeout) {
202
- let stdout;
203
- let failed = false;
204
- try {
205
- ({ stdout } = await runFile(process.execPath, ['index.mjs', ...args], {
206
- cwd, timeout, killSignal: 'SIGKILL',
207
- }));
208
- } catch (error) {
209
- if (error.killed) throw new Error(timeoutMessage);
210
- failed = true;
211
- stdout = error.stdout;
243
+ // The capability prints one JSON object on stdout.
244
+ function parseOutput(stdout, failed, stoppedAfter) {
245
+ if (stoppedAfter) {
246
+ const seconds = Math.max(1, Math.round(stoppedAfter / 1000));
247
+ throw new Error('Domain Hound stopped the lookup after ' + seconds + (seconds === 1 ? ' second.' : ' seconds.'));
212
248
  }
213
249
  let data;
214
250
  try {
@@ -225,24 +261,122 @@ async function runBroker(args, cwd, timeout) {
225
261
  return data;
226
262
  }
227
263
 
228
- async function runLookup(args, cwd, timeout, buildArgs, render) {
229
- let data;
230
- try {
231
- data = await runBroker(buildArgs(args), cwd, timeout);
232
- } catch (error) {
233
- return errorResult(error.message);
234
- }
235
- try {
236
- return textResult(render(data));
237
- } catch {
238
- return errorResult('Domain Hound could not format the result.');
264
+ // Progress events from the capability: each registry answer and its current stage.
265
+ function readProgress(progress, line) {
266
+ if (!line.startsWith(progressPrefix)) return;
267
+ let event;
268
+ try { event = JSON.parse(line.slice(progressPrefix.length)); } catch { return; }
269
+ if (!isObject(event)) return;
270
+ if (typeof event.domain === 'string' && typeof event.status === 'string' && progress.answers.size < 1000) {
271
+ progress.answers.set(event.domain.slice(0, 127), event.status.slice(0, 20));
239
272
  }
273
+ if (typeof event.stage === 'string') progress.stage = event.stage.slice(0, 20);
240
274
  }
241
275
 
242
- export async function serve({ input = process.stdin, output = process.stdout, cwd = capabilityDir, timeout = timeoutMs } = {}) {
276
+ // Start one capability run. It ends on its own; only the maximum lookup time or server shutdown stops it.
277
+ function startLookup(args, cwd, maxMs) {
278
+ const lookup = { started: performance.now(), progress: { answers: new Map(), stage: null }, finished: false,
279
+ collect: false, outcome: null };
280
+ const child = spawn(process.execPath, ['index.mjs', ...args], {
281
+ cwd, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, DOMAIN_HOUND_PROGRESS: '1' },
282
+ });
283
+ lookup.child = child;
284
+ const chunks = [];
285
+ let size = 0;
286
+ child.stdout.on('data', chunk => {
287
+ size += chunk.length;
288
+ if (size <= 4_000_000) chunks.push(chunk);
289
+ });
290
+ createInterface({ input: child.stderr, crlfDelay: Infinity }).on('line', line => readProgress(lookup.progress, line));
291
+ let stopped = false;
292
+ const limit = setTimeout(() => {
293
+ stopped = true;
294
+ child.kill('SIGKILL');
295
+ }, maxMs);
296
+ lookup.done = new Promise(resolve => {
297
+ let settled = false;
298
+ const finish = failed => {
299
+ if (settled) return;
300
+ settled = true;
301
+ clearTimeout(limit);
302
+ try {
303
+ lookup.outcome = { data: parseOutput(Buffer.concat(chunks).toString('utf8'), failed, stopped && maxMs) };
304
+ } catch (problem) {
305
+ lookup.outcome = { error: problem.message };
306
+ }
307
+ lookup.finished = true;
308
+ resolve();
309
+ };
310
+ child.once('error', () => finish(true));
311
+ child.once('close', code => finish(code !== 0));
312
+ });
313
+ return lookup;
314
+ }
315
+
316
+ // Wait for the lookup while this call's budget lasts. The lookup itself keeps running either way.
317
+ async function within(lookup, budget) {
318
+ let timer;
319
+ const finished = await Promise.race([
320
+ lookup.done.then(() => true),
321
+ new Promise(resolve => { timer = setTimeout(() => resolve(false), Math.max(0, budget)); }),
322
+ ]);
323
+ clearTimeout(timer);
324
+ return finished;
325
+ }
326
+
327
+ export async function serve({
328
+ input = process.stdin, output = process.stdout, cwd = capabilityDir, timeout = timeoutMs, maxLookup = maxLookupMs,
329
+ } = {}) {
243
330
  const send = response => output.write(JSON.stringify({ jsonrpc: '2.0', ...response }) + '\n');
244
331
  const error = (id, code, message) => send({ id, error: { code, message } });
245
332
  const pending = new Set();
333
+ const lookups = new Map();
334
+
335
+ // Join the running or finished lookup for the same input, or start one. Answer within the budget with the
336
+ // result, or with the progress so far while the lookup keeps running for a repeated call to collect.
337
+ async function runLookup(args, buildArgs, rowsFor, render, renderProgress) {
338
+ const started = performance.now();
339
+ let cliArgs;
340
+ let rows;
341
+ try {
342
+ cliArgs = buildArgs(args);
343
+ rows = rowsFor(args);
344
+ } catch (problem) {
345
+ return errorResult(problem.message);
346
+ }
347
+ const key = JSON.stringify(cliArgs);
348
+ let lookup = lookups.get(key);
349
+ if (!lookup) {
350
+ lookup = startLookup(cliArgs, cwd, maxLookup);
351
+ lookups.set(key, lookup);
352
+ lookup.done.then(() => {
353
+ 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) {
356
+ lookups.delete(key);
357
+ return;
358
+ }
359
+ setTimeout(() => { if (lookups.get(key) === lookup) lookups.delete(key); }, keepFinishedMs).unref();
360
+ });
361
+ }
362
+ if (!await within(lookup, timeout - (performance.now() - started))) {
363
+ lookup.collect = true;
364
+ try {
365
+ return toolResult(renderProgress(lookup.progress, {
366
+ rows, elapsedMs: performance.now() - lookup.started, budgetMs: timeout }));
367
+ } catch {
368
+ return errorResult('Domain Hound could not format the progress.');
369
+ }
370
+ }
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);
374
+ try {
375
+ return toolResult(render(lookup.outcome.data));
376
+ } catch {
377
+ return errorResult('Domain Hound could not format the result.');
378
+ }
379
+ }
246
380
  let shortlist;
247
381
  let initialized = false;
248
382
  let negotiated = false;
@@ -282,21 +416,26 @@ export async function serve({ input = process.stdin, output = process.stdout, cw
282
416
  const { name, arguments: args } = params ?? {};
283
417
  if (name === namingTool.name) {
284
418
  if (args !== undefined && (!isObject(args) || Object.keys(args).some(key => key !== 'about') ||
285
- (Object.hasOwn(args, 'about') && (typeof args.about !== 'string' || !args.about.trim() || args.about.length > 160)))) {
286
- return reply(errorResult('naming_method accepts only an optional about description of up to 160 characters.'));
419
+ (Object.hasOwn(args, 'about') && (typeof args.about !== 'string' || !args.about.trim() ||
420
+ args.about.length > namingTool.inputSchema.properties.about.maxLength)))) {
421
+ return reply(errorResult('naming_method accepts an optional about description of up to 512 characters.'));
287
422
  }
288
423
  shortlist = undefined;
289
- return reply(textResult(JSON.stringify({ display: attributed(namingRecipe(args?.about)) })));
424
+ return reply(toolResult(JSON.stringify({ display: attributed(namingRecipe(args?.about?.slice(0, 160))) })));
290
425
  }
426
+ const purchase = isObject(args) && args.purchase === true;
291
427
  if (name === triageTool.name) {
292
428
  const prior = shortlist && Date.now() - shortlist.at < 120_000 ? shortlist.data : undefined;
293
- return reply(await runLookup(args, cwd, timeout, triageArguments, data => triageText(data, prior)));
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 })));
294
431
  }
295
432
  if (name !== checkTool.name && name !== legacyTool.name) return error(id, -32602, 'Unknown tool');
296
- return reply(await runLookup(args, cwd, timeout, cliArguments, data => {
433
+ // An exact lookup includes the purchase line while its registration status is unsettled.
434
+ const exact = isObject(args) && typeof args.query === 'string' && args.query.includes('.');
435
+ return reply(await runLookup(args, cliArguments, checkRows, data => {
297
436
  if (args.shortlist) shortlist = { at: Date.now(), data };
298
- return checkText(data, args.shortlist);
299
- }));
437
+ return checkText(data, args.shortlist, { purchase, preferred: args.endings });
438
+ }, (progress, timing) => progressText(progress, { ...timing, purchase: purchase || exact })));
300
439
  }
301
440
 
302
441
  const lines = createInterface({ input, terminal: false, crlfDelay: Infinity });
@@ -305,6 +444,9 @@ export async function serve({ input = process.stdin, output = process.stdout, cw
305
444
  pending.add(response);
306
445
  }
307
446
  await Promise.all(pending);
447
+ // The client has gone, so nobody can collect a lookup that is still running.
448
+ for (const lookup of lookups.values()) if (!lookup.finished) lookup.child.kill('SIGKILL');
449
+ await Promise.all([...lookups.values()].map(lookup => lookup.done));
308
450
  }
309
451
 
310
452
  if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await serve();
@@ -1,72 +0,0 @@
1
- import { StringDecoder } from 'node:string_decoder';
2
- import { money } from './prices.mjs';
3
-
4
- const searchUrl = 'https://www.spaceship.com/gateway/api/v1/instantsearch-api/search';
5
-
6
- export function spaceshipFeedQuote(row, domain) {
7
- if (row?.type !== 'result' || row.name !== domain || row.verified !== true || row.isPrimary !== true) return null;
8
- if (row.state === 'taken') return { available: false, premium: false, price: null, renewal: null };
9
- if (row.state !== 'available' || row.price?.currency !== 'USD') return null;
10
- const price = money(row.price.price);
11
- const renewal = money(row.price.renewal);
12
- if (!price || !renewal) return null;
13
- return { available: true, premium: row.premium === true || row.isPremium === true, price, renewal };
14
- }
15
-
16
- // Consume only the exact query's verified result from the storefront's existing response.
17
- // The browser continues to handle the page and its request normally.
18
- export async function watchSpaceshipFeed(page, domain) {
19
- let client;
20
- try {
21
- client = await page.context().newCDPSession(page);
22
- await client.send('Network.enable');
23
- } catch {
24
- await client?.detach().catch(() => {});
25
- return null;
26
- }
27
- const decoder = new StringDecoder('utf8');
28
- let quote = null;
29
- let requestId;
30
- let chunks = [];
31
- let fragment = '';
32
- let ready = false;
33
- let finished = false;
34
-
35
- function consume(data, final = false) {
36
- if (data) fragment += decoder.write(Buffer.from(data, 'base64'));
37
- if (final) fragment += decoder.end() + '\n';
38
- if (fragment.length > 128 * 1024) { fragment = ''; return; }
39
- const lines = fragment.split('\n');
40
- fragment = lines.pop();
41
- for (const line of lines) {
42
- try { quote ??= spaceshipFeedQuote(JSON.parse(line), domain); } catch { /* Ignore malformed lines. */ }
43
- }
44
- }
45
-
46
- client.on('Network.responseReceived', async event => {
47
- const { response } = event;
48
- if (requestId || response.url !== searchUrl || response.status !== 200 ||
49
- response.mimeType !== 'application/x-ndjson') return;
50
- requestId = event.requestId;
51
- try {
52
- const { bufferedData } = await client.send('Network.streamResourceContent', { requestId });
53
- consume(bufferedData);
54
- for (const part of chunks) consume(part);
55
- ready = true;
56
- if (finished) consume(null, true);
57
- } catch { /* The exact visible storefront result remains available. */ }
58
- chunks = [];
59
- });
60
- client.on('Network.dataReceived', event => {
61
- if (event.requestId !== requestId || !event.data || quote) return;
62
- if (ready) consume(event.data);
63
- else if (chunks.length < 24) chunks.push(event.data);
64
- });
65
- client.on('Network.loadingFinished', event => {
66
- if (event.requestId !== requestId) return;
67
- finished = true;
68
- if (ready) consume(null, true);
69
- });
70
-
71
- return { read: () => quote, close: () => client.detach().catch(() => {}) };
72
- }