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
@@ -111,11 +111,21 @@ def version_callback(value: bool):
|
||||
@app.callback(invoke_without_command=True)
|
||||
def main(
|
||||
ctx: typer.Context,
|
||||
home: Path | None = typer.Option(
|
||||
None, "--home", help="Instance root directory",
|
||||
file_okay=False,
|
||||
),
|
||||
version: bool = typer.Option(
|
||||
None, "--version", "-v", callback=version_callback, is_eager=True
|
||||
),
|
||||
):
|
||||
"""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
|
||||
# imports this Typer app directly instead of ``nanobot.cli.entry``. Keep the
|
||||
# role identity correct until that launcher is regenerated.
|
||||
|
||||
@@ -18,6 +18,7 @@ _ROOT_OPTIONS = frozenset(
|
||||
"--version",
|
||||
"--install-completion",
|
||||
"--show-completion",
|
||||
"--home",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -15,6 +15,8 @@ from typing import NoReturn
|
||||
|
||||
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.")
|
||||
|
||||
|
||||
@@ -190,7 +192,7 @@ def pair(
|
||||
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]
|
||||
candidates = RemoteInspection.model_validate_json(records[-1]).candidates if records else []
|
||||
if len(candidates) == 1:
|
||||
|
||||
@@ -368,7 +368,7 @@ def _ensure_local_webui_channel(
|
||||
console.print(
|
||||
" 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:
|
||||
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 nanobot.config.errors import ConfigIssue, ConfigLoadError, validation_issues
|
||||
from nanobot.config.home import get_home_path
|
||||
from nanobot.config.schema import (
|
||||
Config,
|
||||
_resolve_tool_config_refs, # pyright: ignore[reportPrivateUsage]
|
||||
@@ -36,7 +37,7 @@ def get_config_path() -> Path:
|
||||
"""Get the configuration file path."""
|
||||
if _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:
|
||||
|
||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from nanobot.config.home import get_home_path
|
||||
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:
|
||||
"""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)
|
||||
|
||||
|
||||
def is_default_workspace(workspace: str | Path | None) -> bool:
|
||||
"""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"
|
||||
default = Path.home() / ".nanobot" / "workspace"
|
||||
current = Path(workspace).expanduser() if workspace is not None else get_home_path() / "workspace"
|
||||
default = get_home_path() / "workspace"
|
||||
return current.resolve(strict=False) == default.resolve(strict=False)
|
||||
|
||||
|
||||
def get_cli_history_path() -> Path:
|
||||
"""Return the shared CLI history file path."""
|
||||
return Path.home() / ".nanobot" / "history" / "cli_history"
|
||||
"""Return the selected home's CLI history file path."""
|
||||
return get_home_path() / "history" / "cli_history"
|
||||
|
||||
|
||||
def get_legacy_sessions_dir() -> Path:
|
||||
"""Return the legacy global session directory used for migration fallback."""
|
||||
return Path.home() / ".nanobot" / "sessions"
|
||||
"""Return the selected home's legacy session directory for migration fallback."""
|
||||
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_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.timezone import detect_system_timezone
|
||||
from nanobot.config_base import Base
|
||||
@@ -152,7 +153,7 @@ class ModelPresetConfig(Base):
|
||||
class AgentDefaults(Base):
|
||||
"""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: str = "anthropic/claude-opus-4-5"
|
||||
provider: str = (
|
||||
|
||||
+23
-10
@@ -22,6 +22,7 @@ from typing import Any, Generator, Literal, cast
|
||||
|
||||
from filelock import FileLock
|
||||
|
||||
from nanobot.config.home import get_selected_home_path
|
||||
from nanobot.config.paths import get_data_dir
|
||||
from nanobot.process_runtime import (
|
||||
ManagedProcessRuntime,
|
||||
@@ -33,7 +34,12 @@ from nanobot.process_runtime import (
|
||||
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"]
|
||||
GatewayLifetime = Literal["explicit", "on_demand"]
|
||||
@@ -110,11 +116,15 @@ def build_gateway_command(python_executable: str, options: GatewayStartOptions)
|
||||
python_executable,
|
||||
"-m",
|
||||
"nanobot",
|
||||
]
|
||||
if options.home is not None:
|
||||
command.extend(["--home", options.home])
|
||||
command.extend([
|
||||
"gateway",
|
||||
"--foreground",
|
||||
"--port",
|
||||
str(options.port),
|
||||
]
|
||||
])
|
||||
if options.verbose:
|
||||
command.append("--verbose")
|
||||
if options.workspace:
|
||||
@@ -156,6 +166,7 @@ class GatewayInstance:
|
||||
config_path: Path
|
||||
workspace: str | None
|
||||
paths: GatewayRuntimePaths
|
||||
home: Path | None = None
|
||||
|
||||
@classmethod
|
||||
def resolve(
|
||||
@@ -174,6 +185,7 @@ class GatewayInstance:
|
||||
None if resolved_config == _default_config_path() else str(resolved_config)
|
||||
)
|
||||
return cls(
|
||||
home=get_selected_home_path(),
|
||||
config_path=resolved_config,
|
||||
workspace=resolved_workspace,
|
||||
paths=GatewayRuntimePaths.for_instance(
|
||||
@@ -190,6 +202,7 @@ class GatewayInstance:
|
||||
verbose: bool = False,
|
||||
) -> GatewayStartOptions:
|
||||
return GatewayStartOptions(
|
||||
home=str(self.home) if self.home is not None else None,
|
||||
port=port,
|
||||
verbose=verbose,
|
||||
workspace=self.workspace,
|
||||
@@ -199,7 +212,7 @@ class GatewayInstance:
|
||||
)
|
||||
|
||||
|
||||
class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):
|
||||
class GatewayRuntime(ManagedProcessRuntime[GatewayStartOptions]):
|
||||
"""Manage a background ``nanobot gateway`` process."""
|
||||
|
||||
service_name = "gateway"
|
||||
@@ -223,14 +236,14 @@ class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):
|
||||
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)
|
||||
|
||||
def _transition_lock(self) -> FileLock:
|
||||
"""Serialize long lifecycle transitions without blocking child cleanup."""
|
||||
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."""
|
||||
lease = GatewayClientLease(self, kind="gateway-background")
|
||||
while True:
|
||||
@@ -242,7 +255,7 @@ class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):
|
||||
result = self._start_background(options)
|
||||
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."""
|
||||
lease = GatewayClientLease(self, kind="gateway-start")
|
||||
while True:
|
||||
@@ -256,7 +269,7 @@ class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):
|
||||
lease._mark_ephemeral_locked()
|
||||
return self._start_background(options)
|
||||
|
||||
def _start_background(self, options: ProcessStartOptions) -> RuntimeResult:
|
||||
def _start_background(self, options: GatewayStartOptions) -> RuntimeResult:
|
||||
result = super()._start_background(options)
|
||||
if not result.ok:
|
||||
return self._result(result)
|
||||
@@ -325,7 +338,7 @@ class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):
|
||||
self._write_state(state)
|
||||
|
||||
@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."""
|
||||
self._claim_current_process(options)
|
||||
try:
|
||||
@@ -333,7 +346,7 @@ class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):
|
||||
finally:
|
||||
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")
|
||||
pid = os.getpid()
|
||||
while True:
|
||||
@@ -391,7 +404,7 @@ class GatewayRuntime(ManagedProcessRuntime[ProcessStartOptions]):
|
||||
kind="gateway-exit",
|
||||
)._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."""
|
||||
with self._transition_lock():
|
||||
with self._lifecycle_lock():
|
||||
|
||||
Reference in new issue
Block a user