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