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
8 changes: 3 additions & 5 deletions adapters/python/openclaw/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ Before migration, copy every legacy session directory while the Gateway is stopp

Run `openclaw doctor --fix` with the 2026.9.34 executable and the same path settings. The command imports legacy `sessions.json` files and JSONL session data into each agent's SQLite database. Restart the Gateway after the command succeeds. Keep the verified backup for rollback.

Managed runtimes and NeMo Fabric-owned services use temporary state directories by default, so each new Gateway starts with fresh state. With `runtime.keep_state`, the Gateway's `OPENCLAW_STATE_DIR` is the agent's state folder, `<artifact root>/.fabric/state/nvidia.fabric.openclaw/<agent name>`, for every runtime of the agent; see [Keep OpenClaw State Across Runtimes](../../../docs/integrations/harness/openclaw.mdx#keep-openclaw-state-across-runtimes).
Managed runtimes and NeMo Fabric-owned services use temporary state directories, so each new Gateway starts with fresh state.

## Configuration

Expand All @@ -70,10 +70,8 @@ The adapter maps these fields into a generated `openclaw.json` before starting
the Gateway. A non-empty `tools.enabled` list maps to `tools.allow`, an empty
list maps to a wildcard `tools.deny` policy, and `tools.blocked` maps to
`tools.deny`. It uses a generated one-time token, loopback binding, and an
isolated temporary OpenClaw state directory, or the agent's state folder with
`runtime.keep_state`. The Gateway is stopped and its temporary configuration is
removed when the NeMo Fabric runtime stops; a kept state folder is never
removed.
isolated temporary OpenClaw state directory. The Gateway is stopped and its
temporary configuration is removed when the NeMo Fabric runtime stops.

Each `skills.paths` entry is a skill or a folder of skills, as
[Load Skills from Folders](../../../docs/integrations/harness/skills.mdx)
Expand Down
3 changes: 1 addition & 2 deletions adapters/python/openclaw/openclaw.fabric-adapter.json
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@
"port"
],
"additionalProperties": false,
"description": "OpenClaw's Control UI. After the Gateway starts, the adapter writes its sign-in token to interfaces/dashboard.token in <artifact root>/.fabric/openclaw/runtimes/<runtime-id>, or in the agent's state folder with runtime.keep_state."
"description": "OpenClaw's Control UI. After the Gateway starts, the adapter writes its sign-in token to <artifact root>/.fabric/openclaw/runtimes/<runtime-id>/interfaces/dashboard.token."
},
"terminal": {
"type": "object",
Expand Down Expand Up @@ -208,7 +208,6 @@
"models.top_p",
"models.max_tokens",
"instructions.system",
"runtime.keep_state",
"tools.enabled",
"tools.blocked",
"mcp",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,10 +190,6 @@ def _dashboard_port(settings: dict[str, Any]) -> int | None:


def _dashboard_token_path(context: contract.RuntimeContext, base_dir: Path) -> Path:
# With runtime.keep_state, interfaces live in the agent's state folder,
# where every runtime of the agent finds them, as Hermes's do.
if context.state_dir:
return Path(context.state_dir) / "interfaces" / "dashboard.token"
root = context.artifacts.root
artifact_root = (base_dir / str(root)).resolve() if root else base_dir / "artifacts"
return (
Expand Down Expand Up @@ -1204,31 +1200,7 @@ async def start(self, payload: dict[str, Any]) -> dict[str, Any] | None:
await self._connect_service_runtime(config, context, settings, service)
return None
if service is not None and service.get("operation") == "attach":
if context.state_dir:
raise lifecycle.LifecycleError(
"openclaw_keep_state_requires_managed_gateway",
"OpenClaw keeps state only for a Gateway that NeMo Fabric "
"starts; an attached Gateway keeps its state where its "
"deployment puts it",
metadata={"field": "runtime.keep_state"},
)
return await self._attach_service(config, context, settings, service)
if context.state_dir:
# A runtime that ended without stop can leave its dashboard token
# and interface files in the kept state, for a Gateway that no
# longer runs.
interface_directory = _dashboard_token_path(context, base_dir).parent
try:
(interface_directory / "dashboard.token").unlink(missing_ok=True)
except OSError:
removed = False
else:
removed = native_interfaces.remove(interface_directory)
if not removed:
raise lifecycle.LifecycleError(
"openclaw_interface_cleanup_failed",
"OpenClaw interface files could not be removed",
)
child_env = common_utils.virtualenv_subprocess_env()
child_env.update(context.environment.env)
if model.api_key_env is not None and not child_env.get(model.api_key_env):
Expand Down Expand Up @@ -1291,19 +1263,9 @@ def startup_remaining() -> float:
token = secrets.token_urlsafe(48)
token_env = "OPENCLAW_GATEWAY_TOKEN"

# The generated configuration is this runtime's alone, so it stays in a
# temporary folder that stop removes, with or without kept state.
temp_dir = tempfile.TemporaryDirectory(prefix="nemo-fabric-openclaw-")
if context.state_dir:
# With runtime.keep_state, OpenClaw's native state, such as its
# sessions and the skills the agent writes, is the agent's state
# folder. Fabric locks that folder for one runtime at a time and
# never removes it; neither does the adapter.
state_dir = Path(context.state_dir)
state_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
else:
state_dir = Path(temp_dir.name) / "state"
state_dir.mkdir(mode=0o700)
state_dir = Path(temp_dir.name) / "state"
state_dir.mkdir(mode=0o700)
config_path = Path(temp_dir.name) / "openclaw.json"
generated = _openclaw_config(
config,
Expand Down
62 changes: 2 additions & 60 deletions docs/integrations/harness/openclaw/openclaw.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ Before migration, copy every legacy session directory while the Gateway is stopp

Run `openclaw doctor --fix` with the 2026.9.34 executable and the same path settings. The command imports legacy `sessions.json` files and JSONL session data into each agent's SQLite database. Restart the Gateway after the command succeeds. Keep the verified backup for rollback.

Managed runtimes and NeMo Fabric-owned services use temporary state directories by default, so each new Gateway starts with fresh state. To keep OpenClaw's state across runtimes, set `runtime.keep_state` as [Keep OpenClaw State Across Runtimes](#keep-openclaw-state-across-runtimes) describes.
Managed runtimes and NeMo Fabric-owned services use temporary state directories, so each new Gateway starts with fresh state.

## Configure the Adapter

Expand Down Expand Up @@ -149,65 +149,7 @@ settings = {

The dashboard selects the existing Gateway's base port. Terminal has no port; it discovers that same Gateway, or uses the existing allocator when dashboard is absent. The dashboard port conflicts with `port_range`. Both clients can attach in parallel with SDK and native HTTP clients; use distinct sessions to keep conversations separate.

After readiness, the adapter publishes private connection material under `<artifact root>/.fabric/openclaw/runtimes/<runtime-id>/interfaces/`, or under `interfaces/` in the agent's state folder with `runtime.keep_state`. `gateway.json` contains endpoints, selected agent, executable, workspace, and a credential-file reference. The token is in `dashboard.token` when the dashboard is enabled, otherwise `gateway.token`. Terminal adds an executable `terminal` and `terminal.running` marker. Stop removes the marker first and revokes discovery and credentials before stopping the Gateway. An abrupt host kill can leave files; attachment also checks authenticated Gateway availability.

## Keep OpenClaw State Across Runtimes

By default, each Gateway that the adapter starts uses a temporary
`OPENCLAW_STATE_DIR` that `stop` removes, so the sessions, memory, and skills
that the agent writes there are lost when the runtime stops. Set `keep_state`
in the config's `runtime` mapping to keep that folder:

```python
from nemo_fabric import FabricConfig

config = FabricConfig.from_mapping(
{
"metadata": {"name": "assistant"},
"harness": {"adapter_id": "nvidia.fabric.openclaw"},
"models": {"default": {"provider": "nvidia", "model": "<model>"}},
"runtime": {"artifacts": "/data/artifacts", "keep_state": True},
}
)
```

With `runtime.keep_state`, the Gateway's `OPENCLAW_STATE_DIR` is the agent's
state folder, `<artifact root>/.fabric/state/nvidia.fabric.openclaw/<agent name>`,
for every runtime of the agent and for a NeMo Fabric-owned service:

- Skills that the agent writes through OpenClaw's Skill Workshop stay at the
path where OpenClaw saved them,
`agents/<agent id>/agent/workshop-skills/<skill>/SKILL.md` in that folder,
and the next Gateway discovers them there. The adapter doesn't copy, move, or
recreate them.
- The generated `openclaw.json` and the Gateway token remain specific to one
runtime: the adapter writes the configuration to a temporary folder at each
start and removes it at stop. The native interface files, including the
dashboard token, are written to `interfaces/` in the state folder, removed
by `stop`, and removed at the next start if an earlier runtime ended without
`stop`. A removal failure stops startup with
`openclaw_interface_cleanup_failed` before the Gateway starts.
- `stop` and a failed start never remove the state folder or its contents.
- NeMo Fabric lets one runtime at a time use the folder, as
[Keep Agent State Across Runtimes](../../../sdk/python.mdx#keep-agent-state-across-runtimes)
describes. A second runtime of the agent fails to start while the first runs.
- An attached caller-owned Gateway keeps its state where its deployment puts
it, so attaching a service with `runtime.keep_state` fails with
`openclaw_keep_state_requires_managed_gateway`.

Kept state lasts as long as the artifact root does. When the runtime runs in a
container or sandbox that is replaced, put the artifact root on durable storage,
such as a Kubernetes persistent volume. The folder can hold sessions,
credentials, and sign-ins, so protect it like a home directory. To discard it,
stop every runtime and service of the agent, then remove the folder.

Keeping files doesn't by itself keep a plugin that the agent installed enabled
and usable: the adapter generates a read-only `openclaw.json` at each start, and
plugin use after a restart is not yet qualified.

Keeping state doesn't continue an earlier conversation: each invocation still
uses the NeMo Fabric runtime ID as its OpenClaw session key, so a new runtime
starts a new session, and earlier sessions stay in the state folder.
After readiness, the adapter publishes private connection material under `<artifact root>/.fabric/openclaw/runtimes/<runtime-id>/interfaces/`. `gateway.json` contains endpoints, selected agent, executable, workspace, and a credential-file reference. The token is in `dashboard.token` when the dashboard is enabled, otherwise `gateway.token`. Terminal adds an executable `terminal` and `terminal.running` marker. Stop removes the marker first and revokes discovery and credentials before stopping the Gateway. An abrupt host kill can leave files; attachment also checks authenticated Gateway availability.

## Testing and Limitations

Expand Down
2 changes: 1 addition & 1 deletion docs/sdk/python.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -906,7 +906,7 @@ The operating system releases the lock after all copies of the lock have closed:
- **Windows:** Adapter hosts do not inherit the lock. Only the NeMo Fabric process holds the lock, so the folder becomes available if that process exits while an adapter host is still running.
- **Detached processes:** A native process can continue accessing the state folder after all lock descriptors close. A replacement runtime can then acquire the lock while the detached process still writes to the folder.

Planning fails without an artifact directory or for an adapter that doesn't declare `runtime.keep_state`. The Hermes Agent and OpenClaw adapters declare `runtime.keep_state`.
Planning fails without an artifact directory or for an adapter that doesn't declare `runtime.keep_state`. The Hermes Agent adapter declares `runtime.keep_state`.

## Runtime Resource Snapshots

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2047,7 +2047,6 @@
"models.top_p",
"models.max_tokens",
"instructions.system",
"runtime.keep_state",
"tools.enabled",
"tools.blocked",
"mcp",
Expand Down Expand Up @@ -2234,7 +2233,7 @@
"properties": {
"dashboard": {
"additionalProperties": false,
"description": "OpenClaw's Control UI. After the Gateway starts, the adapter writes its sign-in token to interfaces/dashboard.token in <artifact root>/.fabric/openclaw/runtimes/<runtime-id>, or in the agent's state folder with runtime.keep_state.",
"description": "OpenClaw's Control UI. After the Gateway starts, the adapter writes its sign-in token to <artifact root>/.fabric/openclaw/runtimes/<runtime-id>/interfaces/dashboard.token.",
"properties": {
"enabled": {
"default": true,
Expand Down Expand Up @@ -2330,7 +2329,7 @@
"name": "nemo-fabric-adapters-openclaw",
"version": "0.7.0"
},
"sha256": "fbcead9c7db27d3c41ab93350b90c3b815570a7e51fb09fb6f498bff458af970",
"sha256": "dbfb74e0d2a2ba4db50bdc0d93140c0de3abc07d90f6551b9dd1f28458b9cc59",
"source": "adapters/python/openclaw/openclaw.fabric-adapter.json"
},
"nvidia.fabric.opencode": {
Expand Down
52 changes: 1 addition & 51 deletions tests/_utils/mock_openclaw.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,57 +4,12 @@

"""Mock OpenClaw CLI and Gateway used by adapter tests."""

import hashlib
import json
import os
import signal
import sys
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path


def workshop_skills() -> Path:
"""Where the agent saves the skills it writes, inside OpenClaw's state."""
return (
Path(os.environ["OPENCLAW_STATE_DIR"])
/ "agents"
/ "default"
/ "agent"
/ "workshop-skills"
)


def skill_reply(request: dict) -> str | None:
"""Write or use a skill the way the agent does, for retention tests.

`author-skill <name>` saves a new skill in OpenClaw's state.
`use-skill <name> <nonce>` discovers it there, reads it, and replies with
its path, its hash, and an output that only this request can produce.
"""
messages = [m for m in request.get("messages", []) if m.get("role") == "user"]
words = str(messages[-1].get("content", "")).split() if messages else []
if words[:1] == ["author-skill"] and len(words) == 2:
skill = workshop_skills() / words[1] / "SKILL.md"
skill.parent.mkdir(parents=True, exist_ok=True)
skill.write_text(
f"---\nname: {words[1]}\ndescription: Echo a nonce.\n---\n\n"
"Reply with the skill name and the nonce.\n",
encoding="utf-8",
)
elif words[:1] != ["use-skill"] or len(words) != 3:
return None
found = sorted(workshop_skills().glob("*/SKILL.md"))
skill = next((path for path in found if path.parent.name == words[1]), None)
if skill is None:
return "SKILL_MISSING"
return json.dumps(
{
"path": str(skill),
"sha256": hashlib.sha256(skill.read_bytes()).hexdigest(),
"output": f"{words[1]}:{words[2]}" if words[0] == "use-skill" else None,
}
)


args = sys.argv[1:]
Expand All @@ -78,9 +33,6 @@ def skill_reply(request: dict) -> str | None:
if readonly_path := os.environ.get("FAKE_OPENCLAW_CONFIG_READONLY"):
with open(readonly_path, "w", encoding="utf-8") as stream:
stream.write(os.environ.get("OPENCLAW_CONFIG_READONLY", ""))
if state_path := os.environ.get("FAKE_OPENCLAW_STATE_CAPTURE"):
with open(state_path, "w", encoding="utf-8") as stream:
stream.write(os.environ["OPENCLAW_STATE_DIR"])
if pid_path := os.environ.get("FAKE_OPENCLAW_PID"):
with open(pid_path, "w", encoding="utf-8") as stream:
stream.write(str(os.getpid()))
Expand Down Expand Up @@ -205,9 +157,7 @@ def do_POST(self):
"choices": [
{
"index": 0,
"delta": {
"content": skill_reply(request) or "OpenClaw response"
},
"delta": {"content": "OpenClaw response"},
"finish_reason": None,
}
],
Expand Down
Loading
Loading