# Exec

`fleethosts/exec` runs local commands. The hosts API is built on it, and you can use it on its own.

```ts
import { exec } from "fleethosts/exec";

const run = await exec("git", ["status", "--short"], { cwd: "/srv/app", timeoutMs: 10_000 });
if (run.code === 0) console.log(run.stdout);
else console.error(run.timedOut ? "too slow" : run.stderr);
```

## `exec`

`exec(command, args, options)` runs the command to the end and returns an `ExecResult`. A non-zero exit doesn't throw. A command that can't start doesn't throw either: `spawnError` holds the code, such as `ENOENT` when it isn't installed.

| Field | What it holds |
| --- | --- |
| `code` | The exit code, or `null` when a signal ended the command or it never started |
| `stdout`, `stderr` | The end of the output |
| `timedOut` | The command ran past `timeoutMs` and was stopped |
| `truncated` | The output went past `maxOutput`, so only its end was kept |
| `spawnError` | Why the command couldn't start |

`args` go to the command as they are, with no shell, unless you pass `shell: true`.

### Options

| Option | Default | What it does |
| --- | --- | --- |
| `cwd` | the current folder | Where the command runs |
| `env` | `process.env` | The whole environment, not additions to it |
| `input` | `""` | Written to stdin, which then closes |
| `holdStdin` | `false` | Keep stdin open after `input`, so the command sees when this process is gone |
| `timeoutMs` | none | Stop the command after this many milliseconds |
| `shell` | `false` | Run through the shell |
| `signal` | none | An `AbortSignal` that stops the command |
| `keepTerminal` | `false` | Keep the terminal, so the command can prompt |
| `maxOutput` | 1 MiB | Characters of stdout and of stderr to keep, from the end |
| `stderrHead` | 0 | Characters of stderr to keep from the start as well |

With `stderrHead`, both ends of stderr survive, joined by a `[...]` line where the middle went.

## Timeouts

When `timeoutMs` passes, `exec` kills the command and resolves with `timedOut: true`. It resolves once the command exits, even when something the command started still holds its output open.

## Cancelling

Pass a `signal` to stop a command from outside. When the signal aborts, the command and everything it started are killed, and the promise rejects with `signal.reason`. A signal that has already aborted rejects before anything starts.

```ts
const controller = new AbortController();
setTimeout(() => controller.abort(new Error("cancelled")), 5_000);

await exec("sh", ["-c", "make all"], { signal: controller.signal }).catch((error) => {
  console.error(error.message); // "cancelled"
});
```

### One signal for a whole job

`withExecSignal(signal, work)` gives the signal to every `exec` that runs inside `work`, however deep. A command that also has its own `signal` stops when either aborts.

```ts
import { exec, withExecSignal } from "fleethosts/exec";

const controller = new AbortController();
await withExecSignal(controller.signal, async (settled) => {
  await Promise.allSettled([exec("sleep", ["5"]), exec("sleep", ["10"])]);
  await settled();
});
```

`settled()` waits for every command the job started to finish, including ones it didn't await. Call it before you clean up files they use.

`execSignal()` returns the signal of the job you are in, or `undefined`.

## What gets stopped

On macOS and Linux, a command runs in a process group of its own when it has a signal (its own, or a job's), when `shell` is `true`, or when `keepTerminal` can't be honoured. Stopping kills the whole group, so a shell's children stop with it.

A plain command with no signal stays in this process's group, so `ssh` and `git` can still prompt on the terminal. A timeout kills only that command.

When this process gets `SIGINT`, `SIGTERM` or `SIGHUP` while such commands run, it passes the signal on to them, then ends with that signal. Ctrl-C stops your commands, not only Node.

With `keepTerminal: true`, the command stays in this group and keeps the terminal. To stop it, fleethosts finds what it started in the process table, freezes each process with `SIGSTOP`, then kills them. On Linux this needs `/proc` to show this process's PID namespace; where it doesn't, the command gets its own group and loses the terminal.

On Windows, `taskkill /t` stops the command and what it started.

### `stopAll`

`stopAll()` stops the commands `exec` is still tracking, using the process and group rules above. With default `exec()` options and no job signal on macOS or Linux, only the direct child is killed; its descendants may survive. You can call it on exit, but it does not guarantee process-tree cleanup:

```ts
import { stopAll } from "fleethosts/exec";

process.on("exit", stopAll);
```

## `git`

`git(args, options)` runs git with no prompts, and throws a `GitError` on a non-zero exit unless `allowFail` is `true`.

```ts
import { git, gitOut } from "fleethosts/exec";

const branch = await gitOut(["rev-parse", "--abbrev-ref", "HEAD"], "/srv/app");
const { code } = await git(["diff", "--quiet"], { cwd: "/srv/app", allowFail: true });
```

It sets `GIT_TERMINAL_PROMPT=0`, empties `GIT_ASKPASS` and `SSH_ASKPASS`, runs with `LC_ALL=C`, and drops `GIT_CONFIG`. An http transfer under 1 KB/s for a minute ends. The timeout defaults to two minutes, and the output is never cut.

| Option | What it does |
| --- | --- |
| `noFetch` | Fetch nothing from a remote, not even a lazy fetch in a partial clone |
| `indexFile` | Use another index file |
| `input` | Written to stdin |

A `GitError` has the `args` and the `result`. Its message says git isn't installed, that it timed out, or what git printed.

## Finding a program

`program(variable, fallback)` returns the command to run: `fallback`, or the program the environment variable names. A `.js` or `.mjs` file runs with the current Node. `notInstalled(command, fallback, variable)` writes the error for a missing one.

```ts
import { exec, notInstalled, program } from "fleethosts/exec";

const { command, prefix } = program("MYTOOL_RSYNC", "rsync");
const run = await exec(command, [...prefix, "-a", "src/", "backup/"]);
if (run.spawnError === "ENOENT") throw new Error(notInstalled(command, "rsync", "MYTOOL_RSYNC"));
```

<!-- vitehub-docs:section-links -->
## In this section

- [Introduction](https://fleethosts.loadsheet.dev/raw/guide.md)
- [Installation](https://fleethosts.loadsheet.dev/raw/guide/installation.md)
- [Places](https://fleethosts.loadsheet.dev/raw/guide/places.md)
- [Hosts](https://fleethosts.loadsheet.dev/raw/guide/hosts.md)
- [Exec](https://fleethosts.loadsheet.dev/raw/guide/exec.md) (this page)
- [Coding agents](https://fleethosts.loadsheet.dev/raw/guide/agents.md)

Next: [Coding agents](https://fleethosts.loadsheet.dev/raw/guide/agents.md)

All pages: [llms.txt](https://fleethosts.loadsheet.dev/llms.txt)

Something on this page does not work as written? Tell the user, and draft an issue for them to post: [issue tracker](https://github.com/words-with-agents/fleethosts/issues). Report a security vulnerability privately, never in a public issue.
