@earendil-works/pi-agent-core 0.85.1 → 0.86.0

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.
Files changed (198) hide show
  1. package/README.md +16 -6
  2. package/dist/agent-loop.d.ts.map +1 -1
  3. package/dist/agent-loop.js +64 -22
  4. package/dist/agent-loop.js.map +1 -1
  5. package/dist/agent.d.ts +5 -3
  6. package/dist/agent.d.ts.map +1 -1
  7. package/dist/agent.js +15 -6
  8. package/dist/agent.js.map +1 -1
  9. package/dist/harness/config.d.ts +1 -1
  10. package/dist/harness/config.d.ts.map +1 -1
  11. package/dist/harness/config.js +10 -2
  12. package/dist/harness/config.js.map +1 -1
  13. package/dist/harness/env/nodejs.d.ts +2 -1
  14. package/dist/harness/env/nodejs.d.ts.map +1 -1
  15. package/dist/harness/env/nodejs.js +98 -27
  16. package/dist/harness/env/nodejs.js.map +1 -1
  17. package/dist/harness/execution/tools.d.ts +1 -1
  18. package/dist/harness/execution/tools.d.ts.map +1 -1
  19. package/dist/harness/execution/tools.js +0 -2
  20. package/dist/harness/execution/tools.js.map +1 -1
  21. package/dist/harness/messages.d.ts.map +1 -1
  22. package/dist/harness/messages.js +1 -0
  23. package/dist/harness/messages.js.map +1 -1
  24. package/dist/harness/pico3/bash.d.ts +10 -0
  25. package/dist/harness/pico3/bash.d.ts.map +1 -0
  26. package/dist/harness/pico3/bash.js +25 -0
  27. package/dist/harness/pico3/bash.js.map +1 -0
  28. package/dist/harness/pico3/bounded.d.ts +21 -0
  29. package/dist/harness/pico3/bounded.d.ts.map +1 -0
  30. package/dist/harness/pico3/bounded.js +98 -0
  31. package/dist/harness/pico3/bounded.js.map +1 -0
  32. package/dist/harness/pico3/chord.d.ts +41 -0
  33. package/dist/harness/pico3/chord.d.ts.map +1 -0
  34. package/dist/harness/pico3/chord.js +130 -0
  35. package/dist/harness/pico3/chord.js.map +1 -0
  36. package/dist/harness/pico3/context.d.ts +16 -0
  37. package/dist/harness/pico3/context.d.ts.map +1 -0
  38. package/dist/harness/pico3/context.js +88 -0
  39. package/dist/harness/pico3/context.js.map +1 -0
  40. package/dist/harness/pico3/harness.d.ts +197 -0
  41. package/dist/harness/pico3/harness.d.ts.map +1 -0
  42. package/dist/harness/pico3/harness.js +654 -0
  43. package/dist/harness/pico3/harness.js.map +1 -0
  44. package/dist/harness/pico3/hooks.d.ts +10 -0
  45. package/dist/harness/pico3/hooks.d.ts.map +1 -0
  46. package/dist/harness/pico3/hooks.js +33 -0
  47. package/dist/harness/pico3/hooks.js.map +1 -0
  48. package/dist/harness/pico3/index.d.ts +19 -0
  49. package/dist/harness/pico3/index.d.ts.map +1 -0
  50. package/dist/harness/pico3/index.js +15 -0
  51. package/dist/harness/pico3/index.js.map +1 -0
  52. package/dist/harness/pico3/jsonl.d.ts +58 -0
  53. package/dist/harness/pico3/jsonl.d.ts.map +1 -0
  54. package/dist/harness/pico3/jsonl.js +325 -0
  55. package/dist/harness/pico3/jsonl.js.map +1 -0
  56. package/dist/harness/pico3/kinds/collapse.d.ts +49 -0
  57. package/dist/harness/pico3/kinds/collapse.d.ts.map +1 -0
  58. package/dist/harness/pico3/kinds/collapse.js +191 -0
  59. package/dist/harness/pico3/kinds/collapse.js.map +1 -0
  60. package/dist/harness/pico3/kinds/entries.d.ts +78 -0
  61. package/dist/harness/pico3/kinds/entries.d.ts.map +1 -0
  62. package/dist/harness/pico3/kinds/entries.js +13 -0
  63. package/dist/harness/pico3/kinds/entries.js.map +1 -0
  64. package/dist/harness/pico3/kinds/frames.d.ts +9 -0
  65. package/dist/harness/pico3/kinds/frames.d.ts.map +1 -0
  66. package/dist/harness/pico3/kinds/frames.js +75 -0
  67. package/dist/harness/pico3/kinds/frames.js.map +1 -0
  68. package/dist/harness/pico3/kinds/generation.d.ts +94 -0
  69. package/dist/harness/pico3/kinds/generation.d.ts.map +1 -0
  70. package/dist/harness/pico3/kinds/generation.js +504 -0
  71. package/dist/harness/pico3/kinds/generation.js.map +1 -0
  72. package/dist/harness/pico3/kinds/job.d.ts +44 -0
  73. package/dist/harness/pico3/kinds/job.d.ts.map +1 -0
  74. package/dist/harness/pico3/kinds/job.js +143 -0
  75. package/dist/harness/pico3/kinds/job.js.map +1 -0
  76. package/dist/harness/pico3/kinds/plugin.d.ts +15 -0
  77. package/dist/harness/pico3/kinds/plugin.d.ts.map +1 -0
  78. package/dist/harness/pico3/kinds/plugin.js +35 -0
  79. package/dist/harness/pico3/kinds/plugin.js.map +1 -0
  80. package/dist/harness/pico3/kinds/post-tools.d.ts +22 -0
  81. package/dist/harness/pico3/kinds/post-tools.d.ts.map +1 -0
  82. package/dist/harness/pico3/kinds/post-tools.js +145 -0
  83. package/dist/harness/pico3/kinds/post-tools.js.map +1 -0
  84. package/dist/harness/pico3/kinds/task-api.d.ts +3 -0
  85. package/dist/harness/pico3/kinds/task-api.d.ts.map +1 -0
  86. package/dist/harness/pico3/kinds/task-api.js +45 -0
  87. package/dist/harness/pico3/kinds/task-api.js.map +1 -0
  88. package/dist/harness/pico3/kinds/tool.d.ts +43 -0
  89. package/dist/harness/pico3/kinds/tool.d.ts.map +1 -0
  90. package/dist/harness/pico3/kinds/tool.js +373 -0
  91. package/dist/harness/pico3/kinds/tool.js.map +1 -0
  92. package/dist/harness/pico3/membrane.d.ts +23 -0
  93. package/dist/harness/pico3/membrane.d.ts.map +1 -0
  94. package/dist/harness/pico3/membrane.js +141 -0
  95. package/dist/harness/pico3/membrane.js.map +1 -0
  96. package/dist/harness/pico3/memory.d.ts +53 -0
  97. package/dist/harness/pico3/memory.d.ts.map +1 -0
  98. package/dist/harness/pico3/memory.js +264 -0
  99. package/dist/harness/pico3/memory.js.map +1 -0
  100. package/dist/harness/pico3/scheduler.d.ts +46 -0
  101. package/dist/harness/pico3/scheduler.d.ts.map +1 -0
  102. package/dist/harness/pico3/scheduler.js +438 -0
  103. package/dist/harness/pico3/scheduler.js.map +1 -0
  104. package/dist/harness/pico3/session.d.ts +263 -0
  105. package/dist/harness/pico3/session.d.ts.map +1 -0
  106. package/dist/harness/pico3/session.js +1347 -0
  107. package/dist/harness/pico3/session.js.map +1 -0
  108. package/dist/harness/pico3/system.d.ts +126 -0
  109. package/dist/harness/pico3/system.d.ts.map +1 -0
  110. package/dist/harness/pico3/system.js +244 -0
  111. package/dist/harness/pico3/system.js.map +1 -0
  112. package/dist/harness/pico3/types.d.ts +973 -0
  113. package/dist/harness/pico3/types.d.ts.map +1 -0
  114. package/dist/harness/pico3/types.js +96 -0
  115. package/dist/harness/pico3/types.js.map +1 -0
  116. package/dist/harness/pico3/view.d.ts +34 -0
  117. package/dist/harness/pico3/view.d.ts.map +1 -0
  118. package/dist/harness/pico3/view.js +417 -0
  119. package/dist/harness/pico3/view.js.map +1 -0
  120. package/dist/harness/runtime/drive/boundary.d.ts.map +1 -1
  121. package/dist/harness/runtime/drive/boundary.js +6 -3
  122. package/dist/harness/runtime/drive/boundary.js.map +1 -1
  123. package/dist/harness/runtime/drive/response.d.ts.map +1 -1
  124. package/dist/harness/runtime/drive/response.js +4 -4
  125. package/dist/harness/runtime/drive/response.js.map +1 -1
  126. package/dist/harness/runtime/drive/retry.d.ts +2 -2
  127. package/dist/harness/runtime/drive/retry.d.ts.map +1 -1
  128. package/dist/harness/runtime/drive/retry.js +3 -6
  129. package/dist/harness/runtime/drive/retry.js.map +1 -1
  130. package/dist/harness/runtime/drive/structural.d.ts.map +1 -1
  131. package/dist/harness/runtime/drive/structural.js +5 -5
  132. package/dist/harness/runtime/drive/structural.js.map +1 -1
  133. package/dist/harness/runtime/drive/tool-placement.d.ts.map +1 -1
  134. package/dist/harness/runtime/drive/tool-placement.js +2 -27
  135. package/dist/harness/runtime/drive/tool-placement.js.map +1 -1
  136. package/dist/harness/runtime/drive/tools.d.ts.map +1 -1
  137. package/dist/harness/runtime/drive/tools.js.map +1 -1
  138. package/dist/harness/session/fork-policy.d.ts +20 -12
  139. package/dist/harness/session/fork-policy.d.ts.map +1 -1
  140. package/dist/harness/session/fork-policy.js +45 -12
  141. package/dist/harness/session/fork-policy.js.map +1 -1
  142. package/dist/harness/session/fork.d.ts +0 -2
  143. package/dist/harness/session/fork.d.ts.map +1 -1
  144. package/dist/harness/session/fork.js +20 -68
  145. package/dist/harness/session/fork.js.map +1 -1
  146. package/dist/harness/session/in-memory-storage-state.d.ts +5 -5
  147. package/dist/harness/session/in-memory-storage-state.d.ts.map +1 -1
  148. package/dist/harness/session/in-memory-storage-state.js +99 -39
  149. package/dist/harness/session/in-memory-storage-state.js.map +1 -1
  150. package/dist/harness/session/index.d.ts +1 -1
  151. package/dist/harness/session/index.d.ts.map +1 -1
  152. package/dist/harness/session/index.js +1 -1
  153. package/dist/harness/session/index.js.map +1 -1
  154. package/dist/harness/session/jsonl/fork.d.ts +38 -0
  155. package/dist/harness/session/jsonl/fork.d.ts.map +1 -0
  156. package/dist/harness/session/jsonl/fork.js +264 -0
  157. package/dist/harness/session/jsonl/fork.js.map +1 -0
  158. package/dist/harness/session/jsonl/io.d.ts +14 -0
  159. package/dist/harness/session/jsonl/io.d.ts.map +1 -0
  160. package/dist/harness/session/jsonl/io.js +86 -0
  161. package/dist/harness/session/jsonl/io.js.map +1 -0
  162. package/dist/harness/session/jsonl/legacy-v3.d.ts +33 -8
  163. package/dist/harness/session/jsonl/legacy-v3.d.ts.map +1 -1
  164. package/dist/harness/session/jsonl/legacy-v3.js +285 -206
  165. package/dist/harness/session/jsonl/legacy-v3.js.map +1 -1
  166. package/dist/harness/session/jsonl/repo.d.ts +2 -1
  167. package/dist/harness/session/jsonl/repo.d.ts.map +1 -1
  168. package/dist/harness/session/jsonl/repo.js +36 -20
  169. package/dist/harness/session/jsonl/repo.js.map +1 -1
  170. package/dist/harness/session/jsonl/storage.d.ts +4 -5
  171. package/dist/harness/session/jsonl/storage.d.ts.map +1 -1
  172. package/dist/harness/session/jsonl/storage.js +39 -113
  173. package/dist/harness/session/jsonl/storage.js.map +1 -1
  174. package/dist/harness/session/memory.d.ts +3 -5
  175. package/dist/harness/session/memory.d.ts.map +1 -1
  176. package/dist/harness/session/memory.js +9 -14
  177. package/dist/harness/session/memory.js.map +1 -1
  178. package/dist/harness/session/testing/conformance/session-repo.d.ts +2 -0
  179. package/dist/harness/session/testing/conformance/session-repo.d.ts.map +1 -1
  180. package/dist/harness/session/testing/conformance/session-repo.js +220 -1
  181. package/dist/harness/session/testing/conformance/session-repo.js.map +1 -1
  182. package/dist/harness/session/testing/index.d.ts +1 -1
  183. package/dist/harness/session/testing/index.d.ts.map +1 -1
  184. package/dist/harness/session/testing/index.js +1 -1
  185. package/dist/harness/session/testing/index.js.map +1 -1
  186. package/dist/harness/session/types.d.ts +1 -0
  187. package/dist/harness/session/types.d.ts.map +1 -1
  188. package/dist/harness/session/types.js.map +1 -1
  189. package/dist/harness/types.d.ts +14 -0
  190. package/dist/harness/types.d.ts.map +1 -1
  191. package/dist/harness/types.js.map +1 -1
  192. package/dist/proxy.d.ts +2 -2
  193. package/dist/proxy.d.ts.map +1 -1
  194. package/dist/proxy.js.map +1 -1
  195. package/dist/types.d.ts +30 -14
  196. package/dist/types.d.ts.map +1 -1
  197. package/dist/types.js.map +1 -1
  198. package/package.json +10 -6
@@ -1 +1 @@
1
- {"version":3,"file":"nodejs.d.ts","sourceRoot":"","sources":["../../../src/harness/env/nodejs.ts"],"names":[],"mappings":"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","sourcesContent":["import { type ChildProcess, spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { constants, createReadStream, createWriteStream, type WriteStream } from \"node:fs\";\nimport {\n\taccess,\n\tappendFile,\n\tlstat,\n\tmkdir,\n\tmkdtemp,\n\treaddir,\n\treadFile,\n\trealpath,\n\trename,\n\trm,\n\twriteFile,\n} from \"node:fs/promises\";\nimport { homedir, constants as osConstants, tmpdir } from \"node:os\";\nimport { basename, isAbsolute, join, resolve } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Context } from \"../context.ts\";\nimport {\n\ttype ExecutionEnv,\n\tExecutionError,\n\terr,\n\tFileError,\n\ttype FileInfo,\n\ttype FileKind,\n\tok,\n\ttype Result,\n\ttype ShellExecOptions,\n\ttype ShellExecResult,\n\ttoError,\n} from \"../types.ts\";\nimport { OutputCapture } from \"../utils/output-capture.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\nconst EXIT_STDIO_GRACE_MS = 100;\nconst SPILL_HIGH_WATER_MARK = 8 * 1024 * 1024;\n\ntype SpillChunk = string | Uint8Array;\n\nfunction resolveTimeoutMs(timeout: number | undefined): Result<number | undefined, ExecutionError> {\n\tif (timeout === undefined) return ok(undefined);\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\treturn err(new ExecutionError(\"timeout\", \"Invalid timeout: must be a finite number of seconds\"));\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\treturn err(new ExecutionError(\"timeout\", `Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`));\n\t}\n\treturn ok(timeoutMs);\n}\n\nfunction resolvePath(cwd: string, path: string): string {\n\tlet normalized = path;\n\tif (normalized === \"~\") {\n\t\tnormalized = homedir();\n\t} else if (normalized.startsWith(\"~/\") || (process.platform === \"win32\" && normalized.startsWith(\"~\\\\\"))) {\n\t\tnormalized = join(homedir(), normalized.slice(2));\n\t} else if (normalized.startsWith(\"file://\")) {\n\t\ttry {\n\t\t\tnormalized = fileURLToPath(normalized);\n\t\t} catch {\n\t\t\t// Keep malformed URLs as ordinary paths so filesystem methods preserve their non-throwing contract.\n\t\t}\n\t}\n\treturn isAbsolute(normalized) ? resolve(normalized) : resolve(cwd, normalized);\n}\n\nfunction fileKindFromStats(stats: {\n\tisFile(): boolean;\n\tisDirectory(): boolean;\n\tisSymbolicLink(): boolean;\n}): FileKind | undefined {\n\tif (stats.isFile()) return \"file\";\n\tif (stats.isDirectory()) return \"directory\";\n\tif (stats.isSymbolicLink()) return \"symlink\";\n\treturn undefined;\n}\n\nfunction fileInfoFromStats(\n\tpath: string,\n\tstats: { isFile(): boolean; isDirectory(): boolean; isSymbolicLink(): boolean; size: number; mtimeMs: number },\n): Result<FileInfo, FileError> {\n\tconst kind = fileKindFromStats(stats);\n\tif (!kind) return err(new FileError(\"invalid\", \"Unsupported file type\", path));\n\treturn ok({\n\t\tname: basename(path),\n\t\tpath,\n\t\tkind,\n\t\tsize: stats.size,\n\t\tmtimeMs: stats.mtimeMs,\n\t});\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n\treturn error instanceof Error && \"code\" in error;\n}\n\nfunction toFileError(error: unknown, fallbackPath?: string): FileError {\n\tif (error instanceof FileError) return error;\n\tconst cause = toError(error);\n\tconst nodeError = isNodeError(error) ? error : undefined;\n\tconst path = typeof nodeError?.path === \"string\" ? nodeError.path : fallbackPath;\n\tif (nodeError) {\n\t\tconst message = nodeError.message;\n\t\tswitch (nodeError.code) {\n\t\t\tcase \"ABORT_ERR\":\n\t\t\t\treturn new FileError(\"aborted\", message, path, cause);\n\t\t\tcase \"ENOENT\":\n\t\t\t\treturn new FileError(\"not_found\", message, path, cause);\n\t\t\tcase \"EACCES\":\n\t\t\tcase \"EPERM\":\n\t\t\t\treturn new FileError(\"permission_denied\", message, path, cause);\n\t\t\tcase \"ENOTDIR\":\n\t\t\t\treturn new FileError(\"not_directory\", message, path, cause);\n\t\t\tcase \"EISDIR\":\n\t\t\t\treturn new FileError(\"is_directory\", message, path, cause);\n\t\t\tcase \"EINVAL\":\n\t\t\t\treturn new FileError(\"invalid\", message, path, cause);\n\t\t}\n\t}\n\treturn new FileError(\"unknown\", cause.message, path, cause);\n}\n\nfunction abortResult<TValue>(signal: AbortSignal | undefined, path?: string): Result<TValue, FileError> | undefined {\n\treturn signal?.aborted ? err(new FileError(\"aborted\", \"aborted\", path)) : undefined;\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n\ttry {\n\t\tawait access(path, constants.F_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nasync function runCommand(\n\tcommand: string,\n\targs: string[],\n\ttimeoutMs: number,\n): Promise<{ stdout: string; status: number | null }> {\n\treturn await new Promise((resolve) => {\n\t\tlet stdout = \"\";\n\t\tlet child: ReturnType<typeof spawn>;\n\t\ttry {\n\t\t\tchild = spawn(command, args, {\n\t\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t} catch {\n\t\t\tresolve({ stdout: \"\", status: null });\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(() => {\n\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t}, timeoutMs);\n\t\tchild.stdout?.setEncoding(\"utf8\");\n\t\tchild.stdout?.on(\"data\", (chunk: string) => {\n\t\t\tstdout += chunk;\n\t\t});\n\t\tchild.on(\"error\", () => {\n\t\t\tclearTimeout(timeout);\n\t\t\tresolve({ stdout: \"\", status: null });\n\t\t});\n\t\tchild.on(\"close\", (status) => {\n\t\t\tclearTimeout(timeout);\n\t\t\tresolve({ stdout, status });\n\t\t});\n\t});\n}\n\nasync function findBashOnPath(): Promise<string | null> {\n\tconst result =\n\t\tprocess.platform === \"win32\"\n\t\t\t? await runCommand(\"where\", [\"bash.exe\"], 5000)\n\t\t\t: await runCommand(\"which\", [\"bash\"], 5000);\n\tif (result.status !== 0 || !result.stdout) return null;\n\tconst firstMatch = result.stdout.trim().split(/\\r?\\n/)[0];\n\treturn firstMatch && (await pathExists(firstMatch)) ? firstMatch : null;\n}\n\ninterface ShellConfig {\n\tshell: string;\n\targs: string[];\n\tcommandTransport?: \"argv\" | \"stdin\";\n}\n\nfunction isLegacyWslBashPath(path: string): boolean {\n\tconst normalized = path.replace(/\\//g, \"\\\\\").toLowerCase();\n\treturn /^[a-z]:\\\\windows\\\\(?:system32|sysnative)\\\\bash\\.exe$/.test(normalized);\n}\n\nfunction getBashShellConfig(shell: string): ShellConfig {\n\treturn isLegacyWslBashPath(shell) ? { shell, args: [\"-s\"], commandTransport: \"stdin\" } : { shell, args: [\"-c\"] };\n}\n\nasync function getShellConfig(customShellPath?: string): Promise<Result<ShellConfig, ExecutionError>> {\n\tif (customShellPath) {\n\t\tif (await pathExists(customShellPath)) {\n\t\t\treturn ok(getBashShellConfig(customShellPath));\n\t\t}\n\t\treturn err(new ExecutionError(\"shell_unavailable\", `Custom shell path not found: ${customShellPath}`));\n\t}\n\tif (process.platform === \"win32\") {\n\t\tconst candidates: string[] = [];\n\t\tconst programFiles = process.env.ProgramFiles;\n\t\tif (programFiles) candidates.push(`${programFiles}\\\\Git\\\\bin\\\\bash.exe`);\n\t\tconst programFilesX86 = process.env[\"ProgramFiles(x86)\"];\n\t\tif (programFilesX86) candidates.push(`${programFilesX86}\\\\Git\\\\bin\\\\bash.exe`);\n\t\tfor (const candidate of candidates) {\n\t\t\tif (await pathExists(candidate)) {\n\t\t\t\treturn ok(getBashShellConfig(candidate));\n\t\t\t}\n\t\t}\n\t\tconst bashOnPath = await findBashOnPath();\n\t\tif (bashOnPath) {\n\t\t\treturn ok(getBashShellConfig(bashOnPath));\n\t\t}\n\t\treturn err(\n\t\t\tnew ExecutionError(\n\t\t\t\t\"shell_unavailable\",\n\t\t\t\t`No bash shell found. Options:\\n` +\n\t\t\t\t\t` 1. Install Git for Windows: https://git-scm.com/download/win\\n` +\n\t\t\t\t\t` 2. Add your bash to PATH (Cygwin, MSYS2, etc.)\\n` +\n\t\t\t\t\t\" 3. Configure an explicit shellPath\\n\\n\" +\n\t\t\t\t\t`Searched Git Bash in:\\n${candidates.map((path) => ` ${path}`).join(\"\\n\")}`,\n\t\t\t),\n\t\t);\n\t}\n\n\tif (await pathExists(\"/bin/bash\")) {\n\t\treturn ok(getBashShellConfig(\"/bin/bash\"));\n\t}\n\tconst bashOnPath = await findBashOnPath();\n\tif (bashOnPath) {\n\t\treturn ok(getBashShellConfig(bashOnPath));\n\t}\n\treturn ok({ shell: \"sh\", args: [\"-c\"] });\n}\n\nfunction getShellEnv(\n\tbaseEnv?: NodeJS.ProcessEnv,\n\textraEnv?: Record<string, string>,\n\tinheritEnv = true,\n): NodeJS.ProcessEnv {\n\tif (!inheritEnv) return { ...extraEnv };\n\treturn {\n\t\t...process.env,\n\t\t...baseEnv,\n\t\t...extraEnv,\n\t};\n}\n\nfunction killProcessTree(pid: number): void {\n\tif (process.platform === \"win32\") {\n\t\ttry {\n\t\t\tconst child = spawn(\n\t\t\t\tjoin(process.env.SystemRoot ?? \"C:\\\\Windows\", \"System32\", \"taskkill.exe\"),\n\t\t\t\t[\"/F\", \"/T\", \"/PID\", String(pid)],\n\t\t\t\t{\n\t\t\t\t\tstdio: \"ignore\",\n\t\t\t\t\tdetached: true,\n\t\t\t\t\twindowsHide: true,\n\t\t\t\t},\n\t\t\t);\n\t\t\t// A failed spawn emits \"error\" asynchronously; consume it to avoid crashing Node.\n\t\t\tchild.once(\"error\", () => {});\n\t\t} catch {\n\t\t\t// Ignore errors.\n\t\t}\n\t\treturn;\n\t}\n\n\ttry {\n\t\tprocess.kill(-pid, \"SIGKILL\");\n\t} catch {\n\t\ttry {\n\t\t\tprocess.kill(pid, \"SIGKILL\");\n\t\t} catch {\n\t\t\t// Process already dead.\n\t\t}\n\t}\n}\n\nfunction waitForChildProcess(\n\tchild: ChildProcess,\n\tspillIsDraining: () => boolean,\n): Promise<{ code: number | null; signal: NodeJS.Signals | null }> {\n\treturn new Promise((resolvePromise, reject) => {\n\t\tlet settled = false;\n\t\tlet exited = false;\n\t\tlet exitCode: number | null = null;\n\t\tlet exitSignal: NodeJS.Signals | null = null;\n\t\tlet postExitTimer: ReturnType<typeof setTimeout> | undefined;\n\t\tlet stdoutEnded = child.stdout === null;\n\t\tlet stderrEnded = child.stderr === null;\n\n\t\tconst cleanup = (): void => {\n\t\t\tif (postExitTimer) clearTimeout(postExitTimer);\n\t\t\tchild.removeListener(\"error\", onError);\n\t\t\tchild.removeListener(\"exit\", onExit);\n\t\t\tchild.removeListener(\"close\", onClose);\n\t\t\tchild.stdout?.removeListener(\"end\", onStdoutEnd);\n\t\t\tchild.stderr?.removeListener(\"end\", onStderrEnd);\n\t\t\tchild.stdout?.removeListener(\"data\", onData);\n\t\t\tchild.stderr?.removeListener(\"data\", onData);\n\t\t};\n\t\tconst finalize = (): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tchild.stdout?.destroy();\n\t\t\tchild.stderr?.destroy();\n\t\t\tresolvePromise({ code: exitCode, signal: exitSignal });\n\t\t};\n\t\tconst maybeFinalizeAfterExit = (): void => {\n\t\t\tif (exited && stdoutEnded && stderrEnded) finalize();\n\t\t};\n\t\tconst armIdleTimer = (): void => {\n\t\t\tif (postExitTimer) clearTimeout(postExitTimer);\n\t\t\tpostExitTimer = setTimeout(() => {\n\t\t\t\tif (spillIsDraining()) armIdleTimer();\n\t\t\t\telse finalize();\n\t\t\t}, EXIT_STDIO_GRACE_MS);\n\t\t};\n\t\tconst onData = (): void => {\n\t\t\tif (exited && !settled) armIdleTimer();\n\t\t};\n\t\tconst onStdoutEnd = (): void => {\n\t\t\tstdoutEnded = true;\n\t\t\tmaybeFinalizeAfterExit();\n\t\t};\n\t\tconst onStderrEnd = (): void => {\n\t\t\tstderrEnded = true;\n\t\t\tmaybeFinalizeAfterExit();\n\t\t};\n\t\tconst onError = (error: Error): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\treject(error);\n\t\t};\n\t\tconst onExit = (code: number | null, signal: NodeJS.Signals | null): void => {\n\t\t\texited = true;\n\t\t\texitCode = code;\n\t\t\texitSignal = signal;\n\t\t\tmaybeFinalizeAfterExit();\n\t\t\tif (!settled) armIdleTimer();\n\t\t};\n\t\tconst onClose = (code: number | null, signal: NodeJS.Signals | null): void => {\n\t\t\texitCode = code;\n\t\t\texitSignal = signal;\n\t\t\tfinalize();\n\t\t};\n\n\t\tchild.stdout?.once(\"end\", onStdoutEnd);\n\t\tchild.stderr?.once(\"end\", onStderrEnd);\n\t\tchild.stdout?.on(\"data\", onData);\n\t\tchild.stderr?.on(\"data\", onData);\n\t\tchild.once(\"error\", onError);\n\t\tchild.once(\"exit\", onExit);\n\t\tchild.once(\"close\", onClose);\n\t});\n}\n\nexport class NodeExecutionEnv implements ExecutionEnv {\n\tcwd: string;\n\tprivate shellPath?: string;\n\tprivate shellEnv?: NodeJS.ProcessEnv;\n\tprivate activeChildPids = new Set<number>();\n\n\tconstructor(options: { cwd: string; shellPath?: string; shellEnv?: NodeJS.ProcessEnv }) {\n\t\tthis.cwd = options.cwd;\n\t\tthis.shellPath = options.shellPath;\n\t\tthis.shellEnv = options.shellEnv;\n\t}\n\n\tasync absolutePath(path: string, _context: Context): Promise<Result<string, FileError>> {\n\t\treturn ok(resolvePath(this.cwd, path));\n\t}\n\n\tasync joinPath(parts: string[], _context: Context): Promise<Result<string, FileError>> {\n\t\treturn ok(join(...parts));\n\t}\n\n\tasync exec(\n\t\tcommand: string,\n\t\toptions: ShellExecOptions | undefined,\n\t\tcontext: Context,\n\t): Promise<Result<ShellExecResult, ExecutionError>> {\n\t\tconst signal = context.abortSignal;\n\t\tif (signal?.aborted) return err(new ExecutionError(\"aborted\", \"aborted\"));\n\t\tconst timeoutMsResult = resolveTimeoutMs(options?.timeout);\n\t\tif (!timeoutMsResult.ok) return err(timeoutMsResult.error);\n\t\tconst timeoutMs = timeoutMsResult.value;\n\n\t\tconst cwd = options?.cwd ? resolvePath(this.cwd, options.cwd) : this.cwd;\n\t\tconst shellConfig = await getShellConfig(this.shellPath);\n\t\tif (!shellConfig.ok) return shellConfig;\n\t\ttry {\n\t\t\tawait access(cwd, constants.F_OK);\n\t\t} catch (error) {\n\t\t\tconst cause = toError(error);\n\t\t\treturn err(\n\t\t\t\tnew ExecutionError(\n\t\t\t\t\t\"spawn_error\",\n\t\t\t\t\t`Working directory does not exist: ${cwd}\\nCannot execute bash commands.`,\n\t\t\t\t\tcause,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\treturn await new Promise((resolvePromise) => {\n\t\t\tlet settled = false;\n\t\t\tlet timedOut = false;\n\t\t\tlet callbackError: ExecutionError | undefined;\n\t\t\tlet spillError: ExecutionError | undefined;\n\t\t\tlet child: ReturnType<typeof spawn> | undefined;\n\t\t\tlet timeoutId: ReturnType<typeof setTimeout> | undefined;\n\t\t\tconst spillPrefix: SpillChunk[] = [];\n\t\t\tlet spillPath: string | undefined;\n\t\t\tconst spillQueue: SpillChunk[] = [];\n\t\t\tlet spillStart: Promise<void> | undefined;\n\t\t\tlet spillStream: WriteStream | undefined;\n\t\t\tlet spillBackpressured = false;\n\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child?.pid) killProcessTree(child.pid);\n\t\t\t};\n\t\t\tconst failCallback = (error: unknown) => {\n\t\t\t\tif (callbackError !== undefined) return;\n\t\t\t\tconst cause = toError(error);\n\t\t\t\tcallbackError = new ExecutionError(\"callback_error\", cause.message, cause);\n\t\t\t\tonAbort();\n\t\t\t};\n\t\t\tlet capture: OutputCapture;\n\t\t\ttry {\n\t\t\t\tcapture = new OutputCapture(options?.capture, context, {\n\t\t\t\t\tonUpdate: options?.onUpdate,\n\t\t\t\t\tonError: failCallback,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tconst cause = toError(error);\n\t\t\t\tresolvePromise(err(new ExecutionError(\"unknown\", cause.message, cause)));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst settle = (result: Result<ShellExecResult, ExecutionError>) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tif (timeoutId) clearTimeout(timeoutId);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t\tif (child?.pid) this.activeChildPids.delete(child.pid);\n\t\t\t\tcapture.dispose();\n\t\t\t\tresolvePromise(result);\n\t\t\t};\n\t\t\tconst pauseOutput = () => {\n\t\t\t\tchild?.stdout?.pause();\n\t\t\t\tchild?.stderr?.pause();\n\t\t\t};\n\t\t\tconst resumeOutput = () => {\n\t\t\t\tif (callbackError || spillError || timedOut || signal?.aborted || spillBackpressured) return;\n\t\t\t\tchild?.stdout?.resume();\n\t\t\t\tchild?.stderr?.resume();\n\t\t\t};\n\t\t\tconst failSpill = (error: unknown) => {\n\t\t\t\tif (spillError !== undefined) return;\n\t\t\t\tconst cause = toError(error);\n\t\t\t\tspillError = new ExecutionError(\n\t\t\t\t\t\"unknown\",\n\t\t\t\t\t`Failed to preserve complete shell output: ${cause.message}`,\n\t\t\t\t\tcause,\n\t\t\t\t);\n\t\t\t\tspillBackpressured = false;\n\t\t\t\tonAbort();\n\t\t\t};\n\t\t\tconst writeSpill = (chunk: SpillChunk): void => {\n\t\t\t\tif (spillStream === undefined || chunk.length === 0) return;\n\t\t\t\tif (spillStream.write(chunk) || spillBackpressured) return;\n\t\t\t\tspillBackpressured = true;\n\t\t\t\tpauseOutput();\n\t\t\t\tspillStream.once(\"drain\", () => {\n\t\t\t\t\tspillBackpressured = false;\n\t\t\t\t\tresumeOutput();\n\t\t\t\t});\n\t\t\t};\n\t\t\tconst startSpill = (chunk: SpillChunk): void => {\n\t\t\t\tif (spillStream !== undefined) {\n\t\t\t\t\twriteSpill(chunk);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tspillQueue.push(chunk);\n\t\t\t\tif (spillStart !== undefined) return;\n\t\t\t\tpauseOutput();\n\t\t\t\tspillStart = (async () => {\n\t\t\t\t\tconst created = await this.createTempFile({ prefix: \"pi-output-\", suffix: \".log\" }, context);\n\t\t\t\t\tif (!created.ok) throw created.error;\n\t\t\t\t\tspillPath = created.value;\n\t\t\t\t\tcapture.setSpillPath(spillPath);\n\t\t\t\t\tspillStream = createWriteStream(spillPath, { flags: \"a\", highWaterMark: SPILL_HIGH_WATER_MARK });\n\t\t\t\t\tspillStream.on(\"error\", failSpill);\n\t\t\t\t\tfor (const queued of spillQueue) writeSpill(queued);\n\t\t\t\t\tspillQueue.length = 0;\n\t\t\t\t})()\n\t\t\t\t\t.catch(failSpill)\n\t\t\t\t\t.finally(resumeOutput);\n\t\t\t};\n\t\t\tconst finishSpill = async (): Promise<void> => {\n\t\t\t\tawait spillStart;\n\t\t\t\tconst stream = spillStream;\n\t\t\t\tif (stream === undefined || spillError !== undefined || stream.destroyed) return;\n\t\t\t\tawait new Promise<void>((resolveFinish) => {\n\t\t\t\t\tstream.once(\"error\", () => resolveFinish());\n\t\t\t\t\tstream.once(\"finish\", resolveFinish);\n\t\t\t\t\tstream.end();\n\t\t\t\t});\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tconst commandFromStdin = shellConfig.value.commandTransport === \"stdin\";\n\t\t\t\tchild = spawn(\n\t\t\t\t\tshellConfig.value.shell,\n\t\t\t\t\tcommandFromStdin ? shellConfig.value.args : [...shellConfig.value.args, command],\n\t\t\t\t\t{\n\t\t\t\t\t\tcwd,\n\t\t\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\t\t\tenv: getShellEnv(this.shellEnv, options?.env, options?.inheritEnv),\n\t\t\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\t\t\twindowsHide: true,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tif (child.pid) this.activeChildPids.add(child.pid);\n\t\t\t\tif (commandFromStdin) {\n\t\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\t\tchild.stdin?.end(command);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconst cause = toError(error);\n\t\t\t\tsettle(err(new ExecutionError(\"spawn_error\", cause.message, cause)));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\ttimeoutId =\n\t\t\t\ttimeoutMs === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: setTimeout(() => {\n\t\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\t\tonAbort();\n\t\t\t\t\t\t}, timeoutMs);\n\n\t\t\tif (signal) {\n\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t}\n\n\t\t\tconst feed = (chunk: Uint8Array) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst wasTruncated = capture.truncated;\n\t\t\t\t\tcapture.push(chunk);\n\t\t\t\t\tif (!options?.capture?.spill || chunk.length === 0) return;\n\t\t\t\t\tif (spillPath !== undefined || wasTruncated) {\n\t\t\t\t\t\tstartSpill(chunk);\n\t\t\t\t\t} else if (capture.truncated) {\n\t\t\t\t\t\tfor (const prefix of spillPrefix) startSpill(prefix);\n\t\t\t\t\t\tspillPrefix.length = 0;\n\t\t\t\t\t\tstartSpill(chunk);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tspillPrefix.push(chunk);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfailCallback(error);\n\t\t\t\t}\n\t\t\t};\n\t\t\tchild.stdout?.on(\"data\", feed);\n\t\t\tchild.stderr?.on(\"data\", feed);\n\n\t\t\tvoid waitForChildProcess(\n\t\t\t\tchild,\n\t\t\t\t() =>\n\t\t\t\t\tspillError === undefined &&\n\t\t\t\t\tspillStart !== undefined &&\n\t\t\t\t\t(spillStream === undefined || spillBackpressured),\n\t\t\t).then(\n\t\t\t\tasync ({ code, signal: exitSignal }) => {\n\t\t\t\t\tawait finishSpill();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcapture.finish();\n\t\t\t\t\t\tcapture.flush();\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tfailCallback(error);\n\t\t\t\t\t}\n\t\t\t\t\tif (callbackError) {\n\t\t\t\t\t\tsettle(err(callbackError));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (timedOut) {\n\t\t\t\t\t\tsettle(err(new ExecutionError(\"timeout\", `timeout:${options?.timeout}`)));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\tsettle(err(new ExecutionError(\"aborted\", \"aborted\")));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (spillError) {\n\t\t\t\t\t\tsettle(err(spillError));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst output = capture.snapshot();\n\t\t\t\t\t// A process killed by a signal (e.g. OOM killer) has no exit code; map it\n\t\t\t\t\t// to the conventional 128 + signal number so callers do not mistake it\n\t\t\t\t\t// for a successful exit.\n\t\t\t\t\tconst exitCode = code ?? (exitSignal ? 128 + (osConstants.signals[exitSignal] ?? 0) : 1);\n\t\t\t\t\tsettle(\n\t\t\t\t\t\tok({\n\t\t\t\t\t\t\texitCode,\n\t\t\t\t\t\t\ttruncation: output.truncation,\n\t\t\t\t\t\t\t...(output.spillPath === undefined ? {} : { spillPath: output.spillPath }),\n\t\t\t\t\t\t\t...(output.lastLineBytes === undefined ? {} : { lastLineBytes: output.lastLineBytes }),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\t(error: Error) => settle(err(new ExecutionError(\"spawn_error\", error.message, error))),\n\t\t\t);\n\t\t});\n\t}\n\n\tasync readTextFile(path: string, context: Context): Promise<Result<string, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst signal = context.abortSignal;\n\t\tconst aborted = abortResult<string>(signal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\treturn ok(await readFile(resolved, { encoding: \"utf8\", signal }));\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync readTextLines(\n\t\tpath: string,\n\t\toptions: { maxLines?: number } | undefined,\n\t\tcontext: Context,\n\t): Promise<Result<string[], FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst signal = context.abortSignal;\n\t\tconst aborted = abortResult<string[]>(signal, resolved);\n\t\tif (aborted) return aborted;\n\t\tif (options?.maxLines !== undefined && options.maxLines <= 0) return ok([]);\n\t\tlet stream: ReturnType<typeof createReadStream> | undefined;\n\t\tlet lineReader: ReturnType<typeof createInterface> | undefined;\n\t\ttry {\n\t\t\tstream = createReadStream(resolved, { encoding: \"utf8\", signal });\n\t\t\tlineReader = createInterface({ input: stream, crlfDelay: Infinity });\n\t\t\tconst lines: string[] = [];\n\t\t\tfor await (const line of lineReader) {\n\t\t\t\tconst loopAbort = abortResult<string[]>(signal, resolved);\n\t\t\t\tif (loopAbort) return loopAbort;\n\t\t\t\tlines.push(line);\n\t\t\t\tif (options?.maxLines !== undefined && lines.length >= options.maxLines) break;\n\t\t\t}\n\t\t\tconst afterReadAbort = abortResult<string[]>(signal, resolved);\n\t\t\tif (afterReadAbort) return afterReadAbort;\n\t\t\treturn ok(lines);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t} finally {\n\t\t\tlineReader?.close();\n\t\t\tstream?.destroy();\n\t\t}\n\t}\n\n\tasync readBinaryFile(path: string, context: Context): Promise<Result<Uint8Array, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst signal = context.abortSignal;\n\t\tconst aborted = abortResult<Uint8Array>(signal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\treturn ok(await readFile(resolved, { signal }));\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync writeFile(path: string, content: string | Uint8Array, context: Context): Promise<Result<void, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst signal = context.abortSignal;\n\t\tconst aborted = abortResult<void>(signal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tawait mkdir(resolve(resolved, \"..\"), { recursive: true });\n\t\t\tconst afterMkdirAbort = abortResult<void>(signal, resolved);\n\t\t\tif (afterMkdirAbort) return afterMkdirAbort;\n\t\t\tawait writeFile(resolved, content, { signal });\n\t\t\treturn ok(undefined);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync appendFile(path: string, content: string | Uint8Array, context: Context): Promise<Result<void, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst signal = context.abortSignal;\n\t\tconst aborted = abortResult<void>(signal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tawait mkdir(resolve(resolved, \"..\"), { recursive: true });\n\t\t\tconst afterMkdirAbort = abortResult<void>(signal, resolved);\n\t\t\tif (afterMkdirAbort) return afterMkdirAbort;\n\t\t\tawait appendFile(resolved, content);\n\t\t\tconst afterAppendAbort = abortResult<void>(signal, resolved);\n\t\t\treturn afterAppendAbort ?? ok(undefined);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync renameFile(sourcePath: string, destinationPath: string, context: Context): Promise<Result<void, FileError>> {\n\t\tconst source = resolvePath(this.cwd, sourcePath);\n\t\tconst destination = resolvePath(this.cwd, destinationPath);\n\t\tconst aborted = abortResult<void>(context.abortSignal, destination);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tawait rename(source, destination);\n\t\t\treturn ok(undefined);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, source));\n\t\t}\n\t}\n\n\tasync fileInfo(path: string, context: Context): Promise<Result<FileInfo, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<FileInfo>(context.abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\treturn fileInfoFromStats(resolved, await lstat(resolved));\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync listDir(path: string, context: Context): Promise<Result<FileInfo[], FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst signal = context.abortSignal;\n\t\tconst aborted = abortResult<FileInfo[]>(signal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tconst entries = await readdir(resolved, { withFileTypes: true });\n\t\t\tconst infos: FileInfo[] = [];\n\t\t\tfor (const entry of entries) {\n\t\t\t\tconst loopAbort = abortResult<FileInfo[]>(signal, resolved);\n\t\t\t\tif (loopAbort) return loopAbort;\n\t\t\t\tconst entryPath = resolve(resolved, entry.name);\n\t\t\t\ttry {\n\t\t\t\t\tconst info = fileInfoFromStats(entryPath, await lstat(entryPath));\n\t\t\t\t\tif (info.ok) infos.push(info.value);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn err(toFileError(error, entryPath));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn ok(infos);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync canonicalPath(path: string, context: Context): Promise<Result<string, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<string>(context.abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\treturn ok(await realpath(resolved));\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync exists(path: string, context: Context): Promise<Result<boolean, FileError>> {\n\t\tconst result = await this.fileInfo(path, context);\n\t\tif (result.ok) return ok(true);\n\t\tif (result.error.code === \"not_found\") return ok(false);\n\t\treturn err(result.error);\n\t}\n\n\tasync createDir(\n\t\tpath: string,\n\t\toptions: { recursive?: boolean } | undefined,\n\t\tcontext: Context,\n\t): Promise<Result<void, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<void>(context.abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tawait mkdir(resolved, { recursive: options?.recursive ?? true });\n\t\t\treturn ok(undefined);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync remove(\n\t\tpath: string,\n\t\toptions: { recursive?: boolean; force?: boolean } | undefined,\n\t\tcontext: Context,\n\t): Promise<Result<void, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<void>(context.abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tawait rm(resolved, { recursive: options?.recursive ?? false, force: options?.force ?? false });\n\t\t\treturn ok(undefined);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync createTempDir(prefix: string | undefined, context: Context): Promise<Result<string, FileError>> {\n\t\tconst aborted = abortResult<string>(context.abortSignal);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tprefix ??= \"tmp-\";\n\t\t\treturn ok(await mkdtemp(join(tmpdir(), prefix)));\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error));\n\t\t}\n\t}\n\n\tasync createTempFile(\n\t\toptions: { prefix?: string; suffix?: string } | undefined,\n\t\tcontext: Context,\n\t): Promise<Result<string, FileError>> {\n\t\tconst dir = await this.createTempDir(\"tmp-\", context);\n\t\tif (!dir.ok) return dir;\n\t\tconst filePath = join(dir.value, `${options?.prefix ?? \"\"}${randomUUID()}${options?.suffix ?? \"\"}`);\n\t\ttry {\n\t\t\tawait writeFile(filePath, \"\");\n\t\t\treturn ok(filePath);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, filePath));\n\t\t}\n\t}\n\n\tasync cleanup(_context: Context): Promise<void> {\n\t\tfor (const pid of this.activeChildPids) killProcessTree(pid);\n\t\tthis.activeChildPids.clear();\n\t}\n}\n"]}
1
+ {"version":3,"file":"nodejs.d.ts","sourceRoot":"","sources":["../../../src/harness/env/nodejs.ts"],"names":[],"mappings":"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","sourcesContent":["import { type ChildProcess, spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { constants, createWriteStream, type WriteStream } from \"node:fs\";\nimport {\n\taccess,\n\tappendFile,\n\tlstat,\n\tmkdir,\n\tmkdtemp,\n\topen as openFile,\n\treaddir,\n\treadFile,\n\trealpath,\n\trename,\n\trm,\n\twriteFile,\n} from \"node:fs/promises\";\nimport { homedir, constants as osConstants, tmpdir } from \"node:os\";\nimport { basename, isAbsolute, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Context } from \"../context.ts\";\nimport {\n\ttype ExecutionEnv,\n\tExecutionError,\n\terr,\n\tFileError,\n\ttype FileInfo,\n\ttype FileKind,\n\tok,\n\ttype Result,\n\ttype ShellExecOptions,\n\ttype ShellExecResult,\n\ttype TextLine,\n\ttype TextLineReader,\n\ttoError,\n} from \"../types.ts\";\nimport { OutputCapture } from \"../utils/output-capture.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\nconst EXIT_STDIO_GRACE_MS = 100;\nconst SPILL_HIGH_WATER_MARK = 8 * 1024 * 1024;\n\ntype SpillChunk = string | Uint8Array;\n\nfunction resolveTimeoutMs(timeout: number | undefined): Result<number | undefined, ExecutionError> {\n\tif (timeout === undefined) return ok(undefined);\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\treturn err(new ExecutionError(\"timeout\", \"Invalid timeout: must be a finite number of seconds\"));\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\treturn err(new ExecutionError(\"timeout\", `Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`));\n\t}\n\treturn ok(timeoutMs);\n}\n\nfunction resolvePath(cwd: string, path: string): string {\n\tlet normalized = path;\n\tif (normalized === \"~\") {\n\t\tnormalized = homedir();\n\t} else if (normalized.startsWith(\"~/\") || (process.platform === \"win32\" && normalized.startsWith(\"~\\\\\"))) {\n\t\tnormalized = join(homedir(), normalized.slice(2));\n\t} else if (normalized.startsWith(\"file://\")) {\n\t\ttry {\n\t\t\tnormalized = fileURLToPath(normalized);\n\t\t} catch {\n\t\t\t// Keep malformed URLs as ordinary paths so filesystem methods preserve their non-throwing contract.\n\t\t}\n\t}\n\treturn isAbsolute(normalized) ? resolve(normalized) : resolve(cwd, normalized);\n}\n\nfunction fileKindFromStats(stats: {\n\tisFile(): boolean;\n\tisDirectory(): boolean;\n\tisSymbolicLink(): boolean;\n}): FileKind | undefined {\n\tif (stats.isFile()) return \"file\";\n\tif (stats.isDirectory()) return \"directory\";\n\tif (stats.isSymbolicLink()) return \"symlink\";\n\treturn undefined;\n}\n\nfunction fileInfoFromStats(\n\tpath: string,\n\tstats: { isFile(): boolean; isDirectory(): boolean; isSymbolicLink(): boolean; size: number; mtimeMs: number },\n): Result<FileInfo, FileError> {\n\tconst kind = fileKindFromStats(stats);\n\tif (!kind) return err(new FileError(\"invalid\", \"Unsupported file type\", path));\n\treturn ok({\n\t\tname: basename(path),\n\t\tpath,\n\t\tkind,\n\t\tsize: stats.size,\n\t\tmtimeMs: stats.mtimeMs,\n\t});\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n\treturn error instanceof Error && \"code\" in error;\n}\n\nfunction toFileError(error: unknown, fallbackPath?: string): FileError {\n\tif (error instanceof FileError) return error;\n\tconst cause = toError(error);\n\tconst nodeError = isNodeError(error) ? error : undefined;\n\tconst path = typeof nodeError?.path === \"string\" ? nodeError.path : fallbackPath;\n\tif (nodeError) {\n\t\tconst message = nodeError.message;\n\t\tswitch (nodeError.code) {\n\t\t\tcase \"ABORT_ERR\":\n\t\t\t\treturn new FileError(\"aborted\", message, path, cause);\n\t\t\tcase \"ENOENT\":\n\t\t\t\treturn new FileError(\"not_found\", message, path, cause);\n\t\t\tcase \"EACCES\":\n\t\t\tcase \"EPERM\":\n\t\t\t\treturn new FileError(\"permission_denied\", message, path, cause);\n\t\t\tcase \"ENOTDIR\":\n\t\t\t\treturn new FileError(\"not_directory\", message, path, cause);\n\t\t\tcase \"EISDIR\":\n\t\t\t\treturn new FileError(\"is_directory\", message, path, cause);\n\t\t\tcase \"EINVAL\":\n\t\t\t\treturn new FileError(\"invalid\", message, path, cause);\n\t\t}\n\t}\n\treturn new FileError(\"unknown\", cause.message, path, cause);\n}\n\nfunction abortResult<TValue>(signal: AbortSignal | undefined, path?: string): Result<TValue, FileError> | undefined {\n\treturn signal?.aborted ? err(new FileError(\"aborted\", \"aborted\", path)) : undefined;\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n\ttry {\n\t\tawait access(path, constants.F_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nasync function runCommand(\n\tcommand: string,\n\targs: string[],\n\ttimeoutMs: number,\n): Promise<{ stdout: string; status: number | null }> {\n\treturn await new Promise((resolve) => {\n\t\tlet stdout = \"\";\n\t\tlet child: ReturnType<typeof spawn>;\n\t\ttry {\n\t\t\tchild = spawn(command, args, {\n\t\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t} catch {\n\t\t\tresolve({ stdout: \"\", status: null });\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(() => {\n\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t}, timeoutMs);\n\t\tchild.stdout?.setEncoding(\"utf8\");\n\t\tchild.stdout?.on(\"data\", (chunk: string) => {\n\t\t\tstdout += chunk;\n\t\t});\n\t\tchild.on(\"error\", () => {\n\t\t\tclearTimeout(timeout);\n\t\t\tresolve({ stdout: \"\", status: null });\n\t\t});\n\t\tchild.on(\"close\", (status) => {\n\t\t\tclearTimeout(timeout);\n\t\t\tresolve({ stdout, status });\n\t\t});\n\t});\n}\n\nasync function findBashOnPath(): Promise<string | null> {\n\tconst result =\n\t\tprocess.platform === \"win32\"\n\t\t\t? await runCommand(\"where\", [\"bash.exe\"], 5000)\n\t\t\t: await runCommand(\"which\", [\"bash\"], 5000);\n\tif (result.status !== 0 || !result.stdout) return null;\n\tconst firstMatch = result.stdout.trim().split(/\\r?\\n/)[0];\n\treturn firstMatch && (await pathExists(firstMatch)) ? firstMatch : null;\n}\n\ninterface ShellConfig {\n\tshell: string;\n\targs: string[];\n\tcommandTransport?: \"argv\" | \"stdin\";\n}\n\nfunction isLegacyWslBashPath(path: string): boolean {\n\tconst normalized = path.replace(/\\//g, \"\\\\\").toLowerCase();\n\treturn /^[a-z]:\\\\windows\\\\(?:system32|sysnative)\\\\bash\\.exe$/.test(normalized);\n}\n\nfunction getBashShellConfig(shell: string): ShellConfig {\n\treturn isLegacyWslBashPath(shell) ? { shell, args: [\"-s\"], commandTransport: \"stdin\" } : { shell, args: [\"-c\"] };\n}\n\nasync function getShellConfig(customShellPath?: string): Promise<Result<ShellConfig, ExecutionError>> {\n\tif (customShellPath) {\n\t\tif (await pathExists(customShellPath)) {\n\t\t\treturn ok(getBashShellConfig(customShellPath));\n\t\t}\n\t\treturn err(new ExecutionError(\"shell_unavailable\", `Custom shell path not found: ${customShellPath}`));\n\t}\n\tif (process.platform === \"win32\") {\n\t\tconst candidates: string[] = [];\n\t\tconst programFiles = process.env.ProgramFiles;\n\t\tif (programFiles) candidates.push(`${programFiles}\\\\Git\\\\bin\\\\bash.exe`);\n\t\tconst programFilesX86 = process.env[\"ProgramFiles(x86)\"];\n\t\tif (programFilesX86) candidates.push(`${programFilesX86}\\\\Git\\\\bin\\\\bash.exe`);\n\t\tfor (const candidate of candidates) {\n\t\t\tif (await pathExists(candidate)) {\n\t\t\t\treturn ok(getBashShellConfig(candidate));\n\t\t\t}\n\t\t}\n\t\tconst bashOnPath = await findBashOnPath();\n\t\tif (bashOnPath) {\n\t\t\treturn ok(getBashShellConfig(bashOnPath));\n\t\t}\n\t\treturn err(\n\t\t\tnew ExecutionError(\n\t\t\t\t\"shell_unavailable\",\n\t\t\t\t`No bash shell found. Options:\\n` +\n\t\t\t\t\t` 1. Install Git for Windows: https://git-scm.com/download/win\\n` +\n\t\t\t\t\t` 2. Add your bash to PATH (Cygwin, MSYS2, etc.)\\n` +\n\t\t\t\t\t\" 3. Configure an explicit shellPath\\n\\n\" +\n\t\t\t\t\t`Searched Git Bash in:\\n${candidates.map((path) => ` ${path}`).join(\"\\n\")}`,\n\t\t\t),\n\t\t);\n\t}\n\n\tif (await pathExists(\"/bin/bash\")) {\n\t\treturn ok(getBashShellConfig(\"/bin/bash\"));\n\t}\n\tconst bashOnPath = await findBashOnPath();\n\tif (bashOnPath) {\n\t\treturn ok(getBashShellConfig(bashOnPath));\n\t}\n\treturn ok({ shell: \"sh\", args: [\"-c\"] });\n}\n\nfunction getShellEnv(\n\tbaseEnv?: NodeJS.ProcessEnv,\n\textraEnv?: Record<string, string>,\n\tinheritEnv = true,\n): NodeJS.ProcessEnv {\n\tif (!inheritEnv) return { ...extraEnv };\n\treturn {\n\t\t...process.env,\n\t\t...baseEnv,\n\t\t...extraEnv,\n\t};\n}\n\nfunction killProcessTree(pid: number): void {\n\tif (process.platform === \"win32\") {\n\t\ttry {\n\t\t\tconst child = spawn(\n\t\t\t\tjoin(process.env.SystemRoot ?? \"C:\\\\Windows\", \"System32\", \"taskkill.exe\"),\n\t\t\t\t[\"/F\", \"/T\", \"/PID\", String(pid)],\n\t\t\t\t{\n\t\t\t\t\tstdio: \"ignore\",\n\t\t\t\t\tdetached: true,\n\t\t\t\t\twindowsHide: true,\n\t\t\t\t},\n\t\t\t);\n\t\t\t// A failed spawn emits \"error\" asynchronously; consume it to avoid crashing Node.\n\t\t\tchild.once(\"error\", () => {});\n\t\t} catch {\n\t\t\t// Ignore errors.\n\t\t}\n\t\treturn;\n\t}\n\n\ttry {\n\t\tprocess.kill(-pid, \"SIGKILL\");\n\t} catch {\n\t\ttry {\n\t\t\tprocess.kill(pid, \"SIGKILL\");\n\t\t} catch {\n\t\t\t// Process already dead.\n\t\t}\n\t}\n}\n\nfunction waitForChildProcess(\n\tchild: ChildProcess,\n\tspillIsDraining: () => boolean,\n): Promise<{ code: number | null; signal: NodeJS.Signals | null }> {\n\treturn new Promise((resolvePromise, reject) => {\n\t\tlet settled = false;\n\t\tlet exited = false;\n\t\tlet exitCode: number | null = null;\n\t\tlet exitSignal: NodeJS.Signals | null = null;\n\t\tlet postExitTimer: ReturnType<typeof setTimeout> | undefined;\n\t\tlet stdoutEnded = child.stdout === null;\n\t\tlet stderrEnded = child.stderr === null;\n\n\t\tconst cleanup = (): void => {\n\t\t\tif (postExitTimer) clearTimeout(postExitTimer);\n\t\t\tchild.removeListener(\"error\", onError);\n\t\t\tchild.removeListener(\"exit\", onExit);\n\t\t\tchild.removeListener(\"close\", onClose);\n\t\t\tchild.stdout?.removeListener(\"end\", onStdoutEnd);\n\t\t\tchild.stderr?.removeListener(\"end\", onStderrEnd);\n\t\t\tchild.stdout?.removeListener(\"data\", onData);\n\t\t\tchild.stderr?.removeListener(\"data\", onData);\n\t\t};\n\t\tconst finalize = (): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tchild.stdout?.destroy();\n\t\t\tchild.stderr?.destroy();\n\t\t\tresolvePromise({ code: exitCode, signal: exitSignal });\n\t\t};\n\t\tconst maybeFinalizeAfterExit = (): void => {\n\t\t\tif (exited && stdoutEnded && stderrEnded) finalize();\n\t\t};\n\t\tconst armIdleTimer = (): void => {\n\t\t\tif (postExitTimer) clearTimeout(postExitTimer);\n\t\t\tpostExitTimer = setTimeout(() => {\n\t\t\t\tif (spillIsDraining()) armIdleTimer();\n\t\t\t\telse finalize();\n\t\t\t}, EXIT_STDIO_GRACE_MS);\n\t\t};\n\t\tconst onData = (): void => {\n\t\t\tif (exited && !settled) armIdleTimer();\n\t\t};\n\t\tconst onStdoutEnd = (): void => {\n\t\t\tstdoutEnded = true;\n\t\t\tmaybeFinalizeAfterExit();\n\t\t};\n\t\tconst onStderrEnd = (): void => {\n\t\t\tstderrEnded = true;\n\t\t\tmaybeFinalizeAfterExit();\n\t\t};\n\t\tconst onError = (error: Error): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\treject(error);\n\t\t};\n\t\tconst onExit = (code: number | null, signal: NodeJS.Signals | null): void => {\n\t\t\texited = true;\n\t\t\texitCode = code;\n\t\t\texitSignal = signal;\n\t\t\tmaybeFinalizeAfterExit();\n\t\t\tif (!settled) armIdleTimer();\n\t\t};\n\t\tconst onClose = (code: number | null, signal: NodeJS.Signals | null): void => {\n\t\t\texitCode = code;\n\t\t\texitSignal = signal;\n\t\t\tfinalize();\n\t\t};\n\n\t\tchild.stdout?.once(\"end\", onStdoutEnd);\n\t\tchild.stderr?.once(\"end\", onStderrEnd);\n\t\tchild.stdout?.on(\"data\", onData);\n\t\tchild.stderr?.on(\"data\", onData);\n\t\tchild.once(\"error\", onError);\n\t\tchild.once(\"exit\", onExit);\n\t\tchild.once(\"close\", onClose);\n\t});\n}\n\n/** Strict LF reader; Node readline does not report whether its final line was newline-terminated. */\nclass NodeTextLineReader implements TextLineReader {\n\tprivate readonly file: Awaited<ReturnType<typeof openFile>>;\n\tprivate readonly path: string;\n\tprivate readonly decoder = new TextDecoder();\n\tprivate readonly chunk = new Uint8Array(64 * 1024);\n\tprivate byteOffset = 0;\n\tprivate buffered = \"\";\n\tprivate ended = false;\n\tprivate closed = false;\n\n\tconstructor(file: Awaited<ReturnType<typeof openFile>>, path: string) {\n\t\tthis.file = file;\n\t\tthis.path = path;\n\t}\n\n\tasync readLine(context: Context): Promise<Result<TextLine | undefined, FileError>> {\n\t\tconst aborted = abortResult<TextLine | undefined>(context.abortSignal, this.path);\n\t\tif (aborted) return aborted;\n\t\tif (this.closed) return err(new FileError(\"invalid\", \"Text line reader is closed\", this.path));\n\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst newline = this.buffered.indexOf(\"\\n\");\n\t\t\t\tif (newline !== -1) {\n\t\t\t\t\tconst text = this.buffered.slice(0, newline);\n\t\t\t\t\tthis.buffered = this.buffered.slice(newline + 1);\n\t\t\t\t\treturn ok({ text, terminated: true });\n\t\t\t\t}\n\t\t\t\tif (this.ended) {\n\t\t\t\t\tif (this.buffered.length === 0) return ok(undefined);\n\t\t\t\t\tconst text = this.buffered;\n\t\t\t\t\tthis.buffered = \"\";\n\t\t\t\t\treturn ok({ text, terminated: false });\n\t\t\t\t}\n\n\t\t\t\t// Explicit positions allow an aborted read to be retried without skipping bytes.\n\t\t\t\tconst { bytesRead } = await this.file.read(this.chunk, 0, this.chunk.length, this.byteOffset);\n\t\t\t\tconst afterReadAbort = abortResult<TextLine | undefined>(context.abortSignal, this.path);\n\t\t\t\tif (afterReadAbort) return afterReadAbort;\n\t\t\t\tthis.byteOffset += bytesRead;\n\t\t\t\tif (bytesRead === 0) {\n\t\t\t\t\tthis.buffered += this.decoder.decode();\n\t\t\t\t\tthis.ended = true;\n\t\t\t\t} else {\n\t\t\t\t\tthis.buffered += this.decoder.decode(this.chunk.subarray(0, bytesRead), { stream: true });\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, this.path));\n\t\t}\n\t}\n\n\tasync close(_context: Context): Promise<void> {\n\t\tif (this.closed) return;\n\t\tthis.closed = true;\n\t\tthis.buffered = \"\";\n\t\ttry {\n\t\t\tawait this.file.close();\n\t\t} catch {\n\t\t\t// Closing is best-effort, including after cancellation or an earlier I/O failure.\n\t\t}\n\t}\n}\n\nexport class NodeExecutionEnv implements ExecutionEnv {\n\tcwd: string;\n\tprivate shellPath?: string;\n\tprivate shellEnv?: NodeJS.ProcessEnv;\n\tprivate activeChildPids = new Set<number>();\n\n\tconstructor(options: { cwd: string; shellPath?: string; shellEnv?: NodeJS.ProcessEnv }) {\n\t\tthis.cwd = options.cwd;\n\t\tthis.shellPath = options.shellPath;\n\t\tthis.shellEnv = options.shellEnv;\n\t}\n\n\tasync absolutePath(path: string, _context: Context): Promise<Result<string, FileError>> {\n\t\treturn ok(resolvePath(this.cwd, path));\n\t}\n\n\tasync joinPath(parts: string[], _context: Context): Promise<Result<string, FileError>> {\n\t\treturn ok(join(...parts));\n\t}\n\n\tasync exec(\n\t\tcommand: string,\n\t\toptions: ShellExecOptions | undefined,\n\t\tcontext: Context,\n\t): Promise<Result<ShellExecResult, ExecutionError>> {\n\t\tconst signal = context.abortSignal;\n\t\tif (signal?.aborted) return err(new ExecutionError(\"aborted\", \"aborted\"));\n\t\tconst timeoutMsResult = resolveTimeoutMs(options?.timeout);\n\t\tif (!timeoutMsResult.ok) return err(timeoutMsResult.error);\n\t\tconst timeoutMs = timeoutMsResult.value;\n\n\t\tconst cwd = options?.cwd ? resolvePath(this.cwd, options.cwd) : this.cwd;\n\t\tconst shellConfig = await getShellConfig(this.shellPath);\n\t\tif (!shellConfig.ok) return shellConfig;\n\t\ttry {\n\t\t\tawait access(cwd, constants.F_OK);\n\t\t} catch (error) {\n\t\t\tconst cause = toError(error);\n\t\t\treturn err(\n\t\t\t\tnew ExecutionError(\n\t\t\t\t\t\"spawn_error\",\n\t\t\t\t\t`Working directory does not exist: ${cwd}\\nCannot execute bash commands.`,\n\t\t\t\t\tcause,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\treturn await new Promise((resolvePromise) => {\n\t\t\tlet settled = false;\n\t\t\tlet timedOut = false;\n\t\t\tlet callbackError: ExecutionError | undefined;\n\t\t\tlet spillError: ExecutionError | undefined;\n\t\t\tlet child: ReturnType<typeof spawn> | undefined;\n\t\t\tlet timeoutId: ReturnType<typeof setTimeout> | undefined;\n\t\t\tconst spillPrefix: SpillChunk[] = [];\n\t\t\tlet spillPath: string | undefined;\n\t\t\tconst spillQueue: SpillChunk[] = [];\n\t\t\tlet spillStart: Promise<void> | undefined;\n\t\t\tlet spillStream: WriteStream | undefined;\n\t\t\tlet spillBackpressured = false;\n\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child?.pid) killProcessTree(child.pid);\n\t\t\t};\n\t\t\tconst failCallback = (error: unknown) => {\n\t\t\t\tif (callbackError !== undefined) return;\n\t\t\t\tconst cause = toError(error);\n\t\t\t\tcallbackError = new ExecutionError(\"callback_error\", cause.message, cause);\n\t\t\t\tonAbort();\n\t\t\t};\n\t\t\tlet capture: OutputCapture;\n\t\t\ttry {\n\t\t\t\tcapture = new OutputCapture(options?.capture, context, {\n\t\t\t\t\tonUpdate: options?.onUpdate,\n\t\t\t\t\tonError: failCallback,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tconst cause = toError(error);\n\t\t\t\tresolvePromise(err(new ExecutionError(\"unknown\", cause.message, cause)));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst settle = (result: Result<ShellExecResult, ExecutionError>) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tif (timeoutId) clearTimeout(timeoutId);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t\tif (child?.pid) this.activeChildPids.delete(child.pid);\n\t\t\t\tcapture.dispose();\n\t\t\t\tresolvePromise(result);\n\t\t\t};\n\t\t\tconst pauseOutput = () => {\n\t\t\t\tchild?.stdout?.pause();\n\t\t\t\tchild?.stderr?.pause();\n\t\t\t};\n\t\t\tconst resumeOutput = () => {\n\t\t\t\tif (callbackError || spillError || timedOut || signal?.aborted || spillBackpressured) return;\n\t\t\t\tchild?.stdout?.resume();\n\t\t\t\tchild?.stderr?.resume();\n\t\t\t};\n\t\t\tconst failSpill = (error: unknown) => {\n\t\t\t\tif (spillError !== undefined) return;\n\t\t\t\tconst cause = toError(error);\n\t\t\t\tspillError = new ExecutionError(\n\t\t\t\t\t\"unknown\",\n\t\t\t\t\t`Failed to preserve complete shell output: ${cause.message}`,\n\t\t\t\t\tcause,\n\t\t\t\t);\n\t\t\t\tspillBackpressured = false;\n\t\t\t\tonAbort();\n\t\t\t};\n\t\t\tconst writeSpill = (chunk: SpillChunk): void => {\n\t\t\t\tif (spillStream === undefined || chunk.length === 0) return;\n\t\t\t\tif (spillStream.write(chunk) || spillBackpressured) return;\n\t\t\t\tspillBackpressured = true;\n\t\t\t\tpauseOutput();\n\t\t\t\tspillStream.once(\"drain\", () => {\n\t\t\t\t\tspillBackpressured = false;\n\t\t\t\t\tresumeOutput();\n\t\t\t\t});\n\t\t\t};\n\t\t\tconst startSpill = (chunk: SpillChunk): void => {\n\t\t\t\tif (spillStream !== undefined) {\n\t\t\t\t\twriteSpill(chunk);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tspillQueue.push(chunk);\n\t\t\t\tif (spillStart !== undefined) return;\n\t\t\t\tpauseOutput();\n\t\t\t\tspillStart = (async () => {\n\t\t\t\t\tconst created = await this.createTempFile({ prefix: \"pi-output-\", suffix: \".log\" }, context);\n\t\t\t\t\tif (!created.ok) throw created.error;\n\t\t\t\t\tspillPath = created.value;\n\t\t\t\t\tcapture.setSpillPath(spillPath);\n\t\t\t\t\tspillStream = createWriteStream(spillPath, { flags: \"a\", highWaterMark: SPILL_HIGH_WATER_MARK });\n\t\t\t\t\tspillStream.on(\"error\", failSpill);\n\t\t\t\t\tfor (const queued of spillQueue) writeSpill(queued);\n\t\t\t\t\tspillQueue.length = 0;\n\t\t\t\t})()\n\t\t\t\t\t.catch(failSpill)\n\t\t\t\t\t.finally(resumeOutput);\n\t\t\t};\n\t\t\tconst finishSpill = async (): Promise<void> => {\n\t\t\t\tawait spillStart;\n\t\t\t\tconst stream = spillStream;\n\t\t\t\tif (stream === undefined || spillError !== undefined || stream.destroyed) return;\n\t\t\t\tawait new Promise<void>((resolveFinish) => {\n\t\t\t\t\tstream.once(\"error\", () => resolveFinish());\n\t\t\t\t\tstream.once(\"finish\", resolveFinish);\n\t\t\t\t\tstream.end();\n\t\t\t\t});\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tconst commandFromStdin = shellConfig.value.commandTransport === \"stdin\";\n\t\t\t\tchild = spawn(\n\t\t\t\t\tshellConfig.value.shell,\n\t\t\t\t\tcommandFromStdin ? shellConfig.value.args : [...shellConfig.value.args, command],\n\t\t\t\t\t{\n\t\t\t\t\t\tcwd,\n\t\t\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\t\t\tenv: getShellEnv(this.shellEnv, options?.env, options?.inheritEnv),\n\t\t\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\t\t\twindowsHide: true,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tif (child.pid) this.activeChildPids.add(child.pid);\n\t\t\t\tif (commandFromStdin) {\n\t\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\t\tchild.stdin?.end(command);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconst cause = toError(error);\n\t\t\t\tsettle(err(new ExecutionError(\"spawn_error\", cause.message, cause)));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\ttimeoutId =\n\t\t\t\ttimeoutMs === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: setTimeout(() => {\n\t\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\t\tonAbort();\n\t\t\t\t\t\t}, timeoutMs);\n\n\t\t\tif (signal) {\n\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t}\n\n\t\t\tconst feed = (chunk: Uint8Array) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst wasTruncated = capture.truncated;\n\t\t\t\t\tcapture.push(chunk);\n\t\t\t\t\tif (!options?.capture?.spill || chunk.length === 0) return;\n\t\t\t\t\tif (spillPath !== undefined || wasTruncated) {\n\t\t\t\t\t\tstartSpill(chunk);\n\t\t\t\t\t} else if (capture.truncated) {\n\t\t\t\t\t\tfor (const prefix of spillPrefix) startSpill(prefix);\n\t\t\t\t\t\tspillPrefix.length = 0;\n\t\t\t\t\t\tstartSpill(chunk);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tspillPrefix.push(chunk);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfailCallback(error);\n\t\t\t\t}\n\t\t\t};\n\t\t\tchild.stdout?.on(\"data\", feed);\n\t\t\tchild.stderr?.on(\"data\", feed);\n\n\t\t\tvoid waitForChildProcess(\n\t\t\t\tchild,\n\t\t\t\t() =>\n\t\t\t\t\tspillError === undefined &&\n\t\t\t\t\tspillStart !== undefined &&\n\t\t\t\t\t(spillStream === undefined || spillBackpressured),\n\t\t\t).then(\n\t\t\t\tasync ({ code, signal: exitSignal }) => {\n\t\t\t\t\tawait finishSpill();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcapture.finish();\n\t\t\t\t\t\tcapture.flush();\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tfailCallback(error);\n\t\t\t\t\t}\n\t\t\t\t\tif (callbackError) {\n\t\t\t\t\t\tsettle(err(callbackError));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (timedOut) {\n\t\t\t\t\t\tsettle(err(new ExecutionError(\"timeout\", `timeout:${options?.timeout}`)));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\tsettle(err(new ExecutionError(\"aborted\", \"aborted\")));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (spillError) {\n\t\t\t\t\t\tsettle(err(spillError));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst output = capture.snapshot();\n\t\t\t\t\t// A process killed by a signal (e.g. OOM killer) has no exit code; map it\n\t\t\t\t\t// to the conventional 128 + signal number so callers do not mistake it\n\t\t\t\t\t// for a successful exit.\n\t\t\t\t\tconst exitCode = code ?? (exitSignal ? 128 + (osConstants.signals[exitSignal] ?? 0) : 1);\n\t\t\t\t\tsettle(\n\t\t\t\t\t\tok({\n\t\t\t\t\t\t\texitCode,\n\t\t\t\t\t\t\ttruncation: output.truncation,\n\t\t\t\t\t\t\t...(output.spillPath === undefined ? {} : { spillPath: output.spillPath }),\n\t\t\t\t\t\t\t...(output.lastLineBytes === undefined ? {} : { lastLineBytes: output.lastLineBytes }),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\t(error: Error) => settle(err(new ExecutionError(\"spawn_error\", error.message, error))),\n\t\t\t);\n\t\t});\n\t}\n\n\tasync openTextLineReader(path: string, context: Context): Promise<Result<TextLineReader, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<TextLineReader>(context.abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tconst file = await openFile(resolved, \"r\");\n\t\t\tconst afterOpenAbort = abortResult<TextLineReader>(context.abortSignal, resolved);\n\t\t\tif (afterOpenAbort) {\n\t\t\t\tawait file.close().catch(() => undefined);\n\t\t\t\treturn afterOpenAbort;\n\t\t\t}\n\t\t\treturn ok(new NodeTextLineReader(file, resolved));\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync readTextFile(path: string, context: Context): Promise<Result<string, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst signal = context.abortSignal;\n\t\tconst aborted = abortResult<string>(signal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\treturn ok(await readFile(resolved, { encoding: \"utf8\", signal }));\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync readTextLines(\n\t\tpath: string,\n\t\toptions: { maxLines?: number } | undefined,\n\t\tcontext: Context,\n\t): Promise<Result<string[], FileError>> {\n\t\tif (options?.maxLines !== undefined && options.maxLines <= 0) return ok([]);\n\t\tconst opened = await this.openTextLineReader(path, context);\n\t\tif (!opened.ok) return opened;\n\t\tconst lines: string[] = [];\n\t\ttry {\n\t\t\twhile (options?.maxLines === undefined || lines.length < options.maxLines) {\n\t\t\t\tconst line = await opened.value.readLine(context);\n\t\t\t\tif (!line.ok) return line;\n\t\t\t\tif (line.value === undefined) break;\n\t\t\t\tlines.push(line.value.text);\n\t\t\t}\n\t\t\treturn ok(lines);\n\t\t} finally {\n\t\t\tawait opened.value.close(context);\n\t\t}\n\t}\n\n\tasync readBinaryFile(path: string, context: Context): Promise<Result<Uint8Array, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst signal = context.abortSignal;\n\t\tconst aborted = abortResult<Uint8Array>(signal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\treturn ok(await readFile(resolved, { signal }));\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync writeFile(path: string, content: string | Uint8Array, context: Context): Promise<Result<void, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst signal = context.abortSignal;\n\t\tconst aborted = abortResult<void>(signal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tawait mkdir(resolve(resolved, \"..\"), { recursive: true });\n\t\t\tconst afterMkdirAbort = abortResult<void>(signal, resolved);\n\t\t\tif (afterMkdirAbort) return afterMkdirAbort;\n\t\t\tawait writeFile(resolved, content, { signal });\n\t\t\treturn ok(undefined);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync appendFile(path: string, content: string | Uint8Array, context: Context): Promise<Result<void, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst signal = context.abortSignal;\n\t\tconst aborted = abortResult<void>(signal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tawait mkdir(resolve(resolved, \"..\"), { recursive: true });\n\t\t\tconst afterMkdirAbort = abortResult<void>(signal, resolved);\n\t\t\tif (afterMkdirAbort) return afterMkdirAbort;\n\t\t\tawait appendFile(resolved, content);\n\t\t\tconst afterAppendAbort = abortResult<void>(signal, resolved);\n\t\t\treturn afterAppendAbort ?? ok(undefined);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync renameFile(sourcePath: string, destinationPath: string, context: Context): Promise<Result<void, FileError>> {\n\t\tconst source = resolvePath(this.cwd, sourcePath);\n\t\tconst destination = resolvePath(this.cwd, destinationPath);\n\t\tconst aborted = abortResult<void>(context.abortSignal, destination);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tawait rename(source, destination);\n\t\t\treturn ok(undefined);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, source));\n\t\t}\n\t}\n\n\tasync fileInfo(path: string, context: Context): Promise<Result<FileInfo, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<FileInfo>(context.abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\treturn fileInfoFromStats(resolved, await lstat(resolved));\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync listDir(path: string, context: Context): Promise<Result<FileInfo[], FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst signal = context.abortSignal;\n\t\tconst aborted = abortResult<FileInfo[]>(signal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tconst entries = await readdir(resolved, { withFileTypes: true });\n\t\t\tconst infos: FileInfo[] = [];\n\t\t\tfor (const entry of entries) {\n\t\t\t\tconst loopAbort = abortResult<FileInfo[]>(signal, resolved);\n\t\t\t\tif (loopAbort) return loopAbort;\n\t\t\t\tconst entryPath = resolve(resolved, entry.name);\n\t\t\t\ttry {\n\t\t\t\t\tconst info = fileInfoFromStats(entryPath, await lstat(entryPath));\n\t\t\t\t\tif (info.ok) infos.push(info.value);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn err(toFileError(error, entryPath));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn ok(infos);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync canonicalPath(path: string, context: Context): Promise<Result<string, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<string>(context.abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\treturn ok(await realpath(resolved));\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync exists(path: string, context: Context): Promise<Result<boolean, FileError>> {\n\t\tconst result = await this.fileInfo(path, context);\n\t\tif (result.ok) return ok(true);\n\t\tif (result.error.code === \"not_found\") return ok(false);\n\t\treturn err(result.error);\n\t}\n\n\tasync createDir(\n\t\tpath: string,\n\t\toptions: { recursive?: boolean } | undefined,\n\t\tcontext: Context,\n\t): Promise<Result<void, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<void>(context.abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tawait mkdir(resolved, { recursive: options?.recursive ?? true });\n\t\t\treturn ok(undefined);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync remove(\n\t\tpath: string,\n\t\toptions: { recursive?: boolean; force?: boolean } | undefined,\n\t\tcontext: Context,\n\t): Promise<Result<void, FileError>> {\n\t\tconst resolved = resolvePath(this.cwd, path);\n\t\tconst aborted = abortResult<void>(context.abortSignal, resolved);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tawait rm(resolved, { recursive: options?.recursive ?? false, force: options?.force ?? false });\n\t\t\treturn ok(undefined);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, resolved));\n\t\t}\n\t}\n\n\tasync createTempDir(prefix: string | undefined, context: Context): Promise<Result<string, FileError>> {\n\t\tconst aborted = abortResult<string>(context.abortSignal);\n\t\tif (aborted) return aborted;\n\t\ttry {\n\t\t\tprefix ??= \"tmp-\";\n\t\t\treturn ok(await mkdtemp(join(tmpdir(), prefix)));\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error));\n\t\t}\n\t}\n\n\tasync createTempFile(\n\t\toptions: { prefix?: string; suffix?: string } | undefined,\n\t\tcontext: Context,\n\t): Promise<Result<string, FileError>> {\n\t\tconst dir = await this.createTempDir(\"tmp-\", context);\n\t\tif (!dir.ok) return dir;\n\t\tconst filePath = join(dir.value, `${options?.prefix ?? \"\"}${randomUUID()}${options?.suffix ?? \"\"}`);\n\t\ttry {\n\t\t\tawait writeFile(filePath, \"\");\n\t\t\treturn ok(filePath);\n\t\t} catch (error) {\n\t\t\treturn err(toFileError(error, filePath));\n\t\t}\n\t}\n\n\tasync cleanup(_context: Context): Promise<void> {\n\t\tfor (const pid of this.activeChildPids) killProcessTree(pid);\n\t\tthis.activeChildPids.clear();\n\t}\n}\n"]}
@@ -1,10 +1,9 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
- import { constants, createReadStream, createWriteStream } from "node:fs";
4
- import { access, appendFile, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rename, rm, writeFile, } from "node:fs/promises";
3
+ import { constants, createWriteStream } from "node:fs";
4
+ import { access, appendFile, lstat, mkdir, mkdtemp, open as openFile, readdir, readFile, realpath, rename, rm, writeFile, } from "node:fs/promises";
5
5
  import { homedir, constants as osConstants, tmpdir } from "node:os";
6
6
  import { basename, isAbsolute, join, resolve } from "node:path";
7
- import { createInterface } from "node:readline";
8
7
  import { fileURLToPath } from "node:url";
9
8
  import { ExecutionError, err, FileError, ok, toError, } from "../types.js";
10
9
  import { OutputCapture } from "../utils/output-capture.js";
@@ -312,6 +311,73 @@ function waitForChildProcess(child, spillIsDraining) {
312
311
  child.once("close", onClose);
313
312
  });
314
313
  }
314
+ /** Strict LF reader; Node readline does not report whether its final line was newline-terminated. */
315
+ class NodeTextLineReader {
316
+ file;
317
+ path;
318
+ decoder = new TextDecoder();
319
+ chunk = new Uint8Array(64 * 1024);
320
+ byteOffset = 0;
321
+ buffered = "";
322
+ ended = false;
323
+ closed = false;
324
+ constructor(file, path) {
325
+ this.file = file;
326
+ this.path = path;
327
+ }
328
+ async readLine(context) {
329
+ const aborted = abortResult(context.abortSignal, this.path);
330
+ if (aborted)
331
+ return aborted;
332
+ if (this.closed)
333
+ return err(new FileError("invalid", "Text line reader is closed", this.path));
334
+ try {
335
+ while (true) {
336
+ const newline = this.buffered.indexOf("\n");
337
+ if (newline !== -1) {
338
+ const text = this.buffered.slice(0, newline);
339
+ this.buffered = this.buffered.slice(newline + 1);
340
+ return ok({ text, terminated: true });
341
+ }
342
+ if (this.ended) {
343
+ if (this.buffered.length === 0)
344
+ return ok(undefined);
345
+ const text = this.buffered;
346
+ this.buffered = "";
347
+ return ok({ text, terminated: false });
348
+ }
349
+ // Explicit positions allow an aborted read to be retried without skipping bytes.
350
+ const { bytesRead } = await this.file.read(this.chunk, 0, this.chunk.length, this.byteOffset);
351
+ const afterReadAbort = abortResult(context.abortSignal, this.path);
352
+ if (afterReadAbort)
353
+ return afterReadAbort;
354
+ this.byteOffset += bytesRead;
355
+ if (bytesRead === 0) {
356
+ this.buffered += this.decoder.decode();
357
+ this.ended = true;
358
+ }
359
+ else {
360
+ this.buffered += this.decoder.decode(this.chunk.subarray(0, bytesRead), { stream: true });
361
+ }
362
+ }
363
+ }
364
+ catch (error) {
365
+ return err(toFileError(error, this.path));
366
+ }
367
+ }
368
+ async close(_context) {
369
+ if (this.closed)
370
+ return;
371
+ this.closed = true;
372
+ this.buffered = "";
373
+ try {
374
+ await this.file.close();
375
+ }
376
+ catch {
377
+ // Closing is best-effort, including after cancellation or an earlier I/O failure.
378
+ }
379
+ }
380
+ }
315
381
  export class NodeExecutionEnv {
316
382
  cwd;
317
383
  shellPath;
@@ -561,52 +627,57 @@ export class NodeExecutionEnv {
561
627
  }, (error) => settle(err(new ExecutionError("spawn_error", error.message, error))));
562
628
  });
563
629
  }
564
- async readTextFile(path, context) {
630
+ async openTextLineReader(path, context) {
565
631
  const resolved = resolvePath(this.cwd, path);
566
- const signal = context.abortSignal;
567
- const aborted = abortResult(signal, resolved);
632
+ const aborted = abortResult(context.abortSignal, resolved);
568
633
  if (aborted)
569
634
  return aborted;
570
635
  try {
571
- return ok(await readFile(resolved, { encoding: "utf8", signal }));
636
+ const file = await openFile(resolved, "r");
637
+ const afterOpenAbort = abortResult(context.abortSignal, resolved);
638
+ if (afterOpenAbort) {
639
+ await file.close().catch(() => undefined);
640
+ return afterOpenAbort;
641
+ }
642
+ return ok(new NodeTextLineReader(file, resolved));
572
643
  }
573
644
  catch (error) {
574
645
  return err(toFileError(error, resolved));
575
646
  }
576
647
  }
577
- async readTextLines(path, options, context) {
648
+ async readTextFile(path, context) {
578
649
  const resolved = resolvePath(this.cwd, path);
579
650
  const signal = context.abortSignal;
580
651
  const aborted = abortResult(signal, resolved);
581
652
  if (aborted)
582
653
  return aborted;
654
+ try {
655
+ return ok(await readFile(resolved, { encoding: "utf8", signal }));
656
+ }
657
+ catch (error) {
658
+ return err(toFileError(error, resolved));
659
+ }
660
+ }
661
+ async readTextLines(path, options, context) {
583
662
  if (options?.maxLines !== undefined && options.maxLines <= 0)
584
663
  return ok([]);
585
- let stream;
586
- let lineReader;
664
+ const opened = await this.openTextLineReader(path, context);
665
+ if (!opened.ok)
666
+ return opened;
667
+ const lines = [];
587
668
  try {
588
- stream = createReadStream(resolved, { encoding: "utf8", signal });
589
- lineReader = createInterface({ input: stream, crlfDelay: Infinity });
590
- const lines = [];
591
- for await (const line of lineReader) {
592
- const loopAbort = abortResult(signal, resolved);
593
- if (loopAbort)
594
- return loopAbort;
595
- lines.push(line);
596
- if (options?.maxLines !== undefined && lines.length >= options.maxLines)
669
+ while (options?.maxLines === undefined || lines.length < options.maxLines) {
670
+ const line = await opened.value.readLine(context);
671
+ if (!line.ok)
672
+ return line;
673
+ if (line.value === undefined)
597
674
  break;
675
+ lines.push(line.value.text);
598
676
  }
599
- const afterReadAbort = abortResult(signal, resolved);
600
- if (afterReadAbort)
601
- return afterReadAbort;
602
677
  return ok(lines);
603
678
  }
604
- catch (error) {
605
- return err(toFileError(error, resolved));
606
- }
607
679
  finally {
608
- lineReader?.close();
609
- stream?.destroy();
680
+ await opened.value.close(context);
610
681
  }
611
682
  }
612
683
  async readBinaryFile(path, context) {