# Commands for Other Machines

URL: https://tuios.dev/docs/cli-reference/commands-for-other-machines

> Commands for Other Machines: part of the CLI Reference of TUIOS.

This page is one part of `docs/CLI_REFERENCE.md` of the [tuios repository](https://github.com/Gaurav-Gosain/tuios/blob/f32fbfd7faca14e5260a1d711262cb81c49f68a6/docs/CLI_REFERENCE.md). The [CLI Reference](https://tuios.dev/docs/cli-reference) page lists every part.

## Commands for Other Machines

| Command                           | What it does                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `tuios hosts`                     | List the machines in the `[hosts]` config table and the state of each link. A host whose tuios is too old to stream its agents is named below the table, with what to update: its agents are polled and what waits there is not in the Inbox. A host with mail waiting here for its link says how many                                                                                                                                                                                                                                                                                                                                                                                    |
| `tuios hosts add <name> <addr>`   | Add a machine. `--tailnet` takes the address from your tailnet; `--command`, `--ssh-option` and `--connect-timeout` tune the link; `--repos-root DIR` says where the host keeps its checkouts, for `fan --host`, `worktree new --host` and `start-agent -s HOST:SESSION`, and is kept when the host is added again without it, as its link policy fields are                                                                                                                                                                                                                                                                                                                              |
| `tuios hosts setup [DEST] [NAME]` | Set up a machine in one command: test ssh, install tuios when it is missing, start the daemon, add the machine and test the link. `--install copy\|release\|pkg\|script`, `--service`, `--both-ways`, `--tailnet` with `--all` or `--only`, `--yes`, `--dry-run`, `--json`. See [below](https://tuios.dev/docs/cli-reference/commands-for-other-machines#tuios-hosts-setup)                                                                                                                                                                                                                                                                                                               |
| `tuios hosts remove <name>`       | Remove a machine or a paired device. The key that `hosts setup --both-ways` or `tuios pair` added for it is removed from `~/.ssh/authorized_keys` first. When tuios cannot read or write that file, the command fails and the table stays                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `tuios hosts test <name>`         | Open one link to a host and report what happened. `--start` starts the daemon there when it does not run. `--speed` measures how fast a copy to the host can be. `--dry-run`, `--json`. See [below](https://tuios.dev/docs/cli-reference/commands-for-other-machines#tuios-hosts-test)                                                                                                                                                                                                                                                                                                                                                                                                    |
| `tuios cp SRC... DST`             | Copy files and folders between this machine and its hosts, or between two hosts. See [below](https://tuios.dev/docs/cli-reference/commands-for-other-machines#tuios-cp)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `tuios transfers`                 | List the copies the daemon runs, and pause, resume, cancel, wait for or clear them (also `tuios copies`). See [below](https://tuios.dev/docs/cli-reference/commands-for-other-machines#tuios-transfers)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `tuios hosts tailnet`             | List the machines on your tailnet and which are offered as addresses                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `tuios hosts signin [name]`       | Open the Tailscale sign-in page of each host that waits for one, or of the named host. With no desktop, it prints the address. `--print`, `--json`. See [Tailscale SSH check mode](https://github.com/Gaurav-Gosain/tuios/blob/f32fbfd7faca14e5260a1d711262cb81c49f68a6/docs/SESSIONS.md#tailscale-ssh-check-mode)                                                                                                                                                                                                                                                                                                                                                                        |
| `tuios hosts sync [host...]`      | Install the tuios version of this machine on the hosts in the `[hosts]` table, every host when none is named. `--dev` builds a checkout (`--src DIR`, or the current folder), `--binary PATH` sends a file, and a release build fetches its own release. The daemon on a host keeps its old version unless `--restart` is given, which upgrades it live where it can and restarts it where it cannot, listing what a restart would end and asking first (`--yes` without a terminal). `--start` starts each daemon that does not run, after the install. `--dry-run`, `--json`, `--local`. See [below](https://tuios.dev/docs/cli-reference/commands-for-other-machines#tuios-hosts-sync) |
| `tuios pair`                      | Show a QR code that adds this machine to a phone. The phone sends its key, and you accept it. The key can only open a tuios link, with the policy of a new `[hosts.DEVICE]` table. See [below](https://tuios.dev/docs/cli-reference/commands-for-other-machines#tuios-pair)                                                                                                                                                                                                                                                                                                                                                                                                               |
| `tuios stdio-proxy [--as NAME]`   | Hidden. What the other machine's daemon runs over ssh for a link. `--as` pins the name this machine's link policy is resolved for, whatever the other machine calls itself: put it in a forced command in `authorized_keys` (`command="tuios stdio-proxy --as laptop",restrict ...`) to make the policy a boundary. See [What another machine may do here](https://tuios.dev/docs/configuration/permissions#what-another-machine-may-do-here)                                                                                                                                                                                                                                             |

A call over a link that the far machine's policy does not allow fails with
`forbidden`, and the message names the capability and the `[hosts]` table on
that machine that grants it. By default a linked machine may not answer
prompts: `tuios respond -w HOST:SESSION:WINDOW` needs `"respond"` in `allow`
there.

### `tuios pair` (Added in v0.9.3)

Show a QR code that adds this machine to a phone. You do not copy a key by hand.

The tuios phone app is not released yet. An Android app is in private
testing. An iOS app comes later. `tuios pair` pairs a phone with that app.

To use tuios on a phone today:

- Open tuios-web in the browser on the phone. Keep tuios-web on `localhost`
  and reach it over Tailscale or an ssh tunnel, or start it with a password.
  See [Who can connect](https://github.com/Gaurav-Gosain/tuios/blob/f32fbfd7faca14e5260a1d711262cb81c49f68a6/docs/WEB.md#who-can-connect).
- Use [Collie](https://github.com/AltanS/collie) to talk to agents. Collie has
  its own pairing. It does not use `tuios pair`.

```
tuios pair [--name DEVICE] [--machine NAME] [--allow list,mail,open,write,respond,files] [--timeout 5m]
           [--listen HOST:PORT] [--listen-all] [--accept-local] [--authorized-keys PATH]
           [--advertise-ssh HOST:PORT,...] [--advertise-pair HOST:PORT,...]
           [--ssh-port 22] [--host-key PATH] [--command PATH] [--yes] [--json]
```

1. Run `tuios pair` on the machine.
2. Scan the code with the tuios app on the phone.
3. Compare the check code and the key fingerprint on the screen with the ones
   on the phone.
4. Type `y` to accept the key.

The question shows the device name, the check code, the key, the address the
request came from and the allow list:

```
A device asks to pair.
  Name:  phone
  Check: 482916
  Key:   ECDSA SHA256:...
  From:  192.168.1.23:51734
  Allow: list, mail
Compare the check code and the key with the phone. Add this key? [y/N]
```

tuios then changes two files, in this order:

1. It adds a new `[hosts.DEVICE]` table to `config.toml`, with `allow` set to
   `--allow`. Without `--allow`, the list is `list` and `mail`. tuios reads
   the file back. When the table is not there as the policy of the device,
   tuios stops and does not add the key.
2. It adds one line to `~/.ssh/authorized_keys`:

```
command="/usr/bin/tuios stdio-proxy --as phone",restrict ecdsa-sha2-nistp256 AAAA... tuios-pair:phone
```

The key can only run `tuios stdio-proxy --as phone`. `restrict` stops port
forwards, agent forwards and a terminal. The `[hosts.phone]` table sets what
the phone may do here. See
[What another machine may do here](https://tuios.dev/docs/configuration/permissions#what-another-machine-may-do-here).

tuios refuses a device name that is in use here. Case does not matter. A name
is in use when:

- `config.toml` has a `[hosts]` table of that name.
- A forced command in the authorized keys file opens links under that name
  (`stdio-proxy --as NAME`).
- It is the name of this machine.

| Flag                     | What it does                                                                                                                                                                                                                                                                                                                     |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--name DEVICE`          | The device name. It replaces the name the phone sends. Use letters, digits, dot, dash and underscore                                                                                                                                                                                                                             |
| `--machine NAME`         | The machine name in the code. The phone shows it. The default is the host name, up to the first dot                                                                                                                                                                                                                              |
| `--allow LIST`           | The `allow` list of the new `[hosts.DEVICE]` table. The default is `list,mail`. `files` lets the device read and write files here; a write from it lands only under the device's `files_roots` (the receive folder `~/Downloads/tuios` unless you add more in `config.toml`) and never in keys, credentials or shell start files |
| `--timeout D`            | The time the code works. The default is 5 minutes. The maximum is 1 hour                                                                                                                                                                                                                                                         |
| `--listen HOST:PORT`     | Listen on this address. Port 0 picks a free port. Without it, tuios listens on each address in the code                                                                                                                                                                                                                          |
| `--listen-all`           | Let the listener use every interface, as `0.0.0.0` or `[::]` do, or a public address. tuios prints a warning for every interface                                                                                                                                                                                                 |
| `--accept-local`         | Accept a request from this machine. Use it for a phone in an emulator, or for a machine that runs tailscaled in userspace mode, which sends each tailnet connection from `127.0.0.1`                                                                                                                                             |
| `--authorized-keys PATH` | The file for the key. The default is `~/.ssh/authorized_keys`. tuios makes the file (0600) and its folder (0700) when they do not exist                                                                                                                                                                                          |
| `--advertise-ssh LIST`   | The ssh addresses in the code. They replace the addresses tuios finds                                                                                                                                                                                                                                                            |
| `--advertise-pair LIST`  | The pairing addresses in the code. They replace the addresses tuios finds                                                                                                                                                                                                                                                        |
| `--ssh-port N`           | The ssh port for the addresses tuios finds. The default is 22                                                                                                                                                                                                                                                                    |
| `--host-key PATH`        | The ssh host public key in the code. The default is the first of `/etc/ssh/ssh_host_ed25519_key.pub`, `ssh_host_ecdsa_key.pub` and `ssh_host_rsa_key.pub`                                                                                                                                                                        |
| `--command PATH`         | The tuios path in the forced command. See below for the default                                                                                                                                                                                                                                                                  |
| `--yes`                  | Accept the key without a question. Use it for tests only                                                                                                                                                                                                                                                                         |
| `--json`                 | Print the link as the first JSON line and the result as the last                                                                                                                                                                                                                                                                 |

The forced command uses the `tuios` on `PATH`, as `PATH` names it, when that
file is this tuios. For example, it uses `~/.nix-profile/bin/tuios` or
`/opt/homebrew/bin/tuios`, not the file in `/nix/store` or in the Homebrew
`Cellar`. An upgrade replaces that file, and a forced command with its path
stops working. When `tuios` on `PATH` is another binary, or is not there,
tuios uses its own path and prints a warning. Give `--command` to set a path
that stays the same after an upgrade.

tuios finds the addresses itself, in this order:

1. The MagicDNS name of this machine, when `tailscale status --json` answers.
2. Up to three LAN IPv4 addresses. tuios leaves out the interfaces of
   containers, VMs and VPNs.

`s` holds these addresses with the ssh port. `p` holds the addresses that
the listener uses, in the same order. The listener does not use a public
address without `--listen-all`, so `p` can be shorter than `s`. An address in
`p` and the address at the same place in `s` do not always name the same
interface. The phone tries the addresses of each list in order.

tuios refuses the authorized keys file before it shows the code when sshd
would not use keys from it. sshd checks the file, its folder and each folder
above it up to the home folder. tuios refuses one that anyone can write to or
that another user owns. It prints a warning for one that the group can write
to. Debian's sshd accepts a group that holds only you. Other builds of sshd
refuse it.

The code stops when one phone pairs, when the time runs out, or after three
wrong requests. A wrong request is a pairing request with a `mac` that does
not match. A request that is not a pairing request gets an error and does not
count. A key that is in the file already is refused. The key must be ECDSA
P-256, Ed25519, or RSA with 3072 bits or more.

A request with a good `mac` from this machine, or from a machine in the
`[hosts]` table, stops the pairing. A program on such a machine can read the
code from the screen or from a pane, and that program is not the phone.
tuios knows these addresses:

- This machine: each address of its interfaces, loopback included.
  `--accept-local` lets them through.
- A machine in `[hosts]`: the IP in its `addr`, the addresses that the host
  name in `addr` resolves to, and the tailnet IP of the tailnet machine of
  that name. tuios does not ask ssh, so an alias in `~/.ssh/config` with no
  DNS name is not found. `--accept-local` does not change this.

#### The pairing protocol

The QR code holds this link:

```
tuios://pair?v=1&m=MACHINE&u=USER&s=HOST:PORT,...&p=HOST:PORT,...&fp=SHA256:...&t=TOKEN
```

| Field | Value                                                                                   |
| ----- | --------------------------------------------------------------------------------------- |
| `v`   | `1`                                                                                     |
| `m`   | The machine name                                                                        |
| `u`   | The ssh user                                                                            |
| `s`   | The ssh addresses: the tailnet name first, then the LAN addresses                       |
| `p`   | The pairing addresses: the tailnet name first, then the LAN addresses the listener uses |
| `fp`  | The SHA256 fingerprint of the ssh host key, as `ssh-keygen -lf` prints it               |
| `t`   | 16 random bytes in base64url without padding. It works one time                         |

The phone sends `POST /v1/pair` to an address in `p`, with a `Content-Length`
and a JSON body of at most 8 KiB:

```json
{"device": "phone", "key": "ecdsa-sha2-nistp256 AAAA...", "mac": "..."}
```

`mac` is base64url, without padding, of HMAC-SHA256. The HMAC key is the 16
bytes that `t` decodes to. The message is these three lines, joined with
`\n`, with no newline at the end:

```
tuios-pair-v1
phone
ecdsa-sha2-nistp256 AAAA...
```

##### The check code

Both screens show a check code of six digits. The phone computes it before it
sends the request, and shows it while the person answers the question here.

1. Compute HMAC-SHA256 with the 16 bytes of `t` as the key. The message is
   `tuios-pair-v1-check`, a `\n`, and the `key` field of the request, byte
   for byte.
2. Read the first 4 bytes of the result as a big-endian unsigned 32-bit
   integer.
3. Take that number modulo 1000000.
4. Write it as 6 decimal digits, with leading zeros.

A person who scanned the code and sent their own key gets another check code
than the phone shows.

##### The reply

The reply to a good request:

```json
{"ok": true, "device": "phone", "user": "gaurav", "command": "/usr/bin/tuios stdio-proxy --as phone",
 "host_key": "ssh-ed25519 AAAA...", "mac": "...", "check": "482916"}
```

The reply `mac` is made the same way over `tuios-pair-v1-ok`, the device
name and `host_key`. The phone checks this `mac` and checks that the
fingerprint of `host_key` is `fp`. Then it keeps `host_key` as the host key
for the addresses in `s`. `check` is the check code of the request. The phone
compares it with the code it computed. A refused request gets
`{"ok": false, "error": "..."}` and an HTTP status of 400, 403, 404, 405,
409, 410, 411, 413, 429 or 500.

### `tuios hosts test` (Added in v0.8.0)

Open one link to a host and report what happened.

```sh
tuios hosts test build                    # dial build and report
tuios hosts test build --start            # start the daemon on build if it does not run
tuios hosts test build --start --dry-run  # show what --start does, and change nothing
tuios hosts test build --speed            # how fast a copy to build can be
```

| Flag        | What it does                                                                       |
| ----------- | ---------------------------------------------------------------------------------- |
| `--speed`   | Measure the daemon's link to the host: the round trip, and bytes a second each way |
| `--start`   | Start the daemon on the host when it does not run                                  |
| `--dry-run` | Show what `--start` would do and change nothing                                    |
| `--json`    | Print the result as JSON                                                           |

When the host is up and no daemon runs there, the status is `no_daemon`. The
output gives the command to run on the host, with the tuios binary that the
link found:

```
build  gaurav@buildbox  no_daemon
The host is up and no tuios daemon is running on it.
To start the daemon, run this command on the host:
  /home/gaurav/.local/bin/tuios start-server
Or start it from this machine:
  tuios hosts test build --start
```

`--start` runs that command over the same ssh that the link uses. Then it
dials the host again and reports the new state. When a daemon already runs,
`--start` does nothing. When tuios is missing on the host, `--start` starts
nothing: run `tuios hosts sync NAME --start` to install tuios and then start
the daemon. The JSON is the host report, with `action` (`daemon started`,
`would start daemon`, `none` or `start failed`), `before` (the status before
the start) and `start_command`.

When ssh cannot reach the host, the output names what went wrong and how to
fix it. The JSON has `failure` and `fix`, and `fix_command` when a command
fixes it:

| `failure`          | What happened                               | The fix                                                 |
| ------------------ | ------------------------------------------- | ------------------------------------------------------- |
| `host_key_new`     | ssh does not know the host key              | Connect one time with `ssh ADDR true` and check the key |
| `host_key_changed` | The host key changed. This can be an attack | Check the new key with the owner of the host            |
| `auth`             | The host refused your ssh key               | Copy your key with `ssh-copy-id ADDR`                   |
| `dns`              | ssh cannot find the address                 | Check the address                                       |
| `refused`          | No ssh server answers on the port           | Start the ssh server, or check the port                 |
| `timeout`          | The host does not answer                    | Turn on the host, or connect to its network             |

`tuios hosts` prints the same fix under the table, and a `hosts sync --json`
row has the class as `error_kind`, with `fix`.

`--speed` measures the link that the daemon holds to the host, the way a copy
uses it. It needs a running daemon and a link that is up. It takes the middle
of five round trips of a small call. Then it sends 64 MiB of random bytes up
and 64 MiB down, on the same bulk streams that a copy uses. Random bytes do
not compress, so the result is the speed of the link itself:

```
build: round trip 12.4 ms, up 48.2 MiB/s, down 51.7 MiB/s (64.0 MiB each way, random bytes).
```

With `--json` the result has `host`, `bytes` (each way), `rtt_ms`, `up` and
`down` (bytes a second), `up_ms` and `down_ms`. The protocol verb is
`host-speed-test` (see [protocol.md](https://tuios.dev/docs/control-protocol/verbs-other-verbs#files-and-transfers)).

### `tuios hosts setup` (Added in v0.13.1)

Set up another machine for tuios in one command.

```sh
tuios hosts setup gaurav@buildbox --dry-run                           # test ssh and print the plan
tuios hosts setup gaurav@buildbox --name build --install copy --yes   # install, start, add, test
tuios hosts setup gaurav@buildbox --install copy --service --both-ways --yes --json
tuios hosts setup --tailnet --dry-run                                 # the tailnet and each machine's state
tuios hosts setup --tailnet --all --install copy --yes                # every machine that can be set up
tuios hosts setup gaurav@buildbox --no-service --one-way --yes        # no start at boot, this side only
```

`--no-service` does not start tuios at boot on the other machine. `--one-way` does
not add this machine on the other machine. `--ssh-option` passes one extra
argument to ssh, and you repeat the flag for each one.

The steps:

1. Test ssh, with BatchMode on. A failure names its class and its one fix (see
   [`tuios hosts test`](https://tuios.dev/docs/cli-reference/commands-for-other-machines#tuios-hosts-test)).
2. Install tuios when it is missing or too old. `--install copy` sends this
   tuios. For a machine of another platform it sends the release of the same
   version, checked with its sha256, and the result says so in `note`.
   `release` sends the release of this version. `pkg` runs the package manager
   there (`--pkg yay`, `paru`, `brew`, `nix` or `go`). `script` runs the install
   script there. A package manager that asks for a password needs a terminal.
3. With `--service`, install the daemon service there, which starts the
   daemon. Without it, start the daemon.
4. Write `[hosts.NAME]` here, and test the link. A link that does not come up
   is removed again, unless `--keep` is given.
5. With `--both-ways`, add this machine on the other one. That machine first
   tests its way back with BatchMode, to each address of this machine, or to
   `--address`. With `--yes`, the step may add that machine's ssh key to
   `~/.ssh/authorized_keys` here. It prints the key's fingerprint and comment,
   and tags the line, so `tuios hosts remove NAME` takes it out again. When
   that machine cannot connect, nothing is added there.

Without a terminal, every choice comes from a flag. `--install` is the only one
that is required when tuios is missing. A missing choice stops the command
before it changes anything, with exit status 2 and the flag to pass. A dry run
does not stop for it: it plans the first install choice that can run there,
and names it and the other choices by their flags. A step
that needs the person, such as a password or a host key to check, stops it with
exit status 3 and the command to run. tuios never takes a password, and it
never accepts a changed host key.

On a terminal, the command asks for each choice the flags do not make. Pick
how to install tuios from a list that shows each command (`d` shows every
command). Answer start at boot and both ways with `y` or `n`. A fix or a step
that needs you, such as `ssh-copy-id`, runs in the same terminal, and the setup
tests again when it ends. Press ctrl+c at any step to stop. The setup stops at
the end of that step and says what it left: "Stopped. Nothing was added." A
choice that a flag gives is not asked. `--json` and `--dry-run` never ask.

`--as NAME` is the name this machine gets on the other machine in the both-ways
step. Without it, the name comes from this machine's tailnet name or host name.

With `--tailnet` on a terminal, a checklist shows each machine. `space` ticks
a machine, and `a` ticks all that can be set up. `o` gives one machine its own
answers: how to install, start at boot, and both ways. `enter` starts the setup
with the answers under the list. Each machine then gets one line with its step,
and a summary follows at the end. At a fix, `s` skips that machine, and the
others go on. `--all` or `--only` skips the checklist.

`--tailnet` lists the machines on your tailnet with their state: tuios and its
version, no tuios, a Tailscale sign-in first, no ssh, offline, or already
added. An offline machine is never dialed. `--all` or `--only a,b` sets up the
machines with one set of answers. At most 4 run at once, and one failure does
not stop the others. The JSON has `machines`, `skipped` and `summary`.

### `tuios hosts sync` (Added in v0.9.0)

Install the tuios version of this machine on the hosts in the `[hosts]` table.

```sh
tuios hosts sync --dry-run          # the plan, and no change
tuios hosts sync --dev              # install a build of this checkout on every host
tuios hosts sync build lab          # only these hosts
tuios hosts sync build --restart    # install, then upgrade the daemon on build live, else restart it
tuios hosts sync build --start      # install if needed, then start the daemon if it does not run
tuios hosts sync --service          # install the daemon service on each host that has none
tuios hosts sync --restart --yes --json
```

| Flag            | What it does                                                                                                                                                         |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--dev`         | Build the binary from a tuios checkout: `--src DIR`, or else the folder you are in. The version is `dev+COMMIT`, and `dev+COMMIT-dirty.HASH` for a tree with changes |
| `--src DIR`     | The checkout to build. Sets `--dev`                                                                                                                                  |
| `--binary PATH` | Send this binary. A host with a different system fails                                                                                                               |
| `--restart`     | Move each daemon whose version is different onto the new binary: live where it can, else by a restart                                                                |
| `--start`       | Start the daemon on each host where it does not run                                                                                                                  |
| `--service`     | Install the daemon service on each host that has none. See `tuios daemon install-service`                                                                            |
| `--yes`, `-y`   | Move the daemons without a question. Needed for `--restart` without a terminal                                                                                       |
| `--dry-run`     | Show the plan and change nothing                                                                                                                                     |
| `--json`        | Print the result as JSON                                                                                                                                             |
| `--local`       | Sync this machine too. Naming `local` does the same                                                                                                                  |
| `--ghostty`     | Refused: the ghostty backend cannot be cross-compiled                                                                                                                |

First, sync reads every host over ssh at once, four at a time: the system
(`uname -sm`), the tuios that the link finds there, and its version. Then it
reads the daemon over a link of its own. It reads the sessions of the daemon and the
panes that run a program. A pane runs a program when the foreground process of
its terminal is not its shell, or when the pane process is not a shell.

The binary for a release build is the archive of that release for each host
system. sync checks it against the published `checksums.txt` and sends it
over ssh, so the host needs no internet. Without a release, the command
builds the checkout you are in, or asks for `--src` or `--binary`. A build
for each system is made once, with the release flags (`CGO_ENABLED=0`,
`-trimpath`, `-ldflags "-s -w"`), and only for the systems that need it.

The binary goes where the host has tuios, when you can write that folder, and
a configured `command` is where it goes. Otherwise it goes to
`~/.local/bin/tuios`, and sync warns when a login shell on the host does not
find it there. sync never uses sudo. It writes the binary to a temporary file
in the same folder, checks its size and sha256, runs `--version` on it, and
then renames it into place. A daemon that runs the old file keeps running.

sync never touches a daemon by default. The row says that the daemon still runs the old version, and gives the command that moves it. A client of the new version can refuse to connect to an old daemon when the protocol changed.

With `--restart`, sync moves each daemon whose version is different onto the binary it just installed, on that host and against that host's daemon. It runs [`tuios daemon upgrade --binary <installed> --or-restart`](https://tuios.dev/docs/cli-reference/daemon-mode#tuios-daemon-upgrade) there:

- A daemon from a build with live upgrades is upgraded live. It keeps its pid and every program in its panes. The row says `daemon upgraded live`, and in `--json` `daemon.upgraded` is true.
- A daemon that cannot be upgraded live is restarted: one from before live upgrades, one that refuses (a pane on another machine, a running `tuios fan verify`), or one whose protocol the new binary does not speak. A restart is `kill-server`, which saves every session, then `start-server`, which restores them; the layouts come back with new shells, and the programs in them end. The row says `daemon restarted` with a note that names the reason, and `daemon.restarted` is true.
- A daemon that took the upgrade and went back to its old binary, because the new one could not take the panes over, is not restarted. Its programs still run. The host fails with that reason, and `tuios logs` on the host says why.
- A binary without live upgrades (a `--binary` from an older build) restarts the daemon as above, the old binary stopping it before the rename.

Before anything moves, sync lists the sessions on each daemon and the panes with a running program that a restart would end, and asks. A daemon with no sessions is moved without a question. A daemon that already runs the new version is never touched.

On this machine, `--local` from a pane of this machine's daemon only upgrades that daemon live, and never restarts it, since a restart would end the pane the command runs in. The daemon asks for the upgrade in a dialog on every attached client, and sync prints that it waits for your Yes there, for up to a minute. Yes upgrades it live. No, Esc, no answer, or no attached client leaves it on the old version: the row says the binary is installed, the daemon still runs the old version, and to run the sync again with a client attached and answer Yes, or run `tuios daemon upgrade` from a terminal outside tuios. A daemon from before live upgrades cannot be upgraded live, so from a pane it is left too, with a note that asks for the restart from a terminal outside tuios. `tuios --server NAME hosts sync --local` moves the daemon of server NAME and leaves every other daemon alone.

With `--start`, sync starts the daemon on each host where it does not run,
with the binary that the host has after the install. On a host with no
tuios, sync installs tuios first and then starts the daemon. The row says
`daemon started`, and with `--dry-run` it says `would start daemon`. In
`--json`, `daemon.started` is true. Without `--start`, the row for a host
with no daemon gives the command that starts it.

One host that fails does not stop the others. The exit status is 1 when a host
failed. The table has one row per host: the system, the version before and
after, the daemon, and what was done.

All ssh calls of one run to a host use one shared connection, through a
private socket in `$XDG_RUNTIME_DIR` that is removed when the run ends. When
Tailscale SSH in check mode holds the login, one approval covers the run. On a
terminal, sync lists the link to open for each host, and asks to wait up to 5
minutes. Each host continues when you approve its login. Without a terminal,
or with `--json`, the host fails at once. Its row says `needs approval`, and
in `--json` it has `"error_kind": "tailscale_check"` and `approval_url`. A
login the tailnet policy refuses has `"error_kind": "tailscale_policy"`. See
[Tailscale SSH check mode](https://github.com/Gaurav-Gosain/tuios/blob/f32fbfd7faca14e5260a1d711262cb81c49f68a6/docs/SESSIONS.md#tailscale-ssh-check-mode).

### `tuios cp` (Added in v0.9.3)

Copy files and folders between this machine and the hosts in `tuios hosts`.

**Usage:**

```bash
tuios cp [flags] SRC... DST
```

The daemon runs the copy. A closed terminal does not stop it, and it goes on
after a dropped link or a daemon restart. `tuios cp` starts the daemon when
none runs. Every file is checked with sha256 before it is put in place.

**Examples:**

```bash
tuios cp ./build.tar build:                        # to the receive folder on build
tuios cp build:~/logs ./                           # a folder from build to here
tuios cp build:/var/log/app.log gpu:/tmp/          # from one host to another
tuios cp -m ./dist build:~/www/                    # move: remove the original after the check
tuios cp --contents ./site/ build:~/www/           # what is inside site, not site itself
tuios cp --json --conflict replace ./a.bin build:~/  # for a script
tuios cp --detach ./big.iso build:~/iso/           # start the copy and return
```

#### Paths

| Path                               | What it names                                                                              |
| ---------------------------------- | ------------------------------------------------------------------------------------------ |
| `/abs/path`, `./rel`, `~/x`, `rel` | A path on this machine. A relative path is relative to the folder you run the command in   |
| `HOST:/abs/path`                   | An absolute path on the host                                                               |
| `HOST:~/x`                         | A path under the home folder on the host                                                   |
| `HOST:rel`                         | A relative path on a host is under its home folder: `build:logs` is `~/logs` on build      |
| `HOST:`                            | The receive folder of the host (see below)                                                 |
| `local:PATH`                       | A path on this machine. Use it for a path with a colon in it, or write the path as `./a:b` |

The word before the first colon is a host when it is the name of a host in
`[hosts]`, or `local`. A path that starts with `/`, `.` or `~` is always on
this machine. A word before a colon that can be a host name, and is not the
name of a host, is an error with exit code 2. The message suggests the
nearest host name. Write such a path on this machine as `./a:b`.

`HOST:` alone is the receive folder of the host: `~/Downloads/tuios`, or the
first folder of `files_roots` in the config on that host. A host lets this
machine write only in its `files_roots`. So a copy to `build:~/` needs
`files_roots = ["~"]` in the config on build (see
[CONFIGURATION.md](https://tuios.dev/docs/configuration/permissions#what-another-machine-may-do-here)).

#### Files and folders

The rules are the rules of `cp`:

- A DST that is a folder, or that ends in `/`, gets each SRC inside it.
- A DST that does not exist, with one SRC, is the new name.
- Several SRCs need a DST that is a folder and exists.
- A folder copies with all that it holds. `-r` is accepted and changes nothing.
- `--contents` copies what is inside a SRC folder instead of the folder.
- A folder into a folder that exists merges into it, file by file.

Links, named pipes, sockets and devices in a folder are not copied. The
summary names them.

#### Files that are there

A file that is there with the same bytes (sha256) is never copied again. So a
second run of the same copy is a quick check. A file that is there and
differs follows `--conflict`:

| Policy      | Short flag | What it does                                                                          |
| ----------- | ---------- | ------------------------------------------------------------------------------------- |
| `ask`       |            | Ask for each file. The default when stdin and stderr are a terminal, without `--json` |
| `skip`      | `-n`       | Leave the file there as it is. The default in other cases, and always with `--detach` |
| `replace`   | `-f`       | Replace the file there                                                                |
| `keep-both` | `-b`       | Keep the file there, and give the copy a new name                                     |

`keep-both` names a copy from another machine `name (from HOST).ext`, such as
`report (from build).pdf`. A copy on one machine gets a number:
`report 2.pdf`. Give one policy only. Two of `--conflict`, `-n`, `-f` and `-b`
with different policies are an error.

`ask` shows each file, which one is newer and how the sizes differ:

```
~/www/index.html is there on build. The new one is newer, and the new one is 1.20 KiB larger.
Replace it, keep both, or skip? [r/k/s, or R/K/S for all files]
```

An upper case letter gives the same answer for every file of the copy. Another
key is not an answer, and the command asks again. Ctrl+C at the question
cancels the copy and gives no answer. When the terminal cannot be read, the
command also cancels the copy. `ask` needs a terminal. Without one, the
command stops with exit code 2.

#### What a copy keeps

A copy keeps the permission bits and the modification time of each file.
A file that arrives over a link is the exception. It gets the permission bits
under the receiving machine's umask, and never group or world write. The
execute bits stay. A copy from this machine to a host arrives over a link.
`--no-perms` gives each file the default permission bits. `--no-times` gives
each file the time of the copy. A copy never keeps the owner.

On a link the daemon compresses the bytes of a file that compresses well.
`--no-compress` turns this off. `--bwlimit` sets the most bytes a second, such
as `500K` or `5M`. `K`, `M` and `G` are 1024, 1024² and 1024³.

#### Flags

| Flag                  | What it does                                                                              |
| --------------------- | ----------------------------------------------------------------------------------------- |
| `-m`, `--move`        | Remove each original after its copy is checked. A folder move removes only what it copied |
| `-r`, `--recursive`   | Accepted. A folder always copies with all that it holds                                   |
| `--contents`          | Copy what is inside a SRC folder, not the folder itself                                   |
| `--conflict POLICY`   | What to do with a file that is there and differs: `ask`, `skip`, `replace` or `keep-both` |
| `-n`, `--no-clobber`  | The same as `--conflict skip`                                                             |
| `-f`, `--force`       | The same as `--conflict replace`                                                          |
| `-b`, `--keep-both`   | The same as `--conflict keep-both`                                                        |
| `--no-perms`          | Do not copy permission bits                                                               |
| `--no-times`          | Do not copy modification times                                                            |
| `--no-compress`       | Do not compress the bytes on a link                                                       |
| `--bwlimit RATE`      | At most this many bytes a second, such as `500K` or `5M`                                  |
| `--json`              | Print the events of the copy as JSON lines on stdout                                      |
| `-q`, `--quiet`       | Print only errors                                                                         |
| `--detach`            | Start the copy, print its id, and return                                                  |
| `--timeout DURATION`  | Exit 5 when a host stays unreachable this long. The copy goes on                          |
| `--cancel-on-timeout` | With `--timeout`, cancel the copy too                                                     |

#### Output

On a terminal, `tuios cp` draws the progress on stderr: the copy, a bar, the
rate and the time left. A folder copy also shows the file it copies now.
Without a terminal it prints one line for each change of state, and at most
one progress line each ten seconds. At the end it prints one line on stdout
for each copy:

```
Copied 1,204 files, 38.2 MiB, to build:~/www/site (checked).
```

The lines after it name the files that were not copied, and why.

`--detach` prints the id of each copy on stdout and returns. Follow the copy
with `tuios transfers wait ID`. A detached copy has nobody to answer a
question, so its default `--conflict` is `skip`.

#### JSON events

`--json` prints one JSON object on each line of stdout. The `event` field names
the kind:

| `event`               | Fields                                                                                                                                            |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `started`             | `id`, `src`, `dst`, `files`, `bytes`                                                                                                              |
| `progress`            | `id`, `state`, `done`, `size`, `rate`, `eta_ms`, `files`, `files_done`, `current`, `wire_bytes`. At most four a second for each copy              |
| `file`                | `id`, `rel`, `state` (`done`, `same`, `skipped`, `conflict` or `failed`), `sha256`, `code`                                                        |
| `waiting`             | `id`, `host`, `retry_in_ms`, `message`. A host is not reachable. The copy goes on when it is back                                                 |
| `conflict`            | `id`, `rel`, `path`, `src_size`, `src_mtime`, `dst_size`, `dst_mtime`. Only with `--conflict ask`                                                 |
| `done`                | `id`, `dst`, `files`, `files_done`, `bytes`, `wire_bytes`, `same`, `conflicts_skipped`, `conflicts_left`, `skipped`, `verified`, `sha256`, `exit` |
| `failed`, `cancelled` | `id`, `code`, `message`, `exit`. A copy that did not start has `src` instead of `id`                                                              |
| `timeout`             | `exit` (5). A host was not reachable for `--timeout`                                                                                              |

```json
{"event":"started","id":"3f9a1c2b7d00","src":{"path":"/home/me/a.bin"},"dst":{"host":"build","path":"~/"},"files":1,"bytes":52428800}
{"event":"done","id":"3f9a1c2b7d00","dst":"build:~/a.bin","files":1,"files_done":1,"bytes":52428800,"wire_bytes":52428800,"same":0,"conflicts_skipped":0,"conflicts_left":0,"skipped":0,"verified":true,"sha256":"9f2c...","exit":0}
```

`exit` is the exit code this copy gives. The command exits with the worst of
them.

#### A host that goes away

When a host is not reachable, the copy waits for it in the daemon. It goes on
from where it stopped when the host is back. `--timeout 10m` makes the
command exit 5 when a host stays unreachable for ten minutes. The copy goes
on waiting in the daemon, and the command says that it still waits. Add
`--cancel-on-timeout` to cancel the copy too.

#### Ctrl+C

On a terminal, Ctrl+C asks a question:

```
Cancel the copy, or keep it running? [c/k]
```

`k` keeps the copy running in the daemon, and the command returns. Follow the
copy with `tuios transfers`. `c`, or a second Ctrl+C, cancels the copy, and the
command exits 130. Without a terminal, with `--json`, or on SIGTERM, the
command cancels the copy at once.

#### In a pane

A copy started in a pane carries the name of the pane, and the pane grants
decide if the copy may start. `admin` may copy anything. `files` may copy only
inside the folder of the pane, and under the home folders or to the receive
folders of the hosts (see
[`tuios pane-grants`](https://tuios.dev/docs/cli-reference/agent-commands#tuios-pane-grants)).

#### Exit codes of tuios cp

| Code  | What it means                                                                                                                                                           |
| ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `0`   | Every file was copied, or was there with the same bytes                                                                                                                 |
| `1`   | The copy failed. The message says why and what to do                                                                                                                    |
| `2`   | The command line is wrong, or a host name is not known                                                                                                                  |
| `3`   | The copy is done, but some items were not copied: files skipped by the default `--conflict`, links, pipes and devices, or files made at the destination during the copy |
| `4`   | Refused: the pane grants or the link policy of the host do not allow the copy                                                                                           |
| `5`   | A host was not reachable for `--timeout`                                                                                                                                |
| `6`   | A file did not match its original twice, or the file changed during the copy                                                                                            |
| `130` | Cancelled with Ctrl+C                                                                                                                                                   |

A file skipped by a `--conflict` policy that you gave does not give exit 3.

### `tuios transfers` (Added in v0.9.3)

List the copies that the daemon runs, and control them. `tuios copies` is the
same command.

**Usage:**

```bash
tuios transfers [--json]
tuios transfers pause ID... [--json]
tuios transfers resume ID... [--json]
tuios transfers cancel ID... [--json]
tuios transfers wait [ID...] [--json] [-q]
tuios transfers clear [ID...] [--json]
tuios transfers clear-opened
```

`tuios transfers clear-opened` deletes the copies that `o` in the rail made of files
on other machines. `o` copies the file to the user cache and opens the copy. tuios
deletes a copy that nobody opened for 7 days when the daemon starts, or after the
days in `[files] open_copy_keep_days`; this command deletes all of them now. Close
the programs that have a copy open first.

The list has the copies that `tuios cp` started and the copies that other
clients started. A copy that ended stays in the list for 30 minutes, or until
`tuios transfers clear`. In a pane that holds the `files` grant and not
`admin`, the list has only the copies that the pane started. The other
subcommands act only on those copies.

```
╭──────────────┬─────────┬─────────┬──────────────────┬─────────────────────┬───────────────────────────────────────────┬────────────┬──────╮
│ ID           │ STATE   │ NAME    │ FROM             │ TO                  │ DONE                                      │ RATE       │ LEFT │
├──────────────┼─────────┼─────────┼──────────────────┼─────────────────────┼───────────────────────────────────────────┼────────────┼──────┤
│ 3f9a1c2b7d00 │ running │ big.iso │ /home/me/big.iso │ build:~/iso/big.iso │ 1.20 GiB / 4.00 GiB                       │ 48.0 MiB/s │ 59s  │
│ 8c01de4f9a77 │ done    │ site/   │ /home/me/site    │ build:~/www/site    │ 38.2 MiB / 38.2 MiB, 1,204 of 1,204 files │            │      │
╰──────────────┴─────────┴─────────┴──────────────────┴─────────────────────┴───────────────────────────────────────────┴────────────┴──────╯
```

The states are `queued`, `running`, `verifying`, `waiting` (for a host that
went away), `paused`, `conflict` (waits for an answer), `done`, `failed` and
`cancelled`.

| Subcommand      | What it does                                                                                         |
| --------------- | ---------------------------------------------------------------------------------------------------- |
| `pause ID...`   | Pause copies. What they copied stays                                                                 |
| `resume ID...`  | Go on with paused copies, try waiting copies now, or try failed copies again from where they stopped |
| `cancel ID...`  | Cancel copies, and remove the part of the file in flight                                             |
| `wait [ID...]`  | Wait for the copies named, or for every copy that did not end. Show the progress as `tuios cp` does  |
| `clear [ID...]` | Remove the copies that ended from the list, or only the copies named                                 |

`pause`, `resume` and `cancel` exit 1 when one id fails. `--json` prints the
new rows. `clear --json` prints `{"cleared": N}`.

`wait` takes `--json` and `-q` as `tuios cp` does, and prints the same events.
Its exit code is the code `tuios cp` gives for the worst of the copies: `0`,
`1`, `3`, `4`, `6`, or `130` for a cancelled copy. An id that no copy has
exits 1. A copy that waits for a host has not ended, so `wait` goes on
waiting. `wait` cannot see the `--conflict` policy of a copy. So a file that
was there and differs always gives exit 3, as with the default policy of
`tuios cp`.

**Examples:**

```bash
tuios transfers
tuios transfers --json
tuios transfers pause 3f9a1c2b7d00
tuios transfers resume 3f9a1c2b7d00
tuios transfers cancel 3f9a1c2b7d00
tuios transfers wait 3f9a1c2b7d00 --json
tuios transfers clear
```
