Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 48 additions & 13 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -1,33 +1,71 @@
# A tag v<version> builds isbell for Apple silicon Macs and publishes it as a GitHub release, with
# the isbell-tools skill of that version, which is then mirrored to isbell.fmap.dev/releases for
# install.sh and the skill's update.sh to download (docs/development.md). The asset names carry no
# version, so a version's directory, or latest, finds them.
# A tag v<version> builds isbell for Apple silicon Macs and for Linux (x86_64 and arm64, static with
# musl, for any distribution) and publishes them as a GitHub release, with the isbell-tools skill of
# that version, which is then mirrored to isbell.fmap.dev/releases for install.sh and the skill's
# update.sh to download (docs/development.md). The asset names carry no version, so a version's
# directory, or latest, finds them. A pull request that changes this file builds them too, without
# publishing, to see them build before a tag does.
name: Release

on:
push:
tags: ["v*"]
pull_request:
paths: [".github/workflows/release.yml"]

permissions:
contents: write

jobs:
macos-arm64:
runs-on: macos-latest
build:
strategy:
matrix:
include:
- os: macos-latest
target: aarch64-apple-darwin
- os: ubuntu-24.04
target: x86_64-unknown-linux-musl
- os: ubuntu-24.04-arm
target: aarch64-unknown-linux-musl
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4

- name: Check the tag names the crate's version
if: startsWith(github.ref, 'refs/tags/')
run: |
version=$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[] | select(.name == "isbell") | .version')
test "${GITHUB_REF_NAME#v}" = "$version" || { echo "tag $GITHUB_REF_NAME, crate $version"; exit 1; }

- run: cargo build --release --locked -p isbell
# ring, the one dependency with C in it, builds for musl with musl-gcc.
- name: Add musl
if: runner.os == 'Linux'
run: |
sudo apt-get update && sudo apt-get install -y musl-tools
rustup target add ${{ matrix.target }}

- run: cargo build --release --locked -p isbell --target ${{ matrix.target }}

- name: Package
run: |
tar -C target/release -czf isbell-aarch64-apple-darwin.tar.gz isbell
shasum -a 256 isbell-aarch64-apple-darwin.tar.gz > isbell-aarch64-apple-darwin.tar.gz.sha256
asset=isbell-${{ matrix.target }}.tar.gz
tar -C target/${{ matrix.target }}/release -czf "$asset" isbell
shasum -a 256 "$asset" > "$asset.sha256"

- uses: actions/upload-artifact@v4
with:
name: isbell-${{ matrix.target }}
path: isbell-${{ matrix.target }}.tar.gz*

publish:
if: startsWith(github.ref, 'refs/tags/')
needs: build
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4

- uses: actions/download-artifact@v4
with:
merge-multiple: true

# VERSION, only in the package, tells the skill which isbell it goes with: a checkout has none.
- name: Package the skill
Expand All @@ -40,7 +78,4 @@ jobs:
- name: Publish
env:
GH_TOKEN: ${{ github.token }}
run: |
gh release create "$GITHUB_REF_NAME" --generate-notes \
isbell-aarch64-apple-darwin.tar.gz isbell-aarch64-apple-darwin.tar.gz.sha256 \
isbell-tools.tar.gz isbell-tools.tar.gz.sha256
run: gh release create "$GITHUB_REF_NAME" --generate-notes isbell-*.tar.gz isbell-*.tar.gz.sha256
11 changes: 6 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@ guarantee of availability; you can [run your own](docs/self-hosting.md).

## Get started

You need a Mac with Apple silicon ([other systems](docs/install.md#from-source)) and an agent:
Claude Code, Codex and pi are fully supported; any other works through the terminal.
You need a Mac with Apple silicon or a Linux machine, x86_64 or arm64
([other systems](docs/install.md#from-source)), and an agent: Claude Code, Codex and pi are fully
supported; any other works through the terminal.

Paste this to the agent on your Mac:
Paste this to the agent on your machine:

```text
Set up Isbell on this Mac: read https://raw.githubusercontent.com/bencode/Isbell/main/docs/setup.md and follow it.
Set up Isbell on this machine: read https://raw.githubusercontent.com/bencode/Isbell/main/docs/setup.md and follow it.
```

It installs `isbell` (and herdr, if you agree) and runs the gateway. It never sees your space key.
Expand All @@ -35,7 +36,7 @@ Then:
3. Run `herdr` and start your agents in it: Isbell only sees what runs there.

The key is the only credential for your space: anyone who has it can reach the agents on your
machines, so keep it to yourself. For another Mac, paste the same text to the agent there, and run
machines, so keep it to yourself. For another machine, paste the same text to the agent there, and run
`isbell space join <key>` yourself when it asks. To do it all by hand: [docs/install.md](docs/install.md).

## What it does
Expand Down
22 changes: 18 additions & 4 deletions crates/isbell/src/cli/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ use crate::service;
pub enum GatewayCmd {
/// Run the gateway in the foreground.
Run,
/// Run the gateway as a login service (macOS): now, at every login, and again after a failure.
/// Run the gateway as a login service (launchd on macOS, systemd on Linux): now, at every login,
/// and again after a failure.
Install,
/// Stop the service and remove it; the herdr server keeps running.
Uninstall,
Expand All @@ -23,8 +24,11 @@ pub enum GatewayCmd {
}

pub async fn run(ctx: Ctx, cmd: GatewayCmd) -> Result<(), CliError> {
if !matches!(cmd, GatewayCmd::Run) && !cfg!(target_os = "macos") {
return Err(CliError::new("unsupported", "the gateway service needs macOS (launchd)"));
if !matches!(cmd, GatewayCmd::Run) && !service::SUPPORTED {
return Err(CliError::new(
"unsupported",
"the gateway service needs macOS (launchd) or Linux (systemd); elsewhere, run `isbell gateway run` under a supervisor of your own",
));
}
match cmd {
GatewayCmd::Run => run_gateway(ctx).await,
Expand Down Expand Up @@ -77,10 +81,20 @@ fn install(ctx: &Ctx) -> Result<(), CliError> {
true => ctx.out.json(&files),
false => println!(
"gateway service installed and started\n {}\n log: {}",
files.plist.display(),
files.file.display(),
files.log.display()
),
}
// On standard error, which leaves the JSON alone.
match service::stops_at_logout() {
Ok(true) => eprintln!(
"It runs while you are logged in. To keep it running after you log out, and start it at boot:\n sudo loginctl enable-linger $USER"
),
Ok(false) => {}
Err(err) => {
eprintln!("cannot tell whether the service keeps running after you log out: {err:#}")
}
}
Ok(())
}

Expand Down
2 changes: 1 addition & 1 deletion crates/isbell/src/gateway/upgrade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub async fn upgrade() -> Result<Value, RpcError> {
|what: &str, err: std::io::Error| RpcError::new("upgrade_failed", format!("{what}: {err}"));
let home =
env_path("HOME").ok_or_else(|| RpcError::new("upgrade_failed", "HOME is not set"))?;
let dir = home.join("Library/Logs/isbell");
let dir = crate::service::log_dir(&home);
std::fs::create_dir_all(&dir).map_err(|err| failed("cannot create the log directory", err))?;
let path = dir.join("upgrade.log");
let log = File::create(&path).map_err(|err| failed("cannot write upgrade.log", err))?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,10 @@ use std::process::{Command, Output};
use anyhow::{Context, Result, bail};
use serde::Serialize;

use crate::env_path;
use super::Status;

const LABEL: &str = "dev.fmap.isbell.gateway";

#[derive(Debug, Serialize)]
pub struct Files {
pub plist: PathBuf,
pub log: PathBuf,
}

#[derive(Debug, Serialize)]
pub struct Status {
pub installed: bool,
pub running: bool,
pub pid: Option<u32>,
}

/// What launchd runs; see launchd.plist(5).
#[derive(Serialize)]
#[serde(rename_all = "PascalCase")]
Expand All @@ -50,37 +37,37 @@ struct KeepAlive {
successful_exit: bool,
}

/// Writes the service for `exe` with `path_env` as its PATH, and (re)starts it.
pub fn install(exe: &Path, path_env: &OsStr) -> Result<Files> {
let home = home()?;
let files = files(&home);
for dir in [files.plist.parent(), files.log.parent()].into_iter().flatten() {
std::fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?;
}
pub(super) fn file(home: &Path) -> PathBuf {
home.join("Library/LaunchAgents").join(format!("{LABEL}.plist"))
}

/// Writes the service to `plist` for `exe` with `path_env` as its PATH, logging to `log`, and
/// (re)starts it.
pub(super) fn install(
exe: &Path,
path_env: &OsStr,
home: &Path,
plist: &Path,
log: &Path,
) -> Result<()> {
if loaded()? {
launchctl(&["bootout", &target()])?;
}
let agent = agent(exe, path_env, &home, &files.log);
plist::to_file_xml(&files.plist, &agent).context("cannot write the service file")?;
launchctl(&["bootstrap", &domain(), &files.plist.to_string_lossy()])?;
Ok(files)
plist::to_file_xml(plist, &agent(exe, path_env, home, log))
.context("cannot write the service file")?;
launchctl(&["bootstrap", &domain(), &plist.to_string_lossy()])
}

/// Stops the service and removes it; false when it was not installed.
pub fn uninstall() -> Result<bool> {
/// Stops the service, when it is loaded.
pub(super) fn stop() -> Result<()> {
if loaded()? {
launchctl(&["bootout", &target()])?;
}
let plist = files(&home()?).plist;
match std::fs::remove_file(&plist) {
Ok(()) => Ok(true),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(err) => Err(err).with_context(|| format!("cannot remove {}", plist.display())),
}
Ok(())
}

pub fn status() -> Result<Status> {
let installed = files(&home()?).plist.exists();
pub(super) fn status(file: &Path) -> Result<Status> {
let installed = file.exists();
let printed = print()?;
let pid = match printed.status.success() {
true => pid(&String::from_utf8_lossy(&printed.stdout)),
Expand All @@ -103,17 +90,6 @@ fn agent(exe: &Path, path_env: &OsStr, home: &Path, log: &Path) -> Agent {
}
}

fn files(home: &Path) -> Files {
Files {
plist: home.join("Library/LaunchAgents").join(format!("{LABEL}.plist")),
log: home.join("Library/Logs/isbell/gateway.log"),
}
}

fn home() -> Result<PathBuf> {
env_path("HOME").context("HOME is not set")
}

/// This user's login session, where user agents run.
fn domain() -> String {
format!("gui/{}", rustix::process::getuid().as_raw())
Expand Down
103 changes: 103 additions & 0 deletions crates/isbell/src/service/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
//! The gateway as a login service: a launchd user agent on macOS, a systemd user unit on Linux.
//! Either starts it now and again after a failure, and leaves it stopped after a clean exit (another
//! gateway took the machine over). Both are built everywhere, for their tests to run on any system.

mod launchd;
mod systemd;

use std::ffi::OsStr;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use serde::Serialize;

use crate::env_path;

/// Whether this system has a service manager isbell knows.
pub const SUPPORTED: bool = cfg!(any(target_os = "macos", target_os = "linux"));
const LINUX: bool = cfg!(target_os = "linux");

#[derive(Debug, Serialize)]
pub struct Files {
/// What the service manager reads: the launchd plist, or the systemd unit.
pub file: PathBuf,
pub log: PathBuf,
}

#[derive(Debug, Serialize)]
pub struct Status {
pub installed: bool,
pub running: bool,
pub pid: Option<u32>,
}

/// Writes the service for `exe` with `path_env` as its PATH, and (re)starts it.
pub fn install(exe: &Path, path_env: &OsStr) -> Result<Files> {
let home = home()?;
let files = Files { file: file(&home), log: log_dir(&home).join("gateway.log") };
for dir in [files.file.parent(), files.log.parent()].into_iter().flatten() {
std::fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?;
}
match LINUX {
true => systemd::install(exe, path_env, &home, &files.file, &files.log)?,
false => launchd::install(exe, path_env, &home, &files.file, &files.log)?,
}
Ok(files)
}

/// Stops the service and removes it; false when it was not installed.
pub fn uninstall() -> Result<bool> {
let file = file(&home()?);
match LINUX {
true => systemd::stop(&file)?,
false => launchd::stop()?,
}
match std::fs::remove_file(&file) {
Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(err) => return Err(err).with_context(|| format!("cannot remove {}", file.display())),
}
if LINUX {
systemd::reload()?;
}
Ok(true)
}

pub fn status() -> Result<Status> {
let file = file(&home()?);
match LINUX {
true => systemd::status(&file),
false => launchd::status(&file),
}
}

/// Whether the service stops when the user logs out, and waits for them to log in after a boot:
/// a systemd user unit does unless the user lingers.
pub fn stops_at_logout() -> Result<bool> {
match LINUX {
true => systemd::lingers().map(|lingers| !lingers),
false => Ok(false),
}
}

/// Where isbell writes its logs: ~/Library/Logs/isbell on macOS, $XDG_STATE_HOME/isbell (by default
/// ~/.local/state/isbell) on Linux.
pub fn log_dir(home: &Path) -> PathBuf {
match LINUX {
true => {
env_path("XDG_STATE_HOME").unwrap_or_else(|| home.join(".local/state")).join("isbell")
}
false => home.join("Library/Logs/isbell"),
}
}

fn file(home: &Path) -> PathBuf {
match LINUX {
true => systemd::file(home),
false => launchd::file(home),
}
}

fn home() -> Result<PathBuf> {
env_path("HOME").context("HOME is not set")
}
Loading
Loading