A Servers pane for this project's dev servers: what is listening, on which port, since when, with Start, Stop, Restart and Log buttons; names the process…

Claude Code mods (function-hook plugins) I find helpful. Each folder is one plugin.
Requires a Claude Code build with function-hook plugins (2.1.289 or newer). machine-guard reads macOS tools (sysctl, vm_stat, ioreg, ps).
git clone https://github.com/joeldg/claude-mods ~/Projects/claude-mods
A pane of your project's running dev servers, so you don't have to ask Claude to restart them — and a tool so Claude doesn't have to run lsof to find out what's listening.
/servers opens the Servers pane:package.json dev/start/serve/preview scripts (run with your lockfile's package manager), .claude/launch.json and Procfileclaude CLI, which also listen on localhost from the project's folder) are never listed as servers nor counted as other listeners.~/.claude/dev-servers/<project>/.dev_servers tool: this project's running servers (name, port, pid, uptime, and the log when it was started from the pane), the start commands that aren't running, and with all: true every other listener on the machine (port, process), ending with how many Claude Code sessions it left out, e.g. (7 Claude Code sessions not listed), so nothing is hidden silently. Its description tells Claude to use it instead of lsof/netstat/ps. It never starts or stops anything.Port 4000 is held by node (pid 123, up 2h, in /Users/me/other).servers: :4000 :5173.netstat -anv -p tcp (macOS) or ss -ltnp (Linux), never a bare lsof; ps and lsof -d cwd run once per new pid, one pid at a time. One open session scans per interval (15s by default) and writes ~/.claude/dev-servers/scan-cache.json for the others; a slow scan doubles the interval, up to 5 minutes.Puts files you just downloaded into your prompt with one click.
~/Downloads (top level). When a new file arrives (PDF, Markdown, images, 3MF/STL/OBJ, zip, video…), a band appears above the prompt: New in Downloads: paper.pdf, model-b.3mf · 2m ago [Attach] [Dismiss].@"/Users/you/Downloads/paper.pdf" mentions in your prompt. Dismiss hides those files./downloads lists the 10 newest files, numbered. /downloads attach 1 3 (or 2-4) adds those, and /downloads clear dismisses everything new.Settings: folder (~/Downloads), extensions, pollSeconds (5), maxAgeMinutes (120).
Sets effort per message, so you don't have to switch it by hand.
~/.claude/usage-meter/summary.json, at most every 30 s) and, once pct reaches budgetCapAt (80%), caps every turn at budgetCapEffort (high), deep asks included, so you stop hitting the 5-hour wall. A turn already at or below the cap is left alone; lowering over a warm cache waits like any other lowering and never happens mid-turn. A missing or stale summary (over 10 minutes old), or one with no percentage yet (no fresh API reading and no limit learned), is no budget information. The debug log gets one line when the cap engages and one when it releases. budgetCapAt: 0 turns it off.subagentEffort (empty by default) to run every subagent request at that effort; the budget cap applies to them too (the lower of the two). Each subagent turn's effort is decided at its first request and kept for the turn.avoidModel (a regex such as fable) to send those requests to fallbackModel instead, subagents included./route shows the last decision, the session's counts, the budget state (percent used, the cap, whether it is engaged) and the subagent effort. /route off and /route on toggle it all; /route deep and /route routine force the next turn.effort: low (routine); while the budget cap lowers it: effort: high (budget 84%).Settings: routineEffort (low), deepEffort (max), routinePattern, deepPattern, avoidModel, fallbackModel (opus), stickyTurns (2), freeSwitchTokens (30000), cacheTtlMinutes (60), budgetCapAt (80; 0 = off), budgetCapEffort (high), subagentEffort (empty = the session's own).
A Jobs pane for long-running work: training runs, downloads, extractions — and three tools so Claude follows them instead of polling.
nohup … > log & launches by itself./watch <log> [label] adds any other log file./ and /Volumes/* (the NAS).jobs: 2 running · 1 stalled. A timer Claude sets for itself — sleep 600 && echo done, a loop of sleeps, or a task described as a wait, timer, pause or delay that only polls and reports with read-only programs (rg, tail, pgrep…) — is still listed by jobs_list and shown as a dim timer row, but never toasts, never counts in the status line, does not open the pane, is judged by its exit marker alone (no ps), and leaves a minute after it ends. Anything that runs a real program is a job, however it is described./jobs opens the pane, /unwatch <label|id|done|all> removes jobs.jobs_list (every watched job's state, pid, progress, ETA, last-output age, exit code and log path), jobs_watch ({ pid?, log?, name?, quietMinutes? }: follow a process or log started elsewhere; it never starts commands) and jobs_unwatch ({ name }). The first message of each conversation says jobs are watched and names them, so Claude stops writing until … sleep loops and running ps. They need no permission prompt: they only read the mod's own list.tail, checks processes with ps (one listing, or a per-pid lookup when only pids are watched), and runs df. A probe that times out or takes over 2 s is retried at a doubling interval, up to 5 minutes, until it is fast again. The debug log names a probe's pace only once it has held for two probes in a row, and at most once per five minutes per probe, so a pace that flips with the Mac's load leaves no trail.Settings (in /config): stall minutes (10), refresh seconds (10), how long finished jobs stay (120 min; a timer leaves after a minute), auto-open (on), which disks to show.
Memory, swap and GPU on the status line, a machine_status tool for Claude, and a guard that refuses heavy local jobs when the Mac can't take them.
RAM tight 12% free · swap 7.9/8G · top python 31G · GPU 87%, and CPU 4/16 cores whenever macOS has parked the performance cores. "Free" is unused memory (vm_stat's free + inactive + speculative pages): what a new job can take without pushing anyone out. macOS's own "memory free percentage" counts active pages too, which is how a Mac can be "55% free" with the swap nearly full.sysctl calls and vm_stat), every 15 s by default; the GPU (ioreg) on every third sample, never right after a slow one. One session samples and writes ~/.claude/machine-guard/sample.json (with a lock.json while it probes); every other session shows the same numbers instead of probing too. When probes are slow or time out (10–40 s while the Mac swaps) on two samples in a row, the interval doubles, and doubles again with each further slow sample, up to 2 min; a single slow sample is a blip and changes nothing. The configured pace returns once two samples in a row are fast again. The other sessions follow the sampler's pace, so a blip stays quiet in every session.kern.sched_recommended_cores, the bitmask of CPUs the scheduler may use. When macOS's performance controller parks the performance cores (after a thermal event, or stuck until a sleep/wake or reboot), the status line shows CPU 4/16 cores, machine_status and /guard report it with the parked count, you get one toast once at least half the cores have been parked for a minute, or any parking has lasted five minutes (masks blip for seconds under GPU load), and one when they come back, and Claude gets a note when it starts heavy work so it keeps worker counts small. The guard never blocks on it.ps, the slowest probe) is taken only on demand (/guard, machine_status) or when a sample shows pressure, at most once a minute; "biggest" means the apps from a table taken in the last 5 minutes./busy.When memory is only tight (under 20% free, or kernel level 2), the job runs and Claude gets a note to start one heavy job at a time.
machine_status is a tool Claude can call (no input, allowed without asking): the sample's age, RAM free, swap, GPU, the pressure level, the biggest apps (or how to get a table), the guard's verdict and its rules. Claude is told to use it instead of ps, top, vm_stat, memory_pressure or project scripts before launching heavy work./busy 3h training a vision model reserves the Mac in every Claude session. /busy off lifts it. The reservation lives in ~/.claude/machine-guard.json, so a training script can write it too: ``bash echo '{"reason":"overnight training","until":'$(( ($(date +%s) + 8*3600) * 1000 ))'}' > ~/.claude/machine-guard.json ``/guard shows what it sees (and takes a process table when one is due). /guard pause 15m lets heavy jobs through in this session; /guard on resumes the guard.modal run, ssh), tests (pytest) and installs are never treated as heavy.overnight_|nightly_run\.sh.Watches how the other mods behave in real use, without changing them. It is listed first in CLAUDE_CODE_PLUGIN_DIRS, so the other mods' hooks run beneath it.
next.trace), with the mod's name, the event and how long it ran. Slow hooks (over 1.5 s) are recorded too. The first failure of each mod in a session raises a toast.rg, grep, pgrep or pkill exiting 1 with nothing on stderr (no match, no such process), are logged as expected (proc-expected, with why), not as failures; an exit of 2 or more, or anything on stderr, still counts. It also records model calls (the only usage the mods cost: /second-opinion, /recall ask) and file writes (folders only, never contents)./mods: a pane with one row per mod: ✓ active, ⚠ failing, ✗ not seen this session, · seen but idle. Each row shows today's counts and last activity, with Details for its recent events. It also says which mods it can't see, if any of them run above it./mods report [24h|7d|30d]: a per-mod report across all sessions, also written to ~/.claude/mods/monitor/report-latest.md for a scheduled review or Claude to read./mods failures [7d]: failures and failed subprocesses only.~/.claude/mods/monitor/<date>/<session>.jsonl, flushed every minute and at session end, with secrets masked and old days removed after 30 days.$.ui.log with wording like "failed" or "could not"): shown in Details and in /mods failures. Three in an hour mark the mod ⚠ and raise one toast. That is how effort-router's per-request hook, which runs inside the response stream where no monitor should sit, reports a failure. It also always sends the request on unchanged./secrets records there) are watched for failures and slow runs, but not counted per run.Settings: alerts (on), slowMs (1500), watchRender (on), watchCommands (on; off stops "mod-monitor" appearing beside other mods' command output), watchAppend (on), retentionDays (30), flushSeconds (60).
Keeps an eye on Modal so idle GPU containers don't burn credits — in the projects that use Modal, with one CLI run per minute for the whole machine.
.py file with import modal / from modal import … (one rg run, 5 s at most), or modal named in pyproject.toml, requirements*.txt, uv.lock or poetry.lock. The answer is remembered per project for a day. Running /modal, or any modal … command in Bash, switches it on for the session; alwaysPoll (off) watches every project.~/.claude/modal-meter/lock.json runs modal app list --json every pollSeconds (60) and writes cache.json; the other open sessions read the cache and refresh their own status line and pane from it. Once one session learns the CLI has no billing report, none tries it again for a day.app list over 2 s or a timeout doubles the interval (up to 10 minutes); a fast answer brings it back.Modal: 1 running (2 containers). Deployed apps with no containers cost nothing, so they stay off it.alertMinutes (30), repeated at most every 30 minutes./modal opens a pane of apps with state, containers and uptime. Stop asks for Confirm, then runs modal app stop. Nothing is stopped any other way.budgetToday where the Modal CLI supports billing report (1.3.3+, Team/Enterprise workspaces). Otherwise /modal says why spend isn't shown.modal or python3 -m modal. It checks PATH first rather than running a command that can only fail, never retries one that isn't there, and stays silent when Modal isn't set up.Does the "merged #219, clean up branches and start #214" round trip for you, and surfaces CI failures with their logs.
gh pr create Claude runs. It polls gh pr view every 60s.PRs: #219 ✓ · #220 CI… · #221 ✗, for every watched PR.gh pr create) or you added with /prs watch, and for any PR whose branch this worktree has checked out. PRs adopted from the repository at start stay on the status line, in /prs and in prs_status, and still get the merge ritual, but their CI results don't toast — so with seven worktree sessions of one repo a result toasts once, where it matters, not seven times. toastAdoptedCi (off) brings back toasts for every watched PR.git fetch --prune, switch to the default branch (only from the PR's own branch) and git pull --ff-only.--force, never other branches.git worktree add, such as Claude Code's .claude/worktrees/<name> sessions) it only fetches: it never switches or pulls there, because the default branch is checked out in the primary worktree and the switch could only fail ('main' is already used by worktree …). When the merged branch is the one the worktree has checked out, the toast says #N merged → this worktree's branch; remove the worktree when you're done (git worktree remove <path>) and the Tab suggestion tells Claude the branch and worktree stay until you remove them. In the primary worktree the ritual is unchanged.gh pr checks and the tail of the failed log attached, so you don't paste it.prs_status (number, title, state, branch, CI, URL, and how old the data is), instead of running gh pr view or gh pr checks itself: no API call, and it refreshes first when the data is older than a poll.Resource not accessible by personal access token), it tells you once with the fix (gh auth login --web, or grant the token "Checks: read"), keeps polling the PRs without their checks so merges are still handled, shows them as #219 CI?, and tries the checks again after 30 minutes or when you run /prs. If gh can't read PRs at all (not logged in), the status line says PRs: gh can't read them and nothing is polled until then. A GitHub rate limit pauses polling for 5 minutes; any other failure doubles the wait up to 10 minutes, back to normal on the next success. Nothing retries every minute forever; the debug log gets one line per change./prs lists watched PRs and asks gh again at once. /prs watch <n|url> and /prs forget <n|all> add and remove them.gh and git, at about one GitHub API call per open PR per minute.Settings:
pollSeconds (60)authRetryMinutes (30): how long before the checks are tried again after gh refused them over auth.attachCiLogs (on)logLines (120)deleteRemoteBranch (off): deletes the branch on GitHub too, only while it still points at the merged commit. GitHub's own "Automatically delete head branches" setting does the same job.toastAdoptedCi (off): toast the CI results of PRs adopted from the repository too, as every PR's used to; with several worktree sessions of one repo, each would toast.It never closes issues; put "Closes #N" in PR bodies for that.
Search everything you've done with coding agents, from Claude or from /recall. It replaces the broken agent-memory plugin.
/remember notes. Routine (scheduled) runs are left out unless you add routines:include to a query.grep and cat are kept but ranked low.search, expand, recap and list, which run without permission prompts. It checks them when you say "like last time" or "what did we decide", and before asking you something you already settled./goal (or the Stop hook's condition), open tasks with a count of the done ones, the questions you asked with the first line of each answer, the files touched, the commits made and PRs opened. After a compaction it goes back into Claude's context as Ledger (this session, before compaction) (about 40 lines at most), so you don't have to say "don't lose track of where we were". /recall ledger prints it any time; /clear starts a fresh one. It is written to ~/.claude/recall/ledger/<session>.json (readable only by you, secrets masked) so a reload keeps it./recall <query> opens a pane of hits grouped by session. Open shows the conversation around a hit, Attach sends it with your next message, and Copy resume command copies claude --resume <id>./recall last [n] recaps your last session in this repo: last asks, last answer, PRs, commits, open tasks and decisions. Send to Claude attaches it./recall ledger prints this session's ledger (above)./recall timeline [7d|30d|90d] [all]/recall decisions|commands|files|prs|commits|issues|urls|tasks|notes [query]/recall ask <question> answers from your history with Haiku 4.5, citing sessions. It costs a little usage and sends the matching excerpts to the model./recall stats, /recall reindex, /recall forget session <id>|project <name>|before <date> (asks you to confirm), /recall help./remember <fact>, /remember list, /remember forget <ref>.Last session here (2d ago): "…" · PR #99 · 3 open tasks [Recap].#214, ABC-12, a file name or a quoted phrase seen in past sessions, a band offers what happened then. Nothing is sent unless you click.OR gives alternatives, "quotes" an exact phrase, and -word excludes. Filters: project:name, kind:decision, since:7d, until:2026-09-30, source:codex, routines:include.~/.claude/recall/index.db, readable only by you, and never goes in a repo. The ledgers beside it are kept the same way.~/.zshrc, ~/.zprofile, ~/.bashrc and `~/.bash_profilehooks/register.tsx 952 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PluginOptions, ProcessRunInit, ProcessRunResult, Register } from 'claude-code'
3
4import type { CachedListener, Holder, KnownEntry, Listener, ProcessDetail, ScanCache, ScanLock, Server, Snapshot } from '../types'
5import {
6 describe,
7 detectManager,
8 expandHome,
9 findConflict,
10 holderNote,
11 isClaudeCode,
12 isFresh,
13 isInside,
14 isSystemProgram,
15 knownEntries,
16 lastLines,
17 LOCKFILES,
18 logPath,
19 matchServers,
20 MAX_POLL_MS,
21 mayScan,
22 nextPollMs,
23 packageScripts,
24 parseCwds,
25 parseListeners,
26 parseNetstat,
27 parseProcesses,
28 parseScanCache,
29 parseScanLock,
30 parseSs,
31 portFromCommand,
32 portList,
33 programOf,
34 serverLine,
35 SLOW_MS,
36 startScript,
37 statusLine,
38 toolText,
39 upSince,
40} from './servers'
41
42type Engine = EngineInterface
43
44const PANE = 'dev-servers'
45const TITLE = 'Servers'
46/** The read-only tool the model gets, listed as `mcp__dev-servers__dev_servers`. */
47const TOOL = 'dev_servers'
48/** How often a wait (a stop, a free port, a start) looks again. */
49const STEP_MS = 500
50/** How long a start waits for its port before saying it is not up. */
51const START_WAIT_MS = 10_000
52/** How long a restart waits for the stopped server's ports to be free. */
53const FREE_WAIT_MS = 10_000
54/** How long after Stop a second press force stops (SIGKILL). */
55const FORCE_WINDOW_MS = 10_000
56/** How long a force stop waits for the process to go. */
57const KILL_WAIT_MS = 2_000
58/** Pane widths below this draw a row's buttons on a line of their own. */
59const STACK_BELOW = 64
60/** How long the listen scan (netstat, ss or lsof) may take. */
61const SCAN_TIMEOUT_MS = 10_000
62/** How long one pid's ps or lsof may take. */
63const DETAIL_TIMEOUT_MS = 3_000
64/** How long one scan spends on pids it has not seen; the rest wait for the next scan. */
65const DETAIL_BUDGET_MS = 6_000
66/** A lock older than this was left by a scan that never finished. */
67const LOCK_STALE_MS = SCAN_TIMEOUT_MS + DETAIL_BUDGET_MS + DETAIL_TIMEOUT_MS
68/** A cache this much younger than the poll interval still stands at a session's next tick. */
69const CACHE_SLACK_MS = 2_000
70/** A log written this close to a server's start (ps counts whole seconds) is that server's own. */
71const LOG_SLACK_MS = 5_000
72/** Where every session's scan meets, beside the logs: the cache and the lock. */
73const SHARED_DIR = '~/.claude/dev-servers'
74const CACHE_FILE = 'scan-cache.json'
75const LOCK_FILE = 'scan-lock.json'
76/** The commands that list listening TCP ports, tried in order; the first whose table parses is kept for the session. */
77const SCANNERS: readonly { argv: readonly string[]; parse: (text: string) => Listener[] | null }[] = [
78 { argv: ['netstat', '-anv', '-p', 'tcp'], parse: parseNetstat },
79 { argv: ['ss', '-ltnp'], parse: parseSs },
80 { argv: ['lsof', '-nP', '-iTCP', '-sTCP:LISTEN', '-Fpcn'], parse: parseListeners },
81]
82
83const TOOL_DESCRIPTION = [
84 "Lists this project's dev servers: which are running (name, port, pid, uptime, and the log file when it was started from the Servers pane) and which known start commands (package.json scripts, .claude/launch.json, Procfile) are not running. With all: true it also lists every other TCP listener on this machine, with its port and process; Claude Code's own sessions are left out and only counted.",
85 'Use it instead of running lsof, netstat, ss or ps in Bash to learn what is listening on which port, whether a dev server is up, or who holds a port: it answers from a scan every open session shares, where lsof alone can take 10s or more on a loaded machine.',
86 'Read-only: it never starts, stops or restarts anything; the person does that with the Start, Stop and Restart buttons of the Servers pane (/servers).',
87].join(' ')
88
89/** What the model gets with `$.tool.register`: the tool, in the prompt's list from the start so it is reached for. */
90const TOOL_SPEC = {
91 name: TOOL,
92 description: TOOL_DESCRIPTION,
93 inputSchema: {
94 type: 'object',
95 properties: {
96 all: {
97 type: 'boolean',
98 description: 'Also list the listeners outside this project, each with its port and process (to find who holds a port).',
99 },
100 },
101 },
102 isDeferred: false,
103}
104
105const snapshot = atom({ plugin: 'dev-servers', key: 'snapshot' } as const, null)
106const busy = atom({ plugin: 'dev-servers', key: 'busy' } as const, {})
107const armed = atom({ plugin: 'dev-servers', key: 'armed' } as const, {})
108
109type Config = { pollMs: number; logDir: string; graceMs: number }
110
111let config: Config = { pollMs: 15_000, logDir: '~/.claude/dev-servers', graceMs: 5_000 }
112let timer: { cancel: () => void } | null = null
113/** The poll interval now: the configured one, doubled while scans are slow. */
114let pollMs = config.pollMs
115/** The scan under way, and whether it was asked to look past the shared cache. */
116let inflight: { promise: Promise<Snapshot | null>; isForced: boolean } | null = null
117/** The status line last shown; null before the first. */
118let shownStatus: string | undefined | null = null
119let rootFor: { cwd: string; root: string } | null = null
120/** Which of SCANNERS lists ports on this machine. */
121let scanner = 0
122/** What ps and lsof said about each listening pid, kept while it listens and shared through the cache. */
123const details = new Map<number, ProcessDetail>()
124let sessionId: string | null = null
125let warnedWrite = false
126
127/** A host command's result, or null when it could not start or timed out. */
128async function run($: Engine, argv: readonly string[], init?: ProcessRunInit): Promise<ProcessRunResult | null> {
129 return $.process.run(argv, { timeoutMs: 10_000, ...init }).catch(() => null)
130}
131
132/** A host command's result, or why there is none: still running at `timeoutMs`, or it could not start (missing, refused). */
133async function attempt($: Engine, argv: readonly string[], timeoutMs: number): Promise<ProcessRunResult | 'timeout' | 'failed'> {
134 try {
135 return await $.process.run(argv, { timeoutMs })
136 } catch (error) {
137 return /still running/.test(String(error)) ? 'timeout' : 'failed'
138 }
139}
140
141/** The git top level of the session's folder, else the folder itself. */
142async function projectRoot($: Engine): Promise<string> {
143 const cwd = await $.session.cwd()
144 if (rootFor?.cwd === cwd) {
145 return rootFor.root
146 }
147 const out = await run($, ['git', 'rev-parse', '--show-toplevel'], { cwd })
148 const top = out?.exitCode === 0 ? out.stdout.trim() : ''
149 rootFor = { cwd, root: top || cwd }
150 return rootFor.root
151}
152
153async function readText($: Engine, path: string): Promise<string | null> {
154 return $.fs.read(path).catch(() => null)
155}
156
157/** package.json server scripts, .claude/launch.json configurations and Procfile lines. */
158async function readEntries($: Engine, root: string): Promise<KnownEntry[]> {
159 const names = new Set((await $.fs.list(root).catch(() => [])).map(entry => entry.name))
160 const [packageJson, launchJson, procfile] = await Promise.all([
161 names.has('package.json') ? readText($, `${root}/package.json`) : null,
162 names.has('.claude') ? readText($, `${root}/.claude/launch.json`) : null,
163 names.has('Procfile') ? readText($, `${root}/Procfile`) : null,
164 ])
165 const lockfiles = LOCKFILES.map(([file]) => file).filter(file => names.has(file))
166 const manager = detectManager(lockfiles, packageJson === null ? undefined : packageScripts(packageJson)?.packageManager)
167 return knownEntries({ packageJson, launchJson, procfile, manager })
168}
169
170function showStatus($: Engine, servers: readonly Server[]) {
171 const text = statusLine(servers)
172 if (text !== shownStatus) {
173 shownStatus = text
174 $.ui.status(text)
175 }
176}
177
178/** `dir` with `~` expanded; a folder under /tmp when there is no home to expand it with. */
179async function resolvedDir($: Engine, dir: string): Promise<string> {
180 const home = await $.env.get('HOME').catch(() => undefined)
181 const expanded = expandHome(dir, home)
182 return expanded.startsWith('~') ? '/tmp/dev-servers' : expanded
183}
184
185/** `~/.claude/dev-servers/<name>`: a file every session reads and writes. */
186async function sharedPath($: Engine, name: string): Promise<string> {
187 return `${(await resolvedDir($, SHARED_DIR)).replace(/\/+$/, '')}/${name}`
188}
189
190async function whoAmI($: Engine): Promise<string> {
191 if (sessionId === null) {
192 sessionId = await $.session.id().catch(() => 'unknown')
193 }
194 return sessionId
195}
196
197/** Writes a shared file; a failure is said once, in the debug log, never every tick. */
198async function writeShared($: Engine, path: string, value: ScanCache | ScanLock) {
199 try {
200 await $.fs.write(path, JSON.stringify(value))
201 } catch (error) {
202 if (!warnedWrite) {
203 warnedWrite = true
204 $.ui.log(`dev-servers: could not write ${path}: ${String(error)}`, { to: 'debug' })
205 }
206 }
207}
208
209// ---------------------------------------------------------------------------
210// The scan: netstat for the ports, ps and lsof once per new pid
211// ---------------------------------------------------------------------------
212
213/** The listening pids as the first scanner that works here lists them, and how long it took; null when none answered in time. */
214async function scanListeners($: Engine): Promise<{ listeners: Listener[]; tookMs: number } | null> {
215 const began = await $.clock.now()
216 for (;;) {
217 const step = SCANNERS[scanner]
218 if (step === undefined) {
219 return null
220 }
221 const out = await attempt($, step.argv, SCAN_TIMEOUT_MS)
222 if (out === 'timeout') {
223 return null
224 }
225 const listeners = out === 'failed' ? null : step.parse(out.stdout)
226 if (listeners !== null) {
227 return { listeners, tookMs: (await $.clock.now()) - began }
228 }
229 const next = SCANNERS[scanner + 1]
230 if (next === undefined) {
231 return null
232 }
233 $.ui.log(`dev-servers: ${step.argv[0]} does not list ports here; trying ${next.argv[0]}`, { to: 'debug' })
234 scanner += 1
235 }
236}
237
238/** The first process listening on `port`, from the listen scan. */
239async function listenerOn($: Engine, port: number): Promise<Listener | null> {
240 const scanned = await scanListeners($)
241 return scanned?.listeners.find(listener => listener.ports.includes(port)) ?? null
242}
243
244/**
245 * What ps and lsof say about one pid: its command line and start from ps, then its working directory from
246 * lsof, unless the program is the system's own, Claude Code's own or already gone. 'timeout' when either did
247 * not answer in time.
248 */
249async function lookupDetail($: Engine, pid: number): Promise<ProcessDetail | 'timeout'> {
250 const ps = await attempt($, ['ps', '-o', 'pid=,etime=,command=', '-p', String(pid)], DETAIL_TIMEOUT_MS)
251 if (ps === 'timeout') {
252 return 'timeout'
253 }
254 const row = ps === 'failed' ? undefined : parseProcesses(ps.stdout).get(pid)
255 if (row === undefined) {
256 return { commandLine: null, startedAt: null, cwd: null }
257 }
258 const startedAt = row.upSeconds === null ? null : (await $.clock.now()) - row.upSeconds * 1000
259 if (isSystemProgram(row.commandLine) || isClaudeCode(row.commandLine)) {
260 return { commandLine: row.commandLine, startedAt, cwd: null }
261 }
262 const cwd = await attempt($, ['lsof', '-a', '-p', String(pid), '-d', 'cwd', '-Fn'], DETAIL_TIMEOUT_MS)
263 if (cwd === 'timeout') {
264 return 'timeout'
265 }
266 return { commandLine: row.commandLine, startedAt, cwd: cwd === 'failed' ? null : (parseCwds(cwd.stdout).get(pid) ?? null) }
267}
268
269/** One pid's detail: as known, else looked up now and kept; null when the lookup timed out. */
270async function detailOf($: Engine, pid: number): Promise<ProcessDetail | null> {
271 const known = details.get(pid)
272 if (known !== undefined) {
273 return known
274 }
275 const found = await lookupDetail($, pid)
276 if (found === 'timeout') {
277 return null
278 }
279 details.set(pid, found)
280 return found
281}
282
283/** Who holds `port`: its process, how long it has run and in which folder. */
284async function holderOf($: Engine, port: number): Promise<Holder | null> {
285 const first = await listenerOn($, port)
286 if (first === null) {
287 return null
288 }
289 const detail = await detailOf($, first.pid)
290 return {
291 pid: first.pid,
292 command: first.command || programOf(detail?.commandLine ?? '') || `pid ${first.pid}`,
293 upSeconds: upSince(detail?.startedAt ?? null, await $.clock.now()),
294 cwd: detail?.cwd ?? null,
295 }
296}
297
298/** Whether none of `ports` is listened on; false as well when the scan did not answer. */
299async function portsFree($: Engine, ports: readonly number[]): Promise<boolean> {
300 const scanned = await scanListeners($)
301 return scanned !== null && ports.every(port => !scanned.listeners.some(listener => listener.ports.includes(port)))
302}
303
304/** Doubles the poll interval after a slow scan, to five minutes; the configured one again after a fast one. Says so once per change. */
305function pace($: Engine, isSlow: boolean, tookMs: number | null) {
306 const next = nextPollMs(pollMs, config.pollMs, isSlow)
307 if (next === pollMs) {
308 return
309 }
310 const why = !isSlow ? 'is fast again' : tookMs === null ? 'did not answer in time' : `was slow (${tookMs}ms)`
311 $.ui.log(`dev-servers: the port scan ${why}; polling every ${Math.round(next / 1000)}s (at most ${MAX_POLL_MS / 60_000}m)`, {
312 to: 'debug',
313 })
314 pollMs = next
315 timer?.cancel()
316 timer = $.clock.every(pollMs, () => void refresh($, false))
317}
318
319/** Pids on a known entry's port first: the likeliest to be this project's. */
320function prioritized(listeners: readonly Listener[], entries: readonly KnownEntry[]): Listener[] {
321 const ports = new Set(entries.map(entry => entry.port).filter((port): port is number => port !== null))
322 const onKnownPort = (listener: Listener) => listener.ports.some(port => ports.has(port))
323 return [...listeners].sort((a, b) => Number(onKnownPort(b)) - Number(onKnownPort(a)))
324}
325
326/**
327 * Lists the listeners now: the scan, then ps and lsof for each pid not seen before, one pid at a time and
328 * within a time budget (the rest wait for the next scan). Paces the poll by how the scan went.
329 */
330async function scanNow($: Engine, entries: readonly KnownEntry[]): Promise<CachedListener[] | null> {
331 const scanned = await scanListeners($)
332 if (scanned === null) {
333 pace($, true, null)
334 return null
335 }
336 const until = (await $.clock.now()) + DETAIL_BUDGET_MS
337 let timedOut = false
338 for (const listener of prioritized(scanned.listeners, entries)) {
339 if (details.has(listener.pid)) {
340 continue
341 }
342 if ((await $.clock.now()) > until) {
343 break
344 }
345 const found = await lookupDetail($, listener.pid)
346 if (found === 'timeout') {
347 timedOut = true
348 break
349 }
350 details.set(listener.pid, found)
351 }
352 const listening = new Set(scanned.listeners.map(listener => listener.pid))
353 for (const pid of [...details.keys()]) {
354 if (!listening.has(pid)) {
355 details.delete(pid)
356 }
357 }
358 pace($, timedOut || scanned.tookMs > SLOW_MS, scanned.tookMs)
359 return scanned.listeners.map(listener => ({ ...listener, detail: details.get(listener.pid) ?? null }))
360}
361
362/** Takes what another session learned about pids lately as our own: as good as a lookup, and spares one. */
363function adoptDetails(cache: ScanCache | null, now: number) {
364 if (cache === null || now - cache.ts >= MAX_POLL_MS) {
365 return
366 }
367 for (const listener of cache.data.listeners) {
368 if (listener.detail !== null && !details.has(listener.pid)) {
369 details.set(listener.pid, listener.detail)
370 }
371 }
372}
373
374/**
375 * Every session's view of the listeners: a fresh shared cache as it is; else, unless another session is
376 * scanning, a scan of our own, written back for the others. `force` scans whatever the cache says.
377 */
378async function sharedListeners(
379 $: Engine,
380 entries: readonly KnownEntry[],
381 force: boolean,
382): Promise<{ listeners: CachedListener[]; scannedAt: number } | null> {
383 const [cachePath, lockPath, me, now] = await Promise.all([
384 sharedPath($, CACHE_FILE),
385 sharedPath($, LOCK_FILE),
386 whoAmI($),
387 $.clock.now(),
388 ])
389 const [cache, lock] = await Promise.all([readText($, cachePath).then(parseScanCache), readText($, lockPath).then(parseScanLock)])
390 const cached = cache === null ? null : { listeners: cache.data.listeners, scannedAt: cache.ts }
391 adoptDetails(cache, now)
392 if (!force) {
393 if (cache !== null && isFresh(cache.ts, now, Math.max(1_000, config.pollMs - CACHE_SLACK_MS))) {
394 return cached
395 }
396 if (!mayScan(lock, now, me, LOCK_STALE_MS)) {
397 return cached
398 }
399 }
400 await writeShared($, lockPath, { ts: now, by: me })
401 const listeners = await scanNow($, entries)
402 if (listeners === null) {
403 return null
404 }
405 await writeShared($, cachePath, { ts: now, by: me, data: { listeners } })
406 return { listeners, scannedAt: now }
407}
408
409/** One scan: every TCP listener (shared across sessions), which of them run inside the project, and the known entries. */
410async function collect($: Engine, force: boolean): Promise<Snapshot | null> {
411 const root = await projectRoot($)
412 const entries = await readEntries($, root)
413 const shared = await sharedListeners($, entries, force)
414 if (shared === null) {
415 return read($, snapshot)
416 }
417 const now = await $.clock.now()
418 // Claude Code's own sessions listen on localhost from the project's folder: neither its servers nor listeners worth naming.
419 const isSession = (listener: CachedListener) => isClaudeCode(listener.command) || isClaudeCode(listener.detail?.commandLine ?? '')
420 const listeners = shared.listeners.filter(listener => !isSession(listener))
421 const isMine = (listener: CachedListener) =>
422 listener.detail !== null && listener.detail.cwd !== null && isInside(listener.detail.cwd, root)
423 const mine = listeners.filter(isMine)
424 const servers: Server[] = mine.map(listener => {
425 const commandLine = listener.detail?.commandLine ?? ''
426 return {
427 pid: listener.pid,
428 name: programOf(commandLine) || listener.command || `pid ${listener.pid}`,
429 entryId: null,
430 ports: listener.ports,
431 cwd: listener.detail?.cwd ?? root,
432 upSeconds: upSince(listener.detail?.startedAt ?? null, now),
433 commandLine: commandLine || listener.command,
434 }
435 })
436 const matched = matchServers(servers, entries)
437 const fresh: Snapshot = {
438 root,
439 servers: matched.servers,
440 entries,
441 stopped: matched.stopped,
442 others: listeners.length - mine.length,
443 otherListeners: listeners.filter(listener => !isMine(listener)),
444 claudeSessions: shared.listeners.length - listeners.length,
445 scannedAt: shared.scannedAt,
446 at: now,
447 }
448 await update($, snapshot, () => fresh)
449 showStatus($, fresh.servers)
450 return fresh
451}
452
453/**
454 * Scans now and draws the result; a scan already under way is shared, not repeated. A forced scan (a press,
455 * a command, the tool) looks past the shared cache, and follows one under way that did not.
456 */
457function refresh($: Engine, force: boolean): Promise<Snapshot | null> {
458 if (inflight !== null && (inflight.isForced || !force)) {
459 return inflight.promise
460 }
461 const previous = inflight?.promise ?? Promise.resolve(null)
462 const promise: Promise<Snapshot | null> = previous
463 .then(() => collect($, force))
464 .catch(() => null)
465 .finally(() => {
466 if (inflight?.promise === promise) {
467 inflight = null
468 }
469 })
470 inflight = { promise, isForced: force }
471 return promise
472}
473
474function ensureTimer($: Engine) {
475 if (!timer) {
476 timer = $.clock.every(pollMs, () => void refresh($, false))
477 }
478}
479
480// ---------------------------------------------------------------------------
481// Starting, stopping, logs
482// ---------------------------------------------------------------------------
483
484/** Calls `check` every `stepMs` until it answers true (true) or `ms` has passed (false). */
485async function waitFor($: Engine, ms: number, stepMs: number, check: () => Promise<boolean>): Promise<boolean> {
486 const until = (await $.clock.now()) + ms
487 for (;;) {
488 if (await check()) {
489 return true
490 }
491 const now = await $.clock.now()
492 if (now >= until) {
493 return false
494 }
495 await $.clock.sleep(Math.min(stepMs, until - now))
496 }
497}
498
499async function setBusy($: Engine, key: string, label: string | null) {
500 await update($, busy, all => {
501 const next = { ...all }
502 if (label === null) {
503 delete next[key]
504 } else {
505 next[key] = label
506 }
507 return next
508 })
509}
510
511async function pruneArmed($: Engine) {
512 const now = await $.clock.now()
513 await update($, armed, all => Object.fromEntries(Object.entries(all).filter(([, until]) => until > now)))
514}
515
516/** Opens the force-stop window for `pid`: a Stop pressed before it ends sends SIGKILL. */
517async function arm($: Engine, pid: number) {
518 const until = (await $.clock.now()) + FORCE_WINDOW_MS
519 await update($, armed, all => ({ ...all, [String(pid)]: until }))
520 $.clock.after(FORCE_WINDOW_MS, () => void pruneArmed($))
521}
522
523async function disarm($: Engine, pid: number) {
524 await update($, armed, all => Object.fromEntries(Object.entries(all).filter(([key]) => key !== String(pid))))
525}
526
527async function isGone($: Engine, pid: number): Promise<boolean> {
528 const out = await run($, ['kill', '-0', String(pid)])
529 return out !== null && out.exitCode !== 0
530}
531
532/** Sends `signal` to `pid`, and to its process group when it leads one; whether the pid took it. */
533async function signal($: Engine, pid: number, name: 'TERM' | 'KILL'): Promise<boolean> {
534 const group = await run($, ['ps', '-o', 'pgid=', '-p', String(pid)])
535 const leads = group?.exitCode === 0 && Number(group.stdout.trim()) === pid
536 const out = await run($, ['kill', `-${name}`, String(pid)])
537 if (leads) {
538 await run($, ['kill', `-${name}`, '--', `-${pid}`])
539 }
540 return out?.exitCode === 0
541}
542
543/** Whether `pid` still runs the command line the pane drew it with: a pid reused since is never signalled. */
544async function pidState($: Engine, server: Server): Promise<'same' | 'gone' | 'other'> {
545 const out = await run($, ['ps', '-o', 'pid=,etime=,command=', '-p', String(server.pid)])
546 const now = parseProcesses(out?.stdout ?? '').get(server.pid)
547 return now === undefined ? 'gone' : now.commandLine === server.commandLine ? 'same' : 'other'
548}
549
550/** Whether the pid may be signalled; when it is gone or now runs something else, says so and refreshes. */
551async function mayStop($: Engine, server: Server, quiet: boolean): Promise<'same' | 'gone' | 'other'> {
552 const state = await pidState($, server)
553 if (state === 'other') {
554 $.ui.toast(`pid ${server.pid} no longer runs ${server.name}; nothing was signalled`)
555 } else if (state === 'gone' && !quiet) {
556 $.ui.toast(`${server.name} (pid ${server.pid}) has already stopped`)
557 }
558 if (state !== 'same') {
559 void refresh($, true)
560 }
561 return state
562}
563
564/** SIGTERM, then up to the grace period for it to exit. True once it is gone. */
565async function stopServer($: Engine, server: Server, quiet: boolean): Promise<boolean> {
566 const key = `pid-${server.pid}`
567 const state = await mayStop($, server, quiet)
568 if (state !== 'same') {
569 return state === 'gone'
570 }
571 await arm($, server.pid)
572 await setBusy($, key, 'stopping')
573 try {
574 const took = await signal($, server.pid, 'TERM')
575 const gone = await waitFor($, config.graceMs, STEP_MS, () => isGone($, server.pid))
576 if (gone) {
577 // A force stop pressed meanwhile disarmed it and says so itself.
578 const stillArmed = (await read($, armed))[String(server.pid)] !== undefined
579 await disarm($, server.pid)
580 if (stillArmed && !quiet) {
581 $.ui.toast(`Stopped ${server.name} (pid ${server.pid})`)
582 }
583 return true
584 }
585 if (!took) {
586 await disarm($, server.pid)
587 $.ui.toast(`Could not signal ${server.name} (pid ${server.pid}): kill was refused`)
588 return false
589 }
590 await arm($, server.pid)
591 $.ui.toast(
592 `${server.name} (pid ${server.pid}) is still running ${Math.round(config.graceMs / 1000)}s after SIGTERM. Press Stop again within ${FORCE_WINDOW_MS / 1000}s to force stop it.`,
593 { timeoutMs: FORCE_WINDOW_MS },
594 )
595 return false
596 } finally {
597 await setBusy($, key, null)
598 void refresh($, true)
599 }
600}
601
602/** SIGKILL: only ever from a second Stop press inside the force window. */
603async function forceStop($: Engine, server: Server) {
604 const key = `pid-${server.pid}`
605 await disarm($, server.pid)
606 if ((await mayStop($, server, false)) !== 'same') {
607 return
608 }
609 await setBusy($, key, 'force stopping')
610 try {
611 await signal($, server.pid, 'KILL')
612 const gone = await waitFor($, KILL_WAIT_MS, STEP_MS, () => isGone($, server.pid))
613 $.ui.toast(
614 gone
615 ? `Force stopped ${server.name} (pid ${server.pid}) with SIGKILL`
616 : `${server.name} (pid ${server.pid}) is still there after SIGKILL`,
617 )
618 } finally {
619 await setBusy($, key, null)
620 void refresh($, true)
621 }
622}
623
624async function pressStop($: Engine, server: Server) {
625 const until = (await read($, armed))[String(server.pid)]
626 if (until !== undefined && (await $.clock.now()) <= until) {
627 await forceStop($, server)
628 return
629 }
630 if ((await read($, busy))[`pid-${server.pid}`] !== undefined) {
631 return
632 }
633 await stopServer($, server, false)
634}
635
636async function logFile($: Engine, root: string, entry: KnownEntry): Promise<string> {
637 return logPath(await resolvedDir($, config.logDir), root, entry)
638}
639
640async function lastLogLine($: Engine, log: string): Promise<string> {
641 const out = await run($, ['tail', '-n', '20', log])
642 return out?.exitCode === 0 ? (lastLines(out.stdout, 1)[0] ?? '') : ''
643}
644
645/** A server matched to `entry` that was not running before, by its port or the next scan. */
646async function startedServer(
647 $: Engine,
648 entry: KnownEntry,
649 before: ReadonlySet<number>,
650): Promise<{ pid: number; ports: number[] } | null> {
651 if (entry.port !== null) {
652 const first = await listenerOn($, entry.port)
653 return first === null ? null : { pid: first.pid, ports: [entry.port] }
654 }
655 const fresh = await refresh($, true)
656 const server = fresh?.servers.find(one => one.entryId === entry.id && !before.has(one.pid))
657 return server === undefined ? null : { pid: server.pid, ports: server.ports }
658}
659
660/** Starts `entry` detached (nohup, output to its log), then waits up to 10s for it to listen. */
661async function startEntry($: Engine, entry: KnownEntry, verb: 'Started' | 'Restarted'): Promise<boolean> {
662 const key = `entry-${entry.id}`
663 await setBusy($, key, 'starting')
664 try {
665 if (entry.port !== null) {
666 const holder = await holderOf($, entry.port)
667 if (holder !== null) {
668 $.ui.toast(`${entry.name} was not started: ${holderNote(entry.port, holder)}`, { timeoutMs: 10_000 })
669 return false
670 }
671 }
672 const root = await projectRoot($)
673 const log = await logFile($, root, entry)
674 const before = new Set(((await read($, snapshot))?.servers ?? []).map(server => server.pid))
675 const out = await run($, ['sh', '-c', startScript(root, entry.command, log)], { cwd: root })
676 if (out === null || out.exitCode !== 0) {
677 const reason = out?.stderr.trim().split('\n').pop() || 'sh did not run'
678 $.ui.toast(`Could not start ${entry.name}: ${reason}`)
679 return false
680 }
681 const seen: { server: { pid: number; ports: number[] } | null } = { server: null }
682 await waitFor($, START_WAIT_MS, entry.port === null ? 1000 : STEP_MS, async () => {
683 seen.server = await startedServer($, entry, before)
684 return seen.server !== null
685 })
686 if (seen.server !== null) {
687 $.ui.toast(`${verb} ${entry.name} on ${portList(seen.server.ports)} (pid ${seen.server.pid})`)
688 return true
689 }
690 const last = await lastLogLine($, log)
691 const waiting =
692 entry.port === null
693 ? `${verb} ${entry.name}, but no new port is listening after ${START_WAIT_MS / 1000}s.`
694 : `${entry.name} has not opened :${entry.port} after ${START_WAIT_MS / 1000}s.`
695 $.ui.toast(last ? `${waiting} Log: ${last}` : `${waiting} Log: ${log}`, { timeoutMs: 10_000 })
696 return false
697 } finally {
698 await setBusy($, key, null)
699 void refresh($, true)
700 }
701}
702
703async function pressStart($: Engine, entry: KnownEntry) {
704 if ((await read($, busy))[`entry-${entry.id}`] === undefined) {
705 await startEntry($, entry, 'Started')
706 }
707}
708
709/** Stop, wait until its ports are free, start: never a start while the old one still holds the port. */
710async function restartServer($: Engine, server: Server, entry: KnownEntry) {
711 const working = await read($, busy)
712 if (working[`entry-${entry.id}`] !== undefined || working[`pid-${server.pid}`] !== undefined) {
713 return
714 }
715 const stopped = await stopServer($, server, true)
716 if (!stopped) {
717 return
718 }
719 const free = await waitFor($, FREE_WAIT_MS, STEP_MS, () => portsFree($, server.ports))
720 if (!free) {
721 $.ui.toast(
722 `${server.name} stopped, but ${portList(server.ports)} is still in use after ${FREE_WAIT_MS / 1000}s; not restarting`,
723 { timeoutMs: 10_000 },
724 )
725 return
726 }
727 await startEntry($, entry, 'Restarted')
728}
729
730/** Toasts the last three lines of the log a pane start wrote. */
731async function showLog($: Engine, entry: KnownEntry) {
732 const root = await projectRoot($)
733 const log = await logFile($, root, entry)
734 const out = await run($, ['tail', '-n', '50', log])
735 if (out === null || out.exitCode !== 0) {
736 $.ui.toast(`No log for ${entry.name}: only servers started from this pane write one (${log})`, { timeoutMs: 8_000 })
737 return
738 }
739 const lines = lastLines(out.stdout, 3)
740 $.ui.toast(lines.length > 0 ? `${entry.name}: ${lines.join(' | ')}` : `${entry.name}: the log is empty`, {
741 timeoutMs: 10_000,
742 })
743}
744
745/** The log of each running server that was started from the pane: its entry's log, written since the server started. */
746async function paneLogs($: Engine, fresh: Snapshot): Promise<Map<number, string>> {
747 const logs = new Map<number, string>()
748 for (const server of fresh.servers) {
749 const entry = fresh.entries.find(one => one.id === server.entryId)
750 if (entry === undefined) {
751 continue
752 }
753 const log = await logFile($, fresh.root, entry)
754 const stat = await $.fs.stat(log).catch(() => null)
755 const startedAt = server.upSeconds === null ? null : fresh.at - server.upSeconds * 1000
756 if (stat !== null && (startedAt === null || stat.mtimeMs >= startedAt - LOG_SLACK_MS)) {
757 logs.set(server.pid, log)
758 }
759 }
760 return logs
761}
762
763/** The dev_servers tool's answer: a scan now, then what it found, with the logs of pane starts. */
764async function listForModel($: Engine, all: boolean): Promise<string> {
765 ensureTimer($)
766 const fresh = await refresh($, true)
767 if (fresh === null) {
768 return 'dev-servers: the port scan (netstat) did not answer in time, so nothing could be listed; try again in a moment.'
769 }
770 return toolText(fresh, { all, logs: await paneLogs($, fresh), now: await $.clock.now() })
771}
772
773/** Reads the options and starts the module's state over, as a load or a reload does. */
774function configure(options: PluginOptions) {
775 const poll = Number(options.pollSeconds ?? 15)
776 const grace = Number(options.stopGraceSeconds ?? 5)
777 config = {
778 pollMs: Math.max(2, Number.isFinite(poll) ? poll : 15) * 1000,
779 logDir: String(options.logDir ?? '').trim() || '~/.claude/dev-servers',
780 graceMs: Math.min(60, Math.max(1, Number.isFinite(grace) ? grace : 5)) * 1000,
781 }
782 timer = null
783 pollMs = config.pollMs
784 inflight = null
785 shownStatus = null
786 rootFor = null
787 scanner = 0
788 details.clear()
789 sessionId = null
790 warnedWrite = false
791}
792
793/** When a command failed on a taken port: a toast naming the holder, and the note the model reads; null when there is none. */
794async function conflictNote($: Engine, command: string, output: string): Promise<string | null> {
795 const conflict = findConflict(output)
796 const port = conflict === null ? null : (conflict.port ?? portFromCommand(command))
797 if (port === null) {
798 return null
799 }
800 const holder = await holderOf($, port)
801 if (holder === null) {
802 return null
803 }
804 const note = holderNote(port, holder)
805 $.ui.toast(note, { timeoutMs: 10_000 })
806 const root = await projectRoot($)
807 const own = holder.cwd !== null && isInside(holder.cwd, root) ? " It is one of this project's servers; /servers can restart or stop it." : ''
808 return `dev-servers: ${note}.${own}`
809}
810
811export const register: Register = (on, options) => {
812 configure(options)
813
814 on('session.start', async ($, e, next) => {
815 await $.command.register({
816 name: 'servers',
817 description: "Open the Servers pane: this project's dev servers, with Start, Stop, Restart and Log",
818 immediate: true,
819 })
820 await $.tool
821 .register(TOOL_SPEC)
822 .catch(error => $.ui.log(`dev-servers: the ${TOOL} tool did not register: ${String(error)}`, { to: 'debug' }))
823 ensureTimer($)
824 // The first scan runs from a timer of its own: starting the session never waits on netstat, ps or lsof.
825 $.clock.after(0, () => void refresh($, false))
826 return next(e)
827 })
828
829 on('command.run', { command: 'servers' }, async $ => {
830 ensureTimer($)
831 const fresh = await refresh($, true)
832 await $.ui.open({ id: PANE, title: TITLE })
833 return { text: fresh === null ? 'dev-servers: the port scan did not answer, so no servers could be listed.' : describe(fresh) }
834 })
835
836 // The model's view, read-only: this project's servers, the stopped entries and, asked, every other listener.
837 on('tool.check', { tool: 'mcp__dev-servers__dev_servers' }, async ($, e, next) => {
838 const verdict = await next(e)
839 // It only reads the scan this plugin makes anyway: never worth asking, though a deny in settings stands.
840 return verdict.decision === 'deny' ? verdict : { decision: 'allow', reason: 'dev-servers: a read-only listing of the port scan' }
841 })
842
843 on('tool.call', { tool: 'mcp__dev-servers__dev_servers' }, async ($, e) => ({
844 result: await listForModel($, (e as unknown as { all?: unknown }).all === true),
845 }))
846
847 // A command that failed on a taken port: say who holds it.
848 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
849 const ran = await next(e)
850 if (ran.deny !== undefined) {
851 return ran
852 }
853 try {
854 const note = await conflictNote($, e.command, ran.text ?? '')
855 return note === null ? ran : { ...ran, context: [...(ran.context ?? []), note] }
856 } catch (error) {
857 $.ui.log(`dev-servers: could not look up the port holder: ${String(error)}`, { to: 'debug' })
858 return ran
859 }
860 })
861
862 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
863 const { Box, Text, Button } = $.ui.resolve(e)
864 const current = await read($, snapshot)
865 const working = await read($, busy)
866 const forcing = await read($, armed)
867 if (current === null) {
868 return <Text dimColor>Looking for this project's servers…</Text>
869 }
870 const stacked = e.props.bodyColumns < STACK_BELOW
871 const entryOf = (id: string | null) => current.entries.find(entry => entry.id === id) ?? null
872 const others = `${current.others} other listener${current.others === 1 ? '' : 's'} on this machine`
873
874 return (
875 <Box flexDirection="column" gap={1}>
876 <Text dimColor wrap="truncate-start">
877 {current.root}
878 </Text>
879 {current.servers.length === 0 ? (
880 <Text dimColor>No dev servers are listening in this project.</Text>
881 ) : (
882 <Box flexDirection="column">
883 {current.servers.map(server => {
884 const entry = entryOf(server.entryId)
885 const doing = working[`pid-${server.pid}`]
886 const isArmed = forcing[String(server.pid)] !== undefined
887 return (
888 <Box
889 key={`server-${server.pid}`}
890 flexDirection={stacked ? 'column' : 'row'}
891 justifyContent="space-between"
892 columnGap={1}
893 >
894 <Box flexShrink={1}>
895 <Text wrap="truncate-end">
896 <Text color="green">●</Text> {serverLine(server)}
897 {doing === undefined ? '' : ` · ${doing}…`}
898 </Text>
899 </Box>
900 <Box flexDirection="row" gap={1} flexShrink={0}>
901 {entry !== null && (
902 <Button key={`restart-${server.pid}`} label="Restart" onPress={() => void restartServer($, server, entry)} />
903 )}
904 <Button
905 key={`stop-${server.pid}`}
906 label={isArmed ? 'Force stop?' : 'Stop'}
907 variant={isArmed ? 'primary' : undefined}
908 onPress={() => void pressStop($, server)}
909 />
910 {entry !== null && (
911 <Button key={`log-${server.pid}`} label="Log" dimColor onPress={() => void showLog($, entry)} />
912 )}
913 </Box>
914 </Box>
915 )
916 })}
917 </Box>
918 )}
919 {current.stopped.length > 0 && (
920 <Box flexDirection="column">
921 {current.stopped.map(entry => {
922 const doing = working[`entry-${entry.id}`]
923 const detail = [entry.name, entry.command, entry.port === null ? null : `:${entry.port}`]
924 .filter(Boolean)
925 .join(' · ')
926 return (
927 <Box
928 key={`entry-${entry.id}`}
929 flexDirection={stacked ? 'column' : 'row'}
930 justifyContent="space-between"
931 columnGap={1}
932 >
933 <Box flexShrink={1}>
934 <Text dimColor wrap="truncate-end">
935 ○ {detail}
936 {doing === undefined ? '' : ` · ${doing}…`}
937 </Text>
938 </Box>
939 <Box flexShrink={0}>
940 <Button key={`start-${entry.id}`} label="Start" onPress={() => void pressStart($, entry)} />
941 </Box>
942 </Box>
943 )
944 })}
945 </Box>
946 )}
947 <Text dimColor>{others}</Text>
948 </Box>
949 )
950 })
951}
952hooks/servers.ts 866 lines1import type { CachedListener, Holder, KnownEntry, Listener, Manager, ScanCache, ScanLock, Server, Snapshot } from '../types'
2
3// ---------------------------------------------------------------------------
4// lsof and ps output (the listen scan itself is netstat or ss: below)
5// ---------------------------------------------------------------------------
6
7/** The port of an lsof address: `*:4000`, `127.0.0.1:5173`, `[::1]:3000`; null for anything else. */
8export function portOfAddress(address: string): number | null {
9 const local = (address.split('->')[0] ?? '').trim()
10 const match = /:(\d{1,5})(?:\s*\(LISTEN\))?$/.exec(local)
11 const port = match ? Number(match[1]) : NaN
12 return port > 0 && port < 65536 ? port : null
13}
14
15/** `lsof -nP -iTCP -sTCP:LISTEN -F pcn`: one Listener per pid, its ports sorted and deduplicated. */
16export function parseListeners(text: string): Listener[] {
17 const byPid = new Map<number, Listener>()
18 let current: Listener | null = null
19 for (const raw of text.split('\n')) {
20 const line = raw.replace(/\r$/, '')
21 const tag = line[0]
22 const value = line.slice(1)
23 if (tag === 'p') {
24 const pid = Number(value)
25 current = Number.isInteger(pid) && pid > 0 ? (byPid.get(pid) ?? { pid, command: '', ports: [] }) : null
26 if (current) {
27 byPid.set(pid, current)
28 }
29 } else if (tag === 'c' && current) {
30 current.command = value
31 } else if (tag === 'n' && current) {
32 const port = portOfAddress(value)
33 if (port !== null && !current.ports.includes(port)) {
34 current.ports.push(port)
35 }
36 }
37 }
38 return [...byPid.values()]
39 .filter(listener => listener.ports.length > 0)
40 .map(listener => ({ ...listener, ports: [...listener.ports].sort((a, b) => a - b) }))
41}
42
43/** `lsof -a -p <pids> -d cwd -Fn`: each pid's working directory. */
44export function parseCwds(text: string): Map<number, string> {
45 const cwds = new Map<number, string>()
46 let pid: number | null = null
47 for (const raw of text.split('\n')) {
48 const line = raw.replace(/\r$/, '')
49 if (line.startsWith('p')) {
50 const n = Number(line.slice(1))
51 pid = Number.isInteger(n) && n > 0 ? n : null
52 } else if (line.startsWith('n') && pid !== null && !cwds.has(pid)) {
53 cwds.set(pid, line.slice(1))
54 }
55 }
56 return cwds
57}
58
59/** `ps` elapsed time, `[[dd-]hh:]mm:ss`, in seconds; null when it does not read as one. */
60export function parseEtime(text: string): number | null {
61 const match = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(text.trim())
62 if (!match) {
63 return null
64 }
65 const [, days = '0', hours = '0', minutes = '0', seconds = '0'] = match
66 return Number(days) * 86_400 + Number(hours) * 3600 + Number(minutes) * 60 + Number(seconds)
67}
68
69/** `ps -o pid=,etime=,command= -p <pids>`: each pid's uptime and command line. */
70export function parseProcesses(text: string): Map<number, { upSeconds: number | null; commandLine: string }> {
71 const rows = new Map<number, { upSeconds: number | null; commandLine: string }>()
72 for (const line of text.split('\n')) {
73 const match = /^\s*(\d+)\s+(\S+)\s+(.*?)\s*$/.exec(line)
74 if (match) {
75 rows.set(Number(match[1]), { upSeconds: parseEtime(match[2] ?? ''), commandLine: match[3] ?? '' })
76 }
77 }
78 return rows
79}
80
81/** `lsof -nP -iTCP:<port> -sTCP:LISTEN` (the table form): the processes listed, header skipped, one per pid. */
82export function parsePortTable(text: string): { command: string; pid: number }[] {
83 const seen = new Set<number>()
84 const holders: { command: string; pid: number }[] = []
85 for (const line of text.split('\n')) {
86 const match = /^(\S+)\s+(\d+)\s/.exec(line)
87 if (match && !line.startsWith('COMMAND')) {
88 const pid = Number(match[2])
89 if (!seen.has(pid)) {
90 seen.add(pid)
91 holders.push({ command: match[1] ?? '', pid })
92 }
93 }
94 }
95 return holders
96}
97
98/** `2h`, `5m`, `3d`, `40s`: the largest whole unit. */
99export function formatUptime(seconds: number): string {
100 const s = Math.max(0, Math.floor(seconds))
101 if (s < 60) {
102 return `${s}s`
103 }
104 if (s < 3600) {
105 return `${Math.floor(s / 60)}m`
106 }
107 if (s < 86_400) {
108 return `${Math.floor(s / 3600)}h`
109 }
110 return `${Math.floor(s / 86_400)}d`
111}
112
113/** Whether `path` is `root` or lies beneath it. */
114export function isInside(path: string, root: string): boolean {
115 const base = root.length > 1 ? root.replace(/\/+$/, '') : root
116 return path === base || path.startsWith(base === '/' ? '/' : `${base}/`)
117}
118
119export function basename(path: string): string {
120 const trimmed = path.replace(/\/+$/, '')
121 return trimmed.slice(trimmed.lastIndexOf('/') + 1)
122}
123
124export function dirname(path: string): string {
125 const cut = path.lastIndexOf('/')
126 return cut <= 0 ? '/' : path.slice(0, cut)
127}
128
129// ---------------------------------------------------------------------------
130// Known start commands
131// ---------------------------------------------------------------------------
132
133/** Lockfiles in the order they decide the manager. */
134export const LOCKFILES: readonly (readonly [string, Manager])[] = [
135 ['pnpm-lock.yaml', 'pnpm'],
136 ['yarn.lock', 'yarn'],
137 ['bun.lockb', 'bun'],
138 ['bun.lock', 'bun'],
139 ['package-lock.json', 'npm'],
140 ['npm-shrinkwrap.json', 'npm'],
141]
142
143/** The package manager: the first lockfile present, else package.json's `packageManager`, else npm. */
144export function detectManager(present: readonly string[], packageManager?: unknown): Manager {
145 for (const [file, manager] of LOCKFILES) {
146 if (present.includes(file)) {
147 return manager
148 }
149 }
150 const named = typeof packageManager === 'string' ? /^(npm|pnpm|yarn|bun)@/.exec(packageManager) : null
151 return (named?.[1] as Manager | undefined) ?? 'npm'
152}
153
154/** Script names that start a server: dev, start, serve, preview, dev:*, start:*. */
155export function isServerScript(name: string): boolean {
156 return /^(dev|start|serve|preview)$/.test(name) || /^(dev|start):./.test(name)
157}
158
159/** The `scripts` of a package.json, or null when it does not parse. */
160export function packageScripts(text: string): { scripts: Record<string, string>; packageManager?: unknown } | null {
161 try {
162 const parsed: unknown = JSON.parse(text)
163 if (!parsed || typeof parsed !== 'object') {
164 return null
165 }
166 const record = parsed as { scripts?: unknown; packageManager?: unknown }
167 const scripts: Record<string, string> = {}
168 if (record.scripts && typeof record.scripts === 'object') {
169 for (const [name, body] of Object.entries(record.scripts as Record<string, unknown>)) {
170 if (typeof body === 'string') {
171 scripts[name] = body
172 }
173 }
174 }
175 return { scripts, packageManager: record.packageManager }
176 } catch {
177 return null
178 }
179}
180
181type Draft = Omit<KnownEntry, 'id'>
182
183/** The server scripts of a package.json, run with `manager`. */
184export function parsePackageJson(text: string, manager: Manager): Draft[] {
185 const scripts = packageScripts(text)?.scripts ?? {}
186 return Object.entries(scripts)
187 .filter(([name]) => isServerScript(name))
188 .map(([name, body]) => ({
189 name,
190 command: `${manager} run ${name}`,
191 source: 'package.json' as const,
192 port: portFromCommand(body),
193 matchText: resolveScript(body, scripts),
194 }))
195}
196
197/** JSON with `//` and block comments and trailing commas, as VS Code writes launch.json. */
198export function parseLooseJson(text: string): unknown {
199 let out = ''
200 let inString = false
201 for (let i = 0; i < text.length; i++) {
202 const char = text[i]
203 if (inString) {
204 out += char
205 if (char === '\\') {
206 out += text[++i] ?? ''
207 } else if (char === '"') {
208 inString = false
209 }
210 } else if (char === '"') {
211 inString = true
212 out += char
213 } else if (char === '/' && text[i + 1] === '/') {
214 while (i < text.length && text[i] !== '\n') i++
215 out += '\n'
216 } else if (char === '/' && text[i + 1] === '*') {
217 i += 2
218 while (i < text.length && !(text[i] === '*' && text[i + 1] === '/')) i++
219 i++
220 } else {
221 out += char
222 }
223 }
224 return JSON.parse(out.replace(/,(\s*[}\]])/g, '$1'))
225}
226
227/** `.claude/launch.json` configurations that run a command: name, runtimeExecutable + runtimeArgs, port. */
228export function parseLaunchJson(text: string): Draft[] {
229 let parsed: unknown
230 try {
231 parsed = parseLooseJson(text)
232 } catch {
233 return []
234 }
235 const configurations = (parsed as { configurations?: unknown } | null)?.configurations
236 if (!Array.isArray(configurations)) {
237 return []
238 }
239 const drafts: Draft[] = []
240 for (const item of configurations as unknown[]) {
241 const config = (item ?? {}) as { name?: unknown; runtimeExecutable?: unknown; runtimeArgs?: unknown; port?: unknown }
242 if (typeof config.name !== 'string' || typeof config.runtimeExecutable !== 'string' || !config.runtimeExecutable) {
243 continue
244 }
245 const args = Array.isArray(config.runtimeArgs) ? config.runtimeArgs.map(String) : []
246 const command = [config.runtimeExecutable, ...args].map(shellQuote).join(' ')
247 const port = Number(config.port)
248 drafts.push({
249 name: config.name,
250 command,
251 source: 'launch.json',
252 port: Number.isInteger(port) && port > 0 && port < 65536 ? port : portFromCommand(command),
253 matchText: command,
254 })
255 }
256 return drafts
257}
258
259/** Procfile lines, `name: command`. */
260export function parseProcfile(text: string): Draft[] {
261 const drafts: Draft[] = []
262 for (const line of text.split('\n')) {
263 const match = /^\s*([A-Za-z0-9_-]+)\s*:\s*(\S.*?)\s*$/.exec(line)
264 if (match && !line.trimStart().startsWith('#')) {
265 const command = match[2] ?? ''
266 drafts.push({ name: match[1] ?? '', command, source: 'Procfile', port: portFromCommand(command), matchText: command })
267 }
268 }
269 return drafts
270}
271
272/** The package script a command runs (`npm run dev`, `pnpm dev`, `yarn start`, `bun run dev`), or null. */
273export function scriptCalled(command: string): string | null {
274 const match = /^\s*(npm|pnpm|yarn|bun)\s+(?:run(?:-script)?\s+)?([\w:.@/-]+)\s*$/.exec(command)
275 if (!match) {
276 return null
277 }
278 const [, manager, name = ''] = match
279 // `npm dev` is not a script call; npm runs only start, stop, test and restart bare.
280 if (manager === 'npm' && !/^\s*npm\s+run/.test(command) && name !== 'start') {
281 return null
282 }
283 return name
284}
285
286/** A script's body, followed one level when it only calls another script. */
287export function resolveScript(body: string, scripts: Record<string, string>): string {
288 const called = scriptCalled(body)
289 return called !== null && scripts[called] !== undefined ? scripts[called] : body
290}
291
292/** The port a command line names: `--port 3000`, `--port=3000`, `-p 3000`, `PORT=3000`, `--bind :8000`, `runserver 8000`. */
293export function portFromCommand(command: string): number | null {
294 const patterns = [
295 /--port[=\s]+(\d{2,5})\b/,
296 /(?:^|\s)-p\s*(\d{2,5})(?=\s|$)/,
297 /\bPORT=(\d{2,5})\b/,
298 /--(?:bind|listen)[=\s]+[\w.[\]]*:(\d{2,5})\b/,
299 /\brunserver\s+(?:[\w.[\]]+:)?(\d{2,5})\b/,
300 /\bhttp\.server\s+(\d{2,5})\b/,
301 ]
302 for (const pattern of patterns) {
303 const match = pattern.exec(command)
304 const port = match ? Number(match[1]) : NaN
305 if (port > 0 && port < 65536) {
306 return port
307 }
308 }
309 return null
310}
311
312/** A lowercase, file-name-safe id: `dev:api` → `dev-api`. */
313export function slug(text: string): string {
314 return (
315 text
316 .toLowerCase()
317 .replace(/[^a-z0-9]+/g, '-')
318 .replace(/^-+|-+$/g, '') || 'server'
319 )
320}
321
322/**
323 * Every known way to start this project's servers: launch.json first (it names ports), then the
324 * Procfile, then package.json scripts those two do not already run. Names and ids made unique.
325 */
326export function knownEntries(sources: {
327 packageJson: string | null
328 launchJson: string | null
329 procfile: string | null
330 manager: Manager
331}): KnownEntry[] {
332 const scripts = sources.packageJson === null ? {} : (packageScripts(sources.packageJson)?.scripts ?? {})
333 const withScripts = (draft: Draft): Draft => {
334 const called = scriptCalled(draft.command)
335 const body = called === null ? undefined : scripts[called]
336 if (body === undefined) {
337 return draft
338 }
339 const matchText = resolveScript(body, scripts)
340 return { ...draft, matchText, port: draft.port ?? portFromCommand(body) }
341 }
342 const front = [
343 ...(sources.launchJson === null ? [] : parseLaunchJson(sources.launchJson)),
344 ...(sources.procfile === null ? [] : parseProcfile(sources.procfile)),
345 ].map(withScripts)
346 const covered = new Set(front.map(draft => scriptCalled(draft.command)).filter(name => name !== null))
347 const fromPackage =
348 sources.packageJson === null
349 ? []
350 : parsePackageJson(sources.packageJson, sources.manager).filter(draft => !covered.has(draft.name))
351
352 const names = new Set<string>()
353 const ids = new Set<string>()
354 const entries: KnownEntry[] = []
355 for (const draft of [...front, ...fromPackage]) {
356 const name = names.has(draft.name) ? `${draft.name} (${draft.source})` : draft.name
357 names.add(name)
358 let id = slug(name)
359 for (let n = 2; ids.has(id); n++) {
360 id = `${slug(name)}-${n}`
361 }
362 ids.add(id)
363 entries.push({ ...draft, name, id })
364 }
365 return entries
366}
367
368// ---------------------------------------------------------------------------
369// Matching running servers to known entries
370// ---------------------------------------------------------------------------
371
372/** Words a command is launched through, skipped to reach the program itself. */
373const WRAPPERS = new Set(['npx', 'bunx', 'pnpx', 'exec', 'nohup', 'cross-env', 'env', 'nice', 'time'])
374
375/** Interpreters whose name alone says nothing: their arguments must match as well. */
376const GENERIC = new Set(['node', 'python', 'ruby', 'bun', 'deno', 'php', 'java', 'sh', 'bash', 'zsh', 'perl', 'tsx', 'ts-node', 'go', 'dotnet', 'uv', 'poetry'])
377
378/** Splits a command line into words, honouring single and double quotes. */
379export function tokenize(command: string): string[] {
380 const words: string[] = []
381 const pattern = /"((?:[^"\\]|\\.)*)"|'([^']*)'|(\S+)/g
382 for (let match = pattern.exec(command); match !== null; match = pattern.exec(command)) {
383 words.push(match[1] ?? match[2] ?? match[3] ?? '')
384 }
385 return words
386}
387
388/** A program's name without its folder, version or script suffix: `/usr/bin/python3.12` → `python`. */
389export function programName(word: string): string {
390 return basename(word)
391 .toLowerCase()
392 .replace(/\.(c|m)?js$|\.exe$/, '')
393 .replace(/([a-z])[\d.]+$/, '$1')
394}
395
396/** The program and its plain arguments (no flags, no variables) of a command's last segment. */
397export function programWords(command: string): { program: string; args: string[] } | null {
398 const segment = command.split(/&&|\|\||;/).map(part => part.trim()).filter(Boolean).pop() ?? ''
399 const words = tokenize(segment.split(/[|<>]/)[0] ?? '')
400 while (words.length > 0 && (/^\w+=/.test(words[0] ?? '') || WRAPPERS.has(words[0] ?? ''))) {
401 words.shift()
402 }
403 const [first, ...rest] = words
404 if (first === undefined) {
405 return null
406 }
407 return { program: programName(first), args: rest.filter(word => !word.startsWith('-') && !word.includes('$')) }
408}
409
410/**
411 * How well a process's command line fits a start command: 2 for its program and every argument,
412 * 1 for the program alone (never for a bare interpreter such as node), 0 for no fit.
413 */
414export function commandScore(command: string, commandLine: string): number {
415 const words = programWords(command)
416 if (words === null) {
417 return 0
418 }
419 const tokens = tokenize(commandLine)
420 const hasProgram = tokens.some(token => {
421 const name = programName(token)
422 return name === words.program || name.startsWith(`${words.program}-`)
423 })
424 if (!hasProgram) {
425 return 0
426 }
427 const hasArgs = words.args.every(arg => {
428 const bare = arg.replace(/^\.\//, '')
429 return tokens.some(token => token === arg || token === bare || token.endsWith(`/${bare}`))
430 })
431 return hasArgs ? 2 : GENERIC.has(words.program) ? 0 : 1
432}
433
434/** How well a running server fits an entry: 3 by port, else commandScore. */
435export function matchScore(entry: KnownEntry, server: Pick<Server, 'ports' | 'commandLine'>): number {
436 if (entry.port !== null && server.ports.includes(entry.port)) {
437 return 3
438 }
439 return commandScore(entry.matchText, server.commandLine)
440}
441
442/** Names each server by its best-fitting entry (earliest on a tie) and lists the entries none fits. */
443export function matchServers(
444 servers: readonly Server[],
445 entries: readonly KnownEntry[],
446): { servers: Server[]; stopped: KnownEntry[] } {
447 const used = new Set<string>()
448 const named = servers.map(server => {
449 let best: KnownEntry | null = null
450 let bestScore = 0
451 for (const entry of entries) {
452 const score = matchScore(entry, server)
453 if (score > bestScore) {
454 best = entry
455 bestScore = score
456 }
457 }
458 if (best === null) {
459 return { ...server, entryId: null }
460 }
461 used.add(best.id)
462 return { ...server, entryId: best.id, name: best.name }
463 })
464 return { servers: named, stopped: entries.filter(entry => !used.has(entry.id)) }
465}
466
467/** Ports as the status line and the pane draw them: `:4000 :5173`. */
468export function portList(ports: readonly number[]): string {
469 return ports.map(port => `:${port}`).join(' ')
470}
471
472/** The status line: `servers: :4000 :5173`, or undefined when no project server is up. */
473export function statusLine(servers: readonly Server[]): string | undefined {
474 const ports = [...new Set(servers.flatMap(server => server.ports))].sort((a, b) => a - b)
475 return ports.length > 0 ? `servers: ${portList(ports)}` : undefined
476}
477
478// ---------------------------------------------------------------------------
479// Starting, logs and port conflicts
480// ---------------------------------------------------------------------------
481
482/** A word the shell reads back as itself. */
483export function shellQuote(word: string): string {
484 return /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`
485}
486
487/** A short stable hash, base 36. */
488export function hashOf(text: string): string {
489 let hash = 0
490 for (let i = 0; i < text.length; i++) {
491 hash = (hash * 31 + text.charCodeAt(i)) | 0
492 }
493 return (hash >>> 0).toString(36)
494}
495
496/** The project's folder name under the log folder: `myapp-1x2y3z`. */
497export function projectKey(root: string): string {
498 return `${slug(basename(root) || 'root')}-${hashOf(root)}`
499}
500
501/** Where an entry started from the pane writes its output. */
502export function logPath(logDir: string, root: string, entry: Pick<KnownEntry, 'id'>): string {
503 return `${logDir.replace(/\/+$/, '')}/${projectKey(root)}/${entry.id}.log`
504}
505
506/** `~` and `$HOME` at the start of a path, expanded. */
507export function expandHome(path: string, home: string | undefined): string {
508 if (!home) {
509 return path
510 }
511 return path.replace(/^(~|\$HOME|\$\{HOME\})(?=\/|$)/, home)
512}
513
514/**
515 * The `sh -c` script that starts a command detached from the session: in the project root, its
516 * output to the log, its input from /dev/null. A command with shell operators runs under its own sh.
517 */
518export function startScript(root: string, command: string, log: string): string {
519 const program = /&&|\|\||;|\|/.test(command) ? `sh -c ${shellQuote(command)}` : command
520 return `mkdir -p ${shellQuote(dirname(log))} && cd ${shellQuote(root)} && nohup ${program} > ${shellQuote(log)} 2>&1 < /dev/null &`
521}
522
523/** The last `count` non-empty lines of a log's tail. */
524export function lastLines(text: string, count: number): string[] {
525 return text
526 .split(/\r?\n|\r/)
527 .map(line => line.replace(/\u001b\[[0-9;?]*[A-Za-z]/g, '').trimEnd())
528 .filter(line => line.trim() !== '')
529 .slice(-count)
530}
531
532/**
533 * Whether a command's output says a port was taken, and which: `EADDRINUSE ... :::4000`,
534 * `Port 5173 is already in use`, `listen tcp :8080: bind: address already in use`.
535 * `{ port: null }` when it says so without naming the port; null when it does not say so.
536 */
537export function findConflict(text: string): { port: number | null } | null {
538 if (!/EADDRINUSE|address already in use|port \d+ is already in use/i.test(text)) {
539 return null
540 }
541 const patterns = [
542 /port (\d{1,5}) is already in use/i,
543 /EADDRINUSE[^\n]*?:(\d{1,5})\b/,
544 /:(\d{1,5}):? bind: address already in use/i,
545 /address already in use[^\n]*?\bport (\d{1,5})\b/i,
546 /address already in use[^\n]*?:(\d{1,5})\b/i,
547 /\bport (\d{1,5})\b[^\n]*address already in use/i,
548 ]
549 for (const pattern of patterns) {
550 const match = pattern.exec(text)
551 const port = match ? Number(match[1]) : NaN
552 if (port > 0 && port < 65536) {
553 return { port }
554 }
555 }
556 return { port: null }
557}
558
559/** `Port 4000 is held by node (pid 123, up 2h, in /Users/me/other)`. */
560export function holderNote(port: number, holder: Holder): string {
561 const details = [
562 `pid ${holder.pid}`,
563 holder.upSeconds === null ? null : `up ${formatUptime(holder.upSeconds)}`,
564 holder.cwd === null ? null : `in ${holder.cwd}`,
565 ].filter(Boolean)
566 return `Port ${port} is held by ${holder.command} (${details.join(', ')})`
567}
568
569/** One server as a line: `dev · :5173 · pid 4242 · up 2h`. */
570export function serverLine(server: Server): string {
571 return [
572 server.name,
573 portList(server.ports),
574 `pid ${server.pid}`,
575 server.upSeconds === null ? null : `up ${formatUptime(server.upSeconds)}`,
576 ]
577 .filter(Boolean)
578 .join(' · ')
579}
580
581/** What /servers prints: the running servers, the stopped entries, the other listeners. */
582export function describe(snapshot: {
583 root: string
584 servers: readonly Server[]
585 stopped: readonly KnownEntry[]
586 others: number
587}): string {
588 const lines = [
589 snapshot.servers.length === 0
590 ? `No dev servers are listening in ${snapshot.root}.`
591 : `Running in ${snapshot.root}:\n${snapshot.servers.map(server => ` ${serverLine(server)}`).join('\n')}`,
592 ]
593 if (snapshot.stopped.length > 0) {
594 lines.push(`Not running: ${snapshot.stopped.map(entry => `${entry.name} (${entry.command})`).join(', ')}`)
595 }
596 lines.push(`${snapshot.others} other listener${snapshot.others === 1 ? '' : 's'} on this machine.`)
597 return lines.join('\n')
598}
599
600
601// ---------------------------------------------------------------------------
602// The listen scan without lsof: netstat (macOS) and ss (Linux)
603// ---------------------------------------------------------------------------
604
605/** The port ending an address, after its last `separator`: `*.4000`, `::1.5173` (netstat); `[::1]:5432`, `*:8080` (ss). */
606function portAtEnd(address: string, separator: string): number | null {
607 const cut = address.lastIndexOf(separator)
608 const port = cut < 0 ? NaN : Number(address.slice(cut + 1))
609 return Number.isInteger(port) && port > 0 && port < 65536 ? port : null
610}
611
612/** Adds one listening socket to its pid's Listener, naming the process when the table does. */
613function addSocket(byPid: Map<number, Listener>, pid: number, command: string, port: number) {
614 const listener = byPid.get(pid) ?? { pid, command, ports: [] }
615 if (listener.command === '' && command !== '') {
616 listener.command = command
617 }
618 if (!listener.ports.includes(port)) {
619 listener.ports.push(port)
620 }
621 byPid.set(pid, listener)
622}
623
624function withSortedPorts(byPid: Map<number, Listener>): Listener[] {
625 return [...byPid.values()].map(listener => ({ ...listener, ports: [...listener.ports].sort((a, b) => a - b) }))
626}
627
628/**
629 * `netstat -anv -p tcp` on macOS: the LISTEN rows, one Listener per pid. The columns after `(state)` name
630 * the pid: `process:pid` on current systems (the process name may hold spaces), a bare `pid` before `epid`
631 * on older ones, where the command is left ''. Null when the text is not this table (GNU netstat's, say).
632 */
633export function parseNetstat(text: string): Listener[] | null {
634 const lines = text.split('\n').map(line => line.replace(/\r$/, ''))
635 const header = lines.find(line => line.startsWith('Proto') && line.includes('(state)'))
636 const column = header === undefined ? null : netstatPidColumn(header)
637 if (column === null) {
638 return null
639 }
640 const byPid = new Map<number, Listener>()
641 for (const line of lines) {
642 const row = /^tcp\d*\s+\d+\s+\d+\s+(\S+)\s+\S+\s+LISTEN\s+(.*)$/.exec(line)
643 const port = row === null ? null : portAtEnd(row[1] ?? '', '.')
644 const rest = row === null ? null : column.pattern.exec(row[2] ?? '')
645 if (port === null || rest === null) {
646 continue
647 }
648 const pid = Number(column.isNamed ? rest[2] : rest[1])
649 if (Number.isInteger(pid) && pid > 0) {
650 addSocket(byPid, pid, column.isNamed ? (rest[1] ?? '').trim() : '', port)
651 }
652 }
653 return withSortedPorts(byPid)
654}
655
656/**
657 * How netstat's header names the pid after `(state)`: a pattern over the rest of a LISTEN row that captures
658 * `process` and `pid` (`isNamed`) or the bare pid alone. Null when neither column is there.
659 */
660function netstatPidColumn(header: string): { pattern: RegExp; isNamed: boolean } | null {
661 const columns = header.slice(header.indexOf('(state)') + '(state)'.length).trim().split(/\s+/)
662 const named = columns.indexOf('process:pid')
663 const skip = named >= 0 ? named : columns.indexOf('pid')
664 if (skip < 0) {
665 return null
666 }
667 const pattern = named >= 0 ? `^(?:\\S+\\s+){${skip}}(.*?):(\\d+)(?:\\s|$)` : `^(?:\\S+\\s+){${skip}}(\\d+)(?:\\s|$)`
668 return { pattern: new RegExp(pattern), isNamed: named >= 0 }
669}
670
671/**
672 * `ss -ltnp` on Linux: the LISTEN rows, a Listener per pid in `users:(("node",pid=123,fd=18),…)`; a row
673 * with no process (another user's) is skipped. Null when the text is not this table.
674 */
675export function parseSs(text: string): Listener[] | null {
676 const lines = text.split('\n').map(line => line.replace(/\r$/, ''))
677 if (!lines.some(line => /^State\s+Recv-Q/.test(line))) {
678 return null
679 }
680 const byPid = new Map<number, Listener>()
681 for (const line of lines) {
682 const row = /^LISTEN\s+\d+\s+\d+\s+(\S+)\s+\S+\s*(.*)$/.exec(line)
683 if (!row) {
684 continue
685 }
686 const port = portAtEnd(row[1] ?? '', ':')
687 if (port === null) {
688 continue
689 }
690 const users = /\("([^"]*)",pid=(\d+),fd=\d+\)/g
691 const rest = row[2] ?? ''
692 for (let match = users.exec(rest); match !== null; match = users.exec(rest)) {
693 const pid = Number(match[2])
694 if (pid > 0) {
695 addSocket(byPid, pid, match[1] ?? '', port)
696 }
697 }
698 }
699 return withSortedPorts(byPid)
700}
701
702/** Folders whose programs are the system's own, never a project's server: their working directory is not asked. */
703const SYSTEM_PREFIXES = ['/System/', '/usr/libexec/', '/Library/', '/Applications/', '/usr/lib/', '/lib/']
704
705/** Whether a command line runs one of the system's own programs. */
706export function isSystemProgram(commandLine: string): boolean {
707 const program = tokenize(commandLine)[0] ?? ''
708 return SYSTEM_PREFIXES.some(prefix => program.startsWith(prefix))
709}
710
711/** The program a command line runs, by name: `node /app/node_modules/.bin/vite` → `node`. */
712export function programOf(commandLine: string): string {
713 return basename(tokenize(commandLine)[0] ?? '')
714}
715
716/** Where Claude Code runs from: the desktop app's engine (its path has a space in it, so the whole line is read) and the CLI's versioned binaries. */
717const CLAUDE_CODE = /\/claude\.app\/Contents\/MacOS\/claude(?:\s|$)|\/\.local\/share\/claude\/versions\//
718
719/**
720 * Whether a command line, or a process name as netstat has it, is one of Claude Code's own sessions: the
721 * desktop app's engine, the CLI's versioned binary or a bare `claude`. They listen on localhost with the
722 * project as their folder, so they would pass for its servers.
723 */
724export function isClaudeCode(commandLine: string): boolean {
725 return CLAUDE_CODE.test(commandLine) || programOf(commandLine) === 'claude'
726}
727
728/** Whole seconds since `startedAt`, as of `now`; null when the start is unknown. */
729export function upSince(startedAt: number | null, now: number): number | null {
730 return startedAt === null ? null : Math.max(0, Math.floor((now - startedAt) / 1000))
731}
732
733// ---------------------------------------------------------------------------
734// Pacing the scan: backoff, and the cache every session shares
735// ---------------------------------------------------------------------------
736
737/** A scan slower than this, or one that timed out, doubles the poll interval… */
738export const SLOW_MS = 2_000
739/** …up to this. */
740export const MAX_POLL_MS = 5 * 60_000
741
742/** The next poll interval: doubled, to the cap, after a slow scan; the configured one again after a fast one. */
743export function nextPollMs(current: number, configured: number, isSlow: boolean): number {
744 return isSlow ? Math.min(Math.max(current, configured) * 2, MAX_POLL_MS) : configured
745}
746
747function parseJson(text: string | null): unknown {
748 if (text === null) {
749 return null
750 }
751 try {
752 return JSON.parse(text)
753 } catch {
754 return null
755 }
756}
757
758function isRecord(value: unknown): value is Record<string, unknown> {
759 return typeof value === 'object' && value !== null && !Array.isArray(value)
760}
761
762/** Whether `value` is a CachedListener as another session wrote it. */
763function isCachedListener(value: unknown): value is CachedListener {
764 if (!isRecord(value) || typeof value.pid !== 'number' || typeof value.command !== 'string' || !Array.isArray(value.ports)) {
765 return false
766 }
767 if (!value.ports.every(port => typeof port === 'number')) {
768 return false
769 }
770 const detail = value.detail
771 return (
772 detail === null ||
773 (isRecord(detail) &&
774 (detail.commandLine === null || typeof detail.commandLine === 'string') &&
775 (detail.startedAt === null || typeof detail.startedAt === 'number') &&
776 (detail.cwd === null || typeof detail.cwd === 'string'))
777 )
778}
779
780/** `scan-cache.json` as a session wrote it; null for a missing, unreadable or misshapen file. Listeners it cannot read are dropped. */
781export function parseScanCache(text: string | null): ScanCache | null {
782 const value = parseJson(text)
783 if (
784 !isRecord(value) ||
785 typeof value.ts !== 'number' ||
786 typeof value.by !== 'string' ||
787 !isRecord(value.data) ||
788 !Array.isArray(value.data.listeners)
789 ) {
790 return null
791 }
792 return { ts: value.ts, by: value.by, data: { listeners: value.data.listeners.filter(isCachedListener) } }
793}
794
795/** `scan-lock.json`; null for a missing, unreadable or misshapen file. */
796export function parseScanLock(text: string | null): ScanLock | null {
797 const value = parseJson(text)
798 return isRecord(value) && typeof value.ts === 'number' && typeof value.by === 'string' ? { ts: value.ts, by: value.by } : null
799}
800
801/** Whether a cache written at `ts` still stands at `now`. */
802export function isFresh(ts: number, now: number, ttlMs: number): boolean {
803 return ts <= now && now - ts < ttlMs
804}
805
806/** Whether `by` may scan now: no lock, its own, or one older than a scan can take (left by one that never finished). */
807export function mayScan(lock: ScanLock | null, now: number, by: string, staleMs: number): boolean {
808 return lock === null || lock.by === by || now - lock.ts >= staleMs
809}
810
811/** The `all` listing's other listeners, each with its ports, process, pid and folder; one line when there are none. */
812function otherListenersText(listeners: readonly CachedListener[]): string {
813 if (listeners.length === 0) {
814 return 'No other listeners on this machine.'
815 }
816 const rows = listeners.map(listener => {
817 const cwd = listener.detail?.cwd ?? null
818 const parts = [
819 portList(listener.ports),
820 listener.command || programOf(listener.detail?.commandLine ?? '') || 'unknown',
821 `pid ${listener.pid}`,
822 cwd === null ? null : `in ${cwd}`,
823 ]
824 return ` ${parts.filter(Boolean).join(' · ')}`
825 })
826 return `Other listeners on this machine:\n${rows.join('\n')}`
827}
828
829/** `(7 Claude Code sessions not listed)`: what an `all` listing leaves out, said once so nothing is hidden silently; nothing with none. */
830function sessionsNote(count: number): string[] {
831 return count > 0 ? [`(${count} Claude Code session${count === 1 ? '' : 's'} not listed)`] : []
832}
833
834/**
835 * The dev_servers tool's answer: the running servers (with the log of one started from the pane), the
836 * stopped entries and, asked, every other listener on the machine, Claude Code's own sessions counted
837 * rather than listed.
838 */
839export function toolText(
840 snapshot: Pick<Snapshot, 'root' | 'servers' | 'stopped' | 'others' | 'otherListeners' | 'claudeSessions' | 'scannedAt'>,
841 options: { all: boolean; logs: ReadonlyMap<number, string>; now: number },
842): string {
843 const running = snapshot.servers.map(server => {
844 const log = options.logs.get(server.pid)
845 return ` ${serverLine(server)}${log === undefined ? '' : ` · log ${log}`}`
846 })
847 const lines = [
848 snapshot.servers.length === 0
849 ? `No dev servers are listening in ${snapshot.root}.`
850 : `Running in ${snapshot.root}:\n${running.join('\n')}`,
851 ]
852 if (snapshot.stopped.length > 0) {
853 const stopped = snapshot.stopped.map(entry => `${entry.name} (${entry.command}${entry.port === null ? '' : `, :${entry.port}`})`)
854 lines.push(`Not running: ${stopped.join(', ')}.`)
855 }
856 if (!options.all) {
857 lines.push(`${snapshot.others} other listener${snapshot.others === 1 ? '' : 's'} on this machine (all: true lists them).`)
858 } else {
859 lines.push(otherListenersText(snapshot.otherListeners), ...sessionsNote(snapshot.claudeSessions))
860 }
861 lines.push(
862 `Scanned ${formatUptime((options.now - snapshot.scannedAt) / 1000)} ago. Starting, stopping and restarting are the Servers pane's buttons (/servers); this tool only lists.`,
863 )
864 return lines.join('\n')
865}
866types/index.d.ts 93 lines1/** A package manager, picked from the project's lockfile. */
2export type Manager = 'npm' | 'pnpm' | 'yarn' | 'bun'
3
4/** Where a known start command was read from. */
5export type EntrySource = 'package.json' | 'launch.json' | 'Procfile'
6
7/** A way to start one of this project's servers. */
8export type KnownEntry = {
9 /** Unique within the project, safe in a file name and a Button key. */
10 id: string
11 name: string
12 /** The shell command line that starts it, run from the project root. */
13 command: string
14 source: EntrySource
15 /** The port it listens on, when the entry says (launch.json `port`, `--port 3000`, `PORT=3000`). */
16 port: number | null
17 /** The command line its process runs, for matching against `ps`: a package script's body, else `command`. */
18 matchText: string
19}
20
21/**
22 * One process listening on TCP, from `netstat -anv -p tcp` (macOS), `ss -ltnp` (Linux) or, failing both,
23 * `lsof -F pcn`; `command` as that table names the process, '' when it has no name column.
24 */
25export type Listener = { pid: number; command: string; ports: number[] }
26
27/** What `ps` and `lsof -d cwd` say about one listening pid, asked once and kept while it listens. */
28export type ProcessDetail = {
29 /** Its command line as `ps` prints it; null when ps found no such process. */
30 commandLine: string | null
31 /** When it started, in `$.clock.now()` milliseconds; null when ps did not say. */
32 startedAt: number | null
33 /** Its working directory; null when lsof could not say, or was not asked (a system program). */
34 cwd: string | null
35}
36
37/** A listener as the shared scan cache keeps it: `detail` is null until its pid has been looked up. */
38export type CachedListener = Listener & { detail: ProcessDetail | null }
39
40/** `~/.claude/dev-servers/scan-cache.json`: the last scan any session made, for every session to read. */
41export type ScanCache = { ts: number; by: string; data: { listeners: CachedListener[] } }
42
43/** `~/.claude/dev-servers/scan-lock.json`: the session scanning now, and since when. */
44export type ScanLock = { ts: number; by: string }
45
46/** A listening process whose working directory is inside the project. */
47export type Server = {
48 pid: number
49 /** The matched entry's name, else the process's own name. */
50 name: string
51 /** The id of the known entry this server matched, or null. */
52 entryId: string | null
53 ports: number[]
54 cwd: string
55 upSeconds: number | null
56 /** Its command line as `ps` prints it. */
57 commandLine: string
58}
59
60/** What one scan found. */
61export type Snapshot = {
62 root: string
63 servers: Server[]
64 entries: KnownEntry[]
65 /** Known entries no running server matched. */
66 stopped: KnownEntry[]
67 /** Listening processes outside the project. */
68 others: number
69 /** Those processes, for the dev_servers tool's `all`. */
70 otherListeners: CachedListener[]
71 /** Claude Code's own sessions among the listeners (the desktop app's engine, the CLI): left out of every list, counted. */
72 claudeSessions: number
73 /** When the listeners were scanned, by whichever session did. */
74 scannedAt: number
75 /** When this snapshot was made. */
76 at: number
77}
78
79/** The process holding a port, for a conflict note. */
80export type Holder = { pid: number; command: string; upSeconds: number | null; cwd: string | null }
81
82declare module 'claude-code' {
83 interface PluginState {
84 'dev-servers': {
85 snapshot: Snapshot | null
86 /** What is under way per row (`pid-4242`, `entry-dev`): `stopping`, `starting`, `restarting`. */
87 busy: Record<string, string>
88 /** Pids whose Stop was pressed: until this time a second press force stops. */
89 armed: Record<string, number>
90 }
91 }
92}
93