package cabal
Source file backend_process.ml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511(******************************************************************************) (* *) (* Copyright (c) 2026 Epure Team *) (* All rights reserved. *) (* *) (******************************************************************************) open Backend_types type process_result = { status : result_status; stdout : string; stderr : string; exit_code : int; elapsed : duration; cost : cost option; session_id : string option; } let shell_quote_argv argv = argv |> String.concat " " let invalid_managed_namespace_result msg = make_task_result ~status:(Failed msg) ~stderr:msg ~exit_code:1 () let validate_task_namespace (spec : task_spec) = match spec.pi_daybreak with | Some _ -> Some (make_task_result ~status:(Failed "Daybreak production execution is disabled") ()) | None -> match validate_managed_namespace spec.managed_namespace with | Ok () -> None | Error msg -> Some (invalid_managed_namespace_result msg) (* Run a command and capture its stdout as a string. Returns [Ok output] when stdout is non-empty regardless of exit code; returns [Error _] only when the binary is not found or produces no output. This is the version-detection primitive: callers should never crash on a non-zero exit from a --version command. *) (** Default cap for version / availability probes. Five seconds is long enough for cold-start CLIs (large Node binaries on slow disks) but short enough that a hung backend cannot freeze registry initialisation for the whole host. *) let default_probe_timeout_seconds = 5.0 let capture_version_output ~env ?child_env ?(timeout_seconds = default_probe_timeout_seconds) cmd = let proc_mgr = Eio.Stdenv.process_mgr env in let clock = Eio.Stdenv.clock env in let stdout_buf = Buffer.create 256 in let stderr_buf = Buffer.create 64 in let outcome = Eio.Time.with_timeout clock timeout_seconds (fun () -> (try Eio.Process.run proc_mgr ?env:child_env ~stdout:(Eio.Flow.buffer_sink stdout_buf) ~stderr:(Eio.Flow.buffer_sink stderr_buf) cmd with _ -> ()) ; Ok ()) in match outcome with | Error `Timeout -> Error (Printf.sprintf "timeout after %.1fs running %s" timeout_seconds (String.concat " " cmd)) | Ok () -> let out = Buffer.contents stdout_buf in if out <> "" then Ok out else let err = Buffer.contents stderr_buf in if err <> "" then Ok err else Error (Printf.sprintf "no output from %s" (String.concat " " cmd)) (* Check if a command is available by running it. Distinguishes three outcomes: clean exit, process error (missing binary or non-zero exit raising Eio.Io), and timeout. *) let check_available ~env ?(timeout_seconds = default_probe_timeout_seconds) cmd = let proc_mgr = Eio.Stdenv.process_mgr env in let clock = Eio.Stdenv.clock env in let stdout_buf = Buffer.create 64 in let stderr_buf = Buffer.create 64 in let outcome = Eio.Time.with_timeout clock timeout_seconds (fun () -> try Eio.Process.run proc_mgr ~stdout:(Eio.Flow.buffer_sink stdout_buf) ~stderr:(Eio.Flow.buffer_sink stderr_buf) cmd ; Ok true with Eio.Io _ -> Ok false) in match outcome with Error `Timeout -> false | Ok ok -> ok (* Write MCP server configuration to a JSON file *) let write_mcp_config ~env ~path configs = let fs = Eio.Stdenv.fs env in let servers = List.map (fun (cfg : mcp_server_config) -> let env_obj = `Assoc (List.map (fun (k, v) -> (k, `String v)) cfg.env) in ( cfg.name, `Assoc [ ("command", `String cfg.command); ("args", `List (List.map (fun a -> `String a) cfg.args)); ("env", env_obj); ] )) configs in let json = `Assoc [("mcpServers", `Assoc servers)] in let content = Yojson.Safe.pretty_to_string json in Eio.Path.save ~create:(`Or_truncate 0o600) Eio.Path.(fs / path) content (* Create a temporary MCP config file if needed. Uses a unique filename to avoid collisions from concurrent runs. *) let setup_mcp_config ~env spec = match spec.mcp_servers with | [] -> None | servers -> (match validate_managed_namespace spec.managed_namespace with | Ok () -> () | Error msg -> invalid_arg msg) ; let path = Filename.temp_file ~temp_dir:spec.working_dir ("." ^ spec.managed_namespace.id ^ "-mcp-config-") ".json" in write_mcp_config ~env ~path servers ; Some path (* Clean up temporary MCP config file *) let cleanup_mcp_config ~env path = let fs = Eio.Stdenv.fs env in try Eio.Path.unlink Eio.Path.(fs / path) with _ -> () (* Run a git command and return stdout, or empty string on error. *) let run_git ~env ~working_dir args = let proc_mgr = Eio.Stdenv.process_mgr env in let fs = Eio.Stdenv.fs env in try let stdout_buf = Buffer.create 4096 in let stderr_buf = Buffer.create 64 in Eio.Process.run proc_mgr ~cwd:Eio.Path.(fs / working_dir) ~stdout:(Eio.Flow.buffer_sink stdout_buf) ~stderr:(Eio.Flow.buffer_sink stderr_buf) ("git" :: args) ; Buffer.contents stdout_buf with Eio.Io _ -> "" (* Split output into non-empty lines. *) let lines_of_output output = output |> String.split_on_char '\n' |> List.filter (fun s -> String.length (String.trim s) > 0) (** Pathspec exclusions appended to every [git diff] call. These directories are build artefacts that should never appear in the diff shown to review agents — they inflate context, cause context-window overflows, and contain no meaningful code changes. The ":!" pathspec magic works for both commit-range diffs and HEAD diffs. *) let diff_exclude_pathspecs = [ ":(exclude)node_modules"; ":(exclude)_build"; ":(exclude).vite"; ":(exclude)dist"; ":(exclude)vendor"; ] (* Get list of changed files: tracked changes + untracked new files. *) let get_git_diff ~sw:_ ~env ~working_dir = let tracked = run_git ~env ~working_dir (["diff"; "--name-only"; "HEAD"; "--"] @ diff_exclude_pathspecs) in let untracked = run_git ~env ~working_dir ["ls-files"; "--others"; "--exclude-standard"] in let tracked_files = lines_of_output tracked in let untracked_files = lines_of_output untracked in tracked_files @ untracked_files (* Generate a unified diff for an untracked file by diffing /dev/null against it. git diff --no-index exits with code 1 when files differ, so we capture output even on non-zero exit. *) let diff_untracked_file ~env ~working_dir path = let proc_mgr = Eio.Stdenv.process_mgr env in let fs = Eio.Stdenv.fs env in let stdout_buf = Buffer.create 4096 in let stderr_buf = Buffer.create 64 in (try Eio.Process.run proc_mgr ~cwd:Eio.Path.(fs / working_dir) ~stdout:(Eio.Flow.buffer_sink stdout_buf) ~stderr:(Eio.Flow.buffer_sink stderr_buf) ["git"; "diff"; "--no-index"; "--"; "/dev/null"; path] with Eio.Io _ -> (* git diff --no-index exits 1 when files differ — expected *) ()) ; Buffer.contents stdout_buf (* Get full diff content: tracked changes + untracked file contents as pseudo-diffs so that reviewers can see new file content. *) let get_git_diff_content ~sw:_ ~env ~working_dir = let tracked_diff = run_git ~env ~working_dir (["diff"; "HEAD"; "--"] @ diff_exclude_pathspecs) in let untracked = run_git ~env ~working_dir ["ls-files"; "--others"; "--exclude-standard"] in let untracked_files = lines_of_output untracked in if untracked_files = [] then tracked_diff else let untracked_diffs = List.filter_map (fun path -> let d = diff_untracked_file ~env ~working_dir path in if String.length d > 0 then Some d else None) untracked_files in let parts = (if String.length tracked_diff > 0 then [tracked_diff] else []) @ untracked_diffs in String.concat "\n" parts type startup_watch = Process_startup.startup_watch = { window_seconds : float; is_started : string -> bool; } let startup_stalled_prefix = Process_startup.startup_stalled_prefix let startup_stalled_message = Process_startup.startup_stalled_message let is_startup_stalled = Process_startup.is_startup_stalled let environment_with = Process_startup.environment_with (* Run a subprocess and capture output with timeout. Stderr is captured and returned in process_result for the caller to display appropriately (toast in TUI, print in CLI). If on_stdout is provided, it's called for each line of stdout as it arrives. *) let run_process ~sw ~env ~cmd ?(stdin_content = None) ~working_dir ~timeout_seconds ?parse_cost ?on_stdout ?guardian ?(extra_env = []) ?child_env ?startup_watch () = let proc_mgr = Eio.Stdenv.process_mgr env in let fs = Eio.Stdenv.fs env in let clock = Eio.Stdenv.clock env in let start_time = Eio.Time.now clock in (* Create pipes for stdout/stderr *) let stdout_r, stdout_w = Eio.Process.pipe ~sw proc_mgr in let stderr_r, stderr_w = Eio.Process.pipe ~sw proc_mgr in (* Create stdin pipe if we have content to write *) let stdin_r, stdin_w = match stdin_content with | Some _ -> let r, w = Eio.Process.pipe ~sw proc_mgr in (Some r, Some w) | None -> (None, None) in (* Spawn the process *) let proc = Eio.Process.spawn ~sw proc_mgr ~cwd:Eio.Path.(fs / working_dir) ?stdin:(Option.map (fun r -> (r :> _ Eio.Flow.source)) stdin_r) ?env:(match child_env with Some values -> Some values | None -> if extra_env = [] then None else Some (environment_with extra_env)) ~stdout:(stdout_w :> _ Eio.Flow.sink) ~stderr:(stderr_w :> _ Eio.Flow.sink) cmd in (* Register PID with resource guardian for memory-pressure killing *) let pid = Eio.Process.pid proc in Option.iter (fun g -> Resource_guardian.register_pid g pid) guardian ; (* Close write ends - we only read from stdout/stderr *) Eio.Flow.close stdout_w ; Eio.Flow.close stderr_w ; (* Close read end of stdin pipe if we created one: the child owns its copy, and keeping ours open would turn an early child exit into a blocked write instead of EPIPE. *) Option.iter Eio.Flow.close stdin_r ; (* Stdin is written concurrently with output capture, inside the timeout: a child that does not consume a prompt larger than the pipe buffer, or that writes a pipe buffer of output before reading its prompt, must not block [run_process] outside the timeout. A child that stops reading (EPIPE) only loses the rest of its stdin. *) let write_stdin () = match (stdin_content, stdin_w) with | Some content, Some w -> Fun.protect ~finally:(fun () -> Eio.Flow.close w) (fun () -> try Eio.Flow.copy_string content w with Eio.Io _ -> ()) | _ -> () in (* Read output with timeout *) let stdout_buf = Buffer.create 4096 in let stderr_buf = Buffer.create 1024 in let line_buf = Buffer.create 256 in let started, resolve_started = Eio.Promise.create () in let display_line () = let line = Buffer.contents line_buf in Buffer.clear line_buf ; let line = if String.ends_with ~suffix:"\r" line then String.sub line 0 (String.length line - 1) else line in (match startup_watch with | Some watch when not (Eio.Promise.is_resolved started) -> ( match watch.is_started line with | true -> Eio.Promise.resolve resolve_started () | false -> () | exception _ -> ()) | Some _ | None -> ()) ; Option.iter (fun callback -> try callback line with _ -> ()) on_stdout in let split_lines = Option.is_some on_stdout || Option.is_some startup_watch in let capture flow target ?(display = false) () = let chunk = Cstruct.create 4096 in try while true do let count = Eio.Flow.single_read flow chunk in let bytes = Cstruct.to_string ~len:count chunk in Buffer.add_string target bytes ; if display && split_lines then String.iter (fun c -> if c = '\n' then display_line () else Buffer.add_char line_buf c) bytes done with End_of_file -> () in let result = ref None in (* The start-up watchdog never returns once a start line arrived; when the window elapses first it stops the timed section like the task timeout. *) let watchdog () = match startup_watch with | None -> Eio.Fiber.await_cancel () | Some watch -> ( match Eio.Time.with_timeout clock watch.window_seconds (fun () -> Ok (Eio.Promise.await started)) with | Ok () -> Eio.Fiber.await_cancel () | Error `Timeout -> Error `Stalled) in let timeout_result = Eio.Time.with_timeout clock timeout_seconds (fun () -> Eio.Fiber.first watchdog (fun () -> (* Feed stdin and read stdout and stderr concurrently *) Eio.Fiber.all [ write_stdin; (fun () -> capture stdout_r stdout_buf ~display:true ()); (fun () -> (* Capture stderr silently - no live streaming to avoid TUI corruption. The full stderr is returned in process_result.stderr for callers to display appropriately (toast for TUI, print for CLI). *) capture stderr_r stderr_buf ()); ] ; (* Wait for process to complete *) let status = Eio.Process.await proc in result := Some status ; Ok ())) in let elapsed_seconds = Eio.Time.now clock -. start_time in (match timeout_result with | Ok () -> () | Error (`Timeout | `Stalled) -> (* The timed capture fibers have stopped, but the process and its pipe writers may still be alive. Drain concurrently with termination so a SIGTERM handler cannot either deadlock on a full pipe or lose its final terminal evidence. *) let recovered = Eio.Time.with_timeout clock 2.5 (fun () -> Eio.Fiber.both (fun () -> try Eio.Process.signal proc Sys.sigterm ; match Eio.Time.with_timeout clock 2.0 (fun () -> Ok (Eio.Process.await proc)) with | Ok _ -> () | Error `Timeout -> Eio.Process.signal proc Sys.sigkill ; ignore (Eio.Process.await proc) with _ -> ()) (fun () -> Eio.Fiber.both (fun () -> capture stdout_r stdout_buf ~display:true ()) (fun () -> capture stderr_r stderr_buf ())) ; Ok ()) in (* On [Error `Timeout] a detached descendant still holds inherited pipe writers after the direct child is gone; the read ends are closed below either way, which keeps timeout normalization bounded. *) ignore (recovered : (unit, [`Timeout]) result)) ; (* Release the read ends now rather than at the end of the caller's switch, so a long-lived switch running many tasks does not accumulate pipe fds. *) Eio.Flow.close stdout_r ; Eio.Flow.close stderr_r ; (* Unregister only after timeout termination and final pipe draining. *) Option.iter (fun g -> Resource_guardian.unregister_pid g pid) guardian ; if Buffer.length line_buf > 0 then display_line () ; let stdout_str = Buffer.contents stdout_buf in let stderr_str = Buffer.contents stderr_buf in let elapsed = duration_of_seconds elapsed_seconds in let cost = match parse_cost with | Some f -> ( try f stdout_str with _ -> None) | None -> None in let finish status exit_code = { status; stdout = stdout_str; stderr = stderr_str; exit_code; elapsed; cost; session_id = None } in match timeout_result, !result with | Error `Stalled, _ -> let window = match startup_watch with Some w -> w.window_seconds | None -> 0. in finish (Failed (startup_stalled_message window)) (-1) | Error `Timeout, _ -> finish Timeout (-1) | Ok (), Some (`Exited 0) -> finish Success 0 | Ok (), Some (`Exited n) -> finish (Failed (Printf.sprintf "Process exited with code %d" n)) n | Ok (), Some (`Signaled n) -> finish (Failed (Printf.sprintf "Process killed by signal %d" n)) (128 + n) | Ok (), None -> finish (Failed "Unknown error") (-1) (* Standard task execution flow shared by all backends. Uses Fun.protect to ensure MCP config cleanup even on exception. *) let run_task_with ~sw ~env ~spec ~build_command ?parse_cost ?parse_stdout ?parse_session_id ?on_stdout ?guardian ?extra_env ?child_env ?startup_watch () = match validate_task_namespace spec with | Some result -> result | None -> let mcp_config_path = setup_mcp_config ~env spec in Fun.protect ~finally:(fun () -> Option.iter (cleanup_mcp_config ~env) mcp_config_path) (fun () -> let cmd, stdin_content = build_command ~mcp_config_path spec in Diagnostics.debug "backend command: %s" (shell_quote_argv cmd) ; let timeout_seconds = duration_to_seconds spec.timeout in let result = run_process ~sw ~env ~cmd ~stdin_content:(Some stdin_content) ~working_dir:spec.working_dir ~timeout_seconds ?parse_cost ?on_stdout ?guardian ?extra_env ?child_env ?startup_watch () in let files_changed = get_git_diff ~sw ~env ~working_dir:spec.working_dir in let agent_text = match parse_stdout with | Some f -> ( try f result.stdout with _ -> "") | None -> "" in let session_id = match parse_session_id with | Some f -> ( try f result.stdout with _ -> None) | None -> None in { status = result.status; files_changed; report = None; elapsed = result.elapsed; cost = result.cost; stdout = result.stdout; agent_text; stderr = result.stderr; exit_code = result.exit_code; session_id; pi_daybreak_attestation = None; })