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