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