Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PortScanner.ts

1,188 lines45.0 KB

1import {
2 CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS,
3 PREVIEW_URL_MAX_LENGTH,
4 PreviewStopLocalServerError,
5 ThreadId,
6 type DiscoveredLocalServer,
7 type PreviewStopLocalServerInput,
8} from "@t3tools/contracts";
9import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11import { isLoopbackHost, LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview";
12import * as Cause from "effect/Cause";
13import * as Clock from "effect/Clock";
14import * as Context from "effect/Context";
15import * as Duration from "effect/Duration";
16import * as Effect from "effect/Effect";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as PlatformError from "effect/PlatformError";
21import * as Ref from "effect/Ref";
22import * as Schedule from "effect/Schedule";
23import * as Scope from "effect/Scope";
24import * as Semaphore from "effect/Semaphore";
25import { FetchHttpClient, HttpClient } from "effect/http";
26​
27import * as ProcessRunner from "../processRunner.ts";
28​
29export class PortDiscovery extends Context.Service<
30 PortDiscovery,
31 {
32 readonly scan: (
33 configuredUrls?: ReadonlyArray<string>,
34 ) => Effect.Effect<ReadonlyArray<DiscoveredLocalServer>>;
35 readonly subscribe: (
36 input: {
37 readonly configuredUrls: ReadonlyArray<string>;
38 readonly initialSnapshot: ReadonlyArray<DiscoveredLocalServer>;
39 },
40 listener: (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>,
41 ) => Effect.Effect<void, never, Scope.Scope>;
42 readonly retain: Effect.Effect<void, never, Scope.Scope>;
43 readonly registerTerminalProcesses: (input: {
44 readonly threadId: string;
45 readonly terminalId: string;
46 readonly processIds: ReadonlyArray<number>;
47 }) => Effect.Effect<void>;
48 readonly unregisterTerminal: (input: {
49 readonly threadId: string;
50 readonly terminalId: string;
51 }) => Effect.Effect<void>;
52 /**
53 * Counts a running agent until the returned function is called. While one runs, any
54 * listener may be a server it started. Synchronous because provider spawn callbacks run
55 * outside Effect.
56 */
57 readonly trackAgent: () => () => void;
58 /** Stops a listed server's process group, never this server, an agent CLI, or a shell. */
59 readonly stopServer: (
60 input: PreviewStopLocalServerInput,
61 ) => Effect.Effect<void, PreviewStopLocalServerError>;
62 }
63>()("t3/preview/PortScanner/PortDiscovery") {}
64​
65/**
66 * Agents launch with this set to their thread, and every job they start inherits it, so a
67 * server stays attributed after its launching shell exits or the agent settles.
68 */
69export const AGENT_THREAD_ENV = "T3CODE_THREAD_ID";
70​
71const POLL_INTERVAL = Duration.seconds(3);
72const LSOF_TIMEOUT_MS = 5_000;
73const PROC_FD_WALK_LIMIT = 50_000;
74const SOCKET_OWNER_ATTEMPTS = 3;
75const WINDOWS_LISTENER_TIMEOUT_MS = 5_000;
76/** `netstat -ano` lists every connection, not just listeners; ~80 bytes per row, sized for ~200k rows. */
77const WINDOWS_NETSTAT_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
78const WEB_PROBE_TIMEOUT = Duration.seconds(1);
79const WEB_PROBE_CACHE_TTL_MS = Duration.toMillis(Duration.seconds(15));
80/** Bounds how long a cached Windows image name can outlive its process if Windows reuses the PID. */
81const WINDOWS_PROCESS_NAME_TTL_MS = Duration.toMillis(Duration.seconds(60));
82const WINDOWS_PROCESS_NAME_CONCURRENCY = 4;
83const WEB_PROBE_CONCURRENCY = 16;
84const NAVIGATION_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
85const PS_TIMEOUT_MS = 5_000;
86const PS_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
87const STOP_GRACE_MS = 3_000;
88const STOP_POLL_INTERVAL = Duration.millis(250);
89​
90type Listener = (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>;
91​
92interface ListenerSubscription {
93 readonly configuredUrls: ReadonlyArray<string>;
94 readonly lastSnapshot: ReadonlyArray<DiscoveredLocalServer>;
96​
97interface ScannerState {
98 readonly listeners: ReadonlyMap<Listener, ListenerSubscription>;
99 readonly terminalProcesses: ReadonlyMap<
100 string,
101 {
102 readonly owner: TerminalProcessOwner;
103 readonly processIds: ReadonlySet<number>;
104 }
105 >;
106 readonly retainCount: number;
108​
109interface TerminalProcessOwner {
110 readonly threadId: ThreadId;
111 readonly terminalId: string;
113​
114type ServerOwner = Pick<DiscoveredLocalServer, "terminal" | "agent">;
115​
116const UNOWNED: ServerOwner = { terminal: null, agent: null };
117​
118const isOwned = (server: DiscoveredLocalServer): boolean =>
119 server.terminal !== null || (server.agent ?? null) !== null;
120​
121interface ProcessTableRow {
122 readonly pid: number;
123 readonly ppid: number;
124 readonly pgid: number;
126​
127interface WebProbeCacheEntry {
128 readonly pid: number | null;
129 readonly isWeb: boolean;
130 readonly expiresAtMillis: number;
132​
133interface WebProbeGroup {
134 readonly server: DiscoveredLocalServer;
135 readonly urls: ReadonlyArray<string>;
136 readonly configuredKey: string | null;
138​
139interface WebProbeSnapshot {
140 readonly discovered: ReadonlyArray<DiscoveredLocalServer>;
141 readonly configured: ReadonlyMap<string, DiscoveredLocalServer>;
143​
144const terminalOwnerKey = (owner: {
145 readonly threadId: string;
146 readonly terminalId: string;
147}): string => `${owner.threadId}\u0000${owner.terminalId}`;
148​
149const parseConfiguredUrl = (raw: string): URL | null => {
150 try {
151 const url = new URL(raw);
152 if (url.protocol !== "http:" && url.protocol !== "https:") return null;
153 if (!isLoopbackHost(url.hostname)) return null;
154 return url;
155 } catch {
156 return null;
157 }
158};
159​
160const localServerKey = (host: string, port: number): string =>
161 `${isLoopbackHost(host) ? "loopback" : host.toLowerCase()}:${port}`;
162​
163const urlPort = (url: URL): number =>
164 url.port.length > 0 ? Number.parseInt(url.port, 10) : url.protocol === "http:" ? 80 : 443;
165​
166const webProbeCacheKey = (raw: string): string => {
167 const url = new URL(raw);
168 url.hash = "";
169 return url.href;
170};
171​
172const normalizeConfiguredUrls = (urls: ReadonlyArray<string>): ReadonlyArray<string> => [
173 ...new Set(
174 urls
175 .slice(0, CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS)
176 .filter((raw) => raw.length <= PREVIEW_URL_MAX_LENGTH)
177 .map(parseConfiguredUrl)
178 .filter((url): url is URL => url !== null && url.href.length <= PREVIEW_URL_MAX_LENGTH)
179 .map((url) => {
180 if (url.hostname === "0.0.0.0") url.hostname = "localhost";
181 return url.href;
182 })
183 .filter((url) => url.length <= PREVIEW_URL_MAX_LENGTH),
184 ),
185];
186​
187const projectWebProbeSnapshot = (
188 snapshot: WebProbeSnapshot,
189 configuredUrls: ReadonlyArray<string>,
190): ReadonlyArray<DiscoveredLocalServer> => {
191 const visibleByServer = new Map<string, DiscoveredLocalServer>();
192 for (const raw of normalizeConfiguredUrls(configuredUrls)) {
193 const url = new URL(raw);
194 const port = urlPort(url);
195 const serverKey = localServerKey(url.hostname, port);
196 if (visibleByServer.has(serverKey)) continue;
197 const configured = snapshot.configured.get(webProbeCacheKey(raw));
198 if (configured) visibleByServer.set(serverKey, { ...configured, url: raw });
199 }
200 for (const server of snapshot.discovered) {
201 const key = localServerKey(server.host, server.port);
202 if (!visibleByServer.has(key)) visibleByServer.set(key, server);
203 }
204 return [...visibleByServer.values()].toSorted((left, right) => left.port - right.port);
205};
206​
207const parseLsofOutput = (
208 raw: string,
209 owners: ReadonlyMap<number, ServerOwner> = new Map(),
210): ReadonlyArray<DiscoveredLocalServer> => {
211 const seen = new Map<string, DiscoveredLocalServer>();
212 let pid: number | null = null;
213 let processName: string | null = null;
214​
215 for (const line of raw.split("\n")) {
216 if (line.length === 0) continue;
217 const tag = line.charAt(0);
218 const value = line.slice(1);
219 if (tag === "p") {
220 const parsed = Number.parseInt(value, 10);
221 pid = Number.isFinite(parsed) && parsed > 0 ? parsed : null;
222 processName = null;
223 continue;
224 }
225 if (tag === "c") {
226 processName = value.trim() || null;
227 continue;
228 }
229 if (tag === "n") {
230 const portMatch = parsePortFromLsofName(value);
231 if (portMatch == null) continue;
232 const url = `http://localhost:${portMatch}`;
233 const key = `localhost:${portMatch}`;
234 const owner = pid === null ? undefined : owners.get(pid);
235 const existing = seen.get(key);
236 if (existing) {
237 if (owner === undefined) seen.set(key, { ...existing, ...UNOWNED });
238 continue;
239 }
240 seen.set(key, {
241 host: "localhost",
242 port: portMatch,
243 url,
244 processName,
245 pid,
246 ...(owner ?? UNOWNED),
247 });
248 }
249 }
250​
251 return Array.from(seen.values()).toSorted((a, b) => a.port - b.port);
252};
253​
254const parsePortFromLsofName = (name: string): number | null => {
255 const trimmed = name.split(" ", 1)[0]?.trim() ?? "";
256 if (trimmed.length === 0) return null;
257 const lastColon = trimmed.lastIndexOf(":");
258 if (lastColon < 0) return null;
259 const hostPart = trimmed.slice(0, lastColon);
260 const portPart = trimmed.slice(lastColon + 1);
261 if (!LSOF_LOCAL_HOST_TOKENS.has(hostPart)) return null;
262 const port = Number.parseInt(portPart, 10);
263 if (!Number.isFinite(port) || port <= 0 || port >= 65536) return null;
264 return port;
265};
266​
267const parseWindowsListenerLine = (
268 line: string,
269): {
270 readonly host: string;
271 readonly port: number;
272 readonly pid: number | null;
273 readonly processName: string | null;
274} | null => {
275 const trimmed = line.trim();
276 if (trimmed.length === 0) return null;
277​
278 if (trimmed.includes("|")) {
279 const [hostRaw, portRaw, pidRaw, processNameRaw] = trimmed.split("|", 4);
280 const host = hostRaw?.trim() ?? "";
281 if (!LSOF_LOCAL_HOST_TOKENS.has(host) && host !== "::") return null;
282 const port = Number(portRaw);
283 const pid = Number(pidRaw);
284 if (!Number.isInteger(port) || port <= 0 || port >= 65536) return null;
285 return {
286 host,
287 port,
288 pid: Number.isInteger(pid) && pid > 0 ? pid : null,
289 processName: processNameRaw?.trim() || null,
290 };
291 }
292​
293 // Foreign port `:0` identifies a listening TCP socket regardless of Windows locale.
294 const fields = trimmed.split(/\s+/);
295 if (fields.length < 4 || fields[0]?.toUpperCase() !== "TCP") return null;
296 const localEndpoint = fields[1] ?? "";
297 const foreignEndpoint = fields[2] ?? "";
298 if (!foreignEndpoint.endsWith(":0")) return null;
299 const lastColon = localEndpoint.lastIndexOf(":");
300 if (lastColon <= 0) return null;
301 const host = localEndpoint.slice(0, lastColon);
302 if (!LSOF_LOCAL_HOST_TOKENS.has(host) && host !== "::") return null;
303 const port = Number(localEndpoint.slice(lastColon + 1));
304 if (!Number.isInteger(port) || port <= 0 || port >= 65536) return null;
305 const pid = Number(fields.at(-1));
306 return {
307 host,
308 port,
309 pid: Number.isInteger(pid) && pid > 0 ? pid : null,
310 processName: null,
311 };
312};
313​
314const exitedWithError = (result: ProcessRunner.ProcessRunOutput): boolean =>
315 result.code !== null && result.code !== 0;
316​
317const parseTasklistProcessName = (raw: string, pid: number): string | null => {
318 for (const line of raw.split(/\r?\n/g)) {
319 const match = /^"([^"]*)","(\d+)"/.exec(line.trim());
320 if (match && Number(match[2]) === pid) return match[1]!.replace(/\.exe$/i, "") || null;
321 }
322 return null;
323};
324​
325const parseWindowsListenerOutput = (
326 raw: string,
327 owners: ReadonlyMap<number, ServerOwner> = new Map(),
328): ReadonlyArray<DiscoveredLocalServer> => {
329 const seen = new Map<number, DiscoveredLocalServer>();
330 for (const line of raw.split(/\r?\n/g)) {
331 const parsed = parseWindowsListenerLine(line);
332 if (!parsed) continue;
333 const { port, pid: normalizedPid, processName } = parsed;
334 const owner = normalizedPid === null ? undefined : owners.get(normalizedPid);
335 const existing = seen.get(port);
336 if (existing) {
337 if (owner === undefined) seen.set(port, { ...existing, ...UNOWNED });
338 continue;
339 }
340 seen.set(port, {
341 host: "localhost",
342 port,
343 url: `http://localhost:${port}`,
344 processName,
345 pid: normalizedPid,
346 ...(owner ?? UNOWNED),
347 });
348 }
349 return [...seen.values()].toSorted((left, right) => left.port - right.port);
350};
351​
352const PROC_TCP_LISTEN = "0A";
353​
354/** Each 32-bit word of the hex address is little-endian. */
355const procLocalAddress = (hex: string): boolean => {
356 if (hex.length === 8) {
357 return hex === "00000000" || hex.endsWith("7F");
358 }
359 if (hex.length !== 32) return false;
360 if (hex === "0".repeat(32) || hex === `${"0".repeat(24)}01000000`) return true;
361 return hex.startsWith(`${"0".repeat(16)}FFFF0000`) && procLocalAddress(hex.slice(24));
362};
363​
364const parseProcNetTcp = (
365 raw: string,
366): ReadonlyArray<{ readonly port: number; readonly inode: string }> => {
367 const listeners: Array<{ port: number; inode: string }> = [];
368 for (const line of raw.split("\n").slice(1)) {
369 const fields = line.trim().split(/\s+/);
370 const [address, portHex] = fields[1]?.split(":") ?? [];
371 if (fields[3] !== PROC_TCP_LISTEN || !address || !portHex) continue;
372 if (!procLocalAddress(address.toUpperCase())) continue;
373 const port = Number.parseInt(portHex, 16);
374 const inode = fields[9];
375 if (!Number.isInteger(port) || port <= 0 || port >= 65536 || !inode) continue;
376 listeners.push({ port, inode });
377 }
378 return listeners;
379};
380​
381/** Processes holding a loopback or wildcard listener in `lsof -F pcn` output. */
382const lsofProcessIds = (raw: string): ReadonlyArray<number> => {
383 const pids = new Set<number>();
384 let pid: number | null = null;
385 for (const line of raw.split("\n")) {
386 if (line.startsWith("p")) {
387 const parsed = Number.parseInt(line.slice(1), 10);
388 pid = Number.isFinite(parsed) && parsed > 0 ? parsed : null;
389 } else if (
390 line.startsWith("n") &&
391 pid !== null &&
392 parsePortFromLsofName(line.slice(1)) !== null
393 ) {
394 pids.add(pid);
395 }
396 }
397 return [...pids];
398};
399​
400const AGENT_THREAD_ASSIGNMENT = new RegExp(`(?:^|\\s)${AGENT_THREAD_ENV}=(\\S+)`);
401​
402/** Reads `/proc/<pid>/environ`, whose entries are NUL-separated. */
403const parseProcEnvironThread = (raw: string): ThreadId | null => {
404 const prefix = `${AGENT_THREAD_ENV}=`;
405 const value = raw
406 .split("\0")
407 .find((entry) => entry.startsWith(prefix))
408 ?.slice(prefix.length)
409 .trim();
410 return value ? ThreadId.make(value) : null;
411};
412​
413/**
414 * Reads macOS `ps -E -o pid=,command=`, which appends each process's launch environment to its
415 * argv with spaces, so an argument that spells the assignment out also matches.
416 */
417const parsePsEnvironmentThreads = (raw: string): ReadonlyMap<number, ThreadId | null> => {
418 const threads = new Map<number, ThreadId | null>();
419 for (const line of raw.split("\n")) {
420 const match = /^\s*(\d+)\s(.*)$/.exec(line);
421 if (!match) continue;
422 const value = AGENT_THREAD_ASSIGNMENT.exec(match[2]!)?.[1];
423 threads.set(Number(match[1]), value ? ThreadId.make(value) : null);
424 }
425 return threads;
426};
427​
428const parseProcessTable = (raw: string): ReadonlyMap<number, ProcessTableRow> => {
429 const rows = new Map<number, ProcessTableRow>();
430 for (const line of raw.split("\n")) {
431 const [pid, ppid, pgid] = line.trim().split(/\s+/).map(Number);
432 if (Number.isInteger(pid) && Number.isInteger(ppid) && Number.isInteger(pgid)) {
433 rows.set(pid!, { pid: pid!, ppid: ppid!, pgid: pgid! });
434 }
435 }
436 return rows;
437};
438​
439/**
440 * The process group stopping `pid` signals. Shells with job control and agent tool shells give
441 * every job its own group, so the group is the job. Null when the group also holds this server,
442 * a direct child of it (agent CLIs and terminal shells), or one of its ancestors.
443 */
444export const stoppableProcessGroup = (
445 table: ReadonlyMap<number, ProcessTableRow>,
446 pid: number,
447 serverPid: number,
448): number | null => {
449 const group = table.get(pid)?.pgid;
450 if (group === undefined || group <= 1) return null;
451 const guarded = new Set([serverPid]);
452 for (
453 let parent = table.get(serverPid)?.ppid;
454 parent !== undefined && parent > 1 && !guarded.has(parent);
455 parent = table.get(parent)?.ppid
456 ) {
457 guarded.add(parent);
458 }
459 for (const row of table.values()) {
460 if (row.pgid === group && (guarded.has(row.pid) || row.ppid === serverPid)) return null;
461 }
462 return group;
463};
464​
465const serversEqual = (
466 left: ReadonlyArray<DiscoveredLocalServer>,
467 right: ReadonlyArray<DiscoveredLocalServer>,
468): boolean => {
469 if (left.length !== right.length) return false;
470 for (let i = 0; i < left.length; i += 1) {
471 const a = left[i];
472 const b = right[i];
473 if (!a || !b) return false;
474 if (
475 a.host !== b.host ||
476 a.port !== b.port ||
477 a.url !== b.url ||
478 a.processName !== b.processName ||
479 a.pid !== b.pid ||
480 a.terminal?.threadId !== b.terminal?.threadId ||
481 a.terminal?.terminalId !== b.terminal?.terminalId ||
482 a.agent?.threadId !== b.agent?.threadId
483 ) {
484 return false;
485 }
486 }
487 return true;
488};
489​
490const isNoSuchProcess = (cause: unknown): boolean =>
491 typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ESRCH";
492​
493const isCommandNotFound = (error: ProcessRunner.ProcessSpawnError): boolean =>
494 PlatformError.isPlatformError(error.cause) && error.cause.reason._tag === "NotFound";
495​
496/** @public */
497export const make = Effect.gen(function* PortDiscoveryMake() {
498 const processRunner = yield* ProcessRunner.ProcessRunner;
499 const fileSystem = yield* FileSystem.FileSystem;
500 const hostPlatform = yield* HostProcess.Platform;
501 const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.withScope);
502 const stateRef = yield* Ref.make<ScannerState>({
503 listeners: new Map(),
504 terminalProcesses: new Map(),
505 retainCount: 0,
506 });
507 const webProbeCacheRef = yield* Ref.make<ReadonlyMap<string, WebProbeCacheEntry>>(new Map());
508 const scanSemaphore = yield* Semaphore.make(1);
509 const lsofMissingRef = yield* Ref.make(false);
510 const windowsProcessNamesRef = yield* Ref.make<
511 ReadonlyMap<number, { readonly name: string | null; readonly expiresAtMillis: number }>
512 >(new Map());
513 const socketOwnersRef = yield* Ref.make<
514 ReadonlyMap<string, { readonly pid: number; readonly processName: string | null }>
515 >(new Map());
516 const socketOwnerMissesRef = yield* Ref.make<ReadonlyMap<string, number>>(new Map());
517 // Each current listener pid's agent thread, or null without one. A process keeps its launch
518 // environment, so a pid is read once while it listens. Cleared while no client retains the
519 // scanner, since unscanned pids can be reused.
520 const agentThreadsRef = yield* Ref.make<ReadonlyMap<number, ThreadId | null>>(new Map());
521 let runningAgents = 0;
522 // An agent that exited, or a cache cleared with a marked listener, owes one listener read: the
523 // servers it left may still run. So does startup, for agents that ran before a restart.
524 let agentScanPending = true;
525​
526 const readAgentThreads = Effect.fn("PortDiscovery.readAgentThreads")(function* (
527 pids: ReadonlyArray<number>,
528 ) {
529 const cached = yield* Ref.get(agentThreadsRef);
530 const unread = pids.filter((pid) => !cached.has(pid));
531 const read: ReadonlyMap<number, ThreadId | null> =
532 unread.length === 0
533 ? new Map()
534 : hostPlatform === "linux"
535 ? new Map(
536 yield* Effect.forEach(
537 unread,
538 (pid) =>
539 fileSystem.readFileString(`/proc/${pid}/environ`).pipe(
540 Effect.map(parseProcEnvironThread),
541 Effect.orElseSucceed(() => null),
542 Effect.map((threadId) => [pid, threadId] as const),
543 ),
544 { concurrency: 16 },
545 ),
546 )
547 : yield* processRunner
548 .run({
549 command: "ps",
550 args: ["-E", "-ww", "-o", "pid=,command=", "-p", unread.join(",")],
551 timeout: Duration.millis(PS_TIMEOUT_MS),
552 maxOutputBytes: PS_MAX_OUTPUT_BYTES,
553 })
554 .pipe(
555 Effect.map((result) => parsePsEnvironmentThreads(result.stdout)),
556 Effect.orElseSucceed(() => {
557 agentScanPending = true;
558 return new Map();
559 }),
560 );
561 const next = new Map<number, ThreadId | null>();
562 for (const pid of pids) {
563 const threadId = cached.has(pid) ? cached.get(pid) : read.get(pid);
564 if (threadId !== undefined) next.set(pid, threadId);
565 }
566 yield* Ref.set(agentThreadsRef, next);
567 return next;
568 });
569​
570 const withAgentOwners = Effect.fn("PortDiscovery.withAgentOwners")(function* (
571 terminalOwners: ReadonlyMap<number, ServerOwner>,
572 pids: ReadonlyArray<number>,
573 ) {
574 // Runs only once a listener snapshot exists, so a failed read leaves the scan pending.
575 agentScanPending = false;
576 const threads = yield* readAgentThreads(pids.filter((pid) => !terminalOwners.has(pid)));
577 const owners = new Map(terminalOwners);
578 for (const [pid, threadId] of threads) {
579 if (threadId !== null) owners.set(pid, { terminal: null, agent: { threadId } });
580 }
581 return owners;
582 });
583​
584 const findSocketOwners = Effect.fn("PortDiscovery.findSocketOwners")(function* (
585 inodes: ReadonlySet<string>,
586 ) {
587 const owners = new Map<string, { pid: number; processName: string | null }>();
588 const pids = (yield* fileSystem
589 .readDirectory("/proc")
590 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []))).filter((entry) =>
591 /^\d+$/.test(entry),
592 );
593 let budget = PROC_FD_WALK_LIMIT;
594 for (const pidText of pids) {
595 if (owners.size === inodes.size || budget <= 0) break;
596 const fds = yield* fileSystem
597 .readDirectory(`/proc/${pidText}/fd`)
598 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
599 const walked = fds.slice(0, budget);
600 budget -= walked.length;
601 const links = yield* Effect.forEach(
602 walked,
603 (fd) =>
604 fileSystem.readLink(`/proc/${pidText}/fd/${fd}`).pipe(Effect.orElseSucceed(() => "")),
605 { concurrency: 16 },
606 );
607 const held = links.flatMap((link) => /^socket:\[(\d+)\]$/.exec(link)?.[1] ?? []);
608 const matched = held.filter((inode) => inodes.has(inode) && !owners.has(inode));
609 if (matched.length === 0) continue;
610 const processName = yield* fileSystem.readFileString(`/proc/${pidText}/comm`).pipe(
611 Effect.map((name) => name.trim() || null),
612 Effect.orElseSucceed(() => null),
613 );
614 for (const inode of matched) owners.set(inode, { pid: Number(pidText), processName });
615 }
616 return owners;
617 });
618​
619 const scanProcListeners = Effect.fn("PortDiscovery.scanProcListeners")(function* (
620 resolveOwners: (pids: ReadonlyArray<number>) => Effect.Effect<ReadonlyMap<number, ServerOwner>>,
621 ) {
622 if (hostPlatform !== "linux") return null;
623 const tables = yield* Effect.forEach(["/proc/net/tcp", "/proc/net/tcp6"], (path) =>
624 fileSystem.readFileString(path).pipe(Effect.option),
625 );
626 if (tables.every(Option.isNone)) return null;
627 const listeners = tables.flatMap((table) =>
628 Option.isSome(table) ? parseProcNetTcp(table.value) : [],
629 );
630 const known = yield* Ref.get(socketOwnersRef);
631 const knownMisses = yield* Ref.get(socketOwnerMissesRef);
632 const inodes = new Set(listeners.map((listener) => listener.inode));
633 // Walk fds only for unowned sockets; stop after repeated misses for inaccessible or exited processes.
634 const unseen = new Set(
635 [...inodes].filter(
636 (inode) => !known.has(inode) && (knownMisses.get(inode) ?? 0) < SOCKET_OWNER_ATTEMPTS,
637 ),
638 );
639 const found = unseen.size === 0 ? new Map() : yield* findSocketOwners(unseen);
640 const owners = new Map([...known, ...found].filter(([inode]) => inodes.has(inode)));
641 const misses = new Map([...knownMisses].filter(([inode]) => inodes.has(inode)));
642 for (const inode of unseen) {
643 if (!found.has(inode)) misses.set(inode, (misses.get(inode) ?? 0) + 1);
644 }
645 yield* Ref.set(socketOwnersRef, owners);
646 yield* Ref.set(socketOwnerMissesRef, misses);
647 const serverOwners = yield* resolveOwners([
648 ...new Set([...owners.values()].map(({ pid }) => pid)),
649 ]);
650 const seen = new Map<number, DiscoveredLocalServer>();
651 for (const { port, inode } of listeners) {
652 const socketOwner = owners.get(inode) ?? null;
653 const owner = socketOwner === null ? undefined : serverOwners.get(socketOwner.pid);
654 const existing = seen.get(port);
655 if (existing && (existing.pid !== null || socketOwner === null)) {
656 if (owner === undefined) seen.set(port, { ...existing, ...UNOWNED });
657 continue;
658 }
659 seen.set(port, {
660 host: "localhost",
661 port,
662 url: `http://localhost:${port}`,
663 processName: socketOwner?.processName ?? null,
664 pid: socketOwner?.pid ?? null,
665 ...(existing ? UNOWNED : (owner ?? UNOWNED)),
666 });
667 }
668 return [...seen.values()].toSorted((left, right) => left.port - right.port);
669 });
670​
671 const probeWebUrl = Effect.fn("PortDiscovery.probeWebUrl")((url: string) =>
672 httpClient.get(url).pipe(
673 Effect.map((response) => {
674 const location = response.headers.location?.trim();
675 if (NAVIGATION_REDIRECT_STATUSES.has(response.status) && location) return url;
676 if (response.status < 200 || response.status >= 300) return null;
677 if (response.status === 204 || response.status === 205) return null;
678 const contentType = response.headers["content-type"]
679 ?.split(";", 1)[0]
680 ?.trim()
681 .toLowerCase();
682 return contentType === "text/html" || contentType === "application/xhtml+xml" ? url : null;
683 }),
684 Effect.scoped,
685 Effect.timeoutOption(WEB_PROBE_TIMEOUT),
686 Effect.map(Option.getOrNull),
687 Effect.orElseSucceed(() => null),
688 Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }),
689 ),
690 );
691​
692 const makeWebProbeGroups = (
693 servers: ReadonlyArray<DiscoveredLocalServer>,
694 configuredUrls: ReadonlyArray<string>,
695 ): ReadonlyArray<WebProbeGroup> => {
696 const serversByKey = new Map(
697 servers.map((server) => [localServerKey(server.host, server.port), server] as const),
698 );
699 const groups: WebProbeGroup[] = [];
700 const configuredResources = new Set<string>();
701​
702 for (const raw of configuredUrls) {
703 const url = new URL(raw);
704 const port = urlPort(url);
705 const key = localServerKey(url.hostname, port);
706 const resourceKey = webProbeCacheKey(raw);
707 if (configuredResources.has(resourceKey)) continue;
708 configuredResources.add(resourceKey);
709 groups.push({
710 server: serversByKey.get(key) ?? {
711 host: url.hostname,
712 port,
713 url: raw,
714 processName: null,
715 pid: null,
716 terminal: null,
717 },
718 urls: [raw],
719 configuredKey: resourceKey,
720 });
721 }
722​
723 for (const server of servers) {
724 // Never probe an unidentified listener with HTTP or TLS; binary RPC servers can crash on it.
725 if (!isOwned(server)) continue;
726 groups.push({
727 server,
728 urls: [`http://${server.host}:${server.port}`, `https://${server.host}:${server.port}`],
729 configuredKey: null,
730 });
731 }
732​
733 return groups;
734 };
735​
736 const probeWebServers = Effect.fn("PortDiscovery.probeWebServers")(function* (
737 servers: ReadonlyArray<DiscoveredLocalServer>,
738 configuredUrls: ReadonlyArray<string>,
739 ) {
740 const nowMillis = yield* Clock.currentTimeMillis;
741 const cached = yield* Ref.get(webProbeCacheRef);
742 const groups = makeWebProbeGroups(servers, configuredUrls);
743 const batchProbes = new Map<
744 string,
745 Effect.Effect<{ readonly probe: WebProbeCacheEntry; readonly fresh: boolean }>
746 >();
747 const batchProbeSemaphore = yield* Semaphore.make(1);
748 const getProbe = (url: string, pid: number | null) => {
749 const key = webProbeCacheKey(url);
750 const identity = `${key}\u0000${pid ?? ""}`;
751 return batchProbeSemaphore
752 .withPermits(1)(
753 Effect.gen(function* () {
754 const existing = batchProbes.get(identity);
755 if (existing) return [existing] as const;
756 const cachedProbe = cached.get(key);
757 const cachedIsCurrent =
758 cachedProbe?.pid === pid && cachedProbe.expiresAtMillis > nowMillis;
759 const memoized = yield* Effect.cached(
760 cachedIsCurrent
761 ? Effect.succeed({ probe: cachedProbe, fresh: false })
762 : probeWebUrl(url).pipe(
763 Effect.map((result) => ({
764 probe: { pid, isWeb: result !== null, expiresAtMillis: 0 },
765 fresh: true,
766 })),
767 ),
768 );
769 batchProbes.set(identity, memoized);
770 return [memoized] as const;
771 }),
772 )
773 .pipe(Effect.flatMap(([probe]) => probe));
774 };
775 const probed = yield* Effect.forEach(
776 groups,
777 (group) =>
778 Effect.gen(function* () {
779 const probes: Array<readonly [string, WebProbeCacheEntry, boolean]> = [];
780 let visibleUrl: string | null = null;
781 for (const url of group.urls) {
782 const key = webProbeCacheKey(url);
783 const { probe, fresh } = yield* getProbe(url, group.server.pid);
784 probes.push([key, probe, fresh]);
785 if (probe.isWeb) {
786 visibleUrl = url;
787 break;
788 }
789 }
790 return { group, probes, visibleUrl };
791 }),
792 { concurrency: WEB_PROBE_CONCURRENCY },
793 );
794 const completedAtMillis = yield* Clock.currentTimeMillis;
795 const nextCache = new Map(
796 [...cached].filter(([, probe]) => probe.expiresAtMillis > completedAtMillis),
797 );
798 const discovered: DiscoveredLocalServer[] = [];
799 const configured = new Map<string, DiscoveredLocalServer>();
800 for (const { group, probes, visibleUrl } of probed) {
801 for (const [key, probe, fresh] of probes) {
802 nextCache.set(
803 key,
804 fresh ? { ...probe, expiresAtMillis: completedAtMillis + WEB_PROBE_CACHE_TTL_MS } : probe,
805 );
806 }
807 if (visibleUrl === null) continue;
808 const server = { ...group.server, url: visibleUrl };
809 if (group.configuredKey === null) discovered.push(server);
810 else configured.set(group.configuredKey, server);
811 }
812 yield* Ref.set(webProbeCacheRef, nextCache);
813 return { discovered, configured } satisfies WebProbeSnapshot;
814 });
815​
816 // tasklist costs 200-300ms per PID; query visible servers with bounded concurrency and cache names.
817 const withWindowsProcessNames = Effect.fn("PortDiscovery.withWindowsProcessNames")(function* (
818 snapshot: WebProbeSnapshot,
819 ) {
820 const servers = [...snapshot.discovered, ...snapshot.configured.values()];
821 const pids = new Set(servers.flatMap((server) => (server.pid === null ? [] : [server.pid])));
822 const nowMillis = yield* Clock.currentTimeMillis;
823 const cached = [...(yield* Ref.get(windowsProcessNamesRef))].filter(
824 ([pid, entry]) => pids.has(pid) && entry.expiresAtMillis > nowMillis,
825 );
826 const cachedPids = new Set(cached.map(([pid]) => pid));
827 const expiresAtMillis = nowMillis + WINDOWS_PROCESS_NAME_TTL_MS;
828 const fetched = yield* Effect.forEach(
829 [...pids].filter((pid) => !cachedPids.has(pid)),
830 (pid) =>
831 processRunner
832 .run({
833 command: "tasklist.exe",
834 args: ["/FO", "CSV", "/NH", "/FI", `PID eq ${pid}`],
835 timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS),
836 maxOutputBytes: 64 * 1024,
837 })
838 .pipe(
839 Effect.map((result) =>
840 exitedWithError(result)
841 ? []
842 : [
843 [
844 pid,
845 { name: parseTasklistProcessName(result.stdout, pid), expiresAtMillis },
846 ] as const,
847 ],
848 ),
849 Effect.orElseSucceed(() => []),
850 ),
851 { concurrency: WINDOWS_PROCESS_NAME_CONCURRENCY },
852 );
853 const names = new Map([...cached, ...fetched.flat()]);
854 yield* Ref.set(windowsProcessNamesRef, names);
855 const withName = (server: DiscoveredLocalServer): DiscoveredLocalServer =>
856 server.pid === null || server.processName !== null
857 ? server
858 : { ...server, processName: names.get(server.pid)?.name ?? null };
859 return {
860 discovered: snapshot.discovered.map(withName),
861 configured: new Map([...snapshot.configured].map(([key, server]) => [key, withName(server)])),
862 } satisfies WebProbeSnapshot;
863 });
864​
865 const recoverProcessProbeFailure =
866 (probe: "lsof" | "windows-listeners") => (error: ProcessRunner.ProcessRunError) =>
867 Effect.logDebug("preview port process probe failed; probing configured URLs only", {
868 cause: error,
869 probe,
870 platform: hostPlatform,
871 }).pipe(Effect.as(null));
872​
873 const scanUnlocked = Effect.fn("PortDiscovery.scanUnlocked")(function* (
874 configuredUrls: ReadonlyArray<string>,
875 ) {
876 const state = yield* Ref.get(stateRef);
877 const terminalOwners = new Map<number, ServerOwner>();
878 for (const registration of state.terminalProcesses.values()) {
879 for (const processId of registration.processIds) {
880 terminalOwners.set(processId, { terminal: registration.owner, agent: null });
881 }
882 }
883 // A server an agent started can outlive the agent, so listeners are read while the last scan
884 // still found one.
885 const agentsPossible =
886 hostPlatform !== "win32" &&
887 (runningAgents > 0 ||
888 agentScanPending ||
889 [...(yield* Ref.get(agentThreadsRef)).values()].some((threadId) => threadId !== null));
890 if (terminalOwners.size === 0 && configuredUrls.length === 0 && !agentsPossible) {
891 return { discovered: [], configured: new Map() } satisfies WebProbeSnapshot;
892 }
893 const resolveOwners = (pids: ReadonlyArray<number>) =>
894 agentsPossible ? withAgentOwners(terminalOwners, pids) : Effect.succeed(terminalOwners);
895 if (hostPlatform === "win32") {
896 const recoverWindowsProbeFailure = recoverProcessProbeFailure("windows-listeners");
897 const runNetstat = (protocol: "tcp" | "tcpv6") =>
898 processRunner.run({
899 command: "netstat.exe",
900 args: ["-ano", "-p", protocol],
901 timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS),
902 maxOutputBytes: WINDOWS_NETSTAT_MAX_OUTPUT_BYTES,
903 });
904 const listeners = yield* Effect.all([runNetstat("tcp"), runNetstat("tcpv6")], {
905 concurrency: 2,
906 }).pipe(
907 // Failed queries can hide other IPv4/IPv6 listeners on the port; fall back to configured URLs.
908 Effect.map(([tcp4, tcp6]) =>
909 exitedWithError(tcp4) || exitedWithError(tcp6)
910 ? null
911 : parseWindowsListenerOutput(`${tcp4.stdout}\n${tcp6.stdout}`, terminalOwners),
912 ),
913 Effect.catchTags({
914 ProcessSpawnError: recoverWindowsProbeFailure,
915 ProcessStdinError: recoverWindowsProbeFailure,
916 ProcessOutputLimitError: recoverWindowsProbeFailure,
917 ProcessReadError: recoverWindowsProbeFailure,
918 ProcessTimeoutError: recoverWindowsProbeFailure,
919 }),
920 );
921 return yield* withWindowsProcessNames(
922 yield* probeWebServers(listeners ?? [], configuredUrls),
923 );
924 }
925 const recoverLsofProbeFailure = recoverProcessProbeFailure("lsof");
926 if (yield* Ref.get(lsofMissingRef)) {
927 const fromProc = yield* scanProcListeners(resolveOwners);
928 return yield* probeWebServers(fromProc ?? [], configuredUrls);
929 }
930 const lsofResult = yield* processRunner
931 .run({
932 command: "lsof",
933 args: ["-iTCP", "-sTCP:LISTEN", "-P", "-n", "-F", "pcn"],
934 timeout: Duration.millis(LSOF_TIMEOUT_MS),
935 // Partial output could hide another app's listener on an owned port.
936 maxOutputBytes: 1024 * 1024,
937 })
938 .pipe(
939 Effect.flatMap((result) =>
940 resolveOwners(lsofProcessIds(result.stdout)).pipe(
941 Effect.map((owners) => parseLsofOutput(result.stdout, owners)),
942 ),
943 ),
944 Effect.catchTags({
945 ProcessSpawnError: (error) =>
946 (isCommandNotFound(error) ? Ref.set(lsofMissingRef, true) : Effect.void).pipe(
947 Effect.andThen(recoverLsofProbeFailure(error)),
948 ),
949 ProcessStdinError: recoverLsofProbeFailure,
950 ProcessOutputLimitError: recoverLsofProbeFailure,
951 ProcessReadError: recoverLsofProbeFailure,
952 ProcessTimeoutError: recoverLsofProbeFailure,
953 }),
954 );
955 if (lsofResult !== null) return yield* probeWebServers(lsofResult, configuredUrls);
956 const fromProc = yield* scanProcListeners(resolveOwners);
957 return yield* probeWebServers(fromProc ?? [], configuredUrls);
958 });
959​
960 const scanSnapshot = Effect.fn("PortDiscovery.scanSnapshot")(
961 (configuredUrls: ReadonlyArray<string>) =>
962 scanSemaphore.withPermits(1)(scanUnlocked(configuredUrls)),
963 );
964​
965 const scanOnce: PortDiscovery["Service"]["scan"] = (configuredUrls = []) => {
966 const normalized = normalizeConfiguredUrls(configuredUrls);
967 return scanSnapshot(normalized).pipe(
968 Effect.map((snapshot) => projectWebProbeSnapshot(snapshot, normalized)),
969 );
970 };
971​
972 const pollTick = Effect.fn("PortDiscovery.pollTick")(
973 function* () {
974 const configuredUrls = [
975 ...new Set(
976 [...(yield* Ref.get(stateRef)).listeners.values()].flatMap(
977 (subscription) => subscription.configuredUrls,
978 ),
979 ),
980 ];
981 const snapshot = yield* scanSnapshot(configuredUrls);
982 const notifications = yield* Ref.modify(stateRef, (state) => {
983 const listeners = new Map(state.listeners);
984 const changed: Array<readonly [Listener, ReadonlyArray<DiscoveredLocalServer>]> = [];
985 for (const [listener, subscription] of listeners) {
986 const next = projectWebProbeSnapshot(snapshot, subscription.configuredUrls);
987 if (serversEqual(subscription.lastSnapshot, next)) continue;
988 listeners.set(listener, { ...subscription, lastSnapshot: next });
989 changed.push([listener, next]);
990 }
991 return [changed, { ...state, listeners }];
992 });
993 yield* Effect.forEach(notifications, ([listener, servers]) => listener(servers), {
994 discard: true,
995 });
996 },
997 Effect.catchCause((cause: Cause.Cause<never>) =>
998 Effect.logWarning("preview port scan failed", Cause.pretty(cause)),
999 ),
1000 );
1001​
1002 const pollIfRetained = Ref.get(stateRef).pipe(
1003 Effect.flatMap((state) => (state.retainCount > 0 ? pollTick() : Effect.void)),
1004 );
1005 yield* Effect.forkScoped(pollIfRetained.pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL))));
1006​
1007 const acquireRetention = Effect.fn("PortDiscovery.retain")(function* () {
1008 const wasIdle = yield* Ref.modify(stateRef, (state) => [
1009 state.retainCount === 0,
1010 { ...state, retainCount: state.retainCount + 1 },
1011 ]);
1012 if (wasIdle) {
1013 yield* pollTick();
1015 });
1016​
1017 const releaseRetention = Effect.gen(function* () {
1018 const idle = yield* Ref.modify(stateRef, (state) => {
1019 const retainCount = Math.max(0, state.retainCount - 1);
1020 return [retainCount === 0, { ...state, retainCount }];
1021 });
1022 if (!idle) return;
1023 const threads = yield* Ref.getAndSet(agentThreadsRef, new Map());
1024 if ([...threads.values()].some((threadId) => threadId !== null)) agentScanPending = true;
1025 });
1026​
1027 const retain: PortDiscovery["Service"]["retain"] = Effect.acquireRelease(
1028 acquireRetention(),
1029 () => releaseRetention,
1030 );
1031​
1032 const subscribe: PortDiscovery["Service"]["subscribe"] = Effect.fn("PortDiscovery.subscribe")(
1033 (input, listener) =>
1034 Effect.acquireRelease(
1035 Ref.update(stateRef, (state) => {
1036 const listeners = new Map(state.listeners);
1037 listeners.set(listener, {
1038 configuredUrls: normalizeConfiguredUrls(input.configuredUrls),
1039 lastSnapshot: input.initialSnapshot,
1040 });
1041 return { ...state, listeners };
1042 }),
1043 () =>
1044 Ref.update(stateRef, (state) => {
1045 const listeners = new Map(state.listeners);
1046 listeners.delete(listener);
1047 return { ...state, listeners };
1048 }),
1049 ),
1050 );
1051​
1052 const registerTerminalProcesses: PortDiscovery["Service"]["registerTerminalProcesses"] =
1053 Effect.fn("PortDiscovery.registerTerminalProcesses")(function* (input) {
1054 const owner = {
1055 threadId: ThreadId.make(input.threadId),
1056 terminalId: input.terminalId,
1057 };
1058 const processIds = new Set(
1059 input.processIds.filter((processId) => Number.isInteger(processId) && processId > 0),
1060 );
1061 yield* Ref.update(stateRef, (state) => {
1062 const terminalProcesses = new Map(state.terminalProcesses);
1063 const key = terminalOwnerKey(owner);
1064 if (processIds.size === 0) {
1065 terminalProcesses.delete(key);
1066 } else {
1067 terminalProcesses.set(key, { owner, processIds });
1069 return { ...state, terminalProcesses };
1070 });
1071 });
1072​
1073 const unregisterTerminal: PortDiscovery["Service"]["unregisterTerminal"] = Effect.fn(
1074 "PortDiscovery.unregisterTerminal",
1075 )(function* (input) {
1076 yield* Ref.update(stateRef, (state) => {
1077 const terminalProcesses = new Map(state.terminalProcesses);
1078 terminalProcesses.delete(terminalOwnerKey(input));
1079 return { ...state, terminalProcesses };
1080 });
1081 });
1082​
1083 const trackAgent: PortDiscovery["Service"]["trackAgent"] = () => {
1084 runningAgents += 1;
1085 let released = false;
1086 return () => {
1087 if (released) return;
1088 released = true;
1089 runningAgents -= 1;
1090 agentScanPending = true;
1091 };
1092 };
1093​
1094 // Fails when `ps` does, so an empty table never reads as every process having exited.
1095 const readProcessTable = Effect.suspend(() =>
1096 processRunner.run({
1097 command: "ps",
1098 args: ["-A", "-o", "pid=,ppid=,pgid="],
1099 timeout: Duration.millis(PS_TIMEOUT_MS),
1100 maxOutputBytes: PS_MAX_OUTPUT_BYTES,
1101 }),
1102 ).pipe(
1103 Effect.mapError((cause) => new PreviewStopLocalServerError({ reason: "signal-failed", cause })),
1104 Effect.filterOrFail(
1105 (result) => !exitedWithError(result),
1106 () => new PreviewStopLocalServerError({ reason: "signal-failed" }),
1107 ),
1108 Effect.map((result) => parseProcessTable(result.stdout)),
1109 );
1110​
1111 const signalUntilStopped = Effect.fn("PortDiscovery.signalUntilStopped")(function* (
1112 input: PreviewStopLocalServerInput,
1113 ) {
1114 if (hostPlatform === "win32") {
1115 return yield* new PreviewStopLocalServerError({ reason: "unsupported" });
1117 // A socket can outlive its cached owner. Wait for any in-flight scan before invalidating
1118 // that owner, so the /proc fallback confirms who holds it before a signal is sent.
1119 yield* scanSemaphore.withPermits(1)(
1120 Ref.update(
1121 socketOwnersRef,
1122 (owners) => new Map([...owners].filter(([, owner]) => owner.pid !== input.pid)),
1123 ),
1124 );
1125 // The pid comes from a client, so only a server this scan attributes to a thread is signaled,
1126 // from its environment as read now.
1127 yield* Ref.update(agentThreadsRef, (threads) => {
1128 const next = new Map(threads);
1129 next.delete(input.pid);
1130 return next;
1131 });
1132 agentScanPending = true;
1133 const listed = (yield* scanOnce()).some(
1134 (server) => server.pid === input.pid && server.port === input.port && isOwned(server),
1135 );
1136 if (!listed) return yield* new PreviewStopLocalServerError({ reason: "not-found" });
1137 const table = yield* readProcessTable;
1138 // It exited after the scan, so there is nothing left to stop.
1139 if (!table.has(input.pid)) return;
1140 const group = stoppableProcessGroup(table, input.pid, process.pid);
1141 if (group === null) return yield* new PreviewStopLocalServerError({ reason: "shared-group" });
1142 // False when the whole group already exited.
1143 const signalGroup = (signal: "SIGTERM" | "SIGKILL") =>
1144 Effect.suspend(() => {
1145 try {
1146 signalProcessGroup(group, signal);
1147 return Effect.succeed(true);
1148 } catch (cause) {
1149 return isNoSuchProcess(cause)
1150 ? Effect.succeed(false)
1151 : Effect.fail(new PreviewStopLocalServerError({ reason: "signal-failed", cause }));
1153 });
1154 if (!(yield* signalGroup("SIGTERM"))) return;
1155 // While one of the group's original members is still in it, the group has not been reused,
1156 // so SIGKILL goes only to the job that ignored SIGTERM.
1157 const members = [...table.values()].filter((row) => row.pgid === group).map((row) => row.pid);
1158 const jobRunning = readProcessTable.pipe(
1159 Effect.map((current) => members.some((pid) => current.get(pid)?.pgid === group)),
1160 Effect.orElseSucceed(() => false),
1161 );
1162 const deadline = (yield* Clock.currentTimeMillis) + STOP_GRACE_MS;
1163 while ((yield* Clock.currentTimeMillis) < deadline) {
1164 yield* Effect.sleep(STOP_POLL_INTERVAL);
1165 if (!(yield* jobRunning)) return;
1167 yield* signalGroup("SIGKILL");
1168 });
1169​
1170 const stopServer: PortDiscovery["Service"]["stopServer"] = (input) =>
1171 // Subscribers see the server leave now rather than on the next poll.
1172 signalUntilStopped(input).pipe(Effect.andThen(pollIfRetained));
1173​
1174 return PortDiscovery.of({
1175 scan: scanOnce,
1176 subscribe,
1177 retain,
1178 registerTerminalProcesses,
1179 unregisterTerminal,
1180 trackAgent,
1181 stopServer,
1182 });
1183}).pipe(Effect.withSpan("PortDiscovery.make"));
1184​
1185export const layer = Layer.effect(PortDiscovery, make);
1186​
1187/** A scanner that tracks nothing, for tests that build provider runners without a host. */
1188export const layerTest = Layer.mock(PortDiscovery)({ trackAgent: () => () => undefined });