Repository navigation
feat: open Pi's terminal TUI from a runtime #732
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
yczhang-nv
merged 25 commits into
NVIDIA:main
from
yczhang-nv:feat/pi-terminal-interface
Dec 3, 2026
Merged
Changes from all commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
7e7e4b1
feat: open Pi's terminal TUI from a runtime
yczhang-nv fcde84e
fix: keep Pi's terminal configuration equivalent to the SDK session
yczhang-nv f85916e
fix: harden Pi terminal interface cleanup and cover its tools
yczhang-nv 9f383cf
fix: warn about Pi terminal records in streamed invocations
yczhang-nv 9ff1665
fix: keep suspended Pi terminal UIs and URL credentials under control
yczhang-nv f319abe
fix: close Pi terminal UIs without timing assumptions
yczhang-nv 1b6f288
fix: require an identity for each Pi terminal UI
yczhang-nv e1a8636
feat: give Pi's terminal UI the runtime's environment over a socket
yczhang-nv 4f22066
fix: harden the Pi terminal environment socket and launch helper
yczhang-nv 6ffdbc5
fix: verify Pi terminal UIs at stop and keep unverified ones
yczhang-nv eca9e58
fix: register Pi terminal launches before they get the environment
yczhang-nv 20869e1
chore: stop asking for the model key in the Pi TUI example
yczhang-nv e818fe6
fix: bind Pi terminal launches to their runtime and verify before sig…
yczhang-nv 76447c2
fix: send empty MCP header variables from Pi's terminal UI as the SDK…
yczhang-nv 0272daf
fix: signal Pi terminal UIs only by verified identity
yczhang-nv c4e920d
fix: verify a Pi terminal UI's PID before group signals too
yczhang-nv e33ae7e
fix: keep Pi terminal UIs whose identity can't be read when signalled
yczhang-nv 7800da4
fix: report every Pi terminal cleanup failure and compare like identi…
yczhang-nv 78481c9
test: cover partial heartbeat writes before a Pi terminal stop
yczhang-nv 754f7b7
fix: report Pi terminal UIs a failed signal leaves running
yczhang-nv 9b4229f
test: cover denied signals at Pi terminal stop
yczhang-nv c45d46f
fix: use the runtime's key over a saved Pi login in the terminal UI
yczhang-nv 6a5aece
fix: load Pi module tools only for the SDK session
yczhang-nv 6666643
feat: refuse a Pi runtime with both the SDK and the terminal interface
yczhang-nv fac752f
fix: confirm Pi terminal UIs exit after SIGKILL and check readiness a…
yczhang-nv File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| // SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| // The runtime's Pi agent directory: Pi's own configuration files, written from | ||
| // what the adapter resolved from FabricConfig. The embedded SDK session loads its | ||
| // settings, model catalog, MCP servers and system prompt from these files, and | ||
| // Pi's terminal UI reads the same files, so both run on one configuration. | ||
| // models.json names the model key's environment variable, and the SDK session | ||
| // supplies the key in memory. mcp.json holds the configured MCP servers as | ||
| // FabricConfig gives them, including any literal stdio env values, so every file | ||
| // is owner-only. Without the terminal interface or runtime.keep_state the | ||
| // directory is temporary and stop removes it. | ||
| // With runtime.keep_state, every runtime of the agent uses the same directory, so | ||
| // each start rewrites these files from FabricConfig and removes the ones it no | ||
| // longer configures; files Pi writes itself stay, except a login auth.json holds | ||
| // for the configured provider, which the runtime's key replaces. | ||
|
|
||
| import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; | ||
| import { join, resolve } from "node:path"; | ||
|
|
||
| import type { JsonObject } from "nemo-fabric-adapter-contract"; | ||
| import type { AdapterStartInput } from "nemo-fabric-adapters-common"; | ||
|
|
||
| import type { PiNativeConfiguration } from "./native-configuration.js"; | ||
|
|
||
| /** | ||
| * The agent's state folder (`RuntimeContext.state_dir`) with runtime.keep_state, as the | ||
| * Hermes adapter uses it for its home; otherwise `<artifact root>/.fabric/pi/runtimes/<runtime-id>`, | ||
| * as the other adapters' native state uses. | ||
| */ | ||
| export function runtimeDirectory(input: AdapterStartInput): string { | ||
| const stateDir = input.runtimeContext.state_dir; | ||
| if (typeof stateDir === "string" && stateDir.length > 0) return resolve(stateDir); | ||
| const root = input.runtimeContext.artifacts.root; | ||
| const artifactRoot = | ||
| // An unset or empty root is <base_dir>/artifacts, as the Hermes adapter resolves it. | ||
| root === undefined || root === null || String(root).length === 0 | ||
| ? resolve(input.baseDir, "artifacts") | ||
| : resolve(input.baseDir, String(root)); | ||
| return join(artifactRoot, ".fabric", "pi", "runtimes", input.runtimeContext.runtime_id); | ||
| } | ||
|
|
||
| /** Whether the runtime keeps its Pi directory across runtimes of the agent (runtime.keep_state). */ | ||
| export function keepsState(input: AdapterStartInput): boolean { | ||
| const stateDir = input.runtimeContext.state_dir; | ||
| return typeof stateDir === "string" && stateDir.length > 0; | ||
| } | ||
|
|
||
| /** The Pi agent directory (PI_CODING_AGENT_DIR) inside a runtime directory. */ | ||
| export function agentDirectory(runtimeDir: string): string { | ||
| return join(runtimeDir, "pi-agent"); | ||
| } | ||
|
|
||
| /** Pi's session directory (PI_CODING_AGENT_SESSION_DIR) inside a runtime directory. */ | ||
| export function sessionDirectory(runtimeDir: string): string { | ||
| return join(runtimeDir, "pi-sessions"); | ||
| } | ||
|
|
||
| export function piSettings(configuration: PiNativeConfiguration): JsonObject { | ||
| return { | ||
| defaultProvider: configuration.provider, | ||
| defaultModel: String(configuration.model.id), | ||
| // Only agent-directory settings can set this; project files stay untrusted. | ||
| defaultProjectTrust: "never", | ||
| // Cache warming can finish outside a prompt and omit aborted refresh usage. | ||
| cacheWarming: "off", | ||
| compaction: { reserveTokens: configuration.compactionReserveTokens }, | ||
| enableInstallTelemetry: false, | ||
| packages: [], | ||
| }; | ||
| } | ||
|
|
||
| export function piModels(configuration: PiNativeConfiguration): JsonObject { | ||
| return { | ||
| providers: { | ||
| [configuration.provider]: { | ||
| // Keep the endpoint at provider scope so Relay can redirect it without a | ||
| // per-model baseUrl taking precedence over the extension's provider override. | ||
| ...(configuration.baseUrl === undefined ? {} : { baseUrl: configuration.baseUrl }), | ||
| // Pi resolves the reference when a process starts; the file holds no secret. | ||
| apiKey: `\${${configuration.apiKeyEnv}}`, | ||
| models: [configuration.model as JsonObject], | ||
| }, | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| /** Create an owner-only directory if it is missing, and return its path. */ | ||
| export async function privateDirectory(path: string): Promise<string> { | ||
| await mkdir(path, { recursive: true, mode: 0o700 }); | ||
| return path; | ||
| } | ||
|
|
||
| async function writePrivate(path: string, contents: string): Promise<void> { | ||
| await writeFile(path, contents, { mode: 0o600 }); | ||
| // writeFile applies the mode only to a new file; Pi may have recreated one in a kept directory. | ||
| await chmod(path, 0o600); | ||
| } | ||
|
|
||
| /** | ||
| * Remove the login that Pi's auth.json saved for the configured provider, such as one a | ||
| * terminal UI's /login stored in a kept directory. Pi's terminal UI prefers a saved login to | ||
| * the key models.json names, so it would otherwise use another key than the SDK session, | ||
| * which never reads auth.json. Logins for other providers stay; a file Pi can't parse is | ||
| * left as it is, because Pi ignores it too. | ||
| */ | ||
| async function removeSavedLogin(directory: string, provider: string): Promise<void> { | ||
| const path = join(directory, "auth.json"); | ||
| let saved: unknown; | ||
| try { | ||
| saved = JSON.parse((await readFile(path, "utf8")).replace(/^/, "")); | ||
| } catch (error) { | ||
| if (error instanceof SyntaxError || (error as NodeJS.ErrnoException).code === "ENOENT") return; | ||
| throw error; | ||
| } | ||
| if (saved === null || typeof saved !== "object" || Array.isArray(saved) || !Object.hasOwn(saved, provider)) return; | ||
| const { [provider]: _removed, ...logins } = saved as Record<string, unknown>; | ||
| // Replace the file in one step, so a reader never sees it half-written. | ||
| const staging = `${path}.fabric-${process.pid}`; | ||
| await writePrivate(staging, `${JSON.stringify(logins, null, 2)}\n`); | ||
| await rename(staging, path); | ||
| } | ||
|
|
||
| /** Write Pi's configuration files for the runtime. */ | ||
| export async function writeAgentDirectory(configuration: PiNativeConfiguration): Promise<void> { | ||
| const directory = configuration.agentDir; | ||
| await mkdir(directory, { recursive: true, mode: 0o700 }); | ||
| await removeSavedLogin(directory, configuration.provider); | ||
| await writePrivate(join(directory, "settings.json"), `${JSON.stringify(piSettings(configuration), null, 2)}\n`); | ||
| await writePrivate(join(directory, "models.json"), `${JSON.stringify(piModels(configuration), null, 2)}\n`); | ||
| // A kept directory can hold an earlier runtime's optional files; this runtime doesn't inherit them. | ||
| // Only Pi's terminal UI reads mcp.json; the SDK session gets its MCP servers in memory. | ||
| if (configuration.terminal && Object.keys(configuration.mcpServers).length > 0) { | ||
| await writePrivate( | ||
| join(directory, "mcp.json"), | ||
| `${JSON.stringify({ mcpServers: configuration.mcpServers }, null, 2)}\n`, | ||
| ); | ||
| } else { | ||
| await rm(join(directory, "mcp.json"), { force: true }); | ||
| } | ||
| // Pi appends <agent dir>/APPEND_SYSTEM.md to the system prompt. FabricConfig never writes | ||
| // one, so a copy left in a kept directory doesn't reach later runtimes. | ||
| await rm(join(directory, "APPEND_SYSTEM.md"), { force: true }); | ||
| if (configuration.systemPrompt !== undefined) { | ||
| // Pi replaces its default system prompt with <agent dir>/SYSTEM.md. | ||
| await writePrivate(join(directory, "SYSTEM.md"), configuration.systemPrompt); | ||
| } else { | ||
| await rm(join(directory, "SYSTEM.md"), { force: true }); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.