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

PortScanner.ts

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