@warlock.js/process 5.39.2 → 5.40.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/README.md +6 -6
- package/cjs/index.cjs +564 -186
- package/cjs/index.cjs.map +1 -1
- package/esm/guardian.mjs +19 -7
- package/esm/guardian.mjs.map +1 -1
- package/esm/identity.d.mts.map +1 -1
- package/esm/identity.mjs +8 -5
- package/esm/identity.mjs.map +1 -1
- package/esm/platform.d.mts.map +1 -1
- package/esm/platform.mjs +21 -5
- package/esm/platform.mjs.map +1 -1
- package/esm/registry.mjs +5 -3
- package/esm/registry.mjs.map +1 -1
- package/esm/supervisor.d.mts.map +1 -1
- package/esm/supervisor.mjs +114 -19
- package/esm/supervisor.mjs.map +1 -1
- package/esm/types.d.mts +10 -0
- package/esm/types.d.mts.map +1 -1
- package/esm/windows-helper.mjs +257 -0
- package/esm/windows-helper.mjs.map +1 -0
- package/llms-full.txt +5 -1
- package/package.json +1 -1
- package/skills/SKILL.md +5 -1
package/esm/supervisor.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"supervisor.mjs","names":["delay","spawnChild"],"sources":["../../../../../../../packages/process/src/supervisor.ts"],"sourcesContent":["import { spawn as spawnChild } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport path from \"node:path\";\nimport { PassThrough, Writable } from \"node:stream\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { identity, owns, ProcessNotOwnedError, executeCommand } from \"./identity\";\nimport { guardianProof, launchCommand } from \"./guardian\";\nimport { supported, taskkillCommand } from \"./platform\";\nimport { Registry, type RegistryEntry } from \"./registry\";\nimport {\n attachCgroup,\n cgroupMemory,\n cleanCgroup,\n recoveredCgroup,\n validateLimits,\n} from \"./resources\";\nimport type {\n ProcessExit,\n ProcessFilter,\n ProcessHandle,\n ProcessInfo,\n ProcessSupervisor,\n PtyHandle,\n RecoveryResult,\n SpawnOptions,\n SupervisorOptions,\n} from \"./types\";\n\ntype Pty = {\n pid: number;\n onData(listener: (data: string) => void): { dispose(): void };\n onExit(listener: (event: { exitCode: number; signal?: number }) => void): { dispose(): void };\n write(data: string): void;\n resize(columns: number, rows: number): void;\n};\ntype PtyModule = {\n spawn(\n command: string,\n args: string[],\n options: {\n cwd?: string;\n env: Record<string, string>;\n cols: number;\n rows: number;\n name: string;\n },\n ): Pty;\n};\ntype Active = {\n entry: RegistryEntry;\n handle: ProcessHandle;\n reason?: ProcessExit[\"reason\"];\n finish(code: number | null, signal: string | null): Promise<void>;\n stopping?: Promise<void>;\n timer?: ReturnType<typeof setInterval>;\n finished: boolean;\n adopted: boolean;\n fail(error: unknown): void;\n};\n\nfunction info(entry: RegistryEntry): ProcessInfo {\n const { token: _token, start: _start, cgroup: _cgroup, gated: _gated, ...visible } = entry;\n return structuredClone(visible);\n}\nfunction validateFilter(filter: ProcessFilter): void {\n if (\n !filter ||\n typeof filter !== \"object\" ||\n Array.isArray(filter) ||\n Object.keys(filter).some((key) => key !== \"labels\")\n )\n throw new Error(\"Only label filters are supported\");\n if (\n filter.labels !== undefined &&\n (filter.labels === null ||\n typeof filter.labels !== \"object\" ||\n Array.isArray(filter.labels) ||\n !Object.values(filter.labels).every((value) => typeof value === \"string\"))\n )\n throw new Error(\"Labels must be string key/value pairs\");\n}\nfunction matches(entry: RegistryEntry, filter: ProcessFilter): boolean {\n return Object.entries(filter.labels ?? {}).every(([key, value]) => entry.labels[key] === value);\n}\n\nexport function supervisor(options: SupervisorOptions): ProcessSupervisor {\n for (const option of [\"owner\", \"registry\"] as const) {\n if (!options || typeof options[option] !== \"string\" || !options[option].trim()) {\n throw new TypeError(`Invalid supervisor configuration: ${option} must be a nonempty string`);\n }\n }\n validateLimits(options.defaults ?? {});\n // Caller-owned configuration must not change an active supervisor's identity.\n options = { ...options, defaults: { ...options.defaults } };\n const pollMs = options.pollIntervalMs ?? 100;\n const graceMs = options.stopGraceMs ?? 1000;\n if (!Number.isSafeInteger(pollMs) || pollMs < 10 || !Number.isSafeInteger(graceMs) || graceMs < 0)\n throw new Error(\"Invalid polling interval or stop grace period\");\n const registry = new Registry(path.resolve(options.registry), options.owner);\n const entries = new Map<number, RegistryEntry>();\n const active = new Map<number, Active>();\n let ready: Promise<void> | undefined;\n let closing = false;\n let shutdown: Promise<void> | undefined;\n // Serialize public operations, including shutdown, so a gated spawn cannot escape stopAll.\n let queue: Promise<unknown> = Promise.resolve();\n function serial<T>(operation: () => Promise<T>): Promise<T> {\n const next = queue.then(operation);\n queue = next.catch(() => undefined);\n return next;\n }\n async function open(): Promise<void> {\n supported(process.platform);\n if (closing) throw new Error(\"Supervisor has shut down\");\n ready ??= registry.open().then((saved) => {\n for (const entry of saved) {\n delete entry.cgroup;\n entries.set(entry.pid, entry);\n }\n });\n await ready;\n }\n const save = () => registry.save([...entries.values()]);\n\n async function signal(entry: RegistryEntry, value: NodeJS.Signals): Promise<void> {\n if (!(await owns(entry))) throw new ProcessNotOwnedError(entry.pid);\n if (process.platform !== \"linux\" && value === \"SIGCONT\") {\n const proof = await guardianProof(entry.pid, entry.token);\n if (!proof || proof.token !== entry.token || proof.gated)\n throw new ProcessNotOwnedError(entry.pid);\n return;\n }\n if (process.platform === \"win32\") {\n try {\n await executeCommand(taskkillCommand(entry.pid));\n } catch (error) {\n if (await owns(entry)) throw error;\n }\n return;\n }\n // Negative PID targets only the session/group established for this child.\n // Recheck for every signal, including escalation; never match a command line.\n try {\n process.kill(-entry.pid, value);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ESRCH\") throw error;\n }\n }\n async function stopEntry(\n entry: RegistryEntry,\n reason: ProcessExit[\"reason\"] = \"stopped\",\n ): Promise<void> {\n const tracked = active.get(entry.pid);\n let running: Active;\n if (!tracked) {\n if (!(await owns(entry))) throw new ProcessNotOwnedError(entry.pid);\n entry.cgroup = await recoveredCgroup(entry.pid, entry.token);\n running = track(entry);\n } else running = tracked;\n if (running.finished) return running.finish(null, null);\n if (running.stopping) return running.stopping;\n const stopping = (async () => {\n if (!(await owns(entry))) throw new ProcessNotOwnedError(entry.pid);\n running.reason ??= reason;\n await signal(entry, \"SIGTERM\");\n const deadline = Date.now() + graceMs;\n while (await owns(entry)) {\n if (Date.now() >= deadline) {\n await signal(entry, \"SIGKILL\");\n break;\n }\n await delay(20);\n }\n const killedDeadline = Date.now() + 5000;\n while (await owns(entry)) {\n if (Date.now() >= killedDeadline)\n throw new Error(`Process ${entry.pid} did not exit after SIGKILL`);\n await delay(20);\n }\n await running.finish(null, null);\n })();\n running.stopping = stopping;\n try {\n await stopping;\n } catch (error) {\n running.stopping = undefined;\n // The leader may exit between identity verification and a signal. A\n // missing identity is harmless for a tracked handle; a live mismatch is\n // still an ownership failure and must never receive another signal.\n if (error instanceof ProcessNotOwnedError && !(await identity(entry.pid))) {\n await running.finish(null, null);\n return;\n }\n throw error;\n }\n }\n\n function track(\n entry: RegistryEntry,\n streams?: Pick<ProcessHandle, \"stdin\" | \"stdout\" | \"stderr\">,\n ): Active {\n let resolveExit: (exit: ProcessExit) => void = () => undefined;\n let rejectExit: (error: unknown) => void = () => undefined;\n const exited = new Promise<ProcessExit>((resolve, reject) => {\n resolveExit = resolve;\n rejectExit = reject;\n });\n // A rejected persistence operation is still observable through handle.exited.\n void exited.catch(() => undefined);\n const stdout = streams?.stdout ?? new PassThrough();\n const stderr = streams?.stderr ?? new PassThrough();\n const stdin = streams?.stdin ?? new PassThrough();\n let finishing: Promise<void> | undefined;\n const running: Active = {\n entry,\n finished: false,\n adopted: !streams,\n fail: (error) => rejectExit(error),\n handle: {\n pid: entry.pid,\n stdout,\n stderr,\n stdin,\n exited,\n stop: () =>\n serial(async () => {\n if (!running.finished) await stopEntry(entry);\n }),\n },\n finish(code, sig) {\n finishing ??= (async () => {\n running.finished = true;\n clearInterval(running.timer);\n if (entry.cgroup) {\n const memory = await cgroupMemory(entry.cgroup);\n entry.peakMemoryBytes = Math.max(entry.peakMemoryBytes, memory.peak);\n if (memory.oom) running.reason = \"memory-cap\";\n await cleanCgroup(entry.cgroup);\n }\n active.delete(entry.pid);\n entries.delete(entry.pid);\n try {\n await save();\n resolveExit({\n reason: running.reason ?? \"exit\",\n code,\n signal: sig,\n peakMemoryBytes: entry.peakMemoryBytes,\n });\n } catch (error) {\n rejectExit(error);\n throw error;\n }\n if (!streams) {\n (stdout as PassThrough).end();\n (stderr as PassThrough).end();\n stdin.end();\n }\n })();\n return finishing;\n },\n };\n active.set(entry.pid, running);\n return running;\n }\n\n function monitor(running: Active): void {\n if (running.finished) return;\n let sampling = false;\n const sample = async () => {\n if (sampling || running.finished) return;\n sampling = true;\n try {\n const entry = running.entry;\n const current = await identity(entry.pid, true, entry.token);\n if (running.finished) return;\n if (\n current?.start !== entry.start ||\n current.token !== entry.token ||\n current.group !== entry.pid\n ) {\n if (!current) {\n if (running.adopted) await running.finish(null, null);\n } else {\n // A live child that changes its environment or group can no longer\n // be supervised safely. Preserve the entry and surface the failure.\n throw new ProcessNotOwnedError(entry.pid);\n }\n return;\n }\n entry.peakMemoryBytes = Math.max(entry.peakMemoryBytes, current.rss);\n if (entry.cgroup) {\n const memory = await cgroupMemory(entry.cgroup);\n if (running.finished) return;\n entry.peakMemoryBytes = Math.max(entry.peakMemoryBytes, memory.peak);\n if (memory.oom) running.reason = \"memory-cap\";\n }\n if (entry.limits.memoryBytes && entry.peakMemoryBytes > entry.limits.memoryBytes)\n await stopEntry(entry, \"memory-cap\");\n else if (entry.limits.timeoutMs && Date.now() - entry.startedAt >= entry.limits.timeoutMs)\n await stopEntry(entry, \"timeout\");\n } finally {\n sampling = false;\n }\n };\n running.timer = setInterval(() => {\n void sample().catch((error: unknown) => {\n // Never signal on an observation error. Surface it to the caller and keep the registry.\n clearInterval(running.timer);\n if (!running.finished) running.fail(error);\n });\n }, pollMs);\n running.timer.unref();\n }\n\n async function launch(\n input: SpawnOptions & { columns?: number; rows?: number },\n terminal: boolean,\n ): Promise<ProcessHandle | PtyHandle> {\n await open();\n if ([...entries.keys()].some((pid) => !active.has(pid)))\n throw new Error(\"Call recover() before spawning with an existing registry\");\n if (\n typeof input.command !== \"string\" ||\n !input.command ||\n typeof input.kind !== \"string\" ||\n !input.kind\n )\n throw new Error(\"kind and command are required\");\n validateFilter({ labels: input.labels });\n if (\n terminal &&\n [input.columns ?? 80, input.rows ?? 24].some(\n (size) => !Number.isSafeInteger(size) || size <= 0,\n )\n )\n throw new Error(\"Terminal dimensions must be positive safe integers\");\n const limits = { ...options.defaults, ...input.limits };\n validateLimits(limits);\n const token = randomBytes(32).toString(\"hex\");\n const {\n file: executable,\n args,\n env,\n } = launchCommand(\n process.platform,\n process.execPath,\n input.command,\n input.args ?? [],\n limits,\n { ...process.env, ...input.env },\n token,\n );\n let pid: number;\n let streams: Pick<ProcessHandle, \"stdin\" | \"stdout\" | \"stderr\">;\n let terminalProcess: Pty | undefined;\n let exit: { code: number | null; signal: string | null } | undefined;\n let spawnError: Error | undefined;\n let running: Active | undefined;\n const onExit = (code: number | null, sig: string | null) => {\n exit = { code, signal: sig };\n if (running) void running.finish(code, sig).catch(() => undefined);\n };\n if (terminal) {\n // Optional peer loaded only here. Structural types follow node-pty's official typings.\n const peer = \"node-pty\";\n const pty = (await import(peer)) as PtyModule;\n terminalProcess = pty.spawn(executable, args, {\n cwd: input.cwd,\n env: Object.fromEntries(\n Object.entries(env).filter((pair): pair is [string, string] => pair[1] !== undefined),\n ),\n cols: input.columns ?? 80,\n rows: input.rows ?? 24,\n name: \"xterm-256color\",\n });\n pid = terminalProcess.pid;\n const output = new PassThrough();\n const errors = new PassThrough();\n const instance = terminalProcess;\n const dataSubscription = instance.onData((data) => output.write(data));\n const inputStream = new Writable({\n write(chunk: Buffer, _encoding, callback) {\n instance.write(chunk.toString());\n callback();\n },\n });\n const exitSubscription = instance.onExit((event) => {\n dataSubscription.dispose();\n exitSubscription.dispose();\n output.end();\n errors.end();\n inputStream.end();\n onExit(event.exitCode, event.signal ? String(event.signal) : null);\n });\n streams = { stdout: output, stderr: errors, stdin: inputStream };\n } else {\n const child = spawnChild(executable, args, {\n cwd: input.cwd,\n env,\n detached: process.platform !== \"win32\",\n windowsHide: true,\n stdio: \"pipe\",\n });\n child.on(\"error\", (error) => {\n spawnError = error;\n });\n // Finish on leader exit so cgroup cleanup can stop remaining members;\n // waiting for close could deadlock on a descendant holding a pipe open.\n child.on(\"exit\", onExit);\n if (!child.pid) throw new Error(\"Could not start process\");\n pid = child.pid;\n streams = { stdout: child.stdout, stderr: child.stderr, stdin: child.stdin };\n }\n let entry: RegistryEntry | undefined;\n try {\n const deadline = Date.now() + 5000;\n let current = await identity(pid, true, token);\n while (!current?.state.startsWith(\"T\") || current.token !== token) {\n if (spawnError) throw spawnError;\n if (exit || Date.now() >= deadline)\n throw new Error(\"Child failed to reach the resource setup gate\");\n await delay(10);\n current = await identity(pid, true, token);\n }\n if (current.group !== pid) throw new Error(\"Child did not create an isolated process group\");\n entry = {\n pid,\n owner: options.owner,\n type: input.kind,\n command: input.command,\n args: [...(input.args ?? [])],\n labels: { ...input.labels },\n startedAt: Date.now(),\n limits,\n enforcement: process.platform === \"win32\" ? \"rss-polling\" : \"rlimit-polling\",\n peakMemoryBytes: current.rss,\n token,\n start: current.start,\n gated: true,\n };\n entry.cgroup = await attachCgroup(pid, token, limits, options.cgroupRoot);\n if (entry.cgroup) entry.enforcement = \"cgroup-v2\";\n entries.set(pid, entry);\n await save();\n running = track(entry, streams);\n await signal(entry, \"SIGCONT\");\n delete entry.gated;\n await save();\n monitor(running);\n if (terminalProcess) {\n const instance = terminalProcess;\n return {\n ...running.handle,\n write: (data: string) => instance.write(data),\n resize: (columns: number, rows: number) => instance.resize(columns, rows),\n };\n }\n return running.handle;\n } catch (error) {\n // This PID was created by this call. Kill only after its random token is verified.\n const current = await identity(pid, true, token);\n if (current?.token === token) {\n const failed = { pid, token, start: current.start };\n if (await owns(failed)) {\n try {\n if (process.platform === \"win32\") await executeCommand(taskkillCommand(pid));\n else process.kill(-pid, \"SIGKILL\");\n } catch {\n /* Already exited. */\n }\n }\n }\n if (entry && !running) {\n entries.delete(pid);\n await save();\n }\n if (entry?.cgroup) await cleanCgroup(entry.cgroup);\n throw error;\n }\n }\n\n const api: ProcessSupervisor = {\n spawn: (input) => serial(() => launch(input, false)),\n spawnPty: (input) => serial(async () => (await launch(input, true)) as PtyHandle),\n list: (filter = {}) =>\n serial(async () => {\n validateFilter(filter);\n await open();\n return [...entries.values()].filter((entry) => matches(entry, filter)).map(info);\n }),\n stop: (filter = {}) =>\n serial(async () => {\n validateFilter(filter);\n await open();\n for (const entry of [...entries.values()].filter((entry) => matches(entry, filter)))\n await stopEntry(entry);\n }),\n stopPid: (pid) =>\n serial(async () => {\n await open();\n const entry = entries.get(pid);\n if (!entry) throw new ProcessNotOwnedError(pid);\n await stopEntry(entry);\n }),\n recover: (recovery = {}) =>\n serial(async () => {\n await open();\n const result: RecoveryResult = { adopted: [], stopped: [], cleared: [] };\n for (const entry of [...entries.values()]) {\n if (active.has(entry.pid)) continue;\n if (!(await owns(entry))) {\n entries.delete(entry.pid);\n result.cleared.push(entry.pid);\n continue;\n }\n // Never trust a persisted filesystem path for cgroup I/O after a restart.\n entry.cgroup = await recoveredCgroup(entry.pid, entry.token);\n entry.enforcement = entry.cgroup\n ? \"cgroup-v2\"\n : process.platform === \"win32\"\n ? \"rss-polling\"\n : \"rlimit-polling\";\n const keep = await recovery.keep?.(info(entry));\n if (keep) {\n const running = track(entry);\n monitor(running);\n if (entry.gated) {\n await signal(entry, \"SIGCONT\");\n delete entry.gated;\n }\n result.adopted.push(entry.pid);\n } else {\n await stopEntry(entry);\n result.stopped.push(entry.pid);\n }\n }\n await save();\n return result;\n }),\n stopAll() {\n shutdown ??= serial(async () => {\n await open();\n closing = true;\n try {\n const errors: unknown[] = [];\n for (const entry of [...entries.values()]) {\n try {\n if (await owns(entry)) await stopEntry(entry);\n else {\n const running = active.get(entry.pid);\n if (running) await running.finish(null, null);\n else entries.delete(entry.pid);\n }\n } catch (error) {\n errors.push(error);\n }\n }\n await save();\n if (errors.length)\n throw new AggregateError(errors, \"Some owned processes could not be stopped\");\n } finally {\n await registry.close();\n }\n });\n return shutdown;\n },\n };\n return api;\n}\n"],"mappings":";;;;;;;;;;;;AA4DA,SAAS,KAAK,OAAmC;CAC/C,MAAM,EAAE,OAAO,QAAQ,OAAO,QAAQ,QAAQ,SAAS,OAAO,QAAQ,GAAG,YAAY;CACrF,OAAO,gBAAgB,OAAO;AAChC;AACA,SAAS,eAAe,QAA6B;CACnD,IACE,CAAC,UACD,OAAO,WAAW,YAClB,MAAM,QAAQ,MAAM,KACpB,OAAO,KAAK,MAAM,CAAC,CAAC,MAAM,QAAQ,QAAQ,QAAQ,GAElD,MAAM,IAAI,MAAM,kCAAkC;CACpD,IACE,OAAO,WAAW,WACjB,OAAO,WAAW,QACjB,OAAO,OAAO,WAAW,YACzB,MAAM,QAAQ,OAAO,MAAM,KAC3B,CAAC,OAAO,OAAO,OAAO,MAAM,CAAC,CAAC,OAAO,UAAU,OAAO,UAAU,QAAQ,IAE1E,MAAM,IAAI,MAAM,uCAAuC;AAC3D;AACA,SAAS,QAAQ,OAAsB,QAAgC;CACrE,OAAO,OAAO,QAAQ,OAAO,UAAU,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,WAAW,MAAM,OAAO,SAAS,KAAK;AAChG;AAEA,SAAgB,WAAW,SAA+C;CACxE,KAAK,MAAM,UAAU,CAAC,SAAS,UAAU,GACvC,IAAI,CAAC,WAAW,OAAO,QAAQ,YAAY,YAAY,CAAC,QAAQ,OAAO,CAAC,KAAK,GAC3E,MAAM,IAAI,UAAU,qCAAqC,OAAO,2BAA2B;CAG/F,eAAe,QAAQ,YAAY,CAAC,CAAC;CAErC,UAAU;EAAE,GAAG;EAAS,UAAU,EAAE,GAAG,QAAQ,SAAS;CAAE;CAC1D,MAAM,SAAS,QAAQ,kBAAkB;CACzC,MAAM,UAAU,QAAQ,eAAe;CACvC,IA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AM,KAAK,MAAM,KAAK;IAC3D,MAAM,cAAc,MAAM,SACtB,cACA,QAAQ,aAAa,UACnB,gBACA;IAEN,IAAI,MADe,SAAS,OAAO,KAAK,KAAK,CAAC,GACpC;KAER,QADgB,MAAM,KACR,CAAC;KACf,IAAI,MAAM,OAAO;MACf,MAAM,OAAO,OAAO,SAAS;MAC7B,OAAO,MAAM;KACf;KACA,OAAO,QAAQ,KAAK,MAAM,GAAG;IAC/B,OAAO;KACL,MAAM,UAAU,KAAK;KACrB,OAAO,QAAQ,KAAK,MAAM,GAAG;IAC/B;GACF;GACA,MAAM,KAAK;GACX,OAAO;EACT,CAAC;EACH,UAAU;GACR,aAAa,OAAO,YAAY;IAC9B,MAAM,KAAK;IACX,UAAU;IACV,IAAI;KACF,MAAM,SAAoB,CAAC;KAC3B,KAAK,MAAM,SAAS,CAAC,GAAG,QAAQ,OAAO,CAAC,GACtC,IAAI;MACF,IAAI,MAAM,KAAK,KAAK,GAAG,MAAM,UAAU,KAAK;WACvC;OACH,MAAM,UAAU,OAAO,IAAI,MAAM,GAAG;OACpC,IAAI,SAAS,MAAM,QAAQ,OAAO,MAAM,IAAI;YACvC,QAAQ,OAAO,MAAM,GAAG;MAC/B;KACF,SAAS,OAAO;MACd,OAAO,KAAK,KAAK;KACnB;KAEF,MAAM,KAAK;KACX,IAAI,OAAO,QACT,MAAM,IAAI,eAAe,QAAQ,2CAA2C;IAChF,UAAU;KACR,MAAM,SAAS,MAAM;IACvB;GACF,CAAC;GACD,OAAO;EACT;CAEO;AACX"}
|
|
1
|
+
{"version":3,"file":"supervisor.mjs","names":["delay","spawnChild"],"sources":["../../../../../../../packages/process/src/supervisor.ts"],"sourcesContent":["import { spawn as spawnChild } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport path from \"node:path\";\nimport { PassThrough, Writable } from \"node:stream\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { identity, owns, ProcessNotOwnedError, executeCommand, type Observation } from \"./identity\";\nimport { guardianProof, launchCommand } from \"./guardian\";\nimport {\n defaultObservationTimeoutMs,\n defaultPollIntervalMs,\n supported,\n taskkillCommand,\n} from \"./platform\";\nimport { Registry, type RegistryEntry } from \"./registry\";\nimport { createWindowsHelper, type WindowsProcessHelper } from \"./windows-helper\";\nimport {\n attachCgroup,\n cgroupMemory,\n cleanCgroup,\n recoveredCgroup,\n validateLimits,\n} from \"./resources\";\nimport type {\n ProcessExit,\n ProcessFilter,\n ProcessHandle,\n ProcessInfo,\n ProcessSupervisor,\n PtyHandle,\n RecoveryResult,\n SpawnOptions,\n SupervisorOptions,\n} from \"./types\";\n\ntype Pty = {\n pid: number;\n onData(listener: (data: string) => void): { dispose(): void };\n onExit(listener: (event: { exitCode: number; signal?: number }) => void): { dispose(): void };\n write(data: string): void;\n resize(columns: number, rows: number): void;\n};\ntype PtyModule = {\n spawn(\n command: string,\n args: string[],\n options: {\n cwd?: string;\n env: Record<string, string>;\n cols: number;\n rows: number;\n name: string;\n },\n ): Pty;\n};\ntype Active = {\n entry: RegistryEntry;\n handle: ProcessHandle;\n reason?: ProcessExit[\"reason\"];\n finish(code: number | null, signal: string | null): Promise<void>;\n stopping?: Promise<void>;\n timer?: ReturnType<typeof setInterval>;\n finished: boolean;\n adopted: boolean;\n fail(error: unknown): void;\n};\n\nfunction info(entry: RegistryEntry): ProcessInfo {\n const { token: _token, start: _start, cgroup: _cgroup, gated: _gated, ...visible } = entry;\n return structuredClone(visible);\n}\nfunction validateFilter(filter: ProcessFilter): void {\n if (\n !filter ||\n typeof filter !== \"object\" ||\n Array.isArray(filter) ||\n Object.keys(filter).some((key) => key !== \"labels\")\n )\n throw new Error(\"Only label filters are supported\");\n if (\n filter.labels !== undefined &&\n (filter.labels === null ||\n typeof filter.labels !== \"object\" ||\n Array.isArray(filter.labels) ||\n !Object.values(filter.labels).every((value) => typeof value === \"string\"))\n )\n throw new Error(\"Labels must be string key/value pairs\");\n}\nfunction matches(entry: RegistryEntry, filter: ProcessFilter): boolean {\n return Object.entries(filter.labels ?? {}).every(([key, value]) => entry.labels[key] === value);\n}\n\nexport function supervisor(options: SupervisorOptions): ProcessSupervisor {\n for (const option of [\"owner\", \"registry\"] as const) {\n if (!options || typeof options[option] !== \"string\" || !options[option].trim()) {\n throw new TypeError(`Invalid supervisor configuration: ${option} must be a nonempty string`);\n }\n }\n validateLimits(options.defaults ?? {});\n // Caller-owned configuration must not change an active supervisor's identity.\n options = { ...options, defaults: { ...options.defaults } };\n const pollMs = options.pollIntervalMs ?? defaultPollIntervalMs(process.platform);\n const graceMs = options.stopGraceMs ?? 1000;\n if (!Number.isSafeInteger(pollMs) || pollMs < 10 || !Number.isSafeInteger(graceMs) || graceMs < 0)\n throw new Error(\"Invalid polling interval or stop grace period\");\n const registryPath = path.resolve(options.registry);\n // `warlock dev` can evaluate this module more than once in one process. A second supervisor over\n // the same registry would find its own process holding the lock, so reuse the live one.\n const sameProcess = sameProcessSupervisors();\n const live = sameProcess.get(registryPath);\n if (live && live.owner === options.owner) return live.api;\n const observationMs =\n options.observationTimeoutMs ?? defaultObservationTimeoutMs(process.platform);\n if (!Number.isSafeInteger(observationMs) || observationMs < 100)\n throw new Error(\"Invalid observationTimeoutMs: expected an integer of at least 100\");\n // One helper per supervisor, created on first use and closed by stopAll().\n let helper: WindowsProcessHelper | undefined;\n function observe(): Observation {\n if (process.platform === \"win32\") helper ??= createWindowsHelper({ timeoutMs: observationMs });\n return { timeoutMs: observationMs, helper };\n }\n /** Polling tolerates a snapshot up to one interval old; signals never do. */\n function polling(): Observation {\n return { ...observe(), maxAgeMs: pollMs };\n }\n /**\n * Registry lease checks read identities too. Off Linux they go through the shared\n * helper, and a transient failure (an exiting process reports no creation time) is\n * retried instead of failing the whole operation.\n */\n async function lease(pid: number) {\n for (let attempt = 1; ; attempt++) {\n try {\n return await identity(pid, false, undefined, observe());\n } catch (error) {\n if (process.platform === \"linux\" || attempt >= 3) throw error;\n await delay(200);\n }\n }\n }\n const registry = new Registry(registryPath, options.owner, lease);\n const entries = new Map<number, RegistryEntry>();\n const active = new Map<number, Active>();\n let ready: Promise<void> | undefined;\n let closing = false;\n let shutdown: Promise<void> | undefined;\n // Serialize public operations, including shutdown, so a gated spawn cannot escape stopAll.\n let queue: Promise<unknown> = Promise.resolve();\n function serial<T>(operation: () => Promise<T>): Promise<T> {\n const next = queue.then(operation);\n queue = next.catch(() => undefined);\n return next;\n }\n async function open(): Promise<void> {\n supported(process.platform);\n if (closing) throw new Error(\"Supervisor has shut down\");\n ready ??= registry.open().then((saved) => {\n for (const entry of saved) {\n delete entry.cgroup;\n entries.set(entry.pid, entry);\n }\n });\n await ready;\n }\n const save = () => registry.save([...entries.values()]);\n\n async function signal(entry: RegistryEntry, value: NodeJS.Signals): Promise<void> {\n if (!(await owns(entry, observe()))) throw new ProcessNotOwnedError(entry.pid);\n if (process.platform !== \"linux\" && value === \"SIGCONT\") {\n const proof = await guardianProof(entry.pid, entry.token, entry.token, observationMs);\n if (!proof || proof.token !== entry.token || proof.gated)\n throw new ProcessNotOwnedError(entry.pid);\n return;\n }\n if (process.platform === \"win32\") {\n try {\n await executeCommand(taskkillCommand(entry.pid));\n } catch (error) {\n if (await owns(entry, observe())) throw error;\n }\n return;\n }\n // Negative PID targets only the session/group established for this child.\n // Recheck for every signal, including escalation; never match a command line.\n try {\n process.kill(-entry.pid, value);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ESRCH\") throw error;\n }\n }\n /**\n * A process that is exiting can still be listed for a moment after its guardian\n * (and so its token) is gone. Read fresh a few times; only a process that has\n * disappeared counts as gone, and a live one keeps its not-owned failure.\n */\n async function gone(pid: number): Promise<boolean> {\n for (let attempt = 0; attempt < 5; attempt++) {\n if (!(await identity(pid, false, undefined, observe()))) return true;\n await delay(100);\n }\n return false;\n }\n /**\n * Right after SIGCONT the launcher is replacing itself with the workload\n * (exec). For that instant the kernel reports an empty memory map and\n * environment, so a live, owned process momentarily fails verification. A\n * handle returned by launch() must always be stoppable, so wait that window\n * out; a process that stays unverified is still refused.\n */\n async function ownsSettled(entry: RegistryEntry): Promise<boolean> {\n for (let attempt = 0; attempt < 25; attempt++) {\n if (await owns(entry, observe())) return true;\n await delay(20);\n }\n return false;\n }\n async function stopEntry(\n entry: RegistryEntry,\n reason: ProcessExit[\"reason\"] = \"stopped\",\n ): Promise<void> {\n const tracked = active.get(entry.pid);\n let running: Active;\n if (!tracked) {\n if (!(await owns(entry, observe()))) throw new ProcessNotOwnedError(entry.pid);\n entry.cgroup = await recoveredCgroup(entry.pid, entry.token);\n running = track(entry);\n } else running = tracked;\n if (running.finished) return running.finish(null, null);\n if (running.stopping) return running.stopping;\n const stopping = (async () => {\n if (!(await ownsSettled(entry))) throw new ProcessNotOwnedError(entry.pid);\n running.reason ??= reason;\n await signal(entry, \"SIGTERM\");\n const deadline = Date.now() + graceMs;\n while (await owns(entry, observe())) {\n if (Date.now() >= deadline) {\n await signal(entry, \"SIGKILL\");\n break;\n }\n await delay(20);\n }\n const killedDeadline = Date.now() + 5000;\n while (await owns(entry, observe())) {\n if (Date.now() >= killedDeadline)\n throw new Error(`Process ${entry.pid} did not exit after SIGKILL`);\n await delay(20);\n }\n await running.finish(null, null);\n })();\n running.stopping = stopping;\n try {\n await stopping;\n } catch (error) {\n running.stopping = undefined;\n // The leader may exit between identity verification and a signal. A\n // missing identity is harmless for a tracked handle; a live mismatch is\n // still an ownership failure and must never receive another signal.\n if (error instanceof ProcessNotOwnedError && (await gone(entry.pid))) {\n await running.finish(null, null);\n return;\n }\n throw error;\n }\n }\n\n function track(\n entry: RegistryEntry,\n streams?: Pick<ProcessHandle, \"stdin\" | \"stdout\" | \"stderr\">,\n ): Active {\n let resolveExit: (exit: ProcessExit) => void = () => undefined;\n let rejectExit: (error: unknown) => void = () => undefined;\n const exited = new Promise<ProcessExit>((resolve, reject) => {\n resolveExit = resolve;\n rejectExit = reject;\n });\n // A rejected persistence operation is still observable through handle.exited.\n void exited.catch(() => undefined);\n const stdout = streams?.stdout ?? new PassThrough();\n const stderr = streams?.stderr ?? new PassThrough();\n const stdin = streams?.stdin ?? new PassThrough();\n let finishing: Promise<void> | undefined;\n const running: Active = {\n entry,\n finished: false,\n adopted: !streams,\n fail: (error) => rejectExit(error),\n handle: {\n pid: entry.pid,\n stdout,\n stderr,\n stdin,\n exited,\n stop: () =>\n serial(async () => {\n if (!running.finished) await stopEntry(entry);\n }),\n },\n finish(code, sig) {\n finishing ??= (async () => {\n running.finished = true;\n clearInterval(running.timer);\n if (entry.cgroup) {\n const memory = await cgroupMemory(entry.cgroup);\n entry.peakMemoryBytes = Math.max(entry.peakMemoryBytes, memory.peak);\n if (memory.oom) running.reason = \"memory-cap\";\n await cleanCgroup(entry.cgroup);\n }\n active.delete(entry.pid);\n entries.delete(entry.pid);\n try {\n await save();\n resolveExit({\n reason: running.reason ?? \"exit\",\n code,\n signal: sig,\n peakMemoryBytes: entry.peakMemoryBytes,\n });\n } catch (error) {\n rejectExit(error);\n throw error;\n }\n if (!streams) {\n (stdout as PassThrough).end();\n (stderr as PassThrough).end();\n stdin.end();\n }\n })();\n return finishing;\n },\n };\n active.set(entry.pid, running);\n return running;\n }\n\n function monitor(running: Active): void {\n if (running.finished) return;\n let sampling = false;\n const sample = async () => {\n if (sampling || running.finished) return;\n sampling = true;\n try {\n const entry = running.entry;\n let current = await identity(entry.pid, true, entry.token, polling());\n const matches = (value: typeof current) =>\n value?.start === entry.start && value.token === entry.token && value.group === entry.pid;\n // A snapshot taken while the process was exiting can still list it after\n // its guardian is gone. Before calling a mismatch a failure, read fresh\n // (no snapshot) a few times; a process that vanished simply exited.\n for (let attempt = 0; current && !matches(current) && attempt < 3; attempt++) {\n if (running.finished) return;\n await delay(50);\n current = await identity(entry.pid, true, entry.token, observe());\n }\n if (running.finished) return;\n if (\n current?.start !== entry.start ||\n current.token !== entry.token ||\n current.group !== entry.pid\n ) {\n if (!current) {\n if (running.adopted) await running.finish(null, null);\n } else {\n // A live child that changes its environment or group can no longer\n // be supervised safely. Preserve the entry and surface the failure.\n throw new ProcessNotOwnedError(entry.pid);\n }\n return;\n }\n entry.peakMemoryBytes = Math.max(entry.peakMemoryBytes, current.rss);\n if (entry.cgroup) {\n const memory = await cgroupMemory(entry.cgroup);\n if (running.finished) return;\n entry.peakMemoryBytes = Math.max(entry.peakMemoryBytes, memory.peak);\n if (memory.oom) running.reason = \"memory-cap\";\n }\n if (entry.limits.memoryBytes && entry.peakMemoryBytes > entry.limits.memoryBytes)\n await stopEntry(entry, \"memory-cap\");\n else if (entry.limits.timeoutMs && Date.now() - entry.startedAt >= entry.limits.timeoutMs)\n await stopEntry(entry, \"timeout\");\n } finally {\n sampling = false;\n }\n };\n running.timer = setInterval(() => {\n void sample().catch((error: unknown) => {\n // Never signal on an observation error. Surface it to the caller and keep the registry.\n clearInterval(running.timer);\n if (!running.finished) running.fail(error);\n });\n }, pollMs);\n running.timer.unref();\n }\n\n async function launch(\n input: SpawnOptions & { columns?: number; rows?: number },\n terminal: boolean,\n ): Promise<ProcessHandle | PtyHandle> {\n await open();\n if ([...entries.keys()].some((pid) => !active.has(pid)))\n throw new Error(\"Call recover() before spawning with an existing registry\");\n if (\n typeof input.command !== \"string\" ||\n !input.command ||\n typeof input.kind !== \"string\" ||\n !input.kind\n )\n throw new Error(\"kind and command are required\");\n validateFilter({ labels: input.labels });\n if (\n terminal &&\n [input.columns ?? 80, input.rows ?? 24].some(\n (size) => !Number.isSafeInteger(size) || size <= 0,\n )\n )\n throw new Error(\"Terminal dimensions must be positive safe integers\");\n const limits = { ...options.defaults, ...input.limits };\n validateLimits(limits);\n const token = randomBytes(32).toString(\"hex\");\n const {\n file: executable,\n args,\n env,\n } = launchCommand(\n process.platform,\n process.execPath,\n input.command,\n input.args ?? [],\n limits,\n { ...process.env, ...input.env },\n token,\n );\n let pid: number;\n let streams: Pick<ProcessHandle, \"stdin\" | \"stdout\" | \"stderr\">;\n let terminalProcess: Pty | undefined;\n let exit: { code: number | null; signal: string | null } | undefined;\n let spawnError: Error | undefined;\n let running: Active | undefined;\n const onExit = (code: number | null, sig: string | null) => {\n exit = { code, signal: sig };\n if (running) void running.finish(code, sig).catch(() => undefined);\n };\n if (terminal) {\n // Optional peer loaded only here. Structural types follow node-pty's official typings.\n const peer = \"node-pty\";\n const pty = (await import(peer)) as PtyModule;\n terminalProcess = pty.spawn(executable, args, {\n cwd: input.cwd,\n env: Object.fromEntries(\n Object.entries(env).filter((pair): pair is [string, string] => pair[1] !== undefined),\n ),\n cols: input.columns ?? 80,\n rows: input.rows ?? 24,\n name: \"xterm-256color\",\n });\n pid = terminalProcess.pid;\n const output = new PassThrough();\n const errors = new PassThrough();\n const instance = terminalProcess;\n const dataSubscription = instance.onData((data) => output.write(data));\n const inputStream = new Writable({\n write(chunk: Buffer, _encoding, callback) {\n instance.write(chunk.toString());\n callback();\n },\n });\n const exitSubscription = instance.onExit((event) => {\n dataSubscription.dispose();\n exitSubscription.dispose();\n output.end();\n errors.end();\n inputStream.end();\n onExit(event.exitCode, event.signal ? String(event.signal) : null);\n });\n streams = { stdout: output, stderr: errors, stdin: inputStream };\n } else {\n const child = spawnChild(executable, args, {\n cwd: input.cwd,\n env,\n detached: process.platform !== \"win32\",\n windowsHide: true,\n stdio: \"pipe\",\n });\n child.on(\"error\", (error) => {\n spawnError = error;\n });\n // Finish on leader exit so cgroup cleanup can stop remaining members;\n // waiting for close could deadlock on a descendant holding a pipe open.\n child.on(\"exit\", onExit);\n if (!child.pid) throw new Error(\"Could not start process\");\n pid = child.pid;\n streams = { stdout: child.stdout, stderr: child.stderr, stdin: child.stdin };\n }\n let entry: RegistryEntry | undefined;\n try {\n const deadline = Date.now() + 5000;\n // Off Linux an identity read costs a helper query, so poll the guardian's\n // pipe (cheap) until it reports the gate, and read the identity once.\n const portable = process.platform !== \"linux\";\n const gate = async () => {\n if (portable) {\n const proof = await guardianProof(pid, undefined, token, observationMs);\n if (!proof?.gated) return undefined;\n }\n return identity(pid, true, token, observe());\n };\n let current = await gate();\n while (!current?.state.startsWith(\"T\") || current.token !== token) {\n if (spawnError) throw spawnError;\n if (exit || Date.now() >= deadline)\n throw new Error(\"Child failed to reach the resource setup gate\");\n await delay(10);\n current = await gate();\n }\n if (current.group !== pid) throw new Error(\"Child did not create an isolated process group\");\n entry = {\n pid,\n owner: options.owner,\n type: input.kind,\n command: input.command,\n args: [...(input.args ?? [])],\n labels: { ...input.labels },\n startedAt: Date.now(),\n limits,\n enforcement: process.platform === \"win32\" ? \"rss-polling\" : \"rlimit-polling\",\n peakMemoryBytes: current.rss,\n token,\n start: current.start,\n gated: true,\n };\n entry.cgroup = await attachCgroup(pid, token, limits, options.cgroupRoot);\n if (entry.cgroup) entry.enforcement = \"cgroup-v2\";\n entries.set(pid, entry);\n await save();\n running = track(entry, streams);\n await signal(entry, \"SIGCONT\");\n delete entry.gated;\n await save();\n monitor(running);\n if (terminalProcess) {\n const instance = terminalProcess;\n return {\n ...running.handle,\n write: (data: string) => instance.write(data),\n resize: (columns: number, rows: number) => instance.resize(columns, rows),\n };\n }\n return running.handle;\n } catch (error) {\n // This PID was created by this call. Kill only after its random token is verified.\n const current = await identity(pid, true, token, observe());\n if (current?.token === token) {\n const failed = { pid, token, start: current.start };\n if (await owns(failed, observe())) {\n try {\n if (process.platform === \"win32\") await executeCommand(taskkillCommand(pid));\n else process.kill(-pid, \"SIGKILL\");\n } catch {\n /* Already exited. */\n }\n }\n }\n if (entry && !running) {\n entries.delete(pid);\n await save();\n }\n if (entry?.cgroup) await cleanCgroup(entry.cgroup);\n throw error;\n }\n }\n\n const api: ProcessSupervisor = {\n spawn: (input) => serial(() => launch(input, false)),\n spawnPty: (input) => serial(async () => (await launch(input, true)) as PtyHandle),\n list: (filter = {}) =>\n serial(async () => {\n validateFilter(filter);\n await open();\n return [...entries.values()].filter((entry) => matches(entry, filter)).map(info);\n }),\n stop: (filter = {}) =>\n serial(async () => {\n validateFilter(filter);\n await open();\n for (const entry of [...entries.values()].filter((entry) => matches(entry, filter)))\n await stopEntry(entry);\n }),\n stopPid: (pid) =>\n serial(async () => {\n await open();\n const entry = entries.get(pid);\n if (!entry) throw new ProcessNotOwnedError(pid);\n await stopEntry(entry);\n }),\n recover: (recovery = {}) =>\n serial(async () => {\n await open();\n const result: RecoveryResult = { adopted: [], stopped: [], cleared: [] };\n for (const entry of [...entries.values()]) {\n if (active.has(entry.pid)) continue;\n if (!(await owns(entry, observe()))) {\n entries.delete(entry.pid);\n result.cleared.push(entry.pid);\n continue;\n }\n // Never trust a persisted filesystem path for cgroup I/O after a restart.\n entry.cgroup = await recoveredCgroup(entry.pid, entry.token);\n entry.enforcement = entry.cgroup\n ? \"cgroup-v2\"\n : process.platform === \"win32\"\n ? \"rss-polling\"\n : \"rlimit-polling\";\n const keep = await recovery.keep?.(info(entry));\n if (keep) {\n const running = track(entry);\n monitor(running);\n if (entry.gated) {\n await signal(entry, \"SIGCONT\");\n delete entry.gated;\n }\n result.adopted.push(entry.pid);\n } else {\n await stopEntry(entry);\n result.stopped.push(entry.pid);\n }\n }\n await save();\n return result;\n }),\n stopAll() {\n shutdown ??= serial(async () => {\n await open();\n closing = true;\n try {\n const errors: unknown[] = [];\n for (const entry of [...entries.values()]) {\n try {\n if (await owns(entry, observe())) await stopEntry(entry);\n else {\n const running = active.get(entry.pid);\n if (running) await running.finish(null, null);\n else entries.delete(entry.pid);\n }\n } catch (error) {\n errors.push(error);\n }\n }\n await save();\n if (errors.length)\n throw new AggregateError(errors, \"Some owned processes could not be stopped\");\n } finally {\n await helper?.close();\n await registry.close();\n }\n });\n return shutdown;\n },\n };\n const stopAll = api.stopAll;\n api.stopAll = () => {\n const stopping = stopAll();\n const forget = () => {\n if (sameProcess.get(registryPath)?.api === api) sameProcess.delete(registryPath);\n };\n stopping.then(forget, forget);\n return stopping;\n };\n sameProcess.set(registryPath, { owner: options.owner, api });\n return api;\n}\n\nconst SUPERVISORS = Symbol.for(\"@warlock.js/process.supervisors\");\n\n/** Live supervisors of this process by registry path; shared by every copy of this module. */\nfunction sameProcessSupervisors(): Map<string, { owner: string; api: ProcessSupervisor }> {\n const holder = globalThis as unknown as Record<symbol, Map<string, any> | undefined>;\n return (holder[SUPERVISORS] ??= new Map());\n}\n"],"mappings":";;;;;;;;;;;;;AAkEA,SAAS,KAAK,OAAmC;CAC/C,MAAM,EAAE,OAAO,QAAQ,OAAO,QAAQ,QAAQ,SAAS,OAAO,QAAQ,GAAG,YAAY;CACrF,OAAO,gBAAgB,OAAO;AAChC;AACA,SAAS,eAAe,QAA6B;CACnD,IACE,CAAC,UACD,OAAO,WAAW,YAClB,MAAM,QAAQ,MAAM,KACpB,OAAO,KAAK,MAAM,CAAC,CAAC,MAAM,QAAQ,QAAQ,QAAQ,GAElD,MAAM,IAAI,MAAM,kCAAkC;CACpD,IACE,OAAO,WAAW,WACjB,OAAO,WAAW,QACjB,OAAO,OAAO,WAAW,YACzB,MAAM,QAAQ,OAAO,MAAM,KAC3B,CAAC,OAAO,OAAO,OAAO,MAAM,CAAC,CAAC,OAAO,UAAU,OAAO,UAAU,QAAQ,IAE1E,MAAM,IAAI,MAAM,uCAAuC;AAC3D;AACA,SAAS,QAAQ,OAAsB,QAAgC;CACrE,OAAO,OAAO,QAAQ,OAAO,UAAU,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,WAAW,MAAM,OAAO,SAAS,KAAK;AAChG;AAEA,SAAgB,WAAW,SAA+C;CACxE,KAAK,MAAM,UAAU,CAAC,SAAS,UAAU,GACvC,IAAI,CAAC,WAAW,OAAO,QAAQ,YAAY,YAAY,CAAC,QAAQ,OAAO,CAAC,KAAK,GAC3E,MAAM,IAAI,UAAU,qCAAqC,OAAO,2BAA2B;CAG/F,eAAe,QAAQ,YAAY,CAAC,CAAC;CAErC,UAAU;EAAE,GAAG;EAAS,UAAU,EAAE,GAAG,QAAQ,SAAS;CAAE;CAC1D,MAAM,SAAS,QAAQ,kBAAkB,sBAAsB,QAAQ,QAAQ;CAC/E,MAAM,UAAU,QAAQ,eAAe;CACvC,IAAI,CAAC,OAAO,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MAAM,GAAG;MAC/B;KACF,SAAS,OAAO;MACd,OAAO,KAAK,KAAK;KACnB;KAEF,MAAM,KAAK;KACX,IAAI,OAAO,QACT,MAAM,IAAI,eAAe,QAAQ,2CAA2C;IAChF,UAAU;KACR,MAAM,QAAQ,MAAM;KACpB,MAAM,SAAS,MAAM;IACvB;GACF,CAAC;GACD,OAAO;EACT;CACF;CACA,MAAM,UAAU,IAAI;CACpB,IAAI,gBAAgB;EAClB,MAAM,WAAW,QAAQ;EACzB,MAAM,eAAe;GACnB,IAAI,YAAY,IAAI,YAAY,CAAC,EAAE,QAAQ,KAAK,YAAY,OAAO,YAAY;EACjF;EACA,SAAS,KAAK,QAAQ,MAAM;EAC5B,OAAO;CACT;CACA,YAAY,IAAI,cAAc;EAAE,OAAO,QAAQ;EAAO;CAAI,CAAC;CAC3D,OAAO;AACT;AAEA,MAAM,cAAc,OAAO,IAAI,iCAAiC;;AAGhE,SAAS,yBAAiF;CACxF,MAAM,SAAS;CACf,OAAQ,OAAO,iCAAiB,IAAI,IAAI;AAC1C"}
|
package/esm/types.d.mts
CHANGED
|
@@ -13,7 +13,17 @@ export type SupervisorOptions = {
|
|
|
13
13
|
/** Absolute or cwd-relative JSON file. One supervisor per registry. */
|
|
14
14
|
registry: string;
|
|
15
15
|
defaults?: ProcessLimits;
|
|
16
|
+
/**
|
|
17
|
+
* How often running processes are sampled. Defaults per platform: 100 on Linux
|
|
18
|
+
* (reads /proc), 500 on macOS and 1500 on Windows (each sample queries the OS).
|
|
19
|
+
*/
|
|
16
20
|
pollIntervalMs?: number;
|
|
21
|
+
/**
|
|
22
|
+
* Longest wait, in milliseconds, for the ownership check off Linux (the guardian's
|
|
23
|
+
* reply and, on Windows, the process helper's answer). Defaults to 2000 on Linux and
|
|
24
|
+
* 15000 on Windows and macOS. Raise it on a heavily loaded machine.
|
|
25
|
+
*/
|
|
26
|
+
observationTimeoutMs?: number;
|
|
17
27
|
stopGraceMs?: number;
|
|
18
28
|
/** Linux delegated cgroup v2 directory; defaults to this process's cgroup. */
|
|
19
29
|
cgroupRoot?: string;
|
package/esm/types.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../packages/process/src/types.ts"],"mappings":";;YAEY;EACV;EACA;;EAEA;;EAEA;;YAEU;EACV;;EAEA;EACA,WAAW;
|
|
1
|
+
{"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../packages/process/src/types.ts"],"mappings":";;YAEY;EACV;EACA;;EAEA;;EAEA;;YAEU;EACV;;EAEA;EACA,WAAW;;;;;EAKX;;;;;;EAMA;EACA;;EAEA;;YAEU;;EAEV;EACA;EACA;EACA;EACA,MAAM,OAAO;EACb,SAAS;EACT,SAAS;;YAEC;EAAkB,SAAS;;YAC3B;EACV;EACA;EACA;EACA;;YAEU;EACV;EACA;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA,QAAQ;EACR;EACA;;YAEU;EACV;EACA,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,QAAQ,QAAQ;EAChB,QAAQ;;YAEE,YAAY;EACtB,MAAM;EACN,OAAO,iBAAiB;;YAEd;EAAmB;EAAmB;EAAmB;;YACzD;EACV,MAAM,SAAS,eAAe,QAAQ;EACtC,SAAS,SAAS;IAAiB;IAAkB;MAAkB,QAAQ;EAC/E,KAAK,SAAS,gBAAgB,QAAQ;EACtC,KAAK,SAAS,gBAAgB;EAC9B,QAAQ,cAAc;EACtB,QAAQ;IACN,QAAQ,OAAO,0BAA0B;MACvC,QAAQ;EACZ,WAAW"}
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import { windowsRows } from "./platform.mjs";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
|
|
4
|
+
//#region ../../packages/process/src/windows-helper.ts
|
|
5
|
+
/**
|
|
6
|
+
* One long-lived PowerShell per supervisor answers batched process queries over
|
|
7
|
+
* stdin/stdout, one JSON object per line:
|
|
8
|
+
*
|
|
9
|
+
* request {"id":1,"pids":[42,43],"all":false}
|
|
10
|
+
* response {"id":1,"rows":[{"pid":42,"parent":4,"start":"638...","rss":1024}]}
|
|
11
|
+
* failure {"id":1,"error":"message"}
|
|
12
|
+
*
|
|
13
|
+
* `all: true` returns the whole process table (needed to sum a process tree).
|
|
14
|
+
* Starting PowerShell costs about a second on Windows; paying that once instead
|
|
15
|
+
* of twice per observation is what keeps a busy machine responsive.
|
|
16
|
+
*/
|
|
17
|
+
const helperScript = [
|
|
18
|
+
"$ErrorActionPreference = 'Stop'",
|
|
19
|
+
"[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)",
|
|
20
|
+
"$reader = [Console]::In",
|
|
21
|
+
"while ($null -ne ($line = $reader.ReadLine())) {",
|
|
22
|
+
" $id = 0",
|
|
23
|
+
" try {",
|
|
24
|
+
" $request = $line | ConvertFrom-Json",
|
|
25
|
+
" $id = [int]$request.id",
|
|
26
|
+
" $wanted = @($request.pids | ForEach-Object { [int]$_ })",
|
|
27
|
+
" if ($request.all) { $found = @(Get-CimInstance Win32_Process) }",
|
|
28
|
+
" elseif ($wanted.Count -eq 0) { $found = @() }",
|
|
29
|
+
" else { $found = @(Get-CimInstance Win32_Process -Filter (($wanted | ForEach-Object { 'ProcessId=' + $_ }) -join ' OR ')) }",
|
|
30
|
+
" $rows = @($found | ForEach-Object {",
|
|
31
|
+
" if ($wanted -contains [int]$_.ProcessId -and $null -eq $_.CreationDate) { throw 'Cannot read process creation time' }",
|
|
32
|
+
" if ($null -ne $_.CreationDate) {",
|
|
33
|
+
" [pscustomobject]@{ pid = [int]$_.ProcessId; parent = [int]$_.ParentProcessId; start = $_.CreationDate.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture); rss = [double]$_.WorkingSetSize }",
|
|
34
|
+
" }",
|
|
35
|
+
" })",
|
|
36
|
+
" $reply = ConvertTo-Json -InputObject @{ id = $id; rows = $rows } -Compress -Depth 4",
|
|
37
|
+
" } catch {",
|
|
38
|
+
" $reply = ConvertTo-Json -InputObject @{ id = $id; error = [string]$_.Exception.Message } -Compress",
|
|
39
|
+
" }",
|
|
40
|
+
" [Console]::Out.WriteLine($reply)",
|
|
41
|
+
" [Console]::Out.Flush()",
|
|
42
|
+
"}"
|
|
43
|
+
].join("\n");
|
|
44
|
+
function defaultHelperSpawn(file, args) {
|
|
45
|
+
const child = spawn(file, args, {
|
|
46
|
+
stdio: [
|
|
47
|
+
"pipe",
|
|
48
|
+
"pipe",
|
|
49
|
+
"ignore"
|
|
50
|
+
],
|
|
51
|
+
windowsHide: true
|
|
52
|
+
});
|
|
53
|
+
child.unref();
|
|
54
|
+
child.stdin.unref?.();
|
|
55
|
+
child.stdout.unref?.();
|
|
56
|
+
return child;
|
|
57
|
+
}
|
|
58
|
+
function helperArguments() {
|
|
59
|
+
return [
|
|
60
|
+
"-NoLogo",
|
|
61
|
+
"-NoProfile",
|
|
62
|
+
"-NonInteractive",
|
|
63
|
+
"-EncodedCommand",
|
|
64
|
+
Buffer.from(helperScript, "utf16le").toString("base64")
|
|
65
|
+
];
|
|
66
|
+
}
|
|
67
|
+
var WindowsProcessHelper = class {
|
|
68
|
+
child;
|
|
69
|
+
buffer = "";
|
|
70
|
+
flight;
|
|
71
|
+
batch;
|
|
72
|
+
scheduled = false;
|
|
73
|
+
nextId = 1;
|
|
74
|
+
closed = false;
|
|
75
|
+
last;
|
|
76
|
+
/** Number of PowerShell processes started; a restart shows up here. */
|
|
77
|
+
starts = 0;
|
|
78
|
+
/** Number of requests written to the helper. */
|
|
79
|
+
requests = 0;
|
|
80
|
+
spawn;
|
|
81
|
+
timeoutMs;
|
|
82
|
+
now;
|
|
83
|
+
constructor(options = {}) {
|
|
84
|
+
this.spawn = options.spawn ?? defaultHelperSpawn;
|
|
85
|
+
this.timeoutMs = options.timeoutMs ?? 15e3;
|
|
86
|
+
this.now = options.now ?? Date.now;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Rows for the given PIDs, or the whole table with `all`. Calls made while a
|
|
90
|
+
* request is in flight share the next request, so N concurrent observations
|
|
91
|
+
* cost one query. `maxAgeMs` accepts a snapshot at most that old.
|
|
92
|
+
*/
|
|
93
|
+
query(pids, all = false, maxAgeMs = 0) {
|
|
94
|
+
if (this.closed) return Promise.reject(/* @__PURE__ */ new Error("Windows process helper is closed"));
|
|
95
|
+
const cached = this.last;
|
|
96
|
+
if (maxAgeMs > 0 && cached && this.now() - cached.at <= maxAgeMs && (cached.all || !all && pids.every((pid) => cached.pids.has(pid)))) return Promise.resolve(cached.rows);
|
|
97
|
+
return new Promise((resolve, reject) => {
|
|
98
|
+
const batch = this.batch ??= {
|
|
99
|
+
pids: /* @__PURE__ */ new Set(),
|
|
100
|
+
all: false,
|
|
101
|
+
waiters: []
|
|
102
|
+
};
|
|
103
|
+
for (const pid of pids) batch.pids.add(pid);
|
|
104
|
+
batch.all ||= all;
|
|
105
|
+
batch.waiters.push({
|
|
106
|
+
resolve,
|
|
107
|
+
reject,
|
|
108
|
+
pids
|
|
109
|
+
});
|
|
110
|
+
this.schedule();
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/** Stops the helper; pending queries reject. Safe to call twice. */
|
|
114
|
+
async close() {
|
|
115
|
+
this.closed = true;
|
|
116
|
+
const error = /* @__PURE__ */ new Error("Windows process helper is closed");
|
|
117
|
+
this.failAll(error);
|
|
118
|
+
this.discard();
|
|
119
|
+
}
|
|
120
|
+
schedule() {
|
|
121
|
+
if (this.flight || this.scheduled) return;
|
|
122
|
+
this.scheduled = true;
|
|
123
|
+
setImmediate(() => {
|
|
124
|
+
this.scheduled = false;
|
|
125
|
+
this.dispatch();
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
dispatch() {
|
|
129
|
+
if (this.flight || !this.batch) return;
|
|
130
|
+
const batch = this.batch;
|
|
131
|
+
this.batch = void 0;
|
|
132
|
+
this.flight = {
|
|
133
|
+
id: this.nextId++,
|
|
134
|
+
pids: [...batch.pids],
|
|
135
|
+
all: batch.all,
|
|
136
|
+
waiters: batch.waiters,
|
|
137
|
+
attempts: 0
|
|
138
|
+
};
|
|
139
|
+
this.send(this.flight);
|
|
140
|
+
}
|
|
141
|
+
send(flight) {
|
|
142
|
+
flight.attempts += 1;
|
|
143
|
+
try {
|
|
144
|
+
const child = this.ensure();
|
|
145
|
+
this.requests += 1;
|
|
146
|
+
child.stdin.write(JSON.stringify({
|
|
147
|
+
id: flight.id,
|
|
148
|
+
pids: flight.pids,
|
|
149
|
+
all: flight.all
|
|
150
|
+
}) + "\n");
|
|
151
|
+
} catch (error) {
|
|
152
|
+
this.retryOrFail(flight, error);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
clearTimeout(flight.timer);
|
|
156
|
+
flight.timer = setTimeout(() => {
|
|
157
|
+
this.discard();
|
|
158
|
+
this.retryOrFail(flight, /* @__PURE__ */ new Error(`Windows process helper did not answer within ${this.timeoutMs} ms; raise the observationTimeoutMs supervisor option`));
|
|
159
|
+
}, this.timeoutMs);
|
|
160
|
+
flight.timer.unref?.();
|
|
161
|
+
}
|
|
162
|
+
ensure() {
|
|
163
|
+
if (this.child) return this.child;
|
|
164
|
+
const child = this.spawn("powershell.exe", helperArguments());
|
|
165
|
+
this.starts += 1;
|
|
166
|
+
this.child = child;
|
|
167
|
+
this.buffer = "";
|
|
168
|
+
child.stdout.setEncoding?.("utf8");
|
|
169
|
+
child.stdout.on("data", (chunk) => {
|
|
170
|
+
if (this.child !== child) return;
|
|
171
|
+
this.buffer += chunk.toString();
|
|
172
|
+
let newline = this.buffer.indexOf("\n");
|
|
173
|
+
while (newline >= 0) {
|
|
174
|
+
const line = this.buffer.slice(0, newline).replace(/^/, "").trim();
|
|
175
|
+
this.buffer = this.buffer.slice(newline + 1);
|
|
176
|
+
if (line) this.receive(line);
|
|
177
|
+
newline = this.buffer.indexOf("\n");
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
child.stdin.on("error", () => void 0);
|
|
181
|
+
const died = () => {
|
|
182
|
+
if (this.child !== child) return;
|
|
183
|
+
this.child = void 0;
|
|
184
|
+
const flight = this.flight;
|
|
185
|
+
if (flight) this.retryOrFail(flight, /* @__PURE__ */ new Error("Windows process helper exited unexpectedly"));
|
|
186
|
+
};
|
|
187
|
+
child.on("exit", died);
|
|
188
|
+
child.on("error", died);
|
|
189
|
+
return child;
|
|
190
|
+
}
|
|
191
|
+
receive(line) {
|
|
192
|
+
const flight = this.flight;
|
|
193
|
+
if (!flight) return;
|
|
194
|
+
let reply;
|
|
195
|
+
try {
|
|
196
|
+
reply = JSON.parse(line);
|
|
197
|
+
} catch {
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
if (reply.id !== flight.id) return;
|
|
201
|
+
clearTimeout(flight.timer);
|
|
202
|
+
this.flight = void 0;
|
|
203
|
+
try {
|
|
204
|
+
if (typeof reply.error === "string") throw new Error(reply.error);
|
|
205
|
+
const rows = windowsRows(reply.rows);
|
|
206
|
+
this.last = {
|
|
207
|
+
at: this.now(),
|
|
208
|
+
all: flight.all,
|
|
209
|
+
pids: new Set(flight.pids),
|
|
210
|
+
rows
|
|
211
|
+
};
|
|
212
|
+
for (const waiter of flight.waiters) waiter.resolve(rows);
|
|
213
|
+
} catch (error) {
|
|
214
|
+
for (const waiter of flight.waiters) waiter.reject(error);
|
|
215
|
+
}
|
|
216
|
+
if (this.batch) this.schedule();
|
|
217
|
+
}
|
|
218
|
+
/** One automatic retry on a fresh helper; queries are read-only, so repeating is safe. */
|
|
219
|
+
retryOrFail(flight, error) {
|
|
220
|
+
clearTimeout(flight.timer);
|
|
221
|
+
if (this.closed || flight.attempts >= 2) {
|
|
222
|
+
if (this.flight === flight) this.flight = void 0;
|
|
223
|
+
for (const waiter of flight.waiters) waiter.reject(error);
|
|
224
|
+
if (this.batch && !this.closed) this.schedule();
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
this.discard();
|
|
228
|
+
this.send(flight);
|
|
229
|
+
}
|
|
230
|
+
failAll(error) {
|
|
231
|
+
const flight = this.flight;
|
|
232
|
+
this.flight = void 0;
|
|
233
|
+
clearTimeout(flight?.timer);
|
|
234
|
+
const batch = this.batch;
|
|
235
|
+
this.batch = void 0;
|
|
236
|
+
for (const waiter of [...flight?.waiters ?? [], ...batch?.waiters ?? []]) waiter.reject(error);
|
|
237
|
+
}
|
|
238
|
+
discard() {
|
|
239
|
+
const child = this.child;
|
|
240
|
+
this.child = void 0;
|
|
241
|
+
this.last = void 0;
|
|
242
|
+
if (!child) return;
|
|
243
|
+
try {
|
|
244
|
+
child.stdin.end();
|
|
245
|
+
} catch {}
|
|
246
|
+
try {
|
|
247
|
+
child.kill();
|
|
248
|
+
} catch {}
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
function createWindowsHelper(options = {}) {
|
|
252
|
+
return new WindowsProcessHelper(options);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
//#endregion
|
|
256
|
+
export { WindowsProcessHelper, createWindowsHelper, defaultHelperSpawn, helperArguments, helperScript };
|
|
257
|
+
//# sourceMappingURL=windows-helper.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"windows-helper.mjs","names":["spawnChild"],"sources":["../../../../../../../packages/process/src/windows-helper.ts"],"sourcesContent":["import { spawn as spawnChild } from \"node:child_process\";\nimport type { Readable, Writable } from \"node:stream\";\nimport { windowsRows, type Row } from \"./platform\";\n\n/**\n * One long-lived PowerShell per supervisor answers batched process queries over\n * stdin/stdout, one JSON object per line:\n *\n * request {\"id\":1,\"pids\":[42,43],\"all\":false}\n * response {\"id\":1,\"rows\":[{\"pid\":42,\"parent\":4,\"start\":\"638...\",\"rss\":1024}]}\n * failure {\"id\":1,\"error\":\"message\"}\n *\n * `all: true` returns the whole process table (needed to sum a process tree).\n * Starting PowerShell costs about a second on Windows; paying that once instead\n * of twice per observation is what keeps a busy machine responsive.\n */\nexport const helperScript = [\n \"$ErrorActionPreference = 'Stop'\",\n \"[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)\",\n \"$reader = [Console]::In\",\n \"while ($null -ne ($line = $reader.ReadLine())) {\",\n \" $id = 0\",\n \" try {\",\n \" $request = $line | ConvertFrom-Json\",\n \" $id = [int]$request.id\",\n \" $wanted = @($request.pids | ForEach-Object { [int]$_ })\",\n \" if ($request.all) { $found = @(Get-CimInstance Win32_Process) }\",\n \" elseif ($wanted.Count -eq 0) { $found = @() }\",\n \" else { $found = @(Get-CimInstance Win32_Process -Filter (($wanted | ForEach-Object { 'ProcessId=' + $_ }) -join ' OR ')) }\",\n \" $rows = @($found | ForEach-Object {\",\n \" if ($wanted -contains [int]$_.ProcessId -and $null -eq $_.CreationDate) { throw 'Cannot read process creation time' }\",\n \" if ($null -ne $_.CreationDate) {\",\n \" [pscustomobject]@{ pid = [int]$_.ProcessId; parent = [int]$_.ParentProcessId; start = $_.CreationDate.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture); rss = [double]$_.WorkingSetSize }\",\n \" }\",\n \" })\",\n \" $reply = ConvertTo-Json -InputObject @{ id = $id; rows = $rows } -Compress -Depth 4\",\n \" } catch {\",\n \" $reply = ConvertTo-Json -InputObject @{ id = $id; error = [string]$_.Exception.Message } -Compress\",\n \" }\",\n \" [Console]::Out.WriteLine($reply)\",\n \" [Console]::Out.Flush()\",\n \"}\",\n].join(\"\\n\");\n\n/** The subset of ChildProcess the helper uses; tests inject a fake. */\nexport type HelperChild = {\n pid?: number;\n stdin: Writable;\n stdout: Readable;\n on(event: \"exit\" | \"error\", listener: () => void): unknown;\n kill(): unknown;\n unref?(): void;\n};\nexport type HelperSpawn = (file: string, args: string[]) => HelperChild;\n\nexport function defaultHelperSpawn(file: string, args: string[]): HelperChild {\n const child = spawnChild(file, args, { stdio: [\"pipe\", \"pipe\", \"ignore\"], windowsHide: true });\n // The helper must never keep the host process alive; stopAll() closes it.\n child.unref();\n (child.stdin as unknown as { unref?(): void }).unref?.();\n (child.stdout as unknown as { unref?(): void }).unref?.();\n return child;\n}\n\nexport function helperArguments(): string[] {\n return [\n \"-NoLogo\",\n \"-NoProfile\",\n \"-NonInteractive\",\n \"-EncodedCommand\",\n Buffer.from(helperScript, \"utf16le\").toString(\"base64\"),\n ];\n}\n\nexport type WindowsHelperOptions = {\n spawn?: HelperSpawn;\n /** Longest wait for one response, including PowerShell's own start-up. */\n timeoutMs?: number;\n now?: () => number;\n};\n\ntype Waiter = { resolve(rows: Row[]): void; reject(error: unknown): void; pids: number[] };\ntype Batch = { pids: Set<number>; all: boolean; waiters: Waiter[] };\ntype Flight = {\n id: number;\n pids: number[];\n all: boolean;\n waiters: Waiter[];\n attempts: number;\n timer?: ReturnType<typeof setTimeout>;\n};\ntype Snapshot = { at: number; all: boolean; pids: Set<number>; rows: Row[] };\n\nexport class WindowsProcessHelper {\n private child: HelperChild | undefined;\n private buffer = \"\";\n private flight: Flight | undefined;\n private batch: Batch | undefined;\n private scheduled = false;\n private nextId = 1;\n private closed = false;\n private last: Snapshot | undefined;\n /** Number of PowerShell processes started; a restart shows up here. */\n starts = 0;\n /** Number of requests written to the helper. */\n requests = 0;\n private readonly spawn: HelperSpawn;\n private readonly timeoutMs: number;\n private readonly now: () => number;\n\n constructor(options: WindowsHelperOptions = {}) {\n this.spawn = options.spawn ?? defaultHelperSpawn;\n this.timeoutMs = options.timeoutMs ?? 15_000;\n this.now = options.now ?? Date.now;\n }\n\n /**\n * Rows for the given PIDs, or the whole table with `all`. Calls made while a\n * request is in flight share the next request, so N concurrent observations\n * cost one query. `maxAgeMs` accepts a snapshot at most that old.\n */\n query(pids: number[], all = false, maxAgeMs = 0): Promise<Row[]> {\n if (this.closed) return Promise.reject(new Error(\"Windows process helper is closed\"));\n const cached = this.last;\n if (\n maxAgeMs > 0 &&\n cached &&\n this.now() - cached.at <= maxAgeMs &&\n (cached.all || (!all && pids.every((pid) => cached.pids.has(pid))))\n )\n return Promise.resolve(cached.rows);\n return new Promise<Row[]>((resolve, reject) => {\n const batch = (this.batch ??= { pids: new Set(), all: false, waiters: [] });\n for (const pid of pids) batch.pids.add(pid);\n batch.all ||= all;\n batch.waiters.push({ resolve, reject, pids });\n this.schedule();\n });\n }\n\n /** Stops the helper; pending queries reject. Safe to call twice. */\n async close(): Promise<void> {\n this.closed = true;\n const error = new Error(\"Windows process helper is closed\");\n this.failAll(error);\n this.discard();\n }\n\n private schedule(): void {\n if (this.flight || this.scheduled) return;\n this.scheduled = true;\n // Let observations started in the same tick join one request.\n setImmediate(() => {\n this.scheduled = false;\n this.dispatch();\n });\n }\n\n private dispatch(): void {\n if (this.flight || !this.batch) return;\n const batch = this.batch;\n this.batch = undefined;\n this.flight = {\n id: this.nextId++,\n pids: [...batch.pids],\n all: batch.all,\n waiters: batch.waiters,\n attempts: 0,\n };\n this.send(this.flight);\n }\n\n private send(flight: Flight): void {\n flight.attempts += 1;\n try {\n const child = this.ensure();\n this.requests += 1;\n child.stdin.write(\n JSON.stringify({ id: flight.id, pids: flight.pids, all: flight.all }) + \"\\n\",\n );\n } catch (error) {\n this.retryOrFail(flight, error);\n return;\n }\n clearTimeout(flight.timer);\n flight.timer = setTimeout(() => {\n // A wedged helper is replaced, never trusted for the next request.\n this.discard();\n this.retryOrFail(\n flight,\n new Error(\n `Windows process helper did not answer within ${this.timeoutMs} ms; raise the observationTimeoutMs supervisor option`,\n ),\n );\n }, this.timeoutMs);\n flight.timer.unref?.();\n }\n\n private ensure(): HelperChild {\n if (this.child) return this.child;\n const child = this.spawn(\"powershell.exe\", helperArguments());\n this.starts += 1;\n this.child = child;\n this.buffer = \"\";\n child.stdout.setEncoding?.(\"utf8\");\n child.stdout.on(\"data\", (chunk: string | Buffer) => {\n if (this.child !== child) return;\n this.buffer += chunk.toString();\n let newline = this.buffer.indexOf(\"\\n\");\n while (newline >= 0) {\n const line = this.buffer.slice(0, newline).replace(/^/, \"\").trim();\n this.buffer = this.buffer.slice(newline + 1);\n if (line) this.receive(line);\n newline = this.buffer.indexOf(\"\\n\");\n }\n });\n child.stdin.on(\"error\", () => undefined);\n const died = () => {\n if (this.child !== child) return;\n this.child = undefined;\n const flight = this.flight;\n if (flight) this.retryOrFail(flight, new Error(\"Windows process helper exited unexpectedly\"));\n };\n child.on(\"exit\", died);\n child.on(\"error\", died);\n return child;\n }\n\n private receive(line: string): void {\n const flight = this.flight;\n if (!flight) return;\n let reply: { id?: unknown; rows?: unknown; error?: unknown };\n try {\n reply = JSON.parse(line) as typeof reply;\n } catch {\n return; // Banner or stray output; only well-formed replies count.\n }\n if (reply.id !== flight.id) return;\n clearTimeout(flight.timer);\n this.flight = undefined;\n try {\n if (typeof reply.error === \"string\") throw new Error(reply.error);\n const rows = windowsRows(reply.rows);\n this.last = {\n at: this.now(),\n all: flight.all,\n pids: new Set(flight.pids),\n rows,\n };\n for (const waiter of flight.waiters) waiter.resolve(rows);\n } catch (error) {\n for (const waiter of flight.waiters) waiter.reject(error);\n }\n if (this.batch) this.schedule();\n }\n\n /** One automatic retry on a fresh helper; queries are read-only, so repeating is safe. */\n private retryOrFail(flight: Flight, error: unknown): void {\n clearTimeout(flight.timer);\n if (this.closed || flight.attempts >= 2) {\n if (this.flight === flight) this.flight = undefined;\n for (const waiter of flight.waiters) waiter.reject(error);\n if (this.batch && !this.closed) this.schedule();\n return;\n }\n this.discard();\n this.send(flight);\n }\n\n private failAll(error: unknown): void {\n const flight = this.flight;\n this.flight = undefined;\n clearTimeout(flight?.timer);\n const batch = this.batch;\n this.batch = undefined;\n for (const waiter of [...(flight?.waiters ?? []), ...(batch?.waiters ?? [])])\n waiter.reject(error);\n }\n\n private discard(): void {\n const child = this.child;\n this.child = undefined;\n this.last = undefined;\n if (!child) return;\n try {\n child.stdin.end();\n } catch {\n /* Already closed. */\n }\n try {\n child.kill();\n } catch {\n /* Already gone. */\n }\n }\n}\n\nexport function createWindowsHelper(options: WindowsHelperOptions = {}): WindowsProcessHelper {\n return new WindowsProcessHelper(options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,MAAa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minal output; stderr is empty. `stdin` is writable too.
|
|
|
102
102
|
`RLIMIT_RSS`; fallback RSS accounting covers the leader and can overshoot.
|
|
103
103
|
V8 reserves large address space; avoid small address-space limits.
|
|
104
104
|
- macOS reads `ps` start times with `LC_ALL=C TZ=UTC`, applies CPU/data rlimits
|
|
105
|
-
and polls tree RSS. Windows
|
|
105
|
+
and polls tree RSS. Windows reads CIM creation times through one long-lived PowerShell helper per supervisor, polls tree
|
|
106
106
|
working sets (`enforcement: "rss-polling"`) and stops verified trees with
|
|
107
107
|
`taskkill /PID <pid> /T /F`. Memory caps on both are softer than Linux cgroups.
|
|
108
108
|
- Both use a Node guardian as the handle PID. It proves the random token from
|
|
@@ -110,6 +110,10 @@ PTY stdout combines terminal output; stderr is empty. `stdin` is writable too.
|
|
|
110
110
|
until registry persistence, and survives supervisor restarts for recovery.
|
|
111
111
|
Memory includes the guardian and its descendants. No identity-helper setup
|
|
112
112
|
or custom native compilation is needed.
|
|
113
|
+
- Defaults per platform: `pollIntervalMs` 100 ms Linux, 500 macOS, 1500 Windows;
|
|
114
|
+
`observationTimeoutMs` (ownership check wait) 2 s Linux, 15 s macOS/Windows. Explicit
|
|
115
|
+
options win. Raise `observationTimeoutMs` on a loaded machine; the timeout error names it.
|
|
116
|
+
The guardian replies to resume before launching the workload.
|
|
113
117
|
- Windows needs PowerShell/CIM. `cpuSeconds` is POSIX-only and
|
|
114
118
|
`virtualMemoryBytes` Linux-only; unsupported limits fail before launch.
|
|
115
119
|
Timeouts apply everywhere. Windows always forces the PID tree immediately;
|
package/package.json
CHANGED
package/skills/SKILL.md
CHANGED
|
@@ -94,7 +94,7 @@ PTY stdout combines terminal output; stderr is empty. `stdin` is writable too.
|
|
|
94
94
|
`RLIMIT_RSS`; fallback RSS accounting covers the leader and can overshoot.
|
|
95
95
|
V8 reserves large address space; avoid small address-space limits.
|
|
96
96
|
- macOS reads `ps` start times with `LC_ALL=C TZ=UTC`, applies CPU/data rlimits
|
|
97
|
-
and polls tree RSS. Windows
|
|
97
|
+
and polls tree RSS. Windows reads CIM creation times through one long-lived PowerShell helper per supervisor, polls tree
|
|
98
98
|
working sets (`enforcement: "rss-polling"`) and stops verified trees with
|
|
99
99
|
`taskkill /PID <pid> /T /F`. Memory caps on both are softer than Linux cgroups.
|
|
100
100
|
- Both use a Node guardian as the handle PID. It proves the random token from
|
|
@@ -102,6 +102,10 @@ PTY stdout combines terminal output; stderr is empty. `stdin` is writable too.
|
|
|
102
102
|
until registry persistence, and survives supervisor restarts for recovery.
|
|
103
103
|
Memory includes the guardian and its descendants. No identity-helper setup
|
|
104
104
|
or custom native compilation is needed.
|
|
105
|
+
- Defaults per platform: `pollIntervalMs` 100 ms Linux, 500 macOS, 1500 Windows;
|
|
106
|
+
`observationTimeoutMs` (ownership check wait) 2 s Linux, 15 s macOS/Windows. Explicit
|
|
107
|
+
options win. Raise `observationTimeoutMs` on a loaded machine; the timeout error names it.
|
|
108
|
+
The guardian replies to resume before launching the workload.
|
|
105
109
|
- Windows needs PowerShell/CIM. `cpuSeconds` is POSIX-only and
|
|
106
110
|
`virtualMemoryBytes` Linux-only; unsupported limits fail before launch.
|
|
107
111
|
Timeouts apply everywhere. Windows always forces the PID tree immediately;
|