diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b32255e..d4b3fb7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,36 +1,81 @@ -# A tag v builds isbell for Apple silicon Macs and publishes it as a GitHub release, which -# is then mirrored to isbell.fmap.dev/releases for install.sh to download (docs/development.md). The -# asset names carry no version, so a version's directory, or latest, finds them. +# A tag v 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 + run: | + mkdir skill && cp -R integrations/isbell-tools skill/ + printf '%s\n' "${GITHUB_REF_NAME#v}" > skill/isbell-tools/VERSION + tar -C skill -czf isbell-tools.tar.gz isbell-tools + shasum -a 256 isbell-tools.tar.gz > isbell-tools.tar.gz.sha256 - 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 + run: gh release create "$GITHUB_REF_NAME" --generate-notes isbell-*.tar.gz isbell-*.tar.gz.sha256 diff --git a/Cargo.lock b/Cargo.lock index 3388db4..4829ce3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1708,7 +1708,7 @@ checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" [[package]] name = "isbell" -version = "0.8.0" +version = "0.13.0" dependencies = [ "anyhow", "async-trait", @@ -1745,7 +1745,7 @@ dependencies = [ [[package]] name = "isbell-proto" -version = "0.8.0" +version = "0.13.0" dependencies = [ "data-encoding", "ed25519-dalek", @@ -1759,7 +1759,7 @@ dependencies = [ [[package]] name = "isbell-relay" -version = "0.8.0" +version = "0.13.0" dependencies = [ "anyhow", "axum", diff --git a/Cargo.toml b/Cargo.toml index d840a11..297e492 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "0.8.0" +version = "0.13.0" edition = "2024" publish = false @@ -29,7 +29,7 @@ plist = "1" rand = "0.10" reqwest = { version = "0.12", default-features = false, features = ["http2", "rustls-tls-webpki-roots"] } redis = { version = "1.7", features = ["tokio-comp", "connection-manager", "script"] } -rustix = { version = "1", features = ["process"] } +rustix = { version = "1", features = ["fs", "process"] } rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/README.md b/README.md index 175b51f..e741659 100644 --- a/README.md +++ b/README.md @@ -1,38 +1,31 @@ # Isbell -Run AI coding agents on your own Macs. Watch them, answer them and read what they write from any +Run AI coding agents on your own machines. Watch them, answer them and read what they write, from any browser or your iPhone. -![Isbell in a browser: projects and files on the left, a session's chat in the middle, and every running session on the right](docs/workbench.png) + + + Isbell in a browser: projects on the left, an agent asking a question in the middle, and every agent on every machine on the right + -An agent can work for an hour and then stop to ask you one question. Isbell is for that moment: - -- **Every agent in one place**, across all your machines, the ones waiting for you first. -- **Answer from anywhere**: reply in a chat, or work in the agent's real terminal, from a browser - or your phone. Your iPhone can tell you when an agent needs you. -- **See what they made**: Markdown, code, diagrams, images and HTML pages, without opening an editor. -- **Nothing to expose**: your Macs open no port, and the server stores none of your data. - -Your agents keep running on your own Macs, inside [herdr](https://herdr.dev), the terminal workspace -Isbell connects to. Isbell does not replace them or run any model. +An agent can work for an hour and then stop to ask you one question. Isbell is for that moment. +Your agents keep running on your own machines, inside [herdr](https://herdr.dev), the terminal workspace +Isbell connects to; Isbell does not replace them or run any model. Your machines open no port, and the +server stores none of your data. Status: early development. The public server at `isbell.fmap.dev` is provided as is, with no -guarantee of availability; you can [run your own](#self-hosting). - -## What you need +guarantee of availability; you can [run your own](docs/self-hosting.md). -- A Mac with Apple silicon. On other systems, [build from source](#from-source). -- [herdr](https://herdr.dev). Setup offers to install it. -- An agent. Claude Code, Codex and pi are fully supported; any other works through the Terminal. +## Get started -Isbell only sees what runs inside herdr, so start your agents there. +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. -## Set up - -Paste this to the agent on your Mac (Claude Code, Codex, …): +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. @@ -40,164 +33,57 @@ Then: 1. Run `isbell space show` in your own terminal and copy the key. 2. Open and paste it. -3. Run `herdr` and start your agents in it. +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 -`isbell space join ` yourself when it asks. - -Setup also offers a small hook for Claude Code, Codex and pi. It puts what each agent was asked and -what it is doing on its card, and records sessions so that you can find and resume them after their -pane is closed. +machines, so keep it to yourself. For another machine, paste the same text to the agent there, and run +`isbell space join ` yourself when it asks. To do it all by hand: [docs/install.md](docs/install.md). ## What it does -### On a computer - -- **Workbench**: your projects, each one's sessions and files, and a tab for whatever you open, in - one window that remembers where you were. -- **Active Sessions**: every agent on all your machines, the ones asking first, then those just - finished and those running. -- **Look without leaving**: open a session in a drawer over your work and answer the agent there. - ⌘K finds any agent. -- **Chat**: a session reads as turns, from the agent's own record; reply, or answer what it asks in - its terminal ([Codex needs `--no-daemon`](docs/setup.md)). -- **Terminal**: work in any pane from the browser; paste or drop in a file to hand it to the agent. -- **Files**: read what the agents write, on any worktree. Markdown with its outline, math and - diagrams; source with highlighting; images; HTML pages, run apart from the app. -- **Sessions**: a project's past sessions by day, to search, read again or resume. -- **New**: start an agent or a shell in a project, on any machine. -- **Notifications** when an agent asks or finishes, while Isbell is open in a tab. - -### On your iPhone - -Isbell on an iPhone: the sessions asking first, then those just finished and those running - -A remote control for when you are away from your computer, with a layout of its own: +- **Every agent in one place**: across all your machines, the ones asking you first. Look at one in + a drawer without leaving your work; ⌘K finds any. +- **Answer them**: in a chat read from the agent's own record, or in its real terminal; drop in a + file, or speak. +- **Read what they make**: Markdown, code, diagrams, images and HTML pages, on any worktree. Share a + file by a link that lasts an hour, a day or a week. +- **Run a team**: agents take names, keep your goals and tasks, and send you messages that wait for + your answer, with [the isbell-tools skill](integrations/isbell-tools/SKILL.md). +- **Share agents**: let someone else talk to a few of your agents while you watch. +- **Start and resume**: start an agent in any project on any machine, from your own templates; find + and resume past sessions; send a session a message on a schedule. -- See every session, the ones asking you first, and get a push when an agent asks or finishes, even - with Isbell closed. -- Read a session as a chat and reply, or answer in its terminal with a bar of the keys agents ask - for. -- Read the files agents write, start a new session, and find and resume past ones. +## On your iPhone -To set it up: + + + The Isbell iPhone app: a push from an agent asking, the agents with the one asking first, and answering it in the chat + -1. Open in Safari, then Share → Add to Home Screen. -2. Open Isbell from the Home Screen and paste your key. -3. In Settings, turn on **Push to this iPhone**. Pushes need `isbell` 0.3.0 or later on your machines. +A layout of its own: every session, the ones asking first; chat and terminal; files; your tasks and +messages; and a push when an agent asks, finishes or sends you something, even with Isbell closed. -After an update, close the app completely and open it again to get the new version. +The iPhone app is on its way to the App Store. Until then, the web app does the same from your Home +Screen: open in Safari, then Share → Add to Home Screen. Open Isbell from +the Home Screen, paste your key, and turn on **Push to this iPhone** in Settings. ## CLI -`isbell` does the same from a terminal, and copies files between machines: +`isbell` does the same from a terminal, and copies files between machines; `isbell help` lists it +all. ```bash -isbell machine list -isbell machine probe # tries a direct link, shows its path isbell agent prompt / "..." --wait isbell terminal attach / --control -isbell file get : -isbell file share --for 1d # a link to read it, live, from a browser +isbell file share --for 1d ``` -## Privacy and how it works - -```text -+----------------------- relay server -------------------------+ -| relay <--> Redis: in memory only, every key expires | -| stores no user data, logs no message content | -+-----^---------------------------------------------^----------+ - | | - | WSS: status, | WSS, dialled out - | small calls | by the gateway - | | -+-----+--------------+ +------------+---------------+ -| Browser | WebRTC | Each of your Macs | -| isbell.fmap.dev |<===============>| gateway -- herdr -- agents | -+--------------------+ direct +----------------------------+ - terminal and files go direct; through the relay only if that fails -``` - -- **No user data on the server**: the relay only pairs browsers with gateways and passes messages - along. Redis holds routing and each machine's last status, all expiring within 15 minutes, never - on disk. Your key, settings and read marks stay on your machines and in your browser. -- **Direct first**: terminals and files go over a WebRTC direct link; when none can be opened, the - same traffic goes through the relay. -- **TLS, not end to end**: what goes through the relay is visible to the relay as it passes. If that - matters to you, [run your own](#self-hosting). -- **One key per space**: each connection signs with the key, and the relay checks the signature - without ever receiving it. -- **Gateways only dial out**: a machine opens no port. -- **Pages run apart**: an HTML page from a project runs on an origin of its own, so its scripts - cannot reach the app or your key. - -## Install by hand - -```bash -curl -fsSL https://isbell.fmap.dev/install.sh | sh -``` - -This installs the latest release to `~/.local/bin/isbell` after checking its checksum, and offers -herdr's own installer when herdr is missing. Then: - -1. On your first machine: `isbell space init`, which creates your space and prints its key. -2. `isbell gateway install`, which keeps the gateway running on this machine. -3. Open and paste the key. -4. On each other machine: `isbell space join `, then `isbell gateway install`. - -- `isbell space show` prints the key again on any machine in the space. -- `gateway install` makes a launchd user agent: started at login, restarted after a failure, logging - to `~/Library/Logs/isbell/gateway.log`. It keeps the `PATH` of the shell it ran in, so herdr and - the agents are found; run it again after changing `PATH`. -- `gateway status` and `gateway uninstall` check and remove it. - -### Upgrade and uninstall - -- `isbell upgrade` installs the latest release and restarts the gateway. The web app marks a machine - on an older version in the sidebar. -- `ISBELL_VERSION=v0.1.0` before `sh` in the install command installs that release instead. -- To remove Isbell, see [Uninstall](docs/setup.md#uninstall). - -### From source - -On other systems, or to run `main`, with Rust () and herdr installed: - -```bash -cargo install --git https://github.com/bencode/Isbell --locked isbell -``` - -Where `gateway install` is not available, run `isbell gateway run` under a supervisor of your own. - -## Self-hosting - -`deploy/compose.yml` runs the relay with its own Redis, and the web app as static files. It is set up -for `isbell.fmap.dev`, so point it at your own domain: - -1. In `deploy/compose.yml`, set `PUBLIC_ORIGIN` to `wss://your.domain` and adjust the published ports. -2. Create `web/.env.production`: - - ```bash - VITE_RELAY_URL=wss://your.domain/v1/ws - VITE_PREVIEW_ORIGIN=https://preview.your.domain - ``` - -3. From the repository root: `docker compose -f deploy/compose.yml up -d --build`. -4. Put a TLS reverse proxy in front: - - | Site, path | Upstream | - |---|---| - | `your.domain` `/v1/*`, `/healthz` | relay, port 5800 | - | `your.domain`, everything else | web app, port 5801 | - | `preview.your.domain` | preview origin, port 5802 | - -5. On each machine, before creating or joining a space, add `relay = "wss://your.domain/v1/ws"` to - `~/.config/isbell/config.toml`, or set `ISBELL_RELAY`. - -## Development +## More -Building, running a local relay, tests and releasing: [docs/development.md](docs/development.md). +- [How it works, and your privacy](docs/how-it-works.md) +- [Install by hand, upgrade, uninstall, build from source](docs/install.md) +- [Self-hosting](docs/self-hosting.md) +- [Development](docs/development.md) ## License diff --git a/crates/isbell-proto/src/frame/header.rs b/crates/isbell-proto/src/frame/header.rs index 2095ae1..0d783f1 100644 --- a/crates/isbell-proto/src/frame/header.rs +++ b/crates/isbell-proto/src/frame/header.rs @@ -106,6 +106,9 @@ pub enum DataKind { Ping, /// A piece of a byte stream (a file), in either direction. Chunk, + /// A click or a turn of the wheel in a terminal, as JSON: where, in cells, and not how a program + /// would read it, which herdr knows and the caller does not. + Pointer, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/isbell-proto/tests/vectors.json b/crates/isbell-proto/tests/vectors.json index 3ba4485..5df6586 100644 --- a/crates/isbell-proto/tests/vectors.json +++ b/crates/isbell-proto/tests/vectors.json @@ -175,6 +175,16 @@ "mid": "0123456789abcdef" }, "text": "{\"t\":\"data\",\"id\":7,\"k\":\"resize\",\"cols\":120,\"rows\":40,\"mid\":\"0123456789abcdef\"}" + }, + { + "header": { + "t": "data", + "id": 8, + "k": "pointer", + "mid": "0123456789abcdef" + }, + "bodyHex": "7b2274797065223a226d6f757365222c22616374696f6e223a22646f776e222c22636f6c756d6e223a31322c22726f77223a352c226d6f64696669657273223a307d", + "binaryHex": "0000003a7b2274223a2264617461222c226964223a382c226b223a22706f696e746572222c226d6964223a2230313233343536373839616263646566227d7b2274797065223a226d6f757365222c22616374696f6e223a22646f776e222c22636f6c756d6e223a31322c22726f77223a352c226d6f64696669657273223a307d" } ], "pieces": { diff --git a/crates/isbell/src/book/caller.rs b/crates/isbell/src/book/caller.rs new file mode 100644 index 0000000..e31f015 --- /dev/null +++ b/crates/isbell/src/book/caller.rs @@ -0,0 +1,107 @@ +//! Who runs a command: the agent session that the agent's own variables name. + +use std::path::PathBuf; + +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Agent { + Claude, + Codex, + Pi, +} + +impl Agent { + const ALL: [Agent; 3] = [Agent::Claude, Agent::Codex, Agent::Pi]; + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|a| a.as_str() == s) + } + + pub fn as_str(self) -> &'static str { + match self { + Agent::Claude => "claude", + Agent::Codex => "codex", + Agent::Pi => "pi", + } + } + + /// The variables the agent gives its commands: its session's id, and its directory when not + /// its default. + fn vars(self) -> (&'static str, &'static str) { + match self { + Agent::Claude => ("CLAUDE_CODE_SESSION_ID", "CLAUDE_CONFIG_DIR"), + Agent::Codex => ("CODEX_THREAD_ID", "CODEX_HOME"), + Agent::Pi => ("PI_SESSION_ID", "PI_CODING_AGENT_DIR"), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Caller { + pub agent: Agent, + pub session: String, + /// The agent's directory, when not its default. + pub home: Option, + /// Pi's session file. + pub path: Option, + /// The herdr pane the agent runs in. + pub pane: Option, + pub dir: PathBuf, +} + +/// The agent session running the command in `dir`, from `env`; none outside an agent. +pub fn caller(env: impl Fn(&str) -> Option, dir: PathBuf) -> Option { + let set = |name: &str| env(name).filter(|v| !v.is_empty()); + let (agent, session) = + Agent::ALL.into_iter().find_map(|agent| set(agent.vars().0).map(|id| (agent, id)))?; + Some(Caller { + agent, + session, + home: set(agent.vars().1).map(PathBuf::from), + path: (agent == Agent::Pi).then(|| set("PI_SESSION_FILE").map(PathBuf::from)).flatten(), + pane: set("HERDR_PANE_ID"), + dir, + }) +} + +/// The caller of this process. +pub fn this() -> Option { + let dir = std::env::current_dir().ok()?; + caller(|name| std::env::var(name).ok(), dir) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn from(vars: &[(&str, &str)]) -> Option { + let env = |name: &str| vars.iter().find(|(k, _)| *k == name).map(|(_, v)| v.to_string()); + caller(env, PathBuf::from("/w")) + } + + #[test] + fn each_agent_is_told_by_its_own_variables() { + let claude = from(&[ + ("CLAUDE_CODE_SESSION_ID", "c1"), + ("CLAUDE_CONFIG_DIR", "/cc"), + ("HERDR_PANE_ID", "w1:p2"), + ]) + .unwrap(); + assert_eq!((claude.agent, claude.session.as_str()), (Agent::Claude, "c1")); + assert_eq!(claude.home, Some(PathBuf::from("/cc"))); + assert_eq!(claude.pane.as_deref(), Some("w1:p2")); + + let codex = from(&[("CODEX_THREAD_ID", "x1")]).unwrap(); + assert_eq!((codex.agent, codex.home), (Agent::Codex, None)); + + let pi = from(&[("PI_SESSION_ID", "p1"), ("PI_SESSION_FILE", "/s/p1.jsonl")]).unwrap(); + assert_eq!(pi.path, Some(PathBuf::from("/s/p1.jsonl"))); + } + + #[test] + fn outside_an_agent_there_is_no_caller() { + assert_eq!(from(&[("HERDR_PANE_ID", "w1:p2"), ("CLAUDE_CODE_SESSION_ID", "")]), None); + } +} diff --git a/crates/isbell/src/book/goals.rs b/crates/isbell/src/book/goals.rs new file mode 100644 index 0000000..9d0ea0e --- /dev/null +++ b/crates/isbell/src/book/goals.rs @@ -0,0 +1,670 @@ +//! What the user means to get done: goals, a tree of what and why, and the tasks they break into, +//! each followed by one role. Jun's goals, as they are there: goals of one parent come in the order +//! of their importance, tasks of one goal in the order to do them, and an id is one item's for good. + +use std::collections::{HashMap, HashSet}; + +use chrono::{NaiveDate, Weekday}; +use serde::{Deserialize, Serialize}; + +use super::caller::Agent; +use super::{Book, BookError, Version, check_link, is_line}; + +pub const MAX_TITLE: usize = 200; +pub const MAX_OUTCOME: usize = 500; +pub const MAX_TEXT: usize = 4096; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)] +#[serde(rename_all = "lowercase")] +pub enum GoalState { + Open, + Done, + Dropped, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)] +#[serde(rename_all = "lowercase")] +pub enum TaskState { + Todo, + Doing, + Done, + Dropped, +} + +impl TaskState { + fn ended(self) -> bool { + matches!(self, TaskState::Done | TaskState::Dropped) + } +} + +/// How much a task matters beside the others, whatever their goals. P2, as the rest, is kept as +/// none. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum Priority { + P0, + P1, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct Goals { + pub version: Version, + pub last_goal: u64, + pub last_task: u64, + pub goals: Vec, + pub tasks: Vec, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct Goal { + pub id: u64, + /// The goal it serves; none for a top one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub parent: Option, + pub title: String, + /// What counts as done. + pub outcome: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub link: Option, + /// A date, as 2026-11-28. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub due: Option, + /// The user's plan for it: a month as 2026-11, an ISO week as 2026-W48 or a day as 2026-11-23. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub period: Option, + pub state: GoalState, + pub created_at: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ended_at: Option, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct Task { + pub id: u64, + pub goal: u64, + pub title: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub outcome: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub link: Option, + /// The root of its project. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub project: Option, + /// The role that follows it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub owner: Option, + pub state: TaskState, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub priority: Option, + pub created_at: u64, + /// When it first became doing. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub started_at: Option, + /// When it became done or dropped. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ended_at: Option, + /// The agent sessions that added or changed it, in the order they first did. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub sessions: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TaskSession { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub role: Option, + pub agent: Agent, + pub id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub home: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub path: Option, + pub dir: String, + pub at: u64, +} + +/// What an update sets: `None` leaves a field, `Some("")` clears an optional one. `rank`, from 1, +/// places the goal among its siblings; 0 leaves it. +#[derive(Default)] +pub struct GoalChange { + pub title: Option, + pub outcome: Option, + pub text: Option, + pub link: Option, + pub due: Option, + pub period: Option, + /// 0 for a top goal. + pub parent: Option, + pub state: Option, + pub rank: usize, +} + +/// What an update sets, as `GoalChange`; `priority: Some(None)` is P2. +#[derive(Default)] +pub struct TaskChange { + pub title: Option, + pub outcome: Option, + pub text: Option, + pub link: Option, + pub project: Option, + pub owner: Option, + pub goal: Option, + pub state: Option, + pub priority: Option>, + pub rank: usize, +} + +/// Which goals: those not ended, unless `states` or `all` says; `matches` in the title, outcome +/// or text, whatever its case. +#[derive(Default)] +pub struct GoalFilter { + pub states: Vec, + pub all: bool, + pub matches: Option, +} + +/// Which tasks, as `GoalFilter`; `goal` takes that goal's and those of the goals under it. The +/// conditions all hold. +#[derive(Default)] +pub struct TaskFilter { + pub states: Vec, + pub all: bool, + pub owner: Option, + pub project: Option, + pub goal: Option, + pub matches: Option, +} + +/// What `goal show` and `task show` give: the goal and those above it, the top one first, and +/// the tasks shown. +#[derive(Serialize)] +pub struct Shown<'a> { + pub goals: Vec<&'a Goal>, + pub tasks: Vec<&'a Task>, +} + +impl Goals { + pub fn goal(&self, id: u64) -> Option<&Goal> { + self.goals.iter().find(|g| g.id == id) + } + + pub fn task(&self, id: u64) -> Option<&Task> { + self.tasks.iter().find(|t| t.id == id) + } + + /// The goal and those above it, the top one first. + pub fn chain(&self, goal: u64) -> Vec<&Goal> { + let mut chain: Vec<_> = std::iter::successors(self.goal(goal), |g| self.goal(g.parent?)) + .take(self.goals.len() + 1) + .collect(); + chain.reverse(); + chain + } + + /// The goals, each followed by those under it. + fn tree_order(&self) -> Vec<&Goal> { + fn walk<'a>(book: &'a Goals, parent: Option, order: &mut Vec<&'a Goal>) { + for g in book.goals.iter().filter(|g| g.parent == parent) { + if order.len() < book.goals.len() { + order.push(g); + walk(book, Some(g.id), order); + } + } + } + let mut order = Vec::new(); + walk(self, None, &mut order); + order + } +} + +/// The book with an open goal added, the last of its siblings, and its id. +pub fn add_goal(book: Goals, mut g: Goal, now: u64) -> Result<(Goals, u64), BookError> { + g.id = book.last_goal + 1; + (g.state, g.created_at, g.ended_at) = (GoalState::Open, now, None); + let id = g.id; + let mut next = book; + next.last_goal = id; + next.goals.push(g); + next.check()?; + Ok((next, id)) +} + +/// The book with a task to do added, the last of its goal's, and its id. +pub fn add_task(book: Goals, mut t: Task, now: u64) -> Result<(Goals, u64), BookError> { + book.goal(t.goal).ok_or_else(|| no_goal(t.goal))?; + t.id = book.last_task + 1; + (t.state, t.created_at, t.started_at, t.ended_at) = (TaskState::Todo, now, None, None); + t.sessions.clear(); + let id = t.id; + let mut next = book; + next.last_task = id; + next.tasks.push(t); + next.check()?; + Ok((next, id)) +} + +/// The book with the goal changed. One moved to another parent goes last among its new siblings, +/// unless `rank` places it. +pub fn update_goal(book: Goals, id: u64, c: GoalChange, now: u64) -> Result { + let i = book.goals.iter().position(|g| g.id == id).ok_or_else(|| no_goal(id))?; + let mut g = book.goals[i].clone(); + set(&mut g.title, c.title); + set(&mut g.outcome, c.outcome); + set_optional(&mut g.text, c.text); + set_optional(&mut g.link, c.link); + set_optional(&mut g.due, c.due); + set_optional(&mut g.period, c.period); + let parent = c.parent.map(|p| Some(p).filter(|p| *p != 0)); + let moved = parent.is_some_and(|p| p != g.parent); + g.parent = parent.unwrap_or(g.parent); + if let Some(state) = c.state.filter(|s| *s != g.state) { + (g.state, g.ended_at) = (state, (state != GoalState::Open).then_some(now)); + } + let siblings = g.parent; + let mut next = book; + next.goals = place(next.goals, i, g, moved, c.rank, |o| o.parent == siblings); + next.check()?; + Ok(next) +} + +/// The book with the task changed, its times following its state: doing first starts it, done or +/// dropped ends it, todo starts it over. +pub fn update_task(book: Goals, id: u64, c: TaskChange, now: u64) -> Result { + let i = book.tasks.iter().position(|t| t.id == id).ok_or_else(|| no_task(id))?; + let mut t = book.tasks[i].clone(); + set(&mut t.title, c.title); + set_optional(&mut t.outcome, c.outcome); + set_optional(&mut t.text, c.text); + set_optional(&mut t.link, c.link); + set_optional(&mut t.project, c.project); + set_optional(&mut t.owner, c.owner); + let moved = c.goal.is_some_and(|g| g != t.goal); + t.goal = c.goal.unwrap_or(t.goal); + t.priority = c.priority.unwrap_or(t.priority); + if let Some(state) = c.state.filter(|s| *s != t.state) { + (t.state, t.ended_at) = (state, state.ended().then_some(now)); + if state == TaskState::Todo { + t.started_at = None; + } else if state == TaskState::Doing && t.started_at.is_none() { + t.started_at = Some(now); + } + } + let siblings = t.goal; + let mut next = book; + next.tasks = place(next.tasks, i, t, moved, c.rank, |o| o.goal == siblings); + next.check()?; + Ok(next) +} + +/// The book with the session recorded as one that touched the task, once. +pub fn touch(mut book: Goals, task: u64, s: TaskSession) -> Goals { + if let Some(t) = book.tasks.iter_mut().find(|t| t.id == task) + && !t.sessions.iter().any(|o| o.agent == s.agent && o.id == s.id) + { + t.sessions.push(s); + } + book +} + +/// The book without the goal, one nothing is under: any other is dropped instead, for its history +/// to stay. +pub fn delete_goal(mut book: Goals, id: u64) -> Result { + book.goal(id).ok_or_else(|| no_goal(id))?; + if book.goals.iter().any(|g| g.parent == Some(id)) || book.tasks.iter().any(|t| t.goal == id) { + return Err(BookError::invalid(format!( + "goal G{id} has goals or tasks under it: set its state to dropped instead" + ))); + } + book.goals.retain(|g| g.id != id); + Ok(book) +} + +/// The book without the task, one not started: any other is dropped instead. +pub fn delete_task(mut book: Goals, id: u64) -> Result { + let state = book.task(id).ok_or_else(|| no_task(id))?.state; + if state != TaskState::Todo { + return Err(BookError::invalid(format!( + "task T{id} is {}: set its state to dropped instead", + format!("{state:?}").to_lowercase() + ))); + } + book.tasks.retain(|t| t.id != id); + Ok(book) +} + +/// The goals the filter picks, in the tree's order. +pub fn select_goals<'a>(book: &'a Goals, f: &GoalFilter) -> Vec<&'a Goal> { + let picked = |g: &&Goal| { + picked(f.all, &f.states, g.state, g.state != GoalState::Open) + && found(&f.matches, [Some(&g.title), Some(&g.outcome), g.text.as_ref()]) + }; + book.tree_order().into_iter().filter(picked).collect() +} + +/// The tasks the filter picks, by their goals in the tree's order, then in their goal's. +pub fn select_tasks<'a>(book: &'a Goals, f: &TaskFilter) -> Vec<&'a Task> { + let rank: HashMap = + book.tree_order().iter().enumerate().map(|(i, g)| (g.id, i)).collect(); + let under = |goal: u64| f.goal.is_none_or(|top| book.chain(goal).iter().any(|g| g.id == top)); + let same = |want: &Option, have: &Option| { + want.as_ref() + .is_none_or(|w| have.as_ref().is_some_and(|h| h.to_lowercase() == w.to_lowercase())) + }; + let mut tasks: Vec<_> = book + .tasks + .iter() + .filter(|t| { + picked(f.all, &f.states, t.state, t.state.ended()) + && under(t.goal) + && same(&f.owner, &t.owner) + && same(&f.project, &t.project) + && found(&f.matches, [Some(&t.title), t.outcome.as_ref(), t.text.as_ref()]) + }) + .collect(); + tasks.sort_by_key(|t| rank.get(&t.goal).copied().unwrap_or(usize::MAX)); + tasks +} + +/// Whether the state is one asked for: those given, all, or by default those not ended. +fn picked(all: bool, states: &[S], state: S, ended: bool) -> bool { + if states.is_empty() { all || !ended } else { states.contains(&state) } +} + +fn found(text: &Option, fields: [Option<&String>; N]) -> bool { + let Some(text) = text else { return true }; + let text = text.to_lowercase(); + fields.into_iter().flatten().any(|f| f.to_lowercase().contains(&text)) +} + +fn set(to: &mut String, from: Option) { + if let Some(from) = from { + *to = from; + } +} + +fn set_optional(to: &mut Option, from: Option) { + if let Some(from) = from { + *to = Some(from).filter(|f| !f.is_empty()); + } +} + +/// The items with the item, changed, back in: where it was, last when it moved to other siblings, +/// or at `rank` among its siblings. +fn place( + mut items: Vec, + i: usize, + item: T, + moved: bool, + rank: usize, + sibling: impl Fn(&T) -> bool, +) -> Vec { + if !moved && rank == 0 { + items[i] = item; + return items; + } + items.remove(i); + let at = (rank > 0) + .then(|| items.iter().enumerate().filter(|(_, o)| sibling(o)).nth(rank - 1).map(|(j, _)| j)) + .flatten() + .unwrap_or(items.len()); + items.insert(at, item); + items +} + +fn no_goal(id: u64) -> BookError { + BookError::not_found(format!("no goal G{id}")) +} + +fn no_task(id: u64) -> BookError { + BookError::not_found(format!("no task T{id}")) +} + +impl Book for Goals { + const FILE: &'static str = "goals.json"; + + /// IDs are each one item's and none past the last given; a goal's parent is a goal not under + /// it; a task's goal is there; fields hold their forms; a state goes with its times; a session + /// touches a task once. + fn check(&self) -> Result<(), BookError> { + let mut goals = HashSet::new(); + for g in &self.goals { + if g.id < 1 || g.id > self.last_goal || !goals.insert(g.id) { + return Err(BookError::invalid(format!( + "goal {}: id is not its own, from 1 to the last given, {}", + g.id, self.last_goal + ))); + } + check_goal(g).map_err(|e| BookError::invalid(format!("goal G{}: {e}", g.id)))?; + } + for g in &self.goals { + if let Some(parent) = g.parent + && (!goals.contains(&parent) || self.chain(g.id).len() > self.goals.len()) + { + return Err(BookError::invalid(format!( + "goal G{}: parent {parent} is no goal it can serve", + g.id + ))); + } + } + let mut tasks = HashSet::new(); + for t in &self.tasks { + if t.id < 1 || t.id > self.last_task || !tasks.insert(t.id) { + return Err(BookError::invalid(format!( + "task {}: id is not its own, from 1 to the last given, {}", + t.id, self.last_task + ))); + } + if !goals.contains(&t.goal) { + return Err(not_there(t)); + } + check_task(t).map_err(|e| BookError::invalid(format!("task T{}: {e}", t.id)))?; + } + Ok(()) + } +} + +fn not_there(t: &Task) -> BookError { + BookError::not_found(format!("task T{}: goal {} is not there", t.id, t.goal)) +} + +fn check_goal(g: &Goal) -> Result<(), String> { + if (g.state != GoalState::Open) != g.ended_at.is_some() { + return Err("endedAt goes with done and dropped only".into()); + } + if g.due.as_deref().is_some_and(|d| !is_date(d)) { + return Err(format!( + "due {:?} is not a date as 2026-11-28", + g.due.as_deref().unwrap_or_default() + )); + } + if g.period.as_deref().is_some_and(|p| !is_period(p)) { + return Err(format!( + "period {:?} is none of a month as 2026-11, an ISO week as 2026-W48 or a day as 2026-11-23", + g.period.as_deref().unwrap_or_default() + )); + } + check_fields(&g.title, Some(&g.outcome), g.text.as_deref(), g.link.as_deref()) +} + +fn check_task(t: &Task) -> Result<(), String> { + if t.state.ended() != t.ended_at.is_some() { + return Err("endedAt goes with done and dropped only".into()); + } + if t.state == TaskState::Todo && t.started_at.is_some() { + return Err("a task to do has no startedAt".into()); + } + let mut seen = HashSet::new(); + if let Some(s) = + t.sessions.iter().find(|s| s.id.is_empty() || !seen.insert((s.agent, s.id.as_str()))) + { + return Err(format!("{} session {:?} is not one of its own", s.agent.as_str(), s.id)); + } + check_fields(&t.title, t.outcome.as_ref(), t.text.as_deref(), t.link.as_deref()) +} + +/// What goals and tasks both have. +fn check_fields( + title: &str, + outcome: Option<&String>, + text: Option<&str>, + link: Option<&str>, +) -> Result<(), String> { + if !is_line(title, MAX_TITLE) { + return Err(format!("the title must be one line of 1 to {MAX_TITLE} bytes")); + } + if outcome.is_some_and(|o| !is_line(o, MAX_OUTCOME)) { + return Err(format!("the outcome must be one line of 1 to {MAX_OUTCOME} bytes")); + } + if text.is_some_and(|t| t.len() > MAX_TEXT) { + return Err(format!( + "the text has more than {MAX_TEXT} bytes: write it in a file and link to that" + )); + } + link.map_or(Ok(()), |l| check_link(l, false).map_err(|e| e.message)) +} + +fn is_date(s: &str) -> bool { + s.len() == 10 && NaiveDate::parse_from_str(s, "%Y-%m-%d").is_ok() +} + +/// A month, an ISO week of a year that has it, or a day. +fn is_period(s: &str) -> bool { + let digits = |p: &str, n: usize| p.len() == n && p.bytes().all(|b| b.is_ascii_digit()); + let week = + s.split_once("-W").filter(|(y, w)| digits(y, 4) && digits(w, 2)).and_then(|(y, w)| { + NaiveDate::from_isoywd_opt(y.parse().ok()?, w.parse().ok()?, Weekday::Mon) + }); + week.is_some() || (s.len() == 7 && is_date(&format!("{s}-01"))) || is_date(s) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn goal(title: &str, parent: Option) -> Goal { + Goal { + id: 0, + parent, + title: title.into(), + outcome: "done".into(), + text: None, + link: None, + due: None, + period: None, + state: GoalState::Open, + created_at: 0, + ended_at: None, + } + } + + fn task(title: &str, goal: u64) -> Task { + Task { + id: 0, + goal, + title: title.into(), + outcome: None, + text: None, + link: None, + project: None, + owner: None, + state: TaskState::Todo, + priority: None, + created_at: 0, + started_at: None, + ended_at: None, + sessions: Vec::new(), + } + } + + fn state(s: TaskState) -> TaskChange { + TaskChange { state: Some(s), ..TaskChange::default() } + } + + /// G1 with tasks T1, T2, T3. + fn book() -> Goals { + let (b, g) = add_goal(Goals::default(), goal("G", None), 1).unwrap(); + ["a", "b", "c"].iter().fold(b, |b, t| add_task(b, task(t, g), 1).unwrap().0) + } + + fn titles(b: &Goals) -> Vec<&str> { + b.tasks.iter().map(|t| t.title.as_str()).collect() + } + + #[test] + fn a_task_keeps_the_times_of_its_state() { + let b = update_task(book(), 1, state(TaskState::Doing), 10).unwrap(); + let b = update_task(b, 1, state(TaskState::Done), 20).unwrap(); + let t = b.task(1).unwrap(); + assert_eq!((t.started_at, t.ended_at), (Some(10), Some(20))); + let b = update_task(b, 1, state(TaskState::Doing), 30).unwrap(); + assert_eq!((b.task(1).unwrap().started_at, b.task(1).unwrap().ended_at), (Some(10), None)); + let b = update_task(b, 1, state(TaskState::Todo), 40).unwrap(); + assert_eq!(b.task(1).unwrap().started_at, None); + } + + #[test] + fn rank_places_a_task_among_its_goals_and_a_moved_one_goes_last() { + let b = update_task(book(), 3, TaskChange { rank: 1, ..TaskChange::default() }, 1).unwrap(); + assert_eq!(titles(&b), ["c", "a", "b"]); + let (b, g2) = add_goal(b, goal("G2", None), 1).unwrap(); + let b = add_task(b, task("d", g2), 1).unwrap().0; + let b = + update_task(b, 3, TaskChange { goal: Some(g2), ..TaskChange::default() }, 1).unwrap(); + assert_eq!(titles(&b), ["a", "b", "d", "c"]); + assert_eq!( + select_tasks(&b, &TaskFilter { goal: Some(g2), ..TaskFilter::default() }).len(), + 2 + ); + } + + #[test] + fn only_what_has_no_history_is_taken_out() { + let b = update_task(book(), 1, state(TaskState::Doing), 1).unwrap(); + assert!(delete_task(b, 1).is_err()); + assert!(delete_goal(book(), 1).is_err()); + let b = + ["a", "b", "c"].iter().zip(1..).fold(book(), |b, (_, id)| delete_task(b, id).unwrap()); + let b = delete_goal(b, 1).unwrap(); + let (b, id) = add_goal(b, goal("again", None), 1).unwrap(); + assert_eq!((id, b.last_task), (2, 3), "ids never come back"); + } + + #[test] + fn a_goal_serves_none_under_it() { + let (b, g2) = add_goal(book(), goal("under", Some(1)), 1).unwrap(); + assert_eq!(b.chain(g2).iter().map(|g| g.id).collect::>(), [1, 2]); + assert!( + update_goal(b, 1, GoalChange { parent: Some(g2), ..GoalChange::default() }, 1).is_err() + ); + } + + #[test] + fn fields_hold_their_forms() { + let ok = |p: &str| { + let change = GoalChange { period: Some(p.into()), ..GoalChange::default() }; + update_goal(book(), 1, change, 1).is_ok() + }; + assert!(ok("2026-11") && ok("2026-W48") && ok("2026-11-23") && ok("")); + assert!(!ok("2026-W54") && !ok("2026-1") && !ok("next week")); + let blank = TaskChange { title: Some(String::new()), ..TaskChange::default() }; + assert!(update_task(book(), 1, blank, 1).is_err()); + let link = TaskChange { link: Some("file:notes.md".into()), ..TaskChange::default() }; + assert!(update_task(book(), 1, link, 1).is_err()); + } + + #[test] + fn lists_leave_ended_out_unless_asked() { + let b = update_task(book(), 2, state(TaskState::Done), 1).unwrap(); + let open: Vec<_> = select_tasks(&b, &TaskFilter::default()).iter().map(|t| t.id).collect(); + assert_eq!(open, [1, 3]); + assert_eq!(select_tasks(&b, &TaskFilter { all: true, ..TaskFilter::default() }).len(), 3); + let found = TaskFilter { matches: Some("B".into()), all: true, ..TaskFilter::default() }; + assert_eq!(select_tasks(&b, &found).iter().map(|t| t.id).collect::>(), [2]); + } +} diff --git a/crates/isbell/src/book/live.rs b/crates/isbell/src/book/live.rs new file mode 100644 index 0000000..35a6f57 --- /dev/null +++ b/crates/isbell/src/book/live.rs @@ -0,0 +1,112 @@ +//! The agent sessions running now on this machine, from herdr: what Isbell's agent hook reports of +//! each pane (`isbell_agent`, `isbell_session`), else the session herdr's own integration made out +//! (`agent_session`), for an agent started where Isbell's hook is not installed. + +use serde_json::{Value, json}; + +use super::caller::Agent; +use super::roles::Live; +use crate::env_path; +use crate::gateway::herdr::{Herdr, REQUEST_TIMEOUT}; + +/// The sessions herdr runs, by the socket of the pane the command runs in (or +/// `$ISBELL_HERDR_SOCKET`). Outside herdr, or with herdr not answering, none: said on stderr, as +/// sessions there cannot be told running. +pub async fn sessions() -> Vec { + let Some(socket) = env_path("HERDR_SOCKET_PATH").or_else(|| env_path("ISBELL_HERDR_SOCKET")) + else { + tracing::warn!("not in a herdr pane: no agent session is known to run"); + return Vec::new(); + }; + match Herdr::new(socket).request("agent.list", json!({}), Some(REQUEST_TIMEOUT)).await { + Ok(list) => of_list(&list), + Err(err) => { + tracing::warn!(code = %err.code, message = %err.message, "herdr did not list its agents"); + Vec::new() + } + } +} + +fn of_list(list: &Value) -> Vec { + list["agents"].as_array().into_iter().flatten().filter_map(live_of).collect() +} + +/// The session the agent in a pane runs, from herdr's account of it (an item of `agent.list`, or +/// what `agent.get` answers with), if it is known to run one. +pub fn live_of(a: &Value) -> Option { + let agent = Agent::parse(a["agent"].as_str()?)?; + let tokens = &a["tokens"]; + // What the hook left outlives its agent in the pane: it holds for the one that made it. + // The hook's first version, for Claude Code alone, did not say which. + let ours = tokens["isbell_agent"].as_str().unwrap_or("claude") == agent.as_str(); + let session = ours + .then(|| tokens["isbell_session"].as_str()) + .flatten() + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .or_else(|| herdr_session(&a["agent_session"], agent))?; + Some(Live { + agent, + session, + pane: a["pane_id"].as_str()?.to_owned(), + name: a["name"].as_str().map(str::to_owned), + }) +} + +/// The session herdr made out for the agent in the pane now: its id, or the file it is kept in, +/// named `