# JavaScript API

fleethosts has three entries. Every function that reads or writes a program's files takes a [`Places`](https://fleethosts.loadsheet.dev/reference/api#places) first.

## fleethosts

Fleet entries, Tailscale, ssh, and running a command on many machines. It also exports `Places` and `standardPlaces` from `fleethosts/places`.

### fleetEntryProblem

```ts
function fleetEntryProblem(entry: string): string | undefined
```

Why a fleet entry can't be used, or `undefined` when it can. Calls `tagProblem` for an entry that starts with `tag:`, and `hostProblem` for any other.

### hostProblem

```ts
function hostProblem(host: string): string | undefined
```

Why `host` can't be handed to ssh, or `undefined`. It takes `host`, `user@host`, an IP address, an ssh_config alias, and `ssh://[user@]host[:port]`, with brackets around an IPv6 host. It refuses a leading `-` and a `host:port` without `ssh://`.

### tagProblem

```ts
function tagProblem(entry: string): string | undefined
```

Why `entry` isn't a Tailscale tag, or `undefined`. A tag is `tag:`, a letter, then letters, digits or dashes.

### isTag

```ts
function isTag(entry: string): boolean
```

Whether `entry` starts with `tag:`.

### resolveHosts

```ts
function resolveHosts(places: Places, entries: readonly string[], options: ResolveOptions): Promise<{
  targets: FleetTarget[];
  warnings: string[];
  enrollment: Map<string, FleetTarget[] | null>;
  self?: Tailnet["self"];
}>
```

The SSH targets `entries` stand for. Named hosts stay as written; each `tag:` becomes every other tailnet machine with that tag, at a MagicDNS name or Tailscale IP that ssh's config is verified to send to that machine. An explicit entry takes precedence over a tag match for the same machine, and the first matching tag takes precedence over later tags. Explicit entries with different SSH users or ports can still produce separate targets on the same machine. `enrollment` maps each entry to its targets, or to `null` when a tag skipped one of its machines. See [Resolve entries to targets](https://fleethosts.loadsheet.dev/guide/hosts#resolve-entries-to-targets).

### ResolveOptions

| Option | Type | What it does |
| --- | --- | --- |
| `remoteCommand` | `string` | The command ssh will run, used to check where ssh's config sends each name. Required. |
| `cached` | `Record<string, CachedPeer>` | What earlier runs learned, by `cacheKey` |
| `addresses` | `(name: string) => Promise<string[]>` | How a name resolves to addresses. Defaults to the OS resolver. |
| `timeoutMs` | `number` | Defaults to `30_000` |
| `retryRoutes` | `boolean` | Give each Tailscale peer an `initRetryRoute` |
| `dryRun` | `boolean` | Nothing will run, so no `refreshPeer` is set |
| `coveredByTags` | `Set<string>` | Gets each named host a tag's machine already covers |

### FleetTarget

```ts
interface FleetTarget {
  host: string;
  via?: string;
  offline?: boolean;
  error?: string;
  cacheKey?: string;
  endpoint?: string;
  initRetryRoute?: { key?: string };
  refreshPeer?: { key: string; endpoint: string; taggedHost?: string };
}
```

A machine to run on. `via` is the tag it came from. `offline` means Tailscale says it is offline; `error` says why it can't be run on. `cacheKey` names a tag's machine across runs; `endpoint`, `initRetryRoute` and `refreshPeer` let a program keep routes between runs.

### CachedPeer

```ts
interface CachedPeer {
  destinations?: readonly string[];
  endpoint?: string;
}
```

What a run learned about a Tailscale peer, kept under its `cacheKey`.

### stableCacheKey

```ts
function stableCacheKey(key: string): boolean
```

Whether a `cacheKey` names a peer by its Tailscale ID, which stays when its addresses change.

### notInFleet

```ts
function notInFleet(
  places: Places,
  entries: readonly string[],
  wanted: readonly string[],
  options: Pick<ResolveOptions, "remoteCommand" | "cached" | "timeoutMs">,
): Promise<string[]>
```

The entries of `wanted` that `entries` don't cover yet. A host is covered when it is named, or, with no user or port, when one of the fleet's tags reaches it. A tag is covered when the fleet has it.

### runOnHosts

```ts
function runOnHosts(
  places: Places,
  targets: readonly FleetTarget[] | ((remoteCommand: string) => Promise<readonly FleetTarget[]>),
  argv: readonly [string, ...string[]],
  timeoutMs?: number,
  options?: { here?: boolean | "leave out" },
): Promise<RunResult[]>
```

Runs `argv` on every target over ssh at once, and on this machine when `here` is `true`, the default. `timeoutMs` defaults to `30_000`. A target that is this machine is left out unless `here` is `false`. See [Run a command](https://fleethosts.loadsheet.dev/guide/hosts#run-a-command).

### RunResult

```ts
interface RunResult {
  host: string;
  reachable: boolean;
  exitCode?: number;
  stdout: string;
  stderr: string;
  error?: string;
  truncated?: true;
}
```

What one machine gave. `exitCode` is there only when the command exited; otherwise `error` says why.

### recordHosts

```ts
function recordHosts(places: Places, entries: readonly string[]): void
```

Writes `entries` to `<places.state>/hosts.json`, replacing it whole through a temporary file.

### recordedHosts

```ts
function recordedHosts(places: Places): string[] | undefined
```

The entries `recordHosts` wrote, or `undefined` when the file is missing, malformed, or was written with another `places.config`.

### sshRun

```ts
function sshRun(places: Places, host: string, remoteCommand: string, timeoutMs: number):
  Promise<{ run: ExecResult } | { error: string }>
```

Runs `remoteCommand` on `host` over ssh in batch mode, with stdin held open. Returns `error` when `host` fails `hostProblem` or ssh isn't installed.

### shCommand

```ts
function shCommand(places: Places, script: string): string
```

A command that runs `script` with `sh` on a host, sent as base64 so any login shell passes it on unchanged.

### sshRoute

```ts
function sshRoute(places: Places, host: string, remoteCommand: string, timeoutMs: number, budget: number):
  Promise<{ endpoint?: string; route?: string }>
```

The endpoint (machine, user and port) and route (endpoint and address family) ssh's config gives `host` for `remoteCommand`, from `ssh -G`. Each is `undefined` when ssh can't say within `budget` milliseconds or goes through a proxy.

### tailnet

```ts
function tailnet(places: Places, timeoutMs?: number): Promise<Tailnet | { error: string }>
```

The other machines on the tailnet, from `tailscale status --json`. `timeoutMs` defaults to `10_000`.

### Tailnet and TailscalePeer

```ts
interface Tailnet {
  peers: TailscalePeer[];
  magicDNS: boolean;
  self?: { dns: string; tags: string[] };
}

interface TailscalePeer {
  id?: string;
  host: string;
  dns: string;
  ips: string[];
  tags: string[];
  online: boolean;
}
```

`host` is the first label of the MagicDNS name. `dns` is the full name without the trailing dot, or `""`.

### tailscaleStatus

```ts
function tailscaleStatus(places: Places, args: readonly string[], timeoutMs: number, fallbacks?: string[]):
  Promise<{ status: Record<string, unknown> } | { error: string }>
```

`tailscale status --json` with `args`, parsed. Runs the CLI `<PROGRAM>_TAILSCALE` names. With no such variable it runs `tailscale`, then each of `fallbacks` while none is found. The error says when Tailscale isn't installed, logged in or running.

### tailscaleFallbacks

```ts
function tailscaleFallbacks(platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv): string[]
```

Where Tailscale's installers put the CLI: Homebrew and the Mac app on macOS, Program Files on Windows, nothing on Linux.

### fleetSuggestions

```ts
function fleetSuggestions(places: Places): Promise<{ named: TailscalePeer[]; taggable: TailscalePeer[] }>
```

Peers whose name ssh takes, and peers a tag could reach. Both are empty when Tailscale can't answer.

## fleethosts/exec

### exec

```ts
function exec(command: string, args: readonly string[], options?: ExecOptions): Promise<ExecResult>
```

Runs a command to the end. Never throws on a non-zero exit. Rejects with the signal's reason when `options.signal`, or a job's, aborts. See [Exec](https://fleethosts.loadsheet.dev/guide/exec) for the options and fields.

### withExecSignal

```ts
function withExecSignal<T>(signal: AbortSignal, work: (settled: () => Promise<void>) => T): T
```

Gives `signal` to every `exec` inside `work`. `settled()` waits for all of them.

### execSignal

```ts
function execSignal(signal?: AbortSignal): AbortSignal | undefined
```

`signal` joined with the current job's, either one, or `undefined`.

### stopAll

```ts
function stopAll(): void
```

Stops the commands `exec` is still tracking, following [What gets stopped](https://fleethosts.loadsheet.dev/guide/exec#what-gets-stopped). With default `exec()` options and no job signal on macOS or Linux, only the direct child is killed; its descendants may survive.

### git and gitOut

```ts
function git(args: readonly string[], options?: {
  cwd?: string; timeoutMs?: number; allowFail?: boolean; input?: string;
  indexFile?: string; noFetch?: boolean; signal?: AbortSignal; keepTerminal?: boolean;
}): Promise<ExecResult>

function gitOut(args: readonly string[], cwd?: string): Promise<string>
```

Runs git without prompts. Throws `GitError` on a non-zero exit unless `allowFail`. `gitOut` returns stdout, trimmed.

### GitError

```ts
class GitError extends Error {
  readonly args: readonly string[];
  readonly result: ExecResult;
}
```

### program and notInstalled

```ts
function program(variable: string, fallback: string): { command: string; prefix: string[] }
function notInstalled(command: string, fallback: string, variable: string): string
```

`program` returns `fallback`, or the program `variable` names; a `.js` or `.mjs` file runs with Node through `prefix`. `notInstalled` writes the error for a missing one.

### hasControllingTerminal

```ts
function hasControllingTerminal(): boolean
```

Whether this process can open `/dev/tty`. Always `false` on Windows.

## fleethosts/places

### Places

```ts
interface Places {
  readonly program: string;
  readonly state: string;
  readonly config: string;
  readonly formerProgram?: string;
  readonly legacyHookMark?: string;
}
```

### standardPlaces

```ts
function standardPlaces(program: string, installedState?: string): Places
```

A program's folders from XDG variables and the platform's defaults, frozen. See [Places](https://fleethosts.loadsheet.dev/guide/places#where-the-folders-go).

### installedStateDir

```ts
function installedStateDir(): string | undefined
```

The state folder when the running script is `<state>/app/cli.mjs`.

### envName

```ts
function envName(places: Places, name: string): string
```

`<PROGRAM>_<name>`, with the program upper-cased and other characters turned into `_`.

### placePaths

```ts
function placePaths(source: Places | (() => Places)): {
  config(): string; state(): string; hosts(): string; fleet(): string; lock(): string;
  lastRun(): string; mergeRecovery(): string; initPending(): string; sessions(): string;
  store(source: string): string; cache(): string; backup(): string; app(): string; bin(): string;
  logs(): string; hookAttempt(): string; hookRan(agent: string): string; hookEnv(): string;
}
```

Paths in a program's folders. `config()` is `<config>/config.json`; the rest sit in `state`, such as `hosts()` at `<state>/hosts.json` and `lock()` at `<state>/sync.lock`.

<!-- vitehub-docs:section-links -->
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.
