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
10 changes: 10 additions & 0 deletions changes/remote-machines-from-the-cli-and-agents.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
type: new
link: docs/README.md#remote-machines
---

## Check and control another machine's services from a terminal or an agent

Add `--machine <name>` to `services status`, `logs`, `dev`, `stop` and `restart` to act on
another of your machines, as the app's machine switcher does. Coding agents get the same
through `list_machines` and a `machine` argument on the service tools.
18 changes: 18 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,23 @@ there, the card gives the one command to run on it instead, such as
A service started from an app older than 1.5 shows "Relaunch to share". Relaunch it, after
a confirmation, and its output and controls work from then on.

**From a terminal or an agent.** Add `--machine <name or id>` to act on another machine's
services. Without `--env`, it uses the primary checkout there, and a service name that
exists in two projects needs `--project`.

```bash
localify services status --machine teo-desktop
localify logs web --machine teo-desktop -f
localify dev web --machine teo-desktop --profile staging
localify restart web --machine teo-desktop
```

`dev --machine` takes only `--project`, `--env` and `--profile`: the other machine decides
whether the service starts in its app or in the background. A refusal prints why and
exits with code 2; a control whose outcome never came back prints the service's current
state and exits with code 3. Agents get the same through the `machine` argument of the
service tools, and `list_machines`.

How it works, for contributors: [remote-machines.md](remote-machines.md).

## Access from other devices
Expand Down Expand Up @@ -600,6 +617,7 @@ for debug output. `localify <command> --help` lists the rest.
| `localify billing` | Manage the subscription |
| `localify public-url create\|list\|remove\|protect\|unprotect\|claim` | Manage public URLs |
| `localify machines [pair\|unpair\|remove\|settings]` | Pair machines and choose what they may do here |
| `localify services status\|logs\|dev\|stop\|restart ... --machine <m>` | The same on another machine |
| **Other** | |
| `localify completions <shell>` | Generate shell completions |

Expand Down
8 changes: 4 additions & 4 deletions docs/remote-machines.md
Original file line number Diff line number Diff line change
Expand Up @@ -809,19 +809,19 @@ localify stop <service> --machine <machine> [--project <id>] [--env <slug>]
localify restart <service> --machine <machine> [--project <id>] [--env <slug>]
```

- **Resolving `--machine`:** an exact machine id; otherwise an exact name, ignoring case, among the active machines of the roster. Active names are unique, since a same-name sign-in replaces the older machine; a name that still matches two, differing only in case, is an error that lists both with their ids. A name of no active machine lists the roster. This machine's own id or name acts locally, as without `--machine`.
- **Resolving `--machine`:** an exact machine id; otherwise an exact name, ignoring case, among the active machines of the roster. Active names are unique, since a same-name sign-in replaces the older machine; a name that still matches two, differing only in case, is an error that lists both with their ids. A name of no active machine lists the roster. This machine's own id or name acts locally; `dev` behaves as `dev --in-app`, and the other commands behave as without `--machine`.
- **Resolving a service:** there is no folder to read on another machine, so a service name must be unique on the target, or come with `--project`, and `--env` names a non-primary checkout. An ambiguous name lists the matches.
- **What `--machine` refuses:** with `dev`, every option but `--project`, `--env` and `--profile`: no command after `--`, no `--detach`, `--in-app`, `--env-file`, `--confirm-profile` or `--domain`. The target decides where the service runs.
- **Launch flags:** `--launch-id`, `--launch-expires`, `--remote-launch`, `--expect-rev`, `--request` and `--replace-legacy` are hidden flags for dispatchers, documented here and not in `--help`.
- **Output:** human on a terminal, JSON otherwise, as everywhere. A control prints its progress, then its result; an outcome it could not learn (`lost`) prints the fresh status and exits with code 3. A refusal prints the message of "Errors" and exits with code 2.
- **Output:** human on a terminal, JSON otherwise, as everywhere. A control prints its progress, then its result; an outcome it could not learn (`lost`) prints the fresh status and exits with code 3. A refusal prints the message of "Errors" and exits with code 2; a `conflict` prints "B changed in the meantime." with the service's fresh state, and the control is never sent again. `unknown` is progress, "Outcome unknown. Checking B…", never where a control stops. A control the snapshot already refuses (its `controls`, or a live legacy run, which the app relaunches after a confirmation) is refused the same way without being sent. A run that failed exits with code 1. With JSON, progress goes to stderr, so stdout holds one document: `{outcome, code, message, …}`. `logs` prints plain lines, as without `--machine`, and its next cursor on stderr. When the service restarts during a read or `--follow` (`gone`), it reads the service's current run from offset 0.
- `pair` and `remove` need a terminal: an agent cannot pair or remove machines.

## MCP

- `list_machines`: the roster with states, read-only.
- An optional `machine` argument on `list_services`, `service_status`, `service_logs`, `service_start`, `service_stop` and `service_restart`, and on no other tool. With it, a tool ignores `cwd`.
- An optional `machine` argument on `list_services`, `service_status`, `service_logs`, `service_start`, `service_stop` and `service_restart`, and on no other tool. With it, a tool ignores `cwd`. Any other tool given `machine` fails before it runs anything, rather than acting on this machine.
- With `machine`, `service_start` takes only `service`, `project`, `env` and `profile`. `background`, `env_files`, `confirm_profile`, `command` and `domain` make it fail with an error that says the target decides how its services start. It never creates a project.
- `service_logs` with `machine` returns a cursor `<runId>:<offset>`.
- `service_logs` with `machine` returns a cursor `<runId>:<offset>`. `list_services` and `service_status` with `machine` both give the target's snapshot (`services status --machine`).
- Pairing, unpairing, settings and removal have no tool. Like signing in (ADR 0018), they stay a person's decision.
- An error from a target reaches the agent with its code and message, so `control_disabled` tells it to ask the user to allow controls on that machine, and an outcome it could not learn (`lost`) tells it to check `service_status` before trying again.

Expand Down
4 changes: 4 additions & 0 deletions src/application/ports/daemon_connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ pub enum DaemonConnectionError {
ConnectionFailed(#[source] anyhow::Error),
#[error("Protocol error: {0}")]
ProtocolError(String),
/// Another machine, or the way to it, refused: the contract's code and
/// its message (docs/remote-machines.md, "Errors").
#[error("{message}")]
Remote { code: String, message: String },
}

/// Port for communicating with a running daemon process.
Expand Down
41 changes: 20 additions & 21 deletions src/cli/machines.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use crate::config::LocalifyPaths;
use crate::infrastructure::cloud::api::CloudClient;
use crate::infrastructure::cloud::credentials::CredentialsStore;
use crate::infrastructure::cloud::http::{CloudHttp, block_on};
use crate::infrastructure::mgmt_client::MgmtSocketClient;

#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum Switch {
Expand All @@ -34,36 +35,34 @@ impl Switch {
/// One machine of `remote_machines`.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Machine {
id: String,
name: String,
pub(super) struct Machine {
pub(super) id: String,
pub(super) name: String,
#[serde(rename = "self")]
is_self: bool,
pub(super) is_self: bool,
paired: bool,
state: String,
pub(super) state: String,
#[serde(default)]
version: Option<String>,
#[serde(default)]
sharing: Option<bool>,
}

fn daemon_error(error: DaemonConnectionError) -> anyhow::Error {
pub(super) fn daemon_error(error: DaemonConnectionError) -> anyhow::Error {
match error {
DaemonConnectionError::NotRunning => anyhow!(
"Remote machines go through the {} daemon, which is not running. Start it with: {} start",
BRANDING.app_name,
BRANDING.cli_command()
),
DaemonConnectionError::ProtocolError(message) => anyhow!(message),
DaemonConnectionError::ProtocolError(message)
| DaemonConnectionError::Remote { message, .. } => anyhow!(message),
other => anyhow!("Could not reach the daemon: {other}"),
}
}

fn machines(ctx: &AppContext, probe: bool) -> Result<Vec<Machine>> {
let list = ctx
.mgmt_client
.remote_machines(probe)
.map_err(daemon_error)?;
pub(super) fn machines(client: &MgmtSocketClient, probe: bool) -> Result<Vec<Machine>> {
let list = client.remote_machines(probe).map_err(daemon_error)?;
serde_json::from_value(list).context("The daemon sent a machine list this version cannot read")
}

Expand Down Expand Up @@ -168,21 +167,21 @@ fn state_label(state: &str) -> &str {

/// A machine the person named.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Candidate {
id: String,
name: String,
is_self: bool,
pub(super) struct Candidate {
pub(super) id: String,
pub(super) name: String,
pub(super) is_self: bool,
}

/// An exact machine id, else an exact name ignoring case. A name that
/// matches two machines lists both.
fn resolve(candidates: &[Candidate], query: &str) -> Result<Candidate> {
pub(super) fn resolve(candidates: &[Candidate], query: &str) -> Result<Candidate> {
if let Some(found) = candidates.iter().find(|machine| machine.id == query) {
return Ok(found.clone());
}
let named: Vec<&Candidate> = candidates
.iter()
.filter(|machine| machine.name.eq_ignore_ascii_case(query))
.filter(|machine| machine.name.to_lowercase() == query.to_lowercase())
.collect();
match named.as_slice() {
[one] => Ok((*one).clone()),
Expand Down Expand Up @@ -212,7 +211,7 @@ fn resolve(candidates: &[Candidate], query: &str) -> Result<Candidate> {
}
}

fn candidates(machines: &[Machine]) -> Vec<Candidate> {
pub(super) fn candidates(machines: &[Machine]) -> Vec<Candidate> {
machines
.iter()
.map(|machine| Candidate {
Expand Down Expand Up @@ -246,7 +245,7 @@ fn typed_yes(prompt: &str) -> Result<bool> {
/// `localify machines pair <machine>`, as the viewer.
pub fn pair(query: &str, ctx: &AppContext) -> Result<()> {
require_person("Pair")?;
let target = resolve(&candidates(&machines(ctx, false)?), query)?;
let target = resolve(&candidates(&machines(&ctx.mgmt_client, false)?), query)?;
if target.is_self {
bail!("{} is this machine: pair it from another one.", target.name);
}
Expand Down Expand Up @@ -346,7 +345,7 @@ pub fn accept(ctx: &AppContext) -> Result<()> {
/// `localify machines unpair <machine>`: deletes the pin, and tells the
/// machine when a session is open.
pub fn unpair(query: &str, json_flag: bool, ctx: &AppContext) -> Result<()> {
let machines = machines(ctx, false)?;
let machines = machines(&ctx.mgmt_client, false)?;
let paired: Vec<Machine> = machines
.into_iter()
.filter(|machine| machine.paired)
Expand Down
6 changes: 6 additions & 0 deletions src/cli/mcp/instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ Public URLs (Localify Cloud), only when the user wants to reach an app from anot
- Serving public URLs takes Localify Cloud Pro: $7.99 a month or $79 a year, after a 7-day free trial that asks for a card. Paying is the user's call too: when a tool answers that a plan is needed, tell them the price and the trial and ask them to run `localify subscribe`. When a tool answers that a limit is reached and names a command that raises it, suggest the user run that command. Never start a checkout or pass on a checkout link. `whoami` shows the plan (`plan.entitled`, dates, limits and usage) and why this machine's tunnel is blocked, if it is.
- `public_url_list` shows which machine serves each URL and its `state`: `suspended` when the plan does not cover it, `taken_down` when it was removed for abuse. `public_url_claim` moves one to this machine; `public_url_remove` takes it offline. When every serving slot is taken, removing the URLs another machine serves, or claiming them here, frees its slot.

Other machines (Localify Cloud), only when the user asks about a service on another of their machines:
- `list_machines` lists the account's machines. Pass a name or id as `machine` to `list_services`, `service_status`, `service_logs`, `service_start`, `service_stop` or `service_restart` to act on that machine. `cwd` is ignored there, and `env` names one of its worktrees.
- The other machine decides how a service starts: with `machine`, `service_start` takes only `service`, `project`, `env` and `profile`, and never creates a project.
- A refusal carries the other machine's code. On `control_disabled` or `background_disabled`, ask the user to allow remote controls on that machine. When a control ends `lost`, its outcome is unknown: call `service_status` before you try again.
- Pairing, unpairing and a machine's settings are the user's to change.

When something does not work:
- Call `status` first. A domain that does not resolve: the daemon may be stopped (`daemon` start) or Localify not installed (`install_localify`). A page saying the target is unavailable: the app is not listening; read its logs.
- Do not edit /etc/hosts, run another proxy, bypass certificate errors, edit Localify's config file, or run Localify with sudo.
Expand Down
110 changes: 109 additions & 1 deletion src/cli/mcp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,9 @@ fn call_tool(params: &Value, runner: &CliRunner) -> Result<Value> {
/// can be raised, the command that raises it stays in the text, for the
/// agent to suggest.
fn for_an_agent(text: String) -> String {
if let Some(hint) = remote_hint(&text) {
return format!("{text}\n\n{hint}");
}
if text.contains(RAISE_LIMIT) {
return format!(
"{text}\n\nRaising the limit is a purchase, so it is the user's call: suggest they run that command themselves, then try again. Do not start a checkout or pass on a checkout link."
Expand All @@ -149,10 +152,47 @@ fn for_an_agent(text: String) -> String {
)
}

/// What an agent does when another machine refused, or did not say how a
/// control ended (docs/remote-machines.md, "MCP"). The CLI prints these as
/// JSON when its output is not a terminal.
fn remote_hint(text: &str) -> Option<String> {
let cli = BRANDING.cli_command();
if text.contains(r#""code": "control_disabled""#)
|| text.contains(r#""code": "background_disabled""#)
{
return Some(format!(
"That machine decides who may control its services. Ask the user to allow remote controls on it: Settings → Remote access in Localify there, or `{cli} machines settings --control on` run there (with `--background-starts on` for starts while its app is closed)."
));
}
if text.contains(r#""outcome": "lost""#) {
return Some(
"Call service_status with the same machine to see what happened before you try again."
.to_string(),
);
}
None
}

fn prepare(tool: &Tool, args: &ToolArgs) -> Result<(Vec<String>, Option<PathBuf>)> {
// A tool without `machine` would act on this machine instead: refuse it
// before building or running anything (docs/remote-machines.md, "MCP").
if args.has("machine") && !tool.params.iter().any(|param| param.name == "machine") {
let remote: Vec<&str> = TOOLS
.iter()
.filter(|tool| tool.params.iter().any(|param| param.name == "machine"))
.map(|tool| tool.name)
.collect();
bail!(
"{} acts on this machine only and takes no machine. Only {} act on another machine.",
tool.name,
remote.join(", ")
);
}
let argv = (tool.build)(args)?;
// A tool acting on another machine has no folder of this one to read.
let here = args.string("machine")?.is_none();
let cwd = match args.string("cwd")? {
Some(cwd) if tool.uses_cwd => Some(existing_dir(&cwd)?),
Some(cwd) if tool.uses_cwd && here => Some(existing_dir(&cwd)?),
_ => None,
};
Ok((argv, cwd))
Expand Down Expand Up @@ -354,6 +394,74 @@ mod tests {
);
}

#[test]
fn a_tool_on_another_machine_ignores_cwd() {
let tool = TOOLS
.iter()
.find(|tool| tool.name == "service_logs")
.unwrap();
let here = ToolArgs::new(&json!({ "service": "web", "cwd": "relative/path" })).unwrap();
let there = ToolArgs::new(
&json!({ "service": "web", "cwd": "relative/path", "machine": "teo-mini" }),
)
.unwrap();

assert!(prepare(tool, &here).is_err());
let (argv, cwd) = prepare(tool, &there).unwrap();
assert_eq!(cwd, None);
assert_eq!(argv, ["logs", "web", "--machine=teo-mini"]);
}

#[test]
fn a_tool_without_machine_refuses_one_instead_of_acting_here() {
let local_only: Vec<&Tool> = TOOLS
.iter()
.filter(|tool| !tool.params.iter().any(|param| param.name == "machine"))
.collect();
assert!(local_only.len() > 30, "{}", local_only.len());

for tool in local_only {
let response = handle_line(
&request(
"tools/call",
json!({
"name": tool.name,
"arguments": { "machine": "B", "cwd": "/", "command": ["true"] },
}),
),
&runner(),
)
.unwrap();

let text = response["result"]["content"][0]["text"].as_str().unwrap();
assert_eq!(response["result"]["isError"], true, "{}: {text}", tool.name);
assert!(
text.starts_with(&format!("{} acts on this machine only", tool.name))
&& text.contains("service_status"),
"{}: {text}",
tool.name
);
}
}

#[test]
fn an_error_from_another_machine_reaches_the_agent_with_its_code_and_what_to_do() {
let refused = "{\n \"outcome\": \"refused\",\n \"code\": \"control_disabled\",\n \"message\": \"teo-mini doesn't allow remote controls.\"\n}";

let text = for_an_agent(refused.to_string());

assert!(text.starts_with(refused));
assert!(
text.contains("Ask the user to allow remote controls"),
"{text}"
);

let lost = "{\n \"outcome\": \"lost\",\n \"code\": \"timeout\"\n}";
assert!(
for_an_agent(lost.to_string()).contains("Call service_status with the same machine")
);
}

#[test]
fn an_unknown_method_is_an_error() {
let response = handle_line(&request("resources/list", json!({})), &runner()).unwrap();
Expand Down
Loading
Loading