feat(cli): make nanobot launch the terminal agent

This commit is contained in:
Xubin Ren
2026-08-29 11:26:50 +08:00
parent 559b2d2e5d
commit 7fc90ca6aa
8 changed files with 140 additions and 33 deletions
+4 -4
View File
@@ -146,7 +146,7 @@ Activate it with `source .venv/bin/activate` on macOS/Linux or
python -m pip install -e .
```
After that, the normal commands are identical to a stable install. `nanobot agent` runs the TUI
After that, the normal commands are identical to a stable install. `nanobot` runs the TUI
from this checkout, and `nanobot webui` rebuilds stale frontend assets automatically. A later
`git pull --ff-only` updates the Python, TUI, and WebUI source together; rerun
`python -m pip install -e .` when Python dependencies change. Contributors should also read
@@ -206,10 +206,10 @@ Use `nanobot gateway --background` for the same direct entry point without keepi
**Prefer to work entirely in the terminal?**
```bash
nanobot agent
nanobot
```
This opens the native terminal client with the launch directory as its workspace. It shares saved conversations and the local gateway with the WebUI.
This opens the native terminal client with the launch directory as its workspace. It shares saved conversations and the local gateway with the WebUI. The explicit `nanobot agent` form remains available for compatibility.
- Type `/` to discover commands, `/sessions` to switch conversations, or `@` to mention an app, MCP server, or saved session.
- Press `Enter` to send. While nanobot is working, `Enter` sends now and `Tab` sends after the current response. Press `Shift+Enter` to add a newline (`Ctrl+J` works in terminals that cannot distinguish modified Enter keys).
@@ -220,7 +220,7 @@ Each launch starts a new session by default. Use `--session` to resume one and `
For one request and an immediate exit, use:
```bash
nanobot agent -m "Hello!"
nanobot -m "Hello!"
```
The one-shot form is useful for a quick provider check, shell scripts, and local automation. If you have not configured a model yet, run `nanobot webui` and open **Settings → Models** first.
+11 -11
View File
@@ -12,8 +12,8 @@ Use this page when you know what you want to run and need the command shape. For
| Use guided setup | `nanobot onboard --wizard` | Best when you prefer prompts over hand-editing JSON |
| Open the browser workbench | `nanobot webui` | Prepares local WebUI settings, starts the gateway, and opens the browser |
| Check readiness without calling a model | `nanobot status` | Summarizes config/workspace and validates the active provider/model configuration |
| Send one test message | `nanobot agent -m "Hello!"` | First proof that install, config, provider, model, and workspace all work |
| Chat in the terminal | `nanobot agent` | Interactive local chat; exit with `exit`, `/exit`, `:q`, or `Ctrl+D` |
| Send one test message | `nanobot -m "Hello!"` | First proof that install, config, provider, model, and workspace all work |
| Chat in the terminal | `nanobot` | Interactive local chat; `nanobot agent` remains an explicit alias |
| Run the gateway directly | `nanobot gateway` | Service/ops command for WebUI, chat apps, cron, and heartbeat |
| Deliver a local trigger | `nanobot trigger <id> "message"` | Created first with `/trigger <name>` in the target chat/session |
| Serve an OpenAI-compatible API | `nanobot serve` | Starts `/v1/chat/completions`, `/v1/models`, and `/health` |
@@ -86,15 +86,15 @@ follow the printed WebUI **Settings → Models** or `nanobot onboard --wizard` r
| Command | Description |
|---|---|
| `nanobot agent -m "Hello!"` | Send one message and exit |
| `nanobot agent` | Start interactive terminal chat |
| `nanobot agent --session <id>` | Use a WebSocket session key; add `--classic` for another channel |
| `nanobot agent --workspace <path>` | Override workspace |
| `nanobot agent --config <path>` | Use a specific config file |
| `nanobot agent --classic` | Use the classic Python prompt instead of the native terminal UI |
| `nanobot agent --theme auto\|dark\|light` | Auto-detect the terminal appearance or force a TUI palette |
| `nanobot agent --no-markdown` | Use the classic prompt and print plain text instead of Markdown |
| `nanobot agent --logs` | Use the classic prompt and show runtime logs while chatting |
| `nanobot -m "Hello!"` | Send one message and exit |
| `nanobot` | Start interactive terminal chat |
| `nanobot --session <id>` | Use a WebSocket session key; add `--classic` for another channel |
| `nanobot --workspace <path>` | Override workspace |
| `nanobot --config <path>` | Use a specific config file |
| `nanobot --classic` | Use the classic Python prompt instead of the native terminal UI |
| `nanobot --theme auto\|dark\|light` | Auto-detect the terminal appearance or force a TUI palette |
| `nanobot --no-markdown` | Use the classic prompt and print plain text instead of Markdown |
| `nanobot --logs` | Use the classic prompt and show runtime logs while chatting |
Inside the native TUI, `/sessions` switches saved conversations, `/new-chat` starts another saved
conversation, and `/context` explains the compacted summary and raw session suffix available to
+3 -3
View File
@@ -103,13 +103,13 @@ Use `nanobot gateway logs`, `restart`, and `stop` to manage that background gate
If you do not want the browser or need to isolate a WebUI problem, send one message directly:
```bash
nanobot agent -m "Hello!"
nanobot -m "Hello!"
```
Then start an interactive terminal chat with:
```bash
nanobot agent
nanobot
```
In interactive mode, `Enter` sends and `Shift+Enter` inserts a newline (`Ctrl+J` is the
@@ -173,7 +173,7 @@ nanobot webui
```
The source path follows current `main` and can be newer than the published package. The editable
install keeps Python pointed at the checkout; `nanobot agent` runs `tui/` with Bun, and
install keeps Python pointed at the checkout; `nanobot` runs `tui/` with Bun, and
`nanobot webui` automatically rebuilds `webui/` when its bundled assets are stale. All normal
commands remain the same as a stable install. For development details, follow
[`../CONTRIBUTING.md`](../CONTRIBUTING.md).
+12 -3
View File
@@ -87,7 +87,12 @@ app = typer.Typer(
name="nanobot",
context_settings={"help_option_names": ["-h", "--help"]},
help=f"{__logo__} nanobot - Personal AI Assistant",
no_args_is_help=True,
epilog=(
"Run `nanobot` without a subcommand to start the terminal agent. "
"Use `nanobot agent --help` for agent options."
),
invoke_without_command=True,
no_args_is_help=False,
)
console = Console()
@@ -98,7 +103,7 @@ def version_callback(value: bool):
raise typer.Exit()
@app.callback()
@app.callback(invoke_without_command=True)
def main(
ctx: typer.Context,
version: bool = typer.Option(
@@ -110,7 +115,11 @@ def main(
# imports this Typer app directly instead of ``nanobot.cli.entry``. Keep the
# role identity correct until that launcher is regenerated.
command = ctx.invoked_subcommand
set_cli_process_identity([command] if command else sys.argv[1:])
set_cli_process_identity([command] if command else ["agent"])
if command is None:
from nanobot.cli.entry import _run_agent
_run_agent([], prog_name="nanobot")
# ============================================================================
+44 -10
View File
@@ -8,6 +8,28 @@ from contextlib import suppress
from nanobot.cli.process_identity import set_cli_process_identity
_ROOT_OPTIONS = frozenset(
{
"-h",
"--help",
"-v",
"--version",
"--install-completion",
"--show-completion",
}
)
def _agent_invocation_args(args: list[str]) -> list[str] | None:
"""Return agent arguments when the root command should act as ``agent``."""
if not args:
return []
if args[0] == "agent":
return args[1:]
if args[0].startswith("-") and args[0].split("=", 1)[0] not in _ROOT_OPTIONS:
return args
return None
def _native_tui_candidate(args: list[str]) -> bool:
"""Return whether ``agent`` can start without the classic agent stack."""
@@ -34,19 +56,31 @@ def _configure_windows_console() -> None:
reconfigure(encoding="utf-8", errors="replace")
def _run_agent(args: list[str], *, prog_name: str) -> None:
"""Run the shared agent command without importing the complete CLI graph."""
import typer
from nanobot.cli.agent import agent
agent_app = typer.Typer(add_completion=False)
agent_app.command()(agent)
command = typer.main.get_command(agent_app)
command.main(args=args, prog_name=prog_name)
def main() -> None:
"""Dispatch native TUI startup without importing the complete CLI graph."""
set_cli_process_identity(sys.argv[1:])
raw_args = sys.argv[1:]
agent_args = _agent_invocation_args(raw_args)
dispatch_args = ["agent", *agent_args] if agent_args is not None else raw_args
set_cli_process_identity(dispatch_args)
_configure_windows_console()
if _native_tui_candidate(sys.argv[1:]):
import typer
from nanobot.cli.agent import agent
fast_app = typer.Typer(add_completion=False)
fast_app.command()(agent)
command = typer.main.get_command(fast_app)
command.main(args=sys.argv[2:], prog_name="nanobot agent")
root_agent_alias = agent_args is not None and raw_args[:1] != ["agent"]
if agent_args is not None and (
root_agent_alias or _native_tui_candidate(dispatch_args)
):
prog_name = "nanobot" if root_agent_alias else "nanobot agent"
_run_agent(agent_args, prog_name=prog_name)
return
from nanobot.cli.commands import app
+47 -1
View File
@@ -1,4 +1,50 @@
from nanobot.cli.entry import _native_tui_candidate
from nanobot.cli import entry
from nanobot.cli.entry import _agent_invocation_args, _native_tui_candidate
def test_root_command_routes_to_agent_without_copying_agent_options() -> None:
assert _agent_invocation_args([]) == []
assert _agent_invocation_args(["agent", "--theme", "dark"]) == ["--theme", "dark"]
assert _agent_invocation_args(["--workspace", "./project"]) == [
"--workspace",
"./project",
]
assert _agent_invocation_args(["-mhello"]) == ["-mhello"]
def test_root_metadata_and_subcommands_keep_the_root_cli() -> None:
for args in (
["--help"],
["--version"],
["--install-completion"],
["gateway"],
["webui"],
):
assert _agent_invocation_args(args) is None
def test_root_alias_dispatches_the_shared_agent_command(monkeypatch) -> None:
calls: dict[str, object] = {}
monkeypatch.setattr(entry.sys, "argv", ["nanobot", "-m", "hello"])
monkeypatch.setattr(
entry,
"set_cli_process_identity",
lambda args: calls.__setitem__("identity", args),
)
monkeypatch.setattr(entry, "_configure_windows_console", lambda: None)
monkeypatch.setattr(
entry,
"_run_agent",
lambda args, *, prog_name: calls.update(args=args, prog_name=prog_name),
)
entry.main()
assert calls == {
"identity": ["agent", "-m", "hello"],
"args": ["-m", "hello"],
"prog_name": "nanobot",
}
def test_native_agent_invocations_use_the_lightweight_entrypoint() -> None:
+18
View File
@@ -58,6 +58,24 @@ def test_legacy_console_entrypoint_still_sets_subcommand_identity(
assert commands == [["webui"]]
def test_legacy_console_entrypoint_routes_bare_command_to_agent(
monkeypatch: pytest.MonkeyPatch,
) -> None:
identities: list[list[str]] = []
launches: list[tuple[list[str], str]] = []
monkeypatch.setattr("nanobot.cli.commands.set_cli_process_identity", identities.append)
monkeypatch.setattr(
"nanobot.cli.entry._run_agent",
lambda args, *, prog_name: launches.append((args, prog_name)),
)
result = CliRunner().invoke(app, [])
assert result.exit_code == 0
assert identities == [["agent"]]
assert launches == [([], "nanobot")]
def test_named_executable_creates_stable_role_symlink(
tmp_path: Path,
) -> None:
+1 -1
View File
@@ -9,7 +9,7 @@ bun run --cwd tui test
bun run --cwd tui build
```
`nanobot agent` launches this client, leases the shared local gateway or starts it on demand, and passes the local bootstrap endpoint through environment variables. The client paints before gateway readiness, retries bootstrap in the background, and obtains fresh WebSocket and REST credentials for each connection. Other terminals and the WebUI keep that gateway alive; the final interactive launcher to exit releases the on-demand process. `/detach` closes the TUI after promoting the gateway to persistent background mode, keeping any active agent turn running without clients; the restored terminal prints the exact stop command for that config and explicit workspace. `nanobot gateway --background` can start or promote it persistently before opening a client. Source checkouts automatically align dependencies with `bun.lock` before launch; released installs use a version-matched, checksum-verified archive that keeps the executable together with its licenses, notices, corresponding application source, source offer, and relinking instructions. Startup fails explicitly if the native client is unavailable. The legacy Python prompt is only selected with `nanobot agent --classic`.
`nanobot` (or the explicit `nanobot agent` form) launches this client, leases the shared local gateway or starts it on demand, and passes the local bootstrap endpoint through environment variables. The client paints before gateway readiness, retries bootstrap in the background, and obtains fresh WebSocket and REST credentials for each connection. Other terminals and the WebUI keep that gateway alive; the final interactive launcher to exit releases the on-demand process. `/detach` closes the TUI after promoting the gateway to persistent background mode, keeping any active agent turn running without clients; the restored terminal prints the exact stop command for that config and explicit workspace. `nanobot gateway --background` can start or promote it persistently before opening a client. Source checkouts automatically align dependencies with `bun.lock` before launch; released installs use a version-matched, checksum-verified archive that keeps the executable together with its licenses, notices, corresponding application source, source offer, and relinking instructions. Startup fails explicitly if the native client is unavailable. The legacy Python prompt is selected with `nanobot --classic` or `nanobot agent --classic`.
The TUI uses OpenTUI's retained full-screen layout: the transcript reflows with the terminal while the composer stays fixed at the bottom. Mouse and keyboard scrolling operate inside the transcript, and leaving the TUI restores the previous terminal screen.