diff --git a/adapters/typescript/pi/README.md b/adapters/typescript/pi/README.md index f0dec61b1..9deb545cb 100644 --- a/adapters/typescript/pi/README.md +++ b/adapters/typescript/pi/README.md @@ -7,7 +7,8 @@ SPDX-License-Identifier: Apache-2.0 This package provides a Pi harness adapter for NVIDIA NeMo Fabric. It embeds the Pi SDK in the Node process of the adapter and maps one NeMo Fabric runtime to one -in-memory Pi session. +in-memory Pi session, or, with the terminal interface, offers Pi's own terminal +UI on the runtime's configuration instead (see [Terminal TUI](#terminal-tui)). The adapter supports: @@ -41,8 +42,11 @@ The adapter supports: output, Relay runtime details, and collected ATOF and OTLP artifacts Ambient Pi settings, context files, packages, extensions, skills, prompts, -themes, model files, credentials, and session files are disabled. Explicitly -configured extensions are trusted code. The adapter raises the compaction +themes, model files, credentials, and session files are disabled: the session +loads only the files the adapter writes from `FabricConfig` to the runtime's +agent directory (see [Agent Directory](#agent-directory)), and it saves +conversations only with `runtime.keep_state`. Explicitly configured extensions +are trusted code. The adapter raises the compaction reserve toward the selected model's maximum output while retaining at least half of the context window for input. @@ -263,7 +267,7 @@ extension tools. The following configuration registers a custom tool module: The adapter maps normalized stdio and streamable HTTP servers to Pi's native MCP extension. Stdio servers can define `args` and `env`, but not HTTP headers. Streamable HTTP servers can define `custom_headers`, but not process arguments or environment variables. Remote endpoints require HTTPS, except for loopback development endpoints. -Header values can reference `${NAME}`. Resolution checks the NeMo Fabric runtime environment first and then the adapter process environment. The adapter maps `allowed_tools` and `blocked_tools` to Pi's per-server tool exposure. Normalized MCP authentication and MCP extensions are not supported. +Header values can reference `${NAME}`. For the SDK session, resolution checks the NeMo Fabric runtime environment first and then the adapter process environment. The terminal UI resolves the same references from the environment that runs its launcher (see [Terminal TUI](#terminal-tui)). The adapter maps `allowed_tools` and `blocked_tools` to Pi's per-server tool exposure. Normalized MCP authentication and MCP extensions are not supported. Only servers supplied by NeMo Fabric are loaded. Ambient Pi MCP configuration remains disabled. @@ -296,6 +300,268 @@ redirects, then prints one JSON document containing `atof_records` and the separate terminal `result`. Redirect-decision marks remain in configured Relay ATOF artifacts; Pi's startup marks are not included in `atof_records`. +## Agent Directory + +Each runtime writes Pi's own configuration files to a `pi-agent` directory, +and its Pi SDK session, or each terminal UI, loads them from there. Where that directory lives depends on +who else reads it: + +- **With the terminal interface:** `/.fabric/pi/runtimes//pi-agent`. + The artifact root is the runtime context's artifact directory, or + `/artifacts`. The directory stays after the runtime stops, as the + other adapters' runtime directories do. +- **With `runtime.keep_state`:** the agent's state folder (see + [Keep State Across Runtimes](#keep-state-across-runtimes)). +- **Otherwise:** a private temporary directory that `stop` removes. + +| File | Contents | +| --- | --- | +| `models.json` | The selected model's definition and endpoint, with `apiKey` set to `${}` | +| `settings.json` | Startup model, compaction reserve, cache warming off, project trust `never`, install telemetry off | +| `SYSTEM.md` | The configured system instruction, when one is set | +| `mcp.json` | The configured MCP servers, written only with the terminal interface | + +The session keeps the model key in memory, and `models.json` only names its +environment variable. With the terminal interface enabled, `api_key_env` must +be a valid environment variable name that the launcher doesn't set itself (such +as `PI_OFFLINE` or `TERM`), or startup fails with `pi_api_key_env_invalid`. +With the terminal interface or `runtime.keep_state`, which keep the endpoint on +disk, startup refuses a `base_url` that carries a user name or password +(`pi_base_url_credentials_unsupported`) or doesn't parse (`pi_base_url_invalid`). + +Only the terminal UI reads `mcp.json`. It holds the configured MCP servers as +`FabricConfig` gives them, including any literal stdio `env` values, so every +file and directory is readable only by its owner, and `stop`, or a failed start, +removes it. Values are escaped for Pi's configuration syntax, so the terminal UI +reads the same values as the session and never runs one as a shell command. +Header `${NAME}` references stay references; the terminal UI resolves them from +the runtime's environment (see [Open the Terminal TUI](#open-the-terminal-tui)). +A reference to a variable whose value is empty is resolved in the file instead, +because Pi would treat an empty value as missing and an empty value holds no +secret. +The session itself receives its MCP servers in memory. Each start +removes an `APPEND_SYSTEM.md` from the directory, and the session doesn't load +one, because `FabricConfig` never configures an appended system prompt. Pi can +add its own cache files, such as `models-store.json`. A directory that can't be +written fails startup with `pi_runtime_directory_unavailable`. + +## Keep State Across Runtimes + +The adapter accepts `runtime.keep_state`. With it, the Pi directory is the +agent's state folder, `/.fabric/state/nvidia.fabric.pi/`, +instead of `/.fabric/pi/runtimes/`, so every runtime +of the agent uses the same `pi-agent`, `pi-sessions`, and `interfaces` +directories, as the Hermes adapter uses the state folder as its Hermes home: + +- **Conversations are kept, in one session store.** Conversations in + `pi-sessions` survive a new runtime of the agent, whether an SDK runtime or a + terminal TUI wrote them. An SDK runtime starts a new conversation, and so does + each terminal TUI launch. A terminal TUI can open an earlier conversation, + including one an SDK runtime of the agent wrote, explicitly with `--resume`, + `/resume`, or `--session `. +- **`--continue` opens the most recent conversation in `pi-sessions`.** That + can be the conversation another terminal TUI is still writing. Pi doesn't lock conversation files, so two writers on one + conversation interleave their entries. To choose a conversation, use + `--resume` or `/resume`. +- **Configuration is not.** Each start rewrites `settings.json` and + `models.json` from FabricConfig, writes or removes `SYSTEM.md` and + `mcp.json` to match it, and removes `APPEND_SYSTEM.md`, so changes made from + Pi, such as `/settings`, don't survive a new runtime. +- **Logins Pi saved itself are kept, except the configured provider's.** + `pi-agent/auth.json` is written by `/login` or a key saved in the terminal UI. + Pi's terminal UI prefers a login saved there to the key `models.json` names, + so each start removes the configured provider's login, and the runtime's key + applies. Logins for other providers survive, as do Pi's own cache files. A + file Pi can't parse is left as it is, because Pi ignores it too. +- **Interfaces belong to the running runtime.** A runtime that ended without + `stop`, for example because its host was killed, can leave its + `interfaces/tui.json` attachment file and open terminal UIs behind. The next + start stops them as `stop` would: it removes `tui.json`, sends SIGTERM to + each registered terminal UI's process group, sends SIGKILL after 5 seconds, + and removes the launcher and its generated extensions before it writes its + own. A removal failure stops startup with + `pi_interface_cleanup_failed`. + +NeMo Fabric lets only one runtime of the agent use the folder at a time. A +terminal UI runs outside the adapter host's process tree, so it doesn't hold +the folder's lock: if the host is killed, its open terminal UIs keep writing to +`pi-sessions` until they close or the agent's next runtime starts and closes +them. + +## Terminal TUI + +The adapter offers two execution paths, and a runtime runs one of them: + +- **SDK:** NeMo Fabric invocations run in the embedded Pi session and return + normalized results. +- **Terminal TUI:** a person runs Pi's own terminal UI on the runtime's + configuration, in its own conversation by default. + +The SDK session and terminal UIs keep separate conversations, and NeMo Fabric's +stream collector can't tell their Relay records apart, so the schema and startup +refuse a runtime with both (`pi_execution_path_conflict`). Use separate runtimes +when you need both paths. + +Unlike the Hermes adapter's terminal TUI, Pi's has no backend service to attach +to: each terminal TUI is its own Pi process, so the interface takes no port. + +**Experimental terminal interface:** The `interfaces.terminal` configuration, +the launcher, the `interfaces/tui.json` attachment file, and the +`interfaces/tui.clients` registrations may change as NeMo Fabric adopts the +[launcher contract in #579](https://github.com/NVIDIA/NeMo-Fabric/issues/579). +Compatibility across releases is not guaranteed for these surfaces. + +### Enable the Terminal TUI + +Set `harness.settings.sdk.enabled` to `false` and enable the terminal interface +for a runtime that configures Pi for its terminal TUI: + +```python +config.harness.settings["sdk"] = {"enabled": False} +config.harness.settings["interfaces"] = {"terminal": {}} +``` + +The runtime still resolves FabricConfig, writes the agent directory, checks that +the selected model resolves, and publishes the launcher, but it creates no +embedded session. Your application can still start, check, and stop it through +the NeMo Fabric SDK. Invocation returns a failed `RunResult` with +`pi_sdk_disabled`. Startup fails with `pi_no_execution_path` when neither path +is enabled, and with `pi_execution_path_conflict` when both are. Startup checks +the configured module tool definitions and paths without importing the modules; +each terminal UI loads them in its own process, so a tool's setup runs once for +each terminal UI. With NeMo Relay telemetry enabled, the runtime still runs its +Relay gateway, for terminal TUI turns. + +The same config works on both paths: the terminal TUI reads everything else +from the agent directory, the launcher, and the runtime's environment socket. A +configured setting that only the SDK honors doesn't fail startup; the adapter +writes a `Pi warning:` line to stderr for each one instead. Today that is only +the Relay ATOF sink `nemo-fabric-stream` that `start_runtime(..., streaming=True)` +adds: terminal UI records can reach it, but without the SDK no invocation +delivers them through `invoke_stream()`. + +### Open the Terminal TUI + +With `harness.settings.interfaces.terminal` present and `enabled` not `false`, +the adapter writes an executable launcher to +`/.fabric/pi/runtimes//interfaces/terminal`, or the +agent's state folder with `runtime.keep_state`, after the runtime starts. It opens Pi's own terminal UI on the runtime's agent +directory. In an OpenShell sandbox, a person runs it with: + +```bash +openshell sandbox exec -n SANDBOX --tty -- +``` + +On a `noexec` mount, run it as `sh `. + +- The launcher runs the `pi` CLI from the Pi package the adapter uses, so the + terminal UI runs the Pi version an SDK runtime uses; `pi` needn't be on `PATH`. +- **The terminal UI gets the runtime's environment.** A terminal UI runs Pi + itself, in a process a person starts, so it wouldn't otherwise see the + runtime's `environment.env` or model key. The launcher holds paths and + switches, never secrets. It runs a launch helper that registers the process + with the runtime, fetches the runtime's `environment.env` and model key over + an owner-only Unix socket, and starts `pi` in the same process with them. + The person running the launcher doesn't need to export the key. + - The runtime's values win for their names, except the variables the launcher + sets itself (`PI_CODING_AGENT_DIR`, `PI_CODING_AGENT_SESSION_DIR`, the + offline and telemetry switches, and the Relay variables) and the ones that + describe the person's terminal (`TERM`, `COLORTERM`, `COLUMNS`, `LINES`, + `TERM_PROGRAM`, `TERM_PROGRAM_VERSION`). Everything else, such as proxy or + certificate variables the model endpoint needs that aren't in + `environment.env`, comes from the environment that runs the launcher. + - Variables that MCP header `${NAME}` references name are resolved as the SDK + session resolves them: from `environment.env`, then from the adapter's own + environment. With the terminal interface enabled, startup refuses a header + that references a variable the launcher sets itself or one that describes + the person's terminal (`pi_mcp_header_variable_reserved`), because the + terminal UI couldn't resolve it the way the SDK session does. + - Node reads startup variables such as `NODE_OPTIONS` and + `NODE_EXTRA_CA_CERTS` from that environment, as it does for the SDK session. + - The values travel from the runtime's memory to the terminal UI's process and + are never written to disk. The socket lives in a private temporary directory + while the runtime runs. `stop` closes it right after it removes `tui.json` + and before it closes terminal UIs, so only a launch that read `tui.json` + before then can still fetch the environment, and that terminal UI is + closed with the rest. Anyone who can + run the launcher runs as the same user as the adapter host. +- It turns off what an SDK session also turns off: project files, ambient + extensions, skills, prompt templates, themes, and context files such as + `AGENTS.md`. It passes the configured extensions, skills, and tool policy as + flags, and loads NeMo Fabric module tools through a generated extension. +- Each launch starts a new conversation, stored under + `/pi-sessions`; to continue a saved one, pass Pi's + `--continue`, `--session ` or `--resume` to the launcher, or use + `/resume`. With `runtime.keep_state`, the store also holds conversations from + earlier runtimes of the agent, including SDK runtimes (see + [Keep State Across Runtimes](#keep-state-across-runtimes)). +- After the runtime starts, the adapter publishes an owner-only attachment + file, `interfaces/tui.json`. Like the Hermes adapter's, it carries + `version`, `mode`, and `workspace`. Pi's has no backend port or token, so its + `mode` is `launcher`, and it adds `launcher`, `runtime_id`, `agent_dir`, + `session_dir`, and `env_socket` in place of Hermes's `port` and `token_file`. + The launcher refuses to start without it. Each launcher passes its runtime's + ID to the launch helper, which refuses a `tui.json` that names another + runtime: with `runtime.keep_state`, a later runtime of the agent publishes + `tui.json` at the same path, and an older launcher must not start Pi with its + own arguments under that runtime. +- Each terminal UI registers its process ID and process identity (its start + time, from `/proc` or `ps`) under `interfaces/tui.clients` before it fetches + the runtime's environment and rewrites the registration with a heartbeat. + Its supervisor checks `tui.json` every 500 ms; once the file is gone or names + another runtime, it asks Pi to shut down, and sends the terminal UI SIGTERM + 2 seconds later if Pi has deferred the shutdown, as it does while a command + runs. A terminal UI that can't identify or register itself closes instead + of running unmanaged, and the terminal interface needs `/proc` or `ps` on the + host (`pi_terminal_unsupported_platform`). `stop` stops them as the Hermes + adapter stops its interfaces: it removes `tui.json`, closes the environment + socket, sends SIGTERM to each registered terminal UI's process group, waits up + to 5 seconds, then sends SIGKILL. The recorded identity alone decides which + processes it signals, and `stop` checks it again before each signal: a + suspended terminal UI is still stopped, whatever its heartbeat says, and a + process that later reused a closed terminal UI's PID isn't signalled. If a + registration can't be verified (it can't be read, its identity can't be + looked up, or it was recorded by `ps` where the runtime reads `/proc`), or a + signal is denied, `stop` keeps that registration, doesn't signal it, and + fails with `pi_interface_cleanup_incomplete`, so a retried stop can verify + it. A terminal UI that still runs 2 seconds after SIGKILL, for example while + it waits on a slow disk, keeps its registration and fails `stop` the same + way. If removing `tui.json` and closing terminal UIs both fail, `stop` fails + with `pi_interface_cleanup_failed` and lists both causes. OpenShell denies + process-group signals, so in a sandbox only the terminal UI's own process is + signalled, and processes its tools started can outlive the runtime. If the + adapter host is killed, `tui.json` can remain until the sandbox is replaced + or, with `runtime.keep_state`, until the agent's next runtime starts. +- The agent runs as the same user and can modify the launcher. +- Pi's terminal UI asks no approvals; tools run as configured. +- Pi runs offline: it doesn't download `fd` or `ripgrep`. Install them in the + environment to use the tools that need them. +- With NeMo Relay telemetry enabled, the launcher also loads the configured + Relay Pi extension and sets its variables: the runtime's loopback gateway + URL, the Relay command, and the model's upstream URL. Terminal UI model + requests go through the runtime's gateway, and each terminal UI is its own + Relay session, with its own ATIF trajectory under the runtime's Relay output. + The gateway stops with the runtime, after open terminal UIs close. + +### Terminal TUI Limitations + +- **Credentials typed into the terminal UI are stored in the agent directory.** + Pi creates an empty `pi-agent/auth.json` when the terminal UI starts. Signing + in with `/login`, or saving a key from the terminal UI, writes that credential + there, readable only by its owner, and the agent directory stays after the + runtime stops; with `runtime.keep_state`, later runtimes of the agent use it, + except a login for the configured provider, which the next start removes. + Supply keys through the runtime's environment instead. +- Changes made from the terminal UI, such as `/settings` or a model switch saved + as the default, write to the runtime's agent directory. Other open terminal + UIs loaded the files at start and don't see them, and a new runtime writes its + own directory from FabricConfig, or rewrites the kept one. +- Terminal UI turns produce no NeMo Fabric run results or usage. With NeMo + Relay telemetry enabled, Relay captures them as described below, but they + aren't in any invocation's `relay_artifacts`. +- Open terminal UIs don't change the runtime's health, and their turns aren't + observed, so a passing check reports activity as `unknown`. + ## Runtime Health Local SDK callers can use `Fabric.check()` with the runtime's environment and @@ -307,6 +573,15 @@ exact runtime ID. Pi supports three ordered health levels: | `active` | Liveness plus completed extension binding and an available request interface. | | `ready` | Earlier levels plus the selected model remaining configured, required tools remaining active or callable through other tools, and required MCP transports having no observed error or closure. | +With the terminal interface enabled, `active` and `ready` also require the +launcher and `interfaces/tui.json` to exist, and a passing check reports +activity as `unknown`, as the Hermes adapter does for its native interfaces, +because terminal UI turns aren't observed. With `sdk.enabled: false`, no session +is inspected: `live` passes until stop, and `ready` requires the selected model +to resolve from the agent directory's `models.json` as the file is at each +check, without credentials or network, as a new terminal UI reads it; this is native-only +evidence, not a check of an SDK session. + Health probes use an authenticated channel during invocations. MCP failures and closures remain observable after startup. Stop and ownership changes invalidate observations collected in flight. ## Dependency Rationale diff --git a/assets/pi-invocation-paths.excalidraw b/assets/pi-invocation-paths.excalidraw new file mode 100644 index 000000000..b301fd5c7 --- /dev/null +++ b/assets/pi-invocation-paths.excalidraw @@ -0,0 +1,846 @@ +{ + "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": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-o9xkb08zz174", + "type": "text", + "x": 40, + "y": 25, + "width": 340.48, + "height": 40.0, + "strokeColor": "#245400", + "backgroundColor": "transparent", + "seed": 2081422621, + "versionNonce": 1296851430, + "updated": 1794182400000, + "fontSize": 32, + "fontFamily": 2, + "text": "Pi invocation paths", + "originalText": "Pi invocation paths", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-i7cst5nijubk", + "type": "text", + "x": 40, + "y": 73, + "width": 492.80000000000007, + "height": 25.0, + "strokeColor": "#495057", + "backgroundColor": "transparent", + "seed": 86283452, + "versionNonce": 242351397, + "updated": 1794182400000, + "fontSize": 20, + "fontFamily": 2, + "text": "Two client paths · One path for each runtime", + "originalText": "Two client paths · One path for each runtime", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": { + "type": 3 + }, + "version": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-fj2sw0qmc41o", + "type": "rectangle", + "x": 450, + "y": 130, + "width": 730, + "height": 490, + "strokeColor": "#868e96", + "backgroundColor": "#ffffff", + "seed": 679810957, + "versionNonce": 603204444, + "updated": 1794182400000 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-kbzfsyyezz5z", + "type": "text", + "x": 472, + "y": 146, + "width": 244.72000000000003, + "height": 28.75, + "strokeColor": "#868e96", + "backgroundColor": "transparent", + "seed": 531469267, + "versionNonce": 1198044756, + "updated": 1794182400000, + "fontSize": 23, + "fontFamily": 2, + "text": "NeMo Fabric runtime", + "originalText": "NeMo Fabric runtime", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": { + "type": 3 + }, + "version": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-y2tnv6qxxti3", + "type": "rectangle", + "x": 500, + "y": 190, + "width": 630, + "height": 110, + "strokeColor": "#5c7c20", + "backgroundColor": "#f4fce3", + "seed": 1990045348, + "versionNonce": 1536111028, + "updated": 1794182400000 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-pn00sr77uuty", + "type": "text", + "x": 522, + "y": 206, + "width": 246.40000000000003, + "height": 27.5, + "strokeColor": "#5c7c20", + "backgroundColor": "transparent", + "seed": 1483061771, + "versionNonce": 565442724, + "updated": 1794182400000, + "fontSize": 22, + "fontFamily": 2, + "text": "Shared configuration", + "originalText": "Shared configuration", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-7iktcnko9sdm", + "type": "text", + "x": 522, + "y": 239, + "width": 413.28000000000003, + "height": 45.0, + "strokeColor": "#343a40", + "backgroundColor": "transparent", + "seed": 645565403, + "versionNonce": 1225194432, + "updated": 1794182400000, + "fontSize": 18, + "fontFamily": 2, + "text": "Model · Instructions · Tools/MCP · Skills\nPi agent directory · NeMo Relay", + "originalText": "Model · Instructions · Tools/MCP · Skills\nPi agent directory · NeMo Relay", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": { + "type": 3 + }, + "version": 1, + "isDeleted": false, + "boundElements": [ + { + "id": "pi-agp10tqu2w5l", + "type": "arrow" + } + ], + "link": null, + "locked": false, + "id": "pi-d0i6xc98pjvz", + "type": "rectangle", + "x": 40, + "y": 340, + "width": 300, + "height": 95, + "strokeColor": "#1971c2", + "backgroundColor": "#e7f5ff", + "seed": 1860927103, + "versionNonce": 152949456, + "updated": 1794182400000 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-e5ata7k52565", + "type": "text", + "x": 62, + "y": 356, + "width": 123.20000000000002, + "height": 27.5, + "strokeColor": "#1971c2", + "backgroundColor": "transparent", + "seed": 465648809, + "versionNonce": 784860783, + "updated": 1794182400000, + "fontSize": 22, + "fontFamily": 2, + "text": "SDK client", + "originalText": "SDK client", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-08zhazhwnr30", + "type": "text", + "x": 62, + "y": 389, + "width": 262.08000000000004, + "height": 22.5, + "strokeColor": "#343a40", + "backgroundColor": "transparent", + "seed": 1017113095, + "versionNonce": 838964101, + "updated": 1794182400000, + "fontSize": 18, + "fontFamily": 2, + "text": "invoke() / invoke_stream()", + "originalText": "invoke() / invoke_stream()", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": { + "type": 3 + }, + "version": 1, + "isDeleted": false, + "boundElements": [ + { + "id": "pi-agp10tqu2w5l", + "type": "arrow" + } + ], + "link": null, + "locked": false, + "id": "pi-mmzw6n7n3igz", + "type": "rectangle", + "x": 500, + "y": 340, + "width": 630, + "height": 95, + "strokeColor": "#1971c2", + "backgroundColor": "#e7f5ff", + "seed": 1723012900, + "versionNonce": 614832991, + "updated": 1794182400000 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-dlartv2bhrhb", + "type": "text", + "x": 522, + "y": 356, + "width": 283.36, + "height": 27.5, + "strokeColor": "#1971c2", + "backgroundColor": "transparent", + "seed": 430658600, + "versionNonce": 624964293, + "updated": 1794182400000, + "fontSize": 22, + "fontFamily": 2, + "text": "Embedded Pi SDK session", + "originalText": "Embedded Pi SDK session", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-0ys4r596hnjx", + "type": "text", + "x": 522, + "y": 389, + "width": 483.84000000000003, + "height": 22.5, + "strokeColor": "#343a40", + "backgroundColor": "transparent", + "seed": 698807024, + "versionNonce": 470316165, + "updated": 1794182400000, + "fontSize": 18, + "fontFamily": 2, + "text": "On by default · in the adapter's Node.js process", + "originalText": "On by default · in the adapter's Node.js process", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": { + "type": 3 + }, + "version": 1, + "isDeleted": false, + "boundElements": [ + { + "id": "pi-92mqrr9l2izj", + "type": "arrow" + } + ], + "link": null, + "locked": false, + "id": "pi-vlpb2puzucop", + "type": "rectangle", + "x": 40, + "y": 480, + "width": 300, + "height": 95, + "strokeColor": "#2b8a3e", + "backgroundColor": "#ebfbee", + "seed": 134979795, + "versionNonce": 746749683, + "updated": 1794182400000 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-knutmfpge6vz", + "type": "text", + "x": 62, + "y": 496, + "width": 98.56, + "height": 27.5, + "strokeColor": "#2b8a3e", + "backgroundColor": "transparent", + "seed": 1158008019, + "versionNonce": 1881283542, + "updated": 1794182400000, + "fontSize": 22, + "fontFamily": 2, + "text": "Terminal", + "originalText": "Terminal", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-joz76u5nhxo3", + "type": "text", + "x": 62, + "y": 529, + "width": 221.76000000000002, + "height": 22.5, + "strokeColor": "#343a40", + "backgroundColor": "transparent", + "seed": 800024170, + "versionNonce": 2074029005, + "updated": 1794182400000, + "fontSize": 18, + "fontFamily": 2, + "text": "The runtime's launcher", + "originalText": "The runtime's launcher", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": { + "type": 3 + }, + "version": 1, + "isDeleted": false, + "boundElements": [ + { + "id": "pi-92mqrr9l2izj", + "type": "arrow" + } + ], + "link": null, + "locked": false, + "id": "pi-nq9g9z8veilz", + "type": "rectangle", + "x": 500, + "y": 480, + "width": 630, + "height": 95, + "strokeColor": "#2b8a3e", + "backgroundColor": "#ebfbee", + "seed": 1315673178, + "versionNonce": 519594767, + "updated": 1794182400000 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-ioe9aj1dljyh", + "type": "text", + "x": 522, + "y": 496, + "width": 197.12, + "height": 27.5, + "strokeColor": "#2b8a3e", + "backgroundColor": "transparent", + "seed": 1457250322, + "versionNonce": 1269793681, + "updated": 1794182400000, + "fontSize": 22, + "fontFamily": 2, + "text": "pi CLI processes", + "originalText": "pi CLI processes", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-eodhk76ddoxs", + "type": "text", + "x": 522, + "y": 529, + "width": 463.68000000000006, + "height": 22.5, + "strokeColor": "#343a40", + "backgroundColor": "transparent", + "seed": 47239105, + "versionNonce": 391586266, + "updated": 1794182400000, + "fontSize": 18, + "fontFamily": 2, + "text": "One for each terminal TUI · sdk.enabled: false", + "originalText": "One for each terminal TUI · sdk.enabled: false", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-agp10tqu2w5l", + "type": "arrow", + "x": 348, + "y": 387, + "width": 144, + "height": 0, + "strokeColor": "#1971c2", + "backgroundColor": "transparent", + "seed": 1305194690, + "versionNonce": 2044608041, + "updated": 1794182400000, + "points": [ + [ + 0, + 0 + ], + [ + 144, + 0 + ] + ], + "startBinding": { + "elementId": "pi-d0i6xc98pjvz", + "focus": 0, + "gap": 8 + }, + "endBinding": { + "elementId": "pi-mmzw6n7n3igz", + "focus": 0, + "gap": 8 + }, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-92mqrr9l2izj", + "type": "arrow", + "x": 348, + "y": 527, + "width": 144, + "height": 0, + "strokeColor": "#2b8a3e", + "backgroundColor": "transparent", + "seed": 1816867675, + "versionNonce": 2144402711, + "updated": 1794182400000, + "points": [ + [ + 0, + 0 + ], + [ + 144, + 0 + ] + ], + "startBinding": { + "elementId": "pi-vlpb2puzucop", + "focus": 0, + "gap": 8 + }, + "endBinding": { + "elementId": "pi-nq9g9z8veilz", + "focus": 0, + "gap": 8 + }, + "startArrowhead": null, + "endArrowhead": "arrow", + "elbowed": false + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-p08wmcsyye4m", + "type": "text", + "x": 40, + "y": 665, + "width": 761.6, + "height": 25.0, + "strokeColor": "#212529", + "backgroundColor": "transparent", + "seed": 469678021, + "versionNonce": 1671935995, + "updated": 1794182400000, + "fontSize": 20, + "fontFamily": 2, + "text": "• Same Pi version and configuration files; a runtime runs one path.", + "originalText": "• Same Pi version and configuration files; a runtime runs one path.", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25 + }, + { + "angle": 0, + "fillStyle": "solid", + "strokeWidth": 2, + "strokeStyle": "solid", + "roughness": 0, + "opacity": 100, + "groupIds": [], + "frameId": null, + "roundness": null, + "version": 1, + "isDeleted": false, + "boundElements": null, + "link": null, + "locked": false, + "id": "pi-vn2g5h9m6lc7", + "type": "text", + "x": 40, + "y": 705, + "width": 840.0000000000001, + "height": 50.0, + "strokeColor": "#212529", + "backgroundColor": "transparent", + "seed": 1653272687, + "versionNonce": 1527938705, + "updated": 1794182400000, + "fontSize": 20, + "fontFamily": 2, + "text": "• SDK returns normalized results; terminal TUIs show native output.\n NeMo Relay records each SDK session and terminal TUI as its own session.", + "originalText": "• SDK returns normalized results; terminal TUIs show native output.\n NeMo Relay records each SDK session and terminal TUI as its own session.", + "textAlign": "left", + "verticalAlign": "top", + "containerId": null, + "autoResize": true, + "lineHeight": 1.25 + } + ], + "appState": { + "viewBackgroundColor": "#ffffff", + "gridSize": null + }, + "files": {} +} diff --git a/assets/pi-invocation-paths.png b/assets/pi-invocation-paths.png new file mode 100644 index 000000000..886a42de0 Binary files /dev/null and b/assets/pi-invocation-paths.png differ diff --git a/docs/about-nemo-fabric/supported-harnesses.mdx b/docs/about-nemo-fabric/supported-harnesses.mdx index df05c55a2..aef87b08c 100644 --- a/docs/about-nemo-fabric/supported-harnesses.mdx +++ b/docs/about-nemo-fabric/supported-harnesses.mdx @@ -24,7 +24,7 @@ NVIDIA NeMo Fabric includes adapters for the following harnesses and execution t | [OpenClaw](../integrations/harness/openclaw/openclaw.mdx) | ✓ | ✓ | ✓ | — | ✓ | | [OpenHands](../integrations/harness/openhands.mdx) | ✓ | ✓ | ✓ | — | — | | [OpenCode](../integrations/harness/opencode.mdx) | — | ✓ | ✓ | — | — | -| [Pi](../integrations/harness/pi.mdx) | ✓ | — | ✓ | ✓ | — | +| [Pi](../integrations/harness/pi/pi.mdx) | ✓ | ✓ | ✓ | ✓ | ✓ | | [Qwen Code](../integrations/harness/qwen.mdx) | ✓ | ✓ | ✓ | — | — | | [Remote Agent](../integrations/harness/remote-agent.mdx) | — | — | — | ✓ | — | diff --git a/docs/getting-started/install-adapters.mdx b/docs/getting-started/install-adapters.mdx index f62386b00..2682140ba 100644 --- a/docs/getting-started/install-adapters.mdx +++ b/docs/getting-started/install-adapters.mdx @@ -164,7 +164,7 @@ For a separate runtime interpreter, follow [Install an Adapter and Harness Witho | OpenClaw | [Install the OpenClaw adapter](../integrations/harness/openclaw/openclaw.mdx#install-openclaw-and-the-adapter) | | OpenHands | [Install the OpenHands adapter](../integrations/harness/openhands.mdx#install-the-adapter) | | OpenCode | [Install the OpenCode adapter](../integrations/harness/opencode.mdx#install-the-adapter) | -| Pi | [Install the Pi adapter](../integrations/harness/pi.mdx#install-the-adapter) | +| Pi | [Install the Pi adapter](../integrations/harness/pi/pi.mdx#install-the-adapter) | | Qwen Code | [Install the Qwen Code adapter](../integrations/harness/qwen.mdx#install-the-adapter) | | Remote Agent | [Install the Remote Agent adapter](../integrations/harness/remote-agent.mdx#install-the-adapter) | diff --git a/docs/getting-started/install-relay.mdx b/docs/getting-started/install-relay.mdx index 482be947f..39d899a35 100644 --- a/docs/getting-started/install-relay.mdx +++ b/docs/getting-started/install-relay.mdx @@ -127,7 +127,8 @@ Set directory; relative paths resolve from `environment.workspace`. Relay-enabled Pi configurations must also set `runtime.artifacts` so NeMo Fabric can provide the adapter-owned Relay configuration. Refer to the -[Pi adapter guide](../integrations/harness/pi.mdx) for the complete -configuration and the embedded collector streaming workflow. Do not set +[Pi adapter guide](../integrations/harness/pi/pi.mdx#nemo-relay) for the complete +configuration and the [Pi SDK guide](../integrations/harness/pi/pi-sdk.mdx#stream-relay-records) +for the embedded collector streaming workflow. Do not set `launch_collector=False` for Pi streaming because the Pi extension does not attach the NeMo Fabric request IDs required by an externally managed collector. diff --git a/docs/index.yml b/docs/index.yml index 60b661856..54d699b61 100644 --- a/docs/index.yml +++ b/docs/index.yml @@ -164,8 +164,14 @@ navigation: path: ./integrations/harness/openhands.mdx - page: OpenCode path: ./integrations/harness/opencode.mdx - - page: Pi - path: ./integrations/harness/pi.mdx + - section: Pi + collapsed: true + path: ./integrations/harness/pi/pi.mdx + contents: + - page: SDK + path: ./integrations/harness/pi/pi-sdk.mdx + - page: Terminal TUI + path: ./integrations/harness/pi/pi-tui.mdx - page: Qwen Code path: ./integrations/harness/qwen.mdx - page: Remote Agent diff --git a/docs/integrations/harness/overview.mdx b/docs/integrations/harness/overview.mdx index 93f93a827..d0bea9b53 100644 --- a/docs/integrations/harness/overview.mdx +++ b/docs/integrations/harness/overview.mdx @@ -28,7 +28,7 @@ NeMo Fabric includes the following harness integrations: | 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) | +| Pi | [Use the Pi adapter](./pi/pi.mdx) | | Qwen Code | [Use the Qwen Code adapter](./qwen.mdx) | | Remote Agent | [Use the Remote Agent adapter](./remote-agent.mdx) | diff --git a/docs/integrations/harness/pi/pi-sdk.mdx b/docs/integrations/harness/pi/pi-sdk.mdx new file mode 100644 index 000000000..efd51c2be --- /dev/null +++ b/docs/integrations/harness/pi/pi-sdk.mdx @@ -0,0 +1,151 @@ +--- +title: Pi SDK +description: Invoke the embedded Pi session with normalized configuration and results. +slug: /integrations/harness-integrations/pi-sdk +--- +{/* SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: Apache-2.0 */} + +Start with [pi.mdx](./pi.mdx) for shared setup and an overview of both execution paths. + +NVIDIA NeMo Fabric's Pi SDK path executes requests through an embedded Pi SDK session in the adapter's Node.js process. It returns normalized results and reuses conversation history across ordered invocations. + +## Installation + +Complete the [shared installation](./pi.mdx#install-the-adapter). The SDK path requires no interface-specific packages. + +## Configure the Adapter + +Use the [shared configuration](./pi.mdx#shared-configuration) for the model, instructions, tools, skills, extensions, MCP servers, and NeMo Relay. The SDK session is the default execution path, so an SDK runtime needs no execution-path settings. + +### Pi Settings + +The descriptor uses closed schemas, so unknown settings are rejected. + +| Setting | Default | Behavior | +| --- | --- | --- | +| `sdk.enabled` | `true` | Initialize the embedded SDK session. Set to `false`, with the terminal interface enabled, for a [terminal TUI runtime](./pi-tui.mdx); SDK invocation then fails with `pi_sdk_disabled`, while runtime management remains available. | +| `interfaces.terminal` | Off | Offer Pi's terminal TUI instead of the SDK session. Refer to the [terminal TUI guide](./pi-tui.mdx). | +| `extensions` | `[]` | Workspace-relative Pi extension files, loaded as trusted code. | +| `relay_extension_path` | None | The NeMo Relay Pi extension; refer to [NeMo Relay](./pi.mdx#nemo-relay). | +| `insecure_http_model_hosts` | Omitted | Hosts trusted for credential-free HTTP model forwarding; refer to [Credential-Free HTTP Model Gateways](./pi.mdx#credential-free-http-model-gateways). | + +## Invoke and Stream + +With `config` from the [shared configuration](./pi.mdx#shared-configuration), invoke the runtime through the public SDK: + +```python +from nemo_fabric import Fabric + +async with await Fabric().start_runtime(config) as runtime: + result = await runtime.invoke(input="List the files in the workspace.") + print(result.output) +``` + +`Runtime.invoke_stream()` uses Relay-backed event streaming; retrieve its normalized result with `stream.result()`. Refer to [Stream Relay Records](#stream-relay-records) for the Pi setup and to [streaming](../../../sdk/streaming.mdx#nemo-relay-streaming) for the SDK usage pattern. + +## Lifecycle and Conversations + +Each NeMo Fabric runtime owns one in-memory Pi session in a persistent Node.js +adapter process. Ordered invocations reuse that session and its conversation +history until the runtime stops. Start a new runtime to change the model, +skills, extensions, custom tools, or workspace. + +The session loads its settings, model catalog, and system prompt from the +runtime's [agent directory](./pi.mdx#agent-directory-and-kept-state), as the +`pi` CLI does, and gets its MCP servers and model key in memory. With +`runtime.keep_state`, each runtime starts a new conversation and writes it to +the agent's shared session store, where a later terminal TUI runtime can open +it. + +The Pi adapter doesn't declare `session_resume`, so an SDK runtime can't resume +an earlier conversation: starting a runtime with a `session_ref` fails with +`session_resume_unsupported`. + +Evaluation consumers, including Harbor, invoke through the SDK, so they need +the SDK session, its default. A terminal TUI runtime can't run SDK evaluation +trials. + +## Invocation Usage + +Each invocation reads only new entries from Pi's raw session ledger, including +retained failed attempts, compaction and branch summaries, nested tool usage, +and auxiliary usage records. Automatic cache warming is disabled so background +refresh calls cannot escape the invocation boundary. Session history and previous invocations are not +counted again. Input totals include cache reads and cache writes; output totals +already include reasoning tokens. Available breakdowns are returned through +`nemo_fabric.detailed_token_usage.v1`. + +Missing or inconsistent usage leaves the complete counters unknown. Pi 1.0.3 +initializes unreported provider usage to zero, so an all-zero record also remains +unknown. A failed or retried summary can omit attempt usage from the ledger; +complete counters remain unknown in that case. Nonzero records can retain real +zero input, output, or cache dimensions. Configured-rate SDK cost estimates are +not published as provider-reported `cost_usd`. + +## Results and Relay + +With [NeMo Relay](./pi.mdx#nemo-relay) enabled, the result includes +`relay_runtime` and `relay_artifacts` in `output`. + +The matching Relay Pi extension emits `turn_end` and closes the per-turn +scope, but its local ATIF trajectory remains attached to Pi's session-level +agent scope. Relay therefore finalizes that trajectory only after the Pi session +closes. It is not included in the invocation's `relay_artifacts`. The adapter +does not wait for local ATIF during invocation. It collects per-invocation +artifacts such as ATOF and returns the result. After runtime shutdown, retrieve +the finalized file directly from the ATIF output directory. For the +[shared Relay configuration](./pi.mdx#nemo-relay) and the default filename template, it is written to +`./artifacts/relay//trajectory-.atif.json`. Invocation +results do not prevent subsequent turns. + +Pi emits its startup `model_redirect` marks before NeMo Fabric registers an +invocation, so they are not included in the per-invocation records from +`invoke_stream()`. + +### Stream Relay Records + +Install the matching collector for the embedded streaming path: + +```bash +pip install "nemo-fabric[streaming]" +``` + +Start the runtime with streaming enabled to consume live model-turn ATOF +records for successful Relay redirects in one Pi invocation: + +```python +from nemo_fabric import Fabric + +async with await Fabric().start_runtime(config, streaming=True) as runtime: + stream = runtime.invoke_stream(input="Review the latest patch") + async for record in stream: + print(record) + result = await stream.result() +``` + +The terminal `RunResult` remains separate from the ATOF records. Fully consume +each stream, or call `await stream.aclose()` if iteration stops early, before +starting another invocation. The same runtime can then alternate +`invoke_stream()` and `invoke()` calls. The embedded collector serializes both +methods behind one Pi invocation lease. Streaming capture begins at the first +Pi `turn_start` and closes at `agent_settled`. If Relay output is interrupted or +late, the collector waits for a bounded interval, then admits the next native +invocation and uses Pi's cumulative turn count to discard ambiguous delayed +records until a higher `turn_start` arrives. This can thin the ATOF stream but +does not block later invocations. Increase `completion_wait_timeout` from its +one-second default when Relay delivery can take longer. Use the default embedded +collector for Pi streaming. The Pi extension does not attach NeMo Fabric +request IDs, so +`start_runtime(..., streaming=True, launch_collector=False)` cannot correlate +its records through an externally managed collector. + +This Relay-backed path runs the adapter's ordinary `invoke` operation. It is +independent of native OpenAI streaming, so the adapter descriptor's +`capabilities.streaming` value remains `false`. + +## Health and Limitations + +Runtime health and `idle`/`busy` activity describe the SDK session; refer to +[Health Checks](../../../sdk/health-checks.mdx). Read the +[shared limitations](./pi.mdx#limitations-and-planned-work). diff --git a/docs/integrations/harness/pi/pi-tui.mdx b/docs/integrations/harness/pi/pi-tui.mdx new file mode 100644 index 000000000..e99480ed2 --- /dev/null +++ b/docs/integrations/harness/pi/pi-tui.mdx @@ -0,0 +1,98 @@ +--- +title: Pi Terminal TUI +description: Open Pi's own terminal UI on a managed runtime's configuration and + environment. +slug: /integrations/harness-integrations/pi-terminal-tui +--- +{/* SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: Apache-2.0 */} + +Start with [pi.mdx](./pi.mdx) for shared setup and an overview of both execution paths. + +NVIDIA NeMo Fabric's Pi terminal path opens Pi's own terminal UI, the stock `pi` CLI, on a runtime's configuration. Pi has no backend for a terminal client to attach to, so each terminal TUI runs the agent in its own process, which a person starts with the runtime's launcher. Unlike the Hermes and OpenClaw terminal TUIs, it takes no port. + +**Experimental terminal interface:** The `interfaces.terminal` configuration, the launcher, the `interfaces/tui.json` attachment file, and the `interfaces/tui.clients` registrations may change as NeMo Fabric adopts the [launcher contract in #579](https://github.com/NVIDIA/NeMo-Fabric/issues/579). Compatibility across releases is not guaranteed for these surfaces. + +## Installation + +Complete the [shared installation](./pi.mdx#install-the-adapter) first. The launcher runs the `pi` CLI bundled with the adapter's Pi dependency, so the terminal TUI needs no other packages. It additionally requires: + +- **Host:** POSIX, with `/proc` or `ps` to identify terminal TUI processes. Otherwise startup fails with `pi_terminal_unsupported_platform`. +- **Node.js:** the Node.js runtime that runs the adapter, which the launcher names. + +## Configuration + +Start from the [shared configuration](./pi.mdx#shared-configuration) and replace its `harness` with this one, which that example passes to `FabricConfig` as `harness=harness`: + +```python +from nemo_fabric import HarnessConfig + +harness = HarnessConfig( + adapter_id="nvidia.fabric.pi", + settings={ + "sdk": {"enabled": False}, + "interfaces": {"terminal": {}}, + }, +) +``` + +A runtime runs either the SDK session or terminal TUIs. Planning and startup refuse the terminal interface while `sdk.enabled` is on, its default, with `pi_execution_path_conflict`. A terminal TUI runtime still writes the agent directory and the launcher, and your application can still start, check, and stop it, but it runs no embedded session: invocation returns a failed `RunResult` with `pi_sdk_disabled`. + +The same `FabricConfig` works on both paths. A setting that only the SDK session honors logs a `Pi warning:` line at startup instead of failing it; today that is only the Relay ATOF sink that `start_runtime(..., streaming=True)` adds, which delivers records through `invoke_stream()`. + +With the terminal interface enabled, `api_key_env` must be a valid environment variable name that the launcher doesn't set itself (`pi_api_key_env_invalid`), and MCP headers can't reference such a variable either (`pi_mcp_header_variable_reserved`). + +## Runtime Environment + +A terminal TUI runs Pi itself, in a process a person starts, so it gets the runtime's environment from the running runtime rather than from a backend. The launcher holds no secrets. It runs a launch helper that fetches the runtime's `environment.env` and model key over an owner-only Unix socket and starts Pi with them, so you don't export the key before running the launcher. + +- **Precedence:** The runtime's values win for their names, except the variables the launcher sets itself and those that describe your terminal, such as `TERM` and `COLUMNS`. +- **Shell variables:** Proxy or certificate variables that aren't in `environment.env` come from the environment that runs the launcher. +- **Storage:** Nothing is written to disk. Stopping the runtime closes the socket, so a launcher run after stop can't start Pi. + +## Attachment File + +After the runtime is ready, it publishes an owner-only `interfaces/tui.json` attachment file. It shares `version`, `mode`, and `workspace` with the Hermes adapter's `tui.json`. Its `launcher` mode names the launcher, the runtime ID, Pi's agent and session directories, and the environment socket instead of a backend port and token. The launcher refuses to start without it, or with one that another runtime of the agent published at the same path. + +## Open a Terminal TUI + +The runtime writes the launcher at `interfaces/terminal` in its Pi directory: `/.fabric/pi/runtimes/`, or the agent's state folder with `runtime.keep_state`. Run it from an interactive terminal as the user that runs the runtime. In an OpenShell sandbox, run it with: + +```bash +openshell sandbox exec -n SANDBOX --tty -- +``` + +The launcher passes Pi's own arguments through. Its flags reproduce the SDK session's isolation and tool policy, and it loads NeMo Fabric module tools through a generated extension, so each terminal TUI loads them in its own process. + +Each launch starts a new conversation. Pass `--continue`, `--session `, or `--resume`, or use `/resume`, to open a saved one. `--continue` opens the most recent conversation in `pi-sessions`, which can be one another terminal TUI is still writing. Pi doesn't lock conversation files, so two writers on one conversation interleave their entries; use `--resume` or `/resume` to pick a conversation. With [`runtime.keep_state`](./pi.mdx#keep-state-across-runtimes), conversations from earlier runtimes of the agent, including SDK runtimes, are listed too. + +Quitting a terminal TUI ends only that `pi` process; the runtime and any other terminal TUIs keep running, and the conversation stays in `pi-sessions`. + +### Credentials + +Credentials entered in the terminal TUI, for example with `/login`, are saved in the runtime's agent directory, which stays after the runtime stops and, with `runtime.keep_state`, serves later runtimes of the agent. A login saved for the configured provider lasts only until the next start, which removes it so the runtime's key applies; logins for other providers stay. Supply keys through the runtime's environment instead. + +## Relay + +With NeMo Relay telemetry enabled, the launcher loads the Relay Pi extension on the runtime's Relay gateway, so Relay captures each terminal TUI as its own session, with its own trajectory. Terminal output is native; it is not a normalized NeMo Fabric `RunResult`. + +## Stop and Health + +Each terminal TUI registers itself, with its process identity, in `interfaces/tui.clients` before it fetches the runtime's environment, and closes itself when `tui.json` disappears or names another runtime. A terminal TUI that can't identify or register itself closes instead of running unmanaged. + +Stopping the runtime: + +1. Removes `tui.json` and closes the environment socket. +2. Sends SIGTERM to each registered terminal TUI's process group, and SIGKILL to any still running 5 seconds later. A suspended terminal TUI is stopped too. + +Stop signals only processes whose recorded identity it verifies, and checks again before each signal, so a reused process ID isn't signalled. If it can't verify a terminal TUI, a signal is denied, or a terminal TUI still runs 2 seconds after SIGKILL (for example, while it waits on a slow disk), stop keeps its registration and fails with `pi_interface_cleanup_incomplete`, so a retried stop can try again. When more than one cleanup step fails, stop fails with `pi_interface_cleanup_failed` and lists each cause. In an OpenShell sandbox, which denies process-group signals, only the terminal TUI's own process is signalled. + +For a terminal TUI runtime, `active` and `ready` health checks also require the launcher and `interfaces/tui.json`, and passing checks report `unknown` activity, as for Hermes. `ready` also loads `models.json` as it is at each check, as a new terminal TUI would, and requires the selected model to resolve from it. + +## Try It and Review Limitations + +Use the [Pi interface example](../../../../examples/interfaces/pi/README.md) to open a terminal TUI by hand or run a scripted demo across two kept-state runtimes. Read the [shared limitations](./pi.mdx#limitations-and-planned-work). + +- Processes that a terminal TUI's tools start can outlive the runtime in an OpenShell sandbox, because process-group signals are denied there ([#568](https://github.com/NVIDIA/NeMo-Fabric/issues/568)). +- Terminal TUI conversations aren't collected as NeMo Fabric artifacts yet. +- Terminal TUIs share the runtime's filesystem and tools; separate conversations do not provide user isolation. diff --git a/docs/integrations/harness/pi.mdx b/docs/integrations/harness/pi/pi.mdx similarity index 58% rename from docs/integrations/harness/pi.mdx rename to docs/integrations/harness/pi/pi.mdx index ecc75c7c1..985b34dd9 100644 --- a/docs/integrations/harness/pi.mdx +++ b/docs/integrations/harness/pi/pi.mdx @@ -1,31 +1,29 @@ --- title: Use the Pi Adapter -description: Install and configure the NVIDIA NeMo Fabric harness integration for - Pi. +description: Choose the embedded SDK session or Pi's terminal TUI for a runtime, both + on one Pi configuration. slug: /integrations/harness-integrations/pi --- {/* SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. SPDX-License-Identifier: Apache-2.0 */} -Use the NVIDIA NeMo Fabric `nvidia.fabric.pi` adapter to run tasks with the Pi -SDK in a persistent Node.js process. +You can use Pi through the NVIDIA NeMo Fabric `nvidia.fabric.pi` adapter in two ways: -## Invocation Usage +- **SDK:** Invoke an embedded Pi session programmatically and receive normalized NeMo Fabric results. +- **Terminal TUI:** Chat with Pi in its own terminal UI, the stock `pi` CLI, on the runtime's configuration. -Each invocation reads only new entries from Pi's raw session ledger, including -retained failed attempts, compaction and branch summaries, nested tool usage, -and auxiliary usage records. Automatic cache warming is disabled so background -refresh calls cannot escape the invocation boundary. Session history and previous invocations are not -counted again. Input totals include cache reads and cache writes; output totals -already include reasoning tokens. Available breakdowns are returned through -`nemo_fabric.detailed_token_usage.v1`. +SDK execution is enabled by default; the terminal TUI is an explicit option. A runtime runs one of the two. Both paths use the normalized `FabricConfig`, which the adapter translates into Pi's own configuration files. -Missing or inconsistent usage leaves the complete counters unknown. Pi 1.0.3 -initializes unreported provider usage to zero, so an all-zero record also remains -unknown. A failed or retried summary can omit attempt usage from the ledger; -complete counters remain unknown in that case. Nonzero records can retain real -zero input, output, or cache dimensions. Configured-rate SDK cost estimates are -not published as provider-reported `cost_usd`. +![Two client invocation paths share one Pi configuration within a NeMo Fabric runtime: the embedded SDK session by default, or one pi CLI process for each terminal TUI when the SDK session is off.](../../../../assets/pi-invocation-paths.png) + +| Path | Execution backend | Guide | +| --- | --- | --- | +| SDK | Embedded Pi SDK session in the adapter's Node.js process | [Pi SDK](./pi-sdk.mdx) | +| Terminal TUI | One `pi` CLI process for each terminal TUI, started by a person with the runtime's launcher | [Pi Terminal TUI](./pi-tui.mdx) | + +- **Agent execution:** Both paths run the same Pi version on the same configuration files. Pi has no backend that a terminal client attaches to, so each terminal TUI runs the agent in its own process. +- **One path for each runtime:** The SDK session and terminal TUIs keep separate conversations, and NeMo Fabric's stream collector can't tell their NeMo Relay records apart. Use separate runtimes when you need both paths. +- **Runtime ownership:** A runtime owns its SDK session, or the terminal TUIs it launched, and stops them when it stops. ## Install the Adapter @@ -48,6 +46,8 @@ packages returns `pi_harness_unavailable`. The supported SDK packages are pinned together at 1.0.3. The coding-agent package otherwise permits newer `pi-codemode` versions with incompatible exports; installing all four packages keeps fresh installs on the tested combination. +The terminal TUI runs the `pi` CLI from the same `@earendil-works/pi-coding-agent` +package, so it needs no separate installation. ### Install for Source Development @@ -82,9 +82,42 @@ FABRIC_NEMO_RELAY_COMMAND="/absolute/path/to/nemo-relay" uv run python your_app. The adapter uses the selected executable to start the Relay gateway. With Relay 0.11, the Pi extension also uses that executable to forward hook events. Relay 0.9 and 0.10 extensions send hook events directly over HTTP. When the runtime stops, the adapter restores the extension's previous command setting. -Use the [Pi extension](https://github.com/NVIDIA/NeMo-Relay/tree/0.11.0/crates/cli/assets/pi-extension) from the same Relay release as the command-line tool. Configure the extension path as shown in the next section. +Use the [Pi extension](https://github.com/NVIDIA/NeMo-Relay/tree/0.11.0/crates/cli/assets/pi-extension) from the same Relay release as the command-line tool. Configure the extension path as shown in [NeMo Relay](#nemo-relay). + +## Select an Execution Path + +Use normalized `FabricConfig` fields for the model, instructions, tools, skills, MCP servers, workspace, and telemetry. Use `harness.settings` to select the execution path. The following `harness` offers the terminal TUI; define it in place of the one in the [shared configuration](#shared-configuration), which passes it to `FabricConfig`: + +```python +from nemo_fabric import HarnessConfig + +harness = HarnessConfig( + adapter_id="nvidia.fabric.pi", + settings={ + "sdk": {"enabled": False}, + "interfaces": {"terminal": {}}, + }, +) +``` + +Omit both settings to run the embedded SDK session. A present `interfaces.terminal` is on unless its `enabled` is `false`, and it takes no port. + +- **Terminal TUI:** requires `sdk.enabled: false`. Planning and startup refuse a runtime with both the SDK session and the terminal interface with `pi_execution_path_conflict`. +- **No execution path:** planning and startup refuse `sdk.enabled: false` without the terminal interface with `pi_no_execution_path`. +- **Host:** the terminal interface requires POSIX, and `/proc` or `ps` to identify terminal TUI processes. Otherwise startup fails with `pi_terminal_unsupported_platform`. + +## What NeMo Fabric Normalizes -## Configure the Adapter +| Surface | SDK | Terminal TUI | +| --- | --- | --- | +| Configuration | Pi's configuration files written from `FabricConfig`, loaded by the embedded session | The same files, loaded by each `pi` CLI process | +| Lifecycle | Runtime startup and owned shutdown | The runtime publishes a launcher; stop closes every terminal TUI it launched | +| Results | Normalized `RunResult` | Native terminal output; no normalized invocation result | +| Relay evidence | ATOF for each invocation, `invoke_stream()` records, and an ATIF trajectory written when the session closes | Each terminal TUI is its own Relay session with its own trajectory | +| Usage | Per-invocation token usage from Pi's session ledger | Not collected | +| Session artifacts | SDK invocation artifact collection | Collection of terminal TUI conversations is planned | + +## Shared Configuration Select the Pi harness integration and point NeMo Fabric discovery at the adapter descriptor. The following example uses the descriptor from an installed @@ -94,6 +127,10 @@ npm package: from nemo_fabric import DiscoveryConfig, FabricConfig, HarnessConfig from nemo_fabric import MetadataConfig, ModelConfig, ToolsConfig +# The SDK session. For the terminal TUI, use the harness from +# "Select an Execution Path" instead. +harness = HarnessConfig(adapter_id="nvidia.fabric.pi") + config = FabricConfig( metadata=MetadataConfig(name="pi-review"), discovery=DiscoveryConfig( @@ -101,7 +138,7 @@ config = FabricConfig( "./node_modules/nemo-fabric-adapters-pi/pi.fabric-adapter.json" ] ), - harness=HarnessConfig(adapter_id="nvidia.fabric.pi"), + harness=harness, models={ "default": ModelConfig( provider="nvidia", @@ -122,6 +159,8 @@ system instructions, tool policy, explicit skill paths, and explicit local Pi extensions. Set `models..api_key_env` to the name of the environment variable that contains the provider credential. +### Models + The selected model can be either a model Pi already ships (addressed by its built-in `provider`/`model`) or a model served by an OpenAI-compatible gateway that Pi does not ship. For a Pi-known model, set only `provider`, `model`, and @@ -184,7 +223,7 @@ ModelConfig( The example uses zero cost rates, so Pi calculates zero token cost. Set the rates for your endpoint when you need cost estimates. -## Configure Skills and Extensions +### Skills and Extensions Add normalized skill paths with the Python SDK. NeMo Fabric resolves these paths from the `base_dir` passed to `plan()`, `doctor()`, or `run()`: @@ -203,7 +242,7 @@ config.harness.settings["extensions"] = ["extensions/review.ts"] The adapter loads only the skill and extension paths in the configuration. It does not load ambient Pi resources from the user profile or workspace. -## Configure MCP Servers +### MCP Servers Add normalized MCP servers through the Python SDK: @@ -227,100 +266,9 @@ config.add_mcp_server( The adapter maps stdio and streamable HTTP servers to Pi's native MCP extension. Stdio servers can define `args` and `env`, but not HTTP headers. Streamable HTTP servers can define `custom_headers`, but not process arguments or environment variables. Remote endpoints require HTTPS, except for loopback development endpoints. -Header values can reference `${NAME}`. Resolution checks the NeMo Fabric runtime environment first and then the adapter process environment. The adapter maps `allowed_tools` and `blocked_tools` to Pi's per-server tool exposure. Normalized MCP authentication and MCP extensions are not supported. Only servers supplied by NeMo Fabric are loaded; ambient Pi MCP configuration remains disabled. - -## Configure NeMo Relay - -Enable Relay with the standard NeMo Fabric configuration and provide the Relay -Pi extension as an adapter setting: - -```python -config.runtime.artifacts = "./artifacts/pi" -config.enable_relay(output_dir="./artifacts/relay") -config.harness.settings["relay_extension_path"] = ( - "/path/to/NeMo-Relay/crates/cli/assets/pi-extension" -) -``` - -Relay requires `runtime.artifacts` so NeMo Fabric can create the runtime-owned -configuration passed to the adapter. The extension path can be absolute or -relative to `environment.workspace`. It can identify a JavaScript or TypeScript -file or a Pi extension package directory. Unlike user-configured Pi extensions, -the Relay extension does not need to remain inside `environment.workspace` when -an absolute path is used. - -When the runtime starts, the adapter validates the Relay CLI version, writes an -explicit `plugins.toml`, starts a loopback gateway, and loads the extension into -the isolated Pi session. The result includes `relay_runtime` and -`relay_artifacts` in `output`. The gateway can produce ATOF, ATIF, -OpenTelemetry, and OpenInference output from the Relay observability -configuration. - -The adapter supports one Relay-enabled Pi runtime per adapter process because -the Relay Pi extension receives its gateway and upstream configuration through -process environment variables. NeMo Fabric starts each runtime in a separate -adapter process, so concurrent NeMo Fabric runtimes remain isolated. Direct -embedders must likewise place concurrent Relay-enabled Pi runtimes in separate -processes. - -The matching Relay Pi extension emits `turn_end` and closes the per-turn -scope, but its local ATIF trajectory remains attached to Pi's session-level -agent scope. Relay therefore finalizes that trajectory only after the Pi session -closes. It is not included in the invocation's `relay_artifacts`. The adapter -does not wait for local ATIF during invocation. It collects per-invocation -artifacts such as ATOF and returns the result. After runtime shutdown, retrieve -the finalized file directly from the ATIF output directory. For the -configuration above and the default filename template, it is written to -`./artifacts/relay//trajectory-.atif.json`. Invocation -results do not prevent subsequent turns. - -Session, turn, and tool telemetry does not depend on model redirection. Model -telemetry is available only when Relay supports the selected model API and the -gateway upstream matches the model endpoint. Relay records a skipped redirect -as a `model_redirect` mark with the reason in configured ATOF artifacts. Pi -emits its startup redirect marks before NeMo Fabric registers an invocation, so -they are not included in the per-invocation records from `invoke_stream()`. - -Install the matching collector for the embedded streaming path: - -```bash -pip install "nemo-fabric[streaming]" -``` - -Start the runtime with streaming enabled to consume live model-turn ATOF -records for successful Relay redirects in one Pi invocation: +Header values can reference `${NAME}`. Resolution checks the NeMo Fabric runtime environment first and then the adapter process environment, on both paths. The adapter maps `allowed_tools` and `blocked_tools` to Pi's per-server tool exposure. Normalized MCP authentication and MCP extensions are not supported. Only servers supplied by NeMo Fabric are loaded; ambient Pi MCP configuration remains disabled. -```python -from nemo_fabric import Fabric - -async with await Fabric().start_runtime(config, streaming=True) as runtime: - stream = runtime.invoke_stream(input="Review the latest patch") - async for record in stream: - print(record) - result = await stream.result() -``` - -The terminal `RunResult` remains separate from the ATOF records. Fully consume -each stream, or call `await stream.aclose()` if iteration stops early, before -starting another invocation. The same runtime can then alternate -`invoke_stream()` and `invoke()` calls. The embedded collector serializes both -methods behind one Pi invocation lease. Streaming capture begins at the first -Pi `turn_start` and closes at `agent_settled`. If Relay output is interrupted or -late, the collector waits for a bounded interval, then admits the next native -invocation and uses Pi's cumulative turn count to discard ambiguous delayed -records until a higher `turn_start` arrives. This can thin the ATOF stream but -does not block later invocations. Increase `completion_wait_timeout` from its -one-second default when Relay delivery can take longer. Use the default embedded -collector for Pi streaming. The Pi extension does not attach NeMo Fabric -request IDs, so -`start_runtime(..., streaming=True, launch_collector=False)` cannot correlate -its records through an externally managed collector. - -This Relay-backed path runs the adapter's ordinary `invoke` operation. It is -independent of native OpenAI streaming, so the adapter descriptor's -`capabilities.streaming` value remains `false`. - -## Configure a NeMo Fabric Tool Definition +### Tool Definitions Pi accepts trusted local JavaScript and TypeScript tool factories. The normalized definition uses `kind: "module"`; `ref` is relative to the NeMo Fabric @@ -359,33 +307,66 @@ config.tools.enabled = ["read", "review_context"] The factory receives `{ name, settings, workspace }` and returns a Pi `ToolDefinition` with the same name. Tool modules and explicit Pi extensions -run as trusted code in the adapter process. The adapter rejects paths outside -the workspace and duplicate names across built-ins, NeMo Fabric definitions, -and extensions. +run as trusted code. The adapter rejects paths outside the workspace and a +NeMo Fabric definition named like a Pi built-in tool. The SDK session also +rejects a name that a NeMo Fabric definition and an explicit extension share; +a terminal TUI leaves that collision to Pi, which reports it as a diagnostic +and resolves it by load order. -## Understand the Runtime Lifecycle +The process that runs the agent loads the tools. The SDK session loads each +module in the adapter process at startup. A terminal TUI runtime only checks +the definitions at startup, without importing the modules, and each terminal +TUI loads them in its own process. A tool's setup therefore runs once for each +Pi process, so a tool that binds a fixed local port can serve only one +terminal TUI at a time. -Each NeMo Fabric runtime owns one in-memory Pi session in a persistent Node.js -adapter process. Ordered invocations reuse that session and its conversation -history until the runtime stops. Start a new runtime to change the model, -skills, extensions, custom tools, or workspace. +### NeMo Relay -## Current Limitations +Enable Relay with the standard NeMo Fabric configuration and provide the Relay +Pi extension as an adapter setting: -The current adapter does not expose native OpenAI streaming, caller-driven -cancellation, or remote-service execution. Enabling a third-party extension -can add extension-defined skills, prompts, or themes even though ambient Pi -resources remain disabled. The Relay extension does not add those resources. +```python +config.runtime.artifacts = "./artifacts/pi" +config.enable_relay(output_dir="./artifacts/relay") +config.harness.settings["relay_extension_path"] = ( + "/path/to/NeMo-Relay/crates/cli/assets/pi-extension" +) +``` -The Relay Pi hook route is available only on the loopback gateway and does not -authenticate hook posts. Treat the loopback port as a local trust boundary. +Relay requires `runtime.artifacts` so NeMo Fabric can create the runtime-owned +configuration passed to the adapter. The extension path can be absolute or +relative to `environment.workspace`. It can identify a JavaScript or TypeScript +file or a Pi extension package directory. Unlike user-configured Pi extensions, +the Relay extension does not need to remain inside `environment.workspace` when +an absolute path is used. + +When the runtime starts, the adapter validates the Relay CLI version, writes an +explicit `plugins.toml`, and starts a loopback gateway. The SDK session, or +each terminal TUI, loads the extension on that gateway. The gateway can produce +ATOF, ATIF, OpenTelemetry, and OpenInference output from the Relay +observability configuration. + +The adapter supports one Relay-enabled Pi runtime per adapter process because +the Relay Pi extension receives its gateway and upstream configuration through +process environment variables. NeMo Fabric starts each runtime in a separate +adapter process, so concurrent NeMo Fabric runtimes remain isolated. Direct +embedders must likewise place concurrent Relay-enabled Pi runtimes in separate +processes. + +Session, turn, and tool telemetry does not depend on model redirection. Model +telemetry is available only when Relay supports the selected model API and the +gateway upstream matches the model endpoint. Relay records a skipped redirect +as a `model_redirect` mark with the reason in configured ATOF artifacts. +The [SDK guide](./pi-sdk.mdx#results-and-relay) describes per-invocation +artifacts and streaming; the [terminal TUI guide](./pi-tui.mdx#relay) describes +terminal TUI capture. -## Credential-free HTTP model gateways +### Credential-Free HTTP Model Gateways For Relay-enabled runs, set `harness.settings.insecure_http_model_hosts` to the exact bare DNS hostnames or IP addresses of trusted inference gateways. This requires NeMo Relay CLI 0.11.x. -Remote HTTP model endpoints require `openai-completions`, `openai-responses`, or `anthropic-messages`. Other Pi model APIs, including `mistral-conversations`, require HTTPS or loopback HTTP because their requests bypass Relay's gateway. Fabric rejects unsupported remote HTTP APIs before session startup, including hosts listed in `insecure_http_model_hosts`. +Remote HTTP model endpoints require `openai-completions`, `openai-responses`, or `anthropic-messages`. Other Pi model APIs, including `mistral-conversations`, require HTTPS or loopback HTTP because their requests bypass Relay's gateway. NeMo Fabric rejects unsupported remote HTTP APIs before session startup, including hosts listed in `insecure_http_model_hosts`. ```python config.harness.settings["insecure_http_model_hosts"] = ["inference.internal", "10.0.0.10"] @@ -394,3 +375,69 @@ config.harness.settings["insecure_http_model_hosts"] = ["inference.internal", "1 Entries have no scheme, port, path, wildcard, brackets, or IPv6 zone identifier. DNS matching ignores case and a trailing dot. Each listed host may use custom ports and paths. NeMo Fabric writes explicit `[]` to revoke inherited trust and preserves omission when the setting is absent. System Relay configuration has higher priority and can enforce an empty list. Relay strips authorization, API-key, cookie, custom credential headers, and middleware-added credentials before forwarding remote HTTP model requests, including model credentials supplied to Pi. Relay rejects conflicting upstream authorization configuration. Prompts and responses remain unencrypted. HTTPS is the default; this opt-in does not authorize MCP or observability endpoints, caller-selected destinations, or remote HTTP WebSockets. + +## Agent Directory and Kept State + +The runtime writes Pi's own configuration files to a `pi-agent` directory: +`models.json`, `settings.json`, `SYSTEM.md` when a system instruction is +configured, and, for a terminal TUI runtime, `mcp.json`. The SDK session and +the `pi` CLI load them from there. The model key stays in memory; `models.json` +names only its environment variable. `mcp.json` holds the configured MCP +servers, including any literal stdio `env` values, so the files are readable +only by their owner; stopping the runtime, or a failed start, removes `mcp.json`. + +The directory's location depends on the runtime: + +- **Terminal TUI:** `/.fabric/pi/runtimes//pi-agent`, kept after the runtime stops, as for Hermes. +- **`runtime.keep_state`:** the agent's state folder. +- **Otherwise:** a private temporary directory that stopping the runtime removes. + +With the terminal interface or `runtime.keep_state`, startup refuses a +`base_url` that carries a user name or password +(`pi_base_url_credentials_unsupported`), or that doesn't parse +(`pi_base_url_invalid`), because the endpoint is kept on disk. + +### Keep State Across Runtimes + +With `runtime.keep_state`, the Pi directory is the agent's state folder, +`/.fabric/state/nvidia.fabric.pi/`, so runtimes of +the agent share `pi-agent`, `pi-sessions`, and `interfaces`. Conversations +survive a new runtime, whichever path wrote them. An SDK runtime starts a new +conversation, and so does each terminal TUI launch. A terminal TUI can open an +earlier conversation, including one an SDK runtime of the agent wrote, with +`--resume`, `/resume`, or `--session `. + +The adapter rewrites Pi's configuration files from `FabricConfig` at each +start, so settings changed from Pi don't survive. Logins that Pi saved itself +in `pi-agent/auth.json` survive, except a login for the configured provider: +each start removes it, so the runtime's key applies. Startup also removes the +`interfaces/tui.json` attachment file and launcher that a runtime which ended +without stop left behind, and first stops that runtime's terminal TUIs, as +stopping a runtime does. + +## Health and Shutdown + +With the SDK session, runtime health and `idle`/`busy` activity describe that +session. For a terminal TUI runtime, `active` and `ready` also require the +launcher and `interfaces/tui.json`, `ready` requires the selected model to +resolve from `models.json` as it is at each check, and passing checks report +`unknown` activity, as for Hermes; refer to [Health Checks](../../../sdk/health-checks.mdx). +The [terminal TUI guide](./pi-tui.mdx#stop-and-health) describes how stopping +a runtime closes its terminal TUIs. + +## Limitations and Planned Work + +The current adapter does not expose native OpenAI streaming, caller-driven +cancellation, or remote-service execution. Enabling a third-party extension +can add extension-defined skills, prompts, or themes even though ambient Pi +resources remain disabled. The Relay extension does not add those resources. + +The Relay Pi hook route is available only on the loopback gateway and does not +authenticate hook posts. Treat the loopback port as a local trust boundary. + +Collection of terminal TUI conversations as NeMo Fabric artifacts remains +planned work. + +## Try the Terminal TUI + +See the [Pi interface example](../../../../examples/interfaces/pi/README.md) for a terminal TUI runtime with kept state, run by hand or as a scripted demo. diff --git a/docs/sdk/health-checks.mdx b/docs/sdk/health-checks.mdx index 4a7f1c1af..0ea33d393 100644 --- a/docs/sdk/health-checks.mdx +++ b/docs/sdk/health-checks.mdx @@ -60,7 +60,7 @@ 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) | +| [Pi](../integrations/harness/pi/pi.mdx) | SDK, when enabled: completed initialization, unchanged native session identity, and a fresh `extensionRunner.createContext().isIdle()` response; idle and busy both pass. With `sdk.enabled: false`: the runtime has not stopped. | SDK: completed extension binding and an available native request interface after liveness passes. Terminal interface, when enabled: the launcher and `interfaces/tui.json` exist. | SDK: the selected model remains configured, required tools remain available, and required MCP transports have no observed error or closure. With `sdk.enabled: false`: the selected model resolves from the agent directory. With the terminal interface enabled, passing checks report `unknown` activity. | [Tests](https://github.com/NVIDIA/NeMo-Fabric/blob/66341998b2e954a008cc7f726be64020adc3d1f4/tests/e2e/test_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) | diff --git a/docs/sdk/requests-and-runtimes.mdx b/docs/sdk/requests-and-runtimes.mdx index 321e8e0ef..bdab3a8b2 100644 --- a/docs/sdk/requests-and-runtimes.mdx +++ b/docs/sdk/requests-and-runtimes.mdx @@ -95,7 +95,7 @@ The operating system releases the lock after all copies of the lock have closed: - **Windows:** Adapter hosts do not inherit the lock. Only the NeMo Fabric process holds the lock, so the folder becomes available if that process exits while an adapter host is still running. - **Detached processes:** A native process can continue accessing the state folder after all lock descriptors close. A replacement runtime can then acquire the lock while the detached process still writes to the folder. -Planning fails without an artifact directory or for an adapter that doesn't declare `runtime.keep_state`. The Hermes Agent and OpenClaw adapters declare `runtime.keep_state`. +Planning fails without an artifact directory or for an adapter that doesn't declare `runtime.keep_state`. The Hermes Agent, OpenClaw, and Pi adapters declare `runtime.keep_state`; see the [Pi guide](../integrations/harness/pi/pi.mdx#keep-state-across-runtimes) for what Pi keeps. See the [OpenClaw cold resume guide](https://github.com/NVIDIA/NeMo-Fabric/blob/main/adapters/python/openclaw/README.md#cold-resume) for native Gateway and service behavior. diff --git a/examples/interfaces/README.md b/examples/interfaces/README.md index c661e0318..80850b5a8 100644 --- a/examples/interfaces/README.md +++ b/examples/interfaces/README.md @@ -9,5 +9,6 @@ Choose a harness for its setup instructions, runnable examples, and manual tests - [Hermes](hermes/README.md) - [OpenClaw](openclaw/README.md) +- [Pi](pi/README.md) (experimental terminal TUI, with conversations kept across runtimes) Run commands from the repository root unless the harness README says otherwise. diff --git a/examples/interfaces/pi/README.md b/examples/interfaces/pi/README.md new file mode 100644 index 000000000..cec27f0eb --- /dev/null +++ b/examples/interfaces/pi/README.md @@ -0,0 +1,60 @@ + + +# NVIDIA NeMo Fabric Pi Interface Examples + +Experimental: Pi's terminal TUI as a native interface of a NeMo Fabric runtime, with its conversations kept across runtimes by `runtime.keep_state`. See the [Pi terminal TUI guide](../../../docs/integrations/harness/pi/pi-tui.mdx) for the interface itself. + +## Set Up + +Run commands from the NeMo Fabric repository root. Build the Python SDK, then the adapter contract, the shared adapter package, and the Pi adapter: + +```bash +just build-python +just install-typescript-pi +npm run build --prefix adapter-contract/typescript +npm run build --prefix adapters/typescript --workspace nemo-fabric-adapters-common +npm run build --prefix adapters/typescript --workspace nemo-fabric-adapters-pi +``` + +Set the model and the variable that holds its key. The default provider is `nvidia`; pass `--provider` for another one, and `--api openai-completions` (or another Pi wire protocol) for a gateway-served model that Pi doesn't ship; the script then declares it as a text model with `--context-window` (default 32768): + +```bash +export MODEL_NAME="nvidia/nemotron-3-nano-omni-30b-a3b-reasoning" +export MODEL_BASE_URL="https://integrate.api.nvidia.com/v1" +export MODEL_API_KEY="YOUR_MODEL_API_KEY" +``` + +## Continue a Terminal Conversation in a New Runtime + +`pi_tui.py` starts a terminal TUI runtime (`sdk.enabled: false` and `interfaces.terminal`) with `runtime.keep_state`, prints the launcher command, and stops the runtime when you press Enter: + +```bash +.venv/bin/python -m examples.interfaces.pi.pi_tui +``` + +1. In a second terminal, run the printed launcher and talk to Pi. Ask it to remember something. +2. Press Enter in the first terminal. The runtime stops, and the open terminal UI closes with it. +3. Run the script again with the same `--output-dir` (the default is `outputs/interfaces/pi-kept-state`). A new runtime starts with a new runtime ID. +4. Run the new launcher with `--continue`, or type `/resume` in Pi. The earlier conversation is there. + +Every runtime of the agent uses the same Pi directory, `/.fabric/state/nvidia.fabric.pi/pi-tui-example`: + +| Path | Kept across runtimes | +| --- | --- | +| `pi-sessions/` | Yes. Terminal conversations. | +| `pi-agent/auth.json` | Yes, except a login for the configured provider, which each start removes so the runtime's key applies. Logins that Pi saved itself, for example after `/login`. | +| `pi-agent/settings.json`, `models.json`, `mcp.json`, `SYSTEM.md` | No. Rewritten from `FabricConfig` at each start; changes made in Pi's `/settings` don't survive. | +| `interfaces/` | No. The launcher, `tui.json` and `tui.clients` belong to the running runtime. A start removes the ones a runtime that ended without stop left behind, and closes its terminal UIs first. | + +## Run It Without a Person + +`--demo` starts a runtime, has its terminal UI answer one prompt in print mode, stops the runtime, starts a second one, and continues the conversation from the second runtime's terminal UI: + +```bash +.venv/bin/python -m examples.interfaces.pi.pi_tui --demo --output-dir "outputs/interfaces/pi-demo-$(date +%s)" +``` + +The second runtime's answer names the word from the first runtime. Add `--no-keep-state` for contrast: each runtime then has its own Pi directory, and `--continue` finds nothing to continue. diff --git a/skills/nemo-fabric-integrate/SKILL.md b/skills/nemo-fabric-integrate/SKILL.md index 957afc614..8996587ee 100644 --- a/skills/nemo-fabric-integrate/SKILL.md +++ b/skills/nemo-fabric-integrate/SKILL.md @@ -185,6 +185,8 @@ construction. For Hermes, embedded SDK execution is enabled and eager by default. Set `harness.settings.sdk.enabled=False` only for native-only runtimes with an enabled API, dashboard, or terminal interface; management through the SDK remains available, but invocation fails explicitly. Browser and terminal clients share one managed TUI backend. Native responses remain native even when Relay emits standard ATOF/ATIF; do not treat them as SDK `RunResult` objects. Follow the [Hermes invocation guides](https://github.com/NVIDIA/NeMo-Fabric/blob/main/docs/integrations/harness/hermes/hermes.mdx) for interface-specific installation and attachment. +For Pi, a runtime runs either the embedded SDK session, the default, or Pi's own terminal UI, never both: set `harness.settings.sdk.enabled=False` and `harness.settings.interfaces.terminal` to `{}` for the terminal UI, and use a separate runtime for SDK invocations. Startup refuses both together with `pi_execution_path_conflict`. The terminal interface writes a launcher that opens Pi's terminal UI on the runtime's configuration. The launcher holds no secrets; it fetches the runtime's `environment.env` and model key from the running runtime, so the person running it doesn't export them. Management through the SDK remains available, and invocation fails with `pi_sdk_disabled`. With Relay enabled, Relay captures each terminal UI as its own session. Pi accepts `runtime.keep_state`: runtimes of the agent then share its Pi directory, so conversations survive a new runtime and `--continue` or `/resume` finds them; each start still rewrites Pi's configuration from `FabricConfig`. Follow the [Pi guides](https://github.com/NVIDIA/NeMo-Fabric/blob/main/docs/integrations/harness/pi/pi.mdx) for installation and the terminal TUI. + For Deep Agents, mini-SWE-agent, and the LangGraph custom-agent example, pass the same UUID string through `RunRequest.relay_session_root` on each conversation turn to group Relay trajectories under one session. Core forwards the typed field as `AgentRunRequest.relay_session_root`; context keys do not control Relay propagation. An unusable UUID preserves per-request behavior. The remaining adapters do not consume this field. For Hermes and OpenClaw cold resume, configure `runtime.keep_state` and retain the complete