hostinger-api-mcp 4.15.1 → 4.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/gemini-extension.json +1 -1
  3. package/package.json +1 -1
  4. package/server.json +2 -2
  5. package/skills/headless/SKILL.md +23 -0
  6. package/skills/headless/VERSION +2 -2
  7. package/skills/headless/connect/bootstrap.mjs +3 -3
  8. package/skills/headless/local-server.mjs +64 -0
  9. package/skills/headless/processes.mjs +62 -0
  10. package/skills/headless/report.schema.json +16 -0
  11. package/skills/headless/run-log.mjs +27 -41
  12. package/skills/headless/servers.mjs +169 -0
  13. package/skills/headless/steps/06-frontend/SKILL.md +3 -1
  14. package/skills/headless/steps/06-frontend/bring-your-own-frontend.md +5 -0
  15. package/skills/headless/steps/07-validate/SKILL.md +5 -4
  16. package/skills/headless/steps/09-done/SKILL.md +3 -0
  17. package/skills/headless/workspace.mjs +28 -0
  18. package/src/core/skills.js +52 -24
  19. package/src/core/skills.ts +52 -24
  20. package/src/servers/agency-hosting.js +1 -1
  21. package/src/servers/agency-hosting.ts +1 -1
  22. package/src/servers/agent-readiness.js +1 -1
  23. package/src/servers/agent-readiness.ts +1 -1
  24. package/src/servers/all.js +1 -1
  25. package/src/servers/all.ts +1 -1
  26. package/src/servers/billing.js +1 -1
  27. package/src/servers/billing.ts +1 -1
  28. package/src/servers/dns.js +1 -1
  29. package/src/servers/dns.ts +1 -1
  30. package/src/servers/domains.js +1 -1
  31. package/src/servers/domains.ts +1 -1
  32. package/src/servers/ecommerce.js +1 -1
  33. package/src/servers/ecommerce.ts +1 -1
  34. package/src/servers/gpu.js +1 -1
  35. package/src/servers/gpu.ts +1 -1
  36. package/src/servers/horizons.js +1 -1
  37. package/src/servers/horizons.ts +1 -1
  38. package/src/servers/hosting.js +1 -1
  39. package/src/servers/hosting.ts +1 -1
  40. package/src/servers/mail.js +1 -1
  41. package/src/servers/mail.ts +1 -1
  42. package/src/servers/reach.js +1 -1
  43. package/src/servers/reach.ts +1 -1
  44. package/src/servers/vps.js +1 -1
  45. package/src/servers/vps.ts +1 -1
  46. package/src/servers/wordpress.js +1 -1
  47. package/src/servers/wordpress.ts +1 -1
package/CHANGELOG.md CHANGED
@@ -4,6 +4,21 @@ Generated at release time from the diff between the previous and current
4
4
  build. Tool changes are listed individually; everything else is summarised
5
5
  by area.
6
6
 
7
+ ## v4.16.0 — 2026-11-23
8
+
9
+ ### Also in this release
10
+
11
+ - Dependencies: `package-lock.json`
12
+ - Bundled agent skills: 12 files
13
+ - Other files: `src/core/skills.js`, `src/core/skills.ts`
14
+
15
+ ## v4.15.2 — 2026-11-23
16
+
17
+ ### Also in this release
18
+
19
+ - Bundled agent skills: `skills/headless/VERSION`, `skills/headless/connect/bootstrap.mjs`, `skills/headless/run-log.mjs`
20
+ - Other files: `src/core/skills.js`, `src/core/skills.ts`
21
+
7
22
  ## v4.15.1 — 2026-11-23
8
23
 
9
24
  ### Operations
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hostinger-api-mcp",
3
- "version": "4.15.1",
3
+ "version": "4.16.0",
4
4
  "description": "Hostinger API — manage domains, DNS, hosting, VPS, billing and more from Gemini CLI.",
5
5
  "mcpServers": {
6
6
  "hostinger": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hostinger-api-mcp",
3
- "version": "4.15.1",
3
+ "version": "4.16.0",
4
4
  "mcpName": "io.github.hostinger/hostinger-api-mcp",
5
5
  "description": "MCP server for Hostinger API",
6
6
  "repository": {
package/server.json CHANGED
@@ -17,12 +17,12 @@
17
17
  "url": "https://github.com/hostinger/api-mcp-server",
18
18
  "source": "github"
19
19
  },
20
- "version": "4.15.1",
20
+ "version": "4.16.0",
21
21
  "packages": [
22
22
  {
23
23
  "registryType": "npm",
24
24
  "identifier": "@hostinger/mcp",
25
- "version": "4.15.1",
25
+ "version": "4.16.0",
26
26
  "transport": {
27
27
  "type": "stdio"
28
28
  },
@@ -256,6 +256,28 @@ exits 0 with `ok: true` and what it waited for; 1 with `ok: false` when the job
256
256
  the local Hostinger MCP, with `fallback` naming the connector operation to poll yourself, every ~15 s.
257
257
  Never write your own `sleep` loops.
258
258
 
259
+ ### Local servers: `local-server.mjs`
260
+
261
+ Start every local dev or preview server (frontend's visual check, validate's sign-off preview) through
262
+ `local-server.mjs` (next to this file), never with `&`, `nohup` or your tool's background mode. Run it
263
+ from the project folder; `{port}` in the command becomes the port it picked:
264
+
265
+ ```bash
266
+ cd ~/.hostinger/<domain>/src && node <skill>/local-server.mjs start <domain> -- npx next start -p {port} # Next.js, after npm run build
267
+ cd ~/.hostinger/<domain>/src && node <skill>/local-server.mjs start <domain> -- npx astro preview --port {port} --ignore-lock # Astro, after npm run build
268
+ cd ~/.hostinger/<domain>/src && node <skill>/local-server.mjs start <domain> -- npx next dev -p {port} # a dev server starts the same way
269
+ ```
270
+
271
+ `start` stops the server this domain already runs, so after a rebuild just run it again. It picks a
272
+ free port, so builds running side by side never collide, and waits until the port answers. It prints
273
+ one JSON line and exits 0 with `ok: true` and the `url` to open; 1 with `ok: false`, `error` and
274
+ `log_tail` when the server exited or didn't answer within `--timeout` (90s by default; keep it under
275
+ your tool's command limit); 2 when it couldn't run.
276
+
277
+ `run-log.mjs report` stops the run's servers when it ends, and `run-start` stops any that an earlier,
278
+ ended session left. Neither touches a server `local-server.mjs` didn't start, such as the user's own
279
+ `next dev`.
280
+
259
281
  ---
260
282
 
261
283
  ## State and artifacts
@@ -292,6 +314,7 @@ took from it.
292
314
  | `design.md` (+ `brand/` logo files) | design | chosen design direction: tokens, type, logo, components, per-page composition, accessibility |
293
315
  | `src/` | frontend | the website source implementing `design.md`; framework choice is recorded in `state.json → frontend` |
294
316
  | `deploy.json` | deploy | build id, deployed at, live URLs |
317
+ | `servers.json` (+ `servers/<port>.log`) | `local-server.mjs` only | each local dev or preview server a run started: pid, port, command, start time, and whether it was stopped |
295
318
  | `events.jsonl` | every stage, via `run-log.mjs` | append-only log of issues, user feedback, skill gaps and wins |
296
319
  | `reports/<run>.json` + `.html`, `report.html` | done (or any early stop), via `run-log.mjs` | the build report for each run; `report.html` is the latest |
297
320
 
@@ -1,3 +1,3 @@
1
- version=4.15.1
2
- commit=989db63e0f79
1
+ version=4.16.0
2
+ commit=02f4944d7548
3
3
  built=2026-11-23
@@ -39,14 +39,14 @@ emit('launcher', isWin
39
39
  ? { command: process.execPath, args: [LAUNCHER] }
40
40
  : { command: '/bin/sh', args: [LAUNCHER.replace(/\.mjs$/, '.sh')] });
41
41
 
42
- function capture(cmd, args) {
43
- const r = spawnSync(cmd, args, { encoding: 'utf8', cwd: os.homedir() });
42
+ function capture(args) {
43
+ const r = spawnSync(MCP[0], [...MCP.slice(1), ...args], { encoding: 'utf8', cwd: os.homedir() });
44
44
  return { status: r.status ?? 1, out: `${r.stdout || ''}${r.stderr || ''}`, error: r.error };
45
45
  }
46
46
 
47
47
  // ── 1. MCP server reachable ──────────────────────────────────────────────────
48
48
  function checkMcp() {
49
- const r = capture(MCP[0], [...MCP.slice(1), '--version']);
49
+ const r = capture(['--version']);
50
50
  if (r.status !== 0) fail('mcp_unreachable', { detail: r.out.trim().slice(0, 400) });
51
51
  // npx interleaves "npm notice …" lines, so pick the first semver-looking token.
52
52
  const version = (r.out.match(/\d+\.\d+\.\d+[^\s]*/) || [])[0] || r.out.trim().split('\n').pop();
@@ -0,0 +1,64 @@
1
+ #!/usr/bin/env node
2
+ // Hostinger Headless local server: starts a build's local dev or preview server, and stops them, so a
3
+ // run never leaves one behind.
4
+ //
5
+ // cd <project> && node local-server.mjs start <domain> [--timeout 90s] -- <command…>
6
+ // node local-server.mjs stop <domain>
7
+ //
8
+ // start replaces the servers this domain already runs, picks a free port, runs the command from the
9
+ // current folder with PORT set and every {port} in its arguments replaced, waits until the port answers
10
+ // HTTP and records the server in ~/.hostinger/<domain>/servers.json. stop stops every server recorded
11
+ // there that may still be running. run-log.mjs stops them too, at run-start and report.
12
+ //
13
+ // stdout is one JSON line. Exit 0 when done; 1 when the server didn't come up (`error`, `log_tail`) or
14
+ // a server couldn't be confirmed stopped; 2 when it couldn't run (`error`).
15
+
16
+ import { isDown, startServer, stopServers } from './servers.mjs';
17
+ import { workspaceDir } from './workspace.mjs';
18
+
19
+ const finish = (code, result) => {
20
+ process.stdout.write(`${JSON.stringify(result)}\n`);
21
+ process.exit(code);
22
+ };
23
+ const fail = (message) => finish(2, { ok: false, error: message });
24
+ const DEFAULT_TIMEOUT = '90s';
25
+
26
+ function parseArgs(argv) {
27
+ const positional = [];
28
+ const flags = {};
29
+ for (let i = 0; i < argv.length; i += 1) {
30
+ if (argv[i].startsWith('--')) {
31
+ const key = argv[i].slice(2);
32
+ const value = argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[(i += 1)] : true;
33
+ flags[key] = value;
34
+ } else positional.push(argv[i]);
35
+ }
36
+ return { positional, flags };
37
+ }
38
+
39
+ function duration(text) {
40
+ const m = typeof text === 'string' && text.match(/^(\d+(?:\.\d+)?)\s*([smh])$/);
41
+ if (!m) fail(`--timeout "${text}" should look like 90s, 10m or 1h`);
42
+ return Number(m[1]) * { s: 1e3, m: 6e4, h: 36e5 }[m[2]];
43
+ }
44
+
45
+ const argv = process.argv.slice(2);
46
+ const dash = argv.includes('--') ? argv.indexOf('--') : argv.length;
47
+ const { positional: [action, domain, ...extra], flags } = parseArgs(argv.slice(0, dash));
48
+ const command = argv.slice(dash + 1);
49
+ if (!['start', 'stop'].includes(action) || extra.length) fail(`usage: start <domain> [--timeout ${DEFAULT_TIMEOUT}] -- <command…> | stop <domain>`);
50
+ if (action === 'start' && !command.length) fail('give the server command after --, e.g. start <domain> -- npx next start -p {port}');
51
+ let dir;
52
+ try {
53
+ dir = workspaceDir(domain);
54
+ } catch (error) {
55
+ fail(error.message);
56
+ }
57
+
58
+ if (action === 'start') {
59
+ const result = await startServer(dir, command, { timeoutMs: duration(flags.timeout ?? DEFAULT_TIMEOUT) });
60
+ finish(result.ok ? 0 : 1, result);
61
+ }
62
+ const tried = await stopServers(dir);
63
+ const ok = tried.every(isDown);
64
+ finish(ok ? 0 : 1, { ok, stopped: tried.map(({ port, pid, command: cmd, status }) => ({ port, pid, command: cmd, status })) });
@@ -0,0 +1,62 @@
1
+ // The process list and process-tree signals, shared by run-log.mjs (the domain lock) and
2
+ // local-server.mjs (the servers a run starts). Both tell a live process from a reused PID by its
3
+ // start time.
4
+
5
+ import { spawnSync } from 'node:child_process';
6
+ import { homedir } from 'node:os';
7
+ import { basename, delimiter, isAbsolute, join } from 'node:path';
8
+
9
+ export const processName = (name) => basename(name.replace(/\\/g, '/')).replace(/^-/, '').replace(/\.exe$/i, '').toLowerCase();
10
+
11
+ // These scripts run in the user's project, maybe a cloned repository. Windows looks a bare program name
12
+ // up in the working directory before PATH, as does a relative PATH entry elsewhere, so system programs
13
+ // run from home with only absolute, non-node_modules PATH entries (as connect/launch.mjs runs npx),
14
+ // and Windows programs are named by their full path.
15
+ const helperEnv = { ...process.env, LC_ALL: 'C', TZ: 'UTC' };
16
+ for (const key of Object.keys(helperEnv).filter((k) => k.toUpperCase() === 'PATH')) {
17
+ helperEnv[key] = helperEnv[key].split(delimiter)
18
+ .filter((p) => isAbsolute(p) && !p.split(/[\\/]/).includes('node_modules'))
19
+ .join(delimiter);
20
+ }
21
+ const systemRoot = isAbsolute(process.env.SystemRoot ?? '') ? process.env.SystemRoot : 'C:\\Windows';
22
+ const POWERSHELL = join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
23
+ const TASKKILL = join(systemRoot, 'System32', 'taskkill.exe');
24
+
25
+ // pid -> { ppid, started, name }; null when the process list can't be read (a sandbox that blocks ps).
26
+ export function processTable() {
27
+ const windows = process.platform === 'win32';
28
+ const r = windows
29
+ ? spawnSync(POWERSHELL, ['-NoProfile', '-NonInteractive', '-Command',
30
+ 'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId)`t$($_.ParentProcessId)`t$(if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString(\'o\') })`t$($_.Name)" }'], { encoding: 'utf8', cwd: homedir(), env: helperEnv })
31
+ : spawnSync('ps', ['-A', '-o', 'pid=,ppid=,lstart=,comm='], { encoding: 'utf8', cwd: homedir(), env: helperEnv });
32
+ if (r.status !== 0 || !r.stdout) return null;
33
+ const table = new Map();
34
+ for (const line of r.stdout.split(/\r?\n/)) {
35
+ const m = windows ? line.match(/^(\d+)\t(\d+)\t([^\t]*)\t(.*)$/) : line.trim().match(/^(\d+)\s+(\d+)\s+(\w+\s+\w+\s+\d+\s+[\d:]+\s+\d+)\s+(.*)$/);
36
+ if (m) table.set(Number(m[1]), { ppid: Number(m[2]), started: m[3].replace(/\s+/g, ' ') || null, name: m[4] });
37
+ }
38
+ return table.size ? table : null;
39
+ }
40
+
41
+ // Whether the process group led by pid (on Windows, the process itself) still has a member.
42
+ export function groupAlive(pid) {
43
+ if (process.platform === 'win32') return processTable()?.has(pid) ?? false;
44
+ try {
45
+ process.kill(-pid, 0);
46
+ return true;
47
+ } catch (error) {
48
+ return error.code === 'EPERM';
49
+ }
50
+ }
51
+
52
+ // Signals the process group led by pid: a server started detached leads its own group, so npx, the
53
+ // framework and its workers all get it. Windows has no groups: taskkill /T walks the tree instead.
54
+ export function signalGroup(pid, signal) {
55
+ if (process.platform === 'win32') {
56
+ spawnSync(TASKKILL, ['/PID', String(pid), '/T', ...(signal === 'SIGKILL' ? ['/F'] : [])], { cwd: homedir(), env: helperEnv, stdio: 'ignore' });
57
+ return;
58
+ }
59
+ try {
60
+ process.kill(-pid, signal);
61
+ } catch {}
62
+ }
@@ -138,6 +138,22 @@
138
138
  "properties": { "stage": { "type": "string" }, "phase": { "type": ["string", "null"] }, "problem": { "type": "string" } }
139
139
  }
140
140
  },
141
+ "servers": {
142
+ "description": "Local dev and preview servers this run started through local-server.mjs, and what stopping them at the end of the run found.",
143
+ "type": "array",
144
+ "items": {
145
+ "type": "object",
146
+ "required": ["port", "command", "status"],
147
+ "properties": {
148
+ "pid": { "type": "integer" },
149
+ "port": { "type": "integer" },
150
+ "command": { "type": "string" },
151
+ "started_at": { "type": "string" },
152
+ "stopped_at": { "type": ["string", "null"] },
153
+ "status": { "type": "string", "enum": ["stopped", "already_gone", "not_verified", "still_running"] }
154
+ }
155
+ }
156
+ },
141
157
  "previous_runs": {
142
158
  "type": "array",
143
159
  "items": {
@@ -15,18 +15,18 @@
15
15
  // node run-log.mjs <domain> report-sent [<run>]
16
16
  // node run-log.mjs <domain> report-rejected [<run>]
17
17
 
18
- import { spawnSync } from 'node:child_process';
19
- import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
20
- import { homedir, hostname } from 'node:os';
21
- import { basename, dirname, join } from 'node:path';
18
+ import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
19
+ import { hostname } from 'node:os';
20
+ import { dirname, join } from 'node:path';
22
21
  import { fileURLToPath } from 'node:url';
22
+ import { processName, processTable } from './processes.mjs';
23
+ import { describeServer, isDown, serversSince, stopServers } from './servers.mjs';
24
+ import { now, workspaceDir, writeJsonAtomic } from './workspace.mjs';
23
25
 
24
26
  const STAGES = ['refine', 'connect', 'check_state', 'provision', 'content_model', 'design', 'frontend', 'validate', 'deploy', 'done'];
25
27
  // Stages that stop for the user to restart their tool, so it loads a newly registered Hostinger MCP server.
26
28
  const RESTART_STAGES = ['connect', 'provision', 'content_model'];
27
29
  const PAUSE_NOTE = 'paused for a tool restart';
28
- // A domain names a folder under ~/.hostinger, so "../x" or "a/b" must never reach the file system.
29
- const HOSTNAME = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i;
30
30
  const RESULTS = ['ok', 'ok_after_retries', 'ok_with_fixups', 'failed', 'skipped', 'stopped'];
31
31
  const OUTCOMES = ['live', 'stopped', 'failed', 'abandoned'];
32
32
  const EVENT_FIELDS = {
@@ -38,7 +38,6 @@ const EVENT_FIELDS = {
38
38
  const EVENT_LISTS = { issue: 'issues', feedback: 'user_feedback', skill_gap: 'skill_gaps', good: 'what_went_well' };
39
39
 
40
40
  const here = dirname(fileURLToPath(import.meta.url));
41
- const now = () => new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
42
41
  // A start logged late is kept but marked estimated, so the report can tell measured times from remembered ones.
43
42
  function lateStart(flags, run) {
44
43
  let at = null;
@@ -79,10 +78,12 @@ const writeJson = (file, value) => writeFileSync(file, `${JSON.stringify(value,
79
78
  // run-start is a run's first command, before anything else has written to the workspace.
80
79
  function workspace(domain, { create = false } = {}) {
81
80
  if (!domain || domain.startsWith('-')) fail('first argument must be the domain');
82
- if (!HOSTNAME.test(domain)) fail(`"${domain}" is not a domain (use its ASCII form, e.g. xn--caf-dma.com)`);
83
- const dir = join(homedir(), '.hostinger', domain);
84
- if (create) mkdirSync(dir, { recursive: true });
85
- else if (!existsSync(dir)) fail(`no workspace at ${dir}; run-start creates it`);
81
+ let dir;
82
+ try {
83
+ dir = workspaceDir(domain, { create });
84
+ } catch (error) {
85
+ fail(error.message);
86
+ }
86
87
  return {
87
88
  dir,
88
89
  domain,
@@ -104,25 +105,6 @@ const WRAPPERS = new Set(['sh', 'bash', 'zsh', 'dash', 'fish', 'pwsh', 'powershe
104
105
  // counts as live while it was refreshed this recently.
105
106
  const LOCK_FRESH_MS = 30 * 60 * 1000;
106
107
 
107
- const processName = (name) => basename(name.replace(/\\/g, '/')).replace(/^-/, '').replace(/\.exe$/i, '').toLowerCase();
108
-
109
- // pid -> { ppid, started, name }; null when the process list can't be read. The start time tells a
110
- // reused PID from the process that held the lock.
111
- function processTable() {
112
- const windows = process.platform === 'win32';
113
- const r = windows
114
- ? spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command',
115
- 'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId)`t$($_.ParentProcessId)`t$(if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString(\'o\') })`t$($_.Name)" }'], { encoding: 'utf8' })
116
- : spawnSync('ps', ['-A', '-o', 'pid=,ppid=,lstart=,comm='], { encoding: 'utf8', env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' } });
117
- if (r.status !== 0 || !r.stdout) return null;
118
- const table = new Map();
119
- for (const line of r.stdout.split(/\r?\n/)) {
120
- const m = windows ? line.match(/^(\d+)\t(\d+)\t([^\t]*)\t(.*)$/) : line.trim().match(/^(\d+)\s+(\d+)\s+(\w+\s+\w+\s+\d+\s+[\d:]+\s+\d+)\s+(.*)$/);
121
- if (m) table.set(Number(m[1]), { ppid: Number(m[2]), started: m[3].replace(/\s+/g, ' ') || null, name: m[4] });
122
- }
123
- return table.size ? table : null;
124
- }
125
-
126
108
  function currentHolder(table) {
127
109
  let pid = process.ppid;
128
110
  while (table?.has(pid) && WRAPPERS.has(processName(table.get(pid).name))) pid = table.get(pid).ppid;
@@ -161,12 +143,6 @@ function lockStatus(lock, me, table) {
161
143
  return byRecency(lock);
162
144
  }
163
145
 
164
- // Replacing the lock goes through a rename, so a reader never sees half of it.
165
- function writeLock(ws, lock) {
166
- const tmp = `${ws.lockPath}.${process.pid}.tmp`;
167
- writeJson(tmp, lock);
168
- renameSync(tmp, ws.lockPath);
169
- }
170
146
 
171
147
  // Of two sessions creating a missing lock at once, exactly one succeeds.
172
148
  function createLock(ws, lock) {
@@ -224,7 +200,7 @@ function claimLock(ws, { take = false, start = false, takeOver = false, tool = n
224
200
  const status = verdict === 'unverified' ? (start ? byRecency(lock) : 'own') : verdict;
225
201
  if (status === 'own') {
226
202
  const refreshed = { ...lock, tool: tool ?? lock.tool, refreshed_at: now() };
227
- writeLock(ws, refreshed);
203
+ writeJsonAtomic(ws.lockPath, refreshed);
228
204
  return { lock: refreshed, wasFree: false };
229
205
  }
230
206
  if (status === 'live' && !takeOver) refuse(ws, lock, { offerTakeOver: start });
@@ -232,7 +208,7 @@ function claimLock(ws, { take = false, start = false, takeOver = false, tool = n
232
208
  // Two sessions taking over the same dead lock at once both rename theirs in; the one that lost
233
209
  // is refused at its next command.
234
210
  const taken = record();
235
- writeLock(ws, taken);
211
+ writeJsonAtomic(ws.lockPath, taken);
236
212
  return { lock: taken, wasFree: false };
237
213
  }
238
214
  fail(`${ws.lockPath} keeps appearing and disappearing; another session is starting on ${ws.domain}. Stop and tell the user`);
@@ -296,7 +272,11 @@ function readConnect(ws) {
296
272
  return { tool: typeof connect.tool === 'string' ? connect.tool : null, mcp: version, skills: typeof connect.skills === 'string' ? connect.skills : null };
297
273
  }
298
274
 
299
- function runStart(ws, flags, lockWasFree) {
275
+ // This session holds the domain now, so a server still recorded in the workspace was left by a session
276
+ // that is gone; stopping it first also gets it into the report of the run that started it.
277
+ async function runStart(ws, flags, lockWasFree) {
278
+ const leftovers = await stopServers(ws.dir);
279
+ if (leftovers.length) console.log(`local servers left by an earlier session: ${leftovers.map(describeServer).join('; ')}`);
300
280
  const log = loadLog(ws);
301
281
  // A run left open in a restart stage goes on in the new session, at connect, instead of being
302
282
  // abandoned. The paused stage ends at its last logged activity, so the restart wait isn't counted.
@@ -529,6 +509,7 @@ function buildReport(ws, { outcome, tokens } = {}) {
529
509
  const gaps = [...loggingGaps(stages, run, resolvedOutcome), ...dropped];
530
510
  const strip = ({ ts, run: _run, type: _type, ...rest }) => ({ ...rest, logged_at: ts });
531
511
  const liveStage = stages.find((s) => s.stage === 'deploy' && s.result?.startsWith('ok'));
512
+ const servers = serversSince(ws.dir, run.started_at);
532
513
  if (!OUTCOMES.includes(resolvedOutcome)) fail(`unknown outcome "${resolvedOutcome}"; one of ${OUTCOMES.join(', ')}`);
533
514
 
534
515
  const previous = existsSync(ws.reportsDir)
@@ -575,6 +556,7 @@ function buildReport(ws, { outcome, tokens } = {}) {
575
556
  skill_gaps: events.filter((e) => e.type === 'skill_gap').map(strip),
576
557
  what_went_well: events.filter((e) => e.type === 'good').map(strip),
577
558
  logging_gaps: gaps,
559
+ servers,
578
560
  previous_runs: previous,
579
561
  };
580
562
 
@@ -588,6 +570,7 @@ function buildReport(ws, { outcome, tokens } = {}) {
588
570
  fresh.run.reported_at = now();
589
571
  saveLog(ws, fresh);
590
572
  for (const g of gaps) console.log(`warning: ${g.stage}${g.phase ? `/${g.phase}` : ''}: ${g.problem}`);
573
+ for (const s of servers.filter((s) => !isDown(s))) console.log(`server not stopped: ${describeServer(s)}`);
591
574
  return join(ws.dir, 'report.html');
592
575
  }
593
576
 
@@ -833,6 +816,7 @@ details summary { cursor:pointer; color:var(--text-secondary); margin-top:16px;
833
816
  <div class="legend"><span><span class="swatch sw-solid"></span>Finished</span><span><span class="swatch sw-hatch"></span>Failed, stopped or not finished</span><span><span class="swatch sw-est"></span>Start estimated</span><span>Stages can overlap: prep work runs while provisioning settles.</span></div>
834
817
  <details><summary>Show as table</summary><div class="table-wrap"><table><thead><tr><th>Stage</th><th>Start</th><th>End</th><th class="num">Minutes</th><th>Result</th><th>Note</th></tr></thead><tbody>${stageRows}</tbody></table></div></details></section>
835
818
  ${r.logging_gaps.length ? `<section><h2>Logging gaps (${r.logging_gaps.length})</h2><p class="muted">Where the run log is missing or unsure, so times here are less reliable.</p><ul>${r.logging_gaps.map((g) => `<li><strong>${esc(label(g.stage))}${g.phase ? ` · ${esc(g.phase)}` : ''}</strong> — ${esc(g.problem)}</li>`).join('')}</ul></section>` : ''}
819
+ ${r.servers.length ? `<section><h2>Local servers (${r.servers.length})</h2><p class="muted">Dev and preview servers this run started, and what stopping them when it ended found.</p><div class="table-wrap"><table><thead><tr><th class="num">Port</th><th class="num">PID</th><th>Command</th><th>Started</th><th>Stopped</th><th>Status</th></tr></thead><tbody>${r.servers.map((s) => `<tr><td class="num">${s.port}</td><td class="num">${s.pid}</td><td><code>${esc(s.command)}</code></td><td>${time(s.started_at)}</td><td>${time(s.stopped_at)}</td><td>${esc(label(s.status))}</td></tr>`).join('')}</tbody></table></div></section>` : ''}
836
820
  <section><h2>Issues (${r.issues.length})</h2>${r.issues.length ? `<div class="table-wrap"><table><thead><tr><th>Severity</th><th>Stage</th><th>Symptom</th><th>Cause</th><th>Workaround</th><th>Status</th></tr></thead><tbody>${issues}</tbody></table></div>` : '<p class="muted">No issues logged.</p>'}</section>
837
821
  <div class="cols"><section><h2>User feedback</h2>${list(r.user_feedback, (f) => `<li><span class="chip">${esc(label(f.category))}</span> <span class="muted">${esc(label(f.stage))}</span> — “${esc(f.paraphrase)}”</li>`, 'No feedback logged.')}</section>
838
822
  <section><h2>Skill gaps</h2>${list(r.skill_gaps, (g) => `<li><code>${esc(g.skill)}</code> — ${esc(g.gap)}</li>`, 'No skill gaps logged.')}</section></div>
@@ -853,7 +837,8 @@ document.querySelectorAll('.bar').forEach((el) => {
853
837
  `;
854
838
  }
855
839
 
856
- function report(ws, flags) {
840
+ // The run ends here, finished or stopped early, so its local servers stop before the report records them.
841
+ async function report(ws, flags) {
857
842
  let tokens;
858
843
  if (typeof flags.tokens === 'string') {
859
844
  try {
@@ -865,6 +850,7 @@ function report(ws, flags) {
865
850
  if (tokens === null || (typeof tokens === 'object' && !Array.isArray(tokens) && !Object.keys(tokens).length)) tokens = undefined;
866
851
  else validate(tokens, { ...reportSchema()?.properties?.tokens, type: 'object' }, '--tokens');
867
852
  }
853
+ await stopServers(ws.dir);
868
854
  console.log(`report written: ${buildReport(ws, { outcome: flags.outcome, tokens })}`);
869
855
  const { id, file } = reportFile(ws);
870
856
  console.log(`send it: pass ${file} unchanged to hosting_headless_submit-build-report, then run report-sent ${id} (or report-rejected ${id} on a 422)`);
@@ -902,6 +888,6 @@ const claim = spec.lock === 'none' ? null : claimLock(ws, {
902
888
  takeOver: start && flags['take-over'] === true,
903
889
  tool: start && typeof flags.tool === 'string' ? flags.tool : null,
904
890
  });
905
- spec.run(ws, rest, flags, claim);
891
+ await spec.run(ws, rest, flags, claim);
906
892
  // A command that fails exits before this, so a refused pause or report keeps the lock.
907
893
  if (spec.lock === 'release' && claim.lock) rmSync(ws.lockPath, { force: true });
@@ -0,0 +1,169 @@
1
+ // The local dev and preview servers a Headless build starts, recorded in <workspace>/servers.json so
2
+ // the run can stop them when it ends. local-server.mjs is the agent's command for it; run-log.mjs
3
+ // stops them at run-start and report.
4
+
5
+ import { spawn } from 'node:child_process';
6
+ import { closeSync, mkdirSync, openSync, readFileSync } from 'node:fs';
7
+ import { createServer } from 'node:net';
8
+ import { join } from 'node:path';
9
+ import { groupAlive, processTable, signalGroup } from './processes.mjs';
10
+ import { now, writeJsonAtomic } from './workspace.mjs';
11
+
12
+ // Statuses after which a server is known to be down. Any other (starting, running, still_running,
13
+ // not_verified) may still be running, so a later stop tries it again.
14
+ const DOWN = ['stopped', 'already_gone'];
15
+ export const isDown = (server) => DOWN.includes(server.status);
16
+ const STOP_GRACE_MS = 5000;
17
+ const KILL_GRACE_MS = 2000;
18
+ const START_ATTEMPTS = 3;
19
+
20
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
21
+ const serversPath = (dir) => join(dir, 'servers.json');
22
+
23
+ // Merges fields into this server's record; servers.json keeps every server the domain started, so a
24
+ // pid alone may match an old one.
25
+ function updateServer(dir, server, fields) {
26
+ const same = (s) => s.pid === server.pid && s.started_at === server.started_at;
27
+ writeJsonAtomic(serversPath(dir), readServers(dir).map((s) => (same(s) ? { ...s, ...fields } : s)));
28
+ }
29
+
30
+ function readServers(dir) {
31
+ try {
32
+ const servers = JSON.parse(readFileSync(serversPath(dir), 'utf8'));
33
+ return Array.isArray(servers) ? servers : [];
34
+ } catch {
35
+ return [];
36
+ }
37
+ }
38
+
39
+ const STATUS_TEXT = { stopped: 'stopped', already_gone: 'already gone', still_running: 'still running', not_verified: 'could not be confirmed stopped' };
40
+ export const describeServer = (s) => `port ${s.port} (pid ${s.pid}, ${s.command}): ${STATUS_TEXT[s.status] ?? s.status}`;
41
+
42
+ // The servers started since `since` (a run's started_at), as the build report shows them.
43
+ export const serversSince = (dir, since) => readServers(dir)
44
+ .filter((s) => s.started_at >= since)
45
+ .map(({ pid, port, command, started_at, stopped_at, status }) => ({ pid, port, command, started_at, stopped_at: stopped_at ?? null, status }));
46
+
47
+ // Whether something listens on the port, on any address.
48
+ const portBusy = (port) => new Promise((resolve) => {
49
+ const probe = createServer();
50
+ probe.once('error', (error) => resolve(error.code === 'EADDRINUSE'));
51
+ probe.listen(port, () => probe.close(() => resolve(false)));
52
+ });
53
+
54
+ // A port the system has just handed out is free, unless another program takes it before the server
55
+ // binds it: startServer retries then. One rule for every framework, as Next.js has no port auto-increment.
56
+ const freePort = () => new Promise((resolve, reject) => {
57
+ const probe = createServer();
58
+ probe.once('error', reject);
59
+ probe.listen(0, () => {
60
+ const { port } = probe.address();
61
+ probe.close(() => resolve(port));
62
+ });
63
+ });
64
+
65
+ async function gone(pid, ms) {
66
+ for (const until = Date.now() + ms; Date.now() < until; await sleep(100)) if (!groupAlive(pid)) return true;
67
+ return !groupAlive(pid);
68
+ }
69
+
70
+ // A recorded PID now held by a process with another start time was reused: it isn't ours, so it is
71
+ // left alone. Without a start time to compare (no process list), the group is stopped only while the
72
+ // port is still bound.
73
+ async function stopOne(server, table) {
74
+ if (!groupAlive(server.pid)) return 'already_gone';
75
+ const leader = table?.get(server.pid);
76
+ if (leader && server.started && leader.started !== server.started) return 'already_gone';
77
+ if ((!table || !server.started) && !(await portBusy(server.port))) return 'not_verified';
78
+ signalGroup(server.pid, 'SIGTERM');
79
+ return (await gone(server.pid, STOP_GRACE_MS)) ? 'stopped' : kill(server.pid);
80
+ }
81
+
82
+ async function kill(pid) {
83
+ signalGroup(pid, 'SIGKILL');
84
+ return (await gone(pid, KILL_GRACE_MS)) ? 'stopped' : 'still_running';
85
+ }
86
+
87
+ // Stops every server recorded in the workspace that may still be running, and returns those it tried.
88
+ // One session builds a domain at a time (run-log.mjs's lock), so whatever is recorded here belongs to
89
+ // this session or to one that is gone; servers elsewhere (the user's own, other domains) are never
90
+ // looked at.
91
+ export async function stopServers(dir) {
92
+ const servers = readServers(dir);
93
+ const live = servers.filter((s) => !isDown(s));
94
+ if (!live.length) return [];
95
+ const table = processTable();
96
+ for (const server of live) {
97
+ server.status = await stopOne(server, table);
98
+ server.stopped_at = now();
99
+ }
100
+ writeJsonAtomic(serversPath(dir), servers);
101
+ return live;
102
+ }
103
+
104
+ // Resolves once the port answers HTTP (any status), or with why the server exited or ran out of time.
105
+ async function serving(child, port, timeoutMs) {
106
+ let exited = null;
107
+ child.once('exit', (code, signal) => (exited = `exited with ${signal ?? `code ${code}`}`));
108
+ child.once('error', (error) => (exited = `could not start: ${error.message}`));
109
+ for (const until = Date.now() + timeoutMs; Date.now() < until; await sleep(250)) {
110
+ if (exited) return exited;
111
+ // Astro and Vite listen on localhost, which may be IPv6 only; Next.js listens on every address.
112
+ for (const host of ['127.0.0.1', '[::1]']) {
113
+ try {
114
+ await fetch(`http://${host}:${port}/`, { redirect: 'manual', signal: AbortSignal.timeout(2000) });
115
+ return null;
116
+ } catch {}
117
+ }
118
+ }
119
+ return exited ?? `did not answer on port ${port} within ${timeoutMs / 1000}s`;
120
+ }
121
+
122
+ const tail = (file) => readFileSync(file, 'utf8').trim().split('\n').slice(-15).join('\n');
123
+
124
+ // Spawns the command on the port, logging to servers/<port>.log, and records it as starting before
125
+ // anyone waits on it, so it is still stopped when start is killed mid-wait. Without a process list
126
+ // (no start time) a stop only stops it once it binds its port. server is null when it didn't spawn.
127
+ function launch(dir, command, port) {
128
+ const [program, ...args] = command.map((a) => a.replaceAll('{port}', String(port)));
129
+ const project = process.cwd();
130
+ const log = join(dir, 'servers', `${port}.log`);
131
+ const out = openSync(log, 'w');
132
+ // Its own process group (detached), so a stop reaches npx, the framework and its workers alike.
133
+ // ASTRO_PREVIEW_BACKGROUND keeps `astro preview` in the foreground under an agent, so the recorded
134
+ // pid is the real server. Windows starts npx and npm through .cmd shims, which need a shell.
135
+ const child = spawn(program, args, {
136
+ cwd: project,
137
+ detached: true,
138
+ stdio: ['ignore', out, out],
139
+ env: { ...process.env, PORT: String(port), ASTRO_PREVIEW_BACKGROUND: '1' },
140
+ shell: process.platform === 'win32',
141
+ windowsHide: true,
142
+ });
143
+ closeSync(out);
144
+ if (!child.pid) return { child, server: null, log };
145
+ const started = processTable()?.get(child.pid)?.started ?? null;
146
+ const server = { pid: child.pid, started, port, command: [program, ...args].join(' '), cwd: project, log, started_at: now(), status: 'starting' };
147
+ writeJsonAtomic(serversPath(dir), [...readServers(dir), server]);
148
+ return { child, server, log };
149
+ }
150
+
151
+ // Starts `command` from the current folder on a free port and records it, replacing the servers this
152
+ // domain already runs, since a running server keeps serving the build it started with.
153
+ export async function startServer(dir, command, { timeoutMs }) {
154
+ await stopServers(dir);
155
+ mkdirSync(join(dir, 'servers'), { recursive: true });
156
+ for (let attempt = 1; ; attempt += 1) {
157
+ const port = await freePort();
158
+ const { child, server, log } = launch(dir, command, port);
159
+ const error = await serving(child, port, timeoutMs);
160
+ if (!error) {
161
+ child.unref();
162
+ updateServer(dir, server, { status: 'running' });
163
+ return { ok: true, url: `http://localhost:${port}/`, port, pid: child.pid, log };
164
+ }
165
+ if (server) updateServer(dir, server, { status: await kill(server.pid), stopped_at: now() });
166
+ if (attempt < START_ATTEMPTS && /EADDRINUSE/.test(tail(log))) continue;
167
+ return { ok: false, error: `the server ${error}`, log, log_tail: tail(log) };
168
+ }
169
+ }
@@ -148,7 +148,9 @@ built. Update `state.json` (`stage: "validate"`).
148
148
  Validate (Step 7) owns the clean rebuild + user preview; deploy (Step 8) ships it with the `app_type`
149
149
  and output directory that match the chosen framework + rendering.
150
150
 
151
- **Visual check.** With the site running locally against the live backend, look at the home page and one
151
+ **Visual check.** After `npm run build`, start the site locally against the live backend with
152
+ `local-server.mjs`, as *Local servers* in the top-level `SKILL.md` shows, and open the `url` it prints.
153
+ After a fix, rebuild and start it again. Look at the home page and one
152
154
  page of each template (e.g. a post, a product, the contact page) at desktop and phone width. Take all the
153
155
  screenshots first, then open them all in one turn where your tool can open several images at once, since
154
156
  each separate look costs a model turn. Don't tile several pages onto one image or take one tall
@@ -11,3 +11,8 @@ the user's direction (vibe-code with them). Your job is to connect it to the liv
11
11
  `wp/v2` reads, the WooCommerce/Ecommerce Store API, env/keys) and make it deployable (set
12
12
  `engines.node` to `22`, remove any `.htaccess`), then hand off to deploy. This generalises the Webapp
13
13
  "existing app" case in `SKILL.md` to WordPress and Ecommerce too.
14
+
15
+ Run their dev or preview server only through `local-server.mjs` (top-level `SKILL.md`, *Local
16
+ servers*), from their project folder, so the run stops it when it ends: put `{port}` where their script
17
+ takes a port (`node <skill>/local-server.mjs start <domain> -- npm run dev -- --port {port}`), or leave it
18
+ out when the framework reads `PORT`. Never stop or reuse a server the user already had running.