@sorbetai/tools-node 0.1.0-alpha.17 → 0.1.0-alpha.19
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/dist/environment/index.js +1 -1
- package/dist/{environment-CtRyPVb9.js → environment-BTsGlbsO.js} +5 -1
- package/dist/environment-BTsGlbsO.js.map +1 -0
- package/dist/index.d.ts +13 -1
- package/dist/index.js +44 -45
- package/dist/index.js.map +1 -1
- package/dist/plugin/workspace-component.js +856 -687
- package/package.json +8 -8
- package/dist/environment-CtRyPVb9.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sorbetai/tools-node",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.19",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Node.js workspace tools for Sorbet",
|
|
6
6
|
"type": "module",
|
|
@@ -29,18 +29,18 @@
|
|
|
29
29
|
"execa": "10.2.1",
|
|
30
30
|
"file-type": "22.3.0",
|
|
31
31
|
"koffi": "3.3.7",
|
|
32
|
-
"@earendil-works/pi-schema": "1.
|
|
33
|
-
"@sorbetai/context": "0.1.0-alpha.
|
|
34
|
-
"@sorbetai/
|
|
35
|
-
"@sorbetai/schema": "0.1.0-alpha.
|
|
36
|
-
"@sorbetai/
|
|
32
|
+
"@earendil-works/pi-schema": "1.6.0",
|
|
33
|
+
"@sorbetai/context": "0.1.0-alpha.19",
|
|
34
|
+
"@sorbetai/runtime": "0.1.0-alpha.19",
|
|
35
|
+
"@sorbetai/schema": "0.1.0-alpha.19",
|
|
36
|
+
"@sorbetai/plugins": "0.1.0-alpha.19"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
39
|
-
"@earendil-works/pi-ai": "1.
|
|
39
|
+
"@earendil-works/pi-ai": "1.6.0",
|
|
40
40
|
"@types/node": "^24.2.1",
|
|
41
41
|
"tsdown": "0.15.12",
|
|
42
42
|
"vitest": "^3.2.4",
|
|
43
|
-
"@sorbetai/durable": "0.1.0-alpha.
|
|
43
|
+
"@sorbetai/durable": "0.1.0-alpha.19"
|
|
44
44
|
},
|
|
45
45
|
"repository": {
|
|
46
46
|
"type": "git",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"environment-CtRyPVb9.js","names":["members: GroupMember[]","stat: string","stat","delay","value: unknown","decoded: unknown","signal: EmergencyCleanup['signal']","#retain","#previewBytes","#streams","#bytes","#fd","#path","#chunks","bootSession: string","failure: ExecutionError | undefined","exited: ProcessExited | undefined","startupLoaderCode: string | undefined","cancellationWatchdog: NodeJS.Timeout | undefined","identity: CommandGroupIdentity | undefined","commandPid: number | undefined","workerNonce: string | undefined","#terminate","#failure","#consume","#bytes","release: (() => Promise<void>) | undefined","env: Record<string, string>","supervised: Result<CommandOutput, ExecutionError>","terminate: (() => void) | undefined","outcome: Result<CommandOutput, ExecutionError>","#patterns","#lookahead","#streams","#matchAtStart","#capacity","#shellPath","#shellEnv","#shellEnvironment","#rejectSymlinkReads","#pending","#file","#openForRead","lines: string[]","#metadata","infos: FileInfo[]","#closed","kind: FileInfo['kind']","#runFile","#permits"],"sources":["../src/environment/contracts.ts","../src/environment/process-emergency.ts","../src/environment/process-output.ts","../src/environment/managed-process.ts","../src/environment/process.ts","../src/environment/output-redaction.ts","../src/environment/node-environment.ts","../src/environment/service.ts","../src/environment/process-capacity.ts"],"sourcesContent":["import type { Properties } from '@earendil-works/pi-schema';\nexport type Result<Value, Failure> =\n { readonly ok: true; readonly value: Value } | { readonly ok: false; readonly error: Failure };\n\nexport function ok<Value>(value: Value): { readonly ok: true; readonly value: Value } {\n return { ok: true, value };\n}\n\nexport function err<Failure>(error: Failure): { readonly ok: false; readonly error: Failure } {\n return { ok: false, error };\n}\n\nexport function getOrThrow<Value, Failure>(result: Result<Value, Failure>): Value {\n if (!result.ok) throw result.error;\n return result.value;\n}\n\nexport type FileErrorCode =\n | 'aborted'\n | 'not_found'\n | 'permission_denied'\n | 'not_directory'\n | 'is_directory'\n | 'invalid'\n | 'not_supported'\n /** The sandbox refused or could not run the operation, so nothing was applied. */\n | 'sandbox_failed'\n /** The operation ran but its outcome is unknown; it may already have been applied. */\n | 'unknown';\n\nexport class FileError extends Error {\n readonly code: FileErrorCode;\n readonly path: string | undefined;\n\n constructor(code: FileErrorCode, message: string, path?: string, cause?: Error) {\n super(message, { cause });\n this.name = 'FileError';\n this.code = code;\n this.path = path;\n }\n}\n\nexport type ExecutionErrorCode =\n | 'aborted'\n | 'timeout'\n | 'shell_unavailable'\n | 'spawn_error'\n | 'callback_error'\n | 'quota_exceeded'\n | 'unknown';\n\nexport class ExecutionError extends Error {\n readonly code: ExecutionErrorCode;\n\n /** Captured output remains inspectable after cancellation or execution failure.\n * A capture failure may leave its artifact incomplete; the error still takes precedence.\n */\n readonly output: Omit<CommandOutput, 'exitCode'> | undefined;\n\n constructor(\n code: ExecutionErrorCode,\n message: string,\n cause?: Error,\n output?: Omit<CommandOutput, 'exitCode'>\n ) {\n super(message, { cause });\n this.name = 'ExecutionError';\n this.code = code;\n this.output = output;\n }\n}\n\nexport interface FileInfo {\n readonly name: string;\n readonly path: string;\n /** Metadata describes the addressed object; symlinks are not followed. */\n readonly kind: 'file' | 'directory' | 'symlink';\n readonly size: number;\n readonly mtimeMs: number;\n}\n\nexport interface ProcessStarted {\n /** Opaque verified OS identity for local restart recovery via settleAbandonedProcess.\n * Persist verbatim in trusted task records; never parse it or signal its PID directly.\n */\n readonly processIdentity: string;\n /** Per-invocation nonce: correlate (workerNonce, workerPid, pid, startedAt), never PID alone. */\n readonly workerNonce: string;\n readonly pid: number;\n readonly workerPid: number;\n readonly startedAt: number;\n}\n\nexport interface ProcessExited {\n readonly workerNonce: string;\n readonly pid?: number;\n readonly workerPid: number;\n readonly startedAt: number;\n readonly exitedAt: number;\n readonly exitCode?: number;\n /** Direct-child termination signal, or last emergency group signal if its worker died. */\n readonly signal?: string;\n /** True when Execa escalated or final descendant cleanup sent SIGKILL. */\n readonly forced: boolean;\n readonly truncated: boolean;\n /** False proves the owner never sent execution authorization to the worker.\n * Absence cannot establish whether the command ran.\n */\n readonly dispatched?: boolean;\n /** False reports a cleanup failure; absence makes no stronger containment claim. */\n readonly cleanupVerified?: boolean;\n /** Raw stdout + stderr bytes observed by the worker, including discarded bytes.\n * Zero if the worker fails without delivering a terminal report (total unavailable).\n */\n readonly outputBytes: number;\n readonly stdout: string;\n readonly stderr: string;\n readonly errorCode?: ExecutionErrorCode;\n}\n\n/** Internal task-owner hooks. Callbacks are synchronous; throwing cancels execution.\n * Stream callbacks receive complete decoded output unless the Host explicitly sets maxOutputBytes.\n * Return values retain bounded tails; direct callers can read outputReference for complete output.\n * An explicit combined byte quota drains excess output and reports truncated=true.\n * Exit is delivered after the process-group cleanup attempt, including\n * failed spawns. Owner IPC disconnect always cancels execution.\n * Cancellation sends SIGTERM, then SIGKILL after forceKillAfterDelayMs (default 1000).\n * Execa tree termination is best-effort: descendants creating a new group/session\n * can escape. A ready handshake precedes dispatch. Worker exit before dispatch proves that\n * no command was authorized and reports dispatched=false with verified cleanup.\n * After dispatch, worker failure without a terminal report is a spawn_error, not proof\n * that the command did not run. Validation/abort before worker creation does not\n * invoke hooks; bootstrap/admission failures after creation report dispatched=false.\n * PID metadata is for correlation, not a durable cancellation handle. Pair it with\n * the workerNonce and start time; never signal a recovered PID from Journal data.\n * Execa's final group cleanup has a best-effort PID-reuse race after group exit;\n * the nonce identifies this invocation but cannot fence an OS signal.\n * Managed supervision currently requires Linux (/proc and /bin/ps) or macOS\n * (/bin/ps and kern.bootsessionuuid); other hosts are rejected before dispatch.\n * Before onStarted, the owner verifies boot identity, OS start identities and PGID.\n * Fast commands receive a verified-gone identity only after group inspection;\n * failed inspection cancels/drains execution without exposing onStarted.\n * Unexpected worker exit triggers\n * verified SIGTERM, up to 2s grace, SIGKILL, and up to 2s drain before settlement.\n * Linux start identities use kernel ticks; macOS ps lstart has second resolution.\n * The check-to-signal race remains; no OS-atomic identity handle is claimed.\n * Reused/unverifiable groups are not signaled and report unverified cleanup.\n * This fallback requires a captured identity and a surviving verified group member;\n * worker death before identity capture or loss of every known member is not covered.\n * Processes escaping the original group and simultaneous loss of owner + worker\n * are outside this guarantee. Zombies count as stopped while the OS reaps them.\n */\nexport interface ProcessLifecycle {\n readonly onStarted?: (process: ProcessStarted) => void;\n readonly onExited?: (process: ProcessExited) => void;\n readonly maxOutputBytes?: number;\n readonly forceKillAfterDelayMs?: number;\n}\n\nexport interface ShellExecOptions {\n /** Host admission recheck after resource waiting, immediately before OS dispatch. */\n readonly beforeStart?: () => Promise<void>;\n /** Selects an isolated supervisor per invocation in sandbox environments.\n * Preserves exec results, cancellation, and output callback contracts;\n * lifecycle hooks are configured independently.\n */\n readonly managed?: boolean;\n readonly lifecycle?: ProcessLifecycle;\n readonly cwd?: string;\n readonly env?: Record<string, string>;\n readonly inheritEnv?: boolean;\n /** Seconds; zero, negative, non-finite and overflowing values are rejected. */\n readonly timeout?: number;\n readonly abortSignal?: AbortSignal;\n readonly onStdout?: (chunk: string) => void;\n readonly onStderr?: (chunk: string) => void;\n}\n\n/** Extra variables for a host-bound shell, with values that must be removed from output. */\nexport interface ShellEnvironmentBinding {\n readonly remove?: readonly string[];\n readonly variables?: Readonly<Record<string, string>>;\n readonly secrets?: Readonly<Record<string, string>>;\n}\n\nexport interface CommandOutput {\n readonly stdout: string;\n readonly stderr: string;\n readonly exitCode: number;\n /** Complete combined output artifact when direct execution exceeds its in-memory preview. */\n readonly outputReference?: string;\n readonly outputBytes?: number;\n /** Return strings omit earlier output; stream callbacks still receive it. */\n readonly outputTruncated?: boolean;\n}\n\n/** Rechecks captured source authority after resource waiting, before filesystem dispatch.\n * Failures retain the callback error as a cause; this does not request user approval.\n */\nexport type FileExecutionOptions = Pick<ShellExecOptions, 'abortSignal' | 'beforeStart'>;\n\n/**\n * Borrowed filesystem and command capabilities. Relative paths resolve against cwd;\n * Failures and cancellation return Results. Cleanup cancels and joins owned IO and commands.\n */\nexport interface ExecutionEnv {\n /** Opt-in promise that managed exec supplies lifecycle hooks, owner-death supervision and bounded cancellation. */\n readonly managedCommands?: true;\n readonly cwd: string;\n absolutePath(path: string, options?: FileExecutionOptions): Promise<Result<string, FileError>>;\n joinPath(parts: string[], options?: FileExecutionOptions): Promise<Result<string, FileError>>;\n readTextFile(path: string, options?: FileExecutionOptions): Promise<Result<string, FileError>>;\n readTextLines(\n path: string,\n options?: FileExecutionOptions & { maxLines?: number }\n ): Promise<Result<string[], FileError>>;\n /** A range performs bounded IO from its zero-based byte offset; EOF may shorten it.\n * Offset and length must be nonnegative safe integers. Omit range to read all bytes. */\n readBinaryFile(\n path: string,\n options?: FileExecutionOptions & {\n readonly range?: { readonly offset: number; readonly length: number };\n }\n ): Promise<Result<Uint8Array, FileError>>;\n writeFile(\n path: string,\n content: string | Uint8Array,\n options?: FileExecutionOptions\n ): Promise<Result<void, FileError>>;\n appendFile(\n path: string,\n content: string | Uint8Array,\n options?: FileExecutionOptions\n ): Promise<Result<void, FileError>>;\n renameFile(\n source: string,\n destination: string,\n options?: FileExecutionOptions\n ): Promise<Result<void, FileError>>;\n fileInfo(path: string, options?: FileExecutionOptions): Promise<Result<FileInfo, FileError>>;\n listDir(path: string, options?: FileExecutionOptions): Promise<Result<FileInfo[], FileError>>;\n canonicalPath(path: string, options?: FileExecutionOptions): Promise<Result<string, FileError>>;\n exists(path: string, options?: FileExecutionOptions): Promise<Result<boolean, FileError>>;\n createDir(\n path: string,\n options?: FileExecutionOptions & { recursive?: boolean }\n ): Promise<Result<void, FileError>>;\n remove(\n path: string,\n options?: FileExecutionOptions & { recursive?: boolean; force?: boolean }\n ): Promise<Result<void, FileError>>;\n createTempDir(\n prefix?: string,\n options?: FileExecutionOptions\n ): Promise<Result<string, FileError>>;\n createTempFile(\n options?: FileExecutionOptions & { prefix?: string; suffix?: string }\n ): Promise<Result<string, FileError>>;\n exec(command: string, options?: ShellExecOptions): Promise<Result<CommandOutput, ExecutionError>>;\n cleanup(): Promise<void>;\n}\n\n/**\n * The validated invocation fields an environment provider may inspect. A Tool supplies the\n * fields it validated, so a provider must tolerate the others being absent.\n */\nexport interface EnvironmentInvocation {\n readonly runId?: string;\n readonly approval?: 'approved' | 'not-required';\n readonly toolName?: string;\n readonly path?: string;\n readonly command?: string;\n /** `require-escalated` asks the provider for a widened attempt; it never widens by itself. */\n readonly sandboxPermissions?: string;\n}\n\n/**\n * Tools borrow one environment per invocation. A provider is resolved only when\n * execution starts; constructing a Tool does not resolve it. The Host owns cleanup,\n * and may use the invocation to select the environment for that attempt alone.\n */\nexport type ExecutionEnvironmentSource =\n ExecutionEnv | ((invocation: EnvironmentInvocation) => ExecutionEnv);\n\nexport interface ExecutionEnvironmentProvider {\n forInvocation(invocation: EnvironmentInvocation): ExecutionEnv;\n readonly invocationProperties?: Properties;\n readonly confinement: readonly ('read-only' | 'read-write')[];\n}\n","import * as s from '@earendil-works/pi-schema';\nimport { check } from '@sorbetai/schema';\nimport { readFile } from 'node:fs/promises';\nimport { setTimeout as delay } from 'node:timers/promises';\n\nimport { execa } from 'execa';\nimport { isError } from 'es-toolkit';\n\nimport { cleanupWindowsJob, probeWindowsJob, windowsJobName } from './windows-job.js';\nimport { ExecutionError } from './contracts.js';\n\nconst Pid = s.int({ minimum: 1 });\nconst MemberSchema = s.obj(\n {\n pid: Pid,\n pgid: Pid,\n startIdentity: s.str(),\n zombie: s.bool(),\n },\n { open: false }\n);\nconst IdentitySchema = s.obj(\n {\n version: s.lit(1),\n platform: s.union([s.lit('linux'), s.lit('darwin')]),\n bootSession: s.str(),\n workerNonce: s.str(),\n state: s.union([s.lit('group'), s.lit('gone')]),\n pid: Pid,\n members: s.arr(MemberSchema),\n },\n { open: false }\n);\nconst WindowsIdentitySchema = s.obj(\n {\n version: s.lit(1),\n platform: s.lit('win32'),\n workerNonce: s.str({ pattern: '^[a-zA-Z0-9-]{1,128}$' }),\n },\n { open: false }\n);\nconst WINDOWS_IDENTITY_PREFIX = 'sorbet-job-v1:';\n\nconst IDENTITY_PREFIX = 'sorbet-process-v1:';\nconst MAX_IDENTITY_BYTES = 1024 * 1024;\n\ntype GroupMember = s.Static<typeof MemberSchema>;\n\nexport interface CommandGroupIdentity {\n readonly pid: number;\n readonly members: readonly GroupMember[];\n readonly windowsJob?: string;\n}\n\nexport interface EmergencyCleanup {\n readonly forced: boolean;\n readonly drained: boolean;\n readonly reused?: boolean;\n readonly signal?: 'SIGTERM' | 'SIGKILL';\n}\n\nconst missingProcessCodes = new Set<unknown>(['ENOENT', 'ESRCH']);\nconst SUPPORTED_PLATFORMS = new Set(['linux', 'darwin']);\nconst INSPECTION_TIMEOUT_MS = 1000;\nconst DRAIN_TIMEOUT_MS = 2000;\n\n/** Only inspect live OS state; neither command text nor environment is collected.\n * Linux uses kernel start ticks; Darwin's ps lstart has one-second resolution.\n * This is verification immediately before signaling, not an atomic pidfd operation.\n */\nasync function groupMembers(pgid: number): Promise<GroupMember[]> {\n if (!SUPPORTED_PLATFORMS.has(process.platform)) {\n throw new Error('Emergency process cleanup is unsupported on this platform');\n }\n const inspectionSignal = AbortSignal.timeout(INSPECTION_TIMEOUT_MS);\n const result = await execa('/bin/ps', ['-axo', 'pid=,ppid=,pgid=,stat=,lstart='], {\n env: { LC_ALL: 'C', TZ: 'UTC' },\n timeout: INSPECTION_TIMEOUT_MS,\n cancelSignal: inspectionSignal,\n forceKillAfterDelay: 100,\n maxBuffer: 1024 * 1024,\n });\n const members: GroupMember[] = [];\n for (const line of result.stdout.split('\\n')) {\n const match = /^\\s*(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\S+)\\s+(.+?)\\s*$/.exec(line);\n if (match === null || Number(match[3]) !== pgid) continue;\n const pid = Number(match[1]);\n let startIdentity = match[5] ?? '';\n let zombie = match[4]?.startsWith('Z') ?? false;\n if (process.platform === 'linux') {\n // comm may contain spaces and parentheses. Fields after its final ')' start\n // at state (field 3); starttime is field 22 and pgrp is field 5.\n let stat: string;\n try {\n stat = await readFile(`/proc/${pid}/stat`, { encoding: 'utf8', signal: inspectionSignal });\n } catch (cause) {\n if (!isError(cause) || !missingProcessCodes.has(Reflect.get(cause, 'code'))) throw cause;\n continue;\n }\n const fields = stat\n .slice(stat.lastIndexOf(')') + 2)\n .trim()\n .split(/\\s+/);\n if (Number(fields[2]) !== pgid || fields[19] === undefined) continue;\n startIdentity = fields[19];\n zombie = fields[0] === 'Z';\n }\n if (startIdentity) members.push({ pid, pgid, startIdentity, zombie });\n }\n return members;\n}\n\nfunction matches(member: GroupMember, known: readonly GroupMember[]): boolean {\n return known.some(\n (identity) =>\n identity.pid === member.pid &&\n identity.pgid === member.pgid &&\n identity.startIdentity === member.startIdentity\n );\n}\n\n/** Fail before dispatch when this host cannot support verified emergency cleanup. */\nexport async function verifyProcessInspection(): Promise<string> {\n if (process.platform === 'win32') {\n await probeWindowsJob();\n return 'windows-job';\n }\n const bootSession = await readBootSession();\n await groupMembers(process.pid);\n if (process.platform === 'linux') await readFile('/proc/self/stat', 'utf8');\n return bootSession;\n}\n\nasync function readBootSession(): Promise<string> {\n if (!SUPPORTED_PLATFORMS.has(process.platform)) {\n throw new ExecutionError(\n 'spawn_error',\n 'Managed process supervision is unsupported on this platform; requires Linux or macOS'\n );\n }\n try {\n const value =\n process.platform === 'linux'\n ? await readFile('/proc/sys/kernel/random/boot_id', {\n encoding: 'utf8',\n signal: AbortSignal.timeout(INSPECTION_TIMEOUT_MS),\n })\n : (\n await execa('/usr/sbin/sysctl', ['-n', 'kern.bootsessionuuid'], {\n timeout: INSPECTION_TIMEOUT_MS,\n forceKillAfterDelay: 100,\n maxBuffer: 1024,\n })\n ).stdout;\n return value.trim().toLowerCase();\n } catch {\n throw new ExecutionError('spawn_error', 'Managed process boot identity could not be inspected');\n }\n}\n\n/** Called before exposing onStarted. An empty snapshot proves the group is gone;\n * inspection failures and surviving groups without a verified leader fail closed.\n */\nexport async function captureCommandGroup(\n pid: number,\n workerNonce?: string\n): Promise<CommandGroupIdentity> {\n if (process.platform === 'win32') {\n if (\n !workerNonce ||\n !check(WindowsIdentitySchema, { version: 1, platform: 'win32', workerNonce })\n )\n throw new ExecutionError('spawn_error', 'Invalid Windows Job identity');\n return { pid, members: [], windowsJob: windowsJobName(workerNonce) };\n }\n let members = await groupMembers(pid);\n if (\n members.some((member) => !member.zombie) &&\n !members.some((member) => member.pid === pid && !member.zombie)\n ) {\n // A fast shell may exit just before Execa drains its descendants. Reinspect\n // once before rejecting; never invent a gone token from an unverified group.\n await delay(25);\n members = await groupMembers(pid);\n }\n if (!members.some((member) => !member.zombie)) return { pid, members: [] };\n if (!members.some((member) => member.pid === pid && !member.zombie)) {\n throw new ExecutionError('spawn_error', 'Command process identity could not be verified');\n }\n return { pid, members };\n}\n\nexport function encodeProcessIdentity(\n identity: CommandGroupIdentity,\n workerNonce: string,\n bootSession: string\n): string {\n if (identity.windowsJob !== undefined)\n return WINDOWS_IDENTITY_PREFIX + JSON.stringify({ version: 1, platform: 'win32', workerNonce });\n const value = {\n version: 1,\n platform: process.platform,\n bootSession,\n workerNonce,\n state: identity.members.length === 0 ? 'gone' : 'group',\n pid: identity.pid,\n members: identity.members,\n };\n const token = IDENTITY_PREFIX + JSON.stringify(value);\n if (Buffer.byteLength(token) > MAX_IDENTITY_BYTES)\n throw new ExecutionError('spawn_error', 'Command process identity exceeds size limit');\n return token;\n}\n\n/** Reconcile a trusted local task record before writing restart settlement.\n * Resolves after verified drain, proven absence/reuse, or a different boot session.\n * Throws ExecutionError for malformed/unsupported identities, failed inspection,\n * ambiguous ownership, or failed bounded drain. Never pass model-supplied tokens.\n * Linux kernel ticks and macOS second-resolution start identities are checked\n * before group signals; races and descendants escaping their group remain possible.\n */\nexport async function settleAbandonedProcess(processIdentity: string): Promise<void> {\n if (processIdentity.startsWith(WINDOWS_IDENTITY_PREFIX)) {\n let value: unknown;\n try {\n value = JSON.parse(processIdentity.slice(WINDOWS_IDENTITY_PREFIX.length));\n } catch {\n throw new ExecutionError('spawn_error', 'Invalid managed process identity');\n }\n if (process.platform !== 'win32' || !check(WindowsIdentitySchema, value))\n throw new ExecutionError('spawn_error', 'Invalid managed process identity');\n if (!(await cleanupWindowsJob(windowsJobName(value.workerNonce))))\n throw new ExecutionError(\n 'spawn_error',\n 'Abandoned command Job cleanup could not be verified'\n );\n return;\n }\n let decoded: unknown;\n try {\n if (\n Buffer.byteLength(processIdentity) > MAX_IDENTITY_BYTES ||\n !processIdentity.startsWith(IDENTITY_PREFIX)\n )\n throw new Error('Invalid identity');\n decoded = JSON.parse(processIdentity.slice(IDENTITY_PREFIX.length));\n } catch {\n throw new ExecutionError('spawn_error', 'Invalid managed process identity');\n }\n if (\n !check(IdentitySchema, decoded) ||\n decoded.members.some((member) => member.pgid !== decoded.pid) ||\n (decoded.state === 'gone'\n ? decoded.members.length !== 0\n : !decoded.members.some((member) => member.pid === decoded.pid))\n ) {\n throw new ExecutionError('spawn_error', 'Invalid managed process identity');\n }\n const bootSession = await readBootSession();\n if (decoded.platform !== process.platform)\n throw new ExecutionError(\n 'spawn_error',\n 'Managed process identity belongs to a different platform'\n );\n if (decoded.bootSession !== bootSession || decoded.state === 'gone') return;\n const cleanup = await cleanupCommandGroup(decoded, 1000);\n if (!cleanup.drained && !cleanup.reused) {\n throw new ExecutionError(\n 'spawn_error',\n 'Abandoned command group cleanup could not be verified'\n );\n }\n}\n\nfunction groupWasReused(identity: CommandGroupIdentity, current: readonly GroupMember[]): boolean {\n const previousLeader = identity.members.find((member) => member.pid === identity.pid);\n const currentLeader = current.find((member) => member.pid === identity.pid);\n return (\n previousLeader !== undefined &&\n currentLeader !== undefined &&\n previousLeader.startIdentity !== currentLeader.startIdentity\n );\n}\n\n/** Emergency fallback only: Execa normally owns cancellation inside the worker.\n * Its handle is unavailable after worker death, so revalidate a known surviving\n * group member before each signal. An unknown/reused group is never signaled.\n */\nexport async function cleanupCommandGroup(\n identity: CommandGroupIdentity | undefined,\n graceMs: number\n): Promise<EmergencyCleanup> {\n if (identity === undefined) return { forced: false, drained: false };\n if (identity.windowsJob !== undefined) {\n try {\n return { forced: true, drained: await cleanupWindowsJob(identity.windowsJob) };\n } catch {\n return { forced: false, drained: false };\n }\n }\n let known = identity.members;\n let forced = false;\n let signal: EmergencyCleanup['signal'];\n try {\n const initial = await groupMembers(identity.pid);\n if (!initial.some((member) => !member.zombie)) return { forced, drained: true };\n if (!initial.some((member) => matches(member, known)))\n return { forced, drained: false, reused: groupWasReused(identity, initial) };\n // A verified member anchors the group; retain its current descendants' start\n // identities so escalation remains verifiable if SIGTERM removes the leader.\n known = initial;\n process.kill(-identity.pid, 'SIGTERM');\n signal = 'SIGTERM';\n const forceAt = performance.now() + Math.min(graceMs, DRAIN_TIMEOUT_MS);\n const deadline = forceAt + DRAIN_TIMEOUT_MS;\n while (performance.now() < deadline) {\n const current = await groupMembers(identity.pid);\n if (!current.some((member) => !member.zombie)) return { forced, drained: true, signal };\n if (!current.some((member) => matches(member, known)))\n return { forced, drained: false, signal, reused: groupWasReused(identity, current) };\n known = current;\n if (!forced && performance.now() >= forceAt) {\n process.kill(-identity.pid, 'SIGKILL');\n signal = 'SIGKILL';\n forced = true;\n }\n await delay(25);\n }\n } catch {\n // Fixed diagnostics are emitted by the owner; never expose ps arguments or\n // errors. A failed verification is not permission to signal the numeric PID.\n }\n return { forced, drained: false, signal };\n}\n","import { closeSync, fsyncSync, mkdtempSync, openSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\n\nconst PreviewBytes = 50 * 1024;\n\n/** Callback consumers own their full capture; direct callers receive a retained artifact. */\nexport class ProcessOutput {\n readonly #retain: boolean;\n readonly #previewBytes: number;\n readonly #streams = { stdout: '', stderr: '' };\n #chunks: Buffer[] = [];\n #bytes = 0;\n #fd: number | undefined;\n #path: string | undefined;\n\n constructor(retain: boolean, previewBytes = PreviewBytes) {\n this.#retain = retain;\n this.#previewBytes = previewBytes;\n }\n\n append(stream: 'stdout' | 'stderr', text: string): void {\n if (!text) return;\n const bytes = Buffer.from(text);\n this.#bytes += bytes.length;\n if (this.#retain) {\n if (this.#fd === undefined && this.#bytes > this.#previewBytes) {\n const directory = mkdtempSync(join(tmpdir(), 'sorbet-process-'));\n this.#path = join(directory, 'output.log');\n this.#fd = openSync(this.#path, 'wx', 0o600);\n for (const chunk of this.#chunks) writeFileSync(this.#fd, chunk);\n this.#chunks = [];\n }\n if (this.#fd !== undefined) writeFileSync(this.#fd, bytes);\n else this.#chunks.push(bytes);\n }\n const preview = Buffer.from(this.#streams[stream] + text);\n let offset = Math.max(0, preview.length - this.#previewBytes);\n while (offset < preview.length && (preview[offset]! & 0xc0) === 0x80) offset++;\n this.#streams[stream] = preview.subarray(offset).toString('utf8');\n }\n\n snapshot() {\n const truncated =\n this.#bytes >\n Buffer.byteLength(this.#streams.stdout) + Buffer.byteLength(this.#streams.stderr);\n if (!truncated && this.#path === undefined) return { ...this.#streams };\n return {\n ...this.#streams,\n outputBytes: this.#bytes,\n outputTruncated: truncated,\n outputReference: this.#path,\n };\n }\n\n close(): void {\n if (this.#fd === undefined) return;\n const fd = this.#fd;\n this.#fd = undefined;\n try {\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n }\n}\n","import { fork, type Serializable } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport toError from 'ensure-error';\nimport {\n err,\n ExecutionError,\n ok,\n type CommandOutput,\n type ProcessExited,\n type Result,\n type ShellExecOptions,\n} from './contracts.js';\nimport type { WorkerMessage, WorkerCommand } from './process-protocol.js';\nimport {\n captureCommandGroup,\n cleanupCommandGroup,\n encodeProcessIdentity,\n verifyProcessInspection,\n type CommandGroupIdentity,\n} from './process-emergency.js';\nimport { ProcessOutput } from './process-output.js';\nimport type { StreamingOutputRedactor } from './output-redaction.js';\n\nconst StartupErrorCodes = new Set([\n 'MODULE_NOT_FOUND',\n 'ERR_MODULE_NOT_FOUND',\n 'ERR_PACKAGE_PATH_NOT_EXPORTED',\n 'ERR_PACKAGE_IMPORT_NOT_DEFINED',\n 'ERR_REQUIRE_ESM',\n 'ERR_UNKNOWN_FILE_EXTENSION',\n 'ERR_DLOPEN_FAILED',\n]);\n\nexport async function executeManagedCommand(\n command: WorkerCommand,\n options: ShellExecOptions,\n outputRedactor?: StreamingOutputRedactor\n): Promise<Result<CommandOutput, ExecutionError>> {\n const adjacent = new URL('./process-worker.js', import.meta.url);\n const bundled = new URL('./environment/process-worker.js', import.meta.url);\n let workerPath = adjacent;\n if (!existsSync(workerPath)) workerPath = bundled;\n if (!existsSync(workerPath))\n workerPath = new URL('../../dist/environment/process-worker.js', import.meta.url);\n return executeProcessWorker(workerPath, command, options, outputRedactor);\n}\n\n/** The platform cannot provide verified process-tree supervision here. Callers\n * may use a foreground executor when the command never reached dispatch.\n */\nexport class SupervisionUnavailableError extends Error {\n constructor(cause: Error) {\n super('Managed process supervision is unavailable', { cause });\n this.name = 'SupervisionUnavailableError';\n }\n}\n\n/** The worker must finish resource-free bootstrap and send ready before accepting\n * a request. Command and Sandbox resource acquisition starts only after dispatch.\n */\nexport async function executeProcessWorker<Request extends Serializable>(\n workerPath: URL,\n command: Request,\n options: ShellExecOptions,\n outputRedactor?: StreamingOutputRedactor\n): Promise<Result<CommandOutput, ExecutionError>> {\n let bootSession: string;\n try {\n bootSession = await verifyProcessInspection();\n } catch (cause) {\n return err(\n new ExecutionError(\n 'spawn_error',\n 'Background supervision is unavailable on this platform',\n new SupervisionUnavailableError(toError(cause))\n )\n );\n }\n if (options.abortSignal?.aborted) return err(new ExecutionError('aborted', 'Command aborted'));\n return new Promise((resolve) => {\n let failure: ExecutionError | undefined;\n let exited: ProcessExited | undefined;\n let settled = false;\n let dispatched = false;\n let startupStderr = Buffer.alloc(0);\n let startupLoaderCode: string | undefined;\n let cancellationWatchdog: NodeJS.Timeout | undefined;\n let identity: CommandGroupIdentity | undefined;\n let notifications = Promise.resolve();\n let commandPid: number | undefined;\n let workerNonce: string | undefined;\n let commandStartedAt = Date.now();\n const output = new ProcessOutput(\n options.onStdout === undefined || options.onStderr === undefined\n );\n let outputFlushed = false;\n const flushOutput = () => {\n if (outputFlushed) return;\n outputFlushed = true;\n for (const stream of ['stdout', 'stderr'] as const) {\n const tail = outputRedactor?.transform(stream, '', true) ?? '';\n if (!tail) continue;\n output.append(stream, tail);\n if (stream === 'stdout') options.onStdout?.(tail);\n else options.onStderr?.(tail);\n }\n };\n const startedAt = Date.now();\n const worker = fork(workerPath, [], {\n detached: true,\n stdio: ['ignore', 'ignore', 'pipe', 'ipc'],\n execArgv: [],\n });\n const closed = new Promise<void>((resolveClosed) => {\n worker.once('close', () => resolveClosed());\n });\n worker.stderr?.on('data', (chunk: Buffer) => {\n if (!dispatched) {\n const diagnostic = Buffer.concat([startupStderr, chunk]);\n const codes = diagnostic.toString('utf8').match(/\\b[A-Z][A-Z_]+\\b/g) ?? [];\n startupLoaderCode ??= codes.find((candidate) => StartupErrorCodes.has(candidate));\n startupStderr = diagnostic.subarray(-8192);\n }\n });\n const cancel = () => {\n if (settled) return;\n if (worker.connected) worker.send('cancel', () => {});\n // A stuck setup/reset cannot process IPC cancellation. Parent cleanup remains\n // conservative if no verified command identity was received before it died.\n cancellationWatchdog ??= setTimeout(\n () => worker.kill('SIGKILL'),\n (options.lifecycle?.forceKillAfterDelayMs ?? 1000) + 2000\n );\n };\n const startupWatchdog = setTimeout(() => {\n failure ??= new ExecutionError(\n 'spawn_error',\n 'Command execution worker did not become ready'\n );\n cancel();\n }, 10_000);\n const callback = (run: () => void) => {\n try {\n run();\n } catch (cause) {\n const error = toError(cause);\n failure ??= new ExecutionError('callback_error', error.message, error);\n cancel();\n }\n };\n const finish = async (code: number | null = null, signal: NodeJS.Signals | null = null) => {\n if (settled) return;\n settled = true;\n clearTimeout(cancellationWatchdog);\n clearTimeout(startupWatchdog);\n // onStarted captures OS identity asynchronously. Drain ordered notifications\n // before cleanup or terminal callbacks, even if the worker dies mid-capture.\n await notifications;\n callback(flushOutput);\n options.abortSignal?.removeEventListener('abort', cancel);\n if (exited === undefined) {\n const cleanup = dispatched\n ? await cleanupCommandGroup(identity, options.lifecycle?.forceKillAfterDelayMs ?? 1000)\n : { forced: false, drained: true, signal: undefined };\n const cleanupStatus = cleanup.drained\n ? 'command group drained'\n : 'command group cleanup could not be verified';\n if (!dispatched) {\n // Worker stderr can contain credentials or command text. Publish only\n // recognized loader codes, never the raw diagnostic or stack.\n failure ??= new ExecutionError(\n options.abortSignal?.aborted ? 'aborted' : 'spawn_error',\n `Command execution failed before dispatch (worker=${workerPath.pathname}, exitCode=${code}, signal=${signal}, loader=${startupLoaderCode ?? 'unavailable'})`\n );\n }\n failure ??= new ExecutionError(\n 'spawn_error',\n `Process worker exited without a terminal report (exitCode=${code}, signal=${signal}; ${cleanupStatus})`\n );\n exited = {\n workerNonce: workerNonce ?? 'worker-exited-before-start',\n outputBytes: 0,\n pid: commandPid,\n workerPid: worker.pid ?? 0,\n startedAt: commandPid === undefined ? startedAt : commandStartedAt,\n exitedAt: Date.now(),\n signal: cleanup.signal,\n forced: cleanup.forced,\n truncated: false,\n cleanupVerified: cleanup.drained,\n dispatched,\n ...output.snapshot(),\n errorCode: failure.code,\n };\n }\n const result = exited;\n try {\n output.close();\n } catch (cause) {\n // An incomplete output artifact outranks the stop reason: callers would\n // otherwise read a truncated reference as the command's whole output.\n const error = toError(cause);\n failure = new ExecutionError('callback_error', error.message, error);\n }\n callback(() =>\n options.lifecycle?.onExited?.({ ...result, errorCode: failure?.code ?? result.errorCode })\n );\n if (failure !== undefined)\n resolve(\n err(\n new ExecutionError(\n failure.code,\n failure.message,\n failure.cause === undefined ? undefined : toError(failure.cause),\n output.snapshot()\n )\n )\n );\n else resolve(ok({ ...output.snapshot(), exitCode: result.exitCode ?? 1 }));\n };\n worker.on('message', (message: WorkerMessage) => {\n notifications = notifications.then(async () => {\n switch (message.kind) {\n case 'ready':\n clearTimeout(startupWatchdog);\n if (dispatched || settled || options.abortSignal?.aborted || failure !== undefined)\n break;\n try {\n await Promise.race([options.beforeStart?.(), closed]);\n options.abortSignal?.throwIfAborted();\n } catch (cause) {\n if (settled) break;\n const error = toError(cause);\n failure ??= new ExecutionError(\n options.abortSignal?.aborted ? 'aborted' : 'spawn_error',\n error.message,\n error\n );\n cancel();\n break;\n }\n if (settled || failure !== undefined) break;\n // Mark dispatch before send: a delivery error does not prove that\n // the worker failed to receive or execute the command.\n dispatched = true;\n startupStderr = Buffer.alloc(0);\n worker.send(command, (cause) => {\n if (cause) {\n failure ??= new ExecutionError(\n 'spawn_error',\n 'Process worker request could not be delivered'\n );\n cancel();\n }\n });\n break;\n case 'started':\n commandPid = message.pid;\n workerNonce = message.workerNonce;\n commandStartedAt = message.startedAt;\n try {\n identity = await captureCommandGroup(message.pid, message.workerNonce);\n const processIdentity = encodeProcessIdentity(\n identity,\n message.workerNonce,\n bootSession\n );\n callback(() => options.lifecycle?.onStarted?.({ ...message, processIdentity }));\n } catch {\n failure ??= new ExecutionError(\n 'spawn_error',\n 'Command process identity could not be verified'\n );\n cancel();\n }\n break;\n case 'output':\n callback(() => {\n const text = outputRedactor?.transform(message.stream, message.text) ?? message.text;\n output.append(message.stream, text);\n if (failure === undefined) {\n if (message.stream === 'stdout') options.onStdout?.(text);\n else options.onStderr?.(text);\n }\n });\n if (worker.connected)\n worker.send({ kind: 'output-ack', sequence: message.sequence }, () => {});\n break;\n case 'exited':\n callback(flushOutput);\n exited = { ...message.result, ...output.snapshot() };\n if (message.result.errorCode !== undefined)\n failure ??= new ExecutionError(\n message.result.errorCode,\n message.result.message ?? 'Command failed'\n );\n break;\n }\n });\n });\n worker.once('error', () => {\n failure ??= new ExecutionError('spawn_error', 'Process worker could not be started');\n cancel();\n if (worker.pid === undefined) void finish();\n });\n worker.once('close', (code, signal) => {\n void finish(code, signal);\n });\n options.abortSignal?.addEventListener('abort', cancel, { once: true });\n if (options.abortSignal?.aborted) cancel();\n });\n}\n","import { randomUUID } from 'node:crypto';\nimport { StringDecoder } from 'node:string_decoder';\n\nimport toError from 'ensure-error';\nimport { execa } from 'execa';\n\nimport {\n err,\n ExecutionError,\n ok,\n type CommandOutput,\n type Result,\n type ProcessExited,\n type ShellExecOptions,\n} from './contracts.js';\n\nimport type { ProcessCapacity } from './process-capacity.js';\nimport { executeManagedCommand, SupervisionUnavailableError } from './managed-process.js';\nimport { ProcessOutput } from './process-output.js';\nimport type { StreamingOutputRedactor } from './output-redaction.js';\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n// Plain execa children outlive a SIGKILLed owner; only the supervising worker\n// observes owner death and drains the group, so it is the sole POSIX path.\nconst SUPERVISED_PLATFORMS = new Set(['linux', 'darwin', 'win32']);\n\ninterface CommandOptions {\n readonly capacity?: ProcessCapacity;\n readonly executable: string;\n readonly args: readonly string[];\n readonly cwd: string;\n readonly environment?: NodeJS.ProcessEnv;\n readonly options?: ShellExecOptions;\n readonly input?: string;\n readonly maxOutputBytes?: number;\n readonly outputRedactor?: StreamingOutputRedactor;\n}\n\n/** Both streams share a byte budget and failure, but never share UTF-8 decoder state. */\nclass CommandCapture {\n readonly limit: number | undefined;\n readonly #terminate: () => void;\n #bytes = 0;\n #failure: ExecutionError | undefined;\n\n constructor(limit: number | undefined, terminate: () => void) {\n this.limit = limit;\n this.#terminate = terminate;\n }\n\n get failure(): ExecutionError | undefined {\n return this.#failure;\n }\n\n stream(\n name: 'stdout' | 'stderr',\n outputRedactor: StreamingOutputRedactor | undefined,\n readCallback: () => ((text: string) => void) | undefined\n ) {\n const decoder = new StringDecoder('utf8');\n const consume = (text: string, bytes: number, final = false) =>\n this.#consume(outputRedactor?.transform(name, text, final) ?? text, bytes, readCallback());\n return {\n transform: function* (chunk: Uint8Array) {\n consume(decoder.write(Buffer.from(chunk)), chunk.byteLength);\n yield new Uint8Array();\n },\n final: function* () {\n consume(decoder.end(), 0, true);\n yield new Uint8Array();\n },\n binary: true as const,\n };\n }\n\n exceededLimit(): ExecutionError {\n return new ExecutionError('unknown', `Command exceeded the ${this.limit} byte output limit`);\n }\n\n #consume(chunk: string, bytes: number, callback: ((text: string) => void) | undefined): void {\n this.#bytes += bytes;\n if (this.limit !== undefined && this.#bytes > this.limit) {\n this.#failure = this.exceededLimit();\n this.#terminate();\n throw this.#failure;\n }\n try {\n if (chunk.length > 0) callback?.(chunk);\n } catch (cause) {\n const error = toError(cause);\n this.#failure = new ExecutionError('callback_error', error.message, error);\n this.#terminate();\n throw this.#failure;\n }\n }\n}\n\n/** Executes already assembled argv; cancellation and completion release the whole process group. */\nexport async function executeCommand(\n command: CommandOptions\n): Promise<Result<CommandOutput, ExecutionError>> {\n let release: (() => Promise<void>) | undefined;\n let cleanupVerified = true;\n const lifecycle = command.options?.lifecycle;\n const admitted =\n lifecycle === undefined\n ? command\n : {\n ...command,\n options: {\n ...command.options,\n lifecycle: {\n ...lifecycle,\n onExited: (exit: ProcessExited) => {\n cleanupVerified = exit.cleanupVerified !== false;\n lifecycle.onExited?.(exit);\n },\n },\n },\n };\n try {\n release = await command.capacity?.take(command.options?.abortSignal);\n return await executeAdmittedCommand(admitted);\n } catch (cause) {\n const error = toError(cause);\n return err(\n new ExecutionError(\n command.options?.abortSignal?.aborted ? 'aborted' : 'spawn_error',\n error.message,\n error\n )\n );\n } finally {\n if (cleanupVerified) await release?.();\n }\n}\nasync function executeAdmittedCommand(\n command: CommandOptions\n): Promise<Result<CommandOutput, ExecutionError>> {\n const { options } = command;\n if (options?.abortSignal?.aborted) return err(new ExecutionError('aborted', 'Command aborted'));\n const timeout = options?.timeout === undefined ? undefined : options.timeout * 1000;\n if (\n timeout !== undefined &&\n (!Number.isFinite(timeout) || timeout <= 0 || timeout > MAX_TIMEOUT_MS)\n ) {\n return err(new ExecutionError('timeout', 'Invalid timeout'));\n }\n if (SUPERVISED_PLATFORMS.has(process.platform)) {\n const maxOutputBytes = options?.lifecycle?.maxOutputBytes ?? command.maxOutputBytes;\n const forceKillAfterDelayMs = options?.lifecycle?.forceKillAfterDelayMs ?? 1000;\n if (\n (maxOutputBytes !== undefined &&\n (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 0)) ||\n !Number.isSafeInteger(forceKillAfterDelayMs) ||\n forceKillAfterDelayMs < 0 ||\n forceKillAfterDelayMs > MAX_TIMEOUT_MS\n ) {\n return err(new ExecutionError('spawn_error', 'Invalid managed process limits'));\n }\n const inherited = command.environment ?? process.env;\n const environment =\n options?.inheritEnv === false ? options.env : { ...inherited, ...options?.env };\n const env: Record<string, string> = {};\n for (const [key, value] of Object.entries(environment ?? {})) {\n if (value !== undefined) env[key] = value;\n }\n let supervised: Result<CommandOutput, ExecutionError>;\n try {\n supervised = await executeManagedCommand(\n {\n kind: 'command',\n workerNonce: randomUUID(),\n executable: command.executable,\n args: [...command.args],\n cwd: command.cwd,\n env,\n input: command.input,\n timeout,\n maxOutputBytes,\n forceKillAfterDelayMs,\n },\n options ?? {},\n command.outputRedactor\n );\n } catch {\n return err(new ExecutionError('spawn_error', 'Command could not be started'));\n }\n if (\n process.platform !== 'win32' ||\n supervised.ok ||\n !(supervised.error.cause instanceof SupervisionUnavailableError)\n )\n return supervised;\n }\n let terminate: (() => void) | undefined;\n const capture = new CommandCapture(command.maxOutputBytes, () => terminate?.());\n const output = new ProcessOutput(\n options?.onStdout === undefined || options.onStderr === undefined,\n command.maxOutputBytes\n );\n let outcome: Result<CommandOutput, ExecutionError>;\n try {\n await options?.beforeStart?.();\n options?.abortSignal?.throwIfAborted();\n const child = execa(command.executable, [...command.args], {\n cwd: command.cwd,\n env:\n options?.inheritEnv === false ? options.env : { ...command.environment, ...options?.env },\n extendEnv: command.environment === undefined && options?.inheritEnv !== false,\n killDescendants: true,\n windowsHide: true,\n cancelSignal: options?.abortSignal,\n timeout,\n killSignal: 'SIGKILL',\n reject: false,\n stripFinalNewline: false,\n buffer: false,\n input: command.input,\n stdin: command.input === undefined ? 'ignore' : 'pipe',\n stdout: capture.stream('stdout', command.outputRedactor, () => (text) => {\n output.append('stdout', text);\n options?.onStdout?.(text);\n }),\n stderr: capture.stream('stderr', command.outputRedactor, () => (text) => {\n output.append('stderr', text);\n options?.onStderr?.(text);\n }),\n });\n terminate = () => {\n child.kill('SIGKILL');\n };\n // Shell children may retain stdio after the shell exits; close their group before waiting for streams.\n child.nodeChildProcess.once('exit', terminate);\n const result = await child;\n if (capture.failure !== undefined) throw capture.failure;\n if (result.timedOut)\n throw new ExecutionError('timeout', `Command timed out after ${options?.timeout} seconds`);\n if (result.isCanceled || options?.abortSignal?.aborted)\n throw new ExecutionError('aborted', 'Command aborted');\n if (result.exitCode === undefined) {\n throw new ExecutionError('spawn_error', result.message ?? 'Command could not be executed');\n }\n outcome = ok({ ...output.snapshot(), exitCode: result.exitCode });\n } catch (cause) {\n const error = toError(cause);\n const failure = cause instanceof ExecutionError ? cause : capture.failure;\n outcome = err(\n new ExecutionError(\n failure?.code ?? 'spawn_error',\n failure?.message ?? error.message,\n error,\n output.snapshot()\n )\n );\n } finally {\n terminate?.();\n try {\n output.close();\n } catch (cause) {\n const error = toError(cause);\n outcome = err(new ExecutionError('callback_error', error.message, error, output.snapshot()));\n }\n }\n return outcome;\n}\n","type OutputStream = 'stdout' | 'stderr';\n\ninterface SecretPattern {\n readonly value: string;\n readonly label: string;\n}\n\ninterface StreamState {\n pending: string;\n finished: boolean;\n}\n\nfunction urlComponent(value: string): string {\n return encodeURIComponent(value).replace(\n /[!'()*]/gu,\n (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`\n );\n}\n\nfunction codePointLength(value: string): number {\n const point = value.codePointAt(0);\n return point !== undefined && point > 0xffff ? 2 : 1;\n}\n\nfunction patternsOf(secrets: Readonly<Record<string, string>>): SecretPattern[] {\n const patterns = new Map<string, SecretPattern>();\n for (const [environmentName, value] of Object.entries(secrets)) {\n if (value.length === 0) continue;\n const suffix = environmentName.replace(/^SORBET_SECRET_/u, '');\n const label = `[secret:${suffix || environmentName}]`;\n const variants = new Set([value, JSON.stringify(value).slice(1, -1)]);\n try {\n const encoded = urlComponent(value);\n variants.add(encoded);\n variants.add(encoded.replace(/%20/gu, '+'));\n variants.add(encoded.replace(/%[0-9A-F]{2}/gu, (escape) => escape.toLowerCase()));\n variants.add(\n encoded.replace(/%20/gu, '+').replace(/%[0-9A-F]{2}/gu, (escape) => escape.toLowerCase())\n );\n } catch {\n // A lone surrogate cannot be encoded into a URL component.\n }\n for (const variant of variants) {\n if (variant.length > 0) patterns.set(variant, { value: variant, label });\n }\n }\n return [...patterns.values()].sort((left, right) => right.value.length - left.value.length);\n}\n\n/** Redacts complete values across chunks before command output is retained or emitted. */\nexport class StreamingOutputRedactor {\n readonly #patterns: readonly SecretPattern[];\n readonly #lookahead: number;\n readonly #streams: Record<OutputStream, StreamState> = {\n stdout: { pending: '', finished: false },\n stderr: { pending: '', finished: false },\n };\n\n constructor(secrets: Readonly<Record<string, string>>) {\n this.#patterns = patternsOf(secrets);\n this.#lookahead = Math.max(0, ...this.#patterns.map((pattern) => pattern.value.length)) + 1;\n }\n\n transform(stream: OutputStream, chunk: string, final = false): string {\n const state = this.#streams[stream];\n if (state.finished) return chunk;\n if (this.#patterns.length === 0) {\n if (final) state.finished = true;\n return chunk;\n }\n\n let input = state.pending + chunk;\n state.pending = '';\n let output = '';\n const retained = final ? 0 : this.#lookahead;\n while (input.length > retained) {\n const match = this.#matchAtStart(input);\n if (match !== undefined) {\n output += match.label;\n input = input.slice(match.value.length);\n continue;\n }\n\n const width = codePointLength(input);\n const character = input.slice(0, width);\n output += character;\n input = input.slice(width);\n }\n\n if (final) {\n state.finished = true;\n state.pending = '';\n } else {\n state.pending = input;\n }\n return output;\n }\n\n #matchAtStart(input: string): SecretPattern | undefined {\n for (const pattern of this.#patterns) {\n if (input.startsWith(pattern.value)) return pattern;\n }\n return undefined;\n }\n}\n","import * as s from '@earendil-works/pi-schema';\nimport { check, decode } from '@sorbetai/schema';\nimport { randomUUID } from 'node:crypto';\nimport { constants, createReadStream, type Stats } from 'node:fs';\nimport {\n lstat,\n mkdir,\n mkdtemp,\n open,\n readdir,\n realpath,\n rename,\n rm,\n writeFile,\n} from 'node:fs/promises';\nimport type { FileHandle } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { basename, dirname, join, resolve } from 'node:path';\nimport { createInterface } from 'node:readline';\nimport { fileURLToPath } from 'node:url';\n\nimport toError from 'ensure-error';\n\nimport {\n err,\n ExecutionError,\n FileError,\n ok,\n type ExecutionEnv,\n type FileExecutionOptions,\n type FileErrorCode,\n type FileInfo,\n type Result,\n type ShellExecOptions,\n type ShellEnvironmentBinding,\n} from './contracts.js';\nimport type { ProcessCapacity } from './process-capacity.js';\nimport { executeCommand } from './process.js';\nimport { StreamingOutputRedactor } from './output-redaction.js';\n\nconst NodeFailureSchema = s.obj({ code: s.opt(s.str()) }, { open: true });\nconst FileRangeSchema = s.obj(\n {\n offset: s.int({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }),\n length: s.int({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }),\n },\n { open: true }\n);\nconst FILE_FAILURE_CODES = new Map<string, FileErrorCode>([\n ['ABORT_ERR', 'aborted'],\n ['ENOENT', 'not_found'],\n ['EACCES', 'permission_denied'],\n ['EPERM', 'permission_denied'],\n ['ELOOP', 'permission_denied'],\n ['ENOTDIR', 'not_directory'],\n ['EISDIR', 'is_directory'],\n ['EINVAL', 'invalid'],\n ['ERR_INVALID_ARG_VALUE', 'invalid'],\n ['ERR_INVALID_URL', 'invalid'],\n ['ERR_INVALID_FILE_URL_HOST', 'invalid'],\n ['ERR_INVALID_FILE_URL_PATH', 'invalid'],\n]);\n\nexport class NodeExecutionEnv implements ExecutionEnv {\n readonly managedCommands: true | undefined = new Set(['linux', 'darwin', 'win32']).has(\n process.platform\n )\n ? true\n : undefined;\n readonly cwd: string;\n readonly #capacity: ProcessCapacity | undefined;\n readonly #shellPath: string;\n readonly #shellEnv: NodeJS.ProcessEnv | undefined;\n readonly #shellEnvironment: (() => ShellEnvironmentBinding | undefined) | undefined;\n readonly #rejectSymlinkReads: boolean;\n readonly #pending = new Map<AbortController, Promise<unknown>>();\n #closed = false;\n\n constructor(options: {\n cwd: string;\n shellPath?: string;\n shellEnv?: NodeJS.ProcessEnv;\n shellEnvironment?: () => ShellEnvironmentBinding | undefined;\n capacity?: ProcessCapacity;\n rejectSymlinkReads?: boolean;\n }) {\n this.cwd = resolve(options.cwd);\n this.#capacity = options.capacity;\n this.#shellPath = options.shellPath ?? (process.platform === 'win32' ? 'cmd.exe' : '/bin/bash');\n this.#shellEnv = options.shellEnv;\n this.#shellEnvironment = options.shellEnvironment;\n this.#rejectSymlinkReads = options.rejectSymlinkReads ?? false;\n }\n\n absolutePath(path: string, options?: FileExecutionOptions) {\n return this.#file(path, options, async (absolute) => absolute);\n }\n\n joinPath(parts: string[], options?: FileExecutionOptions) {\n return this.#file(this.cwd, options, async () => join(...parts));\n }\n\n readTextFile(path: string, options?: FileExecutionOptions) {\n return this.#file(path, options, async (absolute, invocation) => {\n const handle = await this.#openForRead(absolute);\n try {\n const data = await handle.readFile({ signal: invocation.abortSignal });\n return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(data);\n } finally {\n await handle.close();\n }\n });\n }\n\n readTextLines(path: string, options?: FileExecutionOptions & { maxLines?: number }) {\n return this.#file(path, options, async (absolute, invocation) => {\n if (options?.maxLines === 0) return [];\n const handle = await this.#openForRead(absolute);\n const stream = createReadStream(absolute, {\n encoding: 'utf8',\n fd: handle.fd,\n autoClose: false,\n signal: invocation.abortSignal,\n });\n const reader = createInterface({ input: stream, crlfDelay: Infinity });\n const lines: string[] = [];\n try {\n for await (const line of reader) {\n lines.push(line);\n if (options?.maxLines !== undefined && lines.length >= options.maxLines) break;\n }\n invocation.abortSignal?.throwIfAborted();\n return lines;\n } finally {\n reader.close();\n stream.destroy();\n await handle.close();\n }\n });\n }\n\n readBinaryFile(\n path: string,\n options?: Parameters<ExecutionEnv['readBinaryFile']>[1]\n ): Promise<Result<Uint8Array, FileError>> {\n const range = options?.range === undefined ? undefined : { ...options.range };\n return this.#file(path, options, async (absolute, invocation) => {\n const handle = await this.#openForRead(absolute);\n try {\n if (range === undefined) return await handle.readFile({ signal: invocation.abortSignal });\n const captured = decode(FileRangeSchema, range);\n invocation.abortSignal?.throwIfAborted();\n await invocation.beforeStart?.();\n invocation.abortSignal?.throwIfAborted();\n const stats = await handle.stat();\n const length = Math.min(captured.length, Math.max(0, stats.size - captured.offset));\n const output = new Uint8Array(length);\n let received = 0;\n while (received < length) {\n await invocation.beforeStart?.();\n invocation.abortSignal?.throwIfAborted();\n const { bytesRead } = await handle.read(\n output,\n received,\n length - received,\n captured.offset + received\n );\n if (bytesRead === 0) break;\n received += bytesRead;\n }\n invocation.abortSignal?.throwIfAborted();\n return output.subarray(0, received);\n } finally {\n await handle.close();\n }\n });\n }\n\n writeFile(path: string, content: string | Uint8Array, options?: FileExecutionOptions) {\n return this.#file(path, options, async (absolute, invocation) => {\n await mkdir(dirname(absolute), { recursive: true });\n invocation.abortSignal?.throwIfAborted();\n await invocation.beforeStart?.();\n invocation.abortSignal?.throwIfAborted();\n await writeFile(absolute, content, { signal: invocation.abortSignal });\n });\n }\n\n appendFile(path: string, content: string | Uint8Array, options?: FileExecutionOptions) {\n return this.#file(path, options, async (absolute, invocation) => {\n await mkdir(dirname(absolute), { recursive: true });\n invocation.abortSignal?.throwIfAborted();\n await invocation.beforeStart?.();\n invocation.abortSignal?.throwIfAborted();\n await writeFile(absolute, content, { flag: 'a', signal: invocation.abortSignal });\n });\n }\n\n renameFile(source: string, destination: string, options?: FileExecutionOptions) {\n return this.#file(source, options, (absolute) =>\n rename(absolute, resolve(this.cwd, destination))\n );\n }\n\n fileInfo(path: string, options?: FileExecutionOptions) {\n return this.#file(path, options, async (absolute) =>\n this.#metadata(absolute, await lstat(absolute))\n );\n }\n\n listDir(path: string, options?: FileExecutionOptions) {\n return this.#file(path, options, async (absolute, invocation) => {\n const entries = await readdir(absolute);\n const infos: FileInfo[] = [];\n for (const name of entries.sort()) {\n invocation.abortSignal?.throwIfAborted();\n const entryPath = join(absolute, name);\n await invocation.beforeStart?.();\n invocation.abortSignal?.throwIfAborted();\n infos.push(this.#metadata(entryPath, await lstat(entryPath)));\n }\n return infos;\n });\n }\n\n canonicalPath(path: string, options?: FileExecutionOptions) {\n return this.#file(path, options, (absolute) => realpath(absolute));\n }\n\n async exists(path: string, options?: FileExecutionOptions): Promise<Result<boolean, FileError>> {\n const result = await this.fileInfo(path, options);\n if (result.ok) return ok(true);\n return result.error.code === 'not_found' ? ok(false) : result;\n }\n\n createDir(path: string, options?: FileExecutionOptions & { recursive?: boolean }) {\n return this.#file(path, options, async (absolute) => {\n await mkdir(absolute, { recursive: options?.recursive ?? true });\n });\n }\n\n remove(path: string, options?: FileExecutionOptions & { recursive?: boolean; force?: boolean }) {\n return this.#file(path, options, (absolute) =>\n rm(absolute, {\n recursive: options?.recursive ?? false,\n force: options?.force ?? false,\n })\n );\n }\n\n createTempDir(prefix = 'tmp-', options?: FileExecutionOptions) {\n return this.#file(tmpdir(), options, (absolute) => mkdtemp(join(absolute, prefix)));\n }\n\n createTempFile(options?: FileExecutionOptions & { prefix?: string; suffix?: string }) {\n return this.#file(tmpdir(), options, async (absolute, invocation) => {\n const directory = await mkdtemp(join(absolute, 'sorbet-'));\n const path = join(\n directory,\n `${options?.prefix ?? ''}${randomUUID()}${options?.suffix ?? ''}`\n );\n invocation.abortSignal?.throwIfAborted();\n await invocation.beforeStart?.();\n invocation.abortSignal?.throwIfAborted();\n await writeFile(path, '', { flag: 'wx', signal: invocation.abortSignal });\n return path;\n });\n }\n\n async exec(command: string, options?: ShellExecOptions) {\n if (this.#closed)\n return err(new ExecutionError('spawn_error', 'Execution environment is closed'));\n const controller = new AbortController();\n const abortSignal =\n options?.abortSignal === undefined\n ? controller.signal\n : AbortSignal.any([controller.signal, options.abortSignal]);\n const binding = this.#shellEnvironment?.();\n let environment = this.#shellEnv;\n if (binding !== undefined) {\n environment = { ...(this.#shellEnv ?? process.env) };\n for (const name of binding.remove ?? []) delete environment[name];\n Object.assign(environment, binding.variables, binding.secrets);\n }\n const argv = process.platform === 'win32' ? ['/d', '/s', '/c', command] : ['-c', command];\n const pending = executeCommand({\n capacity: this.#capacity,\n executable: this.#shellPath,\n args: argv,\n cwd: resolve(this.cwd, options?.cwd ?? this.cwd),\n environment,\n outputRedactor:\n binding?.secrets === undefined ? undefined : new StreamingOutputRedactor(binding.secrets),\n options: { ...options, abortSignal },\n });\n this.#pending.set(controller, pending);\n try {\n return await pending;\n } finally {\n this.#pending.delete(controller);\n }\n }\n\n async cleanup(): Promise<void> {\n this.#closed = true;\n for (const controller of this.#pending.keys()) controller.abort();\n await Promise.allSettled(this.#pending.values());\n }\n\n async #openForRead(path: string): Promise<FileHandle> {\n if (!this.#rejectSymlinkReads) return open(path, constants.O_RDONLY);\n // Darwin's O_NOFOLLOW_ANY rejects symlinks in every component at open.\n if (process.platform === 'darwin') return open(path, constants.O_RDONLY | 0x20000000);\n if (process.platform !== 'linux')\n throw new FileError('not_supported', 'Symlink-safe sandbox reads are unavailable', path);\n\n // Pin each directory before opening its child, so replacing an ancestor cannot redirect the read.\n const components = path.split('/').filter(Boolean);\n let directory = await open('/', constants.O_RDONLY | constants.O_DIRECTORY);\n try {\n for (const component of components.slice(0, -1)) {\n const child = await open(\n `/proc/self/fd/${directory.fd}/${component}`,\n constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW\n );\n await directory.close();\n directory = child;\n }\n const leaf = components.at(-1);\n return await open(\n leaf === undefined\n ? `/proc/self/fd/${directory.fd}/.`\n : `/proc/self/fd/${directory.fd}/${leaf}`,\n constants.O_RDONLY | constants.O_NOFOLLOW\n );\n } finally {\n await directory.close();\n }\n }\n\n #metadata(path: string, stats: Stats): FileInfo {\n let kind: FileInfo['kind'];\n if (stats.isFile()) kind = 'file';\n else if (stats.isDirectory()) kind = 'directory';\n else if (stats.isSymbolicLink()) kind = 'symlink';\n else throw new FileError('not_supported', 'Unsupported filesystem object', path);\n return { name: basename(path), path, kind, size: stats.size, mtimeMs: stats.mtimeMs };\n }\n\n async #file<Value>(\n path: string,\n options: FileExecutionOptions | undefined,\n run: (absolute: string, invocation: FileExecutionOptions) => Promise<Value>\n ): Promise<Result<Value, FileError>> {\n if (this.#closed) return err(new FileError('aborted', 'Execution environment is closed', path));\n const controller = new AbortController();\n const abortSignal =\n options?.abortSignal === undefined\n ? controller.signal\n : AbortSignal.any([controller.signal, options.abortSignal]);\n const pending = this.#runFile(path, { ...options, abortSignal }, run);\n this.#pending.set(controller, pending);\n try {\n return await pending;\n } finally {\n this.#pending.delete(controller);\n }\n }\n\n async #runFile<Value>(\n path: string,\n options: FileExecutionOptions | undefined,\n run: (absolute: string, invocation: FileExecutionOptions) => Promise<Value>\n ): Promise<Result<Value, FileError>> {\n let absolute = resolve(this.cwd, path);\n try {\n if (path.startsWith('file://')) absolute = fileURLToPath(path);\n options?.abortSignal?.throwIfAborted();\n await options?.beforeStart?.();\n if (this.#closed)\n return err(new FileError('aborted', 'Execution environment is closed', absolute));\n options?.abortSignal?.throwIfAborted();\n return ok(await run(absolute, options ?? {}));\n } catch (cause) {\n if (cause instanceof FileError) return err(cause);\n const error = toError(cause);\n const code = check(NodeFailureSchema, cause) ? cause.code : undefined;\n const failureCode = options?.abortSignal?.aborted\n ? 'aborted'\n : (FILE_FAILURE_CODES.get(code ?? '') ?? 'unknown');\n return err(new FileError(failureCode, error.message, absolute, error));\n }\n }\n}\n","import * as Context from 'effect/Context';\nimport type { ExecutionEnvironmentProvider } from './contracts.js';\n\n/** Borrowed by one mounted Tool group; the Provider owns cleanup and sandbox policy. */\nexport const ExecutionEnvironment = /* @__PURE__ */ Context.Service<ExecutionEnvironmentProvider>(\n 'sorbet/tools-node/ExecutionEnvironment/v1'\n);\n","import * as s from '@earendil-works/pi-schema';\nimport { decode } from '@sorbetai/schema';\nimport * as Effect from 'effect/Effect';\nimport * as Exit from 'effect/Exit';\nimport * as Scope from 'effect/Scope';\nimport * as Semaphore from 'effect/Semaphore';\n\n/** Shared by local environments; waiting is cancellable and never launches a process. */\nexport class ProcessCapacity {\n readonly #permits: Semaphore.Semaphore;\n constructor(maximum = 32) {\n this.#permits = Semaphore.makeUnsafe(\n decode(s.int({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }), maximum)\n );\n }\n /** Return the permit only after the owned process and its cleanup have settled. */\n async take(signal?: AbortSignal): Promise<() => Promise<void>> {\n const scope = Scope.makeUnsafe();\n try {\n await Effect.runPromise(\n Effect.uninterruptibleMask((restore) =>\n restore(this.#permits.take(1)).pipe(\n Effect.andThen(Scope.addFinalizer(scope, this.#permits.release(1)))\n )\n ),\n { signal }\n );\n return () => Effect.runPromise(Scope.close(scope, Exit.void));\n } catch (cause) {\n await Effect.runPromise(Scope.close(scope, Exit.void));\n throw cause;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAgB,GAAU,OAA4D;AACpF,QAAO;EAAE,IAAI;EAAM;EAAO;;AAG5B,SAAgB,IAAa,OAAiE;AAC5F,QAAO;EAAE,IAAI;EAAO;EAAO;;AAG7B,SAAgB,WAA2B,QAAuC;AAChF,KAAI,CAAC,OAAO,GAAI,OAAM,OAAO;AAC7B,QAAO,OAAO;;AAgBhB,IAAa,YAAb,cAA+B,MAAM;CACnC,AAAS;CACT,AAAS;CAET,YAAY,MAAqB,SAAiB,MAAe,OAAe;AAC9E,QAAM,SAAS,EAAE,OAAO,CAAC;AACzB,OAAK,OAAO;AACZ,OAAK,OAAO;AACZ,OAAK,OAAO;;;AAahB,IAAa,iBAAb,cAAoC,MAAM;CACxC,AAAS;;;;CAKT,AAAS;CAET,YACE,MACA,SACA,OACA,QACA;AACA,QAAM,SAAS,EAAE,OAAO,CAAC;AACzB,OAAK,OAAO;AACZ,OAAK,OAAO;AACZ,OAAK,SAAS;;;;;;ACzDlB,MAAM,MAAM,EAAE,IAAI,EAAE,SAAS,GAAG,CAAC;AACjC,MAAM,eAAe,EAAE,IACrB;CACE,KAAK;CACL,M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