@wsehl/pls 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +49 -2
  3. package/dist/pls.mjs +828 -0
  4. package/package.json +48 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alex Sehl
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
1
+ # pls
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ See what's listening on your ports, where it runs, and **which agent started it**.
4
+
5
+ ```
6
+ $ pls
7
+ PORT PID PROCESS VIA UP DIRECTORY
8
+ 3000 26235 tsx Claude Code (session ended) 1d 2h ~/Code/acme/apps/server
9
+ 4206 64589 vite Ghostty 2h 30m ~/Code/uptime-zero
10
+ 5173 41022 next Codex 12m ~/Code/shop
11
+ 1 still running after the agent session that started it ended. Stop with: pls kill 3000
12
+ 12 system/app listeners hidden, use --all to show
13
+
14
+ $ pls 3000
15
+ :3000 tsx pid 26235 · me
16
+ bound * reachable from network
17
+ dir ~/Code/acme/apps/server
18
+ up 1d 2h
19
+ via Claude Code (pid 88521) session 66cbf1ad-… · session ended, server still running
20
+ command node --require …/tsx/dist/preflight.cjs src/api/main.ts
21
+ tree tsx 26235 ← tsx 39439 ← pnpm 39362
22
+
23
+ $ pls kill 3000 # SIGTERM; -f for SIGKILL
24
+ ```
25
+
26
+ ## Install
27
+
28
+ ```sh
29
+ pnpm install -g @wsehl/pls
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ | Command | |
35
+ | ------------------------- | ---------------------------------------------------------------------------- |
36
+ | `pls` | Listening TCP ports, hiding GUI apps/system daemons (those running from `/`) |
37
+ | `pls --all` | Everything |
38
+ | `pls <port...>` | Full details for specific ports |
39
+ | `pls --json` | Machine-readable output |
40
+ | `pls kill [-f] <port...>` | Stop whatever listens on those ports |
41
+ | `pls --completions zsh` | Shell completions |
42
+
43
+ ## How it works
44
+
45
+ No native dependencies: it shells out to `lsof` and `ps` (macOS and Linux).
46
+
47
+ - **Sockets**: `lsof -iTCP -sTCP:LISTEN`, merged per process and port across IPv4/IPv6.
48
+ - **What it is**: interpreters are resolved to the tool they run (`node …/vite.js` → `vite`).
49
+ - **Where**: the process's working directory (`lsof -d cwd`).
50
+ - **Who started it**: first the process tree is walked up to the nearest known agent, editor or terminal. If the server was detached (re-parented to PID 1), agent markers inherited through its environment are used instead: `CLAUDECODE`/`CLAUDE_PID`/`CLAUDE_CODE_SESSION_ID`, `CODEX_THREAD_ID`, `GEMINI_CLI`, `CURSOR_AGENT`, or the generic `AI_AGENT`. Only those keys are ever read. If the agent session has ended but the server is still running, it is flagged and the footer suggests the `pls kill` command.
package/dist/pls.mjs ADDED
@@ -0,0 +1,828 @@
1
+ #!/usr/bin/env node
2
+ import { NodeRuntime, NodeServices } from "@effect/platform-node";
3
+ import { Config, Console, Context, Effect, Layer, Option, Schema, Stdio, Terminal } from "effect";
4
+ import { Argument, CliError, Command, Flag } from "effect/cli";
5
+ import { ChildProcess, ChildProcessSpawner } from "effect/process";
6
+ //#region package.json
7
+ var version = "0.2.0";
8
+ //#endregion
9
+ //#region src/Listener.ts
10
+ /** A process id. Branded so a port can never be passed where a pid is expected (e.g. to `kill`). */
11
+ const Pid = Schema.Int.pipe(Schema.brand("Pid"));
12
+ const Port = Schema.Int.pipe(Schema.check(Schema.isBetween({
13
+ minimum: 1,
14
+ maximum: 65535
15
+ })), Schema.brand("Port"));
16
+ /** A process somewhere above a listener in the process tree. */
17
+ var Ancestor = class extends Schema.Class("pls/Ancestor")({
18
+ pid: Pid,
19
+ name: Schema.String,
20
+ command: Schema.String
21
+ }) {};
22
+ const LauncherKind = Schema.Literals([
23
+ "agent",
24
+ "editor",
25
+ "terminal"
26
+ ]);
27
+ /** The recognised agent, editor or terminal that (transitively) started a listener. */
28
+ var Launcher = class extends Schema.Class("pls/Launcher")({
29
+ label: Schema.String,
30
+ kind: LauncherKind,
31
+ /** Unknown when the launcher was identified only by a generic environment marker. */
32
+ pid: Schema.NullOr(Pid),
33
+ /** Agent session or thread id, when the agent exports one (resumable with the agent's CLI). */
34
+ session: Schema.NullOr(Schema.String),
35
+ /** False when the launcher has exited but the listener it started is still running. */
36
+ running: Schema.Boolean
37
+ }) {};
38
+ /** One process listening on one TCP port, possibly bound to several addresses. */
39
+ var Listener = class extends Schema.Class("pls/Listener")({
40
+ port: Port,
41
+ addresses: Schema.Array(Schema.String),
42
+ pid: Pid,
43
+ /** Executable name as reported by the OS, e.g. `node`. */
44
+ name: Schema.String,
45
+ /** What is actually serving, e.g. `vite` for `node …/vite.js`. */
46
+ label: Schema.String,
47
+ user: Schema.String,
48
+ command: Schema.String,
49
+ cwd: Schema.NullOr(Schema.String),
50
+ uptimeSeconds: Schema.NullOr(Schema.Int),
51
+ launcher: Schema.NullOr(Launcher),
52
+ /** Parent first, ending just below PID 1. */
53
+ ancestry: Schema.Array(Ancestor)
54
+ }) {};
55
+ //#endregion
56
+ //#region src/parse.ts
57
+ /** Parses a decimal pid, e.g. from `lsof` output or an environment variable. */
58
+ const parsePid = (text) => text !== void 0 && /^\d+$/.test(text) ? Pid.make(Number(text)) : null;
59
+ /**
60
+ * Parses `lsof -F pcLn` output. Each line is a one-letter field id followed by
61
+ * its value. A `p` line starts a new process; its `c` (command) and `L` (login)
62
+ * apply to every following `n` (socket address) until the next `p`.
63
+ */
64
+ const parseSockets = (output) => {
65
+ const sockets = [];
66
+ let current = null;
67
+ for (const line of output.split("\n")) {
68
+ const field = line[0];
69
+ const value = line.slice(1);
70
+ const pid = field === "p" ? parsePid(value) : null;
71
+ if (pid !== null) current = {
72
+ pid,
73
+ name: "",
74
+ user: ""
75
+ };
76
+ else if (current === null) continue;
77
+ else if (field === "c") current.name = value;
78
+ else if (field === "L") current.user = value;
79
+ else if (field === "n") {
80
+ const endpoint = parseEndpoint(value);
81
+ if (endpoint !== null) sockets.push({
82
+ ...current,
83
+ ...endpoint
84
+ });
85
+ }
86
+ }
87
+ return sockets;
88
+ };
89
+ /** Splits `127.0.0.1:3000`, `[::1]:3000` or `*:3000` into address and port. */
90
+ const parseEndpoint = (value) => {
91
+ const match = /^\[?(.*?)\]?:(\d+)$/.exec(value);
92
+ if (match === null) return null;
93
+ const [, address = "", portText = ""] = match;
94
+ const port = Number(portText);
95
+ return Schema.is(Port)(port) ? {
96
+ address,
97
+ port
98
+ } : null;
99
+ };
100
+ /** Parses `lsof -a -d cwd -F n` output into a map of pid → working directory. */
101
+ const parseCwds = (output) => {
102
+ const cwds = /* @__PURE__ */ new Map();
103
+ let pid = null;
104
+ for (const line of output.split("\n")) if (line.startsWith("p")) pid = parsePid(line.slice(1));
105
+ else if (line.startsWith("n") && pid !== null) cwds.set(pid, line.slice(1));
106
+ return cwds;
107
+ };
108
+ /** Parses `ps -A -o pid=,ppid=,etime=,command=` output into a map of pid → process. */
109
+ const parseProcesses = (output) => {
110
+ const processes = /* @__PURE__ */ new Map();
111
+ for (const line of output.split("\n")) {
112
+ const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(line);
113
+ if (match === null) continue;
114
+ const [, pid = "", ppid = "", elapsed = "", command = ""] = match;
115
+ const info = {
116
+ pid: Pid.make(Number(pid)),
117
+ ppid: Pid.make(Number(ppid)),
118
+ uptimeSeconds: parseElapsed(elapsed),
119
+ command
120
+ };
121
+ processes.set(info.pid, info);
122
+ }
123
+ return processes;
124
+ };
125
+ /** Parses the `ps` elapsed-time format `[[dd-]hh:]mm:ss` into seconds. */
126
+ const parseElapsed = (elapsed) => {
127
+ const match = /^(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+)$/.exec(elapsed);
128
+ if (match === null) return null;
129
+ const [, days = "0", hours = "0", minutes = "0", seconds = "0"] = match;
130
+ return ((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds);
131
+ };
132
+ /**
133
+ * Parses `ps eww -o pid=,command=` output, where each process's environment is
134
+ * appended to its command line. Only the requested keys are kept, because
135
+ * environments routinely hold secrets.
136
+ */
137
+ const parseEnvironments = (output, keys) => {
138
+ const environments = /* @__PURE__ */ new Map();
139
+ for (const line of output.split("\n")) {
140
+ const match = /^\s*(\d+)\s+(.*)$/.exec(line);
141
+ if (match === null) continue;
142
+ const [, pid = "", commandAndEnvironment = ""] = match;
143
+ const environment = /* @__PURE__ */ new Map();
144
+ for (const key of keys) {
145
+ const value = new RegExp(`(?:^|\\s)${key}=(\\S*)`).exec(commandAndEnvironment)?.[1];
146
+ if (value !== void 0) environment.set(key, value);
147
+ }
148
+ environments.set(Pid.make(Number(pid)), environment);
149
+ }
150
+ return environments;
151
+ };
152
+ //#endregion
153
+ //#region src/identify.ts
154
+ /**
155
+ * Heuristics that turn raw process data into something a human recognises:
156
+ * what a process is, and which agent, editor or terminal started it.
157
+ */
158
+ const escapeRegExp = (text) => text.replaceAll(/[.*+?^${}()|[\]\\/]/g, "\\$&");
159
+ /** `name` as the executable itself (`name …` or `/path/to/name …`), not inside some other path. */
160
+ const executable = (name) => new RegExp(`(^|/)${escapeRegExp(name)}(\\s|:|$)`);
161
+ /** A macOS app bundle; also matches variants such as "Zed Preview" or "T3 Code (Nightly)". */
162
+ const app = (name) => new RegExp(`/${escapeRegExp(name)}[^/]*\\.app/`);
163
+ /** A script run from an installed npm package. */
164
+ const npmPackage = (name) => new RegExp(`node_modules/${escapeRegExp(name)}/`);
165
+ /** `python -m name`. */
166
+ const pythonModule = (name) => new RegExp(`\\s-m\\s+${escapeRegExp(name)}(\\s|$)`);
167
+ /** Matched against each ancestor's full command line, nearest ancestor first. */
168
+ const knownLaunchers = [
169
+ {
170
+ label: "Claude Code",
171
+ kind: "agent",
172
+ matchers: [executable("claude"), npmPackage("@anthropic-ai/claude-code")]
173
+ },
174
+ {
175
+ label: "Claude",
176
+ kind: "agent",
177
+ matchers: [app("Claude")]
178
+ },
179
+ {
180
+ label: "Codex",
181
+ kind: "agent",
182
+ matchers: [
183
+ executable("codex"),
184
+ npmPackage("@openai/codex"),
185
+ app("Codex")
186
+ ]
187
+ },
188
+ {
189
+ label: "Gemini CLI",
190
+ kind: "agent",
191
+ matchers: [executable("gemini"), npmPackage("@google/gemini-cli")]
192
+ },
193
+ {
194
+ label: "Copilot CLI",
195
+ kind: "agent",
196
+ matchers: [executable("copilot"), npmPackage("@github/copilot")]
197
+ },
198
+ {
199
+ label: "opencode",
200
+ kind: "agent",
201
+ matchers: [executable("opencode"), npmPackage("opencode-ai")]
202
+ },
203
+ {
204
+ label: "Amp",
205
+ kind: "agent",
206
+ matchers: [executable("amp"), npmPackage("@sourcegraph/amp")]
207
+ },
208
+ {
209
+ label: "Aider",
210
+ kind: "agent",
211
+ matchers: [executable("aider"), pythonModule("aider")]
212
+ },
213
+ {
214
+ label: "Goose",
215
+ kind: "agent",
216
+ matchers: [executable("goose"), app("Goose")]
217
+ },
218
+ {
219
+ label: "Crush",
220
+ kind: "agent",
221
+ matchers: [executable("crush")]
222
+ },
223
+ {
224
+ label: "T3 Code",
225
+ kind: "agent",
226
+ matchers: [app("T3 Code")]
227
+ },
228
+ {
229
+ label: "Cursor",
230
+ kind: "editor",
231
+ matchers: [app("Cursor"), executable("cursor-agent")]
232
+ },
233
+ {
234
+ label: "VS Code",
235
+ kind: "editor",
236
+ matchers: [
237
+ app("Visual Studio Code"),
238
+ executable("code"),
239
+ executable("code-server")
240
+ ]
241
+ },
242
+ {
243
+ label: "Windsurf",
244
+ kind: "editor",
245
+ matchers: [app("Windsurf")]
246
+ },
247
+ {
248
+ label: "Kiro",
249
+ kind: "editor",
250
+ matchers: [app("Kiro")]
251
+ },
252
+ {
253
+ label: "Zed",
254
+ kind: "editor",
255
+ matchers: [app("Zed"), executable("zed")]
256
+ },
257
+ {
258
+ label: "JetBrains",
259
+ kind: "editor",
260
+ matchers: [
261
+ "IntelliJ IDEA",
262
+ "WebStorm",
263
+ "PyCharm",
264
+ "GoLand",
265
+ "RustRover",
266
+ "PhpStorm",
267
+ "Rider"
268
+ ].map(app)
269
+ },
270
+ {
271
+ label: "tmux",
272
+ kind: "terminal",
273
+ matchers: [executable("tmux")]
274
+ },
275
+ {
276
+ label: "Ghostty",
277
+ kind: "terminal",
278
+ matchers: [app("Ghostty"), executable("ghostty")]
279
+ },
280
+ {
281
+ label: "iTerm",
282
+ kind: "terminal",
283
+ matchers: [app("iTerm")]
284
+ },
285
+ {
286
+ label: "Terminal",
287
+ kind: "terminal",
288
+ matchers: [app("Terminal")]
289
+ },
290
+ {
291
+ label: "WezTerm",
292
+ kind: "terminal",
293
+ matchers: [
294
+ app("WezTerm"),
295
+ executable("wezterm"),
296
+ executable("wezterm-gui")
297
+ ]
298
+ },
299
+ {
300
+ label: "kitty",
301
+ kind: "terminal",
302
+ matchers: [app("kitty"), executable("kitty")]
303
+ },
304
+ {
305
+ label: "Alacritty",
306
+ kind: "terminal",
307
+ matchers: [app("Alacritty"), executable("alacritty")]
308
+ },
309
+ {
310
+ label: "Warp",
311
+ kind: "terminal",
312
+ matchers: [app("Warp")]
313
+ }
314
+ ];
315
+ const matches = (launcher, command) => launcher.matchers.some((matcher) => matcher.test(command));
316
+ /**
317
+ * Whether `command` is plausibly the launcher called `label`. Guards against a
318
+ * dead agent's pid having been reused by an unrelated process.
319
+ */
320
+ const isLauncherProcess = (label, command) => knownLaunchers.some((launcher) => launcher.label === label && matches(launcher, command));
321
+ /**
322
+ * Agents export markers into the shells they spawn, and children inherit them.
323
+ * This still identifies the agent after a server has been detached and
324
+ * re-parented to PID 1, which is what happens to backgrounded dev servers.
325
+ */
326
+ const environmentMarkers = [
327
+ {
328
+ label: "Claude Code",
329
+ key: "CLAUDECODE",
330
+ pidKey: "CLAUDE_PID",
331
+ sessionKey: "CLAUDE_CODE_SESSION_ID"
332
+ },
333
+ {
334
+ label: "Codex",
335
+ key: "CODEX_THREAD_ID",
336
+ sessionKey: "CODEX_THREAD_ID"
337
+ },
338
+ {
339
+ label: "Codex",
340
+ key: "CODEX_SANDBOX"
341
+ },
342
+ {
343
+ label: "Gemini CLI",
344
+ key: "GEMINI_CLI"
345
+ },
346
+ {
347
+ label: "Cursor",
348
+ key: "CURSOR_AGENT"
349
+ }
350
+ ];
351
+ /** Emerging cross-agent convention, e.g. `AI_AGENT=claude-code_2-1-301_agent`. */
352
+ const genericAgentKey = "AI_AGENT";
353
+ /** The only environment variables pls ever reads. */
354
+ const environmentKeys = [genericAgentKey, ...environmentMarkers.flatMap(({ key, pidKey, sessionKey }) => [
355
+ key,
356
+ pidKey ?? [],
357
+ sessionKey ?? []
358
+ ].flat())];
359
+ const agentFromEnvironment = (environment) => {
360
+ const marker = environmentMarkers.find(({ key }) => environment.has(key));
361
+ if (marker !== void 0) return new Launcher({
362
+ label: marker.label,
363
+ kind: "agent",
364
+ pid: marker.pidKey === void 0 ? null : parsePid(environment.get(marker.pidKey)),
365
+ session: marker.sessionKey === void 0 ? null : environment.get(marker.sessionKey) ?? null,
366
+ running: true
367
+ });
368
+ const genericAgent = environment.get(genericAgentKey);
369
+ if (genericAgent === void 0 || genericAgent === "") return null;
370
+ const [name = genericAgent] = genericAgent.split("_");
371
+ return new Launcher({
372
+ label: name,
373
+ kind: "agent",
374
+ pid: null,
375
+ session: null,
376
+ running: true
377
+ });
378
+ };
379
+ const nearestLauncherAncestor = (ancestry) => {
380
+ for (const ancestor of ancestry) {
381
+ const launcher = knownLaunchers.find((known) => matches(known, ancestor.command));
382
+ if (launcher !== void 0) return new Launcher({
383
+ label: launcher.label,
384
+ kind: launcher.kind,
385
+ pid: ancestor.pid,
386
+ session: null,
387
+ running: true
388
+ });
389
+ }
390
+ return null;
391
+ };
392
+ /**
393
+ * Picks what started a process, in order of confidence:
394
+ * 1. an agent in the process tree (exact pid), enriched with the session id from its environment;
395
+ * 2. an agent known only from inherited environment markers;
396
+ * 3. the nearest editor or terminal in the process tree.
397
+ */
398
+ const detectLauncher = (ancestry, environment) => {
399
+ const fromTree = nearestLauncherAncestor(ancestry);
400
+ const fromEnvironment = agentFromEnvironment(environment);
401
+ if (fromTree?.kind !== "agent") return fromEnvironment ?? fromTree;
402
+ if (fromEnvironment?.label !== fromTree.label) return fromTree;
403
+ return new Launcher({
404
+ ...fromTree,
405
+ session: fromEnvironment.session
406
+ });
407
+ };
408
+ /** A short display name for a command line, e.g. `Ghostty` or `zsh`. */
409
+ const shortName = (command) => {
410
+ const appName = /^\/(?:[^/]+\/)*?([^/]+)\.app\//.exec(command)?.[1];
411
+ if (appName !== void 0) return appName;
412
+ const [executablePath = command] = command.split(/\s+/);
413
+ return basename(executablePath).replace(/^-/, "");
414
+ };
415
+ const interpreter = /^(node|bun|deno|python[\d.]*|ruby|java|php|perl)$/i;
416
+ /**
417
+ * What a process actually is: `node …/next/dist/bin/next dev` → `next`.
418
+ * Anything that is not an interpreter is already descriptive and returned as-is.
419
+ */
420
+ const labelFor = (name, command) => interpreter.test(name) ? scriptFromCommand(command) ?? name : name;
421
+ /** Guesses which tool an interpreter is running, trying the most specific evidence first. */
422
+ const scriptFromCommand = (command) => {
423
+ const binShim = /node_modules\/\.bin\/([^\s/.][^\s/]*)(\s|$)/.exec(command)?.[1];
424
+ if (binShim !== void 0) return binShim;
425
+ const innermostPackage = Array.from(command.matchAll(/node_modules\/((?:@[^/\s]+\/)?[^/\s.][^/\s]*)\//g)).at(-1)?.[1];
426
+ if (innermostPackage !== void 0) return innermostPackage;
427
+ const module = /\s-m\s+([\w.]+)/.exec(command)?.[1];
428
+ if (module !== void 0) return module;
429
+ const script = command.split(/\s+/).slice(1).find((argument) => !argument.startsWith("-"));
430
+ return script === void 0 ? void 0 : basename(script);
431
+ };
432
+ const basename = (path) => path.slice(path.lastIndexOf("/") + 1);
433
+ //#endregion
434
+ //#region src/assemble.ts
435
+ /** Joins sockets, the process table, working directories and environments into listeners. */
436
+ const assemble = (snapshot) => {
437
+ const parsed = {
438
+ processes: parseProcesses(snapshot.processes),
439
+ cwds: parseCwds(snapshot.cwds),
440
+ environments: parseEnvironments(snapshot.environments, environmentKeys)
441
+ };
442
+ return groupSockets(parseSockets(snapshot.sockets)).map((group) => toListener(group, parsed)).toSorted((a, b) => a.port - b.port || a.pid - b.pid);
443
+ };
444
+ /** One group per (pid, port): servers usually bind IPv4 and IPv6 separately, and lsof lists each. */
445
+ const groupSockets = (sockets) => {
446
+ const groups = /* @__PURE__ */ new Map();
447
+ for (const socket of sockets) {
448
+ const key = `${socket.pid}:${socket.port}`;
449
+ const group = groups.get(key);
450
+ if (group === void 0) groups.set(key, {
451
+ socket,
452
+ addresses: [socket.address]
453
+ });
454
+ else if (!group.addresses.includes(socket.address)) group.addresses.push(socket.address);
455
+ }
456
+ return [...groups.values()];
457
+ };
458
+ const toListener = ({ socket, addresses }, parsed) => {
459
+ const info = parsed.processes.get(socket.pid);
460
+ const command = info?.command ?? socket.name;
461
+ const ancestry = ancestorsOf(socket.pid, parsed.processes);
462
+ const environment = parsed.environments.get(socket.pid) ?? /* @__PURE__ */ new Map();
463
+ const launcher = detectLauncher(ancestry, environment);
464
+ return new Listener({
465
+ port: socket.port,
466
+ addresses,
467
+ pid: socket.pid,
468
+ name: socket.name,
469
+ label: labelFor(socket.name, command),
470
+ user: socket.user,
471
+ command,
472
+ cwd: parsed.cwds.get(socket.pid) ?? null,
473
+ uptimeSeconds: info?.uptimeSeconds ?? null,
474
+ launcher: launcher === null ? null : withLiveness(launcher, parsed.processes),
475
+ ancestry
476
+ });
477
+ };
478
+ /** An agent named by an environment marker may have exited since, and its pid may have been reused. */
479
+ const withLiveness = (launcher, processes) => {
480
+ if (launcher.pid === null) return launcher;
481
+ const launcherProcess = processes.get(launcher.pid);
482
+ return launcherProcess !== void 0 && isLauncherProcess(launcher.label, launcherProcess.command) ? launcher : new Launcher({
483
+ ...launcher,
484
+ running: false
485
+ });
486
+ };
487
+ /** Walks parent links up to, but excluding, PID 1. Tracks visited pids in case pid reuse forms a cycle. */
488
+ const ancestorsOf = (pid, processes) => {
489
+ const ancestry = [];
490
+ const visited = /* @__PURE__ */ new Set([pid]);
491
+ const ppid = processes.get(pid)?.ppid;
492
+ let parent = ppid === void 0 ? void 0 : processes.get(ppid);
493
+ while (parent !== void 0 && parent.pid > 1 && !visited.has(parent.pid)) {
494
+ visited.add(parent.pid);
495
+ ancestry.push(new Ancestor({
496
+ pid: parent.pid,
497
+ name: labelFor(shortName(parent.command), parent.command),
498
+ command: parent.command
499
+ }));
500
+ parent = processes.get(parent.ppid);
501
+ }
502
+ return ancestry;
503
+ };
504
+ //#endregion
505
+ //#region src/PortScanner.ts
506
+ var ScanError = class extends Schema.TaggedError()("ScanError", {
507
+ message: Schema.String,
508
+ cause: Schema.Defect()
509
+ }) {};
510
+ /** Every listening TCP socket as pid (p), command name (c), login (L) and address (n). `+c 0` disables name truncation. */
511
+ const listSockets = ChildProcess.make("lsof", [
512
+ "-nP",
513
+ "+c",
514
+ "0",
515
+ "-iTCP",
516
+ "-sTCP:LISTEN",
517
+ "-F",
518
+ "pcLn"
519
+ ]);
520
+ /** The whole process table, so the parent chain of each listener can be walked. */
521
+ const listProcesses = ChildProcess.make("ps", [
522
+ "-A",
523
+ "-o",
524
+ "pid=,ppid=,etime=,command="
525
+ ]);
526
+ const listCwds = (pids) => ChildProcess.make("lsof", [
527
+ "-a",
528
+ "-d",
529
+ "cwd",
530
+ "-p",
531
+ pids.join(","),
532
+ "-F",
533
+ "n"
534
+ ]);
535
+ /** BSD-style `e` appends each process's environment to its command line, on both macOS and Linux procps. */
536
+ const listEnvironments = (pids) => ChildProcess.make("ps", [
537
+ "eww",
538
+ "-o",
539
+ "pid=,command=",
540
+ "-p",
541
+ pids.join(",")
542
+ ]);
543
+ /** Discovers TCP listeners by running `lsof` and `ps`, and stops them with `kill`. */
544
+ var PortScanner = class PortScanner extends Context.Service()("pls/PortScanner") {
545
+ static layer = Layer.effect(PortScanner, Effect.gen(function* () {
546
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
547
+ const output = (command) => spawner.string(command).pipe(Effect.mapError((cause) => new ScanError({
548
+ message: `Failed to run \`${command.command}\``,
549
+ cause
550
+ })));
551
+ const listeners = Effect.gen(function* () {
552
+ const [sockets, processes] = yield* Effect.all([output(listSockets), output(listProcesses)], { concurrency: "unbounded" });
553
+ const pids = [...new Set(parseSockets(sockets).map((socket) => socket.pid))];
554
+ if (pids.length === 0) return [];
555
+ const [cwds, environments] = yield* Effect.all([output(listCwds(pids)), output(listEnvironments(pids))], { concurrency: "unbounded" });
556
+ return assemble({
557
+ sockets,
558
+ processes,
559
+ cwds,
560
+ environments
561
+ });
562
+ }).pipe(Effect.withSpan("PortScanner.listeners"));
563
+ const kill = Effect.fn("PortScanner.kill")(function* (pid, signal) {
564
+ if ((yield* spawner.exitCode(ChildProcess.make("kill", [
565
+ "-s",
566
+ signal,
567
+ String(pid)
568
+ ])).pipe(Effect.mapError((cause) => new ScanError({
569
+ message: "Failed to run `kill`",
570
+ cause
571
+ })))) !== 0) return yield* new ScanError({
572
+ message: `Could not signal pid ${pid}: it may belong to another user or have already exited`,
573
+ cause: null
574
+ });
575
+ });
576
+ return PortScanner.of({
577
+ listeners,
578
+ kill
579
+ });
580
+ }));
581
+ };
582
+ //#endregion
583
+ //#region src/render.ts
584
+ const ansiCodes = {
585
+ bold: "1",
586
+ dim: "2",
587
+ green: "32",
588
+ yellow: "33",
589
+ blue: "34",
590
+ magenta: "35"
591
+ };
592
+ const makePaint = (color) => (style, text) => color ? `\x1b[${ansiCodes[style]}m${text}\x1b[0m` : text;
593
+ const launcherStyles = {
594
+ agent: "magenta",
595
+ editor: "blue",
596
+ terminal: "dim"
597
+ };
598
+ const missing = "—";
599
+ /** Bind addresses meaning "every interface", i.e. reachable from outside this machine. */
600
+ const wildcardAddresses = /* @__PURE__ */ new Set([
601
+ "*",
602
+ "0.0.0.0",
603
+ "::"
604
+ ]);
605
+ const formatDuration = (seconds) => {
606
+ const minutes = Math.floor(seconds / 60);
607
+ const hours = Math.floor(minutes / 60);
608
+ const days = Math.floor(hours / 24);
609
+ if (days > 0) return `${days}d ${hours % 24}h`;
610
+ if (hours > 0) return `${hours}h ${minutes % 60}m`;
611
+ if (minutes > 0) return `${minutes}m`;
612
+ return `${seconds}s`;
613
+ };
614
+ const formatUptime = (seconds) => seconds === null ? missing : formatDuration(seconds);
615
+ const tildify = (text, home) => home === "" ? text : text.replaceAll(home, "~");
616
+ /** Keeps the end of a path, which is the part that identifies the project. */
617
+ const truncateStart = (text, maxLength) => text.length <= maxLength ? text : `…${text.slice(text.length - maxLength + 1)}`;
618
+ const headers = [
619
+ "PORT",
620
+ "PID",
621
+ "PROCESS",
622
+ "VIA",
623
+ "UP",
624
+ "DIRECTORY"
625
+ ];
626
+ const columnGap = " ";
627
+ /** The directory column never shrinks below this, even if the row then wraps. */
628
+ const minDirectoryWidth = 12;
629
+ const launcherCell = (launcher) => {
630
+ if (launcher === null) return {
631
+ text: missing,
632
+ style: "dim"
633
+ };
634
+ if (!launcher.running) return {
635
+ text: `${launcher.label} (session ended)`,
636
+ style: "yellow"
637
+ };
638
+ return {
639
+ text: launcher.label,
640
+ style: launcherStyles[launcher.kind]
641
+ };
642
+ };
643
+ const rowCells = (listener, home) => [
644
+ {
645
+ text: String(listener.port),
646
+ style: "bold"
647
+ },
648
+ {
649
+ text: String(listener.pid),
650
+ style: "dim"
651
+ },
652
+ {
653
+ text: listener.label,
654
+ style: "green"
655
+ },
656
+ launcherCell(listener.launcher),
657
+ { text: formatUptime(listener.uptimeSeconds) },
658
+ listener.cwd === null ? {
659
+ text: missing,
660
+ style: "dim"
661
+ } : { text: tildify(listener.cwd, home) }
662
+ ];
663
+ /** Pads every column to its widest cell, except the last (directory), which gets the remaining width. */
664
+ const formatRows = (rows, width, paint) => {
665
+ const columnWidths = headers.map((_, column) => Math.max(...rows.map((row) => row[column]?.text.length ?? 0)));
666
+ const fixedWidth = columnWidths.slice(0, -1).reduce((sum, columnWidth) => sum + columnWidth + 2, 0);
667
+ const directoryWidth = Math.max(width - fixedWidth, minDirectoryWidth);
668
+ return rows.map((row) => row.map((cell, column) => {
669
+ const text = column === row.length - 1 ? truncateStart(cell.text, directoryWidth) : cell.text.padEnd(columnWidths[column] ?? 0);
670
+ return cell.style === void 0 ? text : paint(cell.style, text);
671
+ }).join(columnGap));
672
+ };
673
+ /** Notes printed under the table, so nothing is hidden or left running silently. */
674
+ const footerLines = (listeners, hiddenCount, paint) => {
675
+ const lines = [];
676
+ const orphanedPorts = /* @__PURE__ */ new Set();
677
+ for (const listener of listeners) if (listener.launcher?.running === false) orphanedPorts.add(listener.port);
678
+ if (orphanedPorts.size > 0) {
679
+ const pronoun = orphanedPorts.size === 1 ? "it" : "them";
680
+ const killCommand = `pls kill ${[...orphanedPorts].join(" ")}`;
681
+ lines.push(paint("yellow", `${orphanedPorts.size} still running after the agent session that started ${pronoun} ended. Stop with: ${killCommand}`));
682
+ }
683
+ if (hiddenCount > 0) {
684
+ const plural = hiddenCount === 1 ? "" : "s";
685
+ lines.push(paint("dim", `${hiddenCount} system/app listener${plural} hidden, use --all to show`));
686
+ }
687
+ return lines;
688
+ };
689
+ const renderTable = ({ listeners, hiddenCount }, options) => {
690
+ const paint = makePaint(options.color);
691
+ const footer = footerLines(listeners, hiddenCount, paint);
692
+ if (listeners.length === 0) return [paint("dim", "Nothing is listening on any TCP port."), ...footer].join("\n");
693
+ const rows = [headers.map((text) => ({
694
+ text,
695
+ style: "dim"
696
+ })), ...listeners.map((listener) => rowCells(listener, options.home))];
697
+ return [...formatRows(rows, options.width, paint), ...footer].join("\n");
698
+ };
699
+ const describeAddresses = (addresses, paint) => {
700
+ const list = addresses.join(", ");
701
+ return addresses.some((address) => wildcardAddresses.has(address)) ? `${list} ${paint("yellow", "reachable from network")}` : list;
702
+ };
703
+ const describeLauncher = (launcher, paint) => {
704
+ if (launcher === null) return missing;
705
+ const parts = [paint(launcherStyles[launcher.kind], launcher.label)];
706
+ if (launcher.pid !== null) parts.push(paint("dim", `(pid ${launcher.pid})`));
707
+ if (launcher.session !== null) parts.push(paint("dim", `session ${launcher.session}`));
708
+ if (!launcher.running) parts.push(paint("yellow", "· session ended, server still running"));
709
+ return parts.join(" ");
710
+ };
711
+ /** The listener followed by its ancestors, e.g. `vite 64589 ← pnpm 64564 ← zsh 259`. */
712
+ const describeTree = (listener, paint) => {
713
+ return [{
714
+ name: listener.label,
715
+ pid: listener.pid
716
+ }, ...listener.ancestry].map(({ name, pid }) => `${name} ${paint("dim", String(pid))}`).join(paint("dim", " ← "));
717
+ };
718
+ const renderDetail = (listener, options) => {
719
+ const paint = makePaint(options.color);
720
+ const field = (name, value) => ` ${paint("dim", name.padEnd(8))} ${value}`;
721
+ return [
722
+ [
723
+ paint("bold", `:${listener.port}`),
724
+ paint("green", listener.label),
725
+ paint("dim", `pid ${listener.pid} · ${listener.user}`)
726
+ ].join(" "),
727
+ field("bound", describeAddresses(listener.addresses, paint)),
728
+ field("dir", listener.cwd === null ? missing : tildify(listener.cwd, options.home)),
729
+ field("up", formatUptime(listener.uptimeSeconds)),
730
+ field("via", describeLauncher(listener.launcher, paint)),
731
+ field("command", tildify(listener.command, options.home)),
732
+ field("tree", describeTree(listener, paint))
733
+ ].join("\n");
734
+ };
735
+ //#endregion
736
+ //#region src/main.ts
737
+ const toUserError = (error) => new CliError.UserError({
738
+ cause: error,
739
+ userMessage: error.message
740
+ });
741
+ const scanListeners = PortScanner.use((scanner) => scanner.listeners).pipe(Effect.mapError(toUserError));
742
+ const nothingListening = (ports) => new CliError.UserError({
743
+ cause: null,
744
+ userMessage: `Nothing is listening on ${ports.map((port) => `:${port}`).join(", ")}`
745
+ });
746
+ /** Colour and truncation only make sense on an interactive terminal. Honours https://no-color.org. */
747
+ const renderOptions = Effect.gen(function* () {
748
+ const isTerminal = yield* Stdio.Stdio.use((stdio) => stdio.stdoutIsTerminal);
749
+ const noColor = yield* Config.String("NO_COLOR").pipe(Config.option);
750
+ const home = yield* Config.String("HOME").pipe(Config.withDefault(""));
751
+ const width = isTerminal ? yield* Terminal.Terminal.use((terminal) => terminal.columns) : Infinity;
752
+ return {
753
+ color: isTerminal && Option.isNone(noColor),
754
+ width,
755
+ home
756
+ };
757
+ });
758
+ /**
759
+ * GUI apps and system daemons are started by launchd/init with `/` as their
760
+ * working directory, whereas dev servers run inside a project.
761
+ */
762
+ const isSystemListener = (listener) => listener.cwd === "/";
763
+ const selectListeners = (listeners, { ports, includeSystem }) => {
764
+ if (ports.length > 0) return listeners.filter((listener) => ports.includes(listener.port));
765
+ if (includeSystem) return listeners;
766
+ return listeners.filter((listener) => !isSystemListener(listener));
767
+ };
768
+ const portsArgument = (description) => Argument.Int("port").pipe(Argument.withSchema(Port), Argument.withDescription(description));
769
+ const pls = Command.make("pls", {
770
+ ports: portsArgument("Only show these ports, with full details").pipe(Argument.variadic()),
771
+ all: Flag.Boolean("all").pipe(Flag.withAlias("a"), Flag.withDescription("Include system services and GUI apps (those running from `/`)"), Flag.withDefault(false)),
772
+ json: Flag.Boolean("json").pipe(Flag.withDescription("Print machine-readable JSON"), Flag.withDefault(false))
773
+ }, Effect.fn(function* ({ all, json, ports }) {
774
+ const listeners = yield* scanListeners;
775
+ const selected = selectListeners(listeners, {
776
+ ports,
777
+ includeSystem: all
778
+ });
779
+ if (json) return yield* Console.log(JSON.stringify(selected, null, 2));
780
+ if (ports.length > 0 && selected.length === 0) return yield* nothingListening(ports);
781
+ const options = yield* renderOptions;
782
+ if (ports.length > 0) return yield* Console.log(selected.map((listener) => renderDetail(listener, options)).join("\n\n"));
783
+ const hiddenCount = listeners.length - selected.length;
784
+ yield* Console.log(renderTable({
785
+ listeners: selected,
786
+ hiddenCount
787
+ }, options));
788
+ })).pipe(Command.withDescription("See which processes are listening on which TCP ports, where they run and what started them"), Command.withExamples([
789
+ {
790
+ command: "pls",
791
+ description: "List listening ports, hiding system services"
792
+ },
793
+ {
794
+ command: "pls --all",
795
+ description: "List every listening port"
796
+ },
797
+ {
798
+ command: "pls 3000 5173",
799
+ description: "Show details for specific ports"
800
+ },
801
+ {
802
+ command: "pls --json",
803
+ description: "Print listeners as JSON"
804
+ }
805
+ ]));
806
+ const kill = Command.make("kill", {
807
+ ports: portsArgument("Port(s) whose listening processes should be stopped").pipe(Argument.variadic({ min: 1 })),
808
+ force: Flag.Boolean("force").pipe(Flag.withAlias("f"), Flag.withDescription("Send SIGKILL instead of SIGTERM"), Flag.withDefault(false))
809
+ }, Effect.fn(function* ({ force, ports }) {
810
+ const scanner = yield* PortScanner;
811
+ const requested = (yield* scanListeners).filter((listener) => ports.includes(listener.port));
812
+ const targets = new Map(requested.map((listener) => [listener.pid, listener])).values().toArray();
813
+ if (targets.length === 0) return yield* nothingListening(ports);
814
+ const signal = force ? "KILL" : "TERM";
815
+ for (const target of targets) {
816
+ yield* scanner.kill(target.pid, signal).pipe(Effect.mapError(toUserError));
817
+ yield* Console.log(`Sent SIG${signal} to ${target.label} (pid ${target.pid}) on :${target.port}`);
818
+ }
819
+ })).pipe(Command.withDescription("Stop whatever is listening on the given port(s)"), Command.withExamples([{
820
+ command: "pls kill 3000",
821
+ description: "Gracefully stop the server on :3000"
822
+ }, {
823
+ command: "pls kill -f 3000 3001",
824
+ description: "Force-kill servers on :3000 and :3001"
825
+ }]));
826
+ pls.pipe(Command.withSubcommands([kill]), Command.run({ version }), Effect.provide(PortScanner.layer.pipe(Layer.provideMerge(NodeServices.layer))), NodeRuntime.runMain);
827
+ //#endregion
828
+ export {};
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@wsehl/pls",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "See what's listening on your ports",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/wsehl/pls.git"
9
+ },
10
+ "bin": {
11
+ "pls": "./dist/pls.mjs"
12
+ },
13
+ "files": [
14
+ "dist/pls.mjs"
15
+ ],
16
+ "type": "module",
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "scripts": {
21
+ "dev": "node src/main.ts",
22
+ "build": "tsdown",
23
+ "start": "node dist/pls.mjs",
24
+ "format": "oxfmt --write .",
25
+ "format-check": "oxfmt --check .",
26
+ "lint": "oxlint .",
27
+ "test": "vitest run",
28
+ "type-check": "tsc --noEmit",
29
+ "check": "pnpm run type-check && pnpm run lint && pnpm run format-check && pnpm test",
30
+ "prepack": "pnpm run build",
31
+ "prepublishOnly": "pnpm run type-check && pnpm test"
32
+ },
33
+ "dependencies": {
34
+ "@effect/platform-node": "4.0.5",
35
+ "effect": "4.0.5"
36
+ },
37
+ "devDependencies": {
38
+ "@effect/vitest": "4.0.5",
39
+ "@types/node": "^26.6.5",
40
+ "oxfmt": "0.73.0",
41
+ "oxlint": "1.88.0",
42
+ "tsdown": "^0.23.1",
43
+ "typescript": "^7.0.2",
44
+ "vitest": "^5.0.5"
45
+ },
46
+ "engines": {
47
+ "node": ">=22"
48
+ },
49
+ "packageManager": "pnpm@11.5.1"
50
+ }