Skip to content
Open
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
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,9 @@ cd playit-agent
# Build and run the release version
cargo run --release
```

## Local programmatic API

The background daemon provides a local JSON-over-IPC API for automation, dashboards, and MCP integrations. It supports tunnel status, tunnel creation/deletion, account state, and browser-based agent claiming without exposing the agent secret to the caller.

See [docs/ipc-api.md](docs/ipc-api.md) for the wire format, operations, and security boundary.
80 changes: 80 additions & 0 deletions docs/ipc-api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# Local JSON IPC API

`playitd` exposes a local, line-delimited JSON API over its existing IPC transport. It uses a Unix socket on Linux/macOS and a restricted Windows Named Pipe. The default endpoint is the same one used by `playit attach` and `playit status`.

The first server frame is a `hello` envelope. Each request is one JSON object terminated by a newline:

```json
{
"ipc_version": 2,
"request_id": 1,
"request": { "type": "get_tunnels" }
}
```

Responses use the matching `request_id`:

```json
{
"message_kind": "response",
"data": {
"ipc_version": 2,
"request_id": 1,
"response": {
"type": "tunnels",
"data": { "tunnels": [], "pending_tunnels": [] }
}
}
}
```

## Operations

`get_status` returns daemon health and socket metadata. `get_state` returns the lifecycle and the current agent snapshot.

`get_tunnels` returns the current tunnel and pending-tunnel list:

```json
{"ipc_version":2,"request_id":2,"request":{"type":"get_tunnels"}}
```

`create_tunnel` creates a one-port tunnel assigned to the running agent. `protocol` accepts `tcp`, `udp`, or `both`; `local_address` defaults to `127.0.0.1`:

```json
{
"ipc_version": 2,
"request_id": 3,
"request": {
"type": "create_tunnel",
"local_port": 25565,
"protocol": "tcp",
"local_address": "127.0.0.1",
"name": "minecraft"
}
}
```

The response contains the cloud tunnel UUID. The daemon refreshes its local state automatically.

`delete_tunnel` removes a tunnel by UUID:

```json
{
"ipc_version": 2,
"request_id": 4,
"request": {
"type": "delete_tunnel",
"tunnel_id": "00000000-0000-0000-0000-000000000000"
}
}
```

`get_account` returns account status, agent ID, guest login link, and any active claim URL. For an unconfigured daemon, call `start_claim`; it returns a claim URL and automatically provisions the secret after the browser approval:

```json
{"ipc_version":2,"request_id":5,"request":{"type":"start_claim"}}
```

## Security

This API intentionally binds only to local IPC. Unix socket permissions and the Windows restricted Named Pipe ACL are the access control boundary. Any process that can access the endpoint can manage that agent's tunnels and account setup, so the socket must not be forwarded or exposed as a network listener.
3 changes: 3 additions & 0 deletions packages/agent_core/src/agent_control/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ impl<F: serde::Serialize> From<ApiError<F, HttpClientError>> for SetupError {
impl From<ApiErrorNoFail<HttpClientError>> for SetupError {
fn from(value: ApiErrorNoFail<HttpClientError>) -> Self {
match value {
ApiErrorNoFail::UnexpectedFail => {
SetupError::ApiFail("unexpected API fail response".to_string())
}
ApiErrorNoFail::ApiError(api) => SetupError::ApiError(api),
ApiErrorNoFail::ClientError(error) => SetupError::RequestError(error),
}
Expand Down
1 change: 0 additions & 1 deletion packages/agent_proto/src/control_messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1283,5 +1283,4 @@ mod test {
let err = ControlRequest::read_from(&mut &buffer[..]).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
}

}
7 changes: 4 additions & 3 deletions packages/api_client/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ impl<C: PlayitHttpClient> PlayitApiClient<C> {
fn unwrap_no_fail<S>(res: Result<ApiResult<S, ()>, C::Error>) -> Result<S, ApiErrorNoFail<C::Error>> {
match res {
Ok(ApiResult::Success(v)) => Ok(v),
Ok(ApiResult::Fail(_)) => panic!(),
Ok(ApiResult::Fail(_)) => Err(ApiErrorNoFail::UnexpectedFail),
Ok(ApiResult::Error(error)) => Err(ApiErrorNoFail::ApiError(error)),
Err(error) => Err(ApiErrorNoFail::ClientError(error)),
}
Expand Down Expand Up @@ -356,8 +356,9 @@ impl<F: std::fmt::Debug, C: std::fmt::Debug> std::error::Error for ApiError<F, C

#[derive(Debug, serde::Serialize)]
pub enum ApiErrorNoFail<C> {
ApiError(ApiResponseError),
ClientError(C),
UnexpectedFail,
ApiError(ApiResponseError),
ClientError(C),
}

impl<C: std::fmt::Debug> std::fmt::Display for ApiErrorNoFail<C> {
Expand Down
104 changes: 79 additions & 25 deletions packages/api_client/src/http_client.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::panic::Location;
use std::time::Duration;

use reqwest::StatusCode;
use serde::Serialize;
Expand All @@ -13,6 +14,9 @@ pub struct HttpClient {
client: reqwest::Client,
}

const MAX_REQUEST_ATTEMPTS: usize = 3;
const RETRY_DELAY: Duration = Duration::from_millis(250);

impl Clone for HttpClient {
fn clone(&self) -> Self {
Self {
Expand Down Expand Up @@ -54,34 +58,69 @@ impl PlayitHttpClient for HttpClient {
path: &str,
req: Req,
) -> Result<ApiResult<Res, Err>, Self::Error> {
let mut builder = self.client.post(format!("{}{}", self.api_base, path));

{
let lock = self.auth_header.read().await;

if let Some(auth_header) = &*lock {
builder = builder.header(reqwest::header::AUTHORIZATION, auth_header);
}
}

let body = serde_json::to_value(req).map_err(HttpClientError::SerializeError)?;
let res = async move {
builder = builder.json(&req);
let request = builder.build()?;

let response = self.client.execute(request).await?;

let response_status = response.status();
if response_status == StatusCode::TOO_MANY_REQUESTS {
return Err(HttpClientError::TooManyRequests);
for attempt in 0..MAX_REQUEST_ATTEMPTS {
let mut builder = self.client.post(format!("{}{}", self.api_base, path));

{
let lock = self.auth_header.read().await;

if let Some(auth_header) = &*lock {
builder = builder.header(reqwest::header::AUTHORIZATION, auth_header);
}
}

let request = builder.json(&body).build()?;
let response = match self.client.execute(request).await {
Ok(response) => response,
Err(error)
if attempt + 1 < MAX_REQUEST_ATTEMPTS
&& (error.is_connect() || error.is_timeout()) =>
{
tracing::debug!(
attempt = attempt + 1,
max_attempts = MAX_REQUEST_ATTEMPTS,
?error,
"retrying transient API request failure"
);
tokio::time::sleep(RETRY_DELAY * (attempt as u32 + 1)).await;
continue;
}
Err(error) => return Err(HttpClientError::RequestError(error)),
};

let response_status = response.status();
let response_txt = response.text().await?;

if (response_status == StatusCode::TOO_MANY_REQUESTS
|| response_status.is_server_error())
&& attempt + 1 < MAX_REQUEST_ATTEMPTS
{
tracing::debug!(
attempt = attempt + 1,
max_attempts = MAX_REQUEST_ATTEMPTS,
status = %response_status,
"retrying transient API response"
);
tokio::time::sleep(RETRY_DELAY * (attempt as u32 + 1)).await;
continue;
}

if response_status == StatusCode::TOO_MANY_REQUESTS {
return Err(HttpClientError::TooManyRequests);
}

let result: ApiResult<Res, Err> =
serde_json::from_str(&response_txt).map_err(|e| {
tracing::error!("failed to parse json:\n{}", response_txt);
HttpClientError::ParseError(e, response_status, response_txt)
})?;

return Ok(result);
}

let response_txt = response.text().await?;
let result: ApiResult<Res, Err> = serde_json::from_str(&response_txt).map_err(|e| {
tracing::error!("failed to parse json:\n{}", response_txt);
HttpClientError::ParseError(e, response_status, response_txt.to_string())
})?;

Ok::<_, Self::Error>(result)
unreachable!("request loop always returns after the final attempt")
}
.await;

Expand All @@ -101,6 +140,21 @@ pub enum HttpClientError {
TooManyRequests,
}

impl std::fmt::Display for HttpClientError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::SerializeError(error) => write!(f, "failed to serialize API request: {error}"),
Self::ParseError(error, status, _) => {
write!(f, "failed to parse API response ({status}): {error}")
}
Self::RequestError(error) => write!(f, "API request failed: {error}"),
Self::TooManyRequests => write!(f, "API rate limit exceeded"),
}
}
}

impl std::error::Error for HttpClientError {}

impl From<reqwest::Error> for HttpClientError {
fn from(value: reqwest::Error) -> Self {
HttpClientError::RequestError(value)
Expand Down
3 changes: 3 additions & 0 deletions packages/playit-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,9 @@ impl<F: serde::Serialize> From<ApiError<F, HttpClientError>> for CliError {
impl From<ApiErrorNoFail<HttpClientError>> for CliError {
fn from(e: ApiErrorNoFail<HttpClientError>) -> Self {
match e {
ApiErrorNoFail::UnexpectedFail => {
CliError::ApiFail("unexpected API fail response".to_string())
}
ApiErrorNoFail::ApiError(e) => CliError::ApiError(e),
ApiErrorNoFail::ClientError(e) => CliError::RequestError(e),
}
Expand Down
Loading