Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -591,6 +591,28 @@ deep); set `project_roots` (a list) and `worktree_root` in `serve.json`, or
bridge's environment. Both machines append every teleport to
`<live dir>/teleports.jsonl`.

#### A cloud box for teleports

A box is a cloud VM joined to the relay like any machine, that this machine
powers on for a teleport and off when idle. Its disk stays while it is off, so
what the first teleport installed there (tools, logins, checkouts) is still there
for the next one; only the disk is billed meanwhile. Scaleway is supported,
through its `scw` CLI logged in on this machine.

```bash
one-conv live invite cloud-box # here; run the printed join on the VM with --accept-teleport
one-conv live box add cloud-box --scaleway <instance-id> --zone fr-par-1 --yes
one-conv live box ls # registered boxes and whether they run
one-conv live box start cloud-box --yes # or let `live teleport cloud-box` do it
one-conv live box stop cloud-box --yes
```

`live teleport` to a box that is off powers it on and waits for its bridge
(about a minute). The bridge of the machine that registered the box powers it
off once no session on it was busy for 30 minutes (`ONE_CONV_BOX_IDLE_MINUTES`,
`0` never); sessions still open there end, their transcripts stay on its disk
and in the archive. Boxes are listed in `<live dir>/boxes.json`.

#### Self-hosted alternative: the Python relay

`scripts/live-hub.py` is the same relay as one Python process, for a machine you
Expand Down
4 changes: 3 additions & 1 deletion SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,9 @@ a person (logins, 2FA, secrets; never ask for secret values in chat). Then pick
up the task: what isn't blocked now, the rest once provisioned. Read turns the brief omits with `one-conv local thread
ORIGIN --around ...`. The other machine must have opted in with
`one-conv live serve --accept-teleport`; if it refuses, tell the user that
command.
command. A node listed by `one-conv live box ls` is a cloud box: teleporting
there powers it on first (about a minute), and it powers off after 30 minutes
without a busy session, so finish by pushing your work.

Keep exchanges reconstructable. Open each message with
`to: <address> cc: <addresses> re: <subject>`. A relayed message is a user turn
Expand Down
4 changes: 4 additions & 0 deletions mcpb.json
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,10 @@
"live spawn",
"live stop",
"live teleport",
"live box add",
"live box ls",
"live box start",
"live box stop",
"live share",
"live invite",
"board topics",
Expand Down
160 changes: 160 additions & 0 deletions one_conv/live/box.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
"""Cloud boxes: relay nodes on a cloud VM that this machine powers on for a teleport and off when idle.

A box is a node joined like any other (`live invite` / `live join --accept-teleport`) whose VM this
machine can start and stop through the provider's CLI (Scaleway's `scw`, already logged in here).
Its disk is kept while it is off, so tools, logins and checkouts installed on it stay for the next
teleport; only compute stops being billed. The registry lives in boxes.json next to the bridge
settings, so only machines that registered a box manage it.

`live teleport` to a box that is off powers it on first. The bridge of a machine that registered
boxes powers a box off once no session on it was busy for IDLE_MINUTES, from the relay's published
sessions; it never touches a box it has not seen running for that long.
"""

import json
import logging
import os
import shutil
import subprocess
import threading
import time
from collections.abc import Callable
from dataclasses import asdict, dataclass
from pathlib import Path

from . import bridge

logger = logging.getLogger(__name__)

PROVIDERS = ("scaleway",)
IDLE_MINUTES = 30.0
# How often the bridge looks at its boxes' sessions.
CHECK_SECONDS = 60.0
SCW_TIMEOUT = 300.0
RUNNING = "running"
STOPPED = "stopped"


class BoxError(Exception):
"""A box that cannot be found, started or stopped."""


@dataclass
class Box:
node: str
provider: str
server: str
zone: str


def registry_path() -> Path:
return bridge.bridge_dir().parent / "boxes.json"


def load() -> dict[str, Box]:
try:
data = json.loads(registry_path().read_text())
except (FileNotFoundError, json.JSONDecodeError):
return {}
return {node: Box(**entry) for node, entry in data.items()}


def save(boxes: dict[str, Box]) -> None:
path = registry_path()
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps({node: asdict(box) for node, box in sorted(boxes.items())}, indent=2) + "\n")


def idle_minutes() -> float:
"""ONE_CONV_BOX_IDLE_MINUTES, else IDLE_MINUTES; 0 never powers a box off."""
try:
return float(os.environ.get("ONE_CONV_BOX_IDLE_MINUTES", IDLE_MINUTES))
except ValueError:
return IDLE_MINUTES


def _scw(*args: str, run=subprocess.run) -> dict:
if shutil.which("scw") is None and run is subprocess.run:
raise BoxError("the Scaleway CLI `scw` is not installed here (brew install scw, then scw init)")
result = run(["scw", *args, "-o", "json"], check=False, capture_output=True, text=True, timeout=SCW_TIMEOUT)
if result.returncode:
raise BoxError(f"scw {' '.join(args[:3])} failed: {(result.stderr or result.stdout).strip()[:300]}")
return json.loads(result.stdout) if result.stdout.strip() else {}


def state(box: Box, run=subprocess.run) -> str:
"""The VM's provider state: running, stopped, starting, stopping, ..."""
return _scw("instance", "server", "get", box.server, f"zone={box.zone}", run=run).get("state", "")


def start(box: Box, run=subprocess.run) -> bool:
"""Power the VM on and wait until it runs; False when it already ran."""
if state(box, run) == RUNNING:
return False
_scw("instance", "server", "start", box.server, f"zone={box.zone}", "-w", run=run)
return True


def stop(box: Box, run=subprocess.run) -> bool:
"""Power the VM off and keep its disk; False when it was not running."""
if state(box, run) != RUNNING:
return False
_scw("instance", "server", "stop", box.server, f"zone={box.zone}", "-w", run=run)
return True


def idle_boxes(boxes: dict[str, Box], sessions: list[dict], last_busy: dict[str, float], now: float,
idle_seconds: float) -> list[str]:
"""Nodes whose sessions were not busy for idle_seconds; updates `last_busy` from `sessions`.

A node first seen here starts its clock now, so a box is never stopped on the first look.
"""
for row in sessions:
if row.get("node") in boxes and row.get("status") == "busy" and row.get("online", True):
last_busy[row["node"]] = now
idle = []
for node in boxes:
last_busy.setdefault(node, now)
if idle_seconds > 0 and now - last_busy[node] >= idle_seconds:
idle.append(node)
return idle


class Keeper:
"""Powers off this machine's boxes once idle; run from the bridge loop, one stop at a time."""

def __init__(self, idle_seconds: float | None = None, check_seconds: float = CHECK_SECONDS,
clock: Callable[[], float] = time.time, stopper: Callable[[Box], bool] = stop):
self.idle_seconds = idle_minutes() * 60 if idle_seconds is None else idle_seconds
self.check_seconds, self.clock, self.stopper = check_seconds, clock, stopper
self.last_busy: dict[str, float] = {}
self.checked = None
self.worker: threading.Thread | None = None

def poll(self, client) -> list[str]:
"""Check at most every check_seconds; returns the nodes whose stop it started."""
boxes = load()
if not boxes or self.idle_seconds <= 0:
return []
now = self.clock()
if self.checked is not None and now - self.checked < self.check_seconds:
return []
if self.worker is not None and self.worker.is_alive():
return []
self.checked = now
sessions = client.request("GET", "/v1/sessions").get("sessions", [])
idle = idle_boxes(boxes, sessions, self.last_busy, now, self.idle_seconds)
if idle:
self.worker = threading.Thread(target=self._stop, args=([boxes[node] for node in idle],), daemon=True)
self.worker.start()
return idle

def _stop(self, boxes: list[Box]) -> None:
for box in boxes:
try:
if self.stopper(box):
logger.info("powered off box %s: no busy session for %.0f min", box.node, self.idle_seconds / 60)
except (BoxError, subprocess.TimeoutExpired, OSError) as error:
logger.warning("could not power off box %s: %s", box.node, error)
# Restart the clock either way: a failed stop is retried after another idle period.
self.last_busy[box.node] = self.clock()
3 changes: 3 additions & 0 deletions one_conv/live/bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,8 @@ def serve(hub: str, node: str, token: str, hub_port: int = 8789, stopping=None,
ingress, backoff = Ingress(bridge_dir() / "ingress.db"), 1.0
stream = None
archive = archive or ArchiveLanes()
from . import box
keeper = box.Keeper()
holding = HeldDelivery()
holding.start()
_report(hub=hub, node=node, started=time.time(), last_error=None)
Expand Down Expand Up @@ -634,6 +636,7 @@ def serve(hub: str, node: str, token: str, hub_port: int = 8789, stopping=None,
# Reset only after a full step, so a stream that drops right after opening still backs off.
backoff = 1.0
archive.poll(url, token, node)
keeper.poll(client)
_report(last_ok=time.time(), published=len(bridge.directory), notes=bridge.notes)
except (hubclient.HubUnavailable, tunnel.TunnelError) as error:
logger.warning("hub unreachable, retrying in %.0fs: %s", backoff, error)
Expand Down
104 changes: 103 additions & 1 deletion one_conv/live/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
HUB_MESSAGE_ID = re.compile(r"[0-9a-f]{32}")


# A box just powered on boots and starts its bridge in about a minute; each probe waits 60 s.
BOX_PROBE_ATTEMPTS = 4


def examples(*lines: str) -> str:
"""A help epilog click prints as written: its leading \\b keeps the line breaks."""
return "\b\nExamples:\n" + "\n".join(f" {line}" for line in lines)
Expand Down Expand Up @@ -478,6 +482,95 @@ def stop_command(targets, stop_all, as_json, yes):
if as_json:
click.echo(json.dumps(results))

@live.group("box", context_settings=HELP,
epilog=examples("one-conv live box add cloud-box --scaleway 0123abcd-... --zone fr-par-1 --yes",
"one-conv live box ls",
"one-conv live box start cloud-box --yes",
"one-conv live box stop cloud-box --yes"))
def box_group():
"""Cloud VMs on the relay that this machine powers on for a teleport and off when idle.

Join the VM as a node first (`live invite` here, `live join --accept-teleport` there), then
register it with `live box add`. `live teleport` to a box that is off powers it on; this
machine's bridge powers it off after 30 min with no busy session on it
(ONE_CONV_BOX_IDLE_MINUTES; 0 never). Its disk stays, so what is installed there stays.
Uses the provider's CLI logged in here (Scaleway: scw).
"""

@box_group.command("add", context_settings=HELP)
@click.argument("node")
@click.option("--scaleway", "server", required=True, help="The Scaleway instance id of NODE's VM.")
@click.option("--zone", default="fr-par-1", show_default=True, help="The instance's zone.")
@click.option("--yes", is_flag=True, help="Register. Without it, only says what would be registered.")
def box_add(node, server, zone, yes):
"""Register NODE's VM so teleports power it on and the bridge powers it off when idle."""
from . import box
if not yes:
click.echo(f"DRY-RUN: would register box {node} (scaleway {server} in {zone}). Re-run with --yes.")
return
boxes = box.load()
boxes[node] = box.Box(node=node, provider="scaleway", server=server, zone=zone)
try:
current = box.state(boxes[node])
except box.BoxError as error:
raise click.ClickException(str(error)) from None
box.save(boxes)
click.echo(f"registered box {node} (scaleway {server} in {zone}, {current}) in {box.registry_path()}")

@box_group.command("ls", context_settings=HELP)
@click.option("--json", "as_json", is_flag=True, help="Emit [{node, provider, server, zone, state}] as JSON.")
def box_ls(as_json):
"""List registered boxes and whether their VM runs."""
from . import box
rows = []
for item in box.load().values():
try:
current = box.state(item)
except box.BoxError as error:
current = f"unknown ({error})"
rows.append({**box.asdict(item), "state": current})
if as_json:
click.echo(json.dumps(rows))
return
if not rows:
click.echo("No boxes. Register one with `one-conv live box add NODE --scaleway ID`.")
for row in rows:
click.echo(f"{row['node']:<16} {row['state']:<10} {row['provider']} {row['server']} {row['zone']}")

@box_group.command("start", context_settings=HELP)
@click.argument("node")
@click.option("--yes", is_flag=True, help="Power on. Without it, only says what would happen.")
def box_start(node, yes):
"""Power NODE's VM on and wait until it runs; its bridge reconnects a minute later."""
from . import box
item = box.load().get(node)
if item is None:
raise click.ClickException(f"{node} is not a registered box (`one-conv live box ls`)")
if not yes:
click.echo(f"DRY-RUN: would power on {node} (compute is billed while it runs). Re-run with --yes.")
return
try:
click.echo(f"powered on {node}" if box.start(item) else f"{node} already runs")
except box.BoxError as error:
raise click.ClickException(str(error)) from None

@box_group.command("stop", context_settings=HELP)
@click.argument("node")
@click.option("--yes", is_flag=True, help="Power off. Without it, only says what would happen.")
def box_stop(node, yes):
"""Power NODE's VM off now; its disk stays. Sessions running there end."""
from . import box
item = box.load().get(node)
if item is None:
raise click.ClickException(f"{node} is not a registered box (`one-conv live box ls`)")
if not yes:
click.echo(f"DRY-RUN: would power off {node}; sessions running there end. Re-run with --yes.")
return
try:
click.echo(f"powered off {node}" if box.stop(item) else f"{node} was not running")
except box.BoxError as error:
raise click.ClickException(str(error)) from None

@live.command("teleport", context_settings=HELP,
epilog=examples("one-conv live teleport studio --check",
"one-conv live teleport studio --yes",
Expand Down Expand Up @@ -522,9 +615,18 @@ def teleport_command(node, cwd, mode, check, force, sender_address, as_json, yes
raise click.ClickException(f"cannot read {sender.address}'s transcript: {error.message}") from None
found = inventories.build(sender.harness, sender.cwd or read.get("cwd") or "", read.get("blocks") or [],
read.get("path"))
from . import box
attempts = 1
if node in box.load():
try:
if box.start(box.load()[node]):
click.echo(f"powered on box {node}; waiting for its bridge", err=True)
attempts = BOX_PROBE_ATTEMPTS
except box.BoxError as error:
raise click.ClickException(f"cannot power on box {node}: {error}") from None
try:
report = teleport.run(node, sender, read, found, cwd=cwd, mode=mode, check_only=check or not yes,
force=force)
force=force, probe_attempts=attempts)
except (teleport.TeleportError, hubclient.HubRefused) as error:
if as_json:
click.echo(json.dumps({"status": "failed", "error": str(error),
Expand Down
Loading
Loading