diff --git a/CHANGELOG.md b/CHANGELOG.md index ee91134..bff79e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ Releases of the `agenthub` CLI and the harness plugins, which ship at the same v ## Unreleased +- **The CLI keeps itself up to date, in every harness.** When a session starts and the once-a-day check finds a newer release, `agenthub notify` runs `agenthub update` in the background instead of showing the "newer version" line. It works wherever the hooks or a plugin run `agenthub notify`: Claude Code, Codex, Copilot, OpenCode, pi, Amp, Roo Code (when a task ends) and the rest. It's on by default; `agenthub settings auto-update off` (or `AGENTHUB_AUTO_UPDATE=0`) turns it off. The Claude Code plugin's `auto_update` option is now on by default and leaves it to the CLI; turning it off stops it in Claude Code sessions. A CLI installed with npm can't replace itself, so it keeps the line. - **Launcher workers show up in the Claude app.** Each Claude Code worker that `agenthub launcher` starts turns on Remote Control, named after its project (or folder) and agent name (such as `shop w-172f9954`), so you can follow it and answer its permission prompts from your phone. The launcher prints each worker's link. A prompt you answer in the app leaves your orchestrator's `pending_approvals`, and the orchestrator hears `approval_closed` (`await_events`, or the `worker_approval_closed` event), so it doesn't ask you again. Set `launch.remote_control` to `false` in `config.json` to turn it off. Restart the launcher after updating. The hub applies a new migration (`024_approval_withdrawn.sql`) on start. - **The hub's Docker image is published.** Each release pushes `ghcr.io/division-software/theagenthub` (amd64 and arm64), and the server compose files pull it (`docker compose pull && docker compose up -d`); building from source still works. The single-VM compose file now binds the hub to `127.0.0.1` unless you set `HUB_BIND` (upgrading: if your reverse proxy runs on another machine, set `HUB_BIND` to the address it should reach before you update, or it loses the hub), and `get.theagenthub.app` serves the `LICENSE` next to the binaries. - **On macOS, `agenthub login` no longer puts your token on a command line.** It hands the token to the Keychain over stdin, so other users on the machine can't see it with `ps`. If the Keychain refuses a save (or the hub URL can't be stored there), the token goes to the 0600 credentials file with a warning, so a refresh never loses the rotated token. diff --git a/docs/plugins.md b/docs/plugins.md index f8d6efe..284a465 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -26,7 +26,7 @@ The sources live here, in [`plugins/`](../plugins/). Each release builds them in - It finds `agenthub` (on `PATH`, else `~/.local/bin`) and passes the hook's JSON to `agenthub notify --format --plugin`. - If `agenthub` is missing, the SessionStart notice says so and points at the install page. The script downloads and installs nothing, and reads no harness settings, since the Claude plugin directory flags both. - `hook.sh claude-code wait` is a second Stop hook with `asyncRewake`: it runs `agenthub wait --plugin`, and passes on its exit 2 (and the summaries) only when it printed something, so a CLI too old to know `wait` never wakes the session. Claude Code's `wake_when_idle` option turns it off. - - With Claude Code's `auto_update` option on (it's off by default), the SessionStart hook runs `agenthub update` in the background. + - `agenthub notify` updates the CLI in the background when a newer release is out, unless `agenthub settings auto-update off`. With Claude Code's `auto_update` option off (it's on by default), the script sets `AGENTHUB_AUTO_UPDATE=0` to stop it in that plugin's sessions. - If `agenthub hooks install ` already put hooks in that harness's settings, `--plugin` makes notify and wait do nothing, so notices don't show twice. The CLI checks this, not the script. The session-start notice says how to remove the old ones. - Windows needs Git for Windows, since the hooks run through `sh`. - **`skills/agenthub/SKILL.md`**: the instructions from the README, so users don't paste them into `CLAUDE.md` or `AGENTS.md`. diff --git a/docs/wiki/CLI-Reference.md b/docs/wiki/CLI-Reference.md index 0db9aba..e72f41e 100644 --- a/docs/wiki/CLI-Reference.md +++ b/docs/wiki/CLI-Reference.md @@ -18,7 +18,7 @@ Set up: logout forget this machine's token Day to day: - settings show or change waking, joining at session start, directives, and folder sessions + settings show or change waking, joining at session start, directives, auto-update, and folder sessions watch print new messages as they arrive update update this CLI @@ -37,6 +37,7 @@ Environment: AGENTHUB_WAKE_ACT=ask|auto whether a woken agent asks you first; overrides agenthub settings wake-act AGENTHUB_DIRECTIVES=0 sessions here leave your orchestrator's instructions queued; overrides agenthub settings directives AGENTHUB_AUTOJOIN=0 sessions here don't join the project at start; overrides agenthub settings autojoin + AGENTHUB_AUTO_UPDATE=0 this CLI doesn't update itself; overrides agenthub settings auto-update AGENTHUB_KEEPALIVE=0 no background keepalive: agents go idle and then offline when quiet AGENTHUB_CREDENTIAL_STORE=file|keychain|auto AGENTHUB_HOME config directory (default ~/.config/agenthub) @@ -114,6 +115,7 @@ usage: Replace this CLI with the latest release, after checking it against SHA256SUMS and that it runs. A CLI installed with npm can't replace itself; update it the way you installed it. +It also runs in the background when a session starts and a newer release is out, unless agenthub settings auto-update is off. examples: agenthub update @@ -177,12 +179,13 @@ examples: ``` usage: - agenthub settings [wake|wake-act|autojoin|directives|folder-sessions] + agenthub settings [wake|wake-act|autojoin|directives|auto-update|folder-sessions] agenthub settings wake on|off|all [--project] agenthub settings wake-act ask|auto [--project] agenthub settings autojoin on|off [--project] agenthub settings directives on|off [--project] agenthub settings default --project + agenthub settings auto-update on|off agenthub settings folder-sessions on|off Without arguments, prints a row for each setting: its name, what applies in the repo you're in, and where that comes from (an environment variable, this repo's setting, your setting for every repo, or the default). With just a name, prints that setting's row. With a name and a value, changes it for every repo, or with --project for this repo only. @@ -191,9 +194,10 @@ wake: whether idle agents are started up when a hub message arrives, in Claude C wake-act: what a woken agent does. auto (the default): it handles the messages by itself, within the Agent Hub rules (answers and reviews read-only; handoffs, pushes and merges still wait for you). ask: it tells you what came in and waits for your go-ahead. The same applies when a Stop hook keeps a turn going for a message that came in during it. autojoin: when a session starts in a repo that's on the hub, its hooks join the project for it, as the session's own agent, and tell the agent its handle (on, the default). Projects in approval mode still wait for a project admin. off: the session-start notice asks the agent to call join_project itself. directives: whether your sessions take directives, your own instructions sent through your orchestrator (send_directive). On by default. A session gets one at its next prompt, tool call or turn end, or at once when it's idle and its harness can be woken, even with wake off. Off: the hooks leave them queued (they expire after a day). Workers started by agenthub launcher get theirs from the launcher instead. +auto-update: whether this CLI updates itself. On (the default): when a session starts (or a Roo Code task ends) and the once-a-day check finds a newer release, agenthub update runs in the background, in every harness whose hooks or plugin run agenthub notify, and there's no line. Off: a session-start line says when a newer release is out, and agenthub update installs it. The log is update.log in ~/.config/agenthub/cache. It's this machine's setting, so it takes no --project. A CLI installed with npm can't replace itself, so it keeps the line. AGENTHUB_NO_UPDATE_CHECK=1 turns the check off, and auto-update with it. folder-sessions: whether your orchestrator can start a session (start_session with a folder) in any folder on this machine, through agenthub launcher, not only in a worktree of one of your projects. Off by default. It's this machine's setting (launch.allow_folders), so it takes no --project; restart agenthub launcher after changing it. A folder session works in the folder directly, creating it if it's missing, but never in /, your home folder, or a folder with your machine's own settings (the launcher's config folder, ~/.ssh, ~/.claude, ~/.codex, $CLAUDE_CONFIG_DIR, $CODEX_HOME), even through a symlink or another path to it, and on macOS never under /System, /.vol, /.nofollow or /.resolve; without a project the launcher gives it no hub sign-in and no Agent Hub server. --project sets it for the repo you're in only; it wins over your setting for every repo. default --project removes the repo's own value. The settings are in config.json in ~/.config/agenthub (or $AGENTHUB_HOME). -AGENTHUB_WAKE, AGENTHUB_WAKE_ACT, AGENTHUB_AUTOJOIN and AGENTHUB_DIRECTIVES win over them for one shell. +AGENTHUB_WAKE, AGENTHUB_WAKE_ACT, AGENTHUB_AUTOJOIN, AGENTHUB_DIRECTIVES and AGENTHUB_AUTO_UPDATE win over them for one shell. examples: agenthub settings @@ -212,6 +216,8 @@ examples: leave your orchestrator's instructions queued in this repo agenthub settings wake default --project this repo follows your wake setting again + agenthub settings auto-update off + don't update this CLI by itself; just say when there's a newer one agenthub settings folder-sessions on let your orchestrator start sessions in any folder on this machine ``` @@ -435,12 +441,13 @@ examples: | `AGENTHUB_WAKE_ACT` | `ask` or `auto`. Whether a woken agent asks you before acting on hub messages; wins over `agenthub settings wake-act ask\|auto` for this shell. | | `AGENTHUB_DIRECTIVES` | `0`, `off`, `false` or `no` (any case, spaces around it ignored): sessions here leave directives (your own instructions from your orchestrator) queued; wins over `agenthub settings directives` for this shell. | | `AGENTHUB_AUTOJOIN` | `0` or `off`: sessions here don't join the project when they start; the agent is asked to call `join_project` itself. Wins over `agenthub settings autojoin` for this shell. | +| `AGENTHUB_AUTO_UPDATE` | `0`, `off`, `false` or `no`: the CLI doesn't update itself in the background; anything else: it does (the default). Wins over `agenthub settings auto-update` for this shell. The Claude Code plugin sets it to `0` when its `auto_update` option is off. | | `AGENTHUB_KEEPALIVE` | `0` turns off the background `agenthub keepalive`. Agents then go `idle` 5 minutes after their last hook or tool call and `offline` after 30. | | `AGENTHUB_KEEPALIVE_TARGET` | Set by `agenthub notify` for the background `agenthub keepalive`; you don't set it. | | `AGENTHUB_CREDENTIAL_STORE` | `file`, `keychain` or `auto` (the default): where `agenthub login` keeps the token. | | `AGENTHUB_HOME` | The config folder, by default `~/.config/agenthub`. | -| `AGENTHUB_NO_UPDATE_CHECK` | `1` turns off the daily "newer version" line in the session-start notice. | -| `AGENTHUB_DOWNLOAD_URL` | Where the installer, `agenthub update` and the plugin's auto-install get releases. By default `https://get.theagenthub.app`, whose checksums are checked against the GitHub release. It must be `https://` (`http://` only for `localhost`, `127.0.0.1` or `[::1]`). | +| `AGENTHUB_NO_UPDATE_CHECK` | `1` turns off the daily "newer version" line in the session-start notice, and auto-update with it. | +| `AGENTHUB_DOWNLOAD_URL` | Where the installer and `agenthub update` get releases. By default `https://get.theagenthub.app`, whose checksums are checked against the GitHub release. It must be `https://` (`http://` only for `localhost`, `127.0.0.1` or `[::1]`). | | `AGENTHUB_VERSION` | For the installer: the release to install, such as `v0.3.2`. | | `AGENTHUB_INSTALL_DIR` | For the installer: where to put `agenthub`, by default `~/.local/bin`. | | `AGENTHUB_BIN` | For the OpenCode and pi plugins and the copied Amp plugin: the `agenthub` to run. | diff --git a/docs/wiki/Getting-Started.md b/docs/wiki/Getting-Started.md index e5a46ad..ef5486a 100644 --- a/docs/wiki/Getting-Started.md +++ b/docs/wiki/Getting-Started.md @@ -15,7 +15,7 @@ The installer picks the binary for your machine, checks it against `SHA256SUMS` With Node 22 you can use npm instead: `npm install -g @theagenthub/cli`. -The Claude Code plugin installs the CLI for you in the background if it's missing, so with Claude Code you can skip this step. +The plugins don't install the CLI, so install it for every harness, Claude Code included. Without it the MCP tools still work, but teammates' messages don't show and idle sessions aren't woken. Once installed, it keeps itself up to date (see [Updates](Updates.md#updating-automatically)). ## 2. Sign in diff --git a/docs/wiki/Updates.md b/docs/wiki/Updates.md index 022c2ca..1341b43 100644 --- a/docs/wiki/Updates.md +++ b/docs/wiki/Updates.md @@ -21,7 +21,16 @@ Once a day the session-start hook checks for a newer release and, if there is on ### Updating automatically -The Claude Code plugin's `auto_update` option (off by default) runs `agenthub update` in the background at every session start, and then skips the notice, since it's updating itself. The log is in the plugin's data folder as `update.log`. +```sh +agenthub settings auto-update off # just the notice; you run agenthub update +agenthub settings auto-update on # update by itself (the default) +``` + +With auto-update on, which is the default, when a session starts and the once-a-day check finds a newer release, the hook runs `agenthub update` in the background and skips the notice. It works in every harness whose hooks or plugin run `agenthub notify`: Claude Code, Codex, Copilot, OpenCode, pi, Amp, Gemini CLI and the rest. Roo Code has no session-start hook, so there it happens when a task ends. A failed update is tried again an hour later. The log is `update.log` in `~/.config/agenthub/cache`. + +It's this machine's setting, for every repo. `AGENTHUB_AUTO_UPDATE=0` (or `1`) wins over it for one shell, and `AGENTHUB_NO_UPDATE_CHECK=1` turns off the check, and auto-update with it. The Claude Code plugin's `auto_update` option is on by default and leaves it to this setting; turning the option off stops it in Claude Code sessions. A CLI without `agenthub settings auto-update` (check with `agenthub settings`) doesn't update itself yet: run `agenthub update` once. + +A CLI installed with npm can't replace itself, so it keeps the notice; update it with `npm install -g @theagenthub/cli@latest`. ## The plugins diff --git a/docs/wiki/harnesses/Claude-Code.md b/docs/wiki/harnesses/Claude-Code.md index 229c877..63169c9 100644 --- a/docs/wiki/harnesses/Claude-Code.md +++ b/docs/wiki/harnesses/Claude-Code.md @@ -21,7 +21,7 @@ Set these in `/plugin`, under Agent Hub: | Option | Default | What it does | | --- | --- | --- | -| `auto_update` | off | Runs `agenthub update` in the background at session start. | +| `auto_update` | on | Lets the CLI update itself in the background when a session starts and a newer release is out. Off stops it in Claude Code sessions; `agenthub settings auto-update off` stops it everywhere. See [Updates](../Updates.md#updating-automatically). | | `wake_when_idle` | on | Wakes an idle session when a request or reply arrives. | ## Install with the CLI diff --git a/plugins/agenthub/.claude-plugin/plugin.json b/plugins/agenthub/.claude-plugin/plugin.json index 5c46387..512aa79 100644 --- a/plugins/agenthub/.claude-plugin/plugin.json +++ b/plugins/agenthub/.claude-plugin/plugin.json @@ -27,8 +27,8 @@ "auto_update": { "type": "boolean", "title": "Keep the agenthub CLI up to date", - "description": "Run agenthub update in the background when a session starts and a newer release is out.", - "default": false + "description": "Let the agenthub CLI update itself in the background when a session starts and a newer release is out. Off stops it in Claude Code sessions; agenthub settings auto-update off stops it in every harness.", + "default": true }, "wake_when_idle": { "type": "boolean", diff --git a/plugins/agenthub/scripts/hook.sh b/plugins/agenthub/scripts/hook.sh index 85a71b8..763038e 100755 --- a/plugins/agenthub/scripts/hook.sh +++ b/plugins/agenthub/scripts/hook.sh @@ -17,8 +17,6 @@ case "$harness" in claude-code | codex) ;; *) harness=claude-code ;; esac mode="${2:-notify}" input="$(cat)" event="$(printf '%s' "$input" | sed -n 's/.*"hook_event_name"[[:space:]]*:[[:space:]]*"\([A-Za-z]*\)".*/\1/p' | head -n 1)" -# Claude Code sets CLAUDE_PLUGIN_DATA; Codex sets PLUGIN_DATA (and the CLAUDE_ name too). -data="${CLAUDE_PLUGIN_DATA:-${PLUGIN_DATA:-${TMPDIR:-/tmp}/agenthub-plugin}}" hub="${AGENTHUB_URL:-https://hub.theagenthub.app}" agenthub="" @@ -37,16 +35,15 @@ if [ -z "$agenthub" ]; then exit 0 fi -if [ "$event" = SessionStart ]; then - case "${CLAUDE_PLUGIN_OPTION_AUTO_UPDATE:-false}" in - true | 1) - mkdir -p "$data" 2>/dev/null && ("$agenthub" update >"$data/update.log" 2>&1 = { short: "update this CLI", usage: ["agenthub update [--check] [--version ]"], summary: "Replace this CLI with the latest release, after checking it against SHA256SUMS and that it runs.", - details: ["A CLI installed with npm can't replace itself; update it the way you installed it."], + details: ["A CLI installed with npm can't replace itself; update it the way you installed it.", "It also runs in the background when a session starts and a newer release is out, unless agenthub settings auto-update is off."], examples: [ ["agenthub update", "install the latest release"], ["agenthub update --check", "only say whether there's a newer one"], @@ -94,14 +94,15 @@ export const COMMANDS: Record = { ], }, settings: { - short: "show or change waking, joining at session start, directives, and folder sessions", + short: "show or change waking, joining at session start, directives, auto-update, and folder sessions", usage: [ - "agenthub settings [wake|wake-act|autojoin|directives|folder-sessions]", + "agenthub settings [wake|wake-act|autojoin|directives|auto-update|folder-sessions]", "agenthub settings wake on|off|all [--project]", "agenthub settings wake-act ask|auto [--project]", "agenthub settings autojoin on|off [--project]", "agenthub settings directives on|off [--project]", "agenthub settings default --project", + "agenthub settings auto-update on|off", "agenthub settings folder-sessions on|off", ], summary: "Without arguments, prints a row for each setting: its name, what applies in the repo you're in, and where that comes from (an environment variable, this repo's setting, your setting for every repo, or the default). With just a name, prints that setting's row. With a name and a value, changes it for every repo, or with --project for this repo only.", @@ -110,9 +111,10 @@ export const COMMANDS: Record = { "wake-act: what a woken agent does. auto (the default): it handles the messages by itself, within the Agent Hub rules (answers and reviews read-only; handoffs, pushes and merges still wait for you). ask: it tells you what came in and waits for your go-ahead. The same applies when a Stop hook keeps a turn going for a message that came in during it.", "autojoin: when a session starts in a repo that's on the hub, its hooks join the project for it, as the session's own agent, and tell the agent its handle (on, the default). Projects in approval mode still wait for a project admin. off: the session-start notice asks the agent to call join_project itself.", "directives: whether your sessions take directives, your own instructions sent through your orchestrator (send_directive). On by default. A session gets one at its next prompt, tool call or turn end, or at once when it's idle and its harness can be woken, even with wake off. Off: the hooks leave them queued (they expire after a day). Workers started by agenthub launcher get theirs from the launcher instead.", + "auto-update: whether this CLI updates itself. On (the default): when a session starts (or a Roo Code task ends) and the once-a-day check finds a newer release, agenthub update runs in the background, in every harness whose hooks or plugin run agenthub notify, and there's no line. Off: a session-start line says when a newer release is out, and agenthub update installs it. The log is update.log in ~/.config/agenthub/cache. It's this machine's setting, so it takes no --project. A CLI installed with npm can't replace itself, so it keeps the line. AGENTHUB_NO_UPDATE_CHECK=1 turns the check off, and auto-update with it.", "folder-sessions: whether your orchestrator can start a session (start_session with a folder) in any folder on this machine, through agenthub launcher, not only in a worktree of one of your projects. Off by default. It's this machine's setting (launch.allow_folders), so it takes no --project; restart agenthub launcher after changing it. A folder session works in the folder directly, creating it if it's missing, but never in /, your home folder, or a folder with your machine's own settings (the launcher's config folder, ~/.ssh, ~/.claude, ~/.codex, $CLAUDE_CONFIG_DIR, $CODEX_HOME), even through a symlink or another path to it, and on macOS never under /System, /.vol, /.nofollow or /.resolve; without a project the launcher gives it no hub sign-in and no Agent Hub server.", "--project sets it for the repo you're in only; it wins over your setting for every repo. default --project removes the repo's own value. The settings are in config.json in ~/.config/agenthub (or $AGENTHUB_HOME).", - "AGENTHUB_WAKE, AGENTHUB_WAKE_ACT, AGENTHUB_AUTOJOIN and AGENTHUB_DIRECTIVES win over them for one shell.", + "AGENTHUB_WAKE, AGENTHUB_WAKE_ACT, AGENTHUB_AUTOJOIN, AGENTHUB_DIRECTIVES and AGENTHUB_AUTO_UPDATE win over them for one shell.", ], examples: [ ["agenthub settings", "what applies in this repo, and where it comes from"], @@ -123,6 +125,7 @@ export const COMMANDS: Record = { ["agenthub settings autojoin off", "never join for a session; the agent joins itself"], ["agenthub settings directives off --project", "leave your orchestrator's instructions queued in this repo"], ["agenthub settings wake default --project", "this repo follows your wake setting again"], + ["agenthub settings auto-update off", "don't update this CLI by itself; just say when there's a newer one"], ["agenthub settings folder-sessions on", "let your orchestrator start sessions in any folder on this machine"], ], }, @@ -286,6 +289,7 @@ const ENVIRONMENT = `Environment: AGENTHUB_WAKE_ACT=ask|auto whether a woken agent asks you first; overrides agenthub settings wake-act AGENTHUB_DIRECTIVES=0 sessions here leave your orchestrator's instructions queued; overrides agenthub settings directives AGENTHUB_AUTOJOIN=0 sessions here don't join the project at start; overrides agenthub settings autojoin + AGENTHUB_AUTO_UPDATE=0 this CLI doesn't update itself; overrides agenthub settings auto-update AGENTHUB_KEEPALIVE=0 no background keepalive: agents go idle and then offline when quiet AGENTHUB_CREDENTIAL_STORE=file|keychain|auto AGENTHUB_HOME config directory (default ~/.config/agenthub) diff --git a/src/cli/index.ts b/src/cli/index.ts index a6c24d4..c8e8dda 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -105,7 +105,10 @@ async function main(argv: string[]): Promise { } } const { startKeepalive } = await import("./keepalive.js"); - const out = await notifyHook({ format, event, payload }, { store: credentialStore(), version: version(), startKeepalive: (t) => startKeepalive(t) }); + const { startBackgroundUpdate } = await import("./update.js"); + // Only the single-file build can replace itself. + const startUpdate = typeof AGENTHUB_SEA === "boolean" && AGENTHUB_SEA ? () => startBackgroundUpdate() : undefined; + const out = await notifyHook({ format, event, payload }, { store: credentialStore(), version: version(), startKeepalive: (t) => startKeepalive(t), startUpdate }); if (out.stdout) process.stdout.write(out.stdout + "\n"); if (out.stderr) process.stderr.write(out.stderr + "\n"); // Only Kimi Code's Stop hook exits 2, to keep the turn going. diff --git a/src/cli/notify.ts b/src/cli/notify.ts index 689ce58..eafdbc2 100644 --- a/src/cli/notify.ts +++ b/src/cli/notify.ts @@ -9,8 +9,8 @@ import { rememberCheckout, repoRoot } from "./checkouts.js"; import type { CredentialStore } from "./credentials.js"; import { cacheDir } from "./paths.js"; import { accessToken, type Fetch } from "./session.js"; -import { autojoinSetting, hubUrl } from "./settings.js"; -import { updateNotice } from "./update.js"; +import { autojoinSetting, autoUpdateSetting, hubUrl } from "./settings.js"; +import { autoUpdate, updateNotice, type CheckDeps } from "./update.js"; import { kimiWakeable, startKimiWaiter } from "./kimi.js"; import { parentChain, stopKeepalive, type KeepaliveTarget } from "./keepalive.js"; import { actMode, addPending, continueNotice, directivesOn, formatDirectives, mergeInbox, noteDelivered, releaseWaiter, takeDelivered, takePending, wakeMode } from "./wait.js"; @@ -62,6 +62,11 @@ export interface NotifyDeps { cwd?: string; /** This CLI's version. With it, the session-start notice says when a newer one is out. */ version?: string | undefined; + /** + * Starts `agenthub update` in the background, for `agenthub settings auto-update on`. The single-file CLI passes + * it; a CLI installed with npm can't replace itself, so it gets the notice instead. + */ + startUpdate?: (() => void) | undefined; /** Overridable for tests; defaults to running git. */ remotes?: (cwd: string) => { origin?: string | undefined; upstream?: string | undefined }; /** The repo root a session runs in, for the launcher's list of checkouts. Overridable for tests. */ @@ -111,10 +116,7 @@ export async function notify(opts: NotifyOptions, deps: NotifyDeps): Promise { try { const event = opts.event ?? HOOK_EVENTS[String(opts.payload?.hook_event_name ?? "")] ?? "post-tool"; - const update = - event === "session-start" && deps.version - ? updateNotice(deps.version, { env: deps.env ?? process.env, fetch: deps.fetch ?? fetch, ...(deps.now ? { now: deps.now } : {}) }) - : Promise.resolve(""); + const update = deps.version ? versionLine(event, deps.version, deps) : Promise.resolve(""); const [text, notice] = await Promise.all([run(opts, event, deps).catch(() => ""), update.catch(() => "")]); if (typeof text === "object") return text; return { stdout: render(opts.format, event, [text, notice].filter(Boolean).join("\n")) }; @@ -123,6 +125,17 @@ export async function notifyHook(opts: NotifyOptions, deps: NotifyDeps): Promise } } +/** + * The session-start line about a newer CLI, or "". With auto-update on, a newer release is installed in the + * background instead, at session start and at a turn's end (Roo Code's only hook), and there's no line. + */ +async function versionLine(event: NotifyEvent, version: string, deps: NotifyDeps): Promise { + if (event !== "session-start" && event !== "stop") return ""; + const check: CheckDeps = { env: deps.env ?? process.env, fetch: deps.fetch ?? fetch, ...(deps.now ? { now: deps.now } : {}) }; + if (deps.startUpdate && autoUpdateSetting(check.env!).on && (await autoUpdate(version, deps.startUpdate, check))) return ""; + return event === "session-start" ? updateNotice(version, check) : ""; +} + /** * How each harness's Stop hook keeps the turn going, for a request that came in during it. * Claude Code has `agenthub wait` instead; plain text has no Stop hook. diff --git a/src/cli/settings-command.ts b/src/cli/settings-command.ts index 674868d..cf9a685 100644 --- a/src/cli/settings-command.ts +++ b/src/cli/settings-command.ts @@ -1,12 +1,12 @@ /** * `agenthub settings`: shows and sets the machine's Agent Hub settings in config.json (waking, what a woken agent * does, joining at session start, and directives), for every repo or with --project for the repo you're in; and - * whether this machine's launcher allows folder sessions, which has no --project. + * whether this machine's CLI updates itself and its launcher allows folder sessions, which have no --project. * `agenthub wake`, `agenthub autojoin` and `agenthub directives` forward here for one more release. */ import { commandHelp } from "./help.js"; import { actSetting, wakeSetting } from "./wait.js"; -import { autojoinSetting, directivesSetting, projectKey, readSettings, writeSettings, type CliSettings, type WakeSetting } from "./settings.js"; +import { autoUpdateSetting, autojoinSetting, directivesSetting, projectKey, readSettings, writeSettings, type CliSettings, type WakeSetting } from "./settings.js"; export interface SettingsIO { env: NodeJS.ProcessEnv; @@ -94,6 +94,21 @@ const SETTINGS: Record = { ? `Your sessions will take your own instructions from your orchestrator ${where}.` : `Your sessions will leave directives queued ${where}; they expire after a day.`, }, + "auto-update": { + values: ["on", "off"], + envName: "AGENTHUB_AUTO_UPDATE", + current: (env) => { + const s = autoUpdateSetting(env); + return { value: s.on ? "on" : "off", from: s.from }; + }, + set: (s, v) => ({ ...s, auto_update: v as "on" | "off" }), + describe: (v) => + v === "on" ? "on: this CLI updates itself in the background when a newer release is out" : "off: a session-start line says when a newer release is out; agenthub update installs it", + done: (v) => + v === "on" + ? "This CLI will update itself in the background when a session starts and a newer release is out, in every harness that runs agenthub notify (the default). The log is update.log in ~/.config/agenthub/cache. A CLI installed with npm can't replace itself: update it with npm install -g @theagenthub/cli@latest." + : "This CLI won't update itself. A session-start line says when a newer release is out; agenthub update installs it.", + }, "folder-sessions": { values: ["on", "off"], current: (env) => { @@ -155,6 +170,7 @@ export function settingsCommand(argv: string[], io: SettingsIO): number { if (perProject) return usage(io); writeSettings(s.set(settings, value), io.env); io.out(s.done(value, "")); + if (s.envName && io.env[s.envName] !== undefined) io.out(`${s.envName}=${io.env[s.envName]} is set in this shell and wins over this setting.`); return 0; } if (perProject) { diff --git a/src/cli/settings.ts b/src/cli/settings.ts index 70eee2f..25e951b 100644 --- a/src/cli/settings.ts +++ b/src/cli/settings.ts @@ -21,6 +21,8 @@ export interface CliSettings { directives?: "on" | "off"; /** Per-project overrides of `directives`, by `projectKey(origin)` (`agenthub settings directives … --project`). */ directives_projects?: Record; + /** Whether this machine's CLI updates itself in the background when a newer release is out (`agenthub settings auto-update`). */ + auto_update?: "on" | "off"; /** * This machine's limits for `agenthub launcher` workers. `allow_folders`: workers may run in any folder the * orchestrator names, not only in a worktree (`agenthub settings folder-sessions`). @@ -77,6 +79,17 @@ export function directivesSetting(env: NodeJS.ProcessEnv, origin?: string): { on return { on: !["0", "false", "off", "no"].includes(raw.trim().toLowerCase()), from }; } +/** + * Whether this machine's CLI updates itself in the background, and where that comes from: AGENTHUB_AUTO_UPDATE + * (0/off/false/no turns it off, anything else on), else this machine's setting, else on. It's this machine's, never a repo's. + */ +export function autoUpdateSetting(env: NodeJS.ProcessEnv): { on: boolean; from: "env" | "machine" | "default" } { + const raw = env.AGENTHUB_AUTO_UPDATE?.trim().toLowerCase(); + if (raw) return { on: !["0", "off", "false", "no"].includes(raw), from: "env" }; + const s = readSettings(env).auto_update; + return s ? { on: s === "on", from: "machine" } : { on: true, from: "default" }; +} + /** A repo's remote as `host/owner/repo`, the same for its SSH and HTTPS URLs. */ export function projectKey(origin: string): string | undefined { try { diff --git a/src/cli/update.ts b/src/cli/update.ts index adfab42..51095f0 100644 --- a/src/cli/update.ts +++ b/src/cli/update.ts @@ -1,6 +1,6 @@ -import { execFileSync } from "node:child_process"; +import { execFileSync, spawn } from "node:child_process"; import { createHash } from "node:crypto"; -import { chmodSync, createWriteStream, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, closeSync, createWriteStream, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { basename, dirname, join } from "node:path"; import { Readable } from "node:stream"; import { pipeline } from "node:stream/promises"; @@ -119,6 +119,51 @@ export async function cachedLatest(deps: CheckDeps = {}, timeoutMs = 1500): Prom return latest; } +/** How long a background update that was started holds off another one for the same release. */ +const AUTO_UPDATE_RETRY_MS = 3600e3; + +/** + * With auto-update on: when a newer release is out (the once-a-day check), calls `start` to update in the + * background, at most once an hour for the same release, so sessions starting together don't all download it. + * Resolves to true when an update is under way, so the caller skips the "newer version" notice. Never throws. + */ +export async function autoUpdate(current: string, start: () => void, deps: CheckDeps = {}): Promise { + try { + const latest = await cachedLatest(deps); + if (!latest || compareVersions(latest, current) <= 0) return false; + const env = deps.env ?? process.env; + const now = (deps.now ?? Date.now)(); + const file = join(cacheDir(env), "auto-update.json"); + try { + const last = JSON.parse(readFileSync(file, "utf8")) as { at: number; version: string }; + if (last.version === latest && now - last.at < AUTO_UPDATE_RETRY_MS) return true; + } catch { + /* none started yet */ + } + mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); + writeFileSync(file, JSON.stringify({ at: now, version: latest })); + start(); + return true; + } catch { + return false; + } +} + +/** Runs `agenthub update` detached from the hook, logging to update.log in the cache folder. Never throws. */ +export function startBackgroundUpdate(env: NodeJS.ProcessEnv = process.env): void { + try { + const dir = cacheDir(env); + mkdirSync(dir, { recursive: true, mode: 0o700 }); + const log = openSync(join(dir, "update.log"), "w"); + const child = spawn(process.execPath, ["update"], { detached: true, stdio: ["ignore", log, log], windowsHide: true, env }); + child.on("error", () => {}); + child.unref(); + closeSync(log); + } catch { + /* stay quiet: the notice comes back next time */ + } +} + /** One line for a session-start notice when a newer CLI is out, else "". Never throws. */ export async function updateNotice(current: string, deps: CheckDeps = {}): Promise { const latest = await cachedLatest(deps); diff --git a/test/cli.test.ts b/test/cli.test.ts index 960e611..8b70fa4 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -1101,6 +1101,34 @@ describe("agenthub settings", () => { expect(outside.err.join("\n")).toContain("Not in a git repo with an origin remote"); }); + it("turns auto-update on and off for this machine, without --project", () => { + const t = io(); + expect(settingsCommand([], t.ctx)).toBe(0); + expect(t.out.join("\n")).toMatch(/^auto-update .*on: .*\(the default\)$/m); + t.out.length = 0; + expect(settingsCommand(["auto-update", "on"], t.ctx)).toBe(0); + expect(t.config().auto_update).toBe("on"); + expect(t.out.join("\n")).toContain("update itself in the background"); + t.out.length = 0; + expect(settingsCommand(["auto-update"], t.ctx)).toBe(0); + expect(t.out).toEqual([expect.stringMatching(/^auto-update .*on: .*\(this machine's setting\)$/)]); + expect(settingsCommand(["auto-update", "off"], t.ctx)).toBe(0); + expect(t.config().auto_update).toBe("off"); + + // AGENTHUB_AUTO_UPDATE wins, and setting it says so. + const env = io({ AGENTHUB_AUTO_UPDATE: "0" }); + expect(settingsCommand(["auto-update"], env.ctx)).toBe(0); + expect(env.out).toEqual([expect.stringMatching(/^auto-update .*off: .*\(from AGENTHUB_AUTO_UPDATE\)$/)]); + expect(settingsCommand(["auto-update", "on"], env.ctx)).toBe(0); + expect(env.out.at(-1)).toBe("AGENTHUB_AUTO_UPDATE=0 is set in this shell and wins over this setting."); + + for (const bad of [["auto-update", "on", "--project"], ["auto-update", "default", "--project"], ["auto-update", "all"]]) { + t.err.length = 0; + expect(settingsCommand(bad, t.ctx), bad.join(" ")).toBe(2); + } + expect(t.config().auto_update).toBe("off"); + }); + it("turns folder sessions on and off for this machine, without --project", () => { const t = io(); writeSettings({ launch: { allow_edit: true, max_workers: 2 } }, t.ctx.env); diff --git a/test/update.test.ts b/test/update.test.ts index f935dc4..2b386d0 100644 --- a/test/update.test.ts +++ b/test/update.test.ts @@ -6,6 +6,7 @@ import { describe, expect, it } from "vitest"; import { notify } from "../src/cli/notify.js"; import { assetName, cachedLatest, compareVersions, selfUpdate, updateNotice } from "../src/cli/update.js"; import type { CredentialStore } from "../src/cli/credentials.js"; +import { writeSettings } from "../src/cli/settings.js"; const MIRROR = { AGENTHUB_DOWNLOAD_URL: "https://mirror.example" }; const tmp = () => mkdtempSync(join(tmpdir(), "agenthub-update-")); @@ -70,6 +71,52 @@ describe("agenthub update", () => { expect(await notify({ format: "claude-code", event: "prompt" }, { store, env, fetch: fetchFn, version: "0.1.0", remotes: () => ({}) })).toBe(""); }); + it("auto-updates in the background instead of the notice by default, once an hour per release", async () => { + const home = tmp(); + const { fetchFn } = server({ "/latest": "v9.0.0" }); + const store = { get: () => undefined } as unknown as CredentialStore; + let now = 1_000_000; + let started = 0; + const deps = (env: NodeJS.ProcessEnv, startUpdate?: () => void) => ({ store, env, fetch: fetchFn, version: "0.1.0", remotes: () => ({}), now: () => now, startUpdate }); + const start = () => void started++; + const context = (out: string) => (out ? JSON.parse(out).hookSpecificOutput.additionalContext : ""); + + // Off through the setting: the notice, and no update. + writeSettings({ auto_update: "off" }, { AGENTHUB_HOME: home }); + expect(context(await notify({ format: "claude-code", event: "session-start" }, deps({ AGENTHUB_HOME: home }, start)))).toContain("agenthub v9.0.0 is available"); + expect(started).toBe(0); + + // On by default: an update starts and there's no notice. + writeSettings({}, { AGENTHUB_HOME: home }); + expect(context(await notify({ format: "claude-code", event: "session-start" }, deps({ AGENTHUB_HOME: home }, start)))).not.toContain("is available"); + expect(started).toBe(1); + // Another session within the hour doesn't start a second one, and says nothing either. + now += 10 * 60e3; + expect(context(await notify({ format: "claude-code", event: "session-start" }, deps({ AGENTHUB_HOME: home }, start)))).not.toContain("is available"); + expect(started).toBe(1); + // After an hour (the update failed, say) it tries again; a turn's end counts too, for Roo Code. + now += 60 * 60e3; + await notify({ format: "roo", event: "stop" }, deps({ AGENTHUB_HOME: home }, start)); + expect(started).toBe(2); + // Never on other events. + now += 2 * 3600e3; + await notify({ format: "claude-code", event: "prompt" }, deps({ AGENTHUB_HOME: home }, start)); + expect(started).toBe(2); + + // The environment wins over the setting. + expect(context(await notify({ format: "claude-code", event: "session-start" }, deps({ AGENTHUB_HOME: home, AGENTHUB_AUTO_UPDATE: "0" }, start)))).toContain("is available"); + expect(started).toBe(2); + writeSettings({ auto_update: "off" }, { AGENTHUB_HOME: home }); + expect(context(await notify({ format: "claude-code", event: "session-start" }, deps({ AGENTHUB_HOME: home, AGENTHUB_AUTO_UPDATE: "1" }, start)))).not.toContain("is available"); + expect(started).toBe(3); + // A CLI that can't replace itself (installed with npm) keeps the notice. + expect(context(await notify({ format: "claude-code", event: "session-start" }, deps({ AGENTHUB_HOME: home })))).toContain("is available"); + + // Up to date: nothing starts. + await notify({ format: "claude-code", event: "session-start" }, { ...deps({ AGENTHUB_HOME: tmp() }, start), version: "9.0.0" }); + expect(started).toBe(3); + }); + it("replaces the binary after checking its checksum and version", async () => { const dir = tmp(); const binary = join(dir, "agenthub");