A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
document prime agent core features (#493)
kte205edf55c66
diff --git a/README.md b/README.mdindex 0201eb4aba..1e8da17052 100644--- a/README.md+++ b/README.md@@ -27,22 +27,18 @@ Prime Agent: RLM-native Coding and Research Harness</a></p>-## Overview+Prime Agent is a coding and research agent built for long-running tasks.-Prime Agent is an RLM-native coding and research harness.+Most agents are optimized for short, single-threaded sessions. As tasks grow, logs and tool output lead to context rot, compaction drops useful details, and one model becomes the bottleneck. Their skills are simply markdown instructions, and sessions require a client to remain open.-The model-facing runtime is centered on a persistent IPython kernel with recursive subagents exposed through a small `rlm` API. The TypeScript host owns model calls, tools, sessions, scheduling, and child-agent execution while Python provides a durable control environment for composing that functionality.+Prime Agent combines a [Recursive Language Model (RLM)](https://www.primeintellect.ai/blog/rlm) runtime with durable background processes:-Prime Agent is designed for workflows where the model should work inside a durable Python state, compose tools through code, and delegate independent subtasks to child agents without leaving the same harness.--What sets it apart:--1. Persistent IPython execution as the primary model tool.-2. Recursive child agents through `await rlm("subtask")` and normal Python async patterns.-3. Live terminal UI for messages, IPython cells, session history, and child-agent state.-4. Shared provider and auth stack for API-key providers, subscription providers, custom models, and OAuth flows.-5. Python skill surface for Prime workflows such as environments, evals, training, and analysis.-6. JSONL session storage with branching, resume, fork, clone, export, and compaction support.+- **Everything is programmatic:** persistent IPython is the only built-in model tool; file operations, shell commands, tool use, and context management happen through code.+- **Subagents are built in:** `rlm(...)` spawns real child agents from Python for parallel or background work and returns their results programmatically.+- **Skills are executable:** skills are importable Python packages, and the built-in skill creator can turn recurring workflows into project or personal skills.+- **Sessions run in the background:** daemon-backed agents keep running when the terminal disconnects and can be reattached later.+- **Agents communicate directly:** running agents can exchange messages and orchestrate one another without routing everything through the user.+- **Long tasks keep moving:** automatic compaction, persistent goals, heartbeats, cron schedules, autonomous mode, and retained subagents preserve progress across turns and terminal sessions.## Getting Started@@ -66,25 +62,11 @@ Then start Prime Agent:prime-agent```-Alternatively, to test local changes, clone this repository and use the source runner:--```bash-npm ci-./prime-agent.sh-```--Authenticate in the TUI with:--```text-/login-```-Public releases are currently installed from versioned release artifacts through these installer scripts. The repository still contains inherited npm workspace identifiers for source compatibility; they are not the user-facing Prime Agent install path.-## Common Commands+Other useful commands:```bash-prime-agent # Start a new sessionprime-agent agents # Open the agents viewprime-agent --resume [path|id] # Browse or resume a previous sessionprime-agent doctor [--fix] # Inspect or repair background services@@ -92,14 +74,20 @@ prime-agent update [--force] # Update Prime Agentprime-agent shutdown [--force] # Stop every agent, worker, and background service```+## Built for Long-Running Work++- **Direct agent-to-agent communication:** running agents and retained subagents can discover one another, exchange messages, steer active work, or queue follow-ups.+- **Daemon-backed continuity:** active sessions, IPython state, schedules, and subagents keep running when the terminal detaches and can be reattached later.+- **Heartbeats and schedules:** `/heartbeat`, `rlm_heartbeat`, and `prime-agent schedule` can re-enter a session periodically or at a specific time.+- **Persistent goals:** `/goal` keeps an objective and its progress active across turns until it is completed, paused, or cleared.+- **Bounded autonomous mode:** `/autonomous` continues working until its quality gates pass or a configured turn, token, or time limit is reached.+## Documentation- [Documentation index](packages/coding-agent/docs/index.md)- [Quickstart](packages/coding-agent/docs/quickstart.md)+- [RLM programming model](packages/coding-agent/docs/rlm.md)+- [Long-running and background agents](packages/coding-agent/docs/long-running-agents.md)- [Usage and CLI reference](packages/coding-agent/docs/usage.md)- [Provider setup](packages/coding-agent/docs/providers.md)- [Development](packages/coding-agent/docs/development.md)--## Upstream and License--Prime Agent is licensed under the MIT License. The root [LICENSE](LICENSE) preserves attribution for pi-mono by Mario Zechner and identifies Prime Intellect's subsequent work.diff --git a/packages/coding-agent/docs/index.md b/packages/coding-agent/docs/index.mdindex 50bca1f465..3d8cb62f32 100644--- a/packages/coding-agent/docs/index.md+++ b/packages/coding-agent/docs/index.md@@ -25,6 +25,8 @@ Public releases are currently installed from versioned release artifacts. The in- [Quickstart](quickstart.md) - install, authenticate, and run a first session.- [Using Prime Agent](usage.md) - interactive mode, RLM subagents, slash commands, context files, and CLI reference.+- [RLM programming model](rlm.md) - programmatic execution, native subagents, Python skills, and durable state.+- [Long-running and background agents](long-running-agents.md) - daemon workers, messaging, heartbeats, goals, schedules, and autonomous mode.- [Providers](providers.md) - subscription and API-key setup for built-in providers.- [Settings](settings.md) - global and project settings.- [Keybindings](keybindings.md) - default shortcuts and custom keybindings.@@ -34,7 +36,7 @@ Public releases are currently installed from versioned release artifacts. The in## Customization- [Extensions](extensions.md) - TypeScript modules for tools, commands, events, and custom UI.-- [Skills](skills.md) - Agent Skills and Python packages exposed in the persistent kernel.+- [Skills](skills.md) - markdown and Python-backed skills, including how to ask Prime Agent to create them.- [MCP integrations](mcp-integrations.md) - use MCP servers through Python skills without expanding the model's tool surface.- [Prompt templates](prompt-templates.md) - reusable prompts that expand from slash commands.- [Themes](themes.md) - built-in and custom terminal themes.diff --git a/packages/coding-agent/docs/long-running-agents.md b/packages/coding-agent/docs/long-running-agents.mdnew file mode 100644index 0000000000..dbeb375cff--- /dev/null+++ b/packages/coding-agent/docs/long-running-agents.md@@ -0,0 +1,196 @@+# Long-Running and Background Agents++Prime Agent combines daemon-backed session workers with persistent state, scheduled prompts, direct agent messaging, goals, and bounded autonomous continuations. These features serve different purposes but share the same session and worker runtime.++## Daemon-Backed Sessions++Normal interactive sessions run in resident worker processes managed by a local supervisor. The worker owns the root session, its IPython kernel, scheduled jobs, and RLM descendants.++Closing the terminal UI detaches the client; it does not stop the worker. List and reconnect to active agents with:++```bash+prime-agent list+prime-agent attach <agent>+```++Other lifecycle commands are:++```bash+prime-agent agents # Open the agents view+prime-agent rename <agent> <name> # Give an agent a stable readable name+prime-agent stop <agent> # Stop one agent+prime-agent status # Inspect background services+prime-agent doctor [--fix] # Diagnose or repair service state+prime-agent shutdown [--force] # Stop all agents and services+```++Workers persist transcripts as JSONL and store feature-specific state under the session artifact directory. A worker or supervisor restart can recover session state and schedules and rehydrate retained completed RLM children without treating a terminal client as the owner of the work.++Daemon workers are process-isolated for lifecycle and failure containment, not security-sandboxed. They normally run with the same operating-system permissions as the client.++## Agent-to-Agent Communication++The daemon routes direct messages between active sessions and retained daemon-backed subagents. From a shell:++```bash+prime-agent send <agent> "Please verify the latest migration"+```++From the IPython kernel, use the preloaded `agent_message` Python skill:++```python+roster = await agent_message.list_agents()+receipt = await agent_message.send(+ "api-reviewer",+ "Recheck the endpoint after the latest edit",+ mode="auto",+)+print(receipt["deliveryStatus"])+```++For the current parent's direct RLM children, prefer the parent-scoped registry:++```python+children = await rlm.list_subagents()+child = next(item for item in children if item.session_name == "api-reviewer")+await agent_message.send(child.session_name, "Continue with the updated diff")+```++Delivery modes are:++- `auto`: steer a busy target and deliver immediately to an idle target;+- `steer`: intentionally inject the message into active work; and+- `follow_up`: wait until the target's current work finishes.++A receipt is `delivered` when it reached an idle target's context or `queued` when accepted for later delivery. Messaging is direct only; broadcasts are not supported. The daemon derives sender identity and enforces message-size, rate, and pending-queue limits.++## Heartbeats and Scheduled Prompts++Prime Agent has three related scheduling surfaces:++| Surface | Owner | Purpose |+|---|---|---|+| `/heartbeat` | User | One visible recurring instruction for the current session. |+| `rlm_heartbeat` | Agent | Multiple programmatically managed recurring instructions internal to the current session. |+| `prime-agent schedule` | User or automation | General one-time or cron prompts targeted at an agent. |++### User heartbeat++Create and manage the current session's visible heartbeat:++```text+/heartbeat every 10m Check the deployment and report meaningful changes+/heartbeat status+/heartbeat pause+/heartbeat resume+/heartbeat clear+```++Heartbeat delivery defaults to steering active work. Add `--follow-up` when the recurring prompt should wait until the current turn finishes. Use `/heartbeats` to inspect and manage both user and agent-created heartbeats.++### Agent-created RLM heartbeats++An agent can create several internal heartbeats programmatically:++```python+first = await rlm_heartbeat.create(+ "check whether the test run finished",+ interval="5m",+ label="tests",+)+second = await rlm_heartbeat.create(+ "inspect the deployment status",+ interval="10m",+ label="deploy",+ delivery_mode="follow_up",+)++await rlm_heartbeat.list()+await rlm_heartbeat.update(first["heartbeat"]["id"], status="pause")+```++RLM heartbeats are distinct from the user's `/heartbeat`; the Python skill cannot replace or clear the user-owned heartbeat.++### General schedules++Schedule a one-time or recurring prompt for an addressable agent:++```bash+prime-agent schedule add worker "in 30m" -- "Check the benchmark result"+prime-agent schedule add worker "0 9 * * 1-5" -- "Review open work"+prime-agent schedule list --all+prime-agent schedule cancel <job-id>+```++Scheduled jobs are persisted per session and continue while the UI is detached. Due ticks are claimed before delivery so a crash does not replay an uncertain prompt, and missed ticks are coalesced rather than accumulated into an unbounded backlog.++## Persistent Goals++A goal is a durable objective that the harness continues to present across turns until it is complete, paused, budget-limited, errored, or cleared. Start one explicitly from the TUI:++```text+/goal Ship the release and verify every published artifact+/goal --budget 200000 Complete the repository migration+```++Manage its state with:++```text+/goal status+/goal pause+/goal resume+/goal clear+```++The model uses the kernel-side `goal` skill to inspect or finish the objective:++```python+state = await goal.get()+await goal.complete()+```++Goal state records token usage, elapsed time, continuation count, and an optional explicit token budget. The harness keeps prompting an active goal after ordinary assistant turns; only `goal.complete()` marks successful completion. Creating a persistent goal is an explicit user or host action, not something the agent should infer from every task.++## Autonomous Mode++Autonomous mode is a bounded host policy for runs where no human input is expected. Prime Agent adds follow-up continuations until configured quality gates pass or a continuation, turn, token, or wall-clock limit is reached.++Enable it in an interactive session:++```text+/autonomous on+/autonomous status+/autonomous off+```++Or configure a run from the CLI:++```bash+prime-agent \+ --autonomous \+ --autonomous-gate "npm run check" \+ --autonomous-max-turns 20 \+ "Implement and verify the requested change"+```++Autonomous mode supports limits for continuations, assistant turns, tokens, and wall-clock duration. Gate commands run before the session may finish; a failed gate returns its bounded output to the agent for another attempt. Prime Agent avoids rerunning the same failed gate when the workspace has not changed.++Goals and autonomous mode are complementary but different:++- a **goal** stores the objective and its progress state across turns;+- **autonomous mode** decides whether to inject another continuation based on evidence, gates, and limits.++## Compaction and Continuity++Automatic compaction handles context growth during long tasks. On overflow or near the configured threshold, Prime Agent summarizes older messages, retains recent context, and continues. The IPython kernel persists through compaction, so variables, imports, helper functions, and task state remain available.++The agent can inspect or request compaction programmatically:++```python+await compact.status()+await compact.run("Preserve the failing tests and remaining migration steps")+```++Compaction is not a completion signal. It does not stop goals, autonomous continuations, heartbeats, or existing child sessions; later parent turns continue from the compacted context.++For lower-level process and recovery behavior, see [Daemon and Session Worker Architecture](daemon-implementation-summary.md). For recursive child lifecycle details, see [RLM Programming Model](rlm.md) and [Kernel and RLM Recursion](kernel-and-rlm-recursion.md).diff --git a/packages/coding-agent/docs/rlm.md b/packages/coding-agent/docs/rlm.mdnew file mode 100644index 0000000000..21fc29fc39--- /dev/null+++ b/packages/coding-agent/docs/rlm.md@@ -0,0 +1,116 @@+# RLM Programming Model++Prime Agent is built around a recursive language model (RLM) runtime: the model works inside a persistent Python control environment and composes capabilities as code. Provider calls, session persistence, child lifecycles, scheduling, and safety policy remain in the TypeScript host; IPython is the model-facing programming surface.++## Core Invariants++### 1. Execution is programmatic++The default RLM runtime exposes one built-in model tool: `ipython`. Reading and editing files, running project commands, transforming results, invoking skills, and delegating work all begin from that persistent kernel instead of separate built-in tool calls.++Python state survives across tool calls and compaction. Variables, imports, functions, parsed results, and task handles remain available on later turns:++```python+from pathlib import Path++config_files = list(Path(".").rglob("*.toml"))+large_files = [path for path in config_files if path.stat().st_size > 10_000]+```++Run a project's normal commands through its own environment from an IPython cell:++```bash+%%bash+npm run check+```++Each `%%bash` cell is a temporary subshell, while Python state and `%cd` changes persist in the kernel. Prime Agent extensions may intentionally add custom tools, but the built-in RLM design does not require a separate model tool for every capability.++### 2. Subagents are native RLM calls++The callable `rlm` object is preloaded in the kernel. A child is created by calling it like any other async Python function:++```python+result = await rlm("Review the authentication flow for security issues")+print(result.answer)+```++The TypeScript host creates a normal child `AgentSession` with an independent context and session directory. The child inherits the parent model, provider configuration, skills, tools, retry policy, and resource loader unless the call requests another configured model.++Normal Python async patterns provide concurrency:++```python+import asyncio++background = asyncio.create_task(+ rlm("Run the slow integration audit", name="integration-audit")+)++api_review, test_review = await asyncio.gather(+ rlm("Review the public API"),+ rlm("Review the test coverage"),+)++integration_review = await background+```++Use direct `await rlm(...)` when the result is needed immediately, `asyncio.gather(...)` for independent fan-out, and `asyncio.create_task(...)` when the parent can continue useful work before collecting the result.++#### Child results and lifecycle++An `RLMResult` includes the final answer, the child's token usage, assistant-turn count, selected model, session directory, and any model-fallback warning. Child usage is attributed to the parent session while remaining distinguishable in context-tree reporting.++The parent-scoped child registry survives compaction, kernel restart, and parent restoration:++```python+children = await rlm.list_subagents()+for child in children:+ print(child.session_name, child.status, child.active_session_id)+```++Successfully completed daemon-backed children remain addressable while their parent session is open. Delete a child only when its context is no longer needed:++```python+await rlm.delete_subagent(children[0])+```++The default recursion depth allows a root agent to create children. Raising the configured depth allows descendants to recurse further.++### 3. Skills add programmatic capability++Prime Agent supports the Agent Skills markdown format and extends it with Python-backed skills. Both use `SKILL.md` for discovery, routing, and instructions. A Python-backed skill also contains a Python package that Prime Agent installs into the kernel environment and exposes by import name.++For a skill named `release-audit`, the model can call:++```python+report = await release_audit(repository=".", target_version="0.4.0")+```++This makes Python-backed skills a superset of instruction-only skills: they can provide guidance, scripts, references, dependencies, typed callables, and optional shell commands. They may also call `rlm(...)` themselves when a capability needs recursive delegation.++Only skill metadata is placed in the startup prompt. The agent loads the full `SKILL.md` when the task matches, then inspects and calls the documented Python API. See [Skills](skills.md) for discovery, packaging, and the built-in skill-creation workflow.++### 4. State is designed to outlive one turn++The RLM programming model assumes useful work may take many turns or continue after the terminal UI closes:++- automatic compaction summarizes older context while preserving recent messages and kernel state;+- daemon-backed workers keep active sessions running after clients detach;+- child registries and session artifacts make subagents recoverable;+- heartbeats and scheduled prompts re-enter a session later;+- persistent goals continue until the objective is complete or the user changes their state; and+- autonomous mode adds bounded continuations and optional quality gates.++See [Long-Running and Background Agents](long-running-agents.md) for these lifecycle features.++## Host Bridge++Python skills use typed host requests for capabilities whose authoritative state belongs outside the kernel. For example, the `goal`, `agent_message`, `rlm_heartbeat`, and `compact` skills call `rlm.host_request(...)`; the TypeScript host validates the request and owns the state transition.++This keeps credentials, provider execution, transcript writes, worker routing, and scheduling out of Python while retaining a programmatic model interface.++## Trust Model++The IPython kernel runs model-generated Python and project commands with the worker's operating-system permissions. It is a durable control environment, not a security sandbox. Review third-party Python skills and use an external sandbox or restricted environment for untrusted repositories and instructions.++For implementation details, see [Kernel and RLM Recursion](kernel-and-rlm-recursion.md).diff --git a/packages/coding-agent/docs/skills.md b/packages/coding-agent/docs/skills.mdindex d926c93045..2ed4500e10 100644--- a/packages/coding-agent/docs/skills.md+++ b/packages/coding-agent/docs/skills.md@@ -12,6 +12,7 @@ Prime Agent implements the [Agent Skills standard](https://agentskills.io/specif- [Built-in Skills](#built-in-skills)- [How Skills Work](#how-skills-work)- [Python-Backed Skills](#python-backed-skills)+- [Creating Skills with Prime Agent](#creating-skills-with-prime-agent)- [Skill Commands](#skill-commands)- [Skill Structure](#skill-structure)- [Frontmatter](#frontmatter)@@ -197,6 +198,38 @@ await web_search("prime agent")!web_search "prime agent" --limit 3```+## Creating Skills with Prime Agent++Prime Agent ships with a built-in `skill-creator` skill that teaches the agent both the Agent Skills format and the Python-backed package contract. You can ask for a skill in normal language:++```text+Create a project Python-backed skill named release-audit in+.prime/agent/skills/release-audit. It should expose+await release_audit(repository, target_version), include concise SKILL.md+instructions, declare its dependencies, and verify the callable in a fresh+Prime Agent session.+```++To force the creation workflow explicitly, invoke the built-in skill command:++```text+/skill:skill-creator Create a personal markdown skill for reviewing database migrations.+```++Tell the agent three things:++1. **Scope:** use `.prime/agent/skills/<name>/` for a project skill committed with the repository, or `~/.prime/agent/skills/<name>/` for a personal skill.+2. **Kind:** ask for a markdown skill when the capability is primarily instructions; ask for a Python-backed skill when the agent should call reusable functionality from IPython.+3. **Contract:** describe the intended Python call, inputs, output, dependencies, credentials, and verification behavior.++The agent should create `SKILL.md` in both cases. For a Python-backed skill it should also create `pyproject.toml` and `src/<import_name>/__init__.py`, expose a documented callable, and verify that the package imports in the kernel.++Use `/reload` to rediscover new or edited skill metadata. Start a fresh Prime Agent session after adding a Python-backed skill so kernel setup can install and import the package.++### Installed Skills and Continual Harness Skills++An installed Python-backed skill is a real package on disk that adds executable functionality to the kernel. A continual harness skill entry is a persisted description of a reusable Python call, including its reference and argument contract. `/refine` can create or update the latter after a repeated procedure emerges, but it does not replace packaging new functionality with `skill-creator`.+## Skill CommandsSkills register as `/skill:name` commands: