
# Host Commands

> JavaScript functions the guest runs as programs.

```js
const vm = await createKernel({
  commands: {
    hello: (c) => `hello ${c.args.join(" ")} from the host\n`,
    upper: (c) =>
      c.stdin
        .pipeThrough(new TextDecoderStream())
        .pipeThrough(new TransformStream({ transform: (s, out) => out.enqueue(s.toUpperCase()) }))
        .pipeTo(c.stdout),
    fail: () => ({ exitCode: 3 }),
  },
});
await vm.exec("sh", ["-c", "hello world | upper; fail; echo $?"]); // "HELLO WORLD FROM THE HOST\n3\n"

await vm.addCommand("notify", (c) => console.log(c.args)); // at any time
await vm.removeCommand("notify");
```

Host commands are the reverse of [`exec()`](/sdk/programs): a guest program runs a function on your side. Each name becomes `/run/kw/bin/NAME` in the guest, first on `PATH`, so shells, scripts and other programs run it like any other command. Each run is a real guest process with its own pid, arguments, environment, stdio and exit status, and the function is called once for each.

The function gets the process's `name`, `args`, `env`, `cwd`, `pid`, `uid` and `gid`, which of its stdio are terminals (`isTTY`) and the terminal's `cols` and `rows`. It also gets `stdin`, `stdout` and `stderr` as web streams, and a `signal` that aborts when the process is gone (killed, Ctrl-C, a closed pipe). `stdin` is pulled: the guest reads its stdin only as you read, so whatever the function leaves unread stays for the next reader.

What it returns ends the process:

- nothing: exit status 0
- a number (or `{ exitCode }`): that exit status
- a string or bytes: written to stdout, status 0
- `{ signal: "TERM" }`: the process dies by that signal
- a throw or rejection: the message on stderr, status 1

`spawn()` and `exec()` wait until the commands exist in the guest; if they could not be made, the calls reject with a `CommandError`. Commands need vsock (on by default) and run on the thread that owns the VM, in worker mode too. The handlers are not part of a [snapshot](/sdk/snapshots): with `restore`, the guest's commands are replaced by the ones you pass.
