feat(cli): add --home instance directory selector (#6128)
* feat(cli): add --home instance directory selector * refactor(cli): keep instance home selection command-line only * fix(cli): clarify WebUI channel confirmation * docs: condense multiple-instance setup guide * docs(cli): shorten instance home option help * docs: remove manual paragraph wrapping
This commit is contained in:
1 parent
98f89c6a43
commit
36c36a1324
14 files changed
+221
-143
No files matched your search
@@ -27,12 +27,15 @@ Use this page when you know what you want to run and need the command shape. For
|
|||||||
```bash
|
```bash
|
||||||
nanobot --help
|
nanobot --help
|
||||||
nanobot --version
|
nanobot --version
|
||||||
|
nanobot --home ~/.nanobot-work onboard
|
||||||
python -m nanobot --help
|
python -m nanobot --help
|
||||||
python -m nanobot --version
|
python -m nanobot --version
|
||||||
```
|
```
|
||||||
|
|
||||||
`python -m nanobot ...` is useful when the package is installed but the `nanobot` script is not on `PATH`.
|
`python -m nanobot ...` is useful when the package is installed but the `nanobot` script is not on `PATH`.
|
||||||
|
|
||||||
|
`--home <directory>` is a global option; place it before the subcommand. It selects `<directory>/config.json` and the default `<directory>/workspace/`. Explicit `--config` and workspace settings still apply. See [Multiple Instances](./multiple-instances.md) for runtime data locations and port selection. `-h` and `--help` display help.
|
||||||
|
|
||||||
### Coexisting with Nanobot Desktop
|
### Coexisting with Nanobot Desktop
|
||||||
|
|
||||||
The Python package and Nanobot Desktop keep separate runtimes, configuration,
|
The Python package and Nanobot Desktop keep separate runtimes, configuration,
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ If the WebUI does not expose the option you need, start from the task below. Mos
|
|||||||
| Add external tools through MCP | `tools.mcpServers.<name>` | Start `nanobot gateway --verbose` and check startup/tool logs | [MCP](#mcp-model-context-protocol) |
|
| Add external tools through MCP | `tools.mcpServers.<name>` | Start `nanobot gateway --verbose` and check startup/tool logs | [MCP](#mcp-model-context-protocol) |
|
||||||
| Tighten tool and network safety | `tools.restrictToWorkspace`, `tools.exec.sandbox`, `tools.ssrfWhitelist`, `channels.*.allowFrom` | Run the same workflow through the channel or CLI you plan to expose | [Security](#security), [Pairing](#pairing) |
|
| Tighten tool and network safety | `tools.restrictToWorkspace`, `tools.exec.sandbox`, `tools.ssrfWhitelist`, `channels.*.allowFrom` | Run the same workflow through the channel or CLI you plan to expose | [Security](#security), [Pairing](#pairing) |
|
||||||
| Tune request timeouts or process concurrency | `NANOBOT_STREAM_IDLE_TIMEOUT_S`, `NANOBOT_MAX_CONCURRENT_REQUESTS` | Start nanobot from the same environment and inspect startup/runtime logs | [Runtime Environment Variables](#runtime-environment-variables) |
|
| Tune request timeouts or process concurrency | `NANOBOT_STREAM_IDLE_TIMEOUT_S`, `NANOBOT_MAX_CONCURRENT_REQUESTS` | Start nanobot from the same environment and inspect startup/runtime logs | [Runtime Environment Variables](#runtime-environment-variables) |
|
||||||
| Run multiple isolated bots | separate `--config` and `--workspace` paths, plus distinct `gateway.port` or channel ports when processes run together | Use the same explicit paths with `nanobot status`, `agent`, `webui`, `gateway`, and `serve` | [Multiple Instances](./multiple-instances.md), [CLI Reference](./cli-reference.md) |
|
| Run multiple isolated bots | separate `--home` directories, or `--config` and `--workspace` paths, plus distinct `gateway.port` or channel ports when processes run together | Place `--home` before the subcommand; use the same instance selectors with `status`, `agent`, `webui`, `gateway`, and `serve` | [Multiple Instances](./multiple-instances.md), [CLI Reference](./cli-reference.md) |
|
||||||
| Observe model calls | `LANGFUSE_SECRET_KEY`, `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_BASE_URL` environment variables | Run one model call, then check the matching Langfuse project | [Langfuse Observability](#langfuse-observability) |
|
| Observe model calls | `LANGFUSE_SECRET_KEY`, `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_BASE_URL` environment variables | Run one model call, then check the matching Langfuse project | [Langfuse Observability](#langfuse-observability) |
|
||||||
|
|
||||||
## Environment Variables for Secrets
|
## Environment Variables for Secrets
|
||||||
|
|||||||
+28
-121
@@ -1,145 +1,52 @@
|
|||||||
# Multiple Instances
|
# Multiple Instances
|
||||||
|
|
||||||
Run multiple nanobot instances simultaneously with separate configs and runtime data. Use `--config` as the main entrypoint. Optionally pass `--workspace` during `onboard` when you want to initialize or update the saved workspace for a specific instance.
|
Use a separate home directory for each instance. Place `--home` before the subcommand; without it, nanobot uses `~/.nanobot`.
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
If you want each instance to have its own dedicated workspace from the start, pass both `--config` and `--workspace` during onboarding.
|
|
||||||
|
|
||||||
**Initialize instances:**
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Create separate instance configs and workspaces
|
nanobot --home ~/.nanobot-work onboard
|
||||||
nanobot onboard --config ~/.nanobot-telegram/config.json --workspace ~/.nanobot-telegram/workspace
|
nanobot --home ~/.nanobot-work webui --port 8766 --gateway-port 18791
|
||||||
nanobot onboard --config ~/.nanobot-discord/config.json --workspace ~/.nanobot-discord/workspace
|
|
||||||
nanobot onboard --config ~/.nanobot-feishu/config.json --workspace ~/.nanobot-feishu/workspace
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**Configure each instance:**
|
Configure this instance's models and channels in WebUI Settings or `~/.nanobot-work/config.json`. Onboarding saves its default workspace as `~/.nanobot-work/workspace`.
|
||||||
|
|
||||||
Edit `~/.nanobot-telegram/config.json`, `~/.nanobot-discord/config.json`, etc. with different channel settings. The workspace you passed during `onboard` is saved into each config as that instance's default workspace.
|
Use the same home for other commands:
|
||||||
|
|
||||||
**Run instances:**
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Check one instance before starting it
|
nanobot --home ~/.nanobot-work status
|
||||||
nanobot status --config ~/.nanobot-telegram/config.json
|
nanobot --home ~/.nanobot-work agent
|
||||||
|
nanobot --home ~/.nanobot-work gateway --port 18791
|
||||||
# Instance A - Telegram bot
|
|
||||||
nanobot gateway --config ~/.nanobot-telegram/config.json
|
|
||||||
|
|
||||||
# Instance B - Discord bot
|
|
||||||
nanobot gateway --config ~/.nanobot-discord/config.json
|
|
||||||
|
|
||||||
# Instance C - Feishu bot with custom port
|
|
||||||
nanobot gateway --config ~/.nanobot-feishu/config.json --port 18792
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Concurrent instances need distinct gateway health ports and WebUI/channel ports. `webui --port` sets the WebUI/WebSocket port; `--gateway-port` sets the health port. For `gateway`, `--port` sets the health port. You can also save these ports in each config. Chat channels should use separate bot credentials.
|
||||||
|
|
||||||
## Path Resolution
|
## Path Resolution
|
||||||
|
|
||||||
When using `--config`, nanobot derives its runtime data directory from the config file location. The workspace still comes from `agents.defaults.workspace` unless you override it with `--workspace`.
|
| Data | Location |
|
||||||
|
|------|----------|
|
||||||
|
| Config | `<home>/config.json`, or explicit `--config` |
|
||||||
|
| Workspace | `<home>/workspace` by default; saved `agents.defaults.workspace` takes precedence; `--workspace` overrides both |
|
||||||
|
| Sessions | `<config-directory>/sessions/<workspace-id>/` |
|
||||||
|
| Media, logs, runtime state | Under the config directory |
|
||||||
|
| Memory, skills, cron jobs | Under the workspace |
|
||||||
|
| CLI input history | `<home>/history/cli_history` |
|
||||||
|
|
||||||
To open a CLI session against one of these instances locally:
|
An explicit `--config` also selects the runtime data directory. Keep each config in its own directory and use separate workspaces to isolate memory, skills, and sessions. Selecting a home does not relocate paths saved in an existing config.
|
||||||
|
|
||||||
|
For custom config/workspace locations:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
nanobot agent -c ~/.nanobot-telegram/config.json -m "Hello from Telegram instance"
|
nanobot onboard --config ~/bots/work/config.json --workspace ~/work-agent
|
||||||
nanobot agent -c ~/.nanobot-discord/config.json -m "Hello from Discord instance"
|
nanobot webui --config ~/bots/work/config.json --port 8766 --gateway-port 18791
|
||||||
|
|
||||||
# Open the browser workbench for a specific instance
|
|
||||||
nanobot webui -c ~/.nanobot-telegram/config.json
|
|
||||||
|
|
||||||
# Optional one-off workspace override
|
|
||||||
nanobot agent -c ~/.nanobot-telegram/config.json -w /tmp/nanobot-telegram-test
|
|
||||||
```
|
```
|
||||||
|
|
||||||
> Interactive `nanobot agent` and `nanobot webui` commands with the same `--config` and explicit `--workspace` selectors share one gateway instance. Different selectors produce isolated runtime state and processes. The one-shot and `--classic` agent paths remain direct local executions.
|
You can also copy an existing config into the new directory and change `agents.defaults.workspace`. Model presets can be reused; select a different `agents.defaults.modelPreset` when needed.
|
||||||
|
|
||||||
| Component | Resolved From | Example |
|
Interactive `agent` and `webui` commands with the same config and explicit workspace selectors share a gateway. Different selectors produce separate runtime state and processes; one-shot and `--classic` agent runs execute directly. Background gateways receive `--home` through their command-line arguments.
|
||||||
|-----------|---------------|---------|
|
|
||||||
| **Config** | `--config` path | `~/.nanobot-A/config.json` |
|
|
||||||
| **Workspace** | `--workspace` or config | `~/.nanobot-A/workspace/` |
|
|
||||||
| **Sessions** | config directory + workspace ID | `~/.nanobot-A/sessions/<workspace-id>/` |
|
|
||||||
| **Cron Jobs** | workspace directory | `~/.nanobot-A/workspace/cron/` |
|
|
||||||
| **Media / runtime state** | config directory | `~/.nanobot-A/media/` |
|
|
||||||
|
|
||||||
## How It Works
|
## Health Check
|
||||||
|
|
||||||
- `--config` selects which config file to load
|
Each gateway serves `GET /health` on `gateway.host:gateway.port`, bound to `127.0.0.1` by default. It returns `200` when the WebSocket channel is disabled or running, and `503` when enabled but not running. The JSON fields are `status`, `process`, `ready`, and `websocket`; other paths return `404`.
|
||||||
- By default, the workspace comes from `agents.defaults.workspace` in that config
|
|
||||||
- If you pass `--workspace`, it overrides the workspace from the config file
|
|
||||||
|
|
||||||
## Minimal Setup
|
This checks process liveness and WebSocket readiness, not other chat channels, MCP servers, or model connectivity. See [CLI Reference](./cli-reference.md#gateway) for gateway management commands.
|
||||||
|
|
||||||
1. Copy your base config into a new instance directory.
|
|
||||||
2. Set a different `agents.defaults.workspace` for that instance.
|
|
||||||
3. Start the instance with `--config`.
|
|
||||||
|
|
||||||
Example config fragment:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"agents": {
|
|
||||||
"defaults": {
|
|
||||||
"workspace": "~/.nanobot-telegram/workspace"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"channels": {
|
|
||||||
"telegram": {
|
|
||||||
"enabled": true,
|
|
||||||
"token": "YOUR_TELEGRAM_BOT_TOKEN"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"gateway": {
|
|
||||||
"host": "127.0.0.1",
|
|
||||||
"port": 18790
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
The copied base config can keep using the same `modelPresets` and `agents.defaults.modelPreset`. If this instance needs a different model, add another preset and set `agents.defaults.modelPreset` to that preset name.
|
|
||||||
|
|
||||||
Start separate instances:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
nanobot status --config ~/.nanobot-telegram/config.json
|
|
||||||
nanobot gateway --config ~/.nanobot-telegram/config.json
|
|
||||||
nanobot gateway --config ~/.nanobot-discord/config.json
|
|
||||||
```
|
|
||||||
|
|
||||||
Each gateway instance also exposes a lightweight HTTP health endpoint on `gateway.host:gateway.port`. By default, the gateway binds to `127.0.0.1`, so the endpoint stays local unless you explicitly set `gateway.host` to a public or LAN-facing address.
|
|
||||||
|
|
||||||
`GET /health` reports process liveness and WebSocket channel readiness:
|
|
||||||
|
|
||||||
- Returns `200 OK` when the WebSocket channel is disabled or running.
|
|
||||||
- Returns `503 Service Unavailable` when the WebSocket channel is enabled but not running.
|
|
||||||
|
|
||||||
The JSON response includes `status`, `process`, `ready`, and `websocket`.
|
|
||||||
For example, with the WebSocket channel disabled:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{"status":"ok","process":"alive","ready":true,"websocket":"disabled"}
|
|
||||||
```
|
|
||||||
|
|
||||||
Readiness currently reflects only the WebSocket channel. A successful response does not verify other chat channels, MCP servers, or model provider connectivity.
|
|
||||||
|
|
||||||
Other paths return `404`.
|
|
||||||
|
|
||||||
Override workspace for one-off runs when needed:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
nanobot gateway --config ~/.nanobot-telegram/config.json --workspace /tmp/nanobot-telegram-test
|
|
||||||
```
|
|
||||||
|
|
||||||
## Common Use Cases
|
|
||||||
|
|
||||||
- Run separate bots for Telegram, Discord, Feishu, and other platforms
|
|
||||||
- Keep testing and production instances isolated
|
|
||||||
- Use different models or providers for different teams
|
|
||||||
- Serve multiple tenants with separate configs and runtime data
|
|
||||||
|
|
||||||
## Notes
|
|
||||||
|
|
||||||
- Each instance must use a different port if they run at the same time
|
|
||||||
- Session data follows the active config directory; use a different workspace per instance to isolate memory, skills, and the stable session namespace ID
|
|
||||||
- `--workspace` overrides the workspace defined in the config file
|
|
||||||
- Cron jobs are stored in the active workspace; runtime media/state is derived from the config directory
|
|
||||||
@@ -111,11 +111,21 @@ def version_callback(value: bool):
|
|||||||
@app.callback(invoke_without_command=True)
|
@app.callback(invoke_without_command=True)
|
||||||
def main(
|
def main(
|
||||||
ctx: typer.Context,
|
ctx: typer.Context,
|
||||||
|
home: Path | None = typer.Option(
|
||||||
|
None, "--home", help="Instance root directory",
|
||||||
|
file_okay=False,
|
||||||
|
),
|
||||||
version: bool = typer.Option(
|
version: bool = typer.Option(
|
||||||
None, "--version", "-v", callback=version_callback, is_eager=True
|
None, "--version", "-v", callback=version_callback, is_eager=True
|
||||||
),
|
),
|
||||||
):
|
):
|
||||||
"""nanobot - Personal AI Assistant."""
|
"""nanobot - Personal AI Assistant."""
|
||||||
|
if home is not None:
|
||||||
|
from nanobot.config.home import get_selected_home_path, set_home_path
|
||||||
|
|
||||||
|
previous_home = get_selected_home_path()
|
||||||
|
set_home_path(home)
|
||||||
|
ctx.call_on_close(lambda: set_home_path(previous_home))
|
||||||
# Editable/source installs can retain an older generated console script that
|
# Editable/source installs can retain an older generated console script that
|
||||||
# imports this Typer app directly instead of ``nanobot.cli.entry``. Keep the
|
# imports this Typer app directly instead of ``nanobot.cli.entry``. Keep the
|
||||||
# role identity correct until that launcher is regenerated.
|
# role identity correct until that launcher is regenerated.
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ _ROOT_OPTIONS = frozenset(
|
|||||||
"--version",
|
"--version",
|
||||||
"--install-completion",
|
"--install-completion",
|
||||||
"--show-completion",
|
"--show-completion",
|
||||||
|
"--home",
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ from typing import NoReturn
|
|||||||
|
|
||||||
import typer
|
import typer
|
||||||
|
|
||||||
|
from nanobot.config.home import get_home_path
|
||||||
|
|
||||||
app = typer.Typer(help="Pair this server with a local nanobot. No public WebUI or relay.")
|
app = typer.Typer(help="Pair this server with a local nanobot. No public WebUI or relay.")
|
||||||
|
|
||||||
|
|
||||||
@@ -190,7 +192,7 @@ def pair(
|
|||||||
RemoteInspection,
|
RemoteInspection,
|
||||||
)
|
)
|
||||||
|
|
||||||
result = subprocess.run([sys.executable, "-c", _LOCATE, str(Path.home() / ".nanobot/config.json")], capture_output=True, text=True, timeout=8)
|
result = subprocess.run([sys.executable, "-c", _LOCATE, str(get_home_path() / "config.json")], capture_output=True, text=True, timeout=8)
|
||||||
records = [line.partition("NANOBOT_REMOTE:")[2] for line in result.stdout.splitlines() if "NANOBOT_REMOTE:" in line]
|
records = [line.partition("NANOBOT_REMOTE:")[2] for line in result.stdout.splitlines() if "NANOBOT_REMOTE:" in line]
|
||||||
candidates = RemoteInspection.model_validate_json(records[-1]).candidates if records else []
|
candidates = RemoteInspection.model_validate_json(records[-1]).candidates if records else []
|
||||||
if len(candidates) == 1:
|
if len(candidates) == 1:
|
||||||
|
|||||||
@@ -368,7 +368,7 @@ def _ensure_local_webui_channel(
|
|||||||
console.print(
|
console.print(
|
||||||
" LAN access requires an explicit host change plus a WebUI password in config."
|
" LAN access requires an explicit host change plus a WebUI password in config."
|
||||||
)
|
)
|
||||||
_confirm_webui_action("Update the local WebUI channel in this config?", yes=yes)
|
_confirm_webui_action("Enable the WebUI channel?", yes=yes)
|
||||||
|
|
||||||
if not model.enabled:
|
if not model.enabled:
|
||||||
model.enabled = True
|
model.enabled = True
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""Default instance paths selected by the global --home option."""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
_home_path: Path | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def set_home_path(path: Path | None) -> None:
|
||||||
|
"""Select the instance root for the current CLI invocation."""
|
||||||
|
global _home_path
|
||||||
|
_home_path = path.expanduser().resolve() if path is not None else None
|
||||||
|
|
||||||
|
|
||||||
|
def get_selected_home_path() -> Path | None:
|
||||||
|
"""Return the explicit instance root, if one was selected."""
|
||||||
|
return _home_path
|
||||||
|
|
||||||
|
|
||||||
|
def get_home_path() -> Path:
|
||||||
|
"""Return the selected instance root, or the default ~/.nanobot directory."""
|
||||||
|
return _home_path if _home_path is not None else Path.home() / ".nanobot"
|
||||||
|
|
||||||
|
|
||||||
|
def get_default_workspace() -> str:
|
||||||
|
"""Keep the portable default unless an instance home was selected."""
|
||||||
|
if _home_path is not None:
|
||||||
|
return str(get_home_path() / "workspace")
|
||||||
|
return "~/.nanobot/workspace"
|
||||||
@@ -10,6 +10,7 @@ from pydantic import BaseModel, ValidationError
|
|||||||
from pydantic_settings import SettingsError
|
from pydantic_settings import SettingsError
|
||||||
|
|
||||||
from nanobot.config.errors import ConfigIssue, ConfigLoadError, validation_issues
|
from nanobot.config.errors import ConfigIssue, ConfigLoadError, validation_issues
|
||||||
|
from nanobot.config.home import get_home_path
|
||||||
from nanobot.config.schema import (
|
from nanobot.config.schema import (
|
||||||
Config,
|
Config,
|
||||||
_resolve_tool_config_refs, # pyright: ignore[reportPrivateUsage]
|
_resolve_tool_config_refs, # pyright: ignore[reportPrivateUsage]
|
||||||
@@ -36,7 +37,7 @@ def get_config_path() -> Path:
|
|||||||
"""Get the configuration file path."""
|
"""Get the configuration file path."""
|
||||||
if _current_config_path:
|
if _current_config_path:
|
||||||
return _current_config_path
|
return _current_config_path
|
||||||
return Path.home() / ".nanobot" / "config.json"
|
return get_home_path() / "config.json"
|
||||||
|
|
||||||
|
|
||||||
def load_config(config_path: Path | None = None) -> Config:
|
def load_config(config_path: Path | None = None) -> Config:
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from nanobot.config.home import get_home_path
|
||||||
from nanobot.utils.helpers import ensure_dir
|
from nanobot.utils.helpers import ensure_dir
|
||||||
|
|
||||||
|
|
||||||
@@ -50,22 +51,22 @@ def get_webui_dir() -> Path:
|
|||||||
|
|
||||||
def get_workspace_path(workspace: str | Path | None = None) -> Path:
|
def get_workspace_path(workspace: str | Path | None = None) -> Path:
|
||||||
"""Resolve and ensure the agent workspace path."""
|
"""Resolve and ensure the agent workspace path."""
|
||||||
path = Path(workspace).expanduser() if workspace else Path.home() / ".nanobot" / "workspace"
|
path = Path(workspace).expanduser() if workspace else get_home_path() / "workspace"
|
||||||
return ensure_dir(path)
|
return ensure_dir(path)
|
||||||
|
|
||||||
|
|
||||||
def is_default_workspace(workspace: str | Path | None) -> bool:
|
def is_default_workspace(workspace: str | Path | None) -> bool:
|
||||||
"""Return whether a workspace resolves to nanobot's default workspace path."""
|
"""Return whether a workspace resolves to nanobot's default workspace path."""
|
||||||
current = Path(workspace).expanduser() if workspace is not None else Path.home() / ".nanobot" / "workspace"
|
current = Path(workspace).expanduser() if workspace is not None else get_home_path() / "workspace"
|
||||||
default = Path.home() / ".nanobot" / "workspace"
|
default = get_home_path() / "workspace"
|
||||||
return current.resolve(strict=False) == default.resolve(strict=False)
|
return current.resolve(strict=False) == default.resolve(strict=False)
|
||||||
|
|
||||||
|
|
||||||
def get_cli_history_path() -> Path:
|
def get_cli_history_path() -> Path:
|
||||||
"""Return the shared CLI history file path."""
|
"""Return the selected home's CLI history file path."""
|
||||||
return Path.home() / ".nanobot" / "history" / "cli_history"
|
return get_home_path() / "history" / "cli_history"
|
||||||
|
|
||||||
|
|
||||||
def get_legacy_sessions_dir() -> Path:
|
def get_legacy_sessions_dir() -> Path:
|
||||||
"""Return the legacy global session directory used for migration fallback."""
|
"""Return the selected home's legacy session directory for migration fallback."""
|
||||||
return Path.home() / ".nanobot" / "sessions"
|
return get_home_path() / "sessions"
|
||||||
@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any, ClassVar, Literal, cast
|
|||||||
from pydantic import AliasChoices, ConfigDict, Field, PrivateAttr, field_validator, model_validator
|
from pydantic import AliasChoices, ConfigDict, Field, PrivateAttr, field_validator, model_validator
|
||||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
from nanobot.config.home import get_default_workspace
|
||||||
from nanobot.config.provider_api_migration import migrate_legacy_provider_api
|
from nanobot.config.provider_api_migration import migrate_legacy_provider_api
|
||||||
from nanobot.config.timezone import detect_system_timezone
|
from nanobot.config.timezone import detect_system_timezone
|
||||||
from nanobot.config_base import Base
|
from nanobot.config_base import Base
|
||||||
@@ -152,7 +153,7 @@ class ModelPresetConfig(Base):
|
|||||||
class AgentDefaults(Base):
|
class AgentDefaults(Base):
|
||||||
"""Default agent configuration."""
|
"""Default agent configuration."""
|
||||||
|
|
||||||
workspace: str = "~/.nanobot/workspace"
|
workspace: str = Field(default_factory=get_default_workspace)
|
||||||
model_preset: str | None = None # Active preset name — takes precedence over fields below
|
model_preset: str | None = None # Active preset name — takes precedence over fields below
|
||||||
model: str = "anthropic/claude-opus-4-5"
|
model: str = "anthropic/claude-opus-4-5"
|
||||||
provider: str = (
|
provider: str = (
|
||||||
|
|||||||
+23
-10
@@ -22,6 +22,7 @@ from typing import Any, Generator, Literal, cast
|
|||||||
|
|
||||||
from filelock import FileLock
|
from filelock import FileLock
|
||||||
|
|
||||||
|
from nanobot.config.home import get_selected_home_path
|
||||||
from nanobot.config.paths import get_data_dir
|
from nanobot.config.paths import get_data_dir
|
||||||
from nanobot.process_runtime import (
|
from nanobot.process_runtime import (
|
||||||
ManagedProcessRuntime,
|
ManagedProcessRuntime,
|
||||||
@@ -33,7 +34,12 @@ from nanobot.process_runtime import (
|
|||||||
process_is_running,
|
process_is_running,
|
||||||
)
|
)
|
||||||
|
|
||||||
GatewayStartOptions = ProcessStartOptions
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class GatewayStartOptions(ProcessStartOptions):
|
||||||
|
"""Gateway launch options, including the explicit instance root."""
|
||||||
|
|
||||||
|
home: str | None = None
|
||||||
|
|
||||||
GatewayLaunchMode = Literal["foreground", "background", "unknown"]
|
GatewayLaunchMode = Literal["foreground", "background", "unknown"]
|
||||||
GatewayLifetime = Literal["explicit", "on_demand"]
|
GatewayLifetime = Literal["explicit", "on_demand"]
|
||||||
@@ -110,11 +116,15 @@ def build_gateway_command(python_executable: str, options: GatewayStartOptions)
|
|||||||
python_executable,
|
python_executable,
|
||||||
"-m",
|
"-m",
|
||||||
"nanobot",
|
"nanobot",
|
||||||
|
]
|
||||||
|
if options.home is not None:
|
||||||
|
command.extend(["--home", options.home])
|
||||||
|
command.extend([
|
||||||
"gateway",
|
"gateway",
|
||||||
"--foreground",
|
"--foreground",
|
||||||
"--port",
|
"--port",
|
||||||
str(options.port),
|
str(options.port),
|
||||||
]
|
])
|
||||||
if options.verbose:
|
if options.verbose:
|
||||||
command.append("--verbose")
|
command.append("--verbose")
|
||||||
if options.workspace:
|
if options.workspace:
|
||||||
@@ -156,6 +166,7 @@ class GatewayInstance:
|
|||||||
config_path: Path
|
config_path: Path
|
||||||
workspace: str | None
|
workspace: str | None
|
||||||
paths: GatewayRuntimePaths
|
paths: GatewayRuntimePaths
|
||||||
|
home: Path | None = None
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def resolve(
|
def resolve(
|
||||||
@@ -174,6 +185,7 @@ class GatewayInstance:
|
|||||||
None if resolved_config == _default_config_path() else str(resolved_config)
|
None if resolved_config == _default_config_path() else str(resolved_config)
|
||||||
)
|
)
|
||||||
return cls(
|
return cls(
|
||||||
|
home=get_selected_home_path(),
|
||||||
config_path=resolved_config,
|
config_path=resolved_config,
|
||||||
workspace=resolved_workspace,
|
workspace=resolved_workspace,
|
||||||
paths=GatewayRuntimePaths.for_instance(
|
paths=GatewayRuntimePaths.for_instance(
|
||||||
@@ -190,6 +202,7 @@ class GatewayInstance:
|
|||||||
verbose: bool = False,
|
verbose: bool = False,
|
||||||
) -> GatewayStartOptions:
|
) -> GatewayStartOptions:
|
||||||
return GatewayStartOptions(
|
return GatewayStartOptions(
|
||||||
|
home=str(self.home) if self.home is not None else None,
|
||||||
port=port,
|
port=port,
|
||||||
verbose=verbose,
|
verbose=verbose,
|
||||||
workspace=self.workspace,
|
workspace=self.workspace,
|
||||||
@@ -199,7 +212,7 @@ class GatewayInstance:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):
|
class GatewayRuntime(ManagedProcessRuntime[GatewayStartOptions]):
|
||||||
"""Manage a background ``nanobot gateway`` process."""
|
"""Manage a background ``nanobot gateway`` process."""
|
||||||
|
|
||||||
service_name = "gateway"
|
service_name = "gateway"
|
||||||
@@ -223,14 +236,14 @@ class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):
|
|||||||
sleep=sleep,
|
sleep=sleep,
|
||||||
)
|
)
|
||||||
|
|
||||||
def _build_child_command(self, options: ProcessStartOptions) -> list[str]:
|
def _build_child_command(self, options: GatewayStartOptions) -> list[str]:
|
||||||
return build_gateway_command(self.python_executable, options)
|
return build_gateway_command(self.python_executable, options)
|
||||||
|
|
||||||
def _transition_lock(self) -> FileLock:
|
def _transition_lock(self) -> FileLock:
|
||||||
"""Serialize long lifecycle transitions without blocking child cleanup."""
|
"""Serialize long lifecycle transitions without blocking child cleanup."""
|
||||||
return FileLock(f"{self.paths.state_path}.transition.lock")
|
return FileLock(f"{self.paths.state_path}.transition.lock")
|
||||||
|
|
||||||
def start_background(self, options: ProcessStartOptions) -> RuntimeResult:
|
def start_background(self, options: GatewayStartOptions) -> RuntimeResult:
|
||||||
"""Start the gateway detached from the current terminal."""
|
"""Start the gateway detached from the current terminal."""
|
||||||
lease = GatewayClientLease(self, kind="gateway-background")
|
lease = GatewayClientLease(self, kind="gateway-background")
|
||||||
while True:
|
while True:
|
||||||
@@ -242,7 +255,7 @@ class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):
|
|||||||
result = self._start_background(options)
|
result = self._start_background(options)
|
||||||
return RuntimeResult(result.ok, result.message, result.status, promoted)
|
return RuntimeResult(result.ok, result.message, result.status, promoted)
|
||||||
|
|
||||||
def start_on_demand(self, options: ProcessStartOptions) -> RuntimeResult:
|
def start_on_demand(self, options: GatewayStartOptions) -> RuntimeResult:
|
||||||
"""Atomically reuse a gateway or start one owned by local client leases."""
|
"""Atomically reuse a gateway or start one owned by local client leases."""
|
||||||
lease = GatewayClientLease(self, kind="gateway-start")
|
lease = GatewayClientLease(self, kind="gateway-start")
|
||||||
while True:
|
while True:
|
||||||
@@ -256,7 +269,7 @@ class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):
|
|||||||
lease._mark_ephemeral_locked()
|
lease._mark_ephemeral_locked()
|
||||||
return self._start_background(options)
|
return self._start_background(options)
|
||||||
|
|
||||||
def _start_background(self, options: ProcessStartOptions) -> RuntimeResult:
|
def _start_background(self, options: GatewayStartOptions) -> RuntimeResult:
|
||||||
result = super()._start_background(options)
|
result = super()._start_background(options)
|
||||||
if not result.ok:
|
if not result.ok:
|
||||||
return self._result(result)
|
return self._result(result)
|
||||||
@@ -325,7 +338,7 @@ class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):
|
|||||||
self._write_state(state)
|
self._write_state(state)
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def foreground_instance(self, options: ProcessStartOptions) -> Generator[None]:
|
def foreground_instance(self, options: GatewayStartOptions) -> Generator[None]:
|
||||||
"""Publish this foreground gateway while it is available to local clients."""
|
"""Publish this foreground gateway while it is available to local clients."""
|
||||||
self._claim_current_process(options)
|
self._claim_current_process(options)
|
||||||
try:
|
try:
|
||||||
@@ -333,7 +346,7 @@ class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):
|
|||||||
finally:
|
finally:
|
||||||
self._release_current_process()
|
self._release_current_process()
|
||||||
|
|
||||||
def _claim_current_process(self, options: ProcessStartOptions) -> GatewayLaunchMode:
|
def _claim_current_process(self, options: GatewayStartOptions) -> GatewayLaunchMode:
|
||||||
lease = GatewayClientLease(self, kind="gateway-foreground")
|
lease = GatewayClientLease(self, kind="gateway-foreground")
|
||||||
pid = os.getpid()
|
pid = os.getpid()
|
||||||
while True:
|
while True:
|
||||||
@@ -391,7 +404,7 @@ class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):
|
|||||||
kind="gateway-exit",
|
kind="gateway-exit",
|
||||||
)._finish_shutdown_locked()
|
)._finish_shutdown_locked()
|
||||||
|
|
||||||
def restart(self, options: ProcessStartOptions, *, timeout_s: int = 20) -> RuntimeResult:
|
def restart(self, options: GatewayStartOptions, *, timeout_s: int = 20) -> RuntimeResult:
|
||||||
"""Restart an existing gateway without creating a new persistent instance."""
|
"""Restart an existing gateway without creating a new persistent instance."""
|
||||||
with self._transition_lock():
|
with self._transition_lock():
|
||||||
with self._lifecycle_lock():
|
with self._lifecycle_lock():
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ def test_root_metadata_and_subcommands_keep_the_root_cli() -> None:
|
|||||||
for args in (
|
for args in (
|
||||||
["--help"],
|
["--help"],
|
||||||
["--version"],
|
["--version"],
|
||||||
|
["--home", "./instance", "onboard"],
|
||||||
|
["--home=./instance", "webui"],
|
||||||
["--install-completion"],
|
["--install-completion"],
|
||||||
["gateway"],
|
["gateway"],
|
||||||
["webui"],
|
["webui"],
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from typer.testing import CliRunner
|
||||||
|
|
||||||
|
from nanobot.cli.commands import app
|
||||||
|
from nanobot.config import home as instance_home
|
||||||
|
from nanobot.config import loader
|
||||||
|
from nanobot.config.paths import get_cli_history_path, get_legacy_sessions_dir, get_media_dir
|
||||||
|
from nanobot.config.schema import Config
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def isolate_config(monkeypatch):
|
||||||
|
monkeypatch.setattr(loader, "_current_config_path", None)
|
||||||
|
monkeypatch.setattr(instance_home, "_home_path", None)
|
||||||
|
|
||||||
|
|
||||||
|
def test_home_onboard_and_status(tmp_path):
|
||||||
|
home = tmp_path / "instance with spaces"
|
||||||
|
runner = CliRunner()
|
||||||
|
result = runner.invoke(app, ["--home", str(home), "onboard"])
|
||||||
|
assert result.exit_code == 0, result.output
|
||||||
|
data = json.loads((home / "config.json").read_text(encoding="utf-8"))
|
||||||
|
assert Path(data["agents"]["defaults"]["workspace"]) == home / "workspace"
|
||||||
|
assert (home / "workspace" / "SOUL.md").is_file()
|
||||||
|
result = runner.invoke(app, ["--home", str(home), "status"])
|
||||||
|
assert result.exit_code == 0, result.output
|
||||||
|
assert str(home) in "".join(result.output.splitlines())
|
||||||
|
assert instance_home.get_selected_home_path() is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_home_explicit_config_and_workspace_take_precedence(tmp_path):
|
||||||
|
home = tmp_path / "home"
|
||||||
|
config = tmp_path / "other" / "config.json"
|
||||||
|
workspace = tmp_path / "project"
|
||||||
|
result = CliRunner().invoke(app, [
|
||||||
|
"--home", str(home), "onboard", "--config", str(config),
|
||||||
|
"--workspace", str(workspace),
|
||||||
|
])
|
||||||
|
assert result.exit_code == 0, result.output
|
||||||
|
assert not (home / "config.json").exists()
|
||||||
|
loaded = loader.load_config(config)
|
||||||
|
assert loaded.workspace_path == workspace
|
||||||
|
assert loaded.runtime_data_dir == config.parent
|
||||||
|
|
||||||
|
|
||||||
|
def test_home_paths_and_saved_workspace(tmp_path):
|
||||||
|
instance_home.set_home_path(tmp_path)
|
||||||
|
assert loader.get_config_path() == tmp_path / "config.json"
|
||||||
|
assert Config().workspace_path == tmp_path / "workspace"
|
||||||
|
assert get_media_dir() == tmp_path / "media"
|
||||||
|
assert get_cli_history_path() == tmp_path / "history" / "cli_history"
|
||||||
|
assert get_legacy_sessions_dir() == tmp_path / "sessions"
|
||||||
|
config = Config()
|
||||||
|
config.agents.defaults.workspace = str(tmp_path / "custom")
|
||||||
|
loader.save_config(config)
|
||||||
|
assert loader.load_config().workspace_path == tmp_path / "custom"
|
||||||
|
|
||||||
|
|
||||||
|
def test_installed_entry_dispatch_and_help(tmp_path):
|
||||||
|
root = Path(__file__).parents[2]
|
||||||
|
for args in (["--home", str(tmp_path), "onboard"], ["-h"], ["--home", str(tmp_path), "status"]):
|
||||||
|
result = subprocess.run(
|
||||||
|
[sys.executable, "-m", "nanobot", *args], cwd=root,
|
||||||
|
capture_output=True, text=True, encoding="utf-8", check=False,
|
||||||
|
)
|
||||||
|
assert result.returncode == 0, result.stderr
|
||||||
|
assert (tmp_path / "config.json").is_file()
|
||||||
|
|
||||||
|
|
||||||
|
def test_home_rejects_file(tmp_path):
|
||||||
|
target = tmp_path / "file"
|
||||||
|
target.touch()
|
||||||
|
result = CliRunner().invoke(app, ["--home", str(target), "onboard"])
|
||||||
|
assert result.exit_code == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_home_bare_command_starts_agent_and_restores_selection(monkeypatch, tmp_path):
|
||||||
|
from nanobot.cli import entry
|
||||||
|
|
||||||
|
selected = tmp_path / "selected"
|
||||||
|
observed = []
|
||||||
|
|
||||||
|
def run_agent(args, *, prog_name):
|
||||||
|
observed.append((loader.get_config_path(), Config().workspace_path))
|
||||||
|
|
||||||
|
monkeypatch.setattr(entry, "_run_agent", run_agent)
|
||||||
|
result = CliRunner().invoke(app, ["--home", str(selected)])
|
||||||
|
assert result.exit_code == 0, result.output
|
||||||
|
assert observed == [(selected / "config.json", selected / "workspace")]
|
||||||
|
assert instance_home.get_selected_home_path() is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_gateway_child_receives_home_after_cli_selection_ends(tmp_path):
|
||||||
|
from nanobot.gateway import GatewayInstance, build_gateway_command
|
||||||
|
|
||||||
|
home = tmp_path / "instance with spaces"
|
||||||
|
instance_home.set_home_path(home)
|
||||||
|
instance = GatewayInstance.resolve(config_path=home / "config.json")
|
||||||
|
instance_home.set_home_path(None)
|
||||||
|
options = instance.start_options(port=18791)
|
||||||
|
command = build_gateway_command(sys.executable, options)
|
||||||
|
assert command[:5] == [sys.executable, "-m", "nanobot", "--home", str(home)]
|
||||||
|
assert command[5] == "gateway"
|
||||||
|
assert options.config_path == str(home / "config.json")
|
||||||
Reference in new issue
Block a user