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
128 changes: 57 additions & 71 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,88 +1,74 @@
# rustscript-agent

A small independent runner for agents written in RustScript (`.rss`). The runner owns only program loading, HTTP policy configuration, host binding, and the VM `Waiting` → resume driver. Provider protocol, prompt state, turn limits, tool-call handling, and final output remain in the RustScript source.
`rustscript-agent` is a standalone agent runtime with **agent policy in RustScript and authority/durability in Rust**. RSS programs own the model loop, provider adaptation, tool routing, approval policy, and compaction decisions; the Rust host owns admission, capabilities, durable state, effect commits, and transport.

## Run
## Core properties

- **Script-owned behavior:** the bundled coding loop, provider dispatch, Guardian review, and tool registry live under [`rss/`](rss/).
- **Typed host boundary:** named host shapes preserve `Unit`, `Option<T>`, and `Result<T, E>` semantics instead of inferring variants from JSON nulls.
- **Atomic admission:** each run freezes its session context, provider profile, tool registry, workspace authority, limits, prompt, deadline, and plugin graph before execution.
- **Durable lifecycle:** SQLite-backed sessions, messages, runs, events, approvals, graph pins, and effect receipts support restart repair and replay without reissuing completed work.
- **Reviewed effects:** tool calls pass through prepare, Guardian or user review, native execution, and durable commit; managed workspace mutations use private trees and explicit publication.
- **Fail-closed authority:** HTTP, filesystem, process, credential, workspace, and plugin-control capabilities are bounded and deny by default unless the native host grants them.

## Quick start

Start the gateway with the immutable bundled coding entry:

```bash
cargo run --release -- \
--script examples/http_get.rss \
--allow-host api.example.com
RUSTSCRIPT_AGENT_SOURCE=bundled:coding \
RUSTSCRIPT_AGENT_ALLOW_ANONYMOUS=1 \
cargo run --release --bin rustscript-agent-gateway
```

The HTTP host is deny-by-default. Every destination must be explicitly allowlisted (hosts **and** ports; see [Configuration](docs/configuration.md)). The runner enables the RustScript `http-client` feature and does not provide an upstream agent or model adapter.

## Library API
Anonymous mode is for local evaluation. Production deployments should configure bearer authentication, persistent state, provider credentials, and network allowlists; see [Configuration](docs/configuration.md) and [Deployment](docs/deployment.md).

```rust
use rustscript_agent::{AgentConfig, AgentRunner};
The request path is compact:

let runner = AgentRunner::from_file(
"agent.rss",
AgentConfig::for_hosts(["api.example.com"]),
)?;
let result = runner.run()?;
```text
HTTP / Telegram
-> Rust admission snapshot and durable run
-> RSS provider + agent + Guardian policy
-> Rust capability/effect boundary
-> durable messages, events, receipts, and publications
```

The current scope is intentionally synchronous at the Rust API boundary: a pending HTTP host operation is driven internally through the VM's blocking wait/resume path. A future gateway can expose the same VM lifecycle asynchronously without moving agent behavior into Rust.
## Documentation

## Hermes-compatible gateway
- [Architecture](docs/architecture.md) — RSS/native ownership, typed boundaries, lifecycle, effects, replay, and capability fences
- [HTTP API](docs/api.md) — implemented route families and lifecycle semantics
- [Configuration](docs/configuration.md) — canonical environment, embedding, capability, and provider settings
- [Deployment](docs/deployment.md) — source builds, state, operations, shutdown, backup, systemd, and containers
- [Development](docs/development.md) — repository layout, focused tests, CI, RSS corpus, and fixture conventions
- [Status](docs/status.md) — detailed capability and maturity matrix, including explicit exclusions

The gateway is part of this independent repository. It uses the RustScript `pd-vm` crate for RSS execution and does not depend on the `pd-edge` gateway runtime.
## Build and test

The repository uses Rust 1.99 in CI and pins RustScript Core at `11c9ee908a29365bd02573311f56e9308eb7dbe6`.

```bash
RUSTSCRIPT_AGENT_SOURCE=bundled:coding \
RUSTSCRIPT_AGENT_ALLOW_HOSTS=api.example.com \
RUSTSCRIPT_AGENT_ALLOW_PORTS=443 \
RUSTSCRIPT_AGENT_BEARER_TOKEN='<secret>' \
RUSTSCRIPT_AGENT_STATE_DB=/var/lib/rustscript-agent/state.db \
cargo run --release --bin rustscript-agent-gateway
cargo +1.99.1 build --locked
cargo +1.99.1 test --locked --all-features --test docs_contract_tests
cargo +1.99.1 test --locked --all-features --all-targets
cargo +1.99.1 fmt --all -- --check
```

For focused local coding-agent coverage:

```bash
cargo test --test coding_agent_e2e_tests
cargo test --test coding_agent_edge_e2e_tests
```

A present `config.yaml` `agent.source` is the authoritative agent source; a
present-but-invalid config source fails closed with no environment fallback.
Only when the config is missing does the gateway fall back to
`RUSTSCRIPT_AGENT_SOURCE`, then the deprecated `RUSTSCRIPT_AGENT_SCRIPT`, then
the bundled coding entry. A valid source is `bundled:coding`, or `file:` plus
an absolute path. Full environment-variable reference:
[docs/configuration.md](docs/configuration.md).
Deployment, systemd/container examples, shutdown and backup: [docs/deployment.md](docs/deployment.md).

## Status

This repository is **not v1-complete**. The table describes code in this
source checkout; it does not claim a published release, live-provider
availability, or final composed-candidate acceptance. Blocked or excluded
items are explicit, and no placeholder route is advertised.

| Area | Status |
| --- | --- |
| Single-run runner (`rustscript-agent --script … --allow-host …`) | Implemented |
| Gateway HTTP API: sessions, runs, SSE events, stop, jobs CRUD, subagent interrupt | Implemented (see [plans/2026-07-30_rustscript-agent-gateway-api.md](plans/2026-07-30_rustscript-agent-gateway-api.md)) |
| Durable SQLite state: sessions/messages/runs/events/jobs/approvals/compactions, restart recovery | Implemented |
| Gateway entry selection | A present `config.yaml` `agent.source` is authoritative; a missing config falls back to `RUSTSCRIPT_AGENT_SOURCE`, then the deprecated `RUSTSCRIPT_AGENT_SCRIPT`, then bundled `bundled:coding`. |
| Legacy chat completion path (`/api/sessions/{id}/chat`) | Legacy-constructor-only; production gateway selection via `RUSTSCRIPT_AGENT_SOURCE`, legacy `RUSTSCRIPT_AGENT_SCRIPT`, or bundled `bundled:coding` returns `501 agent_source_not_configured`. Normal coded-agent runs use `POST /v1/runs`. |
| OpenAI Chat Completions (`openai`, `openai_chat`, or default) | Current source has buffered and streaming requests through the opaque native credential transport; this is source status, not live-provider validation. |
| Codex Responses (`openai-codex` / `codex-responses`) | Access-only source path is present. Full refresh/lifecycle support is not claimed here. |
| Generic custom Responses adapter (explicit adapter selection) | Not implemented; returns typed `not_implemented` and sends no request. |
| Anthropic Messages | Not implemented; remains a typed `not_implemented` stub. |
| API hardening (A7): bounded per-peer-IP/per-account rate limiting, client-disconnect policy | Implemented (disabled by default; see [docs/configuration.md](docs/configuration.md)) |
| Observability (A9): bounded metrics registry, `GET /metrics`, structured terminal tracing | Implemented (see [docs/deployment.md](docs/deployment.md)) |
| RSS coding loop + durable compaction policies (A5) | The gateway's bundled coding entry runs through the agent worker; compaction policies remain implemented and tested (`rss/agent/compact.rss`). |
| RSS coding tools + workspace-confined loop | Implemented for the library worker: `read_file`, `search_files`, `write_file`, `patch`, `terminal`, `process` run serially through `rss/tools/dispatch.rss`. Local E2E: `cargo test --test coding_agent_e2e_tests` and `cargo test --test coding_agent_edge_e2e_tests`. See [docs/configuration.md](docs/configuration.md). Parallel tools remain excluded (A6). |
| Approval execution chain (A4) | Implemented for tool dispatch: durable approval records, `ask` policy for write/process, HTTP and Telegram approve/reject, one typed terminal result. A general-purpose harness layer beyond tool approval remains excluded. |
| Parallel tools and subagents (A6) | Not implemented (excluded from the current milestone scope) |
| Scheduled / durable job execution | **Not implemented (explicitly excluded)**. Job CRUD, pause/resume, and latest-output routes exist, but there is no scheduler; `POST /api/jobs/{id}/run` is intentionally absent and answers `404`. |
| Telegram gateway (A8) | **Implemented**: native Bot API transport (https/rustls), deny-by-default account/chat/user allowlists, durable delivery cursors (at-least-once), bounded 429/5xx/401 retries, fail-closed first-boot drain, bounded shutdown drain. See [docs/deployment.md](docs/deployment.md). |

The bounded `config.yaml` / `auth.yaml` loaders and production
`config::load_snapshot` bridge exist. Package-level end-to-end config/auth/provider
acceptance, final composed-candidate acceptance, and remote delivery remain
open.

Current lifecycle/reliability behavior is covered by the integration
suites in `tests/` (admission, bounded delivery, terminal-commit retries,
restart recovery, storage stalls, coding-agent E2E). CI runs them with
`cargo test --locked --all-features --all-targets`. The main coding
workflow E2E is `cargo test --test coding_agent_e2e_tests`. Cancellation
and output-limit edges are `cargo test --test coding_agent_edge_e2e_tests`.
## Current maturity

The gateway, durable run lifecycle, serial coding tools, approvals, managed effects, plugin graph pinning, and Telegram transport are implemented in the current source tree. The project remains pre-v1: provider coverage is uneven, scheduled execution and parallel tools/subagents are excluded, and final remote-provider acceptance remains open. See the [status matrix](docs/status.md).

## Related projects

- [RustScript Core](https://github.com/rustscript-lang/rustscript) — language, compiler, VM, and host SDK
- [RustScript specification](https://github.com/rustscript-lang/spec) — language specification
- [pd-edge](https://github.com/rustscript-lang/pd-edge) — RustScript edge runtime and ABI
- [pd-controller](https://github.com/rustscript-lang/pd-controller) — control plane for RustScript edge deployments
- [RustScript Playground](https://github.com/rustscript-lang/playground) — browser playground
- [RustScript website and documentation](https://github.com/rustscript-lang/website)
86 changes: 86 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# HTTP API

The production router is defined in [`src/gateway/api_server.rs`](../src/gateway/api_server.rs). This reference lists only routes registered there; request and response details remain governed by the typed handlers and tests.

## Common behavior

- The configured request-body limit applies to the complete router.
- When bearer authentication is configured, send `Authorization: Bearer ***` on every route. Optional rate limiting runs first per peer IP and then per verified account.
- Anonymous mode can expose ordinary routes, but managed-workspace maintenance, run-effect queries, and plugin control still require configured authentication. Plugin control additionally requires trusted host-side control configuration.
- Handler-generated errors use `{"error":{"code":"...","message":"..."}}`, with route-specific status codes. Framework rejections, including JSON extractor failures and router-wide body-limit rejections, may use Axum's native response format until they are normalized.
- Mutating session/job handlers and run admission commit durable state before publishing it in memory.

See [Configuration](configuration.md) for authentication, body, rate, and lifecycle bounds.

## Health and discovery

| Method | Path | Semantics |
| --- | --- | --- |
| `GET` | `/health/detailed` | Liveness plus active-run and pending-terminal gauges; includes bounded source metadata when available. |
| `GET` | `/metrics` | Prometheus text from the bounded in-memory registry; no storage query. |
| `GET` | `/v1/models` | Returns the configured model/provider identity. |

## Sessions

| Method | Path | Semantics |
| --- | --- | --- |
| `GET`, `POST` | `/api/sessions` | List or create sessions. Listing supports bounded pagination and source/search filters. |
| `GET`, `PATCH`, `DELETE` | `/api/sessions/{session_id}` | Read, update title/end reason, or delete a session. |
| `GET` | `/api/sessions/{session_id}/messages` | Return the session's canonical message history. |
| `POST` | `/v1/sessions/{session_id}/workspace` | Bind a validated workspace; rejected while the session has an active run. |
| `POST` | `/v1/sessions/{session_id}/compact` | Run the durable compaction lifecycle for the session. |
| `POST` | `/api/sessions/{session_id}/chat` | Legacy synchronous chat path. Source-selected production gateway constructors leave it unconfigured and return `501 agent_source_not_configured`; normal coded-agent execution uses `POST /v1/runs`. |

## Runs, events, effects, and approvals

| Method | Path | Semantics |
| --- | --- | --- |
| `POST` | `/v1/runs` | Atomically admit a run and return `202`. Optional `Idempotency-Key` replay returns the original run; reuse with different canonical input returns a conflict. |
| `GET` | `/v1/runs/{run_id}/events` | SSE replay followed by live events. `after_seq` resumes after a cursor; a cursor older than retained history returns `409 event_cursor_too_old`. |
| `POST` | `/v1/runs/{run_id}/stop` | Request cooperative cancellation. The durable run stays `running` until one terminal transition commits. |
| `GET` | `/v1/runs/{run_id}/effects` | Authenticated, read-only, cursor-paginated managed-effect summaries. It accepts `after_effect_id` and a bounded `limit`. |
| `GET` | `/v1/runs/{run_id}/approvals` | List pending approvals for an active run; requires bearer authentication. |
| `POST` | `/v1/runs/{run_id}/approvals/{approval_id}` | Resolve one pending approval with `{"decision":"approved"}` or `{"decision":"denied"}`. Resolution is owner-bound and one-time. |

Run admission freezes provider/tool/workspace/graph state before returning. A fresh admission starts one worker; an idempotent replay does not start another. Events and messages are durable before SSE broadcast. Delivery is at-least-once, so clients should deduplicate by durable event identity and resume by sequence.

## Managed workspaces

These routes require persistent managed-workspace configuration and authenticated native authority. The path workspace ID must equal the typed body workspace ID.

| Method | Path | Semantics |
| --- | --- | --- |
| `POST` | `/v1/workspaces/{workspace_id}/checkpoints` | Freeze a checkpoint; returns `201`, or `202` when submission succeeded but the final receipt is unknown. |
| `POST` | `/v1/workspaces/{workspace_id}/restore` | Restore a checkpoint and atomically admit a new run; returns `202` and starts the restored worker. |
| `POST` | `/v1/workspaces/{workspace_id}/branches` | Create a branch from authorized managed state; returns `201`. |
| `POST` | `/v1/workspaces/{workspace_id}/publish` | Publish a managed branch; returns `200`, or `202` for a submitted-unknown outcome. |

The typed request/receipt families and failure mapping are implemented in [`src/gateway/workspaces.rs`](../src/gateway/workspaces.rs).

## Plugin graphs

Plugin routes require a verified bearer plus trusted host-side `InstallAuthorization`; request JSON cannot supply install authority.

| Method | Path | Semantics |
| --- | --- | --- |
| `POST` | `/v1/plugins/install` | Validate and install an immutable plugin package capture. |
| `POST` | `/v1/plugin-graphs/resolve` | Resolve installed packages into a closed graph lock. |
| `POST` | `/v1/plugin-graphs/{graph_id}/prepare` | Compile and validate the stored graph without activating it. |
| `GET` | `/v1/plugin-graphs/{graph_id}` | Read the stored graph/control view. |
| `POST` | `/v1/plugin-activations` | Activate a prepared graph through the generationed control store. |
| `POST` | `/v1/plugin-activations/{activation_id}/rollback` | Roll back through activation history with conflict checks. |

Handlers and authorization are in [`src/gateway/plugins.rs`](../src/gateway/plugins.rs); durable locks, refs, activation generations, history, retention, and revocation are in [`src/plugins/control_store.rs`](../src/plugins/control_store.rs).

## Jobs and subagent compatibility

| Method | Path | Semantics |
| --- | --- | --- |
| `GET`, `POST` | `/api/jobs` | List or create durable job records. |
| `GET`, `PATCH`, `DELETE` | `/api/jobs/{job_id}` | Read, update, or delete a job record. |
| `GET` | `/api/jobs/{job_id}/output/latest` | Return the stored latest output, if any. |
| `POST` | `/api/jobs/{job_id}/pause` | Set the job record disabled. |
| `POST` | `/api/jobs/{job_id}/resume` | Set the job record enabled. |
| `POST` | `/api/subagents/{subagent_id}/interrupt` | Route an interrupt to the run handle with that ID. |

Job CRUD does not schedule or execute jobs. There is no `/api/jobs/{job_id}/run` route. Parallel tool dispatch and subagent fan-out are not implemented; see [Status](status.md).
Loading
Loading