{"record":{"id":"040f9ffc13465cd0","repo":"microsoft/aspire","slug":"foundry-cli-command-command-exited-before-producing-required","errorCode":null,"errorMessage":"Foundry CLI command '{command}' exited before producing required output with exit code {process.ExitCode}: {incompleteError}{incompleteOutput}","messagePattern":"Foundry CLI command '(.+?)' exited before producing required output with exit code (.+?): (.+?)(.+?)","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Aspire.Hosting.Foundry/FoundryLocalService.cs","lineNumber":443,"sourceCode":"            using var startCancellationRegistration = startCancellation.Token.Register(static state => KillProcess((Process)state!), process);\n\n            try\n            {\n                // The modern \"server start\" command daemonizes, and the daemon inherits the CLI's\n                // redirected stream handles. Wait until the parent exits and reports its endpoint,\n                // then stop draining instead of waiting forever for EOF from the daemon. If both\n                // streams close first, the CLI exited without producing the required endpoint.\n                await process.WaitForExitAsync(startCancellation.Token).ConfigureAwait(false);\n                var readersCompletionTask = Task.WhenAll(outputTask, errorTask);\n                var completedTask = await Task\n                    .WhenAny(outputCompletionSource.Task, readersCompletionTask)\n                    .WaitAsync(startCancellation.Token)\n                    .ConfigureAwait(false);\n                if (completedTask == readersCompletionTask && !outputCompletionSource.Task.IsCompleted)\n                {\n                    var incompleteOutput = await outputTask.ConfigureAwait(false);\n                    var incompleteError = await errorTask.ConfigureAwait(false);\n                    throw new InvalidOperationException(\n                        $\"Foundry CLI command '{command}' exited before producing required output with exit code {process.ExitCode}: {incompleteError}{incompleteOutput}\");\n                }\n            }\n            catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)\n            {\n                throw new TimeoutException($\"Timed out waiting for Foundry CLI server startup after {s_serviceStartTimeout}.\");\n            }\n            finally\n            {\n                readCancellation.Cancel();\n                await Task.WhenAll(outputTask, errorTask).ConfigureAwait(false);\n            }\n        }\n        else\n        {\n            await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);\n        }\n","sourceCodeStart":425,"sourceCodeEnd":461,"githubUrl":"https://github.com/microsoft/aspire/blob/25830f84bd145686607ad00c057b3f84e2e51d43/src/Aspire.Hosting.Foundry/FoundryLocalService.cs#L425-L461","documentation":"During Foundry service startup (stopReadingAfterProcessExit=true), RunProcessAsync waits for the daemonizing `foundry` start command to exit and to emit the required endpoint line. If both output streams close (the process exited) before the endpoint/completion predicate matched, this InvalidOperationException is thrown with the captured partial output and exit code. It means the CLI terminated without ever reporting a service endpoint.","triggerScenarios":"StartCliServerAsync -> RunFoundryCommandCoreAsync -> RunProcessAsync with stopReadingAfterProcessExit=true, when the foundry server-start process exits (success or failure) without a line matching the endpoint completion predicate, e.g. 'Service is Started on <url>'.","commonSituations":"Foundry service fails at startup due to port conflicts, missing runtime dependencies, or corrupt local state; an outdated CLI version whose startup banner no longer matches the expected format; the service dies immediately after spawn (GPU/driver issues, insufficient resources); another Foundry instance crashed leaving stale state.","solutions":["Inspect the exit code and partial output in the message; run `foundry service start` manually to see the real startup error.","Check for port conflicts or a stale/hung Foundry service: `foundry service status`, stop it (`foundry service stop`) and retry.","Update the Foundry Local CLI — older versions may not emit the endpoint line this integration parses.","Look for machine-level issues in the output: GPU driver errors, out-of-memory, or missing prerequisites, and fix them before restarting.","Clear/reinitialize local Foundry state if the service is stuck in a bad state, then start the service again."],"exampleFix":"// before: stale service blocks startup and the CLI exits without an endpoint\n// after: reset the service before starting the app host\n// $ foundry service stop\n// $ foundry service status\n// $ foundry service start   # confirm 'Service is Started on http://...'\n// $ dotnet run --project MyApp.AppHost","handlingStrategy":"try-catch","validationCode":"// Before launching the AppHost, confirm the service can start cleanly:\n//   foundry service stop; foundry service start; foundry service status\nvar psi = new ProcessStartInfo(\"foundry\", \"service status\") { RedirectStandardOutput = true, UseShellExecute = false };\nusing var p = Process.Start(psi)!;\nvar status = await p.StandardOutput.ReadToEndAsync();\nbool serviceHealthy = status.Contains(\"running\", StringComparison.OrdinalIgnoreCase);","typeGuard":null,"tryCatchPattern":"try\n{\n    await foundryResource.StartAsync();\n}\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"exited before producing required output\"))\n{\n    logger.LogError(ex, \"Foundry CLI exited without reporting an endpoint: {Message}\", ex.Message);\n    // Inspect the embedded exit code/output, fix the root cause, then retry.\n}","preventionTips":["Run `foundry service start` manually and confirm the endpoint banner before wiring it into the AppHost.","Keep the Foundry Local CLI updated so its startup output matches the expected format.","Watch for port conflicts and stale service state; stop/reset the service before repeated local runs.","Check GPU drivers and machine resources if the service dies immediately after spawn."],"tags":["foundry","cli","service-startup","process-exit"],"backgroundTag":"connection-refused","analyzedSha":"25830f84bd145686607ad00c057b3f84e2e51d43","analyzedAt":"2026-09-16T11:10:06.193Z","contentChangedAt":"2026-09-16T11:10:06.193Z","schemaVersion":2},"datasetVersion":"2026-09-21T04:17:39.646Z"}