Skip to content
Merged
Show file tree
Hide file tree
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 Dec 2, 2026
fcde84e
fix: keep Pi's terminal configuration equivalent to the SDK session
yczhang-nv Dec 2, 2026
f85916e
fix: harden Pi terminal interface cleanup and cover its tools
yczhang-nv Dec 2, 2026
9f383cf
fix: warn about Pi terminal records in streamed invocations
yczhang-nv Dec 2, 2026
9ff1665
fix: keep suspended Pi terminal UIs and URL credentials under control
yczhang-nv Dec 2, 2026
f319abe
fix: close Pi terminal UIs without timing assumptions
yczhang-nv Dec 2, 2026
1b6f288
fix: require an identity for each Pi terminal UI
yczhang-nv Dec 2, 2026
e1a8636
feat: give Pi's terminal UI the runtime's environment over a socket
yczhang-nv Dec 2, 2026
4f22066
fix: harden the Pi terminal environment socket and launch helper
yczhang-nv Dec 2, 2026
6ffdbc5
fix: verify Pi terminal UIs at stop and keep unverified ones
yczhang-nv Dec 2, 2026
eca9e58
fix: register Pi terminal launches before they get the environment
yczhang-nv Dec 2, 2026
20869e1
chore: stop asking for the model key in the Pi TUI example
yczhang-nv Dec 2, 2026
e818fe6
fix: bind Pi terminal launches to their runtime and verify before sig…
yczhang-nv Dec 2, 2026
76447c2
fix: send empty MCP header variables from Pi's terminal UI as the SDK…
yczhang-nv Dec 2, 2026
0272daf
fix: signal Pi terminal UIs only by verified identity
yczhang-nv Dec 2, 2026
c4e920d
fix: verify a Pi terminal UI's PID before group signals too
yczhang-nv Dec 2, 2026
e33ae7e
fix: keep Pi terminal UIs whose identity can't be read when signalled
yczhang-nv Dec 2, 2026
7800da4
fix: report every Pi terminal cleanup failure and compare like identi…
yczhang-nv Dec 2, 2026
78481c9
test: cover partial heartbeat writes before a Pi terminal stop
yczhang-nv Dec 2, 2026
754f7b7
fix: report Pi terminal UIs a failed signal leaves running
yczhang-nv Dec 2, 2026
9b4229f
test: cover denied signals at Pi terminal stop
yczhang-nv Dec 2, 2026
c45d46f
fix: use the runtime's key over a saved Pi login in the terminal UI
yczhang-nv Dec 3, 2026
6a5aece
fix: load Pi module tools only for the SDK session
yczhang-nv Dec 3, 2026
6666643
feat: refuse a Pi runtime with both the SDK and the terminal interface
yczhang-nv Dec 3, 2026
fac752f
fix: confirm Pi terminal UIs exit after SIGKILL and check readiness a…
yczhang-nv Dec 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 66 additions & 2 deletions adapters/typescript/pi/pi.fabric-adapter.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
"tools.blocked",
"skills",
"mcp",
"mcp.tool_filters"
"mcp.tool_filters",
"runtime.keep_state"
],
"system_instruction_modes": ["replace"]
},
Expand Down Expand Up @@ -57,9 +58,72 @@
"type": "string",
"minLength": 1,
"description": "Absolute path or environment.workspace-relative path to the NeMo Relay Pi extension matching the CLI release"
},
"interfaces": {
"type": "object",
"properties": {
"terminal": {
"type": "object",
"properties": {
"enabled": {
"type": "boolean",
"default": true,
"description": "Offer Pi's terminal TUI. A present terminal interface is on unless this is false."
}
},
"additionalProperties": false,
"description": "Experimental: Pi's terminal TUI, which runs in its own process and needs no port: the launcher interfaces/terminal in the runtime's Pi directory (<artifact root>/.fabric/pi/runtimes/<runtime-id>, or the agent's state folder with runtime.keep_state) opens it on the runtime's agent directory. Requires sdk.enabled false: a runtime runs either the embedded SDK session or terminal UIs. Writes interfaces/terminal and, once the runtime is ready, interfaces/tui.json. The configuration, the launcher, interfaces/tui.json and interfaces/tui.clients may change as the #579 launcher contract is adopted; compatibility is not guaranteed for these surfaces."
}
},
"additionalProperties": false,
"description": "Native interfaces offered by the runtime."
},
"sdk": {
"type": "object",
"properties": {
"enabled": {
"type": "boolean",
"default": true,
"description": "Initialize the embedded SDK session during startup. Disable for native-only execution, which the terminal interface requires; SDK invocation then fails explicitly."
}
},
"additionalProperties": false,
"description": "Embedded SDK execution, enabled by default. Runtime management remains available when disabled."
}
},
"additionalProperties": false
"additionalProperties": false,
"allOf": [
{
"if": {
"required": ["sdk"],
"properties": {"sdk": {"required": ["enabled"], "properties": {"enabled": {"const": false}}}}
},
"then": {
"required": ["interfaces"],
"properties": {
"interfaces": {
"required": ["terminal"],
"properties": {"terminal": {"properties": {"enabled": {"const": true}}}}
}
}
}
},
{
"if": {
"required": ["interfaces"],
"properties": {
"interfaces": {
"required": ["terminal"],
"properties": {"terminal": {"not": {"required": ["enabled"], "properties": {"enabled": {"const": false}}}}}
}
}
},
"then": {
"required": ["sdk"],
"properties": {"sdk": {"required": ["enabled"], "properties": {"enabled": {"const": false}}}}
}
}
]
},
"model_schema": {
"type": "object",
Expand Down
150 changes: 150 additions & 0 deletions adapters/typescript/pi/src/agent-directory.ts
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}}`,
Comment thread
yczhang-nv marked this conversation as resolved.
Resolved
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 });
}
}
6 changes: 4 additions & 2 deletions adapters/typescript/pi/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@ const manifest = createRequire(import.meta.url)("../package.json") as {
assertSupportedNodeVersion(process.versions.node, manifest.engines?.node);

await serve(async () => {
const [{ PiSdkSessionFactory }, { PiAdapterRuntime }] = await Promise.all([
const [{ PiSdkSessionFactory }, { PiAdapterRuntime }, { withTerminalInterface }] = await Promise.all([
import("./pi-sdk.js"),
import("./runtime.js"),
import("./terminal.js"),
]);
return new PiAdapterRuntime(new PiSdkSessionFactory());
// Without interfaces.terminal, the runtime is the SDK session alone.
return new PiAdapterRuntime(withTerminalInterface(new PiSdkSessionFactory()));
}, {
software: {
packageJson: new URL("../package.json", import.meta.url),
Expand Down
Loading
Loading