diff --git a/adapters/python/openclaw/README.md b/adapters/python/openclaw/README.md index a8447ddde..bad14ff6f 100644 --- a/adapters/python/openclaw/README.md +++ b/adapters/python/openclaw/README.md @@ -104,9 +104,11 @@ The following settings are specific to the OpenClaw adapter: | Setting | Default | Description | | --- | --- | --- | | `openclaw_command` | `openclaw` | Executable name or path. | -| `agent_id` | `default` | OpenClaw agent for NeMo Fabric-originated invocations. | +| `agent_id` | `default` | Selected agent for SDK and managed native clients. | | `channel_config` | None | OpenClaw-native `channels` and `bindings` for a prepared service. Every binding must target `agent_id`. Managed runtimes reject this setting. | | `port_range` | Random available range | Inclusive consumer-allocated range with `start` and `end` fields; it must span at least 111 ports. | +| `interfaces.dashboard` | None | Serve the Control UI on a managed runtime, with an exact `port`, optional `enabled`, and `public_origins`; refer to the [dashboard guide](../../../docs/integrations/harness/openclaw/openclaw-dashboard.mdx). | +| `interfaces.terminal` | None | Attach the native terminal to the existing Gateway, without a separate port. Refer to the [terminal guide](../../../docs/integrations/harness/openclaw/openclaw-tui.mdx). | | `startup_timeout_seconds` | `60` | One deadline for all of start, from checking the `openclaw` command to the Gateway becoming ready; at most 75 seconds. | | `shutdown_timeout_seconds` | `5` | Graceful shutdown timeout. | | `connect_timeout_seconds` | `10` | Local HTTP connection timeout. | @@ -114,7 +116,15 @@ The following settings are specific to the OpenClaw adapter: OpenClaw's [derived-port mapping](https://docs.openclaw.ai/gateway/multiple-gateways#port-mapping-derived) uses `base_port + 2` for browser control and allocates browser CDP ports from `base_port + 11` through `base_port + 110`. Set `port_range` when the consumer reserves a port range before configuring NeMo Fabric; the adapter selects a base whose complete derived footprint fits inside that range. The adapter verifies only that `base_port` and `base_port + 2` are available before startup. OpenClaw allocates the CDP ports on demand instead of reserving the complete range, so the adapter cannot guarantee that those ports will still be available when OpenClaw needs them. Keep the configured range reserved for the lifetime of the runtime when using OpenClaw browser features. -Relay telemetry and native OpenTelemetry are not supported. +With native interfaces enabled, one Gateway owns all four client paths. A small adapter-owned plugin adds the configured instruction for the selected agent through the public `before_prompt_build` hook while preserving OpenClaw's native prompt and tool guidance. SDK requests omit duplicate instruction injection in that mode; SDK-only and service behavior are preserved. The existing `replace` mode selects the Fabric instruction without replacing OpenClaw's internal prompt. Model, workspace, tools, MCP, and skill configuration are shared; native responses remain native. + +Startup verifies the loaded hook through an authenticated, model-free probe before publishing connection files. Missing, blocked, or mismatched hooks fail with `openclaw_shared_configuration_unavailable`. The plugin requires both `allowConversationAccess` and `allowPromptInjection`: pinned OpenClaw gates `before_prompt_build` behind both permissions for external plugins. + +After readiness, private `interfaces/gateway.json` discovery references `dashboard.token` or `gateway.token`. Terminal selection adds an executable `interfaces/terminal` and `terminal.running` marker; the marker is removed first on stop. The launcher uses private client configuration and an environment SecretRef, not token arguments. Terminal attachment currently requires POSIX. Pinned TUI `/quit` can use a native exit-code-130 fallback while the Gateway stays usable. + +Refer to the [four-path architecture](../../../docs/integrations/harness/openclaw/openclaw.mdx) and [repeatable examples](../../../examples/interfaces/openclaw/README.md). Relay telemetry, ATIF/ATOF export, and native OpenTelemetry are not supported. + +With native browser or terminal access enabled, runtime activity is `unknown`; healthy endpoints can still pass normalized checks. SDK invocation state alone cannot account for native work. ## Gateway Health diff --git a/adapters/python/openclaw/openclaw.fabric-adapter.json b/adapters/python/openclaw/openclaw.fabric-adapter.json index 5d00b0240..f77440d86 100644 --- a/adapters/python/openclaw/openclaw.fabric-adapter.json +++ b/adapters/python/openclaw/openclaw.fabric-adapter.json @@ -18,7 +18,8 @@ "type": "string", "minLength": 1, "default": "default", - "description": "OpenClaw agent selected for NeMo Fabric-originated invocations." + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$", + "description": "OpenClaw agent selected for SDK invocations and managed native clients." }, "channel_config": { "type": "object", @@ -64,6 +65,55 @@ "additionalProperties": false, "description": "Inclusive consumer-allocated port range. The adapter selects a Gateway base port whose complete derived footprint through base + 110 fits within the range. When omitted, the adapter selects an available local range." }, + "interfaces": { + "type": "object", + "properties": { + "dashboard": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "default": true, + "description": "Serve the Control UI. A present dashboard is on unless this is false." + }, + "port": { + "type": "integer", + "minimum": 1, + "maximum": 65425, + "description": "Exact loopback Gateway base port, which serves the Control UI. Start fails if it or port + 2 is in use. OpenClaw allocates browser ports through port + 110 on demand, so keep that range free. Can't be combined with port_range." + }, + "public_origins": { + "type": "array", + "items": { + "type": "string", + "pattern": "^https?://[^/\\s?#@]+$" + }, + "uniqueItems": true, + "default": [], + "description": "Additional browser HTTP(S) origins. OpenClaw also permits loopback origins; the token is always required." + } + }, + "required": [ + "port" + ], + "additionalProperties": false, + "description": "OpenClaw's Control UI. After the Gateway starts, the adapter writes its sign-in token to /.fabric/openclaw/runtimes//interfaces/dashboard.token." + }, + "terminal": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "default": true + } + }, + "additionalProperties": false, + "description": "Attach the native terminal to the existing Gateway. No terminal port; publishes a private executable launcher and terminal.running marker." + } + }, + "additionalProperties": false, + "description": "Native interfaces served by a managed runtime. Services reject interfaces." + }, "startup_timeout_seconds": { "type": "number", "exclusiveMinimum": 0, @@ -89,6 +139,9 @@ "description": "Timeout between response bytes from the local OpenClaw Gateway. When unset, the invocation timeout bounds the response." } }, + "dependentSchemas": { + "port_range": {"properties": {"interfaces": {"properties": {"dashboard": false}}}} + }, "additionalProperties": false }, "model_schema": { diff --git a/adapters/python/openclaw/pyproject.toml b/adapters/python/openclaw/pyproject.toml index 6af8febd0..0d663d03a 100644 --- a/adapters/python/openclaw/pyproject.toml +++ b/adapters/python/openclaw/pyproject.toml @@ -40,6 +40,9 @@ Documentation = "https://docs.nvidia.com/nemo/fabric" where = ["src"] include = ["nemo_fabric_adapters.openclaw*"] +[tool.setuptools.package-data] +"nemo_fabric_adapters.openclaw" = ["native_config/*.mjs", "native_config/*.json"] + [tool.setuptools.data-files] "share/nemo-fabric/adapters/openclaw" = ["openclaw.fabric-adapter.json"] diff --git a/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/adapter.py b/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/adapter.py index fa450672f..1a0cb4815 100644 --- a/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/adapter.py +++ b/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/adapter.py @@ -33,9 +33,11 @@ from nemo_fabric_adapter_contract import models as contract from nemo_fabric_adapters.common import instructions as common_instructions from nemo_fabric_adapters.common import lifecycle +from nemo_fabric_adapters.common import local_interfaces from nemo_fabric_adapters.common import openai_chat from nemo_fabric_adapters.common import utils as common_utils from nemo_fabric_adapters.openclaw import _windows_job +from nemo_fabric_adapters.openclaw import interfaces as native_interfaces DEFAULT_STARTUP_TIMEOUT_SECONDS = 60.0 @@ -160,15 +162,49 @@ def _positive_setting(settings: dict[str, Any], name: str, default: float) -> fl return float(value) +def _native_interfaces_enabled(settings: dict[str, Any]) -> bool: + """Return whether this runtime exposes a managed browser or terminal client.""" + return any( + native_interfaces.enabled(settings, name) for name in ("dashboard", "terminal") + ) + + +def _dashboard_port(settings: dict[str, Any]) -> int | None: + """Return the Control UI's port when the settings enable it. + + The descriptor's schema has already checked the settings. + """ + dashboard = settings.get("interfaces", {}).get("dashboard") + if dashboard is None or not dashboard.get("enabled", True): + return None + return dashboard["port"] + + +def _dashboard_token_path(context: contract.RuntimeContext, base_dir: Path) -> Path: + root = context.artifacts.root + artifact_root = (base_dir / str(root)).resolve() if root else base_dir / "artifacts" + return ( + artifact_root + / ".fabric" + / "openclaw" + / "runtimes" + / context.runtime_id + / "interfaces" + / "dashboard.token" + ) + + def _agent_id(settings: dict[str, Any]) -> str: value = settings.get("agent_id", "default") - if not isinstance(value, str) or not value.strip(): + if not isinstance(value, str) or not re.fullmatch( + r"[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}", value + ): raise lifecycle.LifecycleError( "openclaw_invalid_configuration", - "OpenClaw agent_id must be a non-empty string", + "OpenClaw agent_id must contain 1–64 ASCII letters, digits, underscores, or hyphens and start with a letter or digit", metadata={"field": "harness.settings.agent_id"}, ) - return value.strip() + return value def _channel_config( @@ -461,6 +497,7 @@ def _openclaw_config( port: int, token_env: str, service_mode: bool = False, + dashboard: bool = False, ) -> dict[str, Any]: model = _selected_model(config) model_id = _model_id(model) @@ -493,7 +530,18 @@ def _openclaw_config( "mode": "token", "token": {"source": "env", "provider": "default", "id": token_env}, }, - "controlUi": {"enabled": False}, + "controlUi": { + "enabled": True, + "allowedOrigins": [ + f"http://127.0.0.1:{port}", + f"http://localhost:{port}", + *native_interfaces.public_origins( + config.harness.settings if config.harness else {} + ), + ], + } + if dashboard + else {"enabled": False}, "http": {"endpoints": {"chatCompletions": {"enabled": True}}}, }, "agents": { @@ -518,6 +566,27 @@ def _openclaw_config( result["agents"]["entries"] = {agent_id: {}} if config.instructions is not None and config.instructions.system is not None: result["agents"]["defaults"]["contextInjection"] = "never" + if _native_interfaces_enabled( + config.harness.settings if config.harness else {} + ): + result["plugins"] = { + "load": { + "paths": [str(Path(__file__).with_name("native_config").resolve())] + }, + "entries": { + "fabric-shared-config": { + "enabled": True, + "hooks": { + "allowConversationAccess": True, + "allowPromptInjection": True, + }, + "config": { + "agentId": agent_id, + "systemInstruction": config.instructions.system.content, + }, + } + }, + } skill_paths = _resolve_skill_paths(config, base_dir) if skill_paths: result["skills"] = {"load": {"extraDirs": skill_paths}} @@ -782,8 +851,6 @@ def _write_service_connection( token: str, agent_id: str, ) -> None: - path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) - os.chmod(path.parent, 0o700) payload = ( json.dumps( { @@ -794,25 +861,7 @@ def _write_service_connection( ) + "\n" ) - descriptor, temporary_name = tempfile.mkstemp( - dir=path.parent, - prefix=f".{path.name}.", - ) - try: - if hasattr(os, "fchmod"): - os.fchmod(descriptor, 0o600) - with os.fdopen(descriptor, "w", encoding="utf-8") as stream: - descriptor = -1 - stream.write(payload) - os.replace(temporary_name, path) - except BaseException: - if descriptor >= 0: - os.close(descriptor) - try: - os.unlink(temporary_name) - except FileNotFoundError: - pass - raise + local_interfaces.write_private_file(path, payload) def _read_service_connection(path: Path) -> tuple[str, str, str]: @@ -857,6 +906,8 @@ def __init__(self) -> None: self._temp_dir: tempfile.TemporaryDirectory[str] | None = None self._port: int | None = None self._token: str | None = None + self._dashboard_token_path: Path | None = None + self._interface_directory: Path | None = None self._gateway_url: str | None = None self._agent_id = "default" self._shutdown_timeout = DEFAULT_SHUTDOWN_TIMEOUT_SECONDS @@ -932,6 +983,11 @@ def observed(outcome: str, reason: str | None) -> dict[str, Any]: if service_host else "stopped" if reason == "agent_exited" + else "unknown" + if config is not None + and _native_interfaces_enabled( + config.harness.settings if config.harness else {} + ) else ( "busy" if self._active_invoke_task is not None @@ -1027,7 +1083,8 @@ def unique(pairs): valid and not service_host and not any( - model["id"] == f"openclaw/{agent_id}" for model in models + model["id"] == f"openclaw/{agent_id.lower()}" + for model in models ) ): return observed("failed", "endpoint_unavailable") @@ -1050,6 +1107,20 @@ async def start(self, payload: dict[str, Any]) -> dict[str, Any] | None: "openclaw_invalid_service_context", "OpenClaw service context must be an object", ) + if service is not None and "interfaces" in settings: + raise lifecycle.LifecycleError( + "openclaw_interfaces_require_managed_runtime", + "OpenClaw interfaces require a managed runtime", + metadata={"field": "harness.settings.interfaces"}, + ) + _agent_id(settings) + dashboard_port = _dashboard_port(settings) + if native_interfaces.enabled(settings, "terminal") and os.name != "posix": + raise lifecycle.LifecycleError( + "openclaw_terminal_platform_unsupported", + "Managed OpenClaw terminal requires POSIX", + ) + native_interfaces.public_origins(settings) self._service_host = service is not None and service.get("operation") in { "prepare", "attach", @@ -1106,7 +1177,20 @@ def startup_remaining() -> float: kind="component", ) - port = _select_port(settings) + if dashboard_port is None: + port = _select_port(settings) + else: + port = dashboard_port + for candidate in (port, port + 2): + if not _port_available(candidate): + raise lifecycle.LifecycleError( + "openclaw_interface_port_unavailable", + f"OpenClaw dashboard port {candidate} is already in use", + metadata={ + "field": "harness.settings.interfaces.dashboard.port", + "port": candidate, + }, + ) # Generate a one-time use token for the OpenClaw gateway token = secrets.token_urlsafe(48) @@ -1123,6 +1207,7 @@ def startup_remaining() -> float: port=port, token_env=token_env, service_mode=service is not None and service.get("operation") == "prepare", + dashboard=dashboard_port is not None, ) config_path.write_text(json.dumps(generated, indent=2) + "\n", encoding="utf-8") config_path.chmod(0o600) @@ -1187,6 +1272,33 @@ def startup_remaining() -> float: ] self._install_signal_handlers() await self._wait_started(port, token, startup_remaining()) + if "fabric-shared-config" in generated.get("plugins", {}).get( + "entries", {} + ): + await self._verify_shared_configuration( + port, token, _agent_id(settings), startup_remaining() + ) + if dashboard_port is not None: + token_path = _dashboard_token_path(context, base_dir) + local_interfaces.write_private_file(token_path, token) + self._dashboard_token_path = token_path + if _native_interfaces_enabled(settings): + self._interface_directory = _dashboard_token_path( + context, base_dir + ).parent + native_interfaces.publish( + self._interface_directory, + runtime_id=context.runtime_id, + port=port, + token=token, + command=command, + workspace=str( + Path(context.environment.workspace or base_dir).resolve() + ), + agent_id=_agent_id(settings), + dashboard=dashboard_port is not None, + terminal=native_interfaces.enabled(settings, "terminal"), + ) self._client = httpx.AsyncClient( headers={"authorization": f"Bearer {token}"}, http2=True, @@ -1623,6 +1735,31 @@ async def _wait_started(self, port: int, token: str, timeout: float) -> None: retryable=True, ) + async def _verify_shared_configuration( + self, port: int, token: str, agent_id: str, timeout: float + ) -> None: + try: + async with asyncio.timeout(timeout): + async with httpx.AsyncClient( + headers={"authorization": f"Bearer {token}"}, + timeout=min(timeout, 5.0), + trust_env=False, + ) as client: + response = await client.get( + f"http://127.0.0.1:{port}/fabric/shared-config/health" + ) + response.raise_for_status() + status = response.json() + if status == {"ready": True, "agent_id": agent_id.lower()}: + return + except (httpx.HTTPError, ValueError, TimeoutError): + pass + raise lifecycle.LifecycleError( + "openclaw_shared_configuration_unavailable", + "OpenClaw shared instruction plugin or before_prompt_build hook is unavailable for the selected agent", + metadata={"field": "instructions.system", "agent_id": agent_id}, + ) + async def invoke( self, request: contract.AgentRunRequest, @@ -1648,7 +1785,9 @@ async def invoke( instruction = ( self._config.instructions.system if self._config.instructions else None ) - if instruction is not None: + if instruction is not None and not _native_interfaces_enabled( + self._config.harness.settings if self._config.harness else {} + ): messages.append({"role": "system", "content": instruction.content}) messages.append( { @@ -1712,6 +1851,22 @@ async def invoke( async def stop(self) -> None: cancellation: asyncio.CancelledError | None = None self._stopping = True + if self._interface_directory is not None: + if native_interfaces.remove(self._interface_directory): + self._interface_directory = None + token_path = self._dashboard_token_path + if token_path is not None: + try: + token_path.unlink(missing_ok=True) + except OSError: + # Keep the path so a later stop can retry. + logger.error( + "OpenClaw could not remove its dashboard token at %s", + token_path, + exc_info=True, + ) + else: + self._dashboard_token_path = None try: self._restore_signal_handlers() except Exception: diff --git a/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/interfaces.py b/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/interfaces.py new file mode 100644 index 000000000..0f10462cb --- /dev/null +++ b/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/interfaces.py @@ -0,0 +1,149 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Private attachment discovery for clients of one managed OpenClaw Gateway.""" + +from __future__ import annotations + +import json +import logging +import os +import shlex +import shutil +import sys +from pathlib import Path +from urllib.parse import urlsplit + +from nemo_fabric_adapters.common import lifecycle, local_interfaces + +logger = logging.getLogger(__name__) +FILES = ("terminal.running", "terminal", "gateway.json", "client.json", "gateway.token") + + +def enabled(settings: dict, name: str) -> bool: + """A present interface is enabled unless explicitly disabled.""" + item = settings.get("interfaces", {}).get(name) + return item is not None and item.get("enabled", True) + + +def public_origins(settings: dict) -> list[str]: + """Accept HTTP origins without credentials, paths, queries, or fragments.""" + origins = ( + settings.get("interfaces", {}).get("dashboard", {}).get("public_origins", []) + ) + for origin in origins: + try: + parsed = urlsplit(origin) + valid = ( + parsed.scheme in {"http", "https"} + and parsed.hostname + and parsed.username is None + and parsed.password is None + and not parsed.path + and not parsed.query + and not parsed.fragment + and parsed.port != 0 + ) + except ValueError: + valid = False + if not valid: + raise lifecycle.LifecycleError( + "openclaw_invalid_origin", + "Dashboard public_origins must contain HTTP(S) origins", + metadata={ + "field": "harness.settings.interfaces.dashboard.public_origins" + }, + ) + return origins + + +def publish( + directory: Path, + *, + runtime_id: str, + port: int, + token: str, + command: Path, + workspace: str, + agent_id: str, + dashboard: bool, + terminal: bool, +) -> None: + """Publish connection material after Gateway readiness and the marker last.""" + token_file = "dashboard.token" if dashboard else "gateway.token" + if not dashboard: + local_interfaces.write_private_file(directory / token_file, token) + connection = { + "version": 1, + "runtime_id": runtime_id, + "http_url": f"http://127.0.0.1:{port}", + "ws_url": f"ws://127.0.0.1:{port}", + "agent_id": agent_id, + "token_file": token_file, + "command": str(command), + "workspace": workspace, + } + local_interfaces.write_private_file( + directory / "gateway.json", json.dumps(connection) + "\n" + ) + if not terminal: + return + client = { + "gateway": { + "mode": "remote", + "remote": { + "url": connection["ws_url"], + "transport": "direct", + "token": { + "source": "env", + "provider": "default", + "id": "FABRIC_OPENCLAW_CLIENT_TOKEN", + }, + }, + }, + } + local_interfaces.write_private_file( + directory / "client.json", json.dumps(client) + "\n" + ) + launcher = ( + "#!/bin/sh\nexec " + + " ".join( + shlex.quote(arg) + for arg in ( + sys.executable, + "-m", + "nemo_fabric_adapters.openclaw.terminal", + "--connection", + str(directory / "gateway.json"), + ) + ) + + ' "$@"\n' + ) + local_interfaces.write_private_file(directory / "terminal", launcher) + os.chmod(directory / "terminal", 0o700) + local_interfaces.write_private_file( + directory / "terminal.running", runtime_id + "\n" + ) + + +def remove(directory: Path) -> bool: + """Revoke the marker first; retain failed paths for a later stop retry.""" + removed = True + for name in FILES: + try: + (directory / name).unlink(missing_ok=True) + except OSError: + removed = False + logger.error( + "OpenClaw could not remove interface file %s", + directory / name, + exc_info=True, + ) + try: + shutil.rmtree(directory / "client-state") + except FileNotFoundError: + pass + except OSError: + removed = False + logger.error("OpenClaw could not remove private client state", exc_info=True) + return removed diff --git a/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/native_config/index.mjs b/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/native_config/index.mjs new file mode 100644 index 000000000..169499a67 --- /dev/null +++ b/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/native_config/index.mjs @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { getGlobalHookRunner } from "openclaw/plugin-sdk/plugin-runtime"; +import { normalizeAgentId } from "openclaw/plugin-sdk/routing"; + +/** Add the managed instruction while retaining OpenClaw's native prompt. */ +export default { + id: "fabric-shared-config", + name: "NeMo Fabric shared configuration", + register(api) { + const { agentId, systemInstruction } = api.pluginConfig; + const managedAgentId = normalizeAgentId(agentId); + const instructionContext = `## Conversation Context\n${systemInstruction}`; + api.on("before_prompt_build", (_event, context) => { + if (context.agentId === managedAgentId) { + return { appendSystemContext: instructionContext }; + } + }, { priority: 1000 }); + api.registerHttpRoute({ + path: "/fabric/shared-config/health", + auth: "gateway", + match: "exact", + async handler(req, res) { + if (req.method !== "GET") { + res.writeHead(405, { Allow: "GET" }); + res.end(); + return; + } + let ready = false; + try { + const runner = getGlobalHookRunner(); + const result = await runner?.runBeforePromptBuild( + { prompt: "", messages: [] }, + { agentId: managedAgentId }, + ); + ready = result?.appendSystemContext === instructionContext + && result?.systemPrompt === undefined; + } catch { + // Startup fails closed without returning instructions or conversation data. + } + res.writeHead(ready ? 200 : 503, { + "Content-Type": "application/json", + "Cache-Control": "no-store", + }); + res.end(JSON.stringify({ ready, agent_id: managedAgentId })); + }, + }); + }, +}; diff --git a/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/native_config/openclaw.plugin.json b/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/native_config/openclaw.plugin.json new file mode 100644 index 000000000..31b4c86c9 --- /dev/null +++ b/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/native_config/openclaw.plugin.json @@ -0,0 +1,24 @@ +{ + "id": "fabric-shared-config", + "name": "NeMo Fabric shared configuration", + "activation": { + "onStartup": true + }, + "configSchema": { + "type": "object", + "additionalProperties": false, + "required": [ + "agentId", + "systemInstruction" + ], + "properties": { + "agentId": { + "type": "string", + "minLength": 1 + }, + "systemInstruction": { + "type": "string" + } + } + } +} diff --git a/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/native_config/package.json b/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/native_config/package.json new file mode 100644 index 000000000..4734f814b --- /dev/null +++ b/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/native_config/package.json @@ -0,0 +1,10 @@ +{ + "name": "nemo-fabric-openclaw-config", + "private": true, + "type": "module", + "openclaw": { + "extensions": [ + "./index.mjs" + ] + } +} diff --git a/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/terminal.py b/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/terminal.py new file mode 100644 index 000000000..5b1fedc79 --- /dev/null +++ b/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/terminal.py @@ -0,0 +1,136 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Launch the native TUI against the managed Gateway without secrets in argv.""" + +from __future__ import annotations + +import argparse +import json +import os +import stat +import sys +import uuid +from pathlib import Path +from urllib.parse import urlsplit + +import httpx + + +def _read_private(path: Path) -> str: + """Read a private owned file without following its final symlink.""" + descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(descriptor) as stream: + info = os.fstat(stream.fileno()) + if ( + not stat.S_ISREG(info.st_mode) + or info.st_uid != os.getuid() + or info.st_mode & 0o077 + ): + raise ValueError("Attachment files must be owner-only regular files") + return stream.read() + + +def attachment( + connection: Path, session: str | None = None +) -> tuple[list[str], dict[str, str], str]: + """Validate discovery and authenticated health, then build a native client launch.""" + if os.name != "posix": + raise ValueError("Managed terminal attachment currently requires POSIX") + parent = connection.parent.lstat() + if ( + not stat.S_ISDIR(parent.st_mode) + or parent.st_uid != os.getuid() + or parent.st_mode & 0o077 + ): + raise ValueError( + "Attachment directory must be private and owned by the current user" + ) + data = json.loads(_read_private(connection)) + parsed = urlsplit(data["http_url"]) + if ( + data["version"] != 1 + or parsed.scheme != "http" + or parsed.hostname != "127.0.0.1" + or not parsed.port + or parsed.username + or parsed.password + or parsed.path + or parsed.query + or parsed.fragment + or data["ws_url"] != f"ws://127.0.0.1:{parsed.port}" + or data["token_file"] not in {"dashboard.token", "gateway.token"} + ): + raise ValueError("Invalid managed Gateway descriptor") + if ( + _read_private(connection.with_name("terminal.running")).strip() + != data["runtime_id"] + ): + raise ValueError("Managed terminal attachment is no longer available") + token = _read_private(connection.with_name(data["token_file"])).strip() + with httpx.Client(trust_env=False, timeout=3) as client: + response = client.get( + data["http_url"] + "/v1/models", + headers={"Authorization": f"Bearer {token}"}, + ) + response.raise_for_status() + # Validate the client config as private even though it contains only a secret reference. + _read_private(connection.with_name("client.json")) + command = Path(data["command"]) + workspace = Path(data["workspace"]) + if ( + not command.is_absolute() + or not os.access(command, os.X_OK) + or not workspace.is_absolute() + or not workspace.is_dir() + ): + raise ValueError("Managed executable or workspace is unavailable") + session = f"fabric-terminal-{uuid.uuid4().hex}" if session is None else session + if ( + ":" in session + or not session + or any(character.isspace() for character in session) + ): + raise ValueError("Use a nonempty session name without colons or whitespace") + environment = { + key: value + for key, value in os.environ.items() + if not key.startswith("OPENCLAW_") + } + environment.update( + { + "OPENCLAW_CONFIG_PATH": str(connection.with_name("client.json").absolute()), + "OPENCLAW_STATE_DIR": str(connection.parent / "client-state"), + "OPENCLAW_CONFIG_READONLY": "1", + "DO_NOT_TRACK": "1", + "FABRIC_OPENCLAW_CLIENT_TOKEN": token, + } + ) + return ( + [str(command), "tui", "--session", f"agent:{data['agent_id']}:{session}"], + environment, + str(workspace), + ) + + +def main() -> None: + """Attach to one selected runtime; the client never starts a Gateway.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--connection", type=Path, required=True) + parser.add_argument( + "--session", help="Native session name; omit for a new conversation" + ) + args = parser.parse_args() + try: + command, environment, workspace = attachment(args.connection, args.session) + except (OSError, ValueError, KeyError, httpx.HTTPError): + parser.exit( + 1, + "Managed OpenClaw attachment is unavailable; check the runtime and private connection files.\n", + ) + os.chdir(workspace) + os.execvpe(command[0], command, environment) + + +if __name__ == "__main__": + main() diff --git a/assets/openclaw-invocation-paths.excalidraw b/assets/openclaw-invocation-paths.excalidraw new file mode 100644 index 000000000..6f4793649 --- /dev/null +++ b/assets/openclaw-invocation-paths.excalidraw @@ -0,0 +1,1356 @@ +{ + "type": "excalidraw", + "version": 2, + "source": "https://excalidraw.com", + "elements": [ + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "title", + "type": "text", + "x": 40, + "y": 25, + "width": 438.4375, + "height": 40, + "strokeColor": "#245400", + "backgroundColor": "transparent", + "seed": 1, + "versionNonce": 896046343, + "updated": 1794203765817, + "fontSize": 32, + "fontFamily": 2, + "text": "OpenClaw invocation paths", + "originalText": "OpenClaw invocation paths", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "a0" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "subtitle", + "type": "text", + "x": 40, + "y": 73, + "width": 516.630859375, + "height": 25, + "strokeColor": "#495057", + "backgroundColor": "transparent", + "seed": 2, + "versionNonce": 584868585, + "updated": 1794203765817, + "fontSize": 20, + "fontFamily": 2, + "text": "Four client paths \u00b7 One Gateway execution backend", + "originalText": "Four client paths \u00b7 One Gateway execution backend", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "a1" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": { + "type": 3 + }, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "runtime-boundary", + "type": "rectangle", + "x": 450, + "y": 130, + "width": 740, + "height": 760, + "strokeColor": "#868e96", + "backgroundColor": "transparent", + "seed": 3, + "versionNonce": 1371429927, + "updated": 1794203765817, + "index": "a2" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "runtime-label", + "type": "text", + "x": 472, + "y": 148, + "width": 249.15234375, + "height": 30, + "strokeColor": "#868e96", + "backgroundColor": "transparent", + "seed": 4, + "versionNonce": 1963072969, + "updated": 1794203765817, + "fontSize": 24, + "fontFamily": 2, + "text": "NeMo Fabric runtime", + "originalText": "NeMo Fabric runtime", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "a3" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "config-group" + ], + "frameId": null, + "roundness": { + "type": 3 + }, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "config", + "type": "rectangle", + "x": 500, + "y": 205, + "width": 640, + "height": 122, + "strokeColor": "#638b20", + "backgroundColor": "#f4fbdf", + "seed": 5, + "versionNonce": 1779318599, + "updated": 1794203765817, + "index": "a4" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "config-group" + ], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "config-title", + "type": "text", + "x": 522, + "y": 222, + "width": 251.3203125, + "height": 30, + "strokeColor": "#638b20", + "backgroundColor": "transparent", + "seed": 6, + "versionNonce": 879590569, + "updated": 1794203765817, + "fontSize": 24, + "fontFamily": 2, + "text": "Shared configuration", + "originalText": "Shared configuration", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "a5" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "config-group" + ], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "config-detail", + "type": "text", + "x": 522, + "y": 261, + "width": 327.65625, + "height": 50, + "strokeColor": "#343a40", + "backgroundColor": "transparent", + "seed": 7, + "versionNonce": 817151591, + "updated": 1794203765817, + "fontSize": 20, + "fontFamily": 2, + "text": "Model \u00b7 Instructions \u00b7 Tools / MCP\nWorkspace \u00b7 Skills", + "originalText": "Model \u00b7 Instructions \u00b7 Tools / MCP\nWorkspace \u00b7 Skills", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "a6" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "adapter-group" + ], + "frameId": null, + "roundness": { + "type": 3 + }, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "adapter", + "type": "rectangle", + "x": 500, + "y": 370, + "width": 640, + "height": 100, + "strokeColor": "#1971c2", + "backgroundColor": "#e7f5ff", + "seed": 8, + "versionNonce": 1892286345, + "updated": 1794203765817, + "index": "a7" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "adapter-group" + ], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "adapter-title", + "type": "text", + "x": 522, + "y": 387, + "width": 172.828125, + "height": 30, + "strokeColor": "#1971c2", + "backgroundColor": "transparent", + "seed": 9, + "versionNonce": 1484675463, + "updated": 1794203765817, + "fontSize": 24, + "fontFamily": 2, + "text": "Fabric adapter", + "originalText": "Fabric adapter", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "a8" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "adapter-group" + ], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "adapter-detail", + "type": "text", + "x": 522, + "y": 426, + "width": 283.037109375, + "height": 25, + "strokeColor": "#343a40", + "backgroundColor": "transparent", + "seed": 10, + "versionNonce": 944973417, + "updated": 1794203765817, + "fontSize": 20, + "fontFamily": 2, + "text": "Invoke \u00b7 Start \u00b7 Health \u00b7 Stop", + "originalText": "Invoke \u00b7 Start \u00b7 Health \u00b7 Stop", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "a9" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "gateway-group" + ], + "frameId": null, + "roundness": { + "type": 3 + }, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "gateway", + "type": "rectangle", + "x": 500, + "y": 525, + "width": 640, + "height": 310, + "strokeColor": "#2b8a3e", + "backgroundColor": "#ebfbee", + "seed": 11, + "versionNonce": 111644839, + "updated": 1794203765817, + "index": "aA" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "gateway-group" + ], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "gateway-title", + "type": "text", + "x": 522, + "y": 542, + "width": 235.51171875, + "height": 30, + "strokeColor": "#2b8a3e", + "backgroundColor": "transparent", + "seed": 12, + "versionNonce": 1171550537, + "updated": 1794203765817, + "fontSize": 24, + "fontFamily": 2, + "text": "OpenClaw Gateway", + "originalText": "OpenClaw Gateway", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "aB" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "gateway-group" + ], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "gateway-detail", + "type": "text", + "x": 522, + "y": 581, + "width": 443.1640625, + "height": 25, + "strokeColor": "#343a40", + "backgroundColor": "transparent", + "seed": 13, + "versionNonce": 81585095, + "updated": 1794203765817, + "fontSize": 20, + "fontFamily": 2, + "text": "Native HTTP + browser + terminal protocols", + "originalText": "Native HTTP + browser + terminal protocols", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "aC" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "gateway-group" + ], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "agent-loop", + "type": "text", + "x": 530, + "y": 655, + "width": 436.37109375, + "height": 30, + "strokeColor": "#2b8a3e", + "backgroundColor": "transparent", + "seed": 14, + "versionNonce": 1856593961, + "updated": 1794203765817, + "fontSize": 24, + "fontFamily": 2, + "text": "Native OpenClaw agent loop + tools", + "originalText": "Native OpenClaw agent loop + tools", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "aD" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "gateway-group" + ], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "sessions", + "type": "text", + "x": 530, + "y": 713, + "width": 361.9423828125, + "height": 52.5, + "strokeColor": "#343a40", + "backgroundColor": "transparent", + "seed": 15, + "versionNonce": 859493095, + "updated": 1794203765817, + "fontSize": 21, + "fontFamily": 2, + "text": "Shared configuration\nConversations selected by session", + "originalText": "Shared configuration\nConversations selected by session", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "aE" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "sdk-group" + ], + "frameId": null, + "roundness": { + "type": 3 + }, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "sdk", + "type": "rectangle", + "x": 40, + "y": 370, + "width": 300, + "height": 100, + "strokeColor": "#1971c2", + "backgroundColor": "#e7f5ff", + "seed": 16, + "versionNonce": 1354593033, + "updated": 1794203765817, + "index": "aF" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "sdk-group" + ], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "sdk-title", + "type": "text", + "x": 62, + "y": 387, + "width": 123, + "height": 30, + "strokeColor": "#1971c2", + "backgroundColor": "transparent", + "seed": 17, + "versionNonce": 978181639, + "updated": 1794203765817, + "fontSize": 24, + "fontFamily": 2, + "text": "SDK client", + "originalText": "SDK client", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "aG" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "sdk-group" + ], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "sdk-detail", + "type": "text", + "x": 62, + "y": 426, + "width": 81.083984375, + "height": 25, + "strokeColor": "#343a40", + "backgroundColor": "transparent", + "seed": 18, + "versionNonce": 1082927593, + "updated": 1794203765817, + "fontSize": 20, + "fontFamily": 2, + "text": "invoke()", + "originalText": "invoke()", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "aH" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "http-group" + ], + "frameId": null, + "roundness": { + "type": 3 + }, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "http", + "type": "rectangle", + "x": 40, + "y": 515, + "width": 300, + "height": 100, + "strokeColor": "#7950b2", + "backgroundColor": "#f3f0ff", + "seed": 19, + "versionNonce": 2098365735, + "updated": 1794203765817, + "index": "aI" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "http-group" + ], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "http-title", + "type": "text", + "x": 62, + "y": 532, + "width": 134.96484375, + "height": 30, + "strokeColor": "#7950b2", + "backgroundColor": "transparent", + "seed": 20, + "versionNonce": 1998652617, + "updated": 1794203765817, + "fontSize": 24, + "fontFamily": 2, + "text": "HTTP client", + "originalText": "HTTP client", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "aJ" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "http-group" + ], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "http-detail", + "type": "text", + "x": 62, + "y": 571, + "width": 195.556640625, + "height": 25, + "strokeColor": "#343a40", + "backgroundColor": "transparent", + "seed": 21, + "versionNonce": 1257588807, + "updated": 1794203765817, + "fontSize": 20, + "fontFamily": 2, + "text": "Native API requests", + "originalText": "Native API requests", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "aK" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "browser-group" + ], + "frameId": null, + "roundness": { + "type": 3 + }, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "browser", + "type": "rectangle", + "x": 40, + "y": 660, + "width": 300, + "height": 100, + "strokeColor": "#2b8a3e", + "backgroundColor": "#ebfbee", + "seed": 22, + "versionNonce": 1541033, + "updated": 1794203765817, + "index": "aL" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "browser-group" + ], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "browser-title", + "type": "text", + "x": 62, + "y": 677, + "width": 97.25390625, + "height": 30, + "strokeColor": "#2b8a3e", + "backgroundColor": "transparent", + "seed": 23, + "versionNonce": 1372759911, + "updated": 1794203765817, + "fontSize": 24, + "fontFamily": 2, + "text": "Browser", + "originalText": "Browser", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "aM" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "browser-group" + ], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "browser-detail", + "type": "text", + "x": 62, + "y": 716, + "width": 207.099609375, + "height": 25, + "strokeColor": "#343a40", + "backgroundColor": "transparent", + "seed": 24, + "versionNonce": 1738221193, + "updated": 1794203765817, + "fontSize": 20, + "fontFamily": 2, + "text": "OpenClaw Control UI", + "originalText": "OpenClaw Control UI", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "aN" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "terminal-group" + ], + "frameId": null, + "roundness": { + "type": 3 + }, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "terminal", + "type": "rectangle", + "x": 40, + "y": 805, + "width": 300, + "height": 100, + "strokeColor": "#2b8a3e", + "backgroundColor": "#ebfbee", + "seed": 25, + "versionNonce": 1341596295, + "updated": 1794203765817, + "index": "aO" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "terminal-group" + ], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "terminal-title", + "type": "text", + "x": 62, + "y": 822, + "width": 101.42578125, + "height": 30, + "strokeColor": "#2b8a3e", + "backgroundColor": "transparent", + "seed": 26, + "versionNonce": 677866857, + "updated": 1794203765817, + "fontSize": 24, + "fontFamily": 2, + "text": "Terminal", + "originalText": "Terminal", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "aP" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [ + "terminal-group" + ], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "terminal-detail", + "type": "text", + "x": 62, + "y": 861, + "width": 140.6640625, + "height": 25, + "strokeColor": "#343a40", + "backgroundColor": "transparent", + "seed": 27, + "versionNonce": 102709671, + "updated": 1794203765817, + "fontSize": 20, + "fontFamily": 2, + "text": "OpenClaw TUI", + "originalText": "OpenClaw TUI", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "aQ" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "sdk-path", + "type": "arrow", + "x": 348, + "y": 420, + "width": 142, + "height": 0, + "strokeColor": "#1971c2", + "backgroundColor": "transparent", + "seed": 28, + "versionNonce": 1506269257, + "updated": 1794203765817, + "points": [ + [ + 0, + 0 + ], + [ + 142, + 0 + ] + ], + "startBinding": null, + "endBinding": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false, + "index": "aR", + "lastCommittedPoint": null + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "config-adapter", + "type": "arrow", + "x": 820, + "y": 335, + "width": 0, + "height": 25, + "strokeColor": "#638b20", + "backgroundColor": "transparent", + "seed": 29, + "versionNonce": 1769434311, + "updated": 1794203765817, + "points": [ + [ + 0, + 0 + ], + [ + 0, + 25 + ] + ], + "startBinding": null, + "endBinding": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false, + "index": "aS", + "lastCommittedPoint": null + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "adapter-gateway", + "type": "arrow", + "x": 820, + "y": 478, + "width": 0, + "height": 37, + "strokeColor": "#1971c2", + "backgroundColor": "transparent", + "seed": 30, + "versionNonce": 496494377, + "updated": 1794203765817, + "points": [ + [ + 0, + 0 + ], + [ + 0, + 37 + ] + ], + "startBinding": null, + "endBinding": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false, + "index": "aT", + "lastCommittedPoint": null + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "http-path", + "type": "arrow", + "x": 348, + "y": 565, + "width": 142, + "height": 0, + "strokeColor": "#7950b2", + "backgroundColor": "transparent", + "seed": 31, + "versionNonce": 362560487, + "updated": 1794203765817, + "points": [ + [ + 0, + 0 + ], + [ + 142, + 0 + ] + ], + "startBinding": null, + "endBinding": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false, + "index": "aU", + "lastCommittedPoint": null + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "browser-path", + "type": "arrow", + "x": 348, + "y": 710, + "width": 142, + "height": 95, + "strokeColor": "#2b8a3e", + "backgroundColor": "transparent", + "seed": 32, + "versionNonce": 1313020425, + "updated": 1794203765817, + "points": [ + [ + 0, + 0 + ], + [ + 72, + 0 + ], + [ + 72, + -95 + ], + [ + 142, + -95 + ] + ], + "startBinding": null, + "endBinding": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false, + "index": "aV", + "lastCommittedPoint": null + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "terminal-path", + "type": "arrow", + "x": 348, + "y": 855, + "width": 142, + "height": 65, + "strokeColor": "#2b8a3e", + "backgroundColor": "transparent", + "seed": 33, + "versionNonce": 2124031751, + "updated": 1794203765817, + "points": [ + [ + 0, + 0 + ], + [ + 82, + 0 + ], + [ + 82, + -65 + ], + [ + 142, + -65 + ] + ], + "startBinding": null, + "endBinding": null, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false, + "index": "aW", + "lastCommittedPoint": null + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "footer-one", + "type": "text", + "x": 40, + "y": 962, + "width": 812.38623046875, + "height": 26.25, + "strokeColor": "#212529", + "backgroundColor": "transparent", + "seed": 34, + "versionNonce": 1824846057, + "updated": 1794203765817, + "fontSize": 21, + "fontFamily": 2, + "text": "\u2022 One Gateway serves every path; clients can select separate conversations.", + "originalText": "\u2022 One Gateway serves every path; clients can select separate conversations.", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "aX" + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 2, + "isDeleted": false, + "boundElements": [], + "link": null, + "locked": false, + "id": "footer-two", + "type": "text", + "x": 40, + "y": 1002, + "width": 758.6455078125, + "height": 26.25, + "strokeColor": "#212529", + "backgroundColor": "transparent", + "seed": 35, + "versionNonce": 1659743783, + "updated": 1794203765817, + "fontSize": 21, + "fontFamily": 2, + "text": "\u2022 SDK returns normalized results; HTTP and UI responses remain native.", + "originalText": "\u2022 SDK returns normalized results; HTTP and UI responses remain native.", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25, + "index": "aY" + } + ], + "appState": { + "viewBackgroundColor": "#ffffff", + "exportBackground": true, + "exportEmbedScene": true + }, + "files": {} +} diff --git a/assets/openclaw-invocation-paths.png b/assets/openclaw-invocation-paths.png new file mode 100644 index 000000000..4c4df50f5 Binary files /dev/null and b/assets/openclaw-invocation-paths.png differ diff --git a/docs/index.yml b/docs/index.yml index 97c5d7d05..629a5ac6c 100644 --- a/docs/index.yml +++ b/docs/index.yml @@ -89,7 +89,15 @@ navigation: - page: mini-SWE-agent path: ./integrations/harness/mini-swe-agent.mdx - page: OpenClaw - path: ./integrations/harness/openclaw.mdx + path: ./integrations/harness/openclaw/openclaw.mdx + - page: OpenClaw SDK + path: ./integrations/harness/openclaw/openclaw-sdk.mdx + - page: OpenClaw HTTP API + path: ./integrations/harness/openclaw/openclaw-api.mdx + - page: OpenClaw Dashboard + path: ./integrations/harness/openclaw/openclaw-dashboard.mdx + - page: OpenClaw Terminal TUI + path: ./integrations/harness/openclaw/openclaw-tui.mdx - page: OpenHands path: ./integrations/harness/openhands.mdx - page: OpenCode diff --git a/docs/integrations/harness/hermes-interfaces.mdx b/docs/integrations/harness/hermes-interfaces.mdx index 1fe7c0bfc..595a9a7b6 100644 --- a/docs/integrations/harness/hermes-interfaces.mdx +++ b/docs/integrations/harness/hermes-interfaces.mdx @@ -114,7 +114,7 @@ Native API responses remain native responses. Relay's standard artifact format p ## 5. Testing -See the [Hermes interfaces example](../../../examples/interfaces/README.md) for setup, manual testing, output verification, and Relay trajectory inspection. +See the [Hermes interfaces example](../../../examples/interfaces/hermes/README.md) for setup, manual testing, output verification, and Relay trajectory inspection. ## 6. Limitations and Planned Work diff --git a/docs/integrations/harness/openclaw.mdx b/docs/integrations/harness/openclaw.mdx deleted file mode 100644 index 5f5589eed..000000000 --- a/docs/integrations/harness/openclaw.mdx +++ /dev/null @@ -1,207 +0,0 @@ ---- -title: "Use the OpenClaw Adapter" -description: "Run an isolated OpenClaw Gateway with NVIDIA NeMo Fabric." ---- -{/* SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -SPDX-License-Identifier: Apache-2.0 */} - -Use the `nvidia.fabric.openclaw` adapter to run an isolated OpenClaw Gateway -for one NeMo Fabric runtime or connect multiple runtimes to a shared Gateway. - -The following diagram shows the managed-runtime path, where the adapter configures and invokes an isolated OpenClaw Gateway: - -```mermaid -flowchart TB - Fabric["NeMo Fabric runtime"] -->|"Adapter contract
JSON over stdio"| Adapter["OpenClaw adapter"] - Adapter -->|"Start with normalized configuration"| Gateway["OpenClaw Gateway process"] - Adapter -->|"Invoke through OpenAI-compatible Chat Completions
over loopback HTTP"| Gateway - Gateway -->|"TypeScript"| Core["OpenClaw Gateway core"] - Core --> Native - - subgraph Selected["Selected OpenClaw runtime"] - Native["Native OpenClaw runtime"] - end -``` - -## Choose a Lifecycle - -Choose the lifecycle that matches who owns the Gateway: - -| Lifecycle | Gateway Ownership | Use Case | -| --- | --- | --- | -| Managed runtime | NeMo Fabric starts one Gateway for each runtime and stops it with the runtime. | Evaluation, benchmark runs, and other bounded jobs. | -| Prepared service | NeMo Fabric starts and supervises one Gateway that multiple runtimes can share. | Long-lived local deployments and OpenClaw chat channels. | -| Attached service | Another deployment system starts and supervises the Gateway; NeMo Fabric connects to it. | Existing or independently managed deployments. | - -## Install OpenClaw and the Adapter - -Refer to the official OpenClaw [installation documentation](https://docs.openclaw.ai/install) for detailed installation and usage instructions. - -To install OpenClaw from an npm package, then install the NeMo Fabric runtime and adapter run the following commands. - -```bash -# Requires Node.js >=24.22.1 <25 or >=26.12.1, and npm 11.16+ -npm install --global openclaw@2026.9.34 --allow-scripts=openclaw -pip install "nemo-fabric[openclaw]" -``` - -To install the adapter without the NeMo Fabric runtime, use -`nemo-fabric-adapters-openclaw`. The adapter package does not install OpenClaw. - -### Upgrade a Gateway With Retained State - -When upgrading a caller-owned Gateway from OpenClaw 2026.9.4, stop the Gateway and run `openclaw backup create --verify` with the Gateway's existing `OPENCLAW_STATE_DIR` and `OPENCLAW_CONFIG_PATH` before upgrading. The backup must include the active config, its include files, and all configured agent directories, including paths outside the state directory. Protect the archive because it can contain credentials. - -Before upgrading, check the backup result and manifest for the active config, its include files, and every configured agent directory. For paths marked `covered`, confirm that the archive contains the data under a parent directory. Fix missing required paths and rerun the backup. Continue with the upgrade after confirming that all required data is backed up. - -Before migration, copy every legacy session directory while the Gateway is stopped. Include `sessions.json`, `.jsonl` transcripts, and session directories outside `OPENCLAW_STATE_DIR`. The backup command excludes legacy `.jsonl` transcripts. Protect these copies and keep them with the verified archive for rollback. - -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, so each new Gateway starts with fresh state. - -## Configure the Adapter - -Select the adapter and, when necessary, specify the OpenClaw executable: - -```python -from nemo_fabric import HarnessConfig - -harness = HarnessConfig( - adapter_id="nvidia.fabric.openclaw", - settings={ - "openclaw_command": "/opt/openclaw/bin/openclaw", - "startup_timeout_seconds": 60, - }, -) -``` - -Omit `openclaw_command` to resolve `openclaw` from `PATH`. A relative path that -contains a directory is resolved from the NeMo Fabric base directory. The adapter -uses the resolved executable for its version check, configuration validation, -and Gateway startup. - -`startup_timeout_seconds` sets one deadline for all of start, from checking the -`openclaw` command to the Gateway becoming ready. It defaults to 60 seconds and -can be at most 75 seconds, which keeps start within NeMo Fabric's 90-second -start limit. - -The adapter supports only OpenClaw's default `openclaw` agent runtime. - -The adapter accepts normalized model provider, model, base URL, temperature, -`top_p`, `max_tokens`, replacement system instruction, workspace, skills, and -MCP configuration. Normalized MCP authentication is not supported. For a -custom OpenAI-compatible endpoint, set the model's `base_url` and, when needed, -`api_key_env`. - -For an endpoint that supports `stream_options.include_usage`, set -`models..settings.supports_usage_in_streaming` to `true`. This maps to -OpenClaw's native `compat.supportsUsageInStreaming` and requires `base_url`. -Use `false` for an endpoint that rejects streaming usage, or omit the setting -to retain OpenClaw's endpoint capability detection. Attached services own -their model configuration and do not accept this setting. - -OpenClaw 2026.9.4's Gateway does not distinguish aggregate usage from its -last-call fallback, and converts missing usage to zero counters. NeMo Fabric -leaves standard complete counters unknown and preserves the Gateway's counts -in `usage.extensions["nvidia.fabric.openclaw.usage_evidence.v1"].observed`. -The evidence includes `scope_unverified` in `gaps`, plus `missing_usage` or -`zero_unverified` when applicable. Reported counts do not establish complete -coverage of retries, compaction, child agents, or background work. - -For a NeMo Fabric-owned service, `harness.settings.channel_config` accepts -OpenClaw-native `channels` and `bindings`. This supports multiple accounts for -Telegram and other OpenClaw channels without a NeMo Fabric-specific channel schema. -Every binding must target the configured `agent_id`; OpenClaw validates the -nested channel settings. Chat-channel traffic goes directly between the -channel and OpenClaw rather than through a NeMo Fabric runtime. - -By default, the adapter chooses an available local port range. Set `port_range` -to an inclusive consumer-allocated range with `start` and `end` fields. The -range must span at least 111 ports. OpenClaw's [derived-port mapping](https://docs.openclaw.ai/gateway/multiple-gateways#port-mapping-derived) uses `base_port + 2` for browser control and allocates browser CDP ports from `base_port + 11` through `base_port + 110`. The adapter verifies only that `base_port` and `base_port + 2` are available before startup. OpenClaw allocates the CDP ports on demand instead of reserving the complete range, so the adapter cannot guarantee that those ports will still be available when OpenClaw needs them. Keep the configured range reserved for the lifetime of the runtime or service when using OpenClaw browser features. - -## Use a Shared Service - -Call `prepare_service()` to map the normalized `FabricConfig` to -`openclaw.json` and start a NeMo Fabric-owned Gateway. Pass the returned service -to `start_runtime()` to give each runtime an independent OpenClaw session: - -```python -from nemo_fabric import Fabric - - -async def invoke_with_prepared_service(config): - fabric = Fabric() - async with await fabric.prepare_service(config) as service: - async with await fabric.start_runtime(config, service=service) as runtime: - return await runtime.invoke(input="Review the workspace changes.") -``` - -Call `attach_service()` when another system owns the Gateway lifecycle. The -reference contains the endpoint and the name of an environment variable that -holds the Gateway token, never the token value: - -```python -from nemo_fabric import Fabric -from nemo_fabric import ServiceReference - - -async def invoke_with_attached_service(config): - reference = ServiceReference.from_mapping( - { - "adapter_id": "nvidia.fabric.openclaw", - "service_type": "openclaw_gateway", - "connection": { - "gateway_url": "https://openclaw.example.com", - "gateway_token_env": "OPENCLAW_GATEWAY_TOKEN", - "agent_id": "default", - }, - } - ) - - fabric = Fabric() - async with await fabric.attach_service(config, reference) as service: - async with await fabric.start_runtime(config, service=service) as runtime: - return await runtime.invoke(input="Review the workspace changes.") -``` - -The service handle contains sanitized identity and connection information and -is valid only in the NeMo Fabric process that created it. Releasing a prepared -service stops its Gateway. Releasing an attached service closes NeMo -Fabric-owned clients and private connection material without stopping the -caller-owned Gateway. Attached Gateways must use HTTPS unless the URL contains -a literal loopback IP address. For an attached service, omit deployment-owned -model endpoints, API-key references, tools, MCP servers, skills, channel -configuration, and startup settings from `config` because NeMo Fabric cannot -apply them to an existing Gateway. - -## Execution and Isolation - -Before starting a managed runtime or prepared service, the adapter writes a -complete temporary `openclaw.json` and sets OpenClaw environment variables. It -does not use the OpenClaw configuration RPC. The generated configuration: - -- binds the Gateway to loopback; -- enables the OpenAI-compatible Chat Completions endpoint; -- uses a cryptographically generated one-time Gateway token; -- applies the normalized workspace, model, skills, and MCP servers; -- disables OpenClaw anonymous telemetry; and -- uses a unique temporary state directory. - -Each invocation sends a terminal request to `/v1/chat/completions` with the -NeMo Fabric runtime ID as the stable OpenClaw session key. A managed runtime -stops its Gateway during runtime shutdown. A prepared service keeps its Gateway -running until the service is released, so multiple runtimes can connect to it. - -The adapter isolates the Gateway in its own process group, continuously checks -its startup endpoint, and forwards `SIGINT` and `SIGTERM` on POSIX systems. -On Linux, the adapter uses `setpriv --pdeathsig SIGTERM` when `setpriv` is -available and can run, so that the kernel signals the Gateway after abrupt -adapter termination. A sandbox that forbids applying capabilities, such as an -OpenShell sandbox, makes `setpriv` fail; the adapter then starts the Gateway -without it. Windows uses a kill-on-close Job Object for the Gateway process -tree. Without `setpriv`, Linux has the same catchable-signal protection as -macOS but cannot handle `SIGKILL`. - -Relay telemetry, native OpenTelemetry, adapter-native response streaming, -cancellation, and live updates are not supported. diff --git a/docs/integrations/harness/openclaw/openclaw-api.mdx b/docs/integrations/harness/openclaw/openclaw-api.mdx new file mode 100644 index 000000000..d5fc227e8 --- /dev/null +++ b/docs/integrations/harness/openclaw/openclaw-api.mdx @@ -0,0 +1,69 @@ +--- +title: "OpenClaw HTTP API" +description: "Send native HTTP requests to the managed OpenClaw Gateway." +--- +{/* SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: Apache-2.0 */} + +Start with the [OpenClaw overview](./openclaw.mdx) for installation and configuration ownership. + +## API Ownership + +The managed Gateway serves `/v1/chat/completions` by default for SDK invocation. Native HTTP clients can use the same endpoint; no separate API server or `interfaces.api` setting is needed. + +Enable either the dashboard or terminal interface so the adapter writes the Gateway address and access token to private connection files. For API-only use, configure the terminal interface: + +```python +from nemo_fabric import HarnessConfig + +harness = HarnessConfig( + adapter_id="nvidia.fabric.openclaw", + settings={"interfaces": {"terminal": {}}}, +) +``` + +Use this `harness` in your `FabricConfig` when starting the runtime. It starts the Gateway and publishes the connection files without requiring browser assets. The terminal client starts only when you run the generated launcher; HTTP clients can use the Gateway without launching it. + +When the Gateway is ready, the adapter writes its connection details to the private `interfaces/gateway.json` file: + +- `http_url`: the Gateway address for API requests. +- `agent_id`: the agent name to use in the request's `model` value. +- `token_file`: the name of the token file in the same directory. + +Read the token from that file and configure your HTTP client to send this header on every request: + +```http +Authorization: Bearer +``` + +## Requests and Conversations + +Send a `POST` request to `/v1/chat/completions` with these fields: + +- `model`: `openclaw/` followed by the `agent_id` from `gateway.json`. This selects the OpenClaw agent that handles the request. +- `messages`: the messages you want to send to the agent. +- `user`: a conversation name chosen by your HTTP client. + +For example, when `agent_id` is `default`, the request body can be: + +```json +{ + "model": "openclaw/default", + "user": "api-review-1", + "messages": [ + {"role": "user", "content": "Read notes.txt and summarize it."} + ] +} +``` + +Reuse `api-review-1` for follow-up requests in that conversation. Choose a new `user` value to start a new conversation. Include `user` explicitly on each request so you control which conversation receives it. + +Each SDK runtime uses its runtime ID as the `user` value. Choose a different value for HTTP requests to keep those conversations separate from the SDK conversation. Reusing the SDK value can direct HTTP requests into its native session. + +The Gateway uses the model endpoint and credentials generated from `FabricConfig`. It also supplies the configured system instructions, workspace, tools, MCP servers, skills, and supported generation defaults. Your HTTP client does not need to copy the system instructions into each request. + +Responses come directly from OpenClaw in its native HTTP format. If you request streaming, the stream also uses OpenClaw's native format. These calls do not produce SDK `RunResult` objects or NeMo Relay streams. + +## Testing and Boundaries + +Follow the [HTTP manual test](../../../../examples/interfaces/openclaw/README.md#2-http-api). Direct requests do not increment SDK invocation accounting. There is no ATIF/ATOF export in this iteration. Fabric runtime shutdown revokes discovery and stops the owned Gateway; a client cannot retain the runtime merely by staying connected. diff --git a/docs/integrations/harness/openclaw/openclaw-dashboard.mdx b/docs/integrations/harness/openclaw/openclaw-dashboard.mdx new file mode 100644 index 000000000..8fee346d2 --- /dev/null +++ b/docs/integrations/harness/openclaw/openclaw-dashboard.mdx @@ -0,0 +1,63 @@ +--- +title: "OpenClaw Dashboard" +description: "Use the native browser Control UI on the owned Gateway." +--- +{/* SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: Apache-2.0 */} + +Start with the [OpenClaw overview](./openclaw.mdx) for installation and shared configuration. + +## Additional Setup + +Install the pinned npm package with its packaged Control UI assets before runtime startup. Startup does not build browser assets or install dependencies. No second backend is needed when terminal or SDK access is also enabled. + +## Serve the Control UI + +OpenClaw's Control UI is its browser dashboard and chat. A managed runtime +serves it when `harness.settings.interfaces.dashboard` is present: + +```python +from nemo_fabric import HarnessConfig + +harness = HarnessConfig( + adapter_id="nvidia.fabric.openclaw", + settings={"interfaces": {"dashboard": {"port": 18789}}}, +) +``` + +- The Gateway listens on `127.0.0.1` at the dashboard `port`, which serves the + Control UI. `start` fails with `openclaw_interface_port_unavailable` if + `port` or `port + 2` is in use. OpenClaw also uses `port + 10` for its + browser relay and allocates browser CDP ports from `port + 11` through + `port + 110`, so reserve the whole range from `port` through `port + 110`. + `port` can't be combined with `port_range`; set `enabled` to `false` to keep + a configured dashboard off. +- After the Gateway starts, the adapter writes the sign-in token, generated at + each start, to + `/.fabric/openclaw/runtimes//interfaces/dashboard.token` + with mode `0600` on POSIX hosts; on Windows, the file inherits the artifact + root's permissions. `stop` removes it; if the adapter host is killed, the file + can remain. +- Open `http://127.0.0.1:/#token=` through a forward to that + port to sign in. The Control UI removes the token from the address bar. + OpenClaw 2026.9.34 accepts any loopback origin, such as a forward to a + different local port; the token is still required. +- Processes that run as the runtime's user, including the agent's own tools, + can read the token and reach the port. +- The adapter regenerates OpenClaw's configuration at each start and marks it + read-only, so changes made through the Control UI don't survive a restart. +- Prepared and attached services reject `interfaces` with + `openclaw_interfaces_require_managed_runtime`. + + +## Origins and Conversations + +`interfaces.dashboard.public_origins` adds explicit HTTP(S) origins to the native allowlist. Supply origins without paths, credentials, queries, or fragments. OpenClaw's loopback-origin exception still applies; the list does not restrict loopback access to only the configured ports. Authentication remains required. This setting does not change the loopback bind; remote access still needs forwarding or a proxy and native pairing where required. + +Select the configured agent and create or select a distinct chat for browser work. Browser tabs can select the same native session; opening another tab does not guarantee a fresh conversation. SDK and HTTP examples use their own stable selectors. + +## Health and Testing + +Native `/healthz`, `/startupz`, `/v1/models`, and `/readyz` observations feed Fabric's normalized checks. With browser or terminal access enabled, runtime activity remains `unknown` because SDK invocation state does not account for native work. Checks do not submit a model turn. + +Follow the [browser manual test](../../../../examples/interfaces/openclaw/README.md#3-browser-dashboard). NeMo Relay export is not supported. diff --git a/docs/integrations/harness/openclaw/openclaw-sdk.mdx b/docs/integrations/harness/openclaw/openclaw-sdk.mdx new file mode 100644 index 000000000..4813000be --- /dev/null +++ b/docs/integrations/harness/openclaw/openclaw-sdk.mdx @@ -0,0 +1,110 @@ +--- +title: "OpenClaw SDK" +description: "Invoke and manage OpenClaw through the NeMo Fabric SDK." +--- +{/* SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: Apache-2.0 */} + +Start with the [OpenClaw overview](./openclaw.mdx) for installation, shared configuration, and the four invocation paths. + +## SDK Execution + +Use the [Code Review Example](../../../../examples/code_review_agent/README.md) with `--variant openclaw`. The adapter sends requests to its managed Gateway's Chat Completions endpoint, preserving the runtime ID as the SDK conversation selector and returning a normalized `RunResult`. + +SDK-only configurations retain existing behavior. When native interfaces are enabled, the same Gateway adds the Fabric instruction through the shared plugin while retaining OpenClaw's native prompt and tool guidance. The SDK omits its separate instruction message in this mode to avoid duplication. Model, workspace, tools, MCP, and skills are generated once for that Gateway. SDK requests retain their configured generation parameters. Native turns do not create SDK invocation records. + +With browser or terminal access enabled, `Fabric.check()` reports activity as `unknown` because SDK invocation state does not cover work from native clients. A passing health check therefore does not establish that the Gateway is idle; callers that wait for `activity: idle` must handle this mode explicitly. SDK-only runtimes retain `idle`/`busy` reporting. See [health checks](../../../sdk/health-checks.mdx) for the shared contract. + +## Usage Accounting + +The adapter treats Gateway usage as observed evidence. Reported counts do not establish whether they cover aggregate usage or a last-call fallback, and zero counters do not prove that no usage occurred. + +NeMo Fabric leaves standard complete counters unknown and preserves reported counts in `usage.extensions["nvidia.fabric.openclaw.usage_evidence.v1"].observed`. The evidence includes `scope_unverified` in `gaps`, plus `missing_usage` or `zero_unverified` when applicable. + +These counts do not establish complete coverage of retries, compaction, child agents, or background work. For endpoint streaming-usage settings, see [Agent Configuration](./openclaw.mdx#agent-configuration). + +## Use a Shared Service + +Call `prepare_service()` to map the normalized `FabricConfig` to +`openclaw.json` and start a NeMo Fabric-owned Gateway. Pass the returned service +to `start_runtime()` to give each runtime an independent OpenClaw session: + +```python +from nemo_fabric import Fabric + + +async def invoke_with_prepared_service(config): + fabric = Fabric() + async with await fabric.prepare_service(config) as service: + async with await fabric.start_runtime(config, service=service) as runtime: + return await runtime.invoke(input="Review the workspace changes.") +``` + +Call `attach_service()` when another system owns the Gateway lifecycle. The +reference contains the endpoint and the name of an environment variable that +holds the Gateway token, never the token value: + +```python +from nemo_fabric import Fabric +from nemo_fabric import ServiceReference + + +async def invoke_with_attached_service(config): + reference = ServiceReference.from_mapping( + { + "adapter_id": "nvidia.fabric.openclaw", + "service_type": "openclaw_gateway", + "connection": { + "gateway_url": "https://openclaw.example.com", + "gateway_token_env": "OPENCLAW_GATEWAY_TOKEN", + "agent_id": "default", + }, + } + ) + + fabric = Fabric() + async with await fabric.attach_service(config, reference) as service: + async with await fabric.start_runtime(config, service=service) as runtime: + return await runtime.invoke(input="Review the workspace changes.") +``` + +The service handle contains sanitized identity and connection information and +is valid only in the NeMo Fabric process that created it. Releasing a prepared +service stops its Gateway. Releasing an attached service closes NeMo +Fabric-owned clients and private connection material without stopping the +caller-owned Gateway. Attached Gateways must use HTTPS unless the URL contains +a literal loopback IP address. For an attached service, omit deployment-owned +model endpoints, API-key references, tools, MCP servers, skills, channel +configuration, and startup settings from `config` because NeMo Fabric cannot +apply them to an existing Gateway. + +## Execution and Isolation + +Before starting a managed runtime or prepared service, the adapter writes a +complete temporary `openclaw.json` and sets OpenClaw environment variables. It +does not use the OpenClaw configuration RPC. The generated configuration: + +- binds the Gateway to loopback; +- enables the OpenAI-compatible Chat Completions endpoint; +- uses a cryptographically generated one-time Gateway token; +- applies the normalized workspace, model, skills, and MCP servers; +- disables OpenClaw anonymous telemetry; and +- uses a unique temporary state directory. + +Each invocation sends a terminal request to `/v1/chat/completions` with the +NeMo Fabric runtime ID as the stable OpenClaw session key. A managed runtime +stops its Gateway during runtime shutdown. A prepared service keeps its Gateway +running until the service is released, so multiple runtimes can connect to it. + +The adapter isolates the Gateway in its own process group, continuously checks +its startup endpoint, and forwards `SIGINT` and `SIGTERM` on POSIX systems. +On Linux, the adapter uses `setpriv --pdeathsig SIGTERM` when `setpriv` is +available and can run, so that the kernel signals the Gateway after abrupt +adapter termination. A sandbox that forbids applying capabilities, such as an +OpenShell sandbox, makes `setpriv` fail; the adapter then starts the Gateway +without it. Windows uses a kill-on-close Job Object for the Gateway process +tree. Without `setpriv`, Linux has the same catchable-signal protection as +macOS but cannot handle `SIGKILL`. + +Relay telemetry, native OpenTelemetry, adapter-native response streaming, +cancellation, and live updates are not supported. diff --git a/docs/integrations/harness/openclaw/openclaw-tui.mdx b/docs/integrations/harness/openclaw/openclaw-tui.mdx new file mode 100644 index 000000000..1566a6571 --- /dev/null +++ b/docs/integrations/harness/openclaw/openclaw-tui.mdx @@ -0,0 +1,61 @@ +--- +title: "OpenClaw Terminal TUI" +description: "Attach the native terminal renderer to the managed Gateway." +--- +{/* SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: Apache-2.0 */} + +Start with the [OpenClaw overview](./openclaw.mdx) for shared installation, configuration, and ownership. + +## Enable Terminal Access + +Complete the [shared installation](./openclaw.mdx#install-openclaw-and-the-adapter) first. Terminal access requires a POSIX host, an interactive terminal, and the supported OpenClaw and Node versions. The OpenClaw package includes the terminal UI; no separate frontend build is needed. + +Use this harness configuration when starting your managed runtime: + +```python +from nemo_fabric import HarnessConfig + +harness = HarnessConfig( + adapter_id="nvidia.fabric.openclaw", + settings={"interfaces": {"terminal": {}}}, +) +``` + +The adapter starts the Gateway and, once it is ready, creates an executable launcher at `/.fabric/openclaw/runtimes//interfaces/terminal`. The terminal connects to that Gateway, so there is no terminal port to configure. Browser assets are unnecessary when dashboard access is disabled. + +## Connect From a Terminal + +Run the generated `terminal` launcher from an interactive terminal. The [manual example](../../../../examples/interfaces/openclaw/README.md#4-terminal-tui) prints its full path as `terminal_launcher`. + +The launcher checks that the runtime's private connection files are valid and that the Gateway accepts its credential. It then starts `openclaw tui` with the correct Gateway address and token. Authentication is automatic; you do not need to paste a token. The credential is supplied through the environment and a private client configuration, rather than command-line arguments. Existing OpenClaw connection settings in your shell are cleared for this client so it connects to the selected runtime. + +For a runtime inside an OpenShell sandbox, run the launcher through a TTY-enabled sandbox command: + +```bash +openshell sandbox exec -n SANDBOX --tty -- /path/to/interfaces/terminal +``` + +Replace `SANDBOX` and the launcher path with your runtime's values. Local attachment has been tested; the OpenShell terminal transport remains unqualified in this prototype. + +## Choose a Conversation + +- Run the launcher without `--session` to start a new conversation on the configured agent. +- Add `--session manual-review` to open or continue that named conversation. Reuse the name when reconnecting to the same runtime. Session names cannot contain spaces or colons. +- Browser and terminal clients can join the same conversation when they explicitly select the same native session. Separate clients do not provide user isolation. + +Session names apply only to the configured agent and current runtime. + +## Disconnect and Check Runtime Health + +After a turn completes, enter `/quit` to close the terminal client. The Gateway keeps running, and SDK, HTTP, browser, and other terminal clients can continue using it. The pinned terminal client can return exit code 130 through its native shutdown fallback; that exit code alone does not mean the Gateway stopped. + +Stop the owning runtime to shut down the Gateway. The adapter removes `terminal.running` first, then the remaining connection files and credentials. + +`Fabric.check()` uses native Gateway endpoints to check health. With browser or terminal access enabled, activity is reported as `unknown` because the adapter cannot observe all interactive work. A passing health check does not establish that the runtime is idle. + +## Try It and Review Limitations + +Follow the [terminal manual test](../../../../examples/interfaces/openclaw/README.md#4-terminal-tui) to send input, continue a conversation, inspect output, and stop the runtime. + +Active-turn detach, interactive approvals, remote attachment, and complete native activity discovery still need qualification. NeMo Relay integration is deferred. diff --git a/docs/integrations/harness/openclaw/openclaw.mdx b/docs/integrations/harness/openclaw/openclaw.mdx new file mode 100644 index 000000000..0dde11b6b --- /dev/null +++ b/docs/integrations/harness/openclaw/openclaw.mdx @@ -0,0 +1,154 @@ +--- +title: "Use the OpenClaw Adapter" +description: "Four client paths through one managed OpenClaw Gateway." +--- +{/* SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: Apache-2.0 */} + +You can use OpenClaw through the NVIDIA NeMo Fabric adapter in four ways: + +- **[SDK](./openclaw-sdk.mdx):** invoke through the NeMo Fabric SDK and receive a normalized `RunResult`. +- **[HTTP API](./openclaw-api.mdx):** call the owned Gateway directly and receive its native HTTP response. +- **[Browser dashboard](./openclaw-dashboard.mdx):** use OpenClaw's native Control UI for chat and session management. +- **[Terminal TUI](./openclaw-tui.mdx):** attach OpenClaw's native terminal client to the running Gateway. + +![OpenClaw invocation paths](../../../../assets/openclaw-invocation-paths.png) + +## Shared Configuration + +All four paths execute through one OpenClaw Gateway and its native agent runtime. NeMo Fabric translates `FabricConfig` into one private `openclaw.json`, with a fresh state directory, configured model/endpoint/credential references, generation parameters, workspace, tool policy, MCP servers, and skill paths. + +When a native interface is enabled, a small adapter-owned plugin adds the configured instruction through OpenClaw's public `before_prompt_build` hook for the selected agent. It preserves OpenClaw's native system prompt, including tool guidance. SDK requests then omit their separate instruction injection, so each client receives the Fabric instruction once. SDK-only and service configurations retain their existing system-message handling. + +The adapter's existing `replace` mode selects the Fabric-provided instruction; it does not replace OpenClaw's internal system prompt. Omitted instructions preserve native behavior; `append` remains unsupported. + +Before publishing native connection files, startup makes an authenticated, model-free check that the loaded plugin's registered hook supplies the instruction for the selected agent. Missing, blocked, or mismatched hooks fail startup with `openclaw_shared_configuration_unavailable`. This startup check is separate from normalized runtime health checks. + +The generated configuration is read-only. Native clients share the configured backend but keep separate conversations when they select different native sessions. Filesystem access and Gateway credentials are shared within the runtime; this is not a user-isolation boundary. Native session/model overrides are not qualified; shared defaults do not enforce immutable policy. Native reconfiguration controls do not provide a supported way to change the Fabric-owned configuration. + +## Ownership and Normalization + +The adapter host starts, checks, and stops one Gateway. The SDK remains available when browser or terminal clients are enabled; no separate embedded SDK agent or additional API/TUI server is created. Attaching or detaching a client does not start or stop the Gateway. + +| Surface | Behavior | +| --- | --- | +| Configuration | Shared Fabric translation for the selected managed agent across all four paths. | +| Lifecycle | Fabric owns the managed Gateway; clients attach independently. | +| Responses | SDK returns a normalized `RunResult`; HTTP, browser, and terminal responses remain native. | +| Activity | With native interfaces enabled, activity is `unknown`; healthy native endpoints can still pass normalized health checks. | +| Relay artifacts | NeMo Relay integration and ATIF/ATOF export are deferred. | + +Native interfaces are opt-in and supported only on managed runtimes. Prepared and attached services retain their existing SDK lifecycle and reject `interfaces`; refer to the [SDK guide](./openclaw-sdk.mdx#use-a-shared-service). Cold resume and prior-runtime conversation restoration are outside this feature. + +## Install OpenClaw and the Adapter + +Refer to the official OpenClaw [installation documentation](https://docs.openclaw.ai/install) for detailed installation and usage instructions. + +To install OpenClaw from an npm package, then install the NeMo Fabric runtime and adapter run the following commands. + +```bash +# Requires Node.js >=24.22.1 <25 or >=26.12.1, and npm 11.16+ +npm install --global openclaw@2026.9.34 --allow-scripts=openclaw +pip install "nemo-fabric[openclaw]" +``` + +To install the adapter without the NeMo Fabric runtime, use +`nemo-fabric-adapters-openclaw`. The adapter package does not install OpenClaw. + +### Upgrade a Gateway With Retained State + +When upgrading a caller-owned Gateway from OpenClaw 2026.9.4, stop the Gateway and run `openclaw backup create --verify` with the Gateway's existing `OPENCLAW_STATE_DIR` and `OPENCLAW_CONFIG_PATH` before upgrading. The backup must include the active config, its include files, and all configured agent directories, including paths outside the state directory. Protect the archive because it can contain credentials. + +Before upgrading, check the backup result and manifest for the active config, its include files, and every configured agent directory. For paths marked `covered`, confirm that the archive contains the data under a parent directory. Fix missing required paths and rerun the backup. Continue with the upgrade after confirming that all required data is backed up. + +Before migration, copy every legacy session directory while the Gateway is stopped. Include `sessions.json`, `.jsonl` transcripts, and session directories outside `OPENCLAW_STATE_DIR`. The backup command excludes legacy `.jsonl` transcripts. Protect these copies and keep them with the verified archive for rollback. + +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, so each new Gateway starts with fresh state. + +## Configure the Adapter + +### Runtime Startup + +Select the adapter and, when necessary, specify the OpenClaw executable: + +```python +from nemo_fabric import HarnessConfig + +harness = HarnessConfig( + adapter_id="nvidia.fabric.openclaw", + settings={ + "openclaw_command": "/opt/openclaw/bin/openclaw", + "startup_timeout_seconds": 60, + }, +) +``` + +| Harness Setting | Behavior | +| --- | --- | +| `openclaw_command` | Omit to find `openclaw` on `PATH`. A relative path containing a directory is resolved from the NeMo Fabric base directory. The same executable is used for version checks, configuration validation, and Gateway startup. | +| `startup_timeout_seconds` | One deadline covering the executable check through Gateway readiness. Defaults to 60 seconds; maximum 75 seconds, within NeMo Fabric's 90-second start limit. | + +The adapter supports OpenClaw's default `openclaw` execution runtime. + +### Agent Configuration + +`harness.settings.agent_id` defaults to `default`. Use 1–64 ASCII letters, digits, underscores, or hyphens, starting with a letter or digit. IDs are case-insensitive; invalid IDs are rejected instead of relying on native character replacement or truncation. + +Set model provider, model, endpoint, generation parameters (`temperature`, `top_p`, and `max_tokens`), replacement system instructions, workspace, skills, and MCP servers through normalized `FabricConfig`. See [Shared Configuration](#shared-configuration) for how these settings reach all four client paths. Normalized MCP authentication is not supported. + +For a custom OpenAI-compatible endpoint, set the model's `base_url` and, when credentials are required, `api_key_env`. + +The optional `models..settings.supports_usage_in_streaming` setting controls OpenClaw's native `compat.supportsUsageInStreaming`: + +- Set `true` when the endpoint supports `stream_options.include_usage`. +- Set `false` when the endpoint rejects streaming usage. +- Omit it to retain OpenClaw's endpoint capability detection. + +This setting requires `base_url`. Attached services own their model configuration and do not accept it. Reported usage has separate completeness limits; see [SDK Usage Accounting](./openclaw-sdk.mdx#usage-accounting). + +### Gateway Ports + +By default, the adapter selects a local Gateway port range. To allocate the range yourself, set `port_range` with inclusive `start` and `end` values spanning at least 111 ports. + +OpenClaw's [derived-port mapping](https://docs.openclaw.ai/gateway/multiple-gateways#port-mapping-derived) uses: + +| Purpose | Port | +| --- | --- | +| Gateway | Selected base port | +| Browser control | Base port + 2 | +| Browser CDP connections | Base port + 11 through base port + 110 | + +Startup checks availability of the base port and base port + 2. OpenClaw allocates CDP ports on demand, so startup does not reserve or guarantee the rest of the range. Keep the full range reserved for the runtime or service lifetime when using browser features. + +For an exact dashboard base port, use the [native interface settings](#select-native-interfaces) instead of `port_range`. + +### Chat Channels + +For a [NeMo Fabric-owned service](./openclaw-sdk.mdx#use-a-shared-service), `harness.settings.channel_config` accepts OpenClaw-native `channels` and `bindings`, including multiple accounts for Telegram and other channels. + +Every binding must target the configured `agent_id`. OpenClaw validates the nested channel settings. Channel traffic flows directly between the channel and OpenClaw; it does not pass through a NeMo Fabric runtime. + +## Select Native Interfaces + +An absent interface is off. A present interface is enabled unless `enabled` is `false`: + +```python +settings = { + "interfaces": { + "dashboard": {"port": 18789, "public_origins": []}, + "terminal": {}, + } +} +``` + +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 `/.fabric/openclaw/runtimes//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 + +Follow the [four-path OpenClaw examples](../../../../examples/interfaces/openclaw/README.md) for repeatable manual tests. The opt-in native qualification uses a recording model endpoint, a rendered browser, and a PTY to verify actual configuration and tool execution. + +Terminal attachment currently requires POSIX. On Windows, dashboard tokens inherit directory ACLs; mode bits do not enforce owner-only ACLs. Interactive approvals, detach during active work, remote terminal attachment, and full native activity/inventory are not qualified. The pinned TUI can use an exit-code-130 fallback during `/quit`; this does not stop the managed Gateway. NeMo Relay integration and trajectory export remain separate work. diff --git a/docs/integrations/harness/overview.mdx b/docs/integrations/harness/overview.mdx index 7b53b29d4..4a2c517c1 100644 --- a/docs/integrations/harness/overview.mdx +++ b/docs/integrations/harness/overview.mdx @@ -25,7 +25,7 @@ NeMo Fabric includes the following harness integrations: | Kiro | [Use the Kiro adapter](./kiro.mdx) | | AWS Strands | [Use the Strands adapter](./strands.mdx) | | mini-SWE-agent | [Use the mini-SWE-agent adapter](./mini-swe-agent.mdx) | -| OpenClaw | [Use the OpenClaw adapter](./openclaw.mdx) | +| OpenClaw | [Use the OpenClaw adapter](./openclaw/openclaw.mdx) | | OpenHands | [Use the OpenHands adapter](./openhands.mdx) | | OpenCode | [Use the OpenCode adapter](./opencode.mdx) | | Pi | [Use the Pi adapter](./pi.mdx) | diff --git a/docs/sdk/health-checks.mdx b/docs/sdk/health-checks.mdx index 0ddb76e04..fab7e2d26 100644 --- a/docs/sdk/health-checks.mdx +++ b/docs/sdk/health-checks.mdx @@ -60,8 +60,8 @@ The table covers all runtime adapters and the OpenClaw Gateway service. Each row | Adapter | `live` Evidence | `active` Evidence | `ready` Evidence | Qualification Tests / Capability Evidence | | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | [Pi](../integrations/harness/pi.mdx) | Completed initialization, unchanged native session identity, and a fresh `extensionRunner.createContext().isIdle()` response; idle and busy both pass. | Completed extension binding and an available native request interface after liveness passes. | The selected model remains configured, required tools remain available, and required MCP transports have no observed error or closure. | [Tests](https://github.com/NVIDIA/NeMo-Fabric/blob/66341998b2e954a008cc7f726be64020adc3d1f4/tests/e2e/test_checks.py) | -| [OpenClaw Runtime](../integrations/harness/openclaw.mdx) | Valid `GET /healthz` response; an owned Gateway process must also remain running. | `GET /startupz` confirms startup, authenticated `GET /v1/models` includes the selected agent, and `GET /v1/chat/completions` returns the expected `405` with `Allow: POST`. | `GET /readyz` reports `ready: true`, including configured channel health. | [Tests](https://github.com/NVIDIA/NeMo-Fabric/blob/66341998b2e954a008cc7f726be64020adc3d1f4/tests/e2e/test_openclaw_checks.py) | -| [OpenClaw Gateway Service](../integrations/harness/openclaw.mdx) | Valid `GET /healthz` response. | Authenticated `GET /v1/models` returns a valid inventory. | `GET /readyz` reports native Gateway readiness, including configured channel health. | [Tests](https://github.com/NVIDIA/NeMo-Fabric/blob/66341998b2e954a008cc7f726be64020adc3d1f4/tests/e2e/test_openclaw_checks.py) | +| [OpenClaw Runtime](../integrations/harness/openclaw/openclaw.mdx) | Valid `GET /healthz` response; an owned Gateway process must also remain running. | `GET /startupz` confirms startup, authenticated `GET /v1/models` includes the selected agent, and `GET /v1/chat/completions` returns the expected `405` with `Allow: POST`. | `GET /readyz` reports `ready: true`, including configured channel health. | [Tests](https://github.com/NVIDIA/NeMo-Fabric/blob/66341998b2e954a008cc7f726be64020adc3d1f4/tests/e2e/test_openclaw_checks.py) | +| [OpenClaw Gateway Service](../integrations/harness/openclaw/openclaw.mdx) | Valid `GET /healthz` response. | Authenticated `GET /v1/models` returns a valid inventory. | `GET /readyz` reports native Gateway readiness, including configured channel health. | [Tests](https://github.com/NVIDIA/NeMo-Fabric/blob/66341998b2e954a008cc7f726be64020adc3d1f4/tests/e2e/test_openclaw_checks.py) | | [Codex](../integrations/harness/codex.mdx) | The owned app-server process has not exited. | A fresh native thread read confirms that the selected thread is loaded. | The fresh thread response reports `idle` or `active`; `systemError` fails readiness. | [Tests](https://github.com/NVIDIA/NeMo-Fabric/blob/86c52264d6e2ecfe7f72f1eb0161f1d1e425ddbb/tests/e2e/test_codex_checks.py) | | [Claude Code](../integrations/harness/claude.mdx) | The owned Claude CLI process has not exited. | A fresh, valid native `get_mcp_status()` response. | The same native status operation establishes initialized CLI responsiveness. Reported MCP connection failures do not themselves fail readiness. | [Tests](https://github.com/NVIDIA/NeMo-Fabric/blob/563ca53755f1a2f57329a79985095acfcfcd5cde/tests/e2e/test_claude_checks.py) | | [LangChain Deep Agents](../integrations/harness/deepagents.mdx) | A fresh read from the owned checkpoint connection with `SELECT 1`. | The compiled graph exposes its message input schema and invocation interface. | Native `aget_state()` returns valid state for the exact owned LangGraph thread. | [Tests](https://github.com/NVIDIA/NeMo-Fabric/blob/5c065c1a7775e4490269f57b406635d30e8a0fd8/tests/e2e/test_deepagents_checks.py) | diff --git a/examples/README.md b/examples/README.md index 265d780ba..5703385db 100644 --- a/examples/README.md +++ b/examples/README.md @@ -50,7 +50,7 @@ The [OpenShell Code Review example](code_review_agent/README.md#run-hermes-in-op ## Native Interfaces -[`interfaces`](interfaces/README.md) demonstrates native harness interfaces alongside a Fabric-managed runtime. Start with the Hermes API example: submit a file task through the native API, verify the generated file, and inspect Relay ATOF events and ATIF tool steps. +The [native interface examples](interfaces/README.md) are organized by harness. Each harness README provides setup, runnable commands, and manual checks for its supported interfaces. ## LangGraph Custom Agent diff --git a/examples/interfaces/README.md b/examples/interfaces/README.md index 31dea54b8..c661e0318 100644 --- a/examples/interfaces/README.md +++ b/examples/interfaces/README.md @@ -3,94 +3,11 @@ SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All SPDX-License-Identifier: Apache-2.0 --> -# NVIDIA NeMo Fabric Native Interface Examples +# NVIDIA NeMo Fabric Interface Examples -This example is a work in progress. Its structure and user experience will be reworked as part of OpenClaw TUI support. +Choose a harness for its setup instructions, runnable examples, and manual tests: -Use native harness interfaces alongside a NeMo Fabric-managed runtime. Each harness example uses the public Python SDK for configuration and lifecycle, then sends input through the harness's native interface. +- [Hermes](hermes/README.md) +- [OpenClaw](openclaw/README.md) -## Hermes API and Relay - -[`hermes.py`](hermes.py) starts one managed Hermes API server, submits a real file task, verifies the generated file, and checks Relay ATOF events and ATIF tool steps. Its API response remains native; the SDK manages the runtime but does not convert this response into a NeMo Fabric `RunResult`. - -### Prepare the Environment - -Follow the [Hermes adapter installation guide](../../docs/integrations/harness/hermes.mdx#install-the-adapter). For source development, run from the repository root: - -```bash -just install-hermes-agent -export ADAPTER_PYTHON="$PWD/.venv-hermes/bin/python" -``` - -This prepares pinned Hermes v0.22.5, the adapter, and Relay 0.10. The application interpreter also needs the NeMo Fabric SDK. The command below uses the prepared Hermes environment for both application and adapter. - -Set your OpenAI-compatible model endpoint, served model name, and credential: - -```bash -export MODEL_BASE_URL="https://MODEL_HOST/v1" -export MODEL_NAME="YOUR_SERVED_MODEL_NAME" -export MODEL_API_KEY="YOUR_MODEL_API_KEY" -``` - -Use HTTPS for remote endpoints that receive credentials. For a local server, use a loopback URL such as `http://127.0.0.1:8000/v1`; an authenticated encrypted tunnel is another option. Use the credential value required by your endpoint. An endpoint without authentication can use a nonempty placeholder credential. To reference an existing credential variable instead, pass its name with `--api-key-env`. - -### Run a Real Task - -Run the example from the repository root: - -```bash -.venv-hermes/bin/python examples/interfaces/hermes.py \ - --base-url "$MODEL_BASE_URL" \ - --model "$MODEL_NAME" \ - --port 8642 -``` - -The example copies sample release notes into a new workspace, asks the native API to read them and write a rollout checklist, and stops the runtime. To use your own notes, add `--input-file /path/to/release-notes.md`. `--output-dir` selects a new evidence directory; the example refuses to overwrite an existing directory. `--keep-running` leaves the API available for additional requests until you press Enter. - -The model and port must be reachable from the adapter environment. The native API binds to loopback and uses a generated bearer token; the example reads the token file and sends the header without printing the token. - -The example prints its evidence directory and checks that: - -- The output file exists and is nonempty. -- ATOF records show `read_file` and `write_file` execution. -- A populated ATIF trajectory contains those tool steps. -- Stop removes the API token. - -It exits unsuccessfully if any check fails. An ATOF file alone does not establish ATIF export. - -### Inspect the Result and Trajectory - -Set `RUN_DIR` to the evidence directory printed by the example: - -```bash -RUN_DIR="outputs/interfaces/" -cat "$RUN_DIR/workspace/rollout-checklist.md" -jq . "$RUN_DIR/summary.json" - -ATIF=$(jq -r '.atif_files[0]' "$RUN_DIR/summary.json") -jq -r '.steps[] | - [.step_id, .source, ((.tool_calls // []) | map(.function_name) | join(","))] | - @tsv' "$ATIF" -``` - -For this task, expect user input, an agent `read_file` step with its observation, an agent `write_file` step with its observation, and a final response. Inspect complete tool arguments and observations with: - -```bash -jq '.steps[] | select(.tool_calls != null) | - {tool_calls, observation}' "$ATIF" -``` - -To inspect the raw event sequence: - -```bash -ATOF=$(jq -r '.atof_files[0]' "$RUN_DIR/summary.json") -jq -r 'select(.kind == "scope" and - (.category == "llm" or .category == "tool")) | - [.timestamp, .scope_category, .category, .name] | @tsv' "$ATOF" -``` - -### ATIF Finalization and Limits - -The pinned Hermes API path leaves its Relay conversation scope open after a turn. ATOF events can therefore exist without ATIF export. The managed native launcher finalizes and flushes an API turn's Relay segment when execution returns, including failed turns. It does not fire native conversation-end plugin hooks or delete conversation state. The conversation can continue; subsequent turns create new Relay segments and ATIF files. Finalization errors are logged without replacing the execution outcome, so consumers should check their artifacts explicitly. - -This example exercises the managed API path. It does not qualify browser chat, TUI, independently restarted gateways, approvals, or complete native-result and artifact normalization. Refer to [Hermes Native Interfaces](../../docs/integrations/harness/hermes-interfaces.mdx) for the configuration and ownership boundaries. +Run commands from the repository root unless the harness README says otherwise. diff --git a/examples/interfaces/hermes/README.md b/examples/interfaces/hermes/README.md new file mode 100644 index 000000000..915ad1026 --- /dev/null +++ b/examples/interfaces/hermes/README.md @@ -0,0 +1,94 @@ + + +# NVIDIA NeMo Fabric Hermes Interface Examples + +Start with the [Hermes architecture guide](../../../docs/integrations/harness/hermes.mdx) for installation and SDK configuration, then see [native interfaces](../../../docs/integrations/harness/hermes-interfaces.mdx) for shared configuration and process ownership. This example tests the native HTTP API using a Fabric-managed runtime and translated Fabric configuration. SDK responses are normalized; API responses remain native. NeMo Relay provides ATOF events and ATIF trajectories. + +## Hermes API and Relay + +[`hermes.py`](hermes.py) starts one managed Hermes API server, submits a real file task, verifies the generated file, and checks Relay ATOF events and ATIF tool steps. Its API response remains native; the SDK manages the runtime but does not convert this response into a NeMo Fabric `RunResult`. + +### Prepare the Environment + +Follow the [Hermes adapter installation guide](../../../docs/integrations/harness/hermes.mdx#install-the-adapter). For source development, run from the repository root: + +```bash +just install-hermes-agent +export ADAPTER_PYTHON="$PWD/.venv-hermes/bin/python" +``` + +This prepares pinned Hermes v0.22.5, the adapter, and Relay 0.10. The application interpreter also needs the NeMo Fabric SDK. The command below uses the prepared Hermes environment for both application and adapter. + +Set your OpenAI-compatible model endpoint, served model name, and credential: + +```bash +export MODEL_BASE_URL="https://MODEL_HOST/v1" +export MODEL_NAME="YOUR_SERVED_MODEL_NAME" +export MODEL_API_KEY="YOUR_MODEL_API_KEY" +``` + +Use HTTPS for remote endpoints that receive credentials. For a local server, use a loopback URL such as `http://127.0.0.1:8000/v1`; an authenticated encrypted tunnel is another option. Use the credential value required by your endpoint. An endpoint without authentication can use a nonempty placeholder credential. To reference an existing credential variable instead, pass its name with `--api-key-env`. + +### Run a Real Task + +Run the example from the repository root: + +```bash +.venv-hermes/bin/python examples/interfaces/hermes/hermes.py \ + --base-url "$MODEL_BASE_URL" \ + --model "$MODEL_NAME" \ + --port 8642 +``` + +The example copies sample release notes into a new workspace, asks the native API to read them and write a rollout checklist, and stops the runtime. To use your own notes, add `--input-file /path/to/release-notes.md`. `--output-dir` selects a new evidence directory; the example refuses to overwrite an existing directory. `--keep-running` leaves the API available for additional requests until you press Enter. + +The model and port must be reachable from the adapter environment. The native API binds to loopback and uses a generated bearer token; the example reads the token file and sends the header without printing the token. + +The example prints its evidence directory and checks that: + +- The output file exists and is nonempty. +- ATOF records show `read_file` and `write_file` execution. +- A populated ATIF trajectory contains those tool steps. +- Stop removes the API token. + +It exits unsuccessfully if any check fails. An ATOF file alone does not establish ATIF export. + +### Inspect the Result and Trajectory + +Set `RUN_DIR` to the evidence directory printed by the example: + +```bash +RUN_DIR="outputs/interfaces/" +cat "$RUN_DIR/workspace/rollout-checklist.md" +jq . "$RUN_DIR/summary.json" + +ATIF=$(jq -r '.atif_files[0]' "$RUN_DIR/summary.json") +jq -r '.steps[] | + [.step_id, .source, ((.tool_calls // []) | map(.function_name) | join(","))] | + @tsv' "$ATIF" +``` + +For this task, expect user input, an agent `read_file` step with its observation, an agent `write_file` step with its observation, and a final response. Inspect complete tool arguments and observations with: + +```bash +jq '.steps[] | select(.tool_calls != null) | + {tool_calls, observation}' "$ATIF" +``` + +To inspect the raw event sequence: + +```bash +ATOF=$(jq -r '.atof_files[0]' "$RUN_DIR/summary.json") +jq -r 'select(.kind == "scope" and + (.category == "llm" or .category == "tool")) | + [.timestamp, .scope_category, .category, .name] | @tsv' "$ATOF" +``` + +### ATIF Finalization and Limits + +The pinned Hermes API path leaves its Relay conversation scope open after a turn. ATOF events can therefore exist without ATIF export. The managed native launcher finalizes and flushes an API turn's Relay segment when execution returns, including failed turns. It does not fire native conversation-end plugin hooks or delete conversation state. The conversation can continue; subsequent turns create new Relay segments and ATIF files. Finalization errors are logged without replacing the execution outcome, so consumers should check their artifacts explicitly. + +This example exercises the managed API path. It does not qualify browser chat, TUI, independently restarted gateways, approvals, or complete native-result and artifact normalization. Refer to [Hermes Native Interfaces](../../../docs/integrations/harness/hermes-interfaces.mdx) for the configuration and ownership boundaries. diff --git a/examples/interfaces/hermes.py b/examples/interfaces/hermes/hermes.py similarity index 100% rename from examples/interfaces/hermes.py rename to examples/interfaces/hermes/hermes.py diff --git a/examples/interfaces/openclaw/README.md b/examples/interfaces/openclaw/README.md new file mode 100644 index 000000000..16c0364bf --- /dev/null +++ b/examples/interfaces/openclaw/README.md @@ -0,0 +1,109 @@ + + +# NVIDIA NeMo Fabric OpenClaw Interface Examples + +Start with the [OpenClaw architecture guide](../../../docs/integrations/harness/openclaw/openclaw.mdx). These four paths share one managed Gateway, its selected agent, and translated Fabric configuration. SDK responses are normalized; other responses remain native. NeMo Relay integration and trajectory export are deferred. + +| Path | Example | Architecture | +| --- | --- | --- | +| SDK | [Code Review Example](../../code_review_agent/README.md) with `--variant openclaw` | [SDK](../../../docs/integrations/harness/openclaw/openclaw-sdk.mdx) | +| HTTP | `openclaw.py --http-input ... --once` | [HTTP API](../../../docs/integrations/harness/openclaw/openclaw-api.mdx) | +| Browser | `openclaw.py --interface dashboard`, then native chat | [Dashboard](../../../docs/integrations/harness/openclaw/openclaw-dashboard.mdx) | +| Terminal | `openclaw.py --interface terminal`, then generated launcher | [Terminal TUI](../../../docs/integrations/harness/openclaw/openclaw-tui.mdx) | + +## Shared Setup + +Run all commands from the repository root. Install pinned OpenClaw `2026.9.34` with Node `>=24.22.1 <25` or `>=26.12.1` and npm `11.16+`: + +```bash +npm install --global openclaw@2026.9.34 --allow-scripts=openclaw +openclaw --version +uv sync --frozen --no-default-groups --group adapters --group adapter-tests --group test +export ADAPTER_PYTHON="${ADAPTER_PYTHON:-$PWD/.venv/bin/python}" +export MODEL_BASE_URL="https://MODEL_HOST/v1" +export MODEL_NAME="YOUR_SERVED_MODEL_NAME" +export MODEL_API_KEY="YOUR_MODEL_API_KEY" +``` + +The npm package provides browser and terminal assets; these tests do not build frontends. The model endpoint must be reachable from the adapter and support OpenAI-compatible Chat Completions with file-tool calls. Use a nonempty placeholder only if the endpoint does not require authentication. A separately selected adapter interpreter must contain this checkout's adapter and dependencies. + +Use a new output directory for each run; the example refuses to overwrite one. `--openclaw-command /path/to/openclaw` selects a separately prepared pinned executable. Use `--api-key-env NAME` when your credential uses another environment variable. No command prints the Gateway token. + +## 1. SDK + +Follow the [Code Review Example](../../code_review_agent/README.md) with `--variant openclaw`. To compare an SDK turn with the native clients in this example, add `--sdk-input 'Read notes.txt and write sdk-result.md with a short checklist.'` to an owner command below. The result is saved as `sdk-result.json`. + +## 2. HTTP API + +Run a real file task, then stop the owner automatically: + +```bash +export RUN_DIR="$PWD/outputs/interfaces/openclaw-http-$(date +%Y%m%d-%H%M%S)" +.venv/bin/python examples/interfaces/openclaw/openclaw.py \ + --base-url "$MODEL_BASE_URL" --model "$MODEL_NAME" \ + --interface terminal --output-dir "$RUN_DIR" \ + --http-input 'Read notes.txt and write api-result.md with a short checklist.' --once +cat "$RUN_DIR/workspace/api-result.md" +cat "$RUN_DIR/http-result.json" +cat "$RUN_DIR/cleanup.json" +``` + +Terminal selection publishes private Gateway connection material without enabling the browser. This command does not launch the terminal client. The HTTP request uses that Gateway, an independent stable `user`, and the configured agent. Inspect a native HTTP response and confirm all cleanup fields are true. There is no additional API server or API port setting. + +## 3. Browser Dashboard + +In the owner terminal, choose an available Gateway base port and keep the owner running: + +```bash +export RUN_DIR="$PWD/outputs/interfaces/openclaw-browser-$(date +%Y%m%d-%H%M%S)" +.venv/bin/python examples/interfaces/openclaw/openclaw.py \ + --base-url "$MODEL_BASE_URL" --model "$MODEL_NAME" \ + --interface dashboard --port 18789 --output-dir "$RUN_DIR" +``` + +Open the printed `http_url` in a browser. Read the printed token-file path privately and enter its value in the native Control UI sign-in field, or use OpenClaw's native token-fragment sign-in flow. The token authenticates to this Gateway; it is not the model API key. Select agent `reviewer` and create a distinct chat. + +Send `Read notes.txt and write browser-result.md with a short checklist.` After completion, send `Read browser-result.md and add one verification step.` + +In another terminal, set `RUN_DIR` to the same output directory used by the owner. Use the parent directory of the `workspace` path printed by the owner, replacing the placeholder below with that exact path: + +```bash +export RUN_DIR="/absolute/path/to/openclaw-browser-YYYYMMDD-HHMMSS" +cat "$RUN_DIR/workspace/browser-result.md" +``` + +Press Enter in the owner terminal to stop. Check `cleanup.json` and confirm the browser can no longer submit work. Browser tabs share a native session when they select the same chat; another tab does not guarantee isolation. + +## 4. Terminal TUI + +In the owner terminal: + +```bash +export RUN_DIR="$PWD/outputs/interfaces/openclaw-terminal-$(date +%Y%m%d-%H%M%S)" +.venv/bin/python examples/interfaces/openclaw/openclaw.py \ + --base-url "$MODEL_BASE_URL" --model "$MODEL_NAME" \ + --interface terminal --output-dir "$RUN_DIR" +``` + +In another terminal, run the exact `terminal_launcher` path printed by the owner. Terminal attachment requires POSIX and a real TTY. The launcher reads private credentials and attaches to the owned Gateway; it does not start another backend. It has no port argument. Add `--session manual-review` to the launcher to intentionally reuse that conversation on agent `reviewer`; omit it for a new session. + +Send `Read notes.txt and write terminal-result.md with a short checklist.` Follow with `Read terminal-result.md and add one verification step.` Inspect the output, then enter `/quit`. The owner should remain usable; press Enter there when finished. The pinned native client can exit with code 130 through its own disconnect fallback. Verify Gateway survival separately from that native exit status. + +Use `--interface both --port 18789` on the owner to attach browser and terminal concurrently to one Gateway. Select distinct chats unless you intend to share a live conversation. + +## Automated Native Qualification + +The ordinary OpenClaw tests use a deterministic mock executable. The opt-in native tests use the pinned Gateway, a recording model endpoint, actual file tools and MCP, a real browser, and a terminal PTY: + +```bash +uv pip install --python .venv/bin/python playwright pexpect +.venv/bin/python -m playwright install chromium +export FABRIC_OPENCLAW_TEST_COMMAND="$(command -v openclaw)" +mkdir -p outputs/interfaces +.venv/bin/python -m pytest tests/adapters/test_openclaw_native.py -q --basetemp outputs/interfaces/openclaw-native-tests +``` + +Use a fresh `--basetemp` directory: pytest removes an existing one. `FABRIC_TEST_CHROMIUM` can select an already installed browser executable. Retained evidence includes captured model requests, a browser screenshot, a terminal transcript, and native skill inventory. Credentials used by the recorder are test placeholders. These tests assert actual endpoint/model/parameter/prompt parity, workspace/tool policy, MCP execution, skills, conversation behavior, health, and cleanup; they do not assert Relay trajectories. diff --git a/examples/interfaces/openclaw/openclaw.py b/examples/interfaces/openclaw/openclaw.py new file mode 100644 index 000000000..8376bc5a1 --- /dev/null +++ b/examples/interfaces/openclaw/openclaw.py @@ -0,0 +1,186 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Host one configured OpenClaw Gateway for SDK, HTTP, browser, and terminal clients.""" + +from __future__ import annotations + +import argparse +import asyncio +import json +import os +import sys +from pathlib import Path + +import httpx +from nemo_fabric import Fabric, FabricConfig + + +def build_config(args: argparse.Namespace, output: Path) -> FabricConfig: + """Prepare a shared file-task workspace and explicitly selected native clients.""" + workspace = output / "workspace" + workspace.mkdir(parents=True) + (workspace / "notes.txt").write_text( + "Release checklist: verify shared model configuration, file tools, and Gateway cleanup.\n" + ) + interfaces = {} + if args.interface in {"terminal", "both"}: + interfaces["terminal"] = {} + if args.interface in {"dashboard", "both"}: + interfaces["dashboard"] = { + "port": args.port, + "public_origins": args.public_origin, + } + settings = {"agent_id": "reviewer", "interfaces": interfaces} + if args.openclaw_command: + settings["openclaw_command"] = args.openclaw_command + return FabricConfig.from_mapping( + { + "metadata": {"name": "openclaw-interfaces-example"}, + "harness": {"adapter_id": "nvidia.fabric.openclaw", "settings": settings}, + "models": { + "default": { + "provider": "fabric-model", + "model": args.model, + "base_url": args.base_url, + "api_key_env": args.api_key_env, + "temperature": 0.0, + "top_p": 0.9, + "max_tokens": 2048, + } + }, + "instructions": { + "system": { + "mode": "replace", + "content": "Complete workspace tasks using the read and write tools. Read source files before writing. " + "Use paths relative to the workspace. Do not use shell or web tools. Summarize actual results briefly.", + } + }, + "tools": {"enabled": ["read", "write"], "blocked": ["exec", "process"]}, + "environment": { + "provider": "local", + "workspace": str(workspace), + "artifacts": str(output / "artifacts"), + }, + } + ) + + +async def run(args: argparse.Namespace) -> None: + """Keep one Gateway alive for clients, or execute supplied SDK/HTTP tasks once.""" + output = args.output_dir.absolute() + output.mkdir(parents=True, exist_ok=False) + os.environ.setdefault("ADAPTER_PYTHON", sys.executable) + config = build_config(args, output) + fabric = Fabric() + async with await fabric.start_runtime(config, base_dir=Path.cwd()) as runtime: + directory = ( + output + / "artifacts/.fabric/openclaw/runtimes" + / runtime.runtime_id + / "interfaces" + ) + connection = json.loads((directory / "gateway.json").read_text()) + # These are paths and endpoints, never credential values. + info = { + "runtime_id": runtime.runtime_id, + "connection": str(directory / "gateway.json"), + "http_url": connection["http_url"], + "agent_id": connection["agent_id"], + "token_file": str(directory / connection["token_file"]), + "workspace": str(output / "workspace"), + } + if "terminal" in config.harness.settings["interfaces"]: + info["terminal_launcher"] = str(directory / "terminal") + (output / "connection.json").write_text(json.dumps(info, indent=2) + "\n") + print(json.dumps(info, indent=2), flush=True) + if args.sdk_input: + result = await runtime.invoke(input=args.sdk_input) + (output / "sdk-result.json").write_text( + json.dumps(result.to_mapping(), indent=2) + "\n" + ) + if result.status != "succeeded": + raise RuntimeError("SDK task failed; inspect sdk-result.json") + if args.http_input: + async with httpx.AsyncClient(trust_env=False, timeout=180) as client: + response = await client.post( + connection["http_url"] + "/v1/chat/completions", + headers={ + "Authorization": "Bearer " + + (directory / connection["token_file"]).read_text().strip() + }, + json={ + "model": f"openclaw/{connection['agent_id']}", + "user": "manual-http-client", + "messages": [{"role": "user", "content": args.http_input}], + }, + ) + response.raise_for_status() + (output / "http-result.json").write_text( + json.dumps(response.json(), indent=2) + "\n" + ) + if not args.once: + print( + "Gateway ready. Attach clients in other terminals; press Enter here to stop.", + flush=True, + ) + await asyncio.to_thread(input) + (output / "cleanup.json").write_text( + json.dumps( + { + "discovery_removed": not (directory / "gateway.json").exists(), + "token_removed": not (directory / connection["token_file"]).exists(), + "terminal_marker_removed": not ( + directory / "terminal.running" + ).exists(), + }, + indent=2, + ) + + "\n" + ) + + +def main() -> None: + """Run the repository example with prepared native dependencies.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--base-url", required=True) + parser.add_argument("--model", required=True) + parser.add_argument("--api-key-env", default="MODEL_API_KEY") + parser.add_argument("--openclaw-command") + parser.add_argument( + "--interface", choices=("terminal", "dashboard", "both"), default="terminal" + ) + parser.add_argument( + "--port", + type=int, + default=18789, + help="Dashboard Gateway base port; terminal-only uses automatic allocation", + ) + parser.add_argument("--public-origin", action="append", default=[]) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--sdk-input") + parser.add_argument("--http-input") + parser.add_argument( + "--once", + action="store_true", + help="Stop after supplied tasks; otherwise wait for manual clients", + ) + args = parser.parse_args() + if not os.environ.get(args.api_key_env): + parser.error( + f"Set {args.api_key_env} to the credential required by the model endpoint" + ) + if args.once and not (args.sdk_input or args.http_input): + parser.error("--once requires --sdk-input or --http-input") + if args.interface == "terminal" and (args.public_origin or args.port != 18789): + parser.error( + "--port and --public-origin apply to the dashboard; terminal has no port setting" + ) + try: + asyncio.run(run(args)) + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json b/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json index a9c22f672..f23440d47 100644 --- a/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json +++ b/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json @@ -2056,11 +2056,23 @@ "settings_schema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, + "dependentSchemas": { + "port_range": { + "properties": { + "interfaces": { + "properties": { + "dashboard": false + } + } + } + } + }, "properties": { "agent_id": { "default": "default", - "description": "OpenClaw agent selected for NeMo Fabric-originated invocations.", + "description": "OpenClaw agent selected for SDK invocations and managed native clients.", "minLength": 1, + "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$", "type": "string" }, "channel_config": { @@ -2108,6 +2120,55 @@ "exclusiveMinimum": 0, "type": "number" }, + "interfaces": { + "additionalProperties": false, + "description": "Native interfaces served by a managed runtime. Services reject interfaces.", + "properties": { + "dashboard": { + "additionalProperties": false, + "description": "OpenClaw's Control UI. After the Gateway starts, the adapter writes its sign-in token to /.fabric/openclaw/runtimes//interfaces/dashboard.token.", + "properties": { + "enabled": { + "default": true, + "description": "Serve the Control UI. A present dashboard is on unless this is false.", + "type": "boolean" + }, + "port": { + "description": "Exact loopback Gateway base port, which serves the Control UI. Start fails if it or port + 2 is in use. OpenClaw allocates browser ports through port + 110 on demand, so keep that range free. Can't be combined with port_range.", + "maximum": 65425, + "minimum": 1, + "type": "integer" + }, + "public_origins": { + "default": [], + "description": "Additional browser HTTP(S) origins. OpenClaw also permits loopback origins; the token is always required.", + "items": { + "pattern": "^https?://[^/\\s?#@]+$", + "type": "string" + }, + "type": "array", + "uniqueItems": true + } + }, + "required": [ + "port" + ], + "type": "object" + }, + "terminal": { + "additionalProperties": false, + "description": "Attach the native terminal to the existing Gateway. No terminal port; publishes a private executable launcher and terminal.running marker.", + "properties": { + "enabled": { + "default": true, + "type": "boolean" + } + }, + "type": "object" + } + }, + "type": "object" + }, "openclaw_command": { "description": "OpenClaw executable name or path. Relative paths containing a directory are resolved from the NeMo Fabric base directory.", "minLength": 1, @@ -2161,7 +2222,7 @@ "name": "nemo-fabric-adapters-openclaw", "version": "0.7.0" }, - "sha256": "27af873589f481bd85f2e8e5fd32826879d5d1ba1dbdd1ff0c1e1d1298bb5be0", + "sha256": "dbfb74e0d2a2ba4db50bdc0d93140c0de3abc07d90f6551b9dd1f28458b9cc59", "source": "adapters/python/openclaw/openclaw.fabric-adapter.json" }, "nvidia.fabric.opencode": { diff --git a/tests/_utils/mock_api_server.py b/tests/_utils/mock_api_server.py index 65dbb82ea..2b66fe0fa 100644 --- a/tests/_utils/mock_api_server.py +++ b/tests/_utils/mock_api_server.py @@ -36,6 +36,7 @@ def reset_state() -> None: app.state.requests = [] app.state.status_code = 200 app.state.delay_seconds = 0.0 + app.state.response_text = None app.state.chat_authorization_headers = [] app.state.tool_calls = [] app.state.tool_call_index = 0 @@ -74,6 +75,7 @@ async def scenario(request: Request) -> dict[str, object]: payload = await request.json() app.state.status_code = int(payload.get("status_code", 200)) app.state.delay_seconds = float(payload.get("delay_seconds", 0.0)) + app.state.response_text = payload.get("response_text") tool_call = payload.get("tool_call") app.state.tool_calls = payload.get("tool_calls") or ( [tool_call] if tool_call is not None else [] @@ -193,7 +195,10 @@ async def chat_completions(request: Request): if isinstance(message, dict) and message.get("role") == "user" ] latest = user_messages[-1].get("content", "") if user_messages else "" - content = f"echo user_count={len(user_messages)} latest={latest}" + content = ( + app.state.response_text + or f"echo user_count={len(user_messages)} latest={latest}" + ) if payload.get("stream") is True: return StreamingResponse( _stream_chat_completion(payload, content), diff --git a/tests/_utils/mock_openclaw.py b/tests/_utils/mock_openclaw.py index 1c8fdeb29..fa4fdf0ee 100755 --- a/tests/_utils/mock_openclaw.py +++ b/tests/_utils/mock_openclaw.py @@ -55,6 +55,31 @@ def do_GET(self): self.send_header("Allow", "POST") self.end_headers() return + if self.path == "/fabric/shared-config/health": + if self.headers.get("Authorization") != f"Bearer {token}": + self.send_response(401) + self.end_headers() + return + mode = os.environ.get("FAKE_OPENCLAW_SHARED_CONFIG", "ready") + if mode == "missing": + self.send_response(404) + self.end_headers() + return + with open(os.environ["OPENCLAW_CONFIG_PATH"], encoding="utf-8") as stream: + generated = json.load(stream) + agent_id = next(iter(generated["agents"]["entries"])) + body = json.dumps( + { + "ready": mode != "inactive", + "agent_id": agent_id.lower() if mode != "wrong-agent" else "other", + } + ).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return if self.path == "/healthz": body = json.dumps({"ok": True, "status": "live"}).encode() self.send_response(200) diff --git a/tests/adapters/test_openclaw.py b/tests/adapters/test_openclaw.py index 9aebfc320..499d1b951 100644 --- a/tests/adapters/test_openclaw.py +++ b/tests/adapters/test_openclaw.py @@ -11,6 +11,7 @@ import os import shutil import signal +import socket import subprocess import sys import time @@ -98,11 +99,46 @@ def _config(command: Path, *, with_skills: bool = False) -> AgentConfig: ) +def _dashboard_config(command: Path, dashboard: dict[str, object]) -> AgentConfig: + config = _config(command) + assert config.harness is not None + config.harness.settings["interfaces"] = {"dashboard": dashboard} + return config + + +def _dashboard_token(base_dir: Path) -> Path: + return ( + base_dir + / "artifacts/.fabric/openclaw/runtimes/openclaw-runtime/interfaces/dashboard.token" + ) + + +async def _start( + runtime: adapter.OpenClawRuntime, + tmp_path: Path, + config: AgentConfig, + **payload: object, +) -> None: + await runtime.start( + { + "config": config, + "runtime_context": _context(tmp_path).to_mapping(), + "base_dir": str(tmp_path), + **payload, + } + ) + + @pytest.fixture(name="mock_openclaw") def mock_openclaw_fixture(repo_root: Path) -> Path: return repo_root / "tests/_utils/mock_openclaw.py" +@pytest.fixture(name="dashboard_port") +def dashboard_port_fixture() -> int: + return adapter._select_port({}) + + def test_openclaw_port_availability_checks_one_port( monkeypatch: pytest.MonkeyPatch, ): @@ -183,6 +219,53 @@ def test_openclaw_rejects_invalid_port_range(settings: dict[str, object]): assert caught.value.metadata == {"field": "harness.settings.port_range"} +@pytest.mark.parametrize( + "settings", + [ + pytest.param( + {"interfaces": {"terminal": {"port": 20_000}}}, id="terminal-has-no-port" + ), + pytest.param( + {"interfaces": {"dashboard": {"port": 20_000, "token": "x"}}}, + id="unknown-field", + ), + pytest.param({"interfaces": {"dashboard": {}}}, id="missing-port"), + pytest.param( + {"interfaces": {"dashboard": {"port": 65_426}}}, id="port-too-high" + ), + pytest.param( + { + "interfaces": {"dashboard": {"port": 20_000}}, + "port_range": {"start": 20_000, "end": 20_200}, + }, + id="port-range-with-dashboard", + ), + pytest.param({"startup_timeout_seconds": 76}, id="startup-timeout-too-long"), + pytest.param({"agent_id": "my agent"}, id="agent-id-spaces"), + pytest.param({"agent_id": "a" * 65}, id="agent-id-too-long"), + pytest.param({"agent_id": "-agent"}, id="agent-id-prefix"), + ], +) +def test_openclaw_plan_rejects_invalid_settings( + tmp_path: Path, settings: dict[str, object] +): + config = FabricConfig.from_mapping( + { + "metadata": {"name": "openclaw-interfaces"}, + "harness": { + "adapter_id": "nvidia.fabric.openclaw", + "resolution": "preinstalled", + "settings": settings, + }, + "models": {"default": {"provider": "test", "model": "fabric-echo"}}, + "environment": {"provider": "local", "workspace": "."}, + } + ) + + with pytest.raises(FabricConfigError): + Fabric().plan(config, base_dir=tmp_path) + + @pytest.mark.parametrize("raw", ["2026.9.34 extra", "2026.9.34\nuntrusted suffix"]) async def test_gateway_records_the_same_version_it_validates(monkeypatch, raw): from nemo_fabric_adapters.common import provenance @@ -481,6 +564,8 @@ async def test_openclaw_runtime_generates_config_invokes_and_cleans_up( assert generated["mcp"]["servers"]["local"]["command"] == "python" assert generated["mcp"]["servers"]["remote"]["transport"] == ("streamable-http") assert "auth" not in generated["mcp"]["servers"]["remote"] + assert generated["gateway"]["controlUi"] == {"enabled": False} + assert not (tmp_path / "artifacts").exists() # The sandbox would deny OpenClaw's model catalog lookup anyway. assert generated["models"]["catalogRefresh"] == {"enabled": False} assert not state_root.exists() @@ -1325,6 +1410,184 @@ async def test_openclaw_stop_continues_after_cleanup_failures( assert runtime._temp_dir is None +@pytest.mark.skipif(sys.platform == "win32", reason="Requires POSIX file permissions") +async def test_openclaw_dashboard_serves_control_ui_with_a_token_file( + mock_openclaw: Path, tmp_path: Path, dashboard_port: int +): + capture = tmp_path / "config.json" + os.environ["FAKE_OPENCLAW_CAPTURE"] = str(capture) + token_path = _dashboard_token(tmp_path) + runtime = adapter.OpenClawRuntime() + + await _start( + runtime, tmp_path, _dashboard_config(mock_openclaw, {"port": dashboard_port}) + ) + try: + gateway_token = runtime._token + stored_token = token_path.read_text(encoding="utf-8") + token_mode = token_path.stat().st_mode & 0o777 + directory_mode = token_path.parent.stat().st_mode & 0o777 + finally: + await runtime.stop() + + generated = json.loads(capture.read_text(encoding="utf-8")) + assert generated["gateway"]["port"] == dashboard_port + assert generated["gateway"]["controlUi"] == { + "enabled": True, + "allowedOrigins": [ + f"http://127.0.0.1:{dashboard_port}", + f"http://localhost:{dashboard_port}", + ], + } + assert stored_token == gateway_token + assert token_mode == 0o600 + assert directory_mode == 0o700 + assert not token_path.exists() + + +@pytest.mark.skipif( + sys.platform in {"darwin", "win32"}, + reason="Starts the mock Gateway, which CI runs only on Linux", +) +async def test_openclaw_dashboard_disabled_serves_no_control_ui( + mock_openclaw: Path, tmp_path: Path, dashboard_port: int +): + capture = tmp_path / "config.json" + os.environ["FAKE_OPENCLAW_CAPTURE"] = str(capture) + runtime = adapter.OpenClawRuntime() + + await _start( + runtime, + tmp_path, + _dashboard_config(mock_openclaw, {"port": dashboard_port, "enabled": False}), + ) + try: + gateway_port = runtime._port + token_exists = _dashboard_token(tmp_path).exists() + finally: + await runtime.stop() + + generated = json.loads(capture.read_text(encoding="utf-8")) + assert generated["gateway"]["controlUi"] == {"enabled": False} + assert gateway_port != dashboard_port + assert not token_exists + + +@pytest.mark.skipif( + sys.platform in {"darwin", "win32"}, + reason="Starts the mock Gateway, which CI runs only on Linux", +) +async def test_openclaw_dashboard_removes_the_token_when_start_fails_after_writing_it( + mock_openclaw: Path, + tmp_path: Path, + dashboard_port: int, + monkeypatch: pytest.MonkeyPatch, +): + os.environ["FAKE_OPENCLAW_CAPTURE"] = str(tmp_path / "config.json") + token_path = _dashboard_token(tmp_path) + token_written: list[bool] = [] + + # Start reads the HTTP read timeout only after it writes the token. + def fail_after_token_write(_settings): + token_written.append(token_path.exists()) + raise RuntimeError("start failed after writing the token") + + monkeypatch.setattr(adapter, "_read_timeout", fail_after_token_write) + runtime = adapter.OpenClawRuntime() + + with pytest.raises(RuntimeError, match="after writing the token"): + await _start( + runtime, + tmp_path, + _dashboard_config(mock_openclaw, {"port": dashboard_port}), + ) + + assert token_written == [True] + assert not token_path.exists() + assert runtime._process is None + + +@pytest.mark.skipif( + sys.platform in {"darwin", "win32"}, + reason="Starts the mock Gateway, which CI runs only on Linux", +) +async def test_openclaw_dashboard_stop_retries_a_token_it_could_not_remove( + mock_openclaw: Path, + tmp_path: Path, + dashboard_port: int, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +): + os.environ["FAKE_OPENCLAW_CAPTURE"] = str(tmp_path / "config.json") + token_path = _dashboard_token(tmp_path) + runtime = adapter.OpenClawRuntime() + await _start( + runtime, tmp_path, _dashboard_config(mock_openclaw, {"port": dashboard_port}) + ) + unlink = Path.unlink + + def fail_token_unlink(path: Path, missing_ok: bool = False) -> None: + if path == token_path: + raise PermissionError("token is locked") + unlink(path, missing_ok=missing_ok) + + with monkeypatch.context() as patch: + patch.setattr(Path, "unlink", fail_token_unlink) + await runtime.stop() + + assert runtime._process is None + assert token_path.exists() + assert "could not remove its dashboard token" in caplog.text + + await runtime.stop() + + assert not token_path.exists() + + +@pytest.mark.skipif( + sys.platform == "win32", reason="Runs the mock openclaw script directly" +) +@pytest.mark.parametrize("offset", [0, 2]) +async def test_openclaw_dashboard_port_in_use_fails_start( + mock_openclaw: Path, tmp_path: Path, dashboard_port: int, offset: int +): + runtime = adapter.OpenClawRuntime() + + with socket.create_server(("127.0.0.1", dashboard_port + offset)): + with pytest.raises(adapter.lifecycle.LifecycleError) as caught: + await _start( + runtime, + tmp_path, + _dashboard_config(mock_openclaw, {"port": dashboard_port}), + ) + + assert caught.value.code == "openclaw_interface_port_unavailable" + assert caught.value.metadata == { + "field": "harness.settings.interfaces.dashboard.port", + "port": dashboard_port + offset, + } + assert runtime._process is None + assert not (tmp_path / "artifacts").exists() + + +@pytest.mark.parametrize("operation", ["prepare", "attach", "connect"]) +async def test_openclaw_services_reject_interfaces( + mock_openclaw: Path, tmp_path: Path, operation: str +): + runtime = adapter.OpenClawRuntime() + + with pytest.raises(adapter.lifecycle.LifecycleError) as caught: + await _start( + runtime, + tmp_path, + _dashboard_config(mock_openclaw, {"port": 20_000}), + service={"operation": operation}, + ) + + assert caught.value.code == "openclaw_interfaces_require_managed_runtime" + assert runtime._process is None + + @pytest.mark.skipif( sys.platform in {"darwin", "win32"}, reason="Starts the mock Gateway, which CI runs only on Linux", @@ -1507,12 +1770,15 @@ def signal_group(pid: int, signum: int) -> None: sys.platform == "win32", reason="Runs the mock openclaw script directly" ) async def test_openclaw_startup_timeout_bounds_all_of_start( - mock_openclaw: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + mock_openclaw: Path, + tmp_path: Path, + dashboard_port: int, + monkeypatch: pytest.MonkeyPatch, ): # Each command finishes within the timeout, but the two together don't. monkeypatch.setenv("FAKE_OPENCLAW_COMMAND_DELAY", "0.6") monkeypatch.setenv("FAKE_OPENCLAW_CAPTURE", str(tmp_path / "config.json")) - config = _config(mock_openclaw) + config = _dashboard_config(mock_openclaw, {"port": dashboard_port}) assert config.harness is not None config.harness.settings["startup_timeout_seconds"] = 1 runtime = adapter.OpenClawRuntime() @@ -1528,6 +1794,7 @@ async def test_openclaw_startup_timeout_bounds_all_of_start( assert caught.value.code == "openclaw_command_timeout" assert runtime._process is None + assert not (tmp_path / "artifacts").exists() async def test_openclaw_startup_deadline_bounds_a_pending_readiness_request(): @@ -2225,3 +2492,147 @@ async def test_openclaw_gateway_stream_keeps_usage_observational(): "observed": {"input_tokens": 42, "output_tokens": 8, "total_tokens": 50}, "gaps": ["scope_unverified"], } + + +@pytest.mark.skipif(os.name != "posix", reason="The native terminal requires POSIX") +@pytest.mark.parametrize( + "selection, shared", + [ + ({}, False), + ({"terminal": {"enabled": False}}, False), + ({"terminal": {}}, True), + ], +) +@pytest.mark.parametrize("agent_id", ["default", "Reviewer"]) +async def test_native_configuration_owns_prompt_once( + mock_openclaw, tmp_path, selection, shared, agent_id +): + capture = tmp_path / "config.json" + request_capture = tmp_path / "request.json" + os.environ["FAKE_OPENCLAW_CAPTURE"] = str(capture) + os.environ["FAKE_OPENCLAW_REQUEST"] = str(request_capture) + config = _config(mock_openclaw) + config.harness.settings["interfaces"] = selection + config.harness.settings["agent_id"] = agent_id + runtime = adapter.OpenClawRuntime() + await _start(runtime, tmp_path, config) + try: + result = await runtime.invoke( + AgentRunRequest(input="Check shared configuration."), _context(tmp_path) + ) + assert result.status == "succeeded" + request = json.loads(request_capture.read_text()) + assert [message["role"] for message in request["messages"]] == ( + ["user"] if shared else ["system", "user"] + ) + generated = json.loads(capture.read_text()) + if shared: + entry = generated["plugins"]["entries"]["fabric-shared-config"] + assert entry["config"] == { + "agentId": agent_id, + "systemInstruction": "Be concise.", + } + directory = _dashboard_token(tmp_path).parent + assert (directory / "terminal.running").exists() + assert (directory / "gateway.json").exists() + assert (await runtime.check("ready"))["activity"] == "unknown" + else: + assert "plugins" not in generated + assert not _dashboard_token(tmp_path).parent.exists() + for level in ("live", "active", "ready"): + report = await runtime.check(level) + assert report["outcome"] == "passed", report + finally: + await runtime.stop() + assert not (_dashboard_token(tmp_path).parent / "terminal.running").exists() + + +@pytest.mark.parametrize( + "agent_id", ["my agent", "-agent", "_agent", "a" * 65, "é", " reviewer "] +) +async def test_openclaw_rejects_noncanonical_agent_ids( + mock_openclaw, tmp_path, agent_id +): + config = _config(mock_openclaw) + config.harness.settings["agent_id"] = agent_id + runtime = adapter.OpenClawRuntime() + with pytest.raises(adapter.lifecycle.LifecycleError) as caught: + await _start(runtime, tmp_path, config) + assert caught.value.code == "openclaw_invalid_configuration" + assert caught.value.metadata == {"field": "harness.settings.agent_id"} + assert runtime._process is None + + +@pytest.mark.skipif(os.name != "posix", reason="The native terminal requires POSIX") +@pytest.mark.parametrize("mode", ["missing", "inactive", "wrong-agent"]) +async def test_shared_instruction_probe_fails_before_publishing_interfaces( + mock_openclaw, tmp_path, mode +): + os.environ["FAKE_OPENCLAW_SHARED_CONFIG"] = mode + os.environ["FAKE_OPENCLAW_CAPTURE"] = str(tmp_path / "config.json") + config = _config(mock_openclaw) + config.harness.settings["interfaces"] = {"terminal": {}} + runtime = adapter.OpenClawRuntime() + with pytest.raises(adapter.lifecycle.LifecycleError) as caught: + await _start(runtime, tmp_path, config) + assert caught.value.code == "openclaw_shared_configuration_unavailable" + assert runtime._process is None + assert not (_dashboard_token(tmp_path).parent / "gateway.json").exists() + assert not (_dashboard_token(tmp_path).parent / "terminal.running").exists() + + +@pytest.mark.skipif( + not os.environ.get("FABRIC_OPENCLAW_TEST_COMMAND"), + reason="Set FABRIC_OPENCLAW_TEST_COMMAND for actual plugin failure qualification", +) +@pytest.mark.parametrize( + "failure", + ["missing", "renamed", "conversation-denied", "prompt-denied", "wrong-agent"], +) +async def test_native_shared_hook_failures_reject_startup( + tmp_path, api_server, monkeypatch, failure +): + plugin = tmp_path / "plugin" + shutil.copytree(Path(adapter.__file__).with_name("native_config"), plugin) + entrypoint = plugin / "index.mjs" + if failure == "missing": + entrypoint.write_text( + 'throw new Error("plugin load failure for qualification");' + ) + elif failure == "renamed": + entrypoint.write_text( + entrypoint.read_text().replace( + 'api.on("before_prompt_build"', 'api.on("agent_end"' + ) + ) + original = adapter._openclaw_config + + def generated_config(*args, **kwargs): + generated = original(*args, **kwargs) + generated["plugins"]["load"]["paths"] = [str(plugin)] + shared = generated["plugins"]["entries"]["fabric-shared-config"] + if failure == "conversation-denied": + shared["hooks"]["allowConversationAccess"] = False + elif failure == "prompt-denied": + shared["hooks"]["allowPromptInjection"] = False + elif failure == "wrong-agent": + shared["config"]["agentId"] = "other" + return generated + + monkeypatch.setattr(adapter, "_openclaw_config", generated_config) + config = _config(Path(os.environ["FABRIC_OPENCLAW_TEST_COMMAND"])) + config.harness.settings["interfaces"] = {"terminal": {}} + config.models["default"].base_url = f"{api_server}/v1" + runtime = adapter.OpenClawRuntime() + with pytest.raises(adapter.lifecycle.LifecycleError) as caught: + await _start(runtime, tmp_path, config) + assert caught.value.code == "openclaw_shared_configuration_unavailable" + assert runtime._process is None + assert not (_dashboard_token(tmp_path).parent / "gateway.json").exists() + async with httpx.AsyncClient(trust_env=False) as client: + assert (await client.get(f"{api_server}/_requests")).json() == [] + + +@pytest.mark.parametrize("agent_id", ["Reviewer", "agent_1-A", "a" * 64]) +def test_openclaw_preserves_valid_agent_id_spelling(agent_id): + assert adapter._agent_id({"agent_id": agent_id}) == agent_id diff --git a/tests/adapters/test_openclaw_interfaces.py b/tests/adapters/test_openclaw_interfaces.py new file mode 100644 index 000000000..a1bbe4e6e --- /dev/null +++ b/tests/adapters/test_openclaw_interfaces.py @@ -0,0 +1,146 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Managed OpenClaw interface ownership and private attachment contracts.""" + +import json +import os +import sys +from pathlib import Path +from unittest.mock import MagicMock + +import pytest +from nemo_fabric_adapters.common import lifecycle +from nemo_fabric_adapters.openclaw import interfaces, terminal + + +@pytest.fixture(name="connection") +def connection_fixture(tmp_path): + if os.name != "posix": + pytest.skip("Managed terminal attachment requires POSIX") + directory = tmp_path / "interfaces" + interfaces.publish( + directory, + runtime_id="test-runtime", + port=18789, + token="test-secret-token", + command=Path(sys.executable).absolute(), + workspace=str(tmp_path), + agent_id="reviewer", + dashboard=False, + terminal=True, + ) + return directory / "gateway.json" + + +@pytest.mark.parametrize( + "origin", + ["https://chat.example.com", "http://localhost:1234", "https://[::1]:8443"], +) +def test_public_origins_accept_http_origins(origin): + assert interfaces.public_origins( + {"interfaces": {"dashboard": {"public_origins": [origin]}}} + ) == [origin] + + +@pytest.mark.parametrize( + "origin", + [ + "https://host/path", + "https://host/", + "https://host?key=value", + "https://user:secret@host", + "javascript:alert(1)", + "https://host:0", + "http://host:invalid", + "https://host#token", + ], +) +def test_public_origins_reject_non_origins(origin): + with pytest.raises(lifecycle.LifecycleError, match="HTTP\\(S\\) origins"): + interfaces.public_origins( + {"interfaces": {"dashboard": {"public_origins": [origin]}}} + ) + + +def test_discovery_has_no_secret_and_cleanup_revokes_marker_first( + connection, monkeypatch +): + directory = connection.parent + assert "test-secret-token" not in connection.read_text() + assert "test-secret-token" not in (directory / "terminal").read_text() + assert "test-secret-token" not in (directory / "client.json").read_text() + assert (directory / "terminal").stat().st_mode & 0o777 == 0o700 + for name in ("gateway.json", "gateway.token", "client.json", "terminal.running"): + assert (directory / name).stat().st_mode & 0o777 == 0o600 + removed = [] + unlink = Path.unlink + + def record(path, **kwargs): + removed.append(path.name) + return unlink(path, **kwargs) + + monkeypatch.setattr(Path, "unlink", record) + assert interfaces.remove(directory) + assert removed[0] == "terminal.running" + assert not any((directory / name).exists() for name in interfaces.FILES) + + +def test_cleanup_retries_failed_removal(connection, monkeypatch): + unlink = Path.unlink + + def deny(path, **kwargs): + if path.name == "gateway.token": + raise PermissionError("denied") + return unlink(path, **kwargs) + + with monkeypatch.context() as scoped: + scoped.setattr(Path, "unlink", deny) + assert not interfaces.remove(connection.parent) + assert interfaces.remove(connection.parent) + assert not connection.with_name("gateway.token").exists() + + +def test_terminal_uses_configured_gateway_without_secret_argv(connection, monkeypatch): + mock_client = MagicMock() + monkeypatch.setattr(terminal.httpx, "Client", mock_client) + os.environ["OPENCLAW_GATEWAY_URL"] = "ws://unmanaged.example" + os.environ["OPENCLAW_GATEWAY_TOKEN"] = "ambient-wrong-token" + command, environment, workspace = terminal.attachment(connection, "review") + assert command[1:] == ["tui", "--session", "agent:reviewer:review"] + assert all("test-secret-token" not in arg for arg in command) + assert "OPENCLAW_GATEWAY_URL" not in environment + assert "OPENCLAW_GATEWAY_TOKEN" not in environment + assert environment["FABRIC_OPENCLAW_CLIENT_TOKEN"] == "test-secret-token" + assert workspace == str(connection.parent.parent) + config = json.loads(Path(environment["OPENCLAW_CONFIG_PATH"]).read_text()) + assert config["gateway"]["mode"] == "remote" + assert config["gateway"]["remote"]["url"] == "ws://127.0.0.1:18789" + mock_client.return_value.__enter__.return_value.get.assert_called_once_with( + "http://127.0.0.1:18789/v1/models", + headers={"Authorization": "Bearer test-secret-token"}, + ) + + +@pytest.mark.parametrize( + "name", ["gateway.json", "gateway.token", "client.json", "terminal.running"] +) +def test_terminal_rejects_public_or_symlinked_files(connection, name, monkeypatch): + monkeypatch.setattr(terminal.httpx, "Client", MagicMock()) + file = connection.with_name(name) + file.chmod(0o644) + with pytest.raises(ValueError, match="owner-only"): + terminal.attachment(connection) + file.chmod(0o600) + target = file.with_suffix(".target") + file.rename(target) + file.symlink_to(target) + with pytest.raises(OSError): + terminal.attachment(connection) + + +@pytest.mark.parametrize("session", ["agent:other:main", "two words", ""]) +def test_terminal_rejects_ambiguous_session(connection, session, monkeypatch): + monkeypatch.setattr(terminal.httpx, "Client", MagicMock()) + with pytest.raises(ValueError, match="session name"): + terminal.attachment(connection, session) diff --git a/tests/adapters/test_openclaw_native.py b/tests/adapters/test_openclaw_native.py new file mode 100644 index 000000000..ecb1a2343 --- /dev/null +++ b/tests/adapters/test_openclaw_native.py @@ -0,0 +1,610 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Opt-in qualification against the pinned OpenClaw Gateway and real native clients.""" + +import asyncio +import json +import os +import sys +from pathlib import Path + +import httpx +import pytest +from nemo_fabric import Fabric, FabricConfig + +pytestmark = pytest.mark.skipif( + not os.environ.get("FABRIC_OPENCLAW_TEST_COMMAND"), + reason="Set FABRIC_OPENCLAW_TEST_COMMAND to pinned OpenClaw for native qualification", +) + + +@pytest.fixture(name="native_config", params=["reviewer", "Reviewer"]) +def native_config_fixture(tmp_path, api_server, unused_tcp_port, request): + os.environ["ADAPTER_PYTHON"] = sys.executable + os.environ["FABRIC_TEST_MODEL_KEY"] = "native-parity-test-key" + marker = "FABRIC_SHARED_PROMPT_72931" + skill = tmp_path / "external-skills/native-parity" + skill.mkdir(parents=True) + (skill / "SKILL.md").write_text( + "---\nname: native-parity\ndescription: Check the Fabric native parity marker.\n---\nFABRIC_SKILL_98214\n" + ) + config = FabricConfig.from_mapping( + { + "metadata": {"name": "openclaw-native-parity"}, + "harness": { + "adapter_id": "nvidia.fabric.openclaw", + "settings": { + "openclaw_command": os.environ["FABRIC_OPENCLAW_TEST_COMMAND"], + "agent_id": request.param, + "interfaces": { + "dashboard": {"port": unused_tcp_port}, + "terminal": {}, + }, + }, + }, + "models": { + "default": { + "provider": "fabric-test", + "model": "fabric-echo", + "base_url": f"{api_server}/v1", + "api_key_env": "FABRIC_TEST_MODEL_KEY", + "temperature": 0.2, + "top_p": 0.8, + "max_tokens": 128, + } + }, + "instructions": {"system": {"content": marker, "mode": "replace"}}, + "tools": {"blocked": ["exec", "process"]}, + "skills": {"paths": [str(skill)]}, + "mcp": { + "servers": { + "fabricprobe": { + "transport": "streamable-http", + "url": f"{api_server}/mcp", + "custom_headers": { + "Authorization": "Bearer native-mcp-test-key" + }, + } + } + }, + "environment": { + "provider": "local", + "workspace": str(tmp_path), + "artifacts": str(tmp_path / "artifacts"), + }, + } + ) + return config + + +async def test_native_and_sdk_share_gateway_configuration( + tmp_path, api_server, unused_tcp_port, native_config +): + from nemo_fabric import CheckRequest, EnvironmentHandle + from playwright.async_api import async_playwright + import pexpect + + marker = native_config.instructions.system.content + (tmp_path / "source.txt").write_text("FABRIC_SOURCE_MARKER_35291\n") + fabric = Fabric() + async with await fabric.start_runtime(native_config, base_dir=tmp_path) as runtime: + directory = ( + tmp_path + / "artifacts/.fabric/openclaw/runtimes" + / runtime.runtime_id + / "interfaces" + ) + token = (directory / "dashboard.token").read_text() + async with httpx.AsyncClient(trust_env=False, timeout=60) as client: + + async def scenario(path, turn): + calls = ( + [ + {"name": "read", "arguments": {"path": "source.txt"}}, + { + "name": "write", + "arguments": { + "path": f"{path}-result.txt", + "content": f"{path} configured workspace verified", + }, + }, + ] + if turn == 1 + else [ + { + "name": "tool_call", + "arguments": { + "id": "mcp:fabricprobe:fabricprobe__get_authorization_header", + "args": {}, + }, + }, + { + "name": "read", + "arguments": { + "path": str( + Path(native_config.skills.paths[0]) / "SKILL.md" + ) + }, + }, + ] + ) + response = await client.post( + f"{api_server}/_scenario", + json={ + "tool_calls": calls, + "response_text": f"{path} turn {turn} complete", + }, + ) + response.raise_for_status() + + for turn in (1, 2): + await scenario("sdk", turn) + result = await runtime.invoke(input=f"SDK parity turn {turn}") + assert result.status == "succeeded", result.to_mapping() + assert ( + tmp_path / "sdk-result.txt" + ).read_text() == "sdk configured workspace verified" + + for turn in (1, 2): + await scenario("http", turn) + response = await client.post( + f"http://127.0.0.1:{unused_tcp_port}/v1/chat/completions", + headers={"Authorization": f"Bearer {token}"}, + json={ + "model": "openclaw/reviewer", + "user": "http-parity-client", + "messages": [ + {"role": "user", "content": f"HTTP parity turn {turn}"} + ], + }, + ) + assert response.status_code == 200, response.text + assert ( + tmp_path / "http-result.txt" + ).read_text() == "http configured workspace verified" + + async with async_playwright() as playwright: + browser = await playwright.chromium.launch( + headless=True, + args=["--no-sandbox"], + executable_path=os.environ.get("FABRIC_TEST_CHROMIUM"), + ) + try: + page = await browser.new_page() + await page.goto( + f"http://127.0.0.1:{unused_tcp_port}/#token={token}" + ) + textarea = page.get_by_role( + "textbox", name="Chat composer", exact=True + ) + await textarea.wait_for(timeout=20000) + for turn in (1, 2): + await scenario("browser", turn) + await textarea.fill(f"Browser parity turn {turn}") + await textarea.press("Enter") + await ( + page.get_by_role("paragraph") + .filter(has_text=f"browser turn {turn} complete") + .wait_for(timeout=30000) + ) + await page.wait_for_timeout(500) + await page.screenshot(path=str(tmp_path / "browser.png")) + (tmp_path / "browser-body.txt").write_text( + (await page.locator("body").inner_text()).replace( + token, "[redacted]" + ) + ) + finally: + await page.screenshot(path=str(tmp_path / "browser.png")) + (tmp_path / "browser-body.txt").write_text( + (await page.locator("body").inner_text()).replace( + token, "[redacted]" + ) + ) + (tmp_path / "browser-model-requests.json").write_text( + json.dumps( + (await client.get(f"{api_server}/_requests")).json(), + indent=2, + ) + ) + await browser.close() + assert ( + tmp_path / "browser-result.txt" + ).read_text() == "browser configured workspace verified" + + def terminal_turns(): + child = pexpect.spawn( + str(directory / "terminal"), + ["--session", "parity-terminal"], + encoding="utf-8", + timeout=45, + dimensions=(32, 120), + ) + try: + with (tmp_path / "terminal.log").open("w") as transcript: + child.logfile_read = transcript + child.expect(r"(?= 4 + messages = json.dumps(payloads) + assert "FABRIC_SOURCE_MARKER_35291" in messages + assert "FABRIC_SKILL_98214" in messages + for name in ( + "terminal.running", + "terminal", + "gateway.json", + "client.json", + "dashboard.token", + ): + assert not (directory / name).exists() + + +async def test_native_mcp_and_skills_use_managed_configuration( + tmp_path, api_server, native_config +): + from nemo_fabric_adapters.openclaw import terminal + + fabric = Fabric() + async with await fabric.start_runtime(native_config, base_dir=tmp_path) as runtime: + async with httpx.AsyncClient(trust_env=False, timeout=60) as client: + await client.post( + f"{api_server}/_scenario", + json={ + "tool_call": { + "name": "tool_search", + "arguments": {"query": "fabricprobe authorization header"}, + } + }, + ) + result = await runtime.invoke( + input="Discover the configured MCP authorization tool." + ) + assert result.status == "succeeded", result.to_mapping() + payloads = (await client.get(f"{api_server}/_requests")).json() + (tmp_path / "mcp-search-requests.json").write_text( + json.dumps(payloads, indent=2) + ) + tool_messages = [ + message + for payload in payloads + for message in payload["messages"] + if message["role"] == "tool" + ] + assert any( + "get_authorization_header" in str(message["content"]) + for message in tool_messages + ), tool_messages + await client.post( + f"{api_server}/_scenario", + json={ + "tool_call": { + "name": "tool_call", + "arguments": { + "id": "mcp:fabricprobe:fabricprobe__get_authorization_header", + "args": {}, + }, + } + }, + ) + result = await runtime.invoke(input="Call the discovered MCP tool.") + assert result.status == "succeeded", result.to_mapping() + assert ( + await client.get(f"{api_server}/_mcp_authorization_headers") + ).json()[-1] == "Bearer native-mcp-test-key" + forbidden = tmp_path / "forbidden-exec.txt" + await client.post( + f"{api_server}/_scenario", + json={ + "tool_call": { + "name": "tool_call", + "arguments": { + "id": "exec", + "args": {"command": f"touch {forbidden}"}, + }, + } + }, + ) + result = await runtime.invoke( + input="Check that blocked shell execution is rejected." + ) + assert result.status == "succeeded", result.to_mapping() + assert not forbidden.exists() + payloads = (await client.get(f"{api_server}/_requests")).json() + refusal = next( + message["content"] + for message in reversed(payloads[-1]["messages"]) + if message["role"] == "tool" + ) + assert any( + term in str(refusal).lower() + for term in ( + "unknown tool", + "not found", + "not allowed", + "denied", + "unavailable", + ) + ), refusal + connection = ( + tmp_path + / "artifacts/.fabric/openclaw/runtimes" + / runtime.runtime_id + / "interfaces/gateway.json" + ) + command, environment, _ = terminal.attachment(connection) + process = await asyncio.create_subprocess_exec( + command[0], + "gateway", + "call", + "skills.status", + "--params", + '{"agentId":"reviewer"}', + "--json", + env=environment, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + stdout, stderr = await asyncio.wait_for(process.communicate(), 30) + (tmp_path / "skills-status.txt").write_bytes(stdout) + assert process.returncode == 0, stderr.decode() + assert "native-parity" in stdout.decode() + + +async def test_four_clients_can_invoke_concurrently( + tmp_path, api_server, unused_tcp_port, native_config +): + import pexpect + from playwright.async_api import async_playwright + + fabric = Fabric() + async with await fabric.start_runtime(native_config, base_dir=tmp_path) as runtime: + directory = ( + tmp_path + / "artifacts/.fabric/openclaw/runtimes" + / runtime.runtime_id + / "interfaces" + ) + token = (directory / "dashboard.token").read_text().strip() + async with async_playwright() as playwright: + browser = await playwright.chromium.launch( + headless=True, + args=["--no-sandbox"], + executable_path=os.environ.get("FABRIC_TEST_CHROMIUM"), + ) + child = None + try: + page = await browser.new_page() + await page.goto(f"http://127.0.0.1:{unused_tcp_port}/#token={token}") + composer = page.get_by_role("textbox", name="Chat composer", exact=True) + await composer.wait_for(timeout=20000) + child = pexpect.spawn( + str(directory / "terminal"), + ["--session", "concurrent-tui"], + encoding="utf-8", + timeout=30, + dimensions=(32, 120), + ) + await asyncio.to_thread(child.expect, r"(? first["result"]["completed_at"] + assert datetime.fromisoformat( + second["result"]["completed_at"] + ) > datetime.fromisoformat(first["result"]["completed_at"]) assert retained.read_text() == "KEEP" if busy: assert invocation.returncode is None