From 7e7e4b199cfe47c5813fec3fe3d9d20eff5de0ef Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Tue, 1 Dec 2026 16:22:37 -0800 Subject: [PATCH 01/25] feat: open Pi's terminal TUI from a runtime MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Write the runtime's Pi configuration as Pi's own files in an agent directory that the embedded SDK session and the stock pi CLI both load. With harness.settings.interfaces.terminal, the runtime writes a secret-free launcher and publishes interfaces/tui.json once it is ready; stop removes it and closes registered terminal UIs with the Hermes SIGTERM/SIGKILL sequence. harness.settings.sdk.enabled=false runs a terminal-only runtime, and the adapter accepts runtime.keep_state so Pi conversations and saved credentials survive a new runtime of the agent. Based on the proof of concept by Kao Félix. Co-authored-by: Kao Félix Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- adapters/typescript/pi/pi.fabric-adapter.json | 53 +- adapters/typescript/pi/src/agent-directory.ts | 114 +++ adapters/typescript/pi/src/cli.ts | 6 +- .../typescript/pi/src/native-configuration.ts | 867 ++++++++++++++++++ adapters/typescript/pi/src/native-only.ts | 92 ++ adapters/typescript/pi/src/pi-sdk.ts | 825 ++--------------- adapters/typescript/pi/src/relay-config.ts | 14 + adapters/typescript/pi/src/relay.ts | 34 +- adapters/typescript/pi/src/runtime.ts | 17 + adapters/typescript/pi/src/settings.ts | 44 + adapters/typescript/pi/src/terminal.ts | 551 +++++++++++ adapters/typescript/pi/test/pi-sdk.test.mjs | 4 +- .../typescript/pi/test/relay-smoke.test.mjs | 117 ++- adapters/typescript/pi/test/runtime.test.mjs | 53 ++ adapters/typescript/pi/test/terminal.test.mjs | 734 +++++++++++++++ adapters/typescript/pi/test/usage.test.mjs | 2 +- adapters/typescript/scripts/check-package.mjs | 10 + examples/interfaces/pi/pi_tui.py | 219 +++++ .../nemo_fabric_adapter_catalog/catalog.json | 78 +- tests/adapters/test_pi_adapter.py | 11 + 20 files changed, 3055 insertions(+), 790 deletions(-) create mode 100644 adapters/typescript/pi/src/agent-directory.ts create mode 100644 adapters/typescript/pi/src/native-configuration.ts create mode 100644 adapters/typescript/pi/src/native-only.ts create mode 100644 adapters/typescript/pi/src/settings.ts create mode 100644 adapters/typescript/pi/src/terminal.ts create mode 100644 adapters/typescript/pi/test/terminal.test.mjs create mode 100644 examples/interfaces/pi/pi_tui.py diff --git a/adapters/typescript/pi/pi.fabric-adapter.json b/adapters/typescript/pi/pi.fabric-adapter.json index 1cae737c4..5d09a8997 100644 --- a/adapters/typescript/pi/pi.fabric-adapter.json +++ b/adapters/typescript/pi/pi.fabric-adapter.json @@ -19,7 +19,8 @@ "tools.blocked", "skills", "mcp", - "mcp.tool_filters" + "mcp.tool_filters", + "runtime.keep_state" ], "system_instruction_modes": ["replace"] }, @@ -57,9 +58,57 @@ "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 (/.fabric/pi/runtimes/, or the agent's state folder with runtime.keep_state) opens it on the runtime's agent directory in a separate conversation. 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; 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}}}} + } + } + } + } + ] }, "model_schema": { "type": "object", diff --git a/adapters/typescript/pi/src/agent-directory.ts b/adapters/typescript/pi/src/agent-directory.ts new file mode 100644 index 000000000..bd0548f52 --- /dev/null +++ b/adapters/typescript/pi/src/agent-directory.ts @@ -0,0 +1,114 @@ +// 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. +// The files hold no secrets: models.json and mcp.json name environment variables, +// and the SDK session supplies the model key in memory. +// 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, such as auth.json, stay. + +import { mkdir, 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 `/.fabric/pi/runtimes/`, + * 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 = + root === undefined || root === null + ? 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 { + await mkdir(path, { recursive: true, mode: 0o700 }); + return path; +} + +async function writePrivate(path: string, contents: string): Promise { + await writeFile(path, contents, { mode: 0o600 }); +} + +/** Write Pi's configuration files for the runtime. */ +export async function writeAgentDirectory(configuration: PiNativeConfiguration): Promise { + const directory = configuration.agentDir; + await mkdir(directory, { recursive: true, mode: 0o700 }); + 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. + if (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 }); + } + if (configuration.systemPrompt !== undefined) { + // Pi replaces its default system prompt with /SYSTEM.md. + await writePrivate(join(directory, "SYSTEM.md"), configuration.systemPrompt); + } else { + await rm(join(directory, "SYSTEM.md"), { force: true }); + } +} diff --git a/adapters/typescript/pi/src/cli.ts b/adapters/typescript/pi/src/cli.ts index 54fe14ef3..b6aa78785 100644 --- a/adapters/typescript/pi/src/cli.ts +++ b/adapters/typescript/pi/src/cli.ts @@ -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), diff --git a/adapters/typescript/pi/src/native-configuration.ts b/adapters/typescript/pi/src/native-configuration.ts new file mode 100644 index 000000000..3000fd23a --- /dev/null +++ b/adapters/typescript/pi/src/native-configuration.ts @@ -0,0 +1,867 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Pi's configuration for a runtime, resolved from FabricConfig: the selected +// model, the API key's variable, extensions, skills, tools and MCP servers. The +// adapter writes it to the runtime's Pi agent directory (agent-directory.ts), +// which the embedded SDK session and Pi's terminal UI both read, and checks that +// Pi resolves the selected model from those files. It starts no session. + +import { readFile, realpath, stat } from "node:fs/promises"; +import { extname, isAbsolute, join, relative, resolve, sep } from "node:path"; + +import type { McpServerConfig, ToolDefinition } from "@earendil-works/pi-coding-agent"; +import { createJiti } from "jiti/static"; +import type { AgentConfig, AgentModelConfig, AgentToolDefinition, JsonObject } from "nemo-fabric-adapter-contract"; +import { LifecycleError, type AdapterStartInput } from "nemo-fabric-adapters-common"; + +import { agentDirectory, keepsState, runtimeDirectory, sessionDirectory, writeAgentDirectory } from "./agent-directory.js"; + +export interface PiNativeCustomTool { + name: string; + path: string; + exportName: string; + settings: JsonObject; +} + +export interface PiNativeConfiguration { + /** The runtime's Pi agent directory, holding this configuration as Pi's own files. */ + agentDir: string; + /** Pi's session directory beside the agent directory, where conversations are kept on disk. */ + sessionDir: string; + /** + * Whether the agent directory and the session directory are the agent's state folder + * (runtime.keep_state), shared by every runtime of the agent. + */ + keepState: boolean; + workspace: string; + provider: string; + /** The provider-scope endpoint the session registered, if any. */ + baseUrl?: string; + /** The model definition the session registered, without its endpoint. */ + model: Record; + /** The variable that holds the model key; never the key itself. */ + apiKeyEnv: string; + compactionReserveTokens: number; + /** Configured extensions only; the Relay extension belongs to the runtime's own gateway. */ + extensionPaths: string[]; + skillPaths: string[]; + systemPrompt?: string; + toolsEnabled?: string[] | null; + toolsBlocked: string[]; + customTools: PiNativeCustomTool[]; + /** MCP servers in Pi's mcp.json shape, with header variable references left unexpanded. */ + mcpServers: Record; +} + +// ProviderConfigInput isn't re-exported from pi's public entrypoint; derive it from +// registerProvider's param type (ModelRuntime's constructor is private, so no InstanceType). +export type PiModelRuntime = Awaited>; +type PiProviderConfigInput = Parameters[1]; +type PiCatalogModel = NonNullable[number]; +// A model already resolved from Pi's catalog (getModel), used as the base to overlay onto. +export type PiResolvedModel = NonNullable>; + +// Per-model Pi metadata (api, context_window, max_tokens, cost, reasoning, input) is adapter- +// owned data carried in the model `extensions` block. It is only used to DEFINE a model Pi does +// not already know (a gateway model); a model already in Pi's catalog is used as-is and never +// rebuilt, so none of its native properties change. The adapter supplies no defaults of its own +// — for an unknown model every field Pi requires must be configured, mirroring how defining a +// custom model in a local Pi models.json requires those fields. + +// The wire protocols Pi understands; a configured model extensions.api must be one of these. +const SUPPORTED_MODEL_APIS = [ + "openai-completions", + "openai-responses", + "azure-openai-responses", + "openai-codex-responses", + "anthropic-messages", + "bedrock-converse-stream", + "google-generative-ai", + "google-vertex", + "mistral-conversations", + "pi-messages", +] as const; + +interface PiHarnessSettings { + extensions: string[]; +} + +interface PiToolFactoryContext { + name: string; + settings: JsonObject; + workspace: string; +} + +export function withCustomBaseUrl( + catalogModel: T, + baseUrl: string | null | undefined, + overrideBaseUrl = true, +): T { + if (!baseUrl) { + return catalogModel; + } + const model = overrideBaseUrl ? { ...catalogModel, baseUrl } : catalogModel; + if (catalogModel.api !== "openai-completions") { + return model; + } + return { + ...model, + // Generic OpenAI-compatible proxies may reject provider-specific + // reasoning_content fields when Pi replays an assistant tool call. + compat: { ...catalogModel.compat, requiresThinkingAsText: true }, + }; +} + +export function modelAwareCompactionReserveTokens( + configuredReserveTokens: number, + maxOutputTokens: number, + contextWindow: number, +): number { + const reserveTokens = Math.max(configuredReserveTokens, maxOutputTokens); + if (contextWindow <= 0) { + return reserveTokens; + } + return Math.min(reserveTokens, Math.floor(contextWindow / 2)); +} + +type PiToolFactory = (context: PiToolFactoryContext) => ToolDefinition | Promise; + +export const PI_BUILTIN_TOOL_NAMES = new Set(["read", "bash", "edit", "write", "grep", "find", "ls"]); +const TOOL_MODULE_EXTENSIONS = new Set([".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"]); +const PI_HARNESS_INSTALL_COMMAND = + "npm install --save-exact @earendil-works/pi-ai@1.0.3 @earendil-works/pi-coding-agent@1.0.3 @earendil-works/pi-mcp@1.0.3 @earendil-works/pi-codemode@1.0.3"; +export interface PiSdkModules { + InMemoryCredentialStore: typeof import("@earendil-works/pi-ai").InMemoryCredentialStore; + StdioTransport: typeof import("@earendil-works/pi-mcp").StdioTransport; + StreamableHttpTransport: typeof import("@earendil-works/pi-mcp").StreamableHttpTransport; + createAgentSession: typeof import("@earendil-works/pi-coding-agent").createAgentSession; + createMcpExtension: typeof import("@earendil-works/pi-coding-agent").createMcpExtension; + DefaultResourceLoader: typeof import("@earendil-works/pi-coding-agent").DefaultResourceLoader; + ModelRuntime: typeof import("@earendil-works/pi-coding-agent").ModelRuntime; + SessionManager: typeof import("@earendil-works/pi-coding-agent").SessionManager; + SettingsManager: typeof import("@earendil-works/pi-coding-agent").SettingsManager; +} + +function isMissingModuleError(error: unknown): boolean { + return ( + typeof error === "object" && + error !== null && + "code" in error && + (error.code === "ERR_MODULE_NOT_FOUND" || error.code === "MODULE_NOT_FOUND") + ); +} + +async function loadPiSdk(): Promise { + let ai: typeof import("@earendil-works/pi-ai"); + let codingAgent: typeof import("@earendil-works/pi-coding-agent"); + let mcp: typeof import("@earendil-works/pi-mcp"); + try { + [ai, codingAgent, mcp] = await Promise.all([ + import("@earendil-works/pi-ai"), + import("@earendil-works/pi-coding-agent"), + import("@earendil-works/pi-mcp"), + ]); + } catch (error) { + if (isMissingModuleError(error)) { + throw new LifecycleError( + "pi_harness_unavailable", + `The Pi SDK harness is not installed. Install a compatible harness with: ${PI_HARNESS_INSTALL_COMMAND}`, + ); + } + throw new LifecycleError("pi_harness_load_failed", "The installed Pi SDK harness could not be loaded"); + } + + if ( + typeof ai.InMemoryCredentialStore !== "function" || + typeof mcp.StdioTransport !== "function" || + typeof mcp.StreamableHttpTransport !== "function" || + typeof codingAgent.createAgentSession !== "function" || + typeof codingAgent.createMcpExtension !== "function" || + typeof codingAgent.DefaultResourceLoader !== "function" || + typeof codingAgent.ModelRuntime !== "function" || + typeof codingAgent.SessionManager !== "function" || + typeof codingAgent.SettingsManager !== "function" + ) { + throw new LifecycleError( + "pi_harness_incompatible", + "The installed Pi SDK harness does not expose the APIs required by this adapter", + ); + } + + return { + InMemoryCredentialStore: ai.InMemoryCredentialStore, + StdioTransport: mcp.StdioTransport, + StreamableHttpTransport: mcp.StreamableHttpTransport, + createAgentSession: codingAgent.createAgentSession, + createMcpExtension: codingAgent.createMcpExtension, + DefaultResourceLoader: codingAgent.DefaultResourceLoader, + ModelRuntime: codingAgent.ModelRuntime, + SessionManager: codingAgent.SessionManager, + SettingsManager: codingAgent.SettingsManager, + }; +} + +const MCP_HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u; +const MCP_ENV_REFERENCE = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/gu; +const MCP_SERVER_NAME = /^[A-Za-z0-9_-]+$/u; + +function loopbackHostname(hostname: string): boolean { + return hostname === "localhost" || hostname === "[::1]" || /^127(?:\.\d{1,3}){3}$/u.test(hostname); +} + +function expandMcpHeader( + value: string, + configuredEnvironment: Record, + parentEnvironment: NodeJS.ProcessEnv, +): string { + return value.replaceAll(MCP_ENV_REFERENCE, (_reference, variable: string) => { + const configured = configuredEnvironment[variable]; + if (Object.hasOwn(configuredEnvironment, variable) && configured !== undefined) { + return configured; + } + const inherited = parentEnvironment[variable]; + if (Object.hasOwn(parentEnvironment, variable) && inherited !== undefined) { + return inherited; + } + throw new LifecycleError( + "pi_mcp_header_variable_missing", + "A configured Pi MCP header references an environment variable that is not available", + ); + }); +} + +function validateMcpHeader(name: string, value: string): void { + if (!MCP_HEADER_NAME.test(name) || value.length === 0 || value.trim() !== value) { + throw new LifecycleError("pi_mcp_invalid_header", "A configured Pi MCP HTTP header is invalid"); + } + for (const character of value) { + const codePoint = character.codePointAt(0); + if (codePoint === undefined || codePoint > 0xFF || (codePoint < 0x20 && codePoint !== 0x09) || codePoint === 0x7F) { + throw new LifecycleError("pi_mcp_invalid_header", "A configured Pi MCP HTTP header is invalid"); + } + } +} + +function validateMcpToolNames(names: readonly string[] | null | undefined): void { + if (names?.some((name) => name.includes("*")) === true) { + throw new LifecycleError( + "pi_mcp_tool_pattern_unsupported", + "Pi MCP tool filters require exact tool names and do not accept patterns", + ); + } +} + +function mcpToolExposure( + allowed: string[] | null | undefined, + blocked: string[] | undefined, +): Pick { + validateMcpToolNames(allowed); + validateMcpToolNames(blocked); + const toolExposure: Record = {}; + if (allowed !== undefined && allowed !== null) { + for (const name of allowed) { + toolExposure[name] = "direct"; + } + } + for (const name of blocked ?? []) { + toolExposure[name] = "hidden"; + } + return { + exposure: allowed === undefined || allowed === null ? "direct" : "hidden", + ...(Object.keys(toolExposure).length === 0 ? {} : { toolExposure }), + }; +} + +export function selectPiMcpServers( + config: AgentConfig, + configuredEnvironment: Record, + parentEnvironment: NodeJS.ProcessEnv, + options: { expandHeaders?: boolean } = {}, +): Record { + const expandHeaders = options.expandHeaders ?? true; + if (config.mcp?.extensions !== undefined) { + throw new LifecycleError("pi_mcp_extensions_unsupported", "Pi does not support Fabric MCP extensions"); + } + const selected = Object.create(null) as Record; + for (const [name, server] of Object.entries(config.mcp?.servers ?? {})) { + if (!MCP_SERVER_NAME.test(name) || server.extensions !== undefined) { + throw new LifecycleError("pi_mcp_invalid_server", "Pi MCP server configuration is unsupported or invalid"); + } + if (server.authentication !== undefined && server.authentication !== null) { + throw new LifecycleError( + "pi_mcp_authentication_unsupported", + "Pi MCP authentication is unsupported; configure a custom authorization header instead", + ); + } + const exposure = mcpToolExposure(server.allowed_tools, server.blocked_tools); + if (server.transport === "stdio") { + if (server.url.trim().length === 0 || Object.keys(server.custom_headers ?? {}).length > 0) { + throw new LifecycleError( + "pi_mcp_invalid_server", + "Pi stdio MCP servers require a command and do not accept HTTP headers", + ); + } + selected[name] = { + type: "stdio", + command: server.url, + ...(server.args === undefined ? {} : { args: server.args }), + ...(server.env === undefined ? {} : { env: server.env }), + ...exposure, + }; + continue; + } + if (server.transport === "streamable-http") { + if ((server.args?.length ?? 0) > 0 || Object.keys(server.env ?? {}).length > 0) { + throw new LifecycleError( + "pi_mcp_invalid_server", + "Pi streamable-HTTP MCP servers do not accept command arguments or environment variables", + ); + } + let endpoint: URL; + try { + endpoint = new URL(server.url); + } catch { + throw new LifecycleError( + "pi_mcp_invalid_server", + "Pi streamable-HTTP MCP servers require an HTTP or HTTPS URL", + ); + } + if ( + (endpoint.protocol !== "http:" && endpoint.protocol !== "https:") || + (endpoint.protocol === "http:" && !loopbackHostname(endpoint.hostname)) + ) { + throw new LifecycleError( + "pi_mcp_invalid_server", + "Pi streamable-HTTP MCP servers require HTTPS unless the endpoint is loopback", + ); + } + const headerNames = new Set(); + const headers = Object.fromEntries( + Object.entries(server.custom_headers ?? {}).map(([headerName, value]) => { + const normalizedName = headerName.toLowerCase(); + if (headerNames.has(normalizedName)) { + throw new LifecycleError("pi_mcp_invalid_header", "A configured Pi MCP HTTP header is invalid"); + } + headerNames.add(normalizedName); + // Pi's mcp.json expands ${NAME} references itself, so a written configuration keeps them. + const expanded = expandMcpHeader(value, configuredEnvironment, parentEnvironment); + validateMcpHeader(headerName, expanded); + return [headerName, expandHeaders ? expanded : value]; + }), + ); + selected[name] = { + type: "http", + url: server.url, + ...(Object.keys(headers).length === 0 ? {} : { headers }), + ...exposure, + }; + continue; + } + throw new LifecycleError( + "pi_mcp_transport_unsupported", + `Pi does not support MCP transport ${JSON.stringify(server.transport)}; supported transports: stdio, streamable-http`, + { + metadata: { + field: `mcp.servers.${name}.transport`, + transport: server.transport, + supported_transports: ["stdio", "streamable-http"], + }, + }, + ); + } + return selected; +} + +/** + * Read the MCP servers from the runtime's mcp.json, expanding each HTTP header's + * `${NAME}` references from the runtime's environment, then the adapter's, as + * selectPiMcpServers validated them. + */ +async function readMcpServers( + agentDir: string, + configuredEnvironment: Record, + parentEnvironment: NodeJS.ProcessEnv, +): Promise> { + let text: string; + try { + text = await readFile(join(agentDir, "mcp.json"), "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return {}; + throw error; + } + const servers = (JSON.parse(text) as { mcpServers: Record }).mcpServers; + return Object.fromEntries(Object.entries(servers).map(([name, server]) => { + if (!("headers" in server) || server.headers === undefined) return [name, server]; + const headers = Object.fromEntries(Object.entries(server.headers).map(([header, value]) => { + const expanded = expandMcpHeader(value, configuredEnvironment, parentEnvironment); + validateMcpHeader(header, expanded); + return [header, expanded]; + })); + return [name, { ...server, headers }]; + })); +} + +function selectModel(config: AgentConfig): AgentModelConfig { + const entries = Object.entries(config.models ?? {}); + if (entries.length === 0) { + throw new LifecycleError("pi_model_required", "The Pi adapter requires one configured model"); + } + const selected = config.models?.default ?? (entries.length === 1 ? entries[0]?.[1] : undefined); + if (selected === undefined) { + throw new LifecycleError( + "pi_model_ambiguous", + "Configure a default model role when the Pi adapter receives multiple models", + ); + } + return selected; +} + +/** + * Build the Pi catalog entry to register for the selected model, as an OVERLAY on `base` (the + * model's existing Pi catalog entry, or undefined when Pi doesn't know it). The rule is a thin + * pass-through: a field the config SUPPLIES (via the model `extensions` block, or `base_url` for + * the endpoint) is used; a field it OMITS falls back to `base`'s value, and if there is no base + * (an unknown gateway model) an optional field is left UNSET so Pi applies its own default. The + * adapter invents no defaults of its own. + * + * It does, however, require what Pi has no usable default for. For an unknown model that means a + * complete-enough definition: `api` (enforced at registration — Pi can't resolve the wire + * protocol otherwise), `base_url`, `context_window`/`max_tokens`, `input`, and `cost`. Supplied values + * are validated (`api` a {@link SUPPORTED_MODEL_APIS} value, token limits positive, cost + * well-formed) so a malformed override fails fast instead of reaching Pi. + */ +export function buildCatalogModel(model: AgentModelConfig, base: PiResolvedModel | undefined): PiCatalogModel { + const meta = (model.extensions ?? {}) as Record; + const fail = (reason: string): never => { + throw new LifecycleError("pi_model_extensions_invalid", reason, { metadata: { model: model.model } }); + }; + if (meta.api !== undefined && !SUPPORTED_MODEL_APIS.includes(meta.api as (typeof SUPPORTED_MODEL_APIS)[number])) { + throw new LifecycleError( + "pi_model_api_invalid", + `Unsupported model api '${String(meta.api)}'; model extensions.api must be one of: ${SUPPORTED_MODEL_APIS.join(", ")}`, + { metadata: { model: model.model } }, + ); + } + // Validate a SUPPLIED token limit (positive number); when absent, inherit base's value or leave + // it unset for Pi to default. Never fabricate a value. + const positive = (value: unknown, inherited: number | undefined, field: string): number | undefined => { + if (value === undefined) { + return inherited; + } + if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) { + return fail(`model extensions.${field} must be a positive number`); + } + return value; + }; + if (Array.isArray(meta.input) && meta.input.some((item) => item !== "text" && item !== "image")) { + fail("model extensions.input must contain only 'text' or 'image' values"); + } + const suppliedInput = Array.isArray(meta.input) + ? (meta.input.filter((item) => item === "text" || item === "image") as ("text" | "image")[]) + : undefined; + const api = typeof meta.api === "string" ? (meta.api as PiCatalogModel["api"]) : base?.api; + const baseUrl = model.base_url ?? base?.baseUrl; + const reasoning = meta.reasoning !== undefined ? meta.reasoning === true : base?.reasoning; + const input = suppliedInput !== undefined && suppliedInput.length > 0 ? suppliedInput : base?.input; + const cost = parseCost(meta.cost, fail) ?? base?.cost; + const contextWindow = positive(meta.context_window, base?.contextWindow, "context_window"); + const maxTokens = positive(model.max_tokens ?? meta.max_tokens, base?.maxTokens, "max_tokens"); + // An unknown model has no catalog entry to supply its endpoint, limits, input modalities, + // or cost rates. Require those fields before Pi uses them; `api` is enforced at registration. + if (base === undefined) { + const missing = [ + baseUrl === undefined ? "base_url" : undefined, + contextWindow === undefined ? "context_window" : undefined, + maxTokens === undefined ? "max_tokens" : undefined, + input === undefined ? "input" : undefined, + cost === undefined ? "cost" : undefined, + ].filter((field): field is string => field !== undefined); + if (missing.length > 0) { + fail( + `model '${model.model}' is not known to Pi, so a complete definition is required; ` + + `missing: ${missing.join(", ")} (set base_url and the required model extensions)`, + ); + } + } + // Include only resolved fields; the adapter adds no defaults for optional metadata. + const entry: Record = { id: model.model }; + if (typeof meta.name === "string" || base?.name !== undefined) { + entry.name = typeof meta.name === "string" ? meta.name : base?.name; + } + if (api !== undefined) entry.api = api; + if (baseUrl !== undefined) entry.baseUrl = baseUrl; + if (reasoning !== undefined) entry.reasoning = reasoning; + if (input !== undefined) entry.input = input; + if (cost !== undefined) entry.cost = cost; + if (contextWindow !== undefined) entry.contextWindow = contextWindow; + if (maxTokens !== undefined) entry.maxTokens = maxTokens; + return entry as unknown as PiCatalogModel; +} + +// Validate a supplied cost (all four numeric rates) and reject a partial object (e.g. `{}`), +// which Pi would turn into NaN costs. Returns undefined when no cost is configured, so the +// caller keeps the base/default cost instead. +function parseCost(value: unknown, fail: (reason: string) => never): PiCatalogModel["cost"] | undefined { + if (value === undefined) { + return undefined; + } + if (typeof value !== "object" || value === null) { + return fail("model extensions.cost must be an object with numeric input/output/cacheRead/cacheWrite rates"); + } + const record = value as Record; + const rates = ["input", "output", "cacheRead", "cacheWrite"] as const; + const parsed: Record = {}; + for (const rate of rates) { + const amount = record[rate]; + if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0) { + return fail(`model extensions.cost.${rate} must be a non-negative number`); + } + parsed[rate] = amount; + } + // SAFETY: every rate was just validated as a finite non-negative number above. + return parsed as unknown as PiCatalogModel["cost"]; +} + +function harnessSettings(config: AgentConfig): PiHarnessSettings { + const raw = config.harness?.settings; + const extensions = raw?.extensions; + if (extensions === undefined) { + return { extensions: [] }; + } + if (!Array.isArray(extensions)) { + throw new LifecycleError("pi_invalid_settings", "Pi extension settings do not match the adapter schema"); + } + const values: string[] = []; + for (const entry of extensions) { + if (typeof entry !== "string") { + throw new LifecycleError("pi_invalid_settings", "Pi extension settings do not match the adapter schema"); + } + values.push(entry); + } + return { extensions: values }; +} + +export function containedBy(root: string, candidate: string): boolean { + const path = relative(root, candidate); + return path === "" || (!path.startsWith(`..${sep}`) && path !== ".." && !isAbsolute(path)); +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +export async function resolveToolModule(workspace: string, reference: string): Promise<{ path: string; exportName: string }> { + const match = /^(?[^#]+?)(?:#(?[A-Za-z_$][\w$]*))?$/.exec(reference); + const configuredPath = match?.groups?.path; + if (configuredPath === undefined || isAbsolute(configuredPath)) { + throw new LifecycleError( + "pi_tool_ref_invalid", + "Pi tool module references must use a workspace-relative path with an optional export fragment", + ); + } + let candidate: string; + try { + candidate = await realpath(resolve(workspace, configuredPath)); + } catch { + throw new LifecycleError("pi_tool_module_not_found", "A configured Pi tool module does not exist"); + } + if (!containedBy(workspace, candidate)) { + throw new LifecycleError("pi_tool_module_outside_workspace", "Pi tool modules must be contained by the workspace"); + } + if (!(await stat(candidate)).isFile() || !TOOL_MODULE_EXTENSIONS.has(extname(candidate))) { + throw new LifecycleError( + "pi_tool_module_invalid", + "Pi tool modules must be JavaScript or TypeScript files", + ); + } + return { path: candidate, exportName: match?.groups?.export ?? "default" }; +} + +function validateToolDefinition(name: string, value: unknown): ToolDefinition { + if ( + !isRecord(value) || + value.name !== name || + typeof value.label !== "string" || + value.label.length === 0 || + typeof value.description !== "string" || + value.description.length === 0 || + !isRecord(value.parameters) || + typeof value.execute !== "function" + ) { + throw new LifecycleError( + "pi_tool_factory_invalid", + "A Pi tool factory returned an invalid tool definition or a mismatched tool name", + { metadata: { tool: name } }, + ); + } + // SAFETY: the checks above verify every field of the ToolDefinition contract at runtime. + return value as unknown as ToolDefinition; +} + +export async function resolveCustomTools( + workspace: string, + definitions: Record, +): Promise { + const jiti = createJiti(import.meta.url, { interopDefault: false }); + const tools: ToolDefinition[] = []; + for (const [name, definition] of Object.entries(definitions)) { + if (PI_BUILTIN_TOOL_NAMES.has(name)) { + throw new LifecycleError("pi_tool_collision", "A Fabric tool definition collides with a Pi built-in tool", { + metadata: { tool: name }, + }); + } + if (definition.kind !== "module") { + throw new LifecycleError("pi_tool_kind_unsupported", "Pi supports only module tool definitions"); + } + const moduleReference = await resolveToolModule(workspace, definition.ref); + let loaded: unknown; + try { + loaded = await jiti.import(moduleReference.path); + } catch { + throw new LifecycleError("pi_tool_module_load_failed", "A configured Pi tool module could not be loaded", { + metadata: { tool: name }, + }); + } + const factory = isRecord(loaded) ? loaded[moduleReference.exportName] : undefined; + if (typeof factory !== "function") { + throw new LifecycleError("pi_tool_factory_missing", "A configured Pi tool module export is not a factory", { + metadata: { tool: name }, + }); + } + let tool: unknown; + try { + tool = await (factory as PiToolFactory)({ + name, + settings: definition.settings ?? {}, + workspace, + }); + } catch { + throw new LifecycleError("pi_tool_factory_failed", "A configured Pi tool factory failed", { + metadata: { tool: name }, + }); + } + tools.push(validateToolDefinition(name, tool)); + } + return tools; +} + +async function resolveExtensionPaths(workspace: string, configured: string[]): Promise { + const resolved: string[] = []; + for (const entry of configured) { + if (isAbsolute(entry)) { + throw new LifecycleError("pi_extension_outside_workspace", "Pi extension paths must be workspace-relative"); + } + let candidate: string; + try { + candidate = await realpath(resolve(workspace, entry)); + } catch { + throw new LifecycleError("pi_extension_not_found", "A configured Pi extension path does not exist"); + } + if (!containedBy(workspace, candidate)) { + throw new LifecycleError("pi_extension_outside_workspace", "Pi extension path resolves outside the workspace"); + } + const info = await stat(candidate); + if (!info.isFile() || (!candidate.endsWith(".ts") && !candidate.endsWith(".js"))) { + throw new LifecycleError("pi_unsupported_extension", "Pi extensions must be .ts or .js files"); + } + resolved.push(candidate); + } + return resolved; +} + +async function resolveSkillPaths(baseDir: string, configured: string[]): Promise { + const resolved: string[] = []; + for (const entry of configured) { + let candidate: string; + try { + candidate = await realpath(resolve(baseDir, entry)); + } catch { + throw new LifecycleError("pi_skill_not_found", "A configured NeMo Fabric skill path does not exist"); + } + let info; + try { + info = await stat(candidate); + } catch { + throw new LifecycleError("pi_skill_not_found", "A configured NeMo Fabric skill path does not exist"); + } + if (!info.isDirectory()) { + throw new LifecycleError("pi_skill_invalid", "NeMo Fabric skill paths must be directories"); + } + try { + if (!(await stat(join(candidate, "SKILL.md"))).isFile()) { + throw new Error("not a file"); + } + } catch { + throw new LifecycleError( + "pi_skill_invalid", + "NeMo Fabric skill directories must contain a SKILL.md file", + ); + } + resolved.push(candidate); + } + return resolved; +} + +function credentialValue(input: AdapterStartInput, name: string): string | undefined { + return input.runtimeContext.environment.env?.[name] ?? process.env[name]; +} + +/** A runtime's Pi configuration, written to its agent directory, with the model Pi resolved from those files. */ +export interface PiPreparedConfiguration { + pi: PiSdkModules; + configuration: PiNativeConfiguration; + /** Pi's model runtime, loaded from the agent directory's models.json and holding the key in memory. */ + modelRuntime: PiModelRuntime; + model: PiResolvedModel; + /** The configured extensions, resolved to absolute paths. */ + extensionPaths: string[]; + skillPaths: string[]; + /** The configured Fabric module tools, loaded. */ + customTools: ToolDefinition[]; + /** The MCP servers from the agent directory's mcp.json, with header references expanded. */ + mcpServers: Record; +} + +/** + * Resolve the runtime's Pi configuration from FabricConfig, write it to the + * runtime's agent directory, and check that Pi resolves the selected model from + * those files. Every execution path starts with this; it runs no session. + */ +export async function preparePiConfiguration(input: AdapterStartInput): Promise { + const systemInstruction = input.config.instructions?.system; + if (systemInstruction?.mode === "append") { + throw new LifecycleError( + "unsupported_system_instruction_mode", + "Pi does not support instructions.system.mode='append'; supported modes: replace", + { + metadata: { + field: "instructions.system.mode", + mode: systemInstruction.mode, + supported_modes: ["replace"], + }, + }, + ); + } + // Validated here, before anything starts; mcp.json keeps header references unexpanded. + const mcpConfiguration = selectPiMcpServers( + input.config, + input.runtimeContext.environment.env ?? {}, + process.env, + { expandHeaders: false }, + ); + const pi = await loadPiSdk(); + let workspace: string; + try { + workspace = await realpath(resolve(input.runtimeContext.environment.workspace ?? input.baseDir)); + if (!(await stat(workspace)).isDirectory()) { + throw new Error("not a directory"); + } + } catch { + throw new LifecycleError("pi_workspace_invalid", "The Fabric runtime workspace must be a directory"); + } + const selected = selectModel(input.config); + const apiKeyEnv = selected.api_key_env; + if (apiKeyEnv === undefined || apiKeyEnv === null || apiKeyEnv.length === 0) { + throw new LifecycleError("pi_api_key_env_required", "The selected Pi model requires api_key_env"); + } + const apiKey = credentialValue(input, apiKeyEnv); + if (apiKey === undefined || apiKey.length === 0) { + throw new LifecycleError("pi_credential_missing", `Credential environment variable ${apiKeyEnv} is not set`); + } + + const extensionPaths = await resolveExtensionPaths(workspace, harnessSettings(input.config).extensions); + const skillPaths = await resolveSkillPaths(input.baseDir, input.config.skills?.paths ?? []); + const customTools = await resolveCustomTools(workspace, input.config.tools?.definitions ?? {}); + + // Resolve the selected model as an overlay on Pi's built-in catalog entry (if any): supplied + // config fields override, omitted ones keep Pi's native value, and for an unknown (gateway) + // model the overlay base is empty so its required metadata must be explicit. This way selecting + // a known provider/model and changing nothing preserves all its native properties, while an + // explicit base_url / extensions field is still honored. A Fabric agent runs ONE model role per + // session (selectModel enforces default-or-sole), mirroring the other single-model adapters. + const builtIns = await pi.ModelRuntime.create({ + credentials: new pi.InMemoryCredentialStore(), + modelsPath: null, + allowModelNetwork: false, + refreshOnCreate: false, + }); + // SAFETY: buildCatalogModel builds a plain object of these fields; here it is models.json data. + const resolvedEntry = buildCatalogModel(selected, builtIns.getModel(selected.provider, selected.model)) as unknown as + Record & { api?: string; baseUrl?: string; compat?: object; maxTokens?: number; contextWindow?: number }; + // The OpenAI-compatible-proxy compat shim (see withCustomBaseUrl) goes into the definition + // itself, so every process that reads models.json gets it. + const catalogEntry = selected.base_url && resolvedEntry.api === "openai-completions" + ? { ...resolvedEntry, compat: { ...resolvedEntry.compat, requiresThinkingAsText: true } } + : resolvedEntry; + const { baseUrl: providerBaseUrl, ...modelDefinition } = catalogEntry; + const compactionReserveTokens = modelAwareCompactionReserveTokens( + pi.SettingsManager.inMemory({}, { projectTrusted: false }).getCompactionReserveTokens(), + catalogEntry.maxTokens ?? 0, + catalogEntry.contextWindow ?? 0, + ); + const configuration: PiNativeConfiguration = { + agentDir: agentDirectory(runtimeDirectory(input)), + sessionDir: sessionDirectory(runtimeDirectory(input)), + keepState: keepsState(input), + workspace, + provider: selected.provider, + ...(providerBaseUrl === undefined ? {} : { baseUrl: providerBaseUrl }), + model: modelDefinition as Record, + apiKeyEnv, + compactionReserveTokens, + extensionPaths: [...extensionPaths], + skillPaths, + ...(systemInstruction?.content === undefined ? {} : { systemPrompt: systemInstruction.content }), + toolsEnabled: input.config.tools?.enabled, + toolsBlocked: input.config.tools?.blocked ?? [], + customTools: await Promise.all( + Object.entries(input.config.tools?.definitions ?? {}).map(async ([name, definition]) => ({ + name, + ...(await resolveToolModule(workspace, definition.ref)), + settings: definition.settings ?? {}, + })), + ), + mcpServers: mcpConfiguration, + }; + + // Pi's own files are the configuration: the SDK session loads them as Pi's CLI and terminal UI do. + const agentDir = configuration.agentDir; + await writeAgentDirectory(configuration); + const modelRuntime = await pi.ModelRuntime.create({ + // The key stays in memory; models.json only names its variable. + credentials: new pi.InMemoryCredentialStore(), + modelsPath: join(agentDir, "models.json"), + allowModelNetwork: false, + refreshOnCreate: false, + }); + const modelsError = modelRuntime.getError(); + if (modelsError !== undefined) { + // Pi reports 'no "api" specified' when it can't resolve the model's wire protocol (not a + // built-in and no extensions.api). Only THAT cause maps to the api-required remediation; + // any other load failure keeps a generic code so the message isn't misleading. + if (/no "api" specified/i.test(modelsError)) { + throw new LifecycleError( + "pi_model_api_required", + `Set extensions.api for a gateway-served model (one of: ${SUPPORTED_MODEL_APIS.join(", ")}); the selected model has no api Pi can resolve`, + { metadata: { provider: selected.provider, model: selected.model, cause: modelsError } }, + ); + } + throw new LifecycleError( + "pi_provider_registration_failed", + `Pi rejected the configuration for provider '${selected.provider}'`, + { metadata: { provider: selected.provider, cause: modelsError } }, + ); + } + await modelRuntime.setRuntimeApiKey(selected.provider, apiKey); + const model = modelRuntime.getModel(selected.provider, selected.model); + if (model === undefined) { + throw new LifecycleError("pi_model_unknown", "The selected provider and model are not present in Pi's catalog"); + } + const mcpServers = await readMcpServers( + agentDir, + input.runtimeContext.environment.env ?? {}, + process.env, + ); + return { pi, configuration, modelRuntime, model, extensionPaths, skillPaths, customTools, mcpServers }; +} diff --git a/adapters/typescript/pi/src/native-only.ts b/adapters/typescript/pi/src/native-only.ts new file mode 100644 index 000000000..c99f91513 --- /dev/null +++ b/adapters/typescript/pi/src/native-only.ts @@ -0,0 +1,92 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// A runtime with sdk.enabled false. It writes the runtime's Pi configuration for +// the native interfaces and runs no embedded session, so it never takes a +// prompt. With Relay enabled it still runs the gateway for the interfaces' turns. +// Configured settings that only the SDK path honors have no effect here, so +// startup logs a warning for each one it finds, rather than refusing the +// config: switching between the SDK and the terminal TUI needs no config change. + +import type { AdapterCheckResult, CheckLevel, CheckSource } from "nemo-fabric-adapter-contract"; +import { LifecycleError, unobservedHealth, type AdapterStartInput } from "nemo-fabric-adapters-common"; + +import { preparePiConfiguration, type PiModelRuntime, type PiNativeConfiguration } from "./native-configuration.js"; +import { atofStreamSinkNames } from "./relay-config.js"; +import { PiRelayFactory, type PiRelayControllerFactory, type PiRelayRuntime } from "./relay.js"; +import type { PiPromptOutcome, PiSessionFactory, PiSessionHandle } from "./runtime.js"; + +class PiNativeOnlyHandle implements PiSessionHandle { + readonly configuration: PiNativeConfiguration; + readonly turnCount = 0; + readonly relay?: PiRelayRuntime; + private readonly modelRuntime: PiModelRuntime; + private readonly expectedModel: { id: string; provider: string }; + private stopped = false; + + constructor(configuration: PiNativeConfiguration, modelRuntime: PiModelRuntime, + expectedModel: { id: string; provider: string }, relay?: PiRelayRuntime) { + this.configuration = configuration; + this.relay = relay; + this.modelRuntime = modelRuntime; + this.expectedModel = expectedModel; + } + + async prompt(): Promise { + // PiAdapterRuntime answers pi_sdk_disabled before it reaches the handle. + throw new LifecycleError("pi_sdk_disabled", "Embedded Pi SDK execution is disabled"); + } + + async check(level: CheckLevel): Promise { + if (this.stopped) return { ...unobservedHealth("session_closed"), outcome: "failed", activity: "stopped" }; + const source: CheckSource = level === "live" ? "fabric.adapter.liveness" + : level === "active" ? "fabric.adapter.interface" : "fabric.adapter.readiness"; + const observed_at = new Date().toISOString(); + if (level === "ready" + && this.modelRuntime.getModel(this.expectedModel.provider, this.expectedModel.id) === undefined) { + return { outcome: "failed", reason_code: "health_failed", activity: "unknown", source, observed_at }; + } + return { outcome: "passed", reason_code: null, activity: "unknown", source, observed_at }; + } + + async stop(): Promise { + this.stopped = true; + } +} + +/** The Relay ATOF sink that the Python SDK adds for `start_runtime(..., streaming=True)`. */ +const FABRIC_STREAM_SINK = "nemo-fabric-stream"; + +/** + * Configured settings that only the embedded SDK session honors, each as the warning a + * native-only runtime logs. Everything else in FabricConfig reaches the terminal TUI + * through the agent directory and the launcher. + */ +export function sdkOnlySettings(relay: PiRelayRuntime | undefined): string[] { + const warnings: string[] = []; + if (relay?.pluginConfig !== undefined && atofStreamSinkNames(relay.pluginConfig).includes(FABRIC_STREAM_SINK)) { + // The collector correlates records with invocations; terminal TUI turns aren't invocations. + warnings.push( + `the Relay ATOF sink ${FABRIC_STREAM_SINK} (start_runtime(..., streaming=True)) only streams SDK invocations, ` + + "and sdk.enabled is false, so it has no effect on the terminal TUI", + ); + } + return warnings; +} + +export class PiNativeOnlySessionFactory implements PiSessionFactory { + private readonly relayFactory: PiRelayControllerFactory; + + constructor(relayFactory: PiRelayControllerFactory = new PiRelayFactory()) { + this.relayFactory = relayFactory; + } + + async create(input: AdapterStartInput): Promise { + const { configuration, modelRuntime, model } = await preparePiConfiguration(input); + const relay = await this.relayFactory.start(input, { api: model.api, baseUrl: model.baseUrl }); + for (const warning of sdkOnlySettings(relay)) { + process.stderr.write(`Pi warning: ${warning}\n`); + } + return new PiNativeOnlyHandle(configuration, modelRuntime, { id: model.id, provider: model.provider }, relay); + } +} diff --git a/adapters/typescript/pi/src/pi-sdk.ts b/adapters/typescript/pi/src/pi-sdk.ts index 31c874d04..d5f2e30ae 100644 --- a/adapters/typescript/pi/src/pi-sdk.ts +++ b/adapters/typescript/pi/src/pi-sdk.ts @@ -1,13 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -// Pi SDK integration boundary. It translates normalized adapter configuration -// into a controlled in-memory Pi session, including model credentials, skills, -// extensions, custom tools, and workspace containment. +// Pi SDK integration boundary. It runs a controlled in-memory Pi session on the +// runtime's Pi configuration (native-configuration.ts), with the model key in +// memory, MCP connections the session tracks, and Relay capture. -import { mkdtemp, realpath, rm, stat } from "node:fs/promises"; -import { homedir, tmpdir } from "node:os"; -import { extname, isAbsolute, join, relative, resolve, sep } from "node:path"; +import { homedir } from "node:os"; +import { join, resolve } from "node:path"; import type { AuthProvider, JsonRpcMessage, McpTransport } from "@earendil-works/pi-mcp"; import type { @@ -19,8 +18,7 @@ import type { McpTransportFactory, ToolDefinition, } from "@earendil-works/pi-coding-agent"; -import { createJiti } from "jiti/static"; -import type { AdapterCheckResult, CheckLevel, CheckSource, AgentConfig, AgentModelConfig, AgentToolDefinition, JsonObject } from "nemo-fabric-adapter-contract"; +import type { AdapterCheckResult, CheckLevel, CheckSource } from "nemo-fabric-adapter-contract"; import { LifecycleError, unobservedHealth, type AdapterStartInput } from "nemo-fabric-adapters-common"; import { @@ -28,327 +26,21 @@ import { type PiRelayControllerFactory, type PiRelayRuntime, } from "./relay.js"; +import { + containedBy, + PI_BUILTIN_TOOL_NAMES, + preparePiConfiguration, + type PiModelRuntime, + type PiNativeConfiguration, + type PiSdkModules, +} from "./native-configuration.js"; +import { privateDirectory } from "./agent-directory.js"; import { invocationUsage } from "./usage.js"; import type { PiPromptOutcome, PiSessionFactory, PiSessionHandle } from "./runtime.js"; +import { sdkEnabled } from "./settings.js"; -// ProviderConfigInput isn't re-exported from pi's public entrypoint; derive it from -// registerProvider's param type (ModelRuntime's constructor is private, so no InstanceType). -type PiModelRuntime = Awaited>; -type PiProviderConfigInput = Parameters[1]; -type PiCatalogModel = NonNullable[number]; -// A model already resolved from Pi's catalog (getModel), used as the base to overlay onto. -type PiResolvedModel = NonNullable>; - -// Per-model Pi metadata (api, context_window, max_tokens, cost, reasoning, input) is adapter- -// owned data carried in the model `extensions` block. It is only used to DEFINE a model Pi does -// not already know (a gateway model); a model already in Pi's catalog is used as-is and never -// rebuilt, so none of its native properties change. The adapter supplies no defaults of its own -// — for an unknown model every field Pi requires must be configured, mirroring how defining a -// custom model in a local Pi models.json requires those fields. - -// The wire protocols Pi understands; a configured model extensions.api must be one of these. -const SUPPORTED_MODEL_APIS = [ - "openai-completions", - "openai-responses", - "azure-openai-responses", - "openai-codex-responses", - "anthropic-messages", - "bedrock-converse-stream", - "google-generative-ai", - "google-vertex", - "mistral-conversations", - "pi-messages", -] as const; - -interface PiHarnessSettings { - extensions: string[]; -} - -interface PiToolFactoryContext { - name: string; - settings: JsonObject; - workspace: string; -} - -export function withCustomBaseUrl( - catalogModel: T, - baseUrl: string | null | undefined, - overrideBaseUrl = true, -): T { - if (!baseUrl) { - return catalogModel; - } - const model = overrideBaseUrl ? { ...catalogModel, baseUrl } : catalogModel; - if (catalogModel.api !== "openai-completions") { - return model; - } - return { - ...model, - // Generic OpenAI-compatible proxies may reject provider-specific - // reasoning_content fields when Pi replays an assistant tool call. - compat: { ...catalogModel.compat, requiresThinkingAsText: true }, - }; -} - -export function modelAwareCompactionReserveTokens( - configuredReserveTokens: number, - maxOutputTokens: number, - contextWindow: number, -): number { - const reserveTokens = Math.max(configuredReserveTokens, maxOutputTokens); - if (contextWindow <= 0) { - return reserveTokens; - } - return Math.min(reserveTokens, Math.floor(contextWindow / 2)); -} - -type PiToolFactory = (context: PiToolFactoryContext) => ToolDefinition | Promise; - -const PI_BUILTIN_TOOL_NAMES = new Set(["read", "bash", "edit", "write", "grep", "find", "ls"]); -const TOOL_MODULE_EXTENSIONS = new Set([".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"]); -const PI_HARNESS_INSTALL_COMMAND = - "npm install --save-exact @earendil-works/pi-ai@1.0.3 @earendil-works/pi-coding-agent@1.0.3 @earendil-works/pi-mcp@1.0.3 @earendil-works/pi-codemode@1.0.3"; const MCP_STARTUP_TIMEOUT_MS = 10_000; -interface PiSdkModules { - InMemoryCredentialStore: typeof import("@earendil-works/pi-ai").InMemoryCredentialStore; - StdioTransport: typeof import("@earendil-works/pi-mcp").StdioTransport; - StreamableHttpTransport: typeof import("@earendil-works/pi-mcp").StreamableHttpTransport; - createAgentSession: typeof import("@earendil-works/pi-coding-agent").createAgentSession; - createMcpExtension: typeof import("@earendil-works/pi-coding-agent").createMcpExtension; - DefaultResourceLoader: typeof import("@earendil-works/pi-coding-agent").DefaultResourceLoader; - ModelRuntime: typeof import("@earendil-works/pi-coding-agent").ModelRuntime; - SessionManager: typeof import("@earendil-works/pi-coding-agent").SessionManager; - SettingsManager: typeof import("@earendil-works/pi-coding-agent").SettingsManager; -} - -function isMissingModuleError(error: unknown): boolean { - return ( - typeof error === "object" && - error !== null && - "code" in error && - (error.code === "ERR_MODULE_NOT_FOUND" || error.code === "MODULE_NOT_FOUND") - ); -} - -async function loadPiSdk(): Promise { - let ai: typeof import("@earendil-works/pi-ai"); - let codingAgent: typeof import("@earendil-works/pi-coding-agent"); - let mcp: typeof import("@earendil-works/pi-mcp"); - try { - [ai, codingAgent, mcp] = await Promise.all([ - import("@earendil-works/pi-ai"), - import("@earendil-works/pi-coding-agent"), - import("@earendil-works/pi-mcp"), - ]); - } catch (error) { - if (isMissingModuleError(error)) { - throw new LifecycleError( - "pi_harness_unavailable", - `The Pi SDK harness is not installed. Install a compatible harness with: ${PI_HARNESS_INSTALL_COMMAND}`, - ); - } - throw new LifecycleError("pi_harness_load_failed", "The installed Pi SDK harness could not be loaded"); - } - - if ( - typeof ai.InMemoryCredentialStore !== "function" || - typeof mcp.StdioTransport !== "function" || - typeof mcp.StreamableHttpTransport !== "function" || - typeof codingAgent.createAgentSession !== "function" || - typeof codingAgent.createMcpExtension !== "function" || - typeof codingAgent.DefaultResourceLoader !== "function" || - typeof codingAgent.ModelRuntime !== "function" || - typeof codingAgent.SessionManager !== "function" || - typeof codingAgent.SettingsManager !== "function" - ) { - throw new LifecycleError( - "pi_harness_incompatible", - "The installed Pi SDK harness does not expose the APIs required by this adapter", - ); - } - - return { - InMemoryCredentialStore: ai.InMemoryCredentialStore, - StdioTransport: mcp.StdioTransport, - StreamableHttpTransport: mcp.StreamableHttpTransport, - createAgentSession: codingAgent.createAgentSession, - createMcpExtension: codingAgent.createMcpExtension, - DefaultResourceLoader: codingAgent.DefaultResourceLoader, - ModelRuntime: codingAgent.ModelRuntime, - SessionManager: codingAgent.SessionManager, - SettingsManager: codingAgent.SettingsManager, - }; -} - -const MCP_HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u; -const MCP_ENV_REFERENCE = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/gu; -const MCP_SERVER_NAME = /^[A-Za-z0-9_-]+$/u; - -function loopbackHostname(hostname: string): boolean { - return hostname === "localhost" || hostname === "[::1]" || /^127(?:\.\d{1,3}){3}$/u.test(hostname); -} - -function expandMcpHeader( - value: string, - configuredEnvironment: Record, - parentEnvironment: NodeJS.ProcessEnv, -): string { - return value.replaceAll(MCP_ENV_REFERENCE, (_reference, variable: string) => { - const configured = configuredEnvironment[variable]; - if (Object.hasOwn(configuredEnvironment, variable) && configured !== undefined) { - return configured; - } - const inherited = parentEnvironment[variable]; - if (Object.hasOwn(parentEnvironment, variable) && inherited !== undefined) { - return inherited; - } - throw new LifecycleError( - "pi_mcp_header_variable_missing", - "A configured Pi MCP header references an environment variable that is not available", - ); - }); -} - -function validateMcpHeader(name: string, value: string): void { - if (!MCP_HEADER_NAME.test(name) || value.length === 0 || value.trim() !== value) { - throw new LifecycleError("pi_mcp_invalid_header", "A configured Pi MCP HTTP header is invalid"); - } - for (const character of value) { - const codePoint = character.codePointAt(0); - if (codePoint === undefined || codePoint > 0xFF || (codePoint < 0x20 && codePoint !== 0x09) || codePoint === 0x7F) { - throw new LifecycleError("pi_mcp_invalid_header", "A configured Pi MCP HTTP header is invalid"); - } - } -} - -function validateMcpToolNames(names: readonly string[] | null | undefined): void { - if (names?.some((name) => name.includes("*")) === true) { - throw new LifecycleError( - "pi_mcp_tool_pattern_unsupported", - "Pi MCP tool filters require exact tool names and do not accept patterns", - ); - } -} - -function mcpToolExposure( - allowed: string[] | null | undefined, - blocked: string[] | undefined, -): Pick { - validateMcpToolNames(allowed); - validateMcpToolNames(blocked); - const toolExposure: Record = {}; - if (allowed !== undefined && allowed !== null) { - for (const name of allowed) { - toolExposure[name] = "direct"; - } - } - for (const name of blocked ?? []) { - toolExposure[name] = "hidden"; - } - return { - exposure: allowed === undefined || allowed === null ? "direct" : "hidden", - ...(Object.keys(toolExposure).length === 0 ? {} : { toolExposure }), - }; -} - -export function selectPiMcpServers( - config: AgentConfig, - configuredEnvironment: Record, - parentEnvironment: NodeJS.ProcessEnv, -): Record { - if (config.mcp?.extensions !== undefined) { - throw new LifecycleError("pi_mcp_extensions_unsupported", "Pi does not support Fabric MCP extensions"); - } - const selected = Object.create(null) as Record; - for (const [name, server] of Object.entries(config.mcp?.servers ?? {})) { - if (!MCP_SERVER_NAME.test(name) || server.extensions !== undefined) { - throw new LifecycleError("pi_mcp_invalid_server", "Pi MCP server configuration is unsupported or invalid"); - } - if (server.authentication !== undefined && server.authentication !== null) { - throw new LifecycleError( - "pi_mcp_authentication_unsupported", - "Pi MCP authentication is unsupported; configure a custom authorization header instead", - ); - } - const exposure = mcpToolExposure(server.allowed_tools, server.blocked_tools); - if (server.transport === "stdio") { - if (server.url.trim().length === 0 || Object.keys(server.custom_headers ?? {}).length > 0) { - throw new LifecycleError( - "pi_mcp_invalid_server", - "Pi stdio MCP servers require a command and do not accept HTTP headers", - ); - } - selected[name] = { - type: "stdio", - command: server.url, - ...(server.args === undefined ? {} : { args: server.args }), - ...(server.env === undefined ? {} : { env: server.env }), - ...exposure, - }; - continue; - } - if (server.transport === "streamable-http") { - if ((server.args?.length ?? 0) > 0 || Object.keys(server.env ?? {}).length > 0) { - throw new LifecycleError( - "pi_mcp_invalid_server", - "Pi streamable-HTTP MCP servers do not accept command arguments or environment variables", - ); - } - let endpoint: URL; - try { - endpoint = new URL(server.url); - } catch { - throw new LifecycleError( - "pi_mcp_invalid_server", - "Pi streamable-HTTP MCP servers require an HTTP or HTTPS URL", - ); - } - if ( - (endpoint.protocol !== "http:" && endpoint.protocol !== "https:") || - (endpoint.protocol === "http:" && !loopbackHostname(endpoint.hostname)) - ) { - throw new LifecycleError( - "pi_mcp_invalid_server", - "Pi streamable-HTTP MCP servers require HTTPS unless the endpoint is loopback", - ); - } - const headerNames = new Set(); - const headers = Object.fromEntries( - Object.entries(server.custom_headers ?? {}).map(([headerName, value]) => { - const normalizedName = headerName.toLowerCase(); - if (headerNames.has(normalizedName)) { - throw new LifecycleError("pi_mcp_invalid_header", "A configured Pi MCP HTTP header is invalid"); - } - headerNames.add(normalizedName); - const expanded = expandMcpHeader(value, configuredEnvironment, parentEnvironment); - validateMcpHeader(headerName, expanded); - return [headerName, expanded]; - }), - ); - selected[name] = { - type: "http", - url: server.url, - ...(Object.keys(headers).length === 0 ? {} : { headers }), - ...exposure, - }; - continue; - } - throw new LifecycleError( - "pi_mcp_transport_unsupported", - `Pi does not support MCP transport ${JSON.stringify(server.transport)}; supported transports: stdio, streamable-http`, - { - metadata: { - field: `mcp.servers.${name}.transport`, - transport: server.transport, - supported_transports: ["stdio", "streamable-http"], - }, - }, - ); - } - return selected; -} - type McpCredentials = NonNullable; function isolatedMcpCredentials(): McpCredentials { @@ -504,250 +196,6 @@ function mcpRegistrationExtension(servers: Record): Ext }; } -function selectModel(config: AgentConfig): AgentModelConfig { - const entries = Object.entries(config.models ?? {}); - if (entries.length === 0) { - throw new LifecycleError("pi_model_required", "The Pi adapter requires one configured model"); - } - const selected = config.models?.default ?? (entries.length === 1 ? entries[0]?.[1] : undefined); - if (selected === undefined) { - throw new LifecycleError( - "pi_model_ambiguous", - "Configure a default model role when the Pi adapter receives multiple models", - ); - } - return selected; -} - -/** - * Build the Pi catalog entry to register for the selected model, as an OVERLAY on `base` (the - * model's existing Pi catalog entry, or undefined when Pi doesn't know it). The rule is a thin - * pass-through: a field the config SUPPLIES (via the model `extensions` block, or `base_url` for - * the endpoint) is used; a field it OMITS falls back to `base`'s value, and if there is no base - * (an unknown gateway model) an optional field is left UNSET so Pi applies its own default. The - * adapter invents no defaults of its own. - * - * It does, however, require what Pi has no usable default for. For an unknown model that means a - * complete-enough definition: `api` (enforced at registration — Pi can't resolve the wire - * protocol otherwise), `base_url`, `context_window`/`max_tokens`, `input`, and `cost`. Supplied values - * are validated (`api` a {@link SUPPORTED_MODEL_APIS} value, token limits positive, cost - * well-formed) so a malformed override fails fast instead of reaching Pi. - */ -export function buildCatalogModel(model: AgentModelConfig, base: PiResolvedModel | undefined): PiCatalogModel { - const meta = (model.extensions ?? {}) as Record; - const fail = (reason: string): never => { - throw new LifecycleError("pi_model_extensions_invalid", reason, { metadata: { model: model.model } }); - }; - if (meta.api !== undefined && !SUPPORTED_MODEL_APIS.includes(meta.api as (typeof SUPPORTED_MODEL_APIS)[number])) { - throw new LifecycleError( - "pi_model_api_invalid", - `Unsupported model api '${String(meta.api)}'; model extensions.api must be one of: ${SUPPORTED_MODEL_APIS.join(", ")}`, - { metadata: { model: model.model } }, - ); - } - // Validate a SUPPLIED token limit (positive number); when absent, inherit base's value or leave - // it unset for Pi to default. Never fabricate a value. - const positive = (value: unknown, inherited: number | undefined, field: string): number | undefined => { - if (value === undefined) { - return inherited; - } - if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) { - return fail(`model extensions.${field} must be a positive number`); - } - return value; - }; - if (Array.isArray(meta.input) && meta.input.some((item) => item !== "text" && item !== "image")) { - fail("model extensions.input must contain only 'text' or 'image' values"); - } - const suppliedInput = Array.isArray(meta.input) - ? (meta.input.filter((item) => item === "text" || item === "image") as ("text" | "image")[]) - : undefined; - const api = typeof meta.api === "string" ? (meta.api as PiCatalogModel["api"]) : base?.api; - const baseUrl = model.base_url ?? base?.baseUrl; - const reasoning = meta.reasoning !== undefined ? meta.reasoning === true : base?.reasoning; - const input = suppliedInput !== undefined && suppliedInput.length > 0 ? suppliedInput : base?.input; - const cost = parseCost(meta.cost, fail) ?? base?.cost; - const contextWindow = positive(meta.context_window, base?.contextWindow, "context_window"); - const maxTokens = positive(model.max_tokens ?? meta.max_tokens, base?.maxTokens, "max_tokens"); - // An unknown model has no catalog entry to supply its endpoint, limits, input modalities, - // or cost rates. Require those fields before Pi uses them; `api` is enforced at registration. - if (base === undefined) { - const missing = [ - baseUrl === undefined ? "base_url" : undefined, - contextWindow === undefined ? "context_window" : undefined, - maxTokens === undefined ? "max_tokens" : undefined, - input === undefined ? "input" : undefined, - cost === undefined ? "cost" : undefined, - ].filter((field): field is string => field !== undefined); - if (missing.length > 0) { - fail( - `model '${model.model}' is not known to Pi, so a complete definition is required; ` + - `missing: ${missing.join(", ")} (set base_url and the required model extensions)`, - ); - } - } - // Include only resolved fields; the adapter adds no defaults for optional metadata. - const entry: Record = { id: model.model }; - if (typeof meta.name === "string" || base?.name !== undefined) { - entry.name = typeof meta.name === "string" ? meta.name : base?.name; - } - if (api !== undefined) entry.api = api; - if (baseUrl !== undefined) entry.baseUrl = baseUrl; - if (reasoning !== undefined) entry.reasoning = reasoning; - if (input !== undefined) entry.input = input; - if (cost !== undefined) entry.cost = cost; - if (contextWindow !== undefined) entry.contextWindow = contextWindow; - if (maxTokens !== undefined) entry.maxTokens = maxTokens; - return entry as unknown as PiCatalogModel; -} - -// Validate a supplied cost (all four numeric rates) and reject a partial object (e.g. `{}`), -// which Pi would turn into NaN costs. Returns undefined when no cost is configured, so the -// caller keeps the base/default cost instead. -function parseCost(value: unknown, fail: (reason: string) => never): PiCatalogModel["cost"] | undefined { - if (value === undefined) { - return undefined; - } - if (typeof value !== "object" || value === null) { - return fail("model extensions.cost must be an object with numeric input/output/cacheRead/cacheWrite rates"); - } - const record = value as Record; - const rates = ["input", "output", "cacheRead", "cacheWrite"] as const; - const parsed: Record = {}; - for (const rate of rates) { - const amount = record[rate]; - if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0) { - return fail(`model extensions.cost.${rate} must be a non-negative number`); - } - parsed[rate] = amount; - } - // SAFETY: every rate was just validated as a finite non-negative number above. - return parsed as unknown as PiCatalogModel["cost"]; -} - -function harnessSettings(config: AgentConfig): PiHarnessSettings { - const raw = config.harness?.settings; - const extensions = raw?.extensions; - if (extensions === undefined) { - return { extensions: [] }; - } - if (!Array.isArray(extensions)) { - throw new LifecycleError("pi_invalid_settings", "Pi extension settings do not match the adapter schema"); - } - const values: string[] = []; - for (const entry of extensions) { - if (typeof entry !== "string") { - throw new LifecycleError("pi_invalid_settings", "Pi extension settings do not match the adapter schema"); - } - values.push(entry); - } - return { extensions: values }; -} - -function containedBy(root: string, candidate: string): boolean { - const path = relative(root, candidate); - return path === "" || (!path.startsWith(`..${sep}`) && path !== ".." && !isAbsolute(path)); -} - -function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - -async function resolveToolModule(workspace: string, reference: string): Promise<{ path: string; exportName: string }> { - const match = /^(?[^#]+?)(?:#(?[A-Za-z_$][\w$]*))?$/.exec(reference); - const configuredPath = match?.groups?.path; - if (configuredPath === undefined || isAbsolute(configuredPath)) { - throw new LifecycleError( - "pi_tool_ref_invalid", - "Pi tool module references must use a workspace-relative path with an optional export fragment", - ); - } - let candidate: string; - try { - candidate = await realpath(resolve(workspace, configuredPath)); - } catch { - throw new LifecycleError("pi_tool_module_not_found", "A configured Pi tool module does not exist"); - } - if (!containedBy(workspace, candidate)) { - throw new LifecycleError("pi_tool_module_outside_workspace", "Pi tool modules must be contained by the workspace"); - } - if (!(await stat(candidate)).isFile() || !TOOL_MODULE_EXTENSIONS.has(extname(candidate))) { - throw new LifecycleError( - "pi_tool_module_invalid", - "Pi tool modules must be JavaScript or TypeScript files", - ); - } - return { path: candidate, exportName: match?.groups?.export ?? "default" }; -} - -function validateToolDefinition(name: string, value: unknown): ToolDefinition { - if ( - !isRecord(value) || - value.name !== name || - typeof value.label !== "string" || - value.label.length === 0 || - typeof value.description !== "string" || - value.description.length === 0 || - !isRecord(value.parameters) || - typeof value.execute !== "function" - ) { - throw new LifecycleError( - "pi_tool_factory_invalid", - "A Pi tool factory returned an invalid tool definition or a mismatched tool name", - { metadata: { tool: name } }, - ); - } - // SAFETY: the checks above verify every field of the ToolDefinition contract at runtime. - return value as unknown as ToolDefinition; -} - -export async function resolveCustomTools( - workspace: string, - definitions: Record, -): Promise { - const jiti = createJiti(import.meta.url, { interopDefault: false }); - const tools: ToolDefinition[] = []; - for (const [name, definition] of Object.entries(definitions)) { - if (PI_BUILTIN_TOOL_NAMES.has(name)) { - throw new LifecycleError("pi_tool_collision", "A Fabric tool definition collides with a Pi built-in tool", { - metadata: { tool: name }, - }); - } - if (definition.kind !== "module") { - throw new LifecycleError("pi_tool_kind_unsupported", "Pi supports only module tool definitions"); - } - const moduleReference = await resolveToolModule(workspace, definition.ref); - let loaded: unknown; - try { - loaded = await jiti.import(moduleReference.path); - } catch { - throw new LifecycleError("pi_tool_module_load_failed", "A configured Pi tool module could not be loaded", { - metadata: { tool: name }, - }); - } - const factory = isRecord(loaded) ? loaded[moduleReference.exportName] : undefined; - if (typeof factory !== "function") { - throw new LifecycleError("pi_tool_factory_missing", "A configured Pi tool module export is not a factory", { - metadata: { tool: name }, - }); - } - let tool: unknown; - try { - tool = await (factory as PiToolFactory)({ - name, - settings: definition.settings ?? {}, - workspace, - }); - } catch { - throw new LifecycleError("pi_tool_factory_failed", "A configured Pi tool factory failed", { - metadata: { tool: name }, - }); - } - tools.push(validateToolDefinition(name, tool)); - } - return tools; -} - function rejectToolCollisions(customTools: ToolDefinition[], configuredExtensionTools: string[]): void { const customNames = new Set(customTools.map((tool) => tool.name)); const seenExtensionNames = new Set(); @@ -784,67 +232,6 @@ function relayExtensionLoadErrors( }); } -async function resolveExtensionPaths(workspace: string, configured: string[]): Promise { - const resolved: string[] = []; - for (const entry of configured) { - if (isAbsolute(entry)) { - throw new LifecycleError("pi_extension_outside_workspace", "Pi extension paths must be workspace-relative"); - } - let candidate: string; - try { - candidate = await realpath(resolve(workspace, entry)); - } catch { - throw new LifecycleError("pi_extension_not_found", "A configured Pi extension path does not exist"); - } - if (!containedBy(workspace, candidate)) { - throw new LifecycleError("pi_extension_outside_workspace", "Pi extension path resolves outside the workspace"); - } - const info = await stat(candidate); - if (!info.isFile() || (!candidate.endsWith(".ts") && !candidate.endsWith(".js"))) { - throw new LifecycleError("pi_unsupported_extension", "Pi extensions must be .ts or .js files"); - } - resolved.push(candidate); - } - return resolved; -} - -async function resolveSkillPaths(baseDir: string, configured: string[]): Promise { - const resolved: string[] = []; - for (const entry of configured) { - let candidate: string; - try { - candidate = await realpath(resolve(baseDir, entry)); - } catch { - throw new LifecycleError("pi_skill_not_found", "A configured NeMo Fabric skill path does not exist"); - } - let info; - try { - info = await stat(candidate); - } catch { - throw new LifecycleError("pi_skill_not_found", "A configured NeMo Fabric skill path does not exist"); - } - if (!info.isDirectory()) { - throw new LifecycleError("pi_skill_invalid", "NeMo Fabric skill paths must be directories"); - } - try { - if (!(await stat(join(candidate, "SKILL.md"))).isFile()) { - throw new Error("not a file"); - } - } catch { - throw new LifecycleError( - "pi_skill_invalid", - "NeMo Fabric skill directories must contain a SKILL.md file", - ); - } - resolved.push(candidate); - } - return resolved; -} - -function credentialValue(input: AdapterStartInput, name: string): string | undefined { - return input.runtimeContext.environment.env?.[name] ?? process.env[name]; -} - function promptText(message: { content?: unknown }): string { if (!Array.isArray(message.content)) { return ""; @@ -875,20 +262,20 @@ class PiSdkSessionHandle implements PiSessionHandle { private readonly unsubscribeTurnCounter: () => void; private stopped = false; private cumulativeTurnCount = 0; - private readonly runtimeDir: string; private initialized = false; private requiredTools: readonly string[] = []; private readonly nativeSessionId: string; private readonly modelRuntime: PiModelRuntime; private readonly expectedModel: { id: string; provider: string }; private readonly connections: Map; + readonly configuration: PiNativeConfiguration; - constructor(session: AgentSession, state: { shutdownRequested: boolean }, runtimeDir: string, + constructor(session: AgentSession, state: { shutdownRequested: boolean }, modelRuntime: PiModelRuntime, expectedModel: { id: string; provider: string }, - connections: Map, relay?: PiRelayRuntime) { + connections: Map, configuration: PiNativeConfiguration, relay?: PiRelayRuntime) { this.session = session; + this.configuration = configuration; this.state = state; - this.runtimeDir = runtimeDir; this.relay = relay; this.modelRuntime = modelRuntime; this.expectedModel = expectedModel; @@ -991,30 +378,28 @@ class PiSdkSessionHandle implements PiSessionHandle { return; } this.stopped = true; + // The runtime's agent directory stays: it holds no secrets, and like other adapters' + // runtime directories it remains under the artifact root for inspection. let failure: unknown; try { - try { - await this.session.abort(); - } catch (error) { - failure = error; - } - try { - await this.session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" }); - } catch (error) { - failure ??= error; - } - try { - this.unsubscribeTurnCounter(); - } catch (error) { - failure ??= error; - } - try { - this.session.dispose(); - } catch (error) { - failure ??= error; - } - } finally { - await rm(this.runtimeDir, { recursive: true, force: true }); + await this.session.abort(); + } catch (error) { + failure = error; + } + try { + await this.session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" }); + } catch (error) { + failure ??= error; + } + try { + this.unsubscribeTurnCounter(); + } catch (error) { + failure ??= error; + } + try { + this.session.dispose(); + } catch (error) { + failure ??= error; } if (failure !== undefined) { throw failure; @@ -1030,113 +415,16 @@ export class PiSdkSessionFactory implements PiSessionFactory { } async create(input: AdapterStartInput): Promise { - const systemInstruction = input.config.instructions?.system; - if (systemInstruction?.mode === "append") { - throw new LifecycleError( - "unsupported_system_instruction_mode", - "Pi does not support instructions.system.mode='append'; supported modes: replace", - { - metadata: { - field: "instructions.system.mode", - mode: systemInstruction.mode, - supported_modes: ["replace"], - }, - }, - ); - } - const mcpServers = selectPiMcpServers( - input.config, - input.runtimeContext.environment.env ?? {}, - process.env, - ); - const pi = await loadPiSdk(); - let workspace: string; - try { - workspace = await realpath(resolve(input.runtimeContext.environment.workspace ?? input.baseDir)); - if (!(await stat(workspace)).isDirectory()) { - throw new Error("not a directory"); - } - } catch { - throw new LifecycleError("pi_workspace_invalid", "The Fabric runtime workspace must be a directory"); - } - const selected = selectModel(input.config); - const apiKeyEnv = selected.api_key_env; - if (apiKeyEnv === undefined || apiKeyEnv === null || apiKeyEnv.length === 0) { - throw new LifecycleError("pi_api_key_env_required", "The selected Pi model requires api_key_env"); - } - const apiKey = credentialValue(input, apiKeyEnv); - if (apiKey === undefined || apiKey.length === 0) { - throw new LifecycleError("pi_credential_missing", `Credential environment variable ${apiKeyEnv} is not set`); - } - - // Cache warming can finish outside the prompt and omit aborted refresh usage. - // Keep all adapter-owned model work inside the invocation ledger boundary. - const settings = pi.SettingsManager.inMemory({ cacheWarming: "off" }, { projectTrusted: false }); - const extensionPaths = await resolveExtensionPaths(workspace, harnessSettings(input.config).extensions); - const skillPaths = await resolveSkillPaths(input.baseDir, input.config.skills?.paths ?? []); - const customTools = await resolveCustomTools(workspace, input.config.tools?.definitions ?? {}); - const credentials = new pi.InMemoryCredentialStore(); - const modelRuntime = await pi.ModelRuntime.create({ - credentials, - modelsPath: null, - allowModelNetwork: false, - refreshOnCreate: false, - }); - await modelRuntime.setRuntimeApiKey(selected.provider, apiKey); - - // Register the selected model into Pi's catalog as an overlay on its existing entry (if any): - // supplied config fields override, omitted ones keep Pi's native value, and for an unknown - // (gateway) model the overlay base is empty so its required metadata must be explicit. This way - // selecting a known provider/model and changing nothing preserves all its native properties, - // while an explicit base_url / extensions field is still honored. A Fabric agent runs ONE - // model role per session (selectModel enforces default-or-sole), mirroring the other - // single-model adapters. The selected provider's credential was set above. - const existing = modelRuntime.getModel(selected.provider, selected.model); - const catalogEntry = buildCatalogModel(selected, existing); - try { - // Keep the endpoint at provider scope so Relay can redirect it without a - // per-model baseUrl taking precedence over the extension's provider override. - const { baseUrl, ...modelDefinition } = catalogEntry; - modelRuntime.registerProvider(selected.provider, { baseUrl, models: [modelDefinition] }); - } catch (error) { - const cause = error instanceof Error ? error.message : String(error); - // Pi throws here with a 'no "api" specified' message when it can't resolve the model's - // wire protocol (not a built-in and no extensions.api). Only THAT cause maps to the - // api-required remediation; any other registration failure keeps a generic code so the - // message isn't misleading. - if (/no "api" specified/i.test(cause)) { - throw new LifecycleError( - "pi_model_api_required", - `Set extensions.api for a gateway-served model (one of: ${SUPPORTED_MODEL_APIS.join(", ")}); the selected model has no api Pi can resolve`, - { metadata: { provider: selected.provider, model: selected.model, cause } }, - ); - } - throw new LifecycleError( - "pi_provider_registration_failed", - `Pi rejected the configuration for provider '${selected.provider}'`, - { metadata: { provider: selected.provider, cause } }, - ); - } - const catalogModel = modelRuntime.getModel(selected.provider, selected.model); - if (catalogModel === undefined) { - throw new LifecycleError("pi_model_unknown", "The selected provider and model are not present in Pi's catalog"); - } - // base_url was already applied during registration; withCustomBaseUrl only adds the - // OpenAI-compatible-proxy compat shim here (never re-overriding the resolved baseUrl). - const model = withCustomBaseUrl(catalogModel, selected.base_url, false); - const compactionReserveTokens = modelAwareCompactionReserveTokens( - settings.getCompactionReserveTokens(), - model.maxTokens ?? 0, - model.contextWindow ?? 0, - ); - settings.applyOverrides({ - compaction: { - reserveTokens: compactionReserveTokens, - }, - }); + if (!sdkEnabled(input.config)) { + // A runtime without the SDK runs only native interfaces (see terminal.ts). + throw new LifecycleError("pi_sdk_disabled", "Embedded Pi SDK execution is disabled"); + } + const { pi, configuration, modelRuntime, model, extensionPaths, skillPaths, customTools, mcpServers } = + await preparePiConfiguration(input); + const { workspace, agentDir } = configuration; + const settings = pi.SettingsManager.create(workspace, agentDir, { projectTrusted: false }); let relay: PiRelayRuntime | undefined; let handle: PiSdkSessionHandle | undefined; - let runtimeDir: string | undefined; try { relay = await this.relayFactory.start(input, { api: model.api, @@ -1145,8 +433,6 @@ export class PiSdkSessionFactory implements PiSessionFactory { if (relay !== undefined && !extensionPaths.includes(relay.extensionPath)) { extensionPaths.push(relay.extensionPath); } - runtimeDir = await mkdtemp(join(tmpdir(), "nemo-fabric-pi-")); - const agentDir = runtimeDir; const mcpConnections = new Map(Object.keys(mcpServers).map((name) => [name, mcpReadiness()])); const extensionFactories = Object.keys(mcpServers).length === 0 ? [] @@ -1175,8 +461,8 @@ export class PiSdkSessionFactory implements PiSessionFactory { noSkills: true, noPromptTemplates: true, noThemes: true, + // The system prompt is /SYSTEM.md, which writeAgentDirectory wrote when one is configured. noContextFiles: true, - systemPrompt: systemInstruction?.content, }); await resourceLoader.reload(); const extensionResult = resourceLoader.getExtensions(); @@ -1233,14 +519,18 @@ export class PiSdkSessionFactory implements PiSessionFactory { model, modelRuntime, resourceLoader, - sessionManager: pi.SessionManager.inMemory(workspace), + // With runtime.keep_state the conversation is kept beside the terminal UI's, so a + // later runtime's terminal UI can resume it; otherwise it lives only in memory. + sessionManager: configuration.keepState + ? pi.SessionManager.create(workspace, await privateDirectory(configuration.sessionDir)) + : pi.SessionManager.inMemory(workspace), settingsManager: settings, customTools, tools: enabled === null ? undefined : enabled, excludeTools: blocked, }); - handle = new PiSdkSessionHandle(session, state, runtimeDir, modelRuntime, - { id: model.id, provider: model.provider }, mcpConnections, relay); + handle = new PiSdkSessionHandle(session, state, modelRuntime, + { id: model.id, provider: model.provider }, mcpConnections, configuration, relay); const blockedNames = new Set(blocked); const availableNames = new Set(session.getAllTools().map((tool) => tool.name)); const missing = (enabled ?? []).filter((name) => !blockedNames.has(name) && !availableNames.has(name)); @@ -1284,9 +574,6 @@ export class PiSdkSessionFactory implements PiSessionFactory { await relay?.stop().catch(() => { process.stderr.write("NeMo Relay cleanup failed after Pi adapter startup error\n"); }); - if (handle === undefined && runtimeDir !== undefined) { - await rm(runtimeDir, { recursive: true, force: true }); - } throw error; } } diff --git a/adapters/typescript/pi/src/relay-config.ts b/adapters/typescript/pi/src/relay-config.ts index dd8cfbff1..fd4376e24 100644 --- a/adapters/typescript/pi/src/relay-config.ts +++ b/adapters/typescript/pi/src/relay-config.ts @@ -69,6 +69,20 @@ function components(pluginConfig: RelayPluginConfig): unknown[] { return value; } +/** The names of the enabled ATOF stream sinks in a Relay plugin configuration. */ +export function atofStreamSinkNames(pluginConfig: RelayPluginConfig): string[] { + const names: string[] = []; + for (const component of components(pluginConfig)) { + if (!isRecord(component) || component.kind !== "observability" || component.enabled === false) continue; + const atof = isRecord(component.config) ? component.config.atof : undefined; + if (!isRecord(atof) || atof.enabled !== true || !Array.isArray(atof.sinks)) continue; + for (const sink of atof.sinks) { + if (isRecord(sink) && sink.type === "stream" && typeof sink.name === "string") names.push(sink.name); + } + } + return names; +} + function relayModelName(input: AdapterStartInput): string { const models = input.config.models ?? {}; const entries = Object.values(models); diff --git a/adapters/typescript/pi/src/relay.ts b/adapters/typescript/pi/src/relay.ts index 45d459507..88d6e099c 100644 --- a/adapters/typescript/pi/src/relay.ts +++ b/adapters/typescript/pi/src/relay.ts @@ -121,10 +121,22 @@ function reserveRelayEnvironment(): () => void { }; } +/** The variables the Relay Pi extension reads: the gateway, its command, and the model's upstream. */ +function relayExtensionEnvironment(gatewayUrl: string, executable: string, model: PiRelayModel): Record { + const environment: Record = { + NEMO_RELAY_PI_COMMAND: executable, + NEMO_RELAY_PI_GATEWAY_URL: gatewayUrl, + }; + if (model.api === "openai-completions" || model.api === "openai-responses") { + environment.NEMO_RELAY_PI_OPENAI_UPSTREAM = model.baseUrl; + } else if (model.api === "anthropic-messages") { + environment.NEMO_RELAY_PI_ANTHROPIC_UPSTREAM = model.baseUrl; + } + return environment; +} + function setRelayEnvironment( - gatewayUrl: string, - executable: string, - model: PiRelayModel, + environment: Record, releaseReservation: () => void, ): () => void { const previous = new Map(); @@ -132,13 +144,7 @@ function setRelayEnvironment( previous.set(name, process.env[name]); delete process.env[name]; } - process.env.NEMO_RELAY_PI_COMMAND = executable; - process.env.NEMO_RELAY_PI_GATEWAY_URL = gatewayUrl; - if (model.api === "openai-completions" || model.api === "openai-responses") { - process.env.NEMO_RELAY_PI_OPENAI_UPSTREAM = model.baseUrl; - } else if (model.api === "anthropic-messages") { - process.env.NEMO_RELAY_PI_ANTHROPIC_UPSTREAM = model.baseUrl; - } + Object.assign(process.env, environment); let restored = false; return () => { if (restored) { @@ -161,6 +167,8 @@ function setRelayEnvironment( export class PiRelayRuntime { readonly extensionPath: string; + /** What the Relay Pi extension needs in another Pi process, such as the terminal TUI; no secrets. */ + readonly extensionEnvironment: Readonly>; readonly pluginConfig: RelayPluginConfig; readonly atifMatchers: RelayAtifMatcher[]; private readonly child: ChildProcess; @@ -172,6 +180,7 @@ export class PiRelayRuntime { constructor(options: { extensionPath: string; + extensionEnvironment?: Record; pluginConfig: RelayPluginConfig; atifMatchers: RelayAtifMatcher[]; child: ChildProcess; @@ -181,6 +190,7 @@ export class PiRelayRuntime { stopGateway?: typeof stopRelayGateway; }) { this.extensionPath = options.extensionPath; + this.extensionEnvironment = { ...(options.extensionEnvironment ?? {}) }; this.pluginConfig = options.pluginConfig; this.atifMatchers = options.atifMatchers; this.child = options.child; @@ -323,9 +333,11 @@ export class PiRelayFactory implements PiRelayControllerFactory { metadata: relayErrorMetadata(error, { gateway_log_path: launch.logPath }), }); } - restoreEnvironment = setRelayEnvironment(launch.url, executable, model, releaseEnvironment); + const extensionEnvironment = relayExtensionEnvironment(launch.url, executable, model); + restoreEnvironment = setRelayEnvironment(extensionEnvironment, releaseEnvironment); const runtime = new PiRelayRuntime({ extensionPath, + extensionEnvironment, pluginConfig, atifMatchers, child, diff --git a/adapters/typescript/pi/src/runtime.ts b/adapters/typescript/pi/src/runtime.ts index e16a3665d..11cc61be4 100644 --- a/adapters/typescript/pi/src/runtime.ts +++ b/adapters/typescript/pi/src/runtime.ts @@ -8,8 +8,10 @@ import type { AdapterCheckResult, CheckLevel, AgentRunRequest, AgentRunResult, AgentUsage, JsonObject, RuntimeContext } from "nemo-fabric-adapter-contract"; import { LifecycleError, unobservedHealth, type AdapterRuntime, type AdapterStartInput } from "nemo-fabric-adapters-common"; +import type { PiNativeConfiguration } from "./native-configuration.js"; import { collectRelayArtifacts, type RelayArtifact } from "./relay-config.js"; import type { PiRelayRuntime } from "./relay.js"; +import { executionPaths } from "./settings.js"; export type PiStopReason = "stop" | "length" | "toolUse" | "error" | "aborted" | string; @@ -27,6 +29,8 @@ export interface PiPromptOutcome { export interface PiSessionHandle { readonly relay?: PiRelayRuntime; readonly turnCount?: number; + /** What the session resolved from FabricConfig, for native interfaces that share it. */ + readonly configuration?: PiNativeConfiguration; prompt(text: string): Promise; stop(): Promise; check(level: CheckLevel): Promise; @@ -78,6 +82,7 @@ export class PiAdapterRuntime implements AdapterRuntime { private unusable = false; private stopping = false; private generation = 0; + private sdk = true; constructor(factory: PiSessionFactory) { this.factory = factory; @@ -87,7 +92,10 @@ export class PiAdapterRuntime implements AdapterRuntime { if (this.session !== undefined) { throw new LifecycleError("pi_already_started", "Pi adapter runtime is already started"); } + // Refuses malformed settings and a runtime with no execution path before anything starts. + const { sdk } = executionPaths(input.config); this.session = await this.factory.create(input); + this.sdk = sdk; this.generation += 1; this.stopping = false; this.turnCount = 0; @@ -101,6 +109,15 @@ export class PiAdapterRuntime implements AdapterRuntime { if (this.unusable) { throw new LifecycleError("pi_runtime_unusable", "Pi adapter runtime cannot accept another invocation"); } + if (!this.sdk) { + // Native-only runtime: management and health stay available; invocation fails explicitly. + return withRelayOutput( + failed("pi_sdk_disabled", "Embedded Pi SDK execution is disabled; use the terminal interface"), + undefined, + false, + 0, + ); + } if (typeof request.input !== "string") { const observedTurnCount = this.session.turnCount; if (observedTurnCount !== undefined) { diff --git a/adapters/typescript/pi/src/settings.ts b/adapters/typescript/pi/src/settings.ts new file mode 100644 index 000000000..517648d80 --- /dev/null +++ b/adapters/typescript/pi/src/settings.ts @@ -0,0 +1,44 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// The runtime's execution paths, read from harness.settings: the embedded SDK +// session (sdk.enabled, on by default) and Pi's terminal TUI +// (interfaces.terminal). A runtime needs at least one of them. + +import type { AgentConfig } from "nemo-fabric-adapter-contract"; +import { LifecycleError } from "nemo-fabric-adapters-common"; + +function invalid(): LifecycleError { + return new LifecycleError("pi_invalid_settings", "Pi settings do not match the adapter schema"); +} + +/** The `enabled` switch of a settings object that is on when present unless `enabled` is false. */ +function switchedOn(section: unknown, whenAbsent: boolean): boolean { + if (section === undefined || section === null) return whenAbsent; + if (typeof section !== "object" || Array.isArray(section)) throw invalid(); + const enabled = (section as Record).enabled; + if (enabled !== undefined && typeof enabled !== "boolean") throw invalid(); + return enabled !== false; +} + +/** Whether the configuration initializes the embedded SDK session (`sdk.enabled`, default true). */ +export function sdkEnabled(config: AgentConfig): boolean { + return switchedOn(config.harness?.settings?.sdk, true); +} + +/** Whether the configuration enables Pi's terminal TUI interface. */ +export function terminalEnabled(config: AgentConfig): boolean { + const interfaces = config.harness?.settings?.interfaces; + if (interfaces === undefined || interfaces === null) return false; + if (typeof interfaces !== "object" || Array.isArray(interfaces)) throw invalid(); + return switchedOn((interfaces as Record).terminal, false); +} + +/** The enabled execution paths; refuses a runtime with neither. */ +export function executionPaths(config: AgentConfig): { sdk: boolean; terminal: boolean } { + const paths = { sdk: sdkEnabled(config), terminal: terminalEnabled(config) }; + if (!paths.sdk && !paths.terminal) { + throw new LifecycleError("pi_no_execution_path", "Enable the Pi SDK or the terminal interface"); + } + return paths; +} diff --git a/adapters/typescript/pi/src/terminal.ts b/adapters/typescript/pi/src/terminal.ts new file mode 100644 index 000000000..cb4cd2810 --- /dev/null +++ b/adapters/typescript/pi/src/terminal.ts @@ -0,0 +1,551 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Pi's terminal UI as a native interface of a Fabric runtime. Every runtime +// writes Pi's own files to its agent directory (agent-directory.ts), so the +// terminal UI is the stock `pi` CLI pointed at them: PI_CODING_AGENT_DIR plus +// the flags for what files can't carry. With harness.settings.interfaces.terminal, +// withTerminalInterface writes that launcher once the runtime is ready, whether +// or not it runs the embedded SDK session. +// A person starts the terminal UI with `openshell sandbox exec --tty`, outside +// the adapter's process tree, so the adapter can't own it as a child; a +// generated extension registers each one and closes it when the runtime stops. +// The launcher holds paths and switches, never secrets: models.json names the +// key's environment variable, and Pi reads it when the terminal UI starts. +// With runtime.keep_state, every runtime of the agent uses the same directory, +// so terminal conversations in pi-sessions outlive the runtime, and a start +// first retires the terminal interface a runtime that ended without stop left. + +import { access, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +import type { AdapterCheckResult, CheckLevel } from "nemo-fabric-adapter-contract"; +import { LifecycleError, type AdapterStartInput } from "nemo-fabric-adapters-common"; + +import { keepsState, runtimeDirectory } from "./agent-directory.js"; +import type { PiNativeConfiguration, PiNativeCustomTool } from "./native-configuration.js"; +import { PiNativeOnlySessionFactory } from "./native-only.js"; +import type { PiPromptOutcome, PiSessionFactory, PiSessionHandle } from "./runtime.js"; +import { sdkEnabled, terminalEnabled } from "./settings.js"; + +export { terminalEnabled }; + +/** How long `stop` waits after SIGTERM before it sends SIGKILL to open terminal UIs, as the Hermes adapter does. */ +const TERMINAL_STOP_GRACE_MS = 5_000; +/** A registration whose heartbeat is older than this belongs to a terminal UI that no longer runs. */ +const TERMINAL_HEARTBEAT_STALE_MS = 3_000; +const TERMINAL_HEARTBEAT_MS = 500; +/** How long a terminal UI waits for its orderly shutdown before it sends itself SIGTERM. */ +const TERMINAL_SELF_TERMINATE_MS = 2_000; +const TOOL_NAME = /^[A-Za-z0-9_.:-]+$/u; + +/** The bundled `pi` CLI of the Pi package the adapter's SDK session uses, so both run one version. */ +export async function resolvePiCli(): Promise { + let entry: string; + try { + entry = fileURLToPath(import.meta.resolve("@earendil-works/pi-coding-agent")); + } catch { + throw new LifecycleError("pi_harness_unavailable", "The Pi coding agent package is not installed"); + } + for (let directory = dirname(entry); directory !== dirname(directory); directory = dirname(directory)) { + let manifest: { name?: unknown; bin?: unknown }; + try { + manifest = JSON.parse(await readFile(join(directory, "package.json"), "utf8")) as typeof manifest; + } catch { + continue; + } + if (manifest.name !== "@earendil-works/pi-coding-agent") continue; + const bin = typeof manifest.bin === "object" && manifest.bin !== null + ? (manifest.bin as Record).pi + : undefined; + if (typeof bin !== "string") break; + const cli = join(directory, bin); + try { + await access(cli); + return cli; + } catch { + break; + } + } + throw new LifecycleError("pi_harness_incompatible", "The installed Pi package does not provide its `pi` CLI"); +} + +function shellQuote(value: string): string { + return `'${value.replaceAll("'", "'\\''")}'`; +} + +function toolList(names: readonly string[], field: string): string { + for (const name of names) { + if (!TOOL_NAME.test(name)) { + throw new LifecycleError("pi_invalid_settings", `Pi's terminal UI can't pass ${field} tool name ${JSON.stringify(name)}`); + } + } + return names.join(","); +} + +/** + * The `pi` arguments for what the agent directory's files can't carry: the embedded + * session's isolation, its extension and skill paths, its tool policy, and the + * terminal UI's own extensions. + */ +export function terminalArguments(plan: PiNativeConfiguration, terminalExtensions: readonly string[]): string[] { + const args = [ + // The embedded session doesn't trust the project: no .pi/ settings, resources or MCP servers. + "--no-approve", + // The embedded session loads no ambient extensions, skills, prompts, themes or context files. + "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-themes", "--no-context-files", + ]; + for (const path of terminalExtensions) args.push("--extension", path); + // --no-extensions also turns off built-in MCP, which reads the agent directory's mcp.json. + if (Object.keys(plan.mcpServers).length > 0) args.push("--extension", "builtin:mcp"); + for (const path of plan.extensionPaths) args.push("--extension", path); + for (const path of plan.skillPaths) args.push("--skill", path); + if (plan.toolsEnabled !== undefined && plan.toolsEnabled !== null) { + if (plan.toolsEnabled.length === 0) args.push("--no-tools"); + else args.push("--tools", toolList(plan.toolsEnabled, "enabled")); + } + if (plan.toolsBlocked.length > 0) args.push("--exclude-tools", toolList(plan.toolsBlocked, "blocked")); + return args; +} + +export function launcherScript(options: { + node: string; + cli: string; + agentDir: string; + sessionDir: string; + workspace: string; + descriptor: string; + args: string[]; + environment?: Readonly>; +}): string { + const exports = Object.entries({ + PI_CODING_AGENT_DIR: options.agentDir, + PI_CODING_AGENT_SESSION_DIR: options.sessionDir, + // The embedded session makes no model-catalog, version or telemetry requests. + PI_OFFLINE: "1", + PI_SKIP_VERSION_CHECK: "1", + PI_TELEMETRY: "0", + ...options.environment, + }).map(([name, value]) => `export ${name}=${shellQuote(value)}`); + return [ + "#!/bin/sh", + "# Opens Pi's terminal UI in a separate session with this NeMo Fabric runtime's", + "# configuration. It holds paths and switches, never secrets: set the model key's", + "# environment variable in the environment that runs this launcher.", + `if [ ! -e ${shellQuote(options.descriptor)} ]; then`, + " echo 'This NeMo Fabric runtime is not running.' >&2", + " exit 1", + "fi", + ...exports, + `cd ${shellQuote(options.workspace)} || exit 1`, + `exec ${[options.node, options.cli, ...options.args].map(shellQuote).join(" ")} "$@"`, + "", + ].join("\n"); +} + +/** + * A Pi extension that ties each terminal UI to the runtime: it registers the + * process while it runs, refreshes the registration as a heartbeat, and shuts + * Pi down in order when the runtime's tui.json attachment file disappears or + * names another runtime of the agent. + */ +export function supervisorExtension(descriptor: string, clients: string, runtimeId: string): string { + return `// Generated by the NeMo Fabric Pi adapter. Ties this terminal UI to its runtime. +import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +const DESCRIPTOR = ${JSON.stringify(descriptor)}; +const CLIENTS = ${JSON.stringify(clients)}; +const RUNTIME_ID = ${JSON.stringify(runtimeId)}; + +function published() { + try { + return JSON.parse(readFileSync(DESCRIPTOR, "utf8")).runtime_id === RUNTIME_ID; + } catch { + return false; + } +} + +export default function (pi) { + const entry = join(CLIENTS, String(process.pid)); + let context; + let stopping = false; + const beat = () => { + if (stopping) return; + if (!published()) { + stopping = true; + clearInterval(timer); + context?.ui?.notify?.("The NeMo Fabric runtime stopped; closing Pi.", "warning"); + // The terminal UI acts on shutdown() at once; other modes defer it until a + // command finishes, so fall back to SIGTERM, which Pi also handles in order. + setTimeout(() => process.kill(process.pid, "SIGTERM"), ${TERMINAL_SELF_TERMINATE_MS}); + context?.shutdown(); + return; + } + mkdirSync(CLIENTS, { recursive: true, mode: 0o700 }); + writeFileSync(entry, "", { mode: 0o600 }); + }; + const timer = setInterval(beat, ${TERMINAL_HEARTBEAT_MS}); + timer.unref?.(); + process.once("exit", () => rmSync(entry, { force: true })); + pi.on("session_start", (_event, ctx) => { + context = ctx; + beat(); + }); +} +`; +} + +/** A module that registers the runtime's Fabric module tools in the terminal UI. */ +export function toolBridgeExtension(workspace: string, tools: readonly PiNativeCustomTool[]): string { + const imports = tools.map((tool, index) => `import * as tool${index} from ${JSON.stringify(tool.path)};`); + const registrations = tools.map((tool, index) => + ` pi.registerTool(await tool${index}[${JSON.stringify(tool.exportName)}](` + + `{ name: ${JSON.stringify(tool.name)}, settings: ${JSON.stringify(tool.settings)}, workspace: WORKSPACE }));`); + return [ + "// Generated by the NeMo Fabric Pi adapter. Registers the runtime's tools.definitions.", + ...imports, + "", + `const WORKSPACE = ${JSON.stringify(workspace)};`, + "", + "export default async function (pi) {", + ...registrations, + "}", + "", + ].join("\n"); +} + +async function writePrivate(path: string, contents: string, mode = 0o600): Promise { + await writeFile(path, contents, { mode }); +} + +/** + * The attachment file, `interfaces/tui.json`: owner-only, published once the runtime + * is ready, removed first at stop. It shares `version`, `mode`, and `workspace` with the + * Hermes adapter's descriptor. Pi's terminal UI has no backend to attach to, so `mode` is + * `launcher`, and the launcher and Pi's directories take the place of a port and token. + */ +export interface PiTuiDescriptor { + version: 1; + mode: "launcher"; + launcher: "terminal"; + /** The runtime that published the attachment file; with runtime.keep_state, runtimes of the agent share its path. */ + runtime_id: string; + workspace: string; + agent_dir: string; + session_dir: string; +} + +/** What the launcher needs to load the runtime's Relay Pi extension. */ +export interface PiTerminalRelay { + readonly extensionPath: string; + readonly extensionEnvironment: Readonly>; +} + +/** The terminal TUI interface of one runtime. */ +export class PiTerminal { + readonly launcher: string; + readonly descriptorPath: string; + private readonly descriptor: PiTuiDescriptor; + private readonly clients: string; + private withdrawn = false; + + private constructor(launcher: string, descriptorPath: string, descriptor: PiTuiDescriptor, clients: string) { + this.launcher = launcher; + this.descriptorPath = descriptorPath; + this.descriptor = descriptor; + this.clients = clients; + } + + /** + * Write the launcher and the terminal UI's own extensions beside the runtime's agent + * directory, which the session already wrote; the launcher refuses to run until {@link publish}. + */ + static async prepare(plan: PiNativeConfiguration, directory: string, runtimeId: string, node: string, + cli: string, relay?: PiTerminalRelay): Promise { + const sessionDir = plan.sessionDir; + const interfaces = join(directory, "interfaces"); + const descriptorPath = join(interfaces, "tui.json"); + const clients = join(interfaces, "tui.clients"); + for (const path of [sessionDir, interfaces]) { + await mkdir(path, { recursive: true, mode: 0o700 }); + } + // Only the terminal UI loads these, so they stay out of the shared agent directory. + const extensions = [join(interfaces, "fabric-terminal.ts")]; + await writePrivate(extensions[0]!, supervisorExtension(descriptorPath, clients, runtimeId)); + if (plan.customTools.length > 0) { + extensions.push(join(interfaces, "fabric-tools.ts")); + await writePrivate(extensions.at(-1)!, toolBridgeExtension(plan.workspace, plan.customTools)); + } + // With Relay, terminal turns go through the runtime's gateway as their own Relay sessions. + if (relay !== undefined && !plan.extensionPaths.includes(relay.extensionPath)) { + extensions.push(relay.extensionPath); + } + const launcher = join(interfaces, "terminal"); + await writePrivate(launcher, launcherScript({ + node, + cli, + agentDir: plan.agentDir, + sessionDir, + workspace: plan.workspace, + descriptor: descriptorPath, + args: terminalArguments(plan, extensions), + environment: relay?.extensionEnvironment, + }), 0o700); + const descriptor: PiTuiDescriptor = { + version: 1, + mode: "launcher", + launcher: "terminal", + runtime_id: runtimeId, + workspace: plan.workspace, + agent_dir: plan.agentDir, + session_dir: sessionDir, + }; + return new PiTerminal(launcher, descriptorPath, descriptor, clients); + } + + /** Whether a person can open the terminal TUI now: the launcher and the published descriptor exist. */ + async available(): Promise { + if (this.withdrawn) return false; + try { + await Promise.all([access(this.launcher), access(this.descriptorPath)]); + return true; + } catch { + return false; + } + } + + /** Let the launcher run: publish the descriptor once the runtime is ready. */ + async publish(): Promise { + // Terminal UIs read it while they run, so it appears whole. + const staging = `${this.descriptorPath}.${process.pid}.tmp`; + await writePrivate(staging, `${JSON.stringify(this.descriptor)}\n`); + await rename(staging, this.descriptorPath); + } + + /** + * Close the interface before the runtime stops, as the Hermes adapter stops its + * interfaces: remove the descriptor so the launcher refuses new terminal UIs, + * send SIGTERM to each open terminal UI's process group, and send SIGKILL to + * those still running after the grace period. + */ + async withdraw(): Promise { + if (this.withdrawn) return; + await rm(this.descriptorPath, { force: true }); + this.withdrawn = true; + await closeTerminals(this.clients); + } +} + +/** + * Close the registered terminal UIs as the Hermes adapter stops its interfaces: + * send SIGTERM to each one's process group, send SIGKILL to the groups still + * running after the grace period, and remove their registrations. + */ +async function closeTerminals(clients: string): Promise { + const terminals = await liveTerminals(clients); + if (terminals.length > 0) { + signal(terminals, "SIGTERM"); + const deadline = Date.now() + TERMINAL_STOP_GRACE_MS; + while (Date.now() < deadline && terminals.some(alive)) { + await new Promise((resolve) => setTimeout(resolve, 100)); + } + // The group too: processes the terminal UI's tools started can outlive it. + signal(terminals, "SIGKILL"); + } + await rm(clients, { recursive: true, force: true }); +} + +/** Registered terminal UIs whose heartbeat is current; stale registrations are removed unsignalled. */ +async function liveTerminals(clients: string): Promise { + let entries: string[]; + try { + entries = await readdir(clients); + } catch { + return []; + } + const live: number[] = []; + for (const name of entries) { + const path = join(clients, name); + const pid = Number(name); + try { + const fresh = Date.now() - (await stat(path)).mtimeMs < TERMINAL_HEARTBEAT_STALE_MS; + if (Number.isSafeInteger(pid) && pid > 1 && fresh && alive(pid)) { + live.push(pid); + continue; + } + } catch { + // Removed while reading: that terminal UI exited. + } + await rm(path, { force: true }); + } + return live; +} + +/** + * Retire the terminal interface that a runtime which ended without stop left in a kept + * state folder, as the Hermes adapter removes its stale interface files: remove its + * attachment file so its launcher refuses to run, close its terminal UIs so they stop + * writing to the folder before this runtime uses it, and remove its files. + */ +export async function retireStaleTerminal(directory: string): Promise { + const interfaces = join(directory, "interfaces"); + try { + await rm(join(interfaces, "tui.json"), { force: true }); + await closeTerminals(join(interfaces, "tui.clients")); + for (const name of ["terminal", "fabric-terminal.ts", "fabric-tools.ts"]) { + await rm(join(interfaces, name), { force: true }); + } + } catch (error) { + throw new LifecycleError("pi_interface_cleanup_failed", "Pi's stale terminal interface files could not be removed", { + metadata: { cause: error instanceof Error ? error.message : String(error) }, + }); + } +} + +function alive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch (error) { + return (error as NodeJS.ErrnoException).code === "EPERM"; + } +} + +/** + * Signal each terminal UI's process group, or only the process when that fails: + * OpenShell denies group signals (EPERM), and a terminal UI that doesn't lead its + * own group has none under its PID (ESRCH). + */ +function signal(pids: readonly number[], name: NodeJS.Signals): void { + for (const pid of pids) { + // Once the terminal UI has exited, its PID may belong to another process. + const fallback = alive(pid); + try { + process.kill(-pid, name); + } catch { + if (!fallback) continue; + try { + process.kill(pid, name); + } catch { + // It has exited. + } + } + } +} + +/** Withdraws the terminal interface before the embedded session stops. */ +export class PiTerminalSessionHandle implements PiSessionHandle { + private readonly inner: PiSessionHandle; + private readonly terminal: PiTerminal; + + constructor(inner: PiSessionHandle, terminal: PiTerminal) { + this.inner = inner; + this.terminal = terminal; + } + + get relay() { + return this.inner.relay; + } + + get turnCount() { + return this.inner.turnCount; + } + + get configuration() { + return this.inner.configuration; + } + + prompt(text: string): Promise { + return this.inner.prompt(text); + } + + async check(level: CheckLevel): Promise { + // As for Hermes's native interfaces, the interface must still be offered. Open + // terminal TUIs are separate clients and don't change the outcome, but their turns + // aren't observed, so a passing result reports activity as unknown. + if (level !== "live" && !(await this.terminal.available())) { + return { + outcome: "failed", + reason_code: "endpoint_unavailable", + activity: "unknown", + source: level === "active" ? "fabric.adapter.interface" : "fabric.adapter.readiness", + observed_at: new Date().toISOString(), + }; + } + const result = await this.inner.check(level); + return result.outcome === "passed" ? { ...result, activity: "unknown" } : result; + } + + async stop(): Promise { + let failure: unknown; + try { + await this.terminal.withdraw(); + } catch (error) { + failure = error; + } + await this.inner.stop(); + if (failure !== undefined) throw failure; + } +} + +/** + * Add Pi's terminal interface to a runtime, as the runtime composes other native + * processes beside the SDK session (Hermes's InterfaceChildren, Pi's Relay + * gateway). Without interfaces.terminal, the SDK factory starts the runtime. + * With it, the SDK factory starts the runtime, or the native-only factory does + * when sdk.enabled is false; this then writes the launcher and descriptor from + * the runtime's configuration, and withdraws them before the runtime stops. + */ +export function withTerminalInterface( + sdk: PiSessionFactory, + nativeOnly: PiSessionFactory = new PiNativeOnlySessionFactory(), +): PiSessionFactory { + return new PiTerminalInterface(sdk, nativeOnly); +} + +class PiTerminalInterface implements PiSessionFactory { + private readonly sdk: PiSessionFactory; + private readonly nativeOnly: PiSessionFactory; + + constructor(sdk: PiSessionFactory, nativeOnly: PiSessionFactory) { + this.sdk = sdk; + this.nativeOnly = nativeOnly; + } + + async create(input: AdapterStartInput): Promise { + // Malformed settings fail here, before the session starts. + const terminal = terminalEnabled(input.config); + // An earlier runtime of the agent may have ended without stop, with or without this interface. + if (keepsState(input)) await retireStaleTerminal(runtimeDirectory(input)); + if (!terminal) { + return this.sdk.create(input); + } + const handle = await (sdkEnabled(input.config) ? this.sdk : this.nativeOnly).create(input); + let interfaceHandle: PiTerminal | undefined; + try { + if (handle.configuration === undefined) { + throw new LifecycleError( + "pi_terminal_unavailable", + "The Pi session did not report the configuration its terminal UI needs", + ); + } + interfaceHandle = await PiTerminal.prepare(handle.configuration, runtimeDirectory(input), + input.runtimeContext.runtime_id, process.execPath, await resolvePiCli(), handle.relay); + await interfaceHandle.publish(); + return new PiTerminalSessionHandle(handle, interfaceHandle); + } catch (error) { + await interfaceHandle?.withdraw().catch(() => { + process.stderr.write("Pi terminal interface cleanup failed after adapter startup error\n"); + }); + await handle.stop().catch(() => { + process.stderr.write("Pi session cleanup failed after adapter startup error\n"); + }); + await handle.relay?.stop().catch(() => { + process.stderr.write("NeMo Relay cleanup failed after adapter startup error\n"); + }); + throw error; + } + } +} diff --git a/adapters/typescript/pi/test/pi-sdk.test.mjs b/adapters/typescript/pi/test/pi-sdk.test.mjs index e74bef829..8c6ba8f6b 100644 --- a/adapters/typescript/pi/test/pi-sdk.test.mjs +++ b/adapters/typescript/pi/test/pi-sdk.test.mjs @@ -11,11 +11,11 @@ import { createServer } from "node:http"; import { buildCatalogModel, modelAwareCompactionReserveTokens, - PiSdkSessionFactory, resolveCustomTools, selectPiMcpServers, withCustomBaseUrl, -} from "../dist/pi-sdk.js"; +} from "../dist/native-configuration.js"; +import { PiSdkSessionFactory } from "../dist/pi-sdk.js"; import { PiAdapterRuntime } from "../dist/runtime.js"; const [major, minor] = process.versions.node.split(".").map(Number); diff --git a/adapters/typescript/pi/test/relay-smoke.test.mjs b/adapters/typescript/pi/test/relay-smoke.test.mjs index ddec55463..ffa070b00 100644 --- a/adapters/typescript/pi/test/relay-smoke.test.mjs +++ b/adapters/typescript/pi/test/relay-smoke.test.mjs @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import assert from "node:assert/strict"; -import { execFile } from "node:child_process"; +import { execFile, spawn } from "node:child_process"; import { mkdtemp, mkdir, readFile, readdir, realpath, rm, writeFile } from "node:fs/promises"; import { createServer } from "node:http"; import { tmpdir } from "node:os"; @@ -12,6 +12,7 @@ import { promisify } from "node:util"; import { PiSdkSessionFactory } from "../dist/pi-sdk.js"; import { PiAdapterRuntime } from "../dist/runtime.js"; +import { withTerminalInterface } from "../dist/terminal.js"; const execFileAsync = promisify(execFile); const relayCommand = process.env.FABRIC_TEST_NEMO_RELAY_COMMAND; @@ -269,3 +270,117 @@ test( } }, ); + +for (const sdk of [true, false]) { + test( + `captures terminal TUI turns through the runtime's Relay gateway${sdk ? "" : " without the SDK"}`, + { skip: relayCommand === undefined ? "set FABRIC_TEST_NEMO_RELAY_COMMAND to the released CLI" : false, timeout: 90_000 }, + async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-relay-terminal-"))); + const workspace = join(root, "workspace"); + const home = join(root, "home"); + const piAgentDir = join(root, "relay-install"); + const runtimeConfigPath = join(root, "relay-runtime.json"); + const upstream = createServer(async (request, response) => { + for await (const _chunk of request) { + // Drain the request. + } + response.writeHead(200, { "content-type": "text/event-stream" }); + response.end(openAiStream("relay terminal ok")); + }); + const upstreamUrl = await listen(upstream); + const previousConfigPath = process.env.FABRIC_RELAY_CONFIG_PATH; + let runtime; + try { + await mkdir(workspace); + await mkdir(home); + await execFileAsync(relayCommand, ["install", "pi", "--skip-doctor"], { + env: { ...process.env, PI_CODING_AGENT_DIR: piAgentDir }, + timeout: 10_000, + }); + const extensionPath = join(piAgentDir, "extensions", "nemo-relay"); + await writeFile(runtimeConfigPath, JSON.stringify({ relay: { config: { version: 1, components: [{ + kind: "observability", + enabled: true, + config: { + version: 4, + atof: { enabled: true, sinks: [{ type: "file", output_directory: join(root, "atof"), filename: "events.atof.jsonl" }] }, + atif: { enabled: true, output_directory: join(root, "atif") }, + }, + }] } } })); + process.env.FABRIC_RELAY_CONFIG_PATH = runtimeConfigPath; + const runtimeContext = { + artifacts: {}, + environment: { + control_location: "external_control", + env: { TEST_API_KEY: "credential-free-smoke" }, + environment_id: "environment-1", + ownership: "caller_owned", + provider: "local", + workspace, + }, + invocation_id: "start", + request_id: "request-start", + runtime_id: "relay-terminal", + telemetry: { relay_enabled: true }, + }; + runtime = new PiAdapterRuntime(withTerminalInterface(new PiSdkSessionFactory())); + await runtime.start({ + agentName: "pi-relay-terminal", + baseDir: root, + config: { + harness: { + settings: { + relay_extension_path: extensionPath, + interfaces: { terminal: {} }, + ...(sdk ? {} : { sdk: { enabled: false } }), + }, + }, + models: { + default: { api_key_env: "TEST_API_KEY", base_url: `${upstreamUrl}/v1`, model: "openai/gpt-oss-20b", provider: "nvidia" }, + }, + tools: { enabled: [] }, + }, + runtimeContext, + }); + if (sdk) { + assert.equal((await runtime.invoke({ input: "Reply from the SDK." }, runtimeContext)).status, "succeeded"); + } + // The launcher carries the Relay extension and its gateway; the person's environment has only the key. + const launcher = join(root, "artifacts", ".fabric", "pi", "runtimes", "relay-terminal", "interfaces", "terminal"); + const child = spawn("/bin/sh", [launcher, "--print", "Reply from the terminal UI."], { + cwd: home, + env: { PATH: process.env.PATH, HOME: home, TEST_API_KEY: "credential-free-smoke" }, + stdio: ["ignore", "pipe", "pipe"], + }); + let output = ""; + child.stdout.on("data", (chunk) => { output += chunk; }); + child.stderr.on("data", (chunk) => { output += chunk; }); + const code = await new Promise((resolve) => child.on("exit", resolve)); + assert.equal(code, 0, output); + assert.match(output, /relay terminal ok/u); + + await runtime.stop(); + runtime = undefined; + const atof = (await readFile(join(root, "atof", "relay-terminal", "events.atof.jsonl"), "utf8")) + .trim().split("\n").map((line) => JSON.parse(line)); + const llmStarts = atof.filter((record) => + record.kind === "scope" && record.category === "llm" && record.scope_category === "start"); + assert.equal(llmStarts.length, sdk ? 2 : 1); + // Each Pi process is its own Relay session with its own trajectory. + const atifFiles = await readdir(join(root, "atif", "relay-terminal")); + assert.equal(atifFiles.length, sdk ? 2 : 1); + } finally { + await runtime?.stop().catch(() => undefined); + if (previousConfigPath === undefined) { + delete process.env.FABRIC_RELAY_CONFIG_PATH; + } else { + process.env.FABRIC_RELAY_CONFIG_PATH = previousConfigPath; + } + upstream.closeAllConnections(); + await new Promise((resolve) => upstream.close(resolve)); + await rm(root, { recursive: true, force: true }); + } + }, + ); +} diff --git a/adapters/typescript/pi/test/runtime.test.mjs b/adapters/typescript/pi/test/runtime.test.mjs index 1726e6201..292a75a0a 100644 --- a/adapters/typescript/pi/test/runtime.test.mjs +++ b/adapters/typescript/pi/test/runtime.test.mjs @@ -557,3 +557,56 @@ test("retries Relay cleanup when gateway shutdown fails", async () => { assert.equal(sessionStopAttempts, 2); assert.equal(relayStopAttempts, 2); }); + +function startInputWith(settings) { + const input = startInput(); + return { ...input, config: { harness: { settings } } }; +} + +test("a native-only runtime answers invocation with pi_sdk_disabled without prompting", async () => { + let prompted = false; + const runtime = new PiAdapterRuntime({ + async create() { + return { + async prompt() { + prompted = true; + return { accepted: true, turnStarted: true, turnCount: 1, text: "ok" }; + }, + async check() { + return { outcome: "passed", reason_code: null, activity: "unknown", source: "fabric.adapter.liveness", observed_at: null }; + }, + async stop() {}, + }; + }, + }); + await runtime.start(startInputWith({ sdk: { enabled: false }, interfaces: { terminal: {} } })); + const result = await runtime.invoke({ input: "hello" }, context); + assert.equal(result.status, "failed"); + assert.equal(result.error.code, "pi_sdk_disabled"); + assert.deepEqual(result.extensions, { pi_turn_count: 0, pi_turn_started: false }); + assert.equal(prompted, false); + // Runtime management stays available. + assert.equal((await runtime.check("live")).outcome, "passed"); + await runtime.stop(); +}); + +test("a runtime with neither the SDK nor the terminal interface is refused before the session starts", async () => { + let created = false; + const runtime = new PiAdapterRuntime({ + async create() { + created = true; + return { async prompt() {}, async stop() {} }; + }, + }); + for (const settings of [ + { sdk: { enabled: false } }, + { sdk: { enabled: false }, interfaces: { terminal: { enabled: false } } }, + ]) { + await assert.rejects(runtime.start(startInputWith(settings)), (error) => error.code === "pi_no_execution_path"); + } + await assert.rejects( + runtime.start(startInputWith({ sdk: { enabled: "false" }, interfaces: { terminal: {} } })), + (error) => error.code === "pi_invalid_settings", + ); + assert.equal(created, false); +}); diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs new file mode 100644 index 000000000..ed346b811 --- /dev/null +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -0,0 +1,734 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { access, mkdir, mkdtemp, readdir, readFile, realpath, rm, stat, writeFile } from "node:fs/promises"; +import { createServer } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; + +import { PiSdkSessionFactory } from "../dist/pi-sdk.js"; +import { sdkEnabled } from "../dist/settings.js"; +import { PiNativeOnlySessionFactory } from "../dist/native-only.js"; +import { launcherScript, terminalArguments, terminalEnabled, withTerminalInterface } from "../dist/terminal.js"; + +const [major, minor] = process.versions.node.split(".").map(Number); +const skip = major > 22 || (major === 22 && minor >= 19) ? false : "Pi requires Node >=22.19"; + +/** The factory the adapter's CLI composes: the terminal interface around the SDK session. */ +function sessionFactory() { + return withTerminalInterface(new PiSdkSessionFactory()); +} + +/** A session handle that records whether it was stopped. */ +function fakeHandle(configuration) { + return { + configuration, + stopped: false, + async prompt() { return { accepted: true, turnStarted: false, turnCount: 0 }; }, + async check() { return { outcome: "passed" }; }, + async stop() { this.stopped = true; }, + }; +} + +const RUNTIME_KEY = "runtime-key-never-written"; +const TERMINAL_KEY = "terminal-key-from-launcher-environment"; +const SYSTEM_PROMPT = "You are the NeMo Fabric terminal test agent."; + +async function modelServer() { + const requests = []; + const server = createServer(async (request, response) => { + const chunks = []; + for await (const chunk of request) chunks.push(chunk); + requests.push({ + path: request.url, + authorization: request.headers.authorization, + body: JSON.parse(Buffer.concat(chunks).toString("utf8")), + }); + const frame = (value) => + `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 0, model: "test-model", ...value })}\n\n`; + response.writeHead(200, { "content-type": "text/event-stream" }); + response.end( + frame({ choices: [{ index: 0, delta: { role: "assistant", content: "terminal-answer" }, finish_reason: "stop" }] }) + + frame({ choices: [], usage: { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 } }) + + "data: [DONE]\n\n", + ); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + return { server, requests, url: `http://127.0.0.1:${server.address().port}/v1` }; +} + +function startInput(workspace, baseUrl, settings) { + return { + agentName: "terminal-test", + baseDir: workspace, + config: { + models: { + default: { + provider: "fabric-test", + model: "test-model", + base_url: baseUrl, + api_key_env: "TEST_API_KEY", + extensions: { + api: "openai-completions", + context_window: 32768, + max_tokens: 1024, + input: ["text"], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + }, + }, + }, + instructions: { system: { mode: "replace", content: SYSTEM_PROMPT } }, + tools: { enabled: ["read", "ls"], blocked: [] }, + ...(settings === undefined ? {} : { harness: { settings } }), + }, + runtimeContext: { + artifacts: {}, + environment: { + control_location: "external_control", + environment_id: "terminal-test", + ownership: "caller_owned", + provider: "local", + workspace, + env: { TEST_API_KEY: RUNTIME_KEY }, + }, + invocation_id: "start", + request_id: "start", + runtime_id: "rt-terminal", + }, + }; +} + +/** Run the launcher as a person would: a bare environment plus the model key, from another directory. */ +function launch(launcher, home, args, options = {}) { + const child = spawn("/bin/sh", [launcher, ...args], { + cwd: home, + env: { PATH: process.env.PATH, HOME: home, TEST_API_KEY: TERMINAL_KEY }, + stdio: [options.stdin ?? "ignore", "pipe", "pipe"], + }); + let stdout = ""; + let stderr = ""; + child.stdout.setEncoding("utf8").on("data", (chunk) => { stdout += chunk; }); + child.stderr.setEncoding("utf8").on("data", (chunk) => { stderr += chunk; }); + const exited = new Promise((resolve) => child.once("close", (code, signal) => resolve({ code, signal, stdout, stderr }))); + return { child, exited }; +} + +async function exists(path) { + try { + await access(path); + return true; + } catch { + return false; + } +} + +async function filesUnder(directory) { + const files = []; + for (const entry of await readdir(directory, { withFileTypes: true, recursive: true })) { + if (entry.isFile()) files.push(join(entry.parentPath, entry.name)); + } + return files; +} + +test("terminalEnabled follows interfaces.terminal and its enabled switch", () => { + assert.equal(terminalEnabled({}), false); + assert.equal(terminalEnabled({ harness: { settings: { interfaces: {} } } }), false); + assert.equal(terminalEnabled({ harness: { settings: { interfaces: { terminal: {} } } } }), true); + assert.equal(terminalEnabled({ harness: { settings: { interfaces: { terminal: { enabled: false } } } } }), false); + assert.throws(() => terminalEnabled({ harness: { settings: { interfaces: { terminal: true } } } }), /schema/); +}); + +test("sdkEnabled is on unless sdk.enabled is false", () => { + assert.equal(sdkEnabled({}), true); + assert.equal(sdkEnabled({ harness: { settings: { sdk: {} } } }), true); + assert.equal(sdkEnabled({ harness: { settings: { sdk: { enabled: false } } } }), false); + assert.throws(() => sdkEnabled({ harness: { settings: { sdk: false } } }), /schema/); +}); + +test("terminal arguments reproduce the embedded session's isolation and tool policy", () => { + const plan = { + workspace: "/work", + provider: "p", + model: { id: "m" }, + apiKeyEnv: "K", + compactionReserveTokens: 1, + extensionPaths: ["/work/ext.ts"], + skillPaths: ["/skills/review"], + toolsEnabled: ["read", "ls"], + toolsBlocked: ["bash"], + customTools: [], + mcpServers: { docs: { type: "http", url: "https://example.com/mcp" } }, + }; + const args = terminalArguments(plan, ["/rt/interfaces/fabric-terminal.ts"]); + for (const flag of ["--no-approve", "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-themes", "--no-context-files"]) { + assert.ok(args.includes(flag), flag); + } + assert.ok(args.includes("/rt/interfaces/fabric-terminal.ts")); + assert.deepEqual(args.slice(args.indexOf("--tools"), args.indexOf("--tools") + 2), ["--tools", "read,ls"]); + assert.deepEqual(args.slice(args.indexOf("--exclude-tools"), args.indexOf("--exclude-tools") + 2), ["--exclude-tools", "bash"]); + assert.ok(args.includes("builtin:mcp")); + assert.ok(args.includes("/work/ext.ts")); + assert.ok(args.includes("/skills/review")); + assert.ok(terminalArguments({ ...plan, toolsEnabled: [] }, []).includes("--no-tools")); + assert.throws(() => terminalArguments({ ...plan, toolsBlocked: ["a,b"] }, []), /tool name/); +}); + +test("the launcher quotes its paths and refuses to run without the tui.json descriptor", () => { + const script = launcherScript({ + node: "/usr/bin/node", + cli: "/opt/pi/cli.js", + agentDir: "/a'b", + sessionDir: "/s", + workspace: "/w", + descriptor: "/m", + args: ["--no-approve"], + }); + assert.match(script, /^#!\/bin\/sh\n/); + assert.match(script, /if \[ ! -e '\/m' \]; then/); + assert.match(script, /export PI_CODING_AGENT_DIR='\/a'\\''b'/); + assert.match(script, /exec '\/usr\/bin\/node' '\/opt\/pi\/cli.js' '--no-approve' "\$@"\n$/); +}); + +test("the terminal factory passes a session through unchanged without interfaces.terminal", async () => { + const handle = fakeHandle(undefined); + const factory = withTerminalInterface({ create: async () => handle }); + assert.equal(await factory.create(startInput("/nonexistent", "http://127.0.0.1:9/v1")), handle); + await assert.rejects( + factory.create(startInput("/nonexistent", "http://127.0.0.1:9/v1", { interfaces: { terminal: "on" } })), + /schema/, + ); +}); + +test("the terminal factory stops the session when it can't write the terminal interface", async () => { + const handle = fakeHandle(undefined); + const factory = withTerminalInterface({ create: async () => handle }); + await assert.rejects( + factory.create(startInput("/nonexistent", "http://127.0.0.1:9/v1", { interfaces: { terminal: {} } })), + (error) => error.code === "pi_terminal_unavailable", + ); + assert.equal(handle.stopped, true); +}); + +test("the SDK session runs on the agent directory's files and ignores interfaces.terminal", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-sdk-"))); + const { server, requests, url } = await modelServer(); + const directory = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal"); + let session; + try { + session = await new PiSdkSessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + // The terminal interface is the wrapper's; the session only writes Pi's own files. + assert.equal(await exists(join(directory, "interfaces")), false); + assert.deepEqual((await readdir(join(directory, "pi-agent"))).sort(), ["SYSTEM.md", "models.json", "settings.json"]); + assert.equal(session.configuration.agentDir, join(directory, "pi-agent")); + // A prompt goes out with what the files say: endpoint, model and system prompt. + const outcome = await session.prompt("hello"); + assert.equal(outcome.text, "terminal-answer"); + assert.equal(requests.length, 1); + assert.equal(requests[0].body.model, "test-model"); + assert.match(JSON.stringify(requests[0].body.messages[0]), new RegExp(SYSTEM_PROMPT)); + // The SDK keeps the key in memory: the request uses it although models.json only names the variable. + assert.equal(requests[0].authorization, `Bearer ${RUNTIME_KEY}`); + assert.equal(session.configuration.provider, "fabric-test"); + assert.equal(session.configuration.apiKeyEnv, "TEST_API_KEY"); + assert.equal(session.configuration.systemPrompt, SYSTEM_PROMPT); + assert.doesNotMatch(JSON.stringify(session.configuration), new RegExp(RUNTIME_KEY)); + } finally { + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + +test("without interfaces.terminal the adapter writes no launcher or tui.json", { skip }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-off-"))); + const { server, url } = await modelServer(); + let session; + try { + session = await sessionFactory().create(startInput(workspace, url)); + const directory = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal"); + assert.equal(await exists(join(directory, "pi-agent", "models.json")), true); + assert.equal(await exists(join(directory, "interfaces")), false); + } finally { + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + +test("the launcher opens Pi on the runtime's model, key variable and system prompt", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-"))); + const home = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-home-"))); + const { server, requests, url } = await modelServer(); + const directory = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal"); + const launcher = join(directory, "interfaces", "terminal"); + const descriptor = join(directory, "interfaces", "tui.json"); + let session; + try { + session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + // The attachment file is owner-only and versioned, with Pi's own launcher mode. + assert.equal((await stat(descriptor)).mode & 0o777, 0o600); + assert.deepEqual(JSON.parse(await readFile(descriptor, "utf8")), { + version: 1, + mode: "launcher", + launcher: "terminal", + runtime_id: "rt-terminal", + workspace, + agent_dir: join(directory, "pi-agent"), + session_dir: join(directory, "pi-sessions"), + }); + assert.equal((await stat(launcher)).mode & 0o777, 0o700); + assert.equal((await stat(join(directory, "interfaces"))).mode & 0o777, 0o700); + // As for Hermes's native interfaces, terminal turns aren't observed, so activity is unknown. + const health = await session.check("ready"); + assert.equal(health.outcome, "passed"); + assert.equal(health.activity, "unknown"); + for (const file of await filesUnder(directory)) { + assert.doesNotMatch(await readFile(file, "utf8"), new RegExp(RUNTIME_KEY), `${file} holds the runtime's key`); + } + const models = JSON.parse(await readFile(join(directory, "pi-agent", "models.json"), "utf8")); + assert.equal(models.providers["fabric-test"].apiKey, "$TEST_API_KEY"); + assert.equal(models.providers["fabric-test"].baseUrl, url); + + const run = await launch(launcher, home, ["--print", "say hello"]).exited; + assert.equal(run.code, 0, run.stderr); + assert.match(run.stdout, /terminal-answer/); + assert.equal(requests.length, 1); + assert.equal(requests[0].path, "/v1/chat/completions"); + assert.equal(requests[0].authorization, `Bearer ${TERMINAL_KEY}`); + assert.equal(requests[0].body.model, "test-model"); + assert.match(JSON.stringify(requests[0].body.messages[0]), new RegExp(SYSTEM_PROMPT)); + assert.deepEqual(requests[0].body.tools.map((tool) => tool.function.name).sort(), ["ls", "read"]); + // The terminal UI keeps its own session, under the runtime's directory, not the person's home. + assert.ok((await filesUnder(join(directory, "pi-sessions"))).some((file) => file.endsWith(".jsonl"))); + assert.equal(await exists(join(home, ".pi")), false); + + await session.stop(); + session = undefined; + assert.equal(await exists(descriptor), false); + const refused = await launch(launcher, home, ["--print", "again"]).exited; + assert.equal(refused.code, 1); + assert.match(refused.stderr, /not running/); + assert.equal(requests.length, 1); + } finally { + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + await rm(home, { recursive: true, force: true }); + } +}); + +test("stopping the runtime closes an open terminal UI before the session stops", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-stop-"))); + const home = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-home-"))); + const { server, url } = await modelServer(); + const directory = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal"); + const registry = join(directory, "interfaces", "tui.clients"); + let session; + let terminal; + try { + session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + // RPC mode keeps Pi running without a TTY while its stdin stays open, as a terminal UI would. + terminal = launch(join(directory, "interfaces", "terminal"), home, ["--mode", "rpc"], { stdin: "pipe" }); + const deadline = Date.now() + 20_000; + while (!(await exists(registry)) || (await readdir(registry)).length === 0) { + assert.ok(Date.now() < deadline, "the terminal UI never registered"); + await new Promise((resolve) => setTimeout(resolve, 100)); + } + assert.deepEqual(await readdir(registry), [String(terminal.child.pid)]); + + const started = Date.now(); + await session.stop(); + session = undefined; + const exit = await terminal.exited; + // The terminal UI closes itself: shutdown() in TUI mode (exit 0); in RPC mode, which defers + // shutdown(), its own SIGTERM handler (exit 143). Either way the adapter didn't have to kill it. + assert.equal(exit.signal, null, "the terminal UI should shut itself down, not be killed"); + assert.ok([0, 143].includes(exit.code), `exit ${exit.code}: ${exit.stderr}`); + assert.ok(Date.now() - started < 5_000, "stop waited for the terminal UI's grace period to expire"); + assert.equal(await exists(registry), false, "stop leaves the terminal UI registrations behind"); + } finally { + terminal?.child.kill("SIGKILL"); + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + await rm(home, { recursive: true, force: true }); + } +}); + +/** + * A registered terminal UI that doesn't close itself when tui.json goes away, leading its own + * process group as `openshell sandbox exec --tty` would start it, with a tool's child process in it. + */ +async function fakeTerminal(clients, { ignoreSigterm }) { + const source = ` + import { spawn } from "node:child_process"; + import { mkdirSync, writeFileSync } from "node:fs"; + import { join } from "node:path"; + const [clients, ignore] = process.argv.slice(1); + process.on("SIGTERM", () => { if (ignore !== "ignore") process.exit(143); }); + const tool = spawn("sleep", ["60"], { stdio: "ignore" }); + mkdirSync(clients, { recursive: true }); + const beat = () => writeFileSync(join(clients, String(process.pid)), ""); + beat(); + setInterval(beat, 200); + console.log(tool.pid); + `; + const child = spawn(process.execPath, ["--input-type=module", "-e", source, clients, ignoreSigterm ? "ignore" : "exit"], { + detached: true, + stdio: ["ignore", "pipe", "inherit"], + }); + const tool = await new Promise((resolve) => child.stdout.setEncoding("utf8").once("data", (line) => resolve(Number(line.trim())))); + const exited = new Promise((resolve) => child.once("exit", (code, signal) => resolve({ code, signal }))); + return { child, tool, exited }; +} + +function running(pid) { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +test("stop sends SIGTERM to open terminal UIs at once", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-sigterm-"))); + const { server, url } = await modelServer(); + const clients = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal", "interfaces", "tui.clients"); + let session; + let terminal; + try { + session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + terminal = await fakeTerminal(clients, { ignoreSigterm: false }); + + const started = Date.now(); + await session.stop(); + session = undefined; + assert.deepEqual(await terminal.exited, { code: 143, signal: null }); + assert.ok(Date.now() - started < 2_000, `stop took ${Date.now() - started} ms before signalling the terminal UI`); + } finally { + if (terminal !== undefined) { + for (const pid of [-terminal.child.pid, terminal.tool]) try { process.kill(pid, "SIGKILL"); } catch {} + } + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + +test("stop kills an open terminal UI's process group five seconds after SIGTERM", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-sigkill-"))); + const { server, url } = await modelServer(); + const clients = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal", "interfaces", "tui.clients"); + let session; + let terminal; + try { + session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + terminal = await fakeTerminal(clients, { ignoreSigterm: true }); + assert.ok(running(terminal.tool)); + + const started = Date.now(); + await session.stop(); + session = undefined; + const elapsed = Date.now() - started; + assert.deepEqual(await terminal.exited, { code: null, signal: "SIGKILL" }); + assert.ok(elapsed >= 4_500 && elapsed < 7_000, `stop took ${elapsed} ms`); + const deadline = Date.now() + 1_000; + while (running(terminal.tool) && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 50)); + assert.equal(running(terminal.tool), false, "the terminal UI's tool process outlived stop"); + } finally { + if (terminal !== undefined) { + for (const pid of [-terminal.child.pid, terminal.tool]) try { process.kill(pid, "SIGKILL"); } catch {} + } + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + +test("a native-only runtime writes Pi's files and the launcher but runs no SDK session",{ skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-native-only-"))); + const home = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-native-only-home-"))); + const { server, requests, url } = await modelServer(); + const directory = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal"); + const launcher = join(directory, "interfaces", "terminal"); + const descriptor = join(directory, "interfaces", "tui.json"); + let session; + try { + session = await sessionFactory().create( + startInput(workspace, url, { sdk: { enabled: false }, interfaces: { terminal: {} } }), + ); + assert.equal(session.relay, undefined); + assert.equal(await exists(join(directory, "pi-agent", "models.json")), true); + assert.equal(await exists(descriptor), true); + for (const level of ["live", "active", "ready"]) { + const health = await session.check(level); + assert.equal(health.outcome, "passed", level); + assert.equal(health.activity, "unknown", level); + } + + const run = await launch(launcher, home, ["--print", "say hello"]).exited; + assert.equal(run.code, 0, run.stderr); + assert.match(run.stdout, /terminal-answer/); + assert.equal(requests.length, 1); + assert.equal(requests[0].authorization, `Bearer ${TERMINAL_KEY}`); + + // A withdrawn interface fails the runtime's active and ready checks. + await rm(descriptor); + assert.equal((await session.check("live")).outcome, "passed"); + assert.equal((await session.check("ready")).reason_code, "endpoint_unavailable"); + } finally { + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + await rm(home, { recursive: true, force: true }); + } +}); + +test("a native-only runtime with Relay runs the gateway, and the launcher loads the Relay extension on it", { skip }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-relay-"))); + const extensionPath = join(workspace, "relay-extension"); + const started = []; + const relayFactory = { + async start(_input, model) { + const relay = { + extensionPath, + extensionEnvironment: { NEMO_RELAY_PI_GATEWAY_URL: "http://127.0.0.1:1", NEMO_RELAY_PI_OPENAI_UPSTREAM: model.baseUrl }, + stop: async () => undefined, + }; + started.push(relay); + return relay; + }, + }; + let session; + try { + const input = startInput(workspace, "http://127.0.0.1:9/v1", { sdk: { enabled: false }, interfaces: { terminal: {} } }); + input.runtimeContext.telemetry = { relay_enabled: true }; + session = await withTerminalInterface(new PiSdkSessionFactory(relayFactory), new PiNativeOnlySessionFactory(relayFactory)).create(input); + assert.equal(started.length, 1); + // The runtime stops the session's Relay gateway after the session. + assert.equal(session.relay, started[0]); + const launcher = await readFile(join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal", "interfaces", "terminal"), "utf8"); + assert.match(launcher, /^export NEMO_RELAY_PI_GATEWAY_URL='http:\/\/127\.0\.0\.1:1'$/mu); + assert.match(launcher, /^export NEMO_RELAY_PI_OPENAI_UPSTREAM='http:\/\/127\.0\.0\.1:9\/v1'$/mu); + assert.ok(launcher.includes(`'--extension' '${extensionPath}'`), launcher); + } finally { + await session?.stop(); + await rm(workspace, { recursive: true, force: true }); + } +}); + +/** A start of the agent's runtime `runtimeId` with `runtime.keep_state`: core passes the agent's state folder. */ +function keptInput(workspace, baseUrl, settings, runtimeId, stateDir) { + const input = startInput(workspace, baseUrl, settings); + input.runtimeContext.runtime_id = runtimeId; + input.runtimeContext.state_dir = stateDir; + return input; +} + +function userTexts(request) { + return request.body.messages + .filter((message) => message.role === "user") + .map((message) => typeof message.content === "string" ? message.content : JSON.stringify(message.content)); +} + +test("with keep_state, a terminal conversation from one runtime continues in the next", { skip, timeout: 90_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-kept-"))); + const home = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-kept-home-"))); + const { server, requests, url } = await modelServer(); + const state = join(workspace, "artifacts", ".fabric", "state", "nvidia.fabric.pi", "terminal-test"); + const launcher = join(state, "interfaces", "terminal"); + let session; + try { + session = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-one", state)); + // The whole Pi directory is the state folder, where NemoClaw looks for a kept agent's interfaces. + assert.deepEqual(JSON.parse(await readFile(join(state, "interfaces", "tui.json"), "utf8")), { + version: 1, + mode: "launcher", + launcher: "terminal", + runtime_id: "rt-one", + workspace, + agent_dir: join(state, "pi-agent"), + session_dir: join(state, "pi-sessions"), + }); + const first = await launch(launcher, home, ["--print", "remember the word heron"]).exited; + assert.equal(first.code, 0, first.stderr); + await session.stop(); + session = undefined; + assert.equal(await exists(join(workspace, "artifacts", ".fabric", "pi", "runtimes")), false); + + session = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-two", state)); + const second = await launch(launcher, home, ["--continue", "--print", "which word?"]).exited; + assert.equal(second.code, 0, second.stderr); + assert.equal(requests.length, 2); + // The second runtime's terminal UI resumed the first runtime's conversation. + const texts = userTexts(requests[1]); + assert.ok(texts.some((text) => text.includes("remember the word heron")), JSON.stringify(texts)); + assert.ok(texts.some((text) => text.includes("which word?")), JSON.stringify(texts)); + } finally { + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + await rm(home, { recursive: true, force: true }); + } +}); + +test("with keep_state, a start replaces what an earlier runtime left but keeps Pi's credentials", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-kept-clean-"))); + const { server, url } = await modelServer(); + const state = join(workspace, "artifacts", ".fabric", "state", "nvidia.fabric.pi", "terminal-test"); + let session; + try { + session = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-one", state)); + // The runtime ends without stop, as when its host is killed; Pi saved a login of its own. + session = undefined; + await writeFile(join(state, "pi-agent", "auth.json"), "{\"other\":{\"type\":\"api_key\",\"key\":\"saved\"}}\n", { mode: 0o600 }); + await mkdir(join(state, "interfaces", "tui.clients"), { recursive: true }); + await writeFile(join(state, "interfaces", "tui.clients", "999999"), ""); + + // The next runtime has no system prompt and no terminal interface. + const input = keptInput(workspace, url, undefined, "rt-two", state); + delete input.config.instructions; + session = await sessionFactory().create(input); + for (const stale of ["tui.json", "tui.clients", "terminal", "fabric-terminal.ts"]) { + assert.equal(await exists(join(state, "interfaces", stale)), false, stale); + } + // Pi's configuration comes from this runtime's FabricConfig alone. + assert.equal(await exists(join(state, "pi-agent", "SYSTEM.md")), false); + assert.equal(session.configuration.systemPrompt, undefined); + // Credentials Pi saved itself survive. + assert.match(await readFile(join(state, "pi-agent", "auth.json"), "utf8"), /saved/); + } finally { + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + +test("with keep_state, the next start closes a terminal UI left open by a killed runtime", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-kept-stale-"))); + const home = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-kept-stale-home-"))); + const { server, url } = await modelServer(); + const state = join(workspace, "artifacts", ".fabric", "state", "nvidia.fabric.pi", "terminal-test"); + const registry = join(state, "interfaces", "tui.clients"); + let session; + let terminal; + try { + await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-one", state)); + // rt-one's host is gone without stop; its terminal UI keeps running. + terminal = launch(join(state, "interfaces", "terminal"), home, ["--mode", "rpc"], { stdin: "pipe" }); + const deadline = Date.now() + 20_000; + while (!(await exists(registry)) || (await readdir(registry)).length === 0) { + assert.ok(Date.now() < deadline, "the terminal UI never registered"); + await new Promise((resolve) => setTimeout(resolve, 100)); + } + + session = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-two", state)); + // The new runtime started only after the old terminal UI stopped writing to the state folder. + assert.notEqual(terminal.child.exitCode ?? terminal.child.signalCode, null, "rt-one's terminal UI still runs"); + assert.equal(JSON.parse(await readFile(join(state, "interfaces", "tui.json"), "utf8")).runtime_id, "rt-two"); + } finally { + terminal?.child.kill("SIGKILL"); + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + await rm(home, { recursive: true, force: true }); + } +}); + +test("with keep_state, the SDK session's conversation is kept where the terminal UI finds it", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-kept-sdk-"))); + const home = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-kept-sdk-home-"))); + const { server, requests, url } = await modelServer(); + const state = join(workspace, "artifacts", ".fabric", "state", "nvidia.fabric.pi", "terminal-test"); + let session; + try { + session = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-one", state)); + assert.equal((await session.prompt("invoked through the SDK")).text, "terminal-answer"); + await session.stop(); + session = undefined; + + session = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-two", state)); + const run = await launch(join(state, "interfaces", "terminal"), home, ["--continue", "--print", "and now?"]).exited; + assert.equal(run.code, 0, run.stderr); + assert.ok(userTexts(requests.at(-1)).some((text) => text.includes("invoked through the SDK"))); + } finally { + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + await rm(home, { recursive: true, force: true }); + } +}); + +/** Run `action` while recording what the adapter writes to stderr. */ +async function capturingStderr(action) { + const written = []; + const write = process.stderr.write; + process.stderr.write = (chunk, ...rest) => { + written.push(String(chunk)); + return write.call(process.stderr, chunk, ...rest); + }; + try { + return { result: await action(), stderr: written.join("") }; + } finally { + process.stderr.write = write; + } +} + +/** A Relay factory whose runtime carries `sinks` as its ATOF sinks. */ +function relayWithAtofSinks(workspace, sinks) { + return { + async start() { + return { + extensionPath: join(workspace, "relay-extension"), + extensionEnvironment: {}, + pluginConfig: { + version: 1, + components: [{ kind: "observability", enabled: true, config: { version: 4, atof: { enabled: true, sinks } } }], + }, + stop: async () => undefined, + }; + }, + }; +} + +test("a native-only runtime warns that Fabric's invocation stream doesn't reach the terminal TUI", { skip }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-native-only-stream-"))); + const collector = { type: "stream", url: "http://127.0.0.1:4319/atof", transport: "ndjson", name: "nemo-fabric-stream" }; + const own = { type: "stream", url: "https://example.test/events", name: "team-events" }; + const start = async (sinks) => { + const relay = relayWithAtofSinks(workspace, sinks); + const input = startInput(workspace, "http://127.0.0.1:9/v1", { sdk: { enabled: false }, interfaces: { terminal: {} } }); + input.runtimeContext.telemetry = { relay_enabled: true }; + return capturingStderr(async () => { + const session = await withTerminalInterface(new PiSdkSessionFactory(relay), new PiNativeOnlySessionFactory(relay)).create(input); + await session.stop(); + }); + }; + try { + // streaming=True adds the collector's sink, which only invoke_stream() reads. + const warned = await start([collector, own]); + const lines = warned.stderr.split("\n").filter((line) => line.includes("nemo-fabric-stream")); + assert.equal(lines.length, 1, warned.stderr); + assert.match(lines[0], /sdk\.enabled is false/); + // A sink of the caller's own still receives the terminal TUI's Relay events: no warning. + const quiet = await start([own]); + assert.doesNotMatch(quiet.stderr, /warning/i); + } finally { + await rm(workspace, { recursive: true, force: true }); + } +}); diff --git a/adapters/typescript/pi/test/usage.test.mjs b/adapters/typescript/pi/test/usage.test.mjs index 085a6ad41..47bda0819 100644 --- a/adapters/typescript/pi/test/usage.test.mjs +++ b/adapters/typescript/pi/test/usage.test.mjs @@ -121,7 +121,7 @@ test("retains observed invocation usage on failed and cancelled results", async }; }, }); - await runtime.start({}); + await runtime.start({ config: {} }); const result = await runtime.invoke({ input: "test" }, {}); assert.notEqual(result.status, "succeeded"); assert.deepEqual(result.usage, observed); diff --git a/adapters/typescript/scripts/check-package.mjs b/adapters/typescript/scripts/check-package.mjs index 04dbabea5..94544164c 100644 --- a/adapters/typescript/scripts/check-package.mjs +++ b/adapters/typescript/scripts/check-package.mjs @@ -66,8 +66,14 @@ const expectedByPackage = { "nemo-fabric-adapters-pi": [ "LICENSE", "README.md", + "dist/agent-directory.d.ts", + "dist/agent-directory.js", "dist/cli.d.ts", "dist/cli.js", + "dist/native-configuration.d.ts", + "dist/native-configuration.js", + "dist/native-only.d.ts", + "dist/native-only.js", "dist/node-version.d.ts", "dist/node-version.js", "dist/pi-sdk.d.ts", @@ -84,6 +90,10 @@ const expectedByPackage = { "dist/relay.js", "dist/runtime.d.ts", "dist/runtime.js", + "dist/settings.d.ts", + "dist/settings.js", + "dist/terminal.d.ts", + "dist/terminal.js", "package.json", "pi.fabric-adapter.json", ], diff --git a/examples/interfaces/pi/pi_tui.py b/examples/interfaces/pi/pi_tui.py new file mode 100644 index 000000000..5d0d48060 --- /dev/null +++ b/examples/interfaces/pi/pi_tui.py @@ -0,0 +1,219 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Open Pi's terminal TUI from a runtime that keeps its state across runtimes. + +With ``runtime.keep_state``, every runtime of the agent uses one Pi directory, the +agent's state folder, so Pi's terminal conversations outlive the runtime. Run this +script, talk to Pi in its terminal UI, stop the runtime, and run the script again +with the same ``--output-dir``: ``/resume`` in the new runtime's terminal UI lists +the earlier conversations, and ``--continue`` reopens the latest one. + +``--demo`` shows the same thing without a person: it starts a runtime, has its +terminal UI answer one prompt in print mode, stops it, starts a second runtime, +and continues that conversation from the second runtime's terminal UI. +""" + +from __future__ import annotations + +import argparse +import asyncio +import os +import shlex +import subprocess +from pathlib import Path + +from nemo_fabric import Fabric, FabricConfig + +AGENT = "pi-tui-example" +DESCRIPTOR = ( + Path(__file__).resolve().parents[3] + / "adapters/typescript/pi/pi.fabric-adapter.json" +) + + +def build_config(args: argparse.Namespace, output: Path) -> FabricConfig: + """A Pi agent with its terminal interface and kept state under ``output``.""" + workspace = output / "workspace" + workspace.mkdir(parents=True, exist_ok=True) + model: dict[str, object] = { + "provider": args.provider, + "model": args.model, + "api_key_env": args.api_key_env, + } + if args.base_url: + model["base_url"] = args.base_url + if args.api: + # A gateway-served model Pi doesn't ship needs a complete definition. + model.update( + api=args.api, + context_window=args.context_window, + max_tokens=4096, + input=["text"], + cost={"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0}, + ) + return FabricConfig.from_mapping( + { + "metadata": {"name": AGENT}, + "discovery": {"local_paths": [str(DESCRIPTOR)]}, + "harness": { + "adapter_id": "nvidia.fabric.pi", + "settings": { + "sdk": {"enabled": args.sdk}, + "interfaces": {"terminal": {}}, + }, + }, + "models": {"default": model}, + "tools": {"enabled": ["read", "ls"]}, + "runtime": {"keep_state": not args.no_keep_state}, + "environment": { + "provider": "local", + "workspace": str(workspace), + "artifacts": str(output / "artifacts"), + }, + } + ) + + +def pi_directory(output: Path, runtime_id: str, keep_state: bool) -> Path: + """Where the adapter keeps Pi's files: the agent's state folder, or the runtime's own folder.""" + artifacts = output / "artifacts" / ".fabric" + if keep_state: + return artifacts / "state" / "nvidia.fabric.pi" / AGENT + return artifacts / "pi" / "runtimes" / runtime_id + + +async def interactive(args: argparse.Namespace, output: Path) -> None: + """Own one runtime until Enter while a person uses its terminal UI.""" + config = build_config(args, output) + async with await Fabric().start_runtime(config, base_dir=Path.cwd()) as runtime: + launcher = ( + pi_directory(output, runtime.runtime_id, not args.no_keep_state) + / "interfaces/terminal" + ) + print(f"Runtime {runtime.runtime_id} is ready.", flush=True) + print( + f"In a second terminal, with {args.api_key_env} set, run:\n {shlex.quote(str(launcher))}", + flush=True, + ) + print( + "Add --continue to reopen the latest conversation, or type /resume in Pi to pick one.", + flush=True, + ) + await asyncio.to_thread( + input, + "Press Enter here to stop the runtime (open terminal UIs close with it).\n", + ) + await runtime.stop() + print( + f"Stopped. Run this again with --output-dir {shlex.quote(str(output))} to continue.", + flush=True, + ) + + +def run_terminal(launcher: Path, *pi_args: str) -> str: + """Run the runtime's terminal UI once in print mode, as a person's shell would.""" + result = subprocess.run( + [str(launcher), *pi_args], + # Pi's print mode reads a piped stdin as more input; give it none. + stdin=subprocess.DEVNULL, + check=True, + capture_output=True, + text=True, + timeout=300, + ) + return result.stdout.strip() + + +async def demo(args: argparse.Namespace, output: Path) -> None: + """Two runtimes in a row: the second's terminal UI continues the first's conversation.""" + keep_state = not args.no_keep_state + fabric = Fabric() + config = build_config(args, output) + async with await fabric.start_runtime(config, base_dir=Path.cwd()) as first: + launcher = ( + pi_directory(output, first.runtime_id, keep_state) / "interfaces/terminal" + ) + print( + f"[{first.runtime_id}] > Remember the word heron. Reply with OK.", + flush=True, + ) + print( + f"[{first.runtime_id}] {run_terminal(launcher, '--print', 'Remember the word heron. Reply with OK.')}", + flush=True, + ) + await first.stop() + async with await fabric.start_runtime(config, base_dir=Path.cwd()) as second: + launcher = ( + pi_directory(output, second.runtime_id, keep_state) / "interfaces/terminal" + ) + question = "Which word did I ask you to remember? Reply with the word only." + print(f"[{second.runtime_id}] > --continue {question}", flush=True) + answer = run_terminal(launcher, "--continue", "--print", question) + print(f"[{second.runtime_id}] {answer}", flush=True) + await second.stop() + sessions = ( + sorted((pi_directory(output, "", True) / "pi-sessions").glob("*.jsonl")) + if keep_state + else [] + ) + print( + f"Kept conversations: {len(sessions)} in {pi_directory(output, '', True) / 'pi-sessions'}" + if keep_state + else "Without keep_state, the second runtime started with no conversations.", + flush=True, + ) + + +def main() -> None: + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument( + "--provider", default=os.environ.get("MODEL_PROVIDER", "nvidia") + ) + parser.add_argument("--model", default=os.environ.get("MODEL_NAME")) + parser.add_argument("--base-url", default=os.environ.get("MODEL_BASE_URL")) + parser.add_argument("--api-key-env", default="MODEL_API_KEY") + parser.add_argument( + "--api", + help="For a gateway-served model Pi doesn't ship: its wire protocol, such as openai-completions", + ) + parser.add_argument( + "--context-window", + type=int, + default=32768, + help="With --api: the model's context window", + ) + parser.add_argument( + "--sdk", action="store_true", help="Also start the embedded SDK session" + ) + parser.add_argument( + "--no-keep-state", + action="store_true", + help="Give each runtime its own Pi directory, for contrast", + ) + parser.add_argument( + "--demo", action="store_true", help="Run two runtimes in a row without a person" + ) + parser.add_argument( + "--output-dir", + type=Path, + default=Path("outputs/interfaces/pi-kept-state"), + help="Workspace and artifacts; reuse it to continue in a later runtime", + ) + args = parser.parse_args() + if not args.model or not os.environ.get(args.api_key_env): + parser.error( + "set --model (or MODEL_NAME) and the credential environment variable named by --api-key-env" + ) + output = args.output_dir.resolve() + output.mkdir(parents=True, exist_ok=True) + try: + asyncio.run(demo(args, output) if args.demo else interactive(args, output)) + except (KeyboardInterrupt, EOFError): + pass + + +if __name__ == "__main__": + main() diff --git a/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json b/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json index 724b55689..5012d62fc 100644 --- a/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json +++ b/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json @@ -3449,7 +3449,8 @@ "tools.blocked", "skills", "mcp", - "mcp.tool_filters" + "mcp.tool_filters", + "runtime.keep_state" ], "system_instruction_modes": [ "replace" @@ -3643,6 +3644,48 @@ }, "settings_schema": { "additionalProperties": false, + "allOf": [ + { + "if": { + "properties": { + "sdk": { + "properties": { + "enabled": { + "const": false + } + }, + "required": [ + "enabled" + ] + } + }, + "required": [ + "sdk" + ] + }, + "then": { + "properties": { + "interfaces": { + "properties": { + "terminal": { + "properties": { + "enabled": { + "const": true + } + } + } + }, + "required": [ + "terminal" + ] + } + }, + "required": [ + "interfaces" + ] + } + } + ], "properties": { "extensions": { "items": { @@ -3671,10 +3714,41 @@ "type": "array", "uniqueItems": true }, + "interfaces": { + "additionalProperties": false, + "description": "Native interfaces offered by the runtime.", + "properties": { + "terminal": { + "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 (/.fabric/pi/runtimes/, or the agent's state folder with runtime.keep_state) opens it on the runtime's agent directory in a separate conversation. 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.", + "properties": { + "enabled": { + "default": true, + "description": "Offer Pi's terminal TUI. A present terminal interface is on unless this is false.", + "type": "boolean" + } + }, + "type": "object" + } + }, + "type": "object" + }, "relay_extension_path": { "description": "Absolute path or environment.workspace-relative path to the NeMo Relay Pi extension matching the CLI release", "minLength": 1, "type": "string" + }, + "sdk": { + "additionalProperties": false, + "description": "Embedded SDK execution, enabled by default. Runtime management remains available when disabled.", + "properties": { + "enabled": { + "default": true, + "description": "Initialize the embedded SDK session during startup. Disable for native-only execution; SDK invocation then fails explicitly.", + "type": "boolean" + } + }, + "type": "object" } }, "type": "object" @@ -3718,7 +3792,7 @@ "name": "nemo-fabric-adapters-pi", "version": "0.8.0" }, - "sha256": "1d3f4b6933689530782ba0ebd019ca9af3476a8f9b7d5b955783d0a59b743283", + "sha256": "01e72ccce63d1a920f4649d1728159aa46c973714e3f21858b800aaa7e72d7f6", "source": "adapters/typescript/pi/pi.fabric-adapter.json" }, "nvidia.fabric.qwen": { diff --git a/tests/adapters/test_pi_adapter.py b/tests/adapters/test_pi_adapter.py index 4eea74aec..fb52d53b1 100644 --- a/tests/adapters/test_pi_adapter.py +++ b/tests/adapters/test_pi_adapter.py @@ -64,6 +64,7 @@ def test_pi_descriptor_declares_the_supported_surface(): "skills", "mcp", "mcp.tool_filters", + "runtime.keep_state", ] assert descriptor["config"]["system_instruction_modes"] == ["replace"] assert descriptor["settings_schema"]["properties"]["relay_extension_path"] == { @@ -135,6 +136,16 @@ def test_pi_descriptor_validates_module_tool_definitions(): } +def test_pi_descriptor_plans_kept_state(tmp_path: Path): + # The Python SDK has no typed keep_state field; the mapping carries it to core. + mapping = config().to_mapping() + mapping["runtime"] = {"keep_state": True, "artifacts": str(tmp_path / "artifacts")} + + plan = Fabric().plan(FabricConfig.from_mapping(mapping), base_dir=ROOT) + + assert plan.adapter_descriptor["descriptor"]["adapter_id"] == "nvidia.fabric.pi" + + def test_pi_descriptor_plans_and_projects_the_selected_model(): plan = Fabric().plan(config(), base_dir=ROOT) From fcde84e557a09f66620bdb36be62c0dc98f572b6 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Tue, 1 Dec 2026 16:41:53 -0800 Subject: [PATCH 02/25] fix: keep Pi's terminal configuration equivalent to the SDK session - Escape MCP stdio env and header values in mcp.json for Pi's configuration-value syntax, so the terminal UI reads the values the SDK session uses and never runs a leading `!` as a shell command. The SDK session keeps its servers in memory instead of reading the file back. - Stop Pi from appending a stale APPEND_SYSTEM.md to the configured system prompt, and remove it at each start. - Without the terminal interface or keep_state, keep Pi's files in a private temporary directory that stop removes, as before. - Reference the model key as ${NAME} and refuse names Pi can't resolve when the terminal interface is enabled. - Run one supervisor heartbeat per terminal UI across session switches. - Report file-system failures as lifecycle errors. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- adapters/typescript/pi/src/agent-directory.ts | 12 +- .../typescript/pi/src/native-configuration.ts | 229 +++++++++++++----- adapters/typescript/pi/src/pi-sdk.ts | 57 +++-- adapters/typescript/pi/src/terminal.ts | 74 ++++-- adapters/typescript/pi/test/terminal.test.mjs | 86 ++++++- tests/adapters/test_pi_adapter.py | 45 ++++ 6 files changed, 385 insertions(+), 118 deletions(-) diff --git a/adapters/typescript/pi/src/agent-directory.ts b/adapters/typescript/pi/src/agent-directory.ts index bd0548f52..b0012a927 100644 --- a/adapters/typescript/pi/src/agent-directory.ts +++ b/adapters/typescript/pi/src/agent-directory.ts @@ -5,8 +5,11 @@ // 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. -// The files hold no secrets: models.json and mcp.json name environment variables, -// and the SDK session supplies the model key in memory. +// 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, such as auth.json, stay. @@ -73,7 +76,7 @@ export function piModels(configuration: PiNativeConfiguration): JsonObject { // 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}`, + apiKey: `\${${configuration.apiKeyEnv}}`, models: [configuration.model as JsonObject], }, }, @@ -105,6 +108,9 @@ export async function writeAgentDirectory(configuration: PiNativeConfiguration): } else { await rm(join(directory, "mcp.json"), { force: true }); } + // Pi appends /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 /SYSTEM.md. await writePrivate(join(directory, "SYSTEM.md"), configuration.systemPrompt); diff --git a/adapters/typescript/pi/src/native-configuration.ts b/adapters/typescript/pi/src/native-configuration.ts index 3000fd23a..391964fe4 100644 --- a/adapters/typescript/pi/src/native-configuration.ts +++ b/adapters/typescript/pi/src/native-configuration.ts @@ -7,7 +7,8 @@ // which the embedded SDK session and Pi's terminal UI both read, and checks that // Pi resolves the selected model from those files. It starts no session. -import { readFile, realpath, stat } from "node:fs/promises"; +import { mkdtemp, realpath, rm, stat } from "node:fs/promises"; +import { tmpdir } from "node:os"; import { extname, isAbsolute, join, relative, resolve, sep } from "node:path"; import type { McpServerConfig, ToolDefinition } from "@earendil-works/pi-coding-agent"; @@ -16,6 +17,7 @@ import type { AgentConfig, AgentModelConfig, AgentToolDefinition, JsonObject } f import { LifecycleError, type AdapterStartInput } from "nemo-fabric-adapters-common"; import { agentDirectory, keepsState, runtimeDirectory, sessionDirectory, writeAgentDirectory } from "./agent-directory.js"; +import { terminalEnabled } from "./settings.js"; export interface PiNativeCustomTool { name: string; @@ -25,6 +27,13 @@ export interface PiNativeCustomTool { } export interface PiNativeConfiguration { + /** The runtime's Pi directory, which holds the agent and session directories and, with the terminal interface, interfaces/. */ + runtimeDir: string; + /** + * Whether the runtime directory is a private temporary directory that stop removes: no + * other process reads it without the terminal interface or runtime.keep_state. + */ + ephemeral: boolean; /** The runtime's Pi agent directory, holding this configuration as Pi's own files. */ agentDir: string; /** Pi's session directory beside the agent directory, where conversations are kept on disk. */ @@ -50,7 +59,10 @@ export interface PiNativeConfiguration { toolsEnabled?: string[] | null; toolsBlocked: string[]; customTools: PiNativeCustomTool[]; - /** MCP servers in Pi's mcp.json shape, with header variable references left unexpanded. */ + /** + * MCP servers as Pi's terminal UI reads them from mcp.json: header variable references + * left unexpanded, and values escaped for Pi's configuration-value syntax. + */ mcpServers: Record; } @@ -204,6 +216,8 @@ async function loadPiSdk(): Promise { const MCP_HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u; const MCP_ENV_REFERENCE = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/gu; +/** A variable name Pi can resolve from a `${NAME}` reference. */ +export const ENVIRONMENT_VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/u; const MCP_SERVER_NAME = /^[A-Za-z0-9_-]+$/u; function loopbackHostname(hostname: string): boolean { @@ -374,31 +388,53 @@ export function selectPiMcpServers( } /** - * Read the MCP servers from the runtime's mcp.json, expanding each HTTP header's - * `${NAME}` references from the runtime's environment, then the adapter's, as - * selectPiMcpServers validated them. + * A literal in Pi's configuration-value syntax, which Pi's terminal UI applies to + * mcp.json stdio `env` values and HTTP header values: a leading `!` runs a shell + * command and `$NAME` or `${NAME}` expands a variable, while `$$` and `$!` are a + * literal `$` and `!`. The SDK session passes these values literally. */ -async function readMcpServers( - agentDir: string, - configuredEnvironment: Record, - parentEnvironment: NodeJS.ProcessEnv, -): Promise> { - let text: string; - try { - text = await readFile(join(agentDir, "mcp.json"), "utf8"); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") return {}; - throw error; - } - const servers = (JSON.parse(text) as { mcpServers: Record }).mcpServers; +export function piConfigLiteral(value: string): string { + const escaped = value.replaceAll("$", () => "$$"); + return escaped.startsWith("!") ? `$${escaped}` : escaped; +} + +/** + * A Fabric MCP header value in Pi's configuration-value syntax: Fabric's `${NAME}` + * references stay references, which Pi's terminal UI resolves from its own + * environment, and everything else is literal. + */ +function piConfigHeader(value: string): string { + let result = ""; + let index = 0; + for (const match of value.matchAll(MCP_ENV_REFERENCE)) { + result += piConfigLiteral(value.slice(index, match.index)); + result += match[0]; + index = match.index + match[0].length; + } + return result + piConfigLiteral(value.slice(index)); +} + +/** + * The MCP servers as Pi's terminal UI reads them from mcp.json: the SDK session's + * servers with stdio `env` values and HTTP header values escaped for Pi's + * configuration-value syntax, so both paths read the same values and none runs a + * shell command. + */ +function piNativeMcpServers(servers: Record): Record { return Object.fromEntries(Object.entries(servers).map(([name, server]) => { - if (!("headers" in server) || server.headers === undefined) return [name, server]; - const headers = Object.fromEntries(Object.entries(server.headers).map(([header, value]) => { - const expanded = expandMcpHeader(value, configuredEnvironment, parentEnvironment); - validateMcpHeader(header, expanded); - return [header, expanded]; - })); - return [name, { ...server, headers }]; + if ("headers" in server && server.headers !== undefined) { + const headers = Object.fromEntries( + Object.entries(server.headers).map(([header, value]) => [header, piConfigHeader(value)]), + ); + return [name, { ...server, headers }]; + } + if ("env" in server && server.env !== undefined) { + const env = Object.fromEntries( + Object.entries(server.env).map(([variable, value]) => [variable, piConfigLiteral(value)]), + ); + return [name, { ...server, env }]; + } + return [name, server]; })); } @@ -719,7 +755,7 @@ export interface PiPreparedConfiguration { skillPaths: string[]; /** The configured Fabric module tools, loaded. */ customTools: ToolDefinition[]; - /** The MCP servers from the agent directory's mcp.json, with header references expanded. */ + /** The MCP servers for the SDK session, with header references expanded; never written to disk. */ mcpServers: Record; } @@ -743,13 +779,16 @@ export async function preparePiConfiguration(input: AdapterStartInput): Promise< }, ); } - // Validated here, before anything starts; mcp.json keeps header references unexpanded. - const mcpConfiguration = selectPiMcpServers( - input.config, - input.runtimeContext.environment.env ?? {}, - process.env, - { expandHeaders: false }, + // Validated here, before anything starts. The SDK session gets the servers in memory with + // header references expanded; mcp.json, which only Pi's terminal UI reads, keeps them as + // references in Pi's own syntax. + const environment = input.runtimeContext.environment.env ?? {}; + const mcpServers = selectPiMcpServers(input.config, environment, process.env); + const nativeMcpServers = piNativeMcpServers( + selectPiMcpServers(input.config, environment, process.env, { expandHeaders: false }), ); + const terminal = terminalEnabled(input.config); + const keepState = keepsState(input); const pi = await loadPiSdk(); let workspace: string; try { @@ -765,6 +804,14 @@ export async function preparePiConfiguration(input: AdapterStartInput): Promise< if (apiKeyEnv === undefined || apiKeyEnv === null || apiKeyEnv.length === 0) { throw new LifecycleError("pi_api_key_env_required", "The selected Pi model requires api_key_env"); } + if (terminal && !ENVIRONMENT_VARIABLE_NAME.test(apiKeyEnv)) { + // Pi's terminal UI reads the key through a ${NAME} reference in models.json. + throw new LifecycleError( + "pi_api_key_env_invalid", + "Pi's terminal interface requires api_key_env to be a valid environment variable name", + { metadata: { field: "models.api_key_env" } }, + ); + } const apiKey = credentialValue(input, apiKeyEnv); if (apiKey === undefined || apiKey.length === 0) { throw new LifecycleError("pi_credential_missing", `Credential environment variable ${apiKeyEnv} is not set`); @@ -800,38 +847,86 @@ export async function preparePiConfiguration(input: AdapterStartInput): Promise< catalogEntry.maxTokens ?? 0, catalogEntry.contextWindow ?? 0, ); - const configuration: PiNativeConfiguration = { - agentDir: agentDirectory(runtimeDirectory(input)), - sessionDir: sessionDirectory(runtimeDirectory(input)), - keepState: keepsState(input), - workspace, - provider: selected.provider, - ...(providerBaseUrl === undefined ? {} : { baseUrl: providerBaseUrl }), - model: modelDefinition as Record, - apiKeyEnv, - compactionReserveTokens, - extensionPaths: [...extensionPaths], - skillPaths, - ...(systemInstruction?.content === undefined ? {} : { systemPrompt: systemInstruction.content }), - toolsEnabled: input.config.tools?.enabled, - toolsBlocked: input.config.tools?.blocked ?? [], - customTools: await Promise.all( - Object.entries(input.config.tools?.definitions ?? {}).map(async ([name, definition]) => ({ - name, - ...(await resolveToolModule(workspace, definition.ref)), - settings: definition.settings ?? {}, - })), - ), - mcpServers: mcpConfiguration, - }; + const customToolModules = await Promise.all( + Object.entries(input.config.tools?.definitions ?? {}).map(async ([name, definition]) => ({ + name, + ...(await resolveToolModule(workspace, definition.ref)), + settings: definition.settings ?? {}, + })), + ); + // Without the terminal interface or kept state no other process reads Pi's files, so, as + // before the files were shared, they live in a private temporary directory that stop removes. + const ephemeral = !terminal && !keepState; + let runtimeDir: string; + try { + runtimeDir = ephemeral ? await mkdtemp(join(tmpdir(), "nemo-fabric-pi-")) : runtimeDirectory(input); + } catch (error) { + throw directoryUnavailable(error); + } + try { + return await writeConfiguration({ + pi, + selected, + apiKey, + mcpServers, + extensionPaths, + skillPaths, + customTools, + configuration: { + runtimeDir, + ephemeral, + agentDir: agentDirectory(runtimeDir), + sessionDir: sessionDirectory(runtimeDir), + keepState, + workspace, + provider: selected.provider, + ...(providerBaseUrl === undefined ? {} : { baseUrl: providerBaseUrl }), + model: modelDefinition as Record, + apiKeyEnv, + compactionReserveTokens, + extensionPaths: [...extensionPaths], + skillPaths, + ...(systemInstruction?.content === undefined ? {} : { systemPrompt: systemInstruction.content }), + toolsEnabled: input.config.tools?.enabled, + toolsBlocked: input.config.tools?.blocked ?? [], + customTools: customToolModules, + mcpServers: nativeMcpServers, + }, + }); + } catch (error) { + if (ephemeral) await rm(runtimeDir, { recursive: true, force: true }).catch(() => undefined); + throw error; + } +} +function directoryUnavailable(error: unknown): LifecycleError { + return new LifecycleError("pi_runtime_directory_unavailable", "Pi's runtime directory could not be written", { + metadata: { cause: error instanceof Error ? error.message : String(error) }, + }); +} + +/** Write the configuration to its agent directory and load the selected model from those files. */ +async function writeConfiguration(options: { + pi: PiSdkModules; + selected: AgentModelConfig; + apiKey: string; + mcpServers: Record; + extensionPaths: string[]; + skillPaths: string[]; + customTools: ToolDefinition[]; + configuration: PiNativeConfiguration; +}): Promise { + const { pi, selected, apiKey, configuration } = options; // Pi's own files are the configuration: the SDK session loads them as Pi's CLI and terminal UI do. - const agentDir = configuration.agentDir; - await writeAgentDirectory(configuration); + try { + await writeAgentDirectory(configuration); + } catch (error) { + throw directoryUnavailable(error); + } const modelRuntime = await pi.ModelRuntime.create({ // The key stays in memory; models.json only names its variable. credentials: new pi.InMemoryCredentialStore(), - modelsPath: join(agentDir, "models.json"), + modelsPath: join(configuration.agentDir, "models.json"), allowModelNetwork: false, refreshOnCreate: false, }); @@ -858,10 +953,14 @@ export async function preparePiConfiguration(input: AdapterStartInput): Promise< if (model === undefined) { throw new LifecycleError("pi_model_unknown", "The selected provider and model are not present in Pi's catalog"); } - const mcpServers = await readMcpServers( - agentDir, - input.runtimeContext.environment.env ?? {}, - process.env, - ); - return { pi, configuration, modelRuntime, model, extensionPaths, skillPaths, customTools, mcpServers }; + return { + pi, + configuration, + modelRuntime, + model, + extensionPaths: options.extensionPaths, + skillPaths: options.skillPaths, + customTools: options.customTools, + mcpServers: options.mcpServers, + }; } diff --git a/adapters/typescript/pi/src/pi-sdk.ts b/adapters/typescript/pi/src/pi-sdk.ts index d5f2e30ae..4d6eaa03e 100644 --- a/adapters/typescript/pi/src/pi-sdk.ts +++ b/adapters/typescript/pi/src/pi-sdk.ts @@ -5,6 +5,7 @@ // runtime's Pi configuration (native-configuration.ts), with the model key in // memory, MCP connections the session tracks, and Relay capture. +import { rm } from "node:fs/promises"; import { homedir } from "node:os"; import { join, resolve } from "node:path"; @@ -255,6 +256,13 @@ function unsupportedSessionAction(name: string): never { throw new LifecycleError("pi_unsupported_session_operation", `Pi session operation ${name} is not supported`); } +/** Remove the runtime directory when it is a private temporary one (no terminal interface or kept state). */ +async function removeEphemeralDirectory(configuration: PiNativeConfiguration): Promise { + if (configuration.ephemeral) { + await rm(configuration.runtimeDir, { recursive: true, force: true }); + } +} + class PiSdkSessionHandle implements PiSessionHandle { readonly relay?: PiRelayRuntime; private readonly session: AgentSession; @@ -378,28 +386,32 @@ class PiSdkSessionHandle implements PiSessionHandle { return; } this.stopped = true; - // The runtime's agent directory stays: it holds no secrets, and like other adapters' - // runtime directories it remains under the artifact root for inspection. + // A temporary runtime directory goes with the session. Otherwise it stays, as the other + // adapters' runtime directories do: the terminal UI's conversations, or the agent's kept state. let failure: unknown; try { - await this.session.abort(); - } catch (error) { - failure = error; - } - try { - await this.session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" }); - } catch (error) { - failure ??= error; - } - try { - this.unsubscribeTurnCounter(); - } catch (error) { - failure ??= error; - } - try { - this.session.dispose(); - } catch (error) { - failure ??= error; + try { + await this.session.abort(); + } catch (error) { + failure = error; + } + try { + await this.session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" }); + } catch (error) { + failure ??= error; + } + try { + this.unsubscribeTurnCounter(); + } catch (error) { + failure ??= error; + } + try { + this.session.dispose(); + } catch (error) { + failure ??= error; + } + } finally { + await removeEphemeralDirectory(this.configuration); } if (failure !== undefined) { throw failure; @@ -463,6 +475,8 @@ export class PiSdkSessionFactory implements PiSessionFactory { noThemes: true, // The system prompt is /SYSTEM.md, which writeAgentDirectory wrote when one is configured. noContextFiles: true, + // Discovery would append /APPEND_SYSTEM.md, which FabricConfig never configures. + appendSystemPrompt: [], }); await resourceLoader.reload(); const extensionResult = resourceLoader.getExtensions(); @@ -574,6 +588,9 @@ export class PiSdkSessionFactory implements PiSessionFactory { await relay?.stop().catch(() => { process.stderr.write("NeMo Relay cleanup failed after Pi adapter startup error\n"); }); + if (handle === undefined) { + await removeEphemeralDirectory(configuration); + } throw error; } } diff --git a/adapters/typescript/pi/src/terminal.ts b/adapters/typescript/pi/src/terminal.ts index cb4cd2810..2f43e3566 100644 --- a/adapters/typescript/pi/src/terminal.ts +++ b/adapters/typescript/pi/src/terminal.ts @@ -158,6 +158,13 @@ import { join } from "node:path"; const DESCRIPTOR = ${JSON.stringify(descriptor)}; const CLIENTS = ${JSON.stringify(clients)}; const RUNTIME_ID = ${JSON.stringify(runtimeId)}; +const ENTRY = join(CLIENTS, String(process.pid)); + +// Pi reruns extension factories when a person switches sessions (/new, /resume, +// /fork), so one process-wide heartbeat serves every session, and it holds only +// the current session's context. +const STATE = Symbol.for("nemo-fabric.pi.terminal-supervisor"); +const supervisor = (globalThis[STATE] ??= { context: undefined, stopping: false, timer: undefined }); function published() { try { @@ -167,32 +174,43 @@ function published() { } } -export default function (pi) { - const entry = join(CLIENTS, String(process.pid)); - let context; - let stopping = false; - const beat = () => { - if (stopping) return; - if (!published()) { - stopping = true; - clearInterval(timer); - context?.ui?.notify?.("The NeMo Fabric runtime stopped; closing Pi.", "warning"); - // The terminal UI acts on shutdown() at once; other modes defer it until a - // command finishes, so fall back to SIGTERM, which Pi also handles in order. - setTimeout(() => process.kill(process.pid, "SIGTERM"), ${TERMINAL_SELF_TERMINATE_MS}); - context?.shutdown(); - return; +function beat() { + if (supervisor.stopping) return; + if (!published()) { + supervisor.stopping = true; + clearInterval(supervisor.timer); + // The terminal UI acts on shutdown() at once; other modes defer it until a + // command finishes, so fall back to SIGTERM, which Pi also handles in order. + setTimeout(() => process.kill(process.pid, "SIGTERM"), ${TERMINAL_SELF_TERMINATE_MS}); + try { + supervisor.context?.ui?.notify?.("The NeMo Fabric runtime stopped; closing Pi.", "warning"); + supervisor.context?.shutdown(); + } catch { + // A context Pi has already torn down; the SIGTERM above still closes Pi. } + return; + } + try { mkdirSync(CLIENTS, { recursive: true, mode: 0o700 }); - writeFileSync(entry, "", { mode: 0o600 }); - }; - const timer = setInterval(beat, ${TERMINAL_HEARTBEAT_MS}); - timer.unref?.(); - process.once("exit", () => rmSync(entry, { force: true })); + writeFileSync(ENTRY, "", { mode: 0o600 }); + } catch { + // Retried on the next heartbeat; the runtime may be withdrawing the interface. + } +} + +export default function (pi) { + if (supervisor.timer === undefined) { + supervisor.timer = setInterval(beat, ${TERMINAL_HEARTBEAT_MS}); + supervisor.timer.unref?.(); + process.once("exit", () => rmSync(ENTRY, { force: true })); + } pi.on("session_start", (_event, ctx) => { - context = ctx; + supervisor.context = ctx; beat(); }); + pi.on("session_shutdown", () => { + supervisor.context = undefined; + }); } `; } @@ -531,9 +549,17 @@ class PiTerminalInterface implements PiSessionFactory { "The Pi session did not report the configuration its terminal UI needs", ); } - interfaceHandle = await PiTerminal.prepare(handle.configuration, runtimeDirectory(input), - input.runtimeContext.runtime_id, process.execPath, await resolvePiCli(), handle.relay); - await interfaceHandle.publish(); + const cli = await resolvePiCli(); + try { + interfaceHandle = await PiTerminal.prepare(handle.configuration, handle.configuration.runtimeDir, + input.runtimeContext.runtime_id, process.execPath, cli, handle.relay); + await interfaceHandle.publish(); + } catch (error) { + if (error instanceof LifecycleError) throw error; + throw new LifecycleError("pi_terminal_unavailable", "Pi's terminal interface files could not be written", { + metadata: { cause: error instanceof Error ? error.message : String(error) }, + }); + } return new PiTerminalSessionHandle(handle, interfaceHandle); } catch (error) { await interfaceHandle?.withdraw().catch(() => { diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index ed346b811..9b4fed89b 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -243,15 +243,24 @@ test("the SDK session runs on the agent directory's files and ignores interfaces } }); -test("without interfaces.terminal the adapter writes no launcher or tui.json", { skip }, async () => { +test("without interfaces.terminal or keep_state, Pi's files live in a temporary directory that stop removes", { skip }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-off-"))); const { server, url } = await modelServer(); let session; try { session = await sessionFactory().create(startInput(workspace, url)); - const directory = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal"); - assert.equal(await exists(join(directory, "pi-agent", "models.json")), true); - assert.equal(await exists(join(directory, "interfaces")), false); + const { runtimeDir, ephemeral } = session.configuration; + assert.equal(ephemeral, true); + assert.equal(runtimeDir.startsWith(join(await realpath(tmpdir()), "nemo-fabric-pi-")) + || runtimeDir.startsWith(join(tmpdir(), "nemo-fabric-pi-")), true, runtimeDir); + assert.equal((await stat(runtimeDir)).mode & 0o777, 0o700); + assert.equal(await exists(join(runtimeDir, "pi-agent", "models.json")), true); + assert.equal(await exists(join(runtimeDir, "interfaces")), false); + // Nothing is written under the artifact root. + assert.equal(await exists(join(workspace, "artifacts")), false); + await session.stop(); + session = undefined; + assert.equal(await exists(runtimeDir), false); } finally { await session?.stop(); server.closeAllConnections(); @@ -291,7 +300,7 @@ test("the launcher opens Pi on the runtime's model, key variable and system prom assert.doesNotMatch(await readFile(file, "utf8"), new RegExp(RUNTIME_KEY), `${file} holds the runtime's key`); } const models = JSON.parse(await readFile(join(directory, "pi-agent", "models.json"), "utf8")); - assert.equal(models.providers["fabric-test"].apiKey, "$TEST_API_KEY"); + assert.equal(models.providers["fabric-test"].apiKey, "${TEST_API_KEY}"); assert.equal(models.providers["fabric-test"].baseUrl, url); const run = await launch(launcher, home, ["--print", "say hello"]).exited; @@ -495,6 +504,65 @@ test("a native-only runtime writes Pi's files and the launcher but runs no SDK s } }); +test("mcp.json escapes MCP values so Pi's terminal UI reads them as the SDK session does", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-mcp-"))); + const { server, url } = await modelServer(); + // Pi's own resolver for mcp.json stdio env and header values. + const { resolveConfigValueOrThrow } = await import( + new URL("core/resolve-config-value.js", import.meta.resolve("@earendil-works/pi-coding-agent")).href + ); + const env = { PASSWORD: "p@ss$word", COMMAND: "!echo injected", DOLLARS: "$$ and $!", PLAIN: "plain" }; + let session; + try { + const input = startInput(workspace, url, { sdk: { enabled: false }, interfaces: { terminal: {} } }); + input.config.mcp = { + servers: { + local: { transport: "stdio", url: "mcp-server", env }, + remote: { + transport: "streamable-http", + url: "https://mcp.example.com/mcp", + custom_headers: { Authorization: "Bearer ${MCP_TOKEN}", "X-Literal": "$literal ${MCP_TOKEN}!" }, + }, + }, + }; + input.runtimeContext.environment.env.MCP_TOKEN = "runtime-token"; + session = await sessionFactory().create(input); + const written = JSON.parse(await readFile(join(session.configuration.agentDir, "mcp.json"), "utf8")).mcpServers; + // The runtime's header values stay references; the file holds none of them. + assert.doesNotMatch(JSON.stringify(written), /runtime-token/); + // The terminal UI resolves references from the launcher's environment. + process.env.MCP_TOKEN = "launcher-token"; + try { + const resolved = Object.fromEntries( + Object.entries(written.local.env).map(([name, value]) => [name, resolveConfigValueOrThrow(value, name)]), + ); + assert.deepEqual(resolved, env); + assert.equal(resolveConfigValueOrThrow(written.remote.headers.Authorization, "authorization"), "Bearer launcher-token"); + assert.equal(resolveConfigValueOrThrow(written.remote.headers["X-Literal"], "literal"), "$literal launcher-token!"); + } finally { + delete process.env.MCP_TOKEN; + } + } finally { + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + +test("the terminal interface refuses a model key variable Pi can't reference", { skip }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-key-name-"))); + try { + const input = startInput(workspace, "http://127.0.0.1:9/v1", { interfaces: { terminal: {} } }); + input.config.models.default.api_key_env = "TEST-API-KEY"; + input.runtimeContext.environment.env["TEST-API-KEY"] = RUNTIME_KEY; + await assert.rejects(sessionFactory().create(input), { code: "pi_api_key_env_invalid" }); + assert.equal(await exists(join(workspace, "artifacts")), false); + } finally { + await rm(workspace, { recursive: true, force: true }); + } +}); + test("a native-only runtime with Relay runs the gateway, and the launcher loads the Relay extension on it", { skip }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-relay-"))); const extensionPath = join(workspace, "relay-extension"); @@ -586,7 +654,7 @@ test("with keep_state, a terminal conversation from one runtime continues in the test("with keep_state, a start replaces what an earlier runtime left but keeps Pi's credentials", { skip, timeout: 60_000 }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-kept-clean-"))); - const { server, url } = await modelServer(); + const { server, requests, url } = await modelServer(); const state = join(workspace, "artifacts", ".fabric", "state", "nvidia.fabric.pi", "terminal-test"); let session; try { @@ -594,6 +662,8 @@ test("with keep_state, a start replaces what an earlier runtime left but keeps P // The runtime ends without stop, as when its host is killed; Pi saved a login of its own. session = undefined; await writeFile(join(state, "pi-agent", "auth.json"), "{\"other\":{\"type\":\"api_key\",\"key\":\"saved\"}}\n", { mode: 0o600 }); + // A file Pi would append to the system prompt, left by a person or an agent. + await writeFile(join(state, "pi-agent", "APPEND_SYSTEM.md"), "INJECTED-APPEND\n", { mode: 0o600 }); await mkdir(join(state, "interfaces", "tui.clients"), { recursive: true }); await writeFile(join(state, "interfaces", "tui.clients", "999999"), ""); @@ -609,6 +679,10 @@ test("with keep_state, a start replaces what an earlier runtime left but keeps P assert.equal(session.configuration.systemPrompt, undefined); // Credentials Pi saved itself survive. assert.match(await readFile(join(state, "pi-agent", "auth.json"), "utf8"), /saved/); + // An appended system prompt FabricConfig didn't configure doesn't survive or reach the model. + assert.equal(await exists(join(state, "pi-agent", "APPEND_SYSTEM.md")), false); + await session.prompt("hello"); + assert.doesNotMatch(JSON.stringify(requests.at(-1).body.messages), /INJECTED-APPEND/); } finally { await session?.stop(); server.closeAllConnections(); diff --git a/tests/adapters/test_pi_adapter.py b/tests/adapters/test_pi_adapter.py index fb52d53b1..5b6ae134a 100644 --- a/tests/adapters/test_pi_adapter.py +++ b/tests/adapters/test_pi_adapter.py @@ -285,3 +285,48 @@ def test_pi_descriptor_rejects_relay_when_support_is_not_declared(tmp_path: Path def test_pi_model_schema_requires_a_credential_name(): with pytest.raises(FabricConfigError, match="api_key_env"): Fabric().plan(config(api_key_env=None), base_dir=ROOT) + + +def config_with_settings(settings: dict[str, object]) -> FabricConfig: + mapping = config().to_mapping() + mapping["harness"]["settings"] = settings + return FabricConfig.from_mapping(mapping) + + +@pytest.mark.parametrize( + "settings", + [ + pytest.param({"interfaces": {"terminal": {}}}, id="terminal-and-sdk"), + pytest.param( + {"sdk": {"enabled": False}, "interfaces": {"terminal": {}}}, + id="terminal-only", + ), + pytest.param( + {"sdk": {"enabled": False}, "interfaces": {"terminal": {"enabled": True}}}, + id="terminal-only-explicit", + ), + pytest.param({"interfaces": {"terminal": {"enabled": False}}}, id="sdk-only"), + ], +) +def test_pi_descriptor_plans_execution_paths(settings: dict[str, object]): + plan = Fabric().plan(config_with_settings(settings), base_dir=ROOT) + + assert plan.adapter_descriptor["descriptor"]["adapter_id"] == "nvidia.fabric.pi" + + +@pytest.mark.parametrize( + "settings", + [ + pytest.param({"sdk": {"enabled": False}}, id="no-execution-path"), + pytest.param( + {"sdk": {"enabled": False}, "interfaces": {"terminal": {"enabled": False}}}, + id="disabled-terminal-is-not-execution", + ), + pytest.param({"sdk": {"enabled": "false"}}, id="sdk-not-boolean"), + pytest.param({"interfaces": {"terminal": {"port": 9119}}}, id="terminal-takes-no-port"), + pytest.param({"interfaces": {"dashboard": {}}}, id="unsupported-interface"), + ], +) +def test_pi_descriptor_rejects_invalid_execution_settings(settings: dict[str, object]): + with pytest.raises(FabricConfigError): + Fabric().plan(config_with_settings(settings), base_dir=ROOT) From f85916e03590d1b4a9a0ae73387dd0951f0a868a Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Tue, 1 Dec 2026 17:00:46 -0800 Subject: [PATCH 03/25] fix: harden Pi terminal interface cleanup and cover its tools - Warn, by name only, which environment.env variables Pi's terminal UI doesn't inherit, since the launcher holds no secrets. - Write mcp.json only with the terminal interface; the SDK session never reads it. - Don't signal the PID of a terminal UI already seen to exit, ignore heartbeats from the future, and keep a failed withdraw retryable. - Report withdraw failures as pi_interface_cleanup_failed alongside session cleanup failures, and map session-directory errors. - Reapply owner-only modes when rewriting files in a kept directory. - Test that the terminal UI gets the SDK session's module tools and MCP servers end to end. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- adapters/typescript/pi/src/agent-directory.ts | 7 +- .../typescript/pi/src/native-configuration.ts | 5 +- adapters/typescript/pi/src/pi-sdk.ts | 7 +- adapters/typescript/pi/src/terminal.ts | 59 +++++++-- adapters/typescript/pi/test/terminal.test.mjs | 119 +++++++++++++++++- 5 files changed, 178 insertions(+), 19 deletions(-) diff --git a/adapters/typescript/pi/src/agent-directory.ts b/adapters/typescript/pi/src/agent-directory.ts index b0012a927..6ff297d2d 100644 --- a/adapters/typescript/pi/src/agent-directory.ts +++ b/adapters/typescript/pi/src/agent-directory.ts @@ -14,7 +14,7 @@ // each start rewrites these files from FabricConfig and removes the ones it no // longer configures; files Pi writes itself, such as auth.json, stay. -import { mkdir, rm, writeFile } from "node:fs/promises"; +import { chmod, mkdir, rm, writeFile } from "node:fs/promises"; import { join, resolve } from "node:path"; import type { JsonObject } from "nemo-fabric-adapter-contract"; @@ -91,6 +91,8 @@ export async function privateDirectory(path: string): Promise { async function writePrivate(path: string, contents: string): Promise { 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); } /** Write Pi's configuration files for the runtime. */ @@ -100,7 +102,8 @@ export async function writeAgentDirectory(configuration: PiNativeConfiguration): 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. - if (Object.keys(configuration.mcpServers).length > 0) { + // 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`, diff --git a/adapters/typescript/pi/src/native-configuration.ts b/adapters/typescript/pi/src/native-configuration.ts index 391964fe4..da2cc8bdb 100644 --- a/adapters/typescript/pi/src/native-configuration.ts +++ b/adapters/typescript/pi/src/native-configuration.ts @@ -34,6 +34,8 @@ export interface PiNativeConfiguration { * other process reads it without the terminal interface or runtime.keep_state. */ ephemeral: boolean; + /** Whether the runtime offers Pi's terminal UI, the only reader of mcp.json. */ + terminal: boolean; /** The runtime's Pi agent directory, holding this configuration as Pi's own files. */ agentDir: string; /** Pi's session directory beside the agent directory, where conversations are kept on disk. */ @@ -875,6 +877,7 @@ export async function preparePiConfiguration(input: AdapterStartInput): Promise< configuration: { runtimeDir, ephemeral, + terminal, agentDir: agentDirectory(runtimeDir), sessionDir: sessionDirectory(runtimeDir), keepState, @@ -899,7 +902,7 @@ export async function preparePiConfiguration(input: AdapterStartInput): Promise< } } -function directoryUnavailable(error: unknown): LifecycleError { +export function directoryUnavailable(error: unknown): LifecycleError { return new LifecycleError("pi_runtime_directory_unavailable", "Pi's runtime directory could not be written", { metadata: { cause: error instanceof Error ? error.message : String(error) }, }); diff --git a/adapters/typescript/pi/src/pi-sdk.ts b/adapters/typescript/pi/src/pi-sdk.ts index 4d6eaa03e..697611c72 100644 --- a/adapters/typescript/pi/src/pi-sdk.ts +++ b/adapters/typescript/pi/src/pi-sdk.ts @@ -29,6 +29,7 @@ import { } from "./relay.js"; import { containedBy, + directoryUnavailable, PI_BUILTIN_TOOL_NAMES, preparePiConfiguration, type PiModelRuntime, @@ -434,10 +435,10 @@ export class PiSdkSessionFactory implements PiSessionFactory { const { pi, configuration, modelRuntime, model, extensionPaths, skillPaths, customTools, mcpServers } = await preparePiConfiguration(input); const { workspace, agentDir } = configuration; - const settings = pi.SettingsManager.create(workspace, agentDir, { projectTrusted: false }); let relay: PiRelayRuntime | undefined; let handle: PiSdkSessionHandle | undefined; try { + const settings = pi.SettingsManager.create(workspace, agentDir, { projectTrusted: false }); relay = await this.relayFactory.start(input, { api: model.api, baseUrl: model.baseUrl, @@ -536,7 +537,9 @@ export class PiSdkSessionFactory implements PiSessionFactory { // With runtime.keep_state the conversation is kept beside the terminal UI's, so a // later runtime's terminal UI can resume it; otherwise it lives only in memory. sessionManager: configuration.keepState - ? pi.SessionManager.create(workspace, await privateDirectory(configuration.sessionDir)) + ? pi.SessionManager.create(workspace, await privateDirectory(configuration.sessionDir).catch((error: unknown) => { + throw directoryUnavailable(error); + })) : pi.SessionManager.inMemory(workspace), settingsManager: settings, customTools, diff --git a/adapters/typescript/pi/src/terminal.ts b/adapters/typescript/pi/src/terminal.ts index 2f43e3566..63910971a 100644 --- a/adapters/typescript/pi/src/terminal.ts +++ b/adapters/typescript/pi/src/terminal.ts @@ -16,7 +16,7 @@ // so terminal conversations in pi-sessions outlive the runtime, and a start // first retires the terminal interface a runtime that ended without stop left. -import { access, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; +import { access, chmod, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -236,6 +236,8 @@ export function toolBridgeExtension(workspace: string, tools: readonly PiNativeC async function writePrivate(path: string, contents: string, mode = 0o600): Promise { await writeFile(path, contents, { mode }); + // writeFile applies the mode only to a new file; a kept directory can hold an older one. + await chmod(path, mode); } /** @@ -351,8 +353,9 @@ export class PiTerminal { async withdraw(): Promise { if (this.withdrawn) return; await rm(this.descriptorPath, { force: true }); - this.withdrawn = true; + // Withdrawn only once the terminal UIs are closed, so a retried stop closes them again. await closeTerminals(this.clients); + this.withdrawn = true; } } @@ -365,12 +368,17 @@ async function closeTerminals(clients: string): Promise { const terminals = await liveTerminals(clients); if (terminals.length > 0) { signal(terminals, "SIGTERM"); + const exited = new Set(); const deadline = Date.now() + TERMINAL_STOP_GRACE_MS; - while (Date.now() < deadline && terminals.some(alive)) { + for (;;) { + for (const pid of terminals) if (!alive(pid)) exited.add(pid); + if (exited.size === terminals.length || Date.now() >= deadline) break; await new Promise((resolve) => setTimeout(resolve, 100)); } - // The group too: processes the terminal UI's tools started can outlive it. - signal(terminals, "SIGKILL"); + // The group too: processes the terminal UI's tools started can outlive it. A terminal UI + // seen to exit gets no signal of its own, since its PID may now belong to another process. + signal(terminals.filter((pid) => !exited.has(pid)), "SIGKILL"); + signal(terminals.filter((pid) => exited.has(pid)), "SIGKILL", { groupOnly: true }); } await rm(clients, { recursive: true, force: true }); } @@ -388,7 +396,9 @@ async function liveTerminals(clients: string): Promise { const path = join(clients, name); const pid = Number(name); try { - const fresh = Date.now() - (await stat(path)).mtimeMs < TERMINAL_HEARTBEAT_STALE_MS; + // A heartbeat from the future (clock skew on a shared volume) is not current. + const age = Date.now() - (await stat(path)).mtimeMs; + const fresh = age >= -TERMINAL_HEARTBEAT_MS && age < TERMINAL_HEARTBEAT_STALE_MS; if (Number.isSafeInteger(pid) && pid > 1 && fresh && alive(pid)) { live.push(pid); continue; @@ -436,10 +446,11 @@ function alive(pid: number): boolean { * OpenShell denies group signals (EPERM), and a terminal UI that doesn't lead its * own group has none under its PID (ESRCH). */ -function signal(pids: readonly number[], name: NodeJS.Signals): void { +function signal(pids: readonly number[], name: NodeJS.Signals, options: { groupOnly?: boolean } = {}): void { for (const pid of pids) { - // Once the terminal UI has exited, its PID may belong to another process. - const fallback = alive(pid); + // Signal the process itself only while it still runs, and never for a terminal UI + // already seen to exit: its PID may belong to another process by now. + const fallback = options.groupOnly !== true && alive(pid); try { process.kill(-pid, name); } catch { @@ -453,6 +464,21 @@ function signal(pids: readonly number[], name: NodeJS.Signals): void { } } +/** + * The launcher holds no secrets, so Pi's terminal UI doesn't inherit the runtime's + * `environment.env`: its tools, its stdio MCP servers, and MCP header `${NAME}` + * references see the environment that runs the launcher. A warning names those + * variables, never their values, so a person can set them there. + */ +export function terminalEnvironmentWarnings(input: AdapterStartInput): string[] { + const names = Object.keys(input.runtimeContext.environment.env ?? {}).sort(); + if (names.length === 0) return []; + return [ + `Pi's terminal UI doesn't inherit environment.env; set ${names.join(", ")} in the environment ` + + "that runs the launcher if the terminal UI, its tools or its MCP servers need them", + ]; +} + /** Withdraws the terminal interface before the embedded session stops. */ export class PiTerminalSessionHandle implements PiSessionHandle { private readonly inner: PiSessionHandle; @@ -501,9 +527,17 @@ export class PiTerminalSessionHandle implements PiSessionHandle { try { await this.terminal.withdraw(); } catch (error) { - failure = error; + failure = new LifecycleError("pi_interface_cleanup_failed", "Pi's terminal interface could not be withdrawn", { + metadata: { cause: error instanceof Error ? error.message : String(error) }, + }); + } + try { + await this.inner.stop(); + } catch (error) { + failure = failure === undefined + ? error + : new AggregateError([failure, error], "Pi terminal interface and session cleanup failed"); } - await this.inner.stop(); if (failure !== undefined) throw failure; } } @@ -560,6 +594,9 @@ class PiTerminalInterface implements PiSessionFactory { metadata: { cause: error instanceof Error ? error.message : String(error) }, }); } + for (const warning of terminalEnvironmentWarnings(input)) { + process.stderr.write(`Pi warning: ${warning}\n`); + } return new PiTerminalSessionHandle(handle, interfaceHandle); } catch (error) { await interfaceHandle?.withdraw().catch(() => { diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index 9b4fed89b..b2050ee8c 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -12,7 +12,13 @@ import test from "node:test"; import { PiSdkSessionFactory } from "../dist/pi-sdk.js"; import { sdkEnabled } from "../dist/settings.js"; import { PiNativeOnlySessionFactory } from "../dist/native-only.js"; -import { launcherScript, terminalArguments, terminalEnabled, withTerminalInterface } from "../dist/terminal.js"; +import { + launcherScript, + terminalArguments, + terminalEnabled, + terminalEnvironmentWarnings, + withTerminalInterface, +} from "../dist/terminal.js"; const [major, minor] = process.versions.node.split(".").map(Number); const skip = major > 22 || (major === 22 && minor >= 19) ? false : "Pi requires Node >=22.19"; @@ -550,6 +556,113 @@ test("mcp.json escapes MCP values so Pi's terminal UI reads them as the SDK sess } }); +/** A minimal stdio MCP server whose one tool describes the MCP_SECRET value it received. */ +const MCP_SERVER = `import { createInterface } from "node:readline"; +const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n"); +createInterface({ input: process.stdin }).on("line", (line) => { + const message = JSON.parse(line); + if (message.method === "initialize") { + send({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: message.params.protocolVersion, + capabilities: { tools: {} }, serverInfo: { name: "fabric-test", version: "1" } } }); + } else if (message.method === "tools/list") { + send({ jsonrpc: "2.0", id: message.id, result: { tools: [{ name: "echo_secret", + description: "secret=" + JSON.stringify(process.env.MCP_SECRET), inputSchema: { type: "object", properties: {} } }] } }); + } else if (message.id !== undefined) { + send({ jsonrpc: "2.0", id: message.id, result: {} }); + } +}); +`; + +const TOOL_MODULE = `export default function ({ name, settings }) { + return { name, label: "Fabric tool", description: "settings=" + JSON.stringify(settings), + parameters: { type: "object", properties: {} }, + async execute() { return { content: [{ type: "text", text: "done" }], details: {} }; } }; +} +`; + +/** A FabricConfig with a module tool and a stdio MCP server, and every tool enabled. */ +async function toolsInput(workspace, url, settings) { + await writeFile(join(workspace, "fabric-tool.mjs"), TOOL_MODULE); + await writeFile(join(workspace, "mcp-server.mjs"), MCP_SERVER); + const input = startInput(workspace, url, settings); + input.config.tools = { + enabled: null, + blocked: [], + definitions: { fabric_tool: { kind: "module", ref: "fabric-tool.mjs", settings: { mode: "test" } } }, + }; + input.config.mcp = { + servers: { + local: { transport: "stdio", url: process.execPath, args: [join(workspace, "mcp-server.mjs")], + env: { MCP_SECRET: "a$b !c" } }, + }, + }; + return input; +} + +function toolDescriptions(request) { + return Object.fromEntries((request.body.tools ?? []).map((tool) => [tool.function.name, tool.function.description])); +} + +test("the terminal UI gets the SDK session's module tools and MCP servers", { skip, timeout: 90_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-tools-"))); + const home = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-tools-home-"))); + const { server, requests, url } = await modelServer(); + let session; + try { + session = await sessionFactory().create(await toolsInput(workspace, url, { interfaces: { terminal: {} } })); + await session.prompt("hello"); + const sdkTools = toolDescriptions(requests[0]); + assert.match(sdkTools.fabric_tool, /"mode":"test"/); + const mcpTool = Object.keys(sdkTools).find((name) => name.includes("echo_secret")); + assert.ok(mcpTool, JSON.stringify(Object.keys(sdkTools))); + assert.match(sdkTools[mcpTool], /secret="a\$b !c"/); + + const launcher = join(session.configuration.runtimeDir, "interfaces", "terminal"); + const run = await launch(launcher, home, ["--print", "say hello"]).exited; + assert.equal(run.code, 0, run.stderr); + // The terminal UI registers the same module tool and MCP tool, with the same MCP env value. + const terminalTools = toolDescriptions(requests[1]); + assert.equal(terminalTools.fabric_tool, sdkTools.fabric_tool); + assert.equal(terminalTools[mcpTool], sdkTools[mcpTool]); + } finally { + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + await rm(home, { recursive: true, force: true }); + } +}); + +test("without the terminal interface the runtime writes no mcp.json", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-no-mcp-file-"))); + const { server, url } = await modelServer(); + const state = join(workspace, "artifacts", ".fabric", "state", "nvidia.fabric.pi", "terminal-test"); + let session; + try { + const input = await toolsInput(workspace, url); + input.runtimeContext.state_dir = state; + session = await sessionFactory().create(input); + assert.equal(await exists(join(state, "pi-agent", "models.json")), true); + assert.equal(await exists(join(state, "pi-agent", "mcp.json")), false); + } finally { + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + +test("the terminal interface names, without values, the runtime variables its UI doesn't inherit", () => { + const input = startInput("/workspace", "http://127.0.0.1:9/v1"); + input.runtimeContext.environment.env = { TEST_API_KEY: RUNTIME_KEY, GITHUB_TOKEN: "ghp-secret" }; + const [warning, ...rest] = terminalEnvironmentWarnings(input); + assert.deepEqual(rest, []); + assert.match(warning, /GITHUB_TOKEN, TEST_API_KEY/); + assert.doesNotMatch(warning, /ghp-secret|runtime-key/); + input.runtimeContext.environment.env = {}; + assert.deepEqual(terminalEnvironmentWarnings(input), []); +}); + test("the terminal interface refuses a model key variable Pi can't reference", { skip }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-key-name-"))); try { @@ -799,9 +912,9 @@ test("a native-only runtime warns that Fabric's invocation stream doesn't reach const lines = warned.stderr.split("\n").filter((line) => line.includes("nemo-fabric-stream")); assert.equal(lines.length, 1, warned.stderr); assert.match(lines[0], /sdk\.enabled is false/); - // A sink of the caller's own still receives the terminal TUI's Relay events: no warning. + // A sink of the caller's own still receives the terminal TUI's Relay events: no sink warning. const quiet = await start([own]); - assert.doesNotMatch(quiet.stderr, /warning/i); + assert.doesNotMatch(quiet.stderr, /nemo-fabric-stream|ATOF/); } finally { await rm(workspace, { recursive: true, force: true }); } From 9f383cf28a63528fb386c781853a5290f5a68158 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Tue, 1 Dec 2026 17:13:46 -0800 Subject: [PATCH 04/25] fix: warn about Pi terminal records in streamed invocations - Warn when the SDK, the terminal interface and the nemo-fabric-stream Relay sink are combined: terminal UI records reach the same sink, so invoke_stream() output can lose or mix records once a terminal UI is used. - Clear inherited NeMo Relay Pi variables in the launcher before it exports the runtime's own. - Signal a terminal UI that registers while stop withdraws the interface. - Resolve an empty artifact root to /artifacts, as Hermes does. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- adapters/typescript/pi/src/agent-directory.ts | 3 +- adapters/typescript/pi/src/native-only.ts | 2 +- adapters/typescript/pi/src/relay.ts | 3 +- adapters/typescript/pi/src/terminal.ts | 34 ++++++++++++++++- adapters/typescript/pi/test/terminal.test.mjs | 37 +++++++++++++++++++ 5 files changed, 74 insertions(+), 5 deletions(-) diff --git a/adapters/typescript/pi/src/agent-directory.ts b/adapters/typescript/pi/src/agent-directory.ts index 6ff297d2d..56b226b52 100644 --- a/adapters/typescript/pi/src/agent-directory.ts +++ b/adapters/typescript/pi/src/agent-directory.ts @@ -32,7 +32,8 @@ export function runtimeDirectory(input: AdapterStartInput): string { if (typeof stateDir === "string" && stateDir.length > 0) return resolve(stateDir); const root = input.runtimeContext.artifacts.root; const artifactRoot = - root === undefined || root === null + // An unset or empty root is /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); diff --git a/adapters/typescript/pi/src/native-only.ts b/adapters/typescript/pi/src/native-only.ts index c99f91513..43f7d1007 100644 --- a/adapters/typescript/pi/src/native-only.ts +++ b/adapters/typescript/pi/src/native-only.ts @@ -55,7 +55,7 @@ class PiNativeOnlyHandle implements PiSessionHandle { } /** The Relay ATOF sink that the Python SDK adds for `start_runtime(..., streaming=True)`. */ -const FABRIC_STREAM_SINK = "nemo-fabric-stream"; +export const FABRIC_STREAM_SINK = "nemo-fabric-stream"; /** * Configured settings that only the embedded SDK session honors, each as the warning a diff --git a/adapters/typescript/pi/src/relay.ts b/adapters/typescript/pi/src/relay.ts index 88d6e099c..2a1954421 100644 --- a/adapters/typescript/pi/src/relay.ts +++ b/adapters/typescript/pi/src/relay.ts @@ -32,7 +32,8 @@ const RELAY_INSTALL_COMMAND = 'Install "nemo-relay-cli-bin>=0.9.0,<0.12.0" and ensure nemo-relay is on PATH'; const RELAY_EXTENSION_REMEDIATION = "set harness.settings.relay_extension_path to the Pi extension file or package directory from the installed NeMo Relay CLI release"; -const RELAY_ENV_NAMES = [ +/** The variables the Relay Pi extension reads; a process that loads it sets or clears each one. */ +export const RELAY_ENV_NAMES = [ "NEMO_RELAY_PI_COMMAND", "NEMO_RELAY_PI_GATEWAY_URL", "NEMO_RELAY_PI_OPENAI_UPSTREAM", diff --git a/adapters/typescript/pi/src/terminal.ts b/adapters/typescript/pi/src/terminal.ts index 63910971a..80ca749c6 100644 --- a/adapters/typescript/pi/src/terminal.ts +++ b/adapters/typescript/pi/src/terminal.ts @@ -25,7 +25,9 @@ import { LifecycleError, type AdapterStartInput } from "nemo-fabric-adapters-com import { keepsState, runtimeDirectory } from "./agent-directory.js"; import type { PiNativeConfiguration, PiNativeCustomTool } from "./native-configuration.js"; -import { PiNativeOnlySessionFactory } from "./native-only.js"; +import { FABRIC_STREAM_SINK, PiNativeOnlySessionFactory } from "./native-only.js"; +import { atofStreamSinkNames } from "./relay-config.js"; +import { RELAY_ENV_NAMES, type PiRelayRuntime } from "./relay.js"; import type { PiPromptOutcome, PiSessionFactory, PiSessionHandle } from "./runtime.js"; import { sdkEnabled, terminalEnabled } from "./settings.js"; @@ -137,6 +139,8 @@ export function launcherScript(options: { " echo 'This NeMo Fabric runtime is not running.' >&2", " exit 1", "fi", + // The Relay extension's variables come only from this runtime, never the person's shell. + `unset ${RELAY_ENV_NAMES.join(" ")}`, ...exports, `cd ${shellQuote(options.workspace)} || exit 1`, `exec ${[options.node, options.cli, ...options.args].map(shellQuote).join(" ")} "$@"`, @@ -380,6 +384,10 @@ async function closeTerminals(clients: string): Promise { signal(terminals.filter((pid) => !exited.has(pid)), "SIGKILL"); signal(terminals.filter((pid) => exited.has(pid)), "SIGKILL", { groupOnly: true }); } + // A terminal UI that registered while the attachment file was being removed closes itself + // on its next heartbeat; signal it too, so its tools' processes don't outlive the runtime. + const late = (await liveTerminals(clients)).filter((pid) => !terminals.includes(pid)); + signal(late, "SIGKILL"); await rm(clients, { recursive: true, force: true }); } @@ -479,6 +487,25 @@ export function terminalEnvironmentWarnings(input: AdapterStartInput): string[] ]; } +/** + * Terminal UIs send their Relay records through the runtime's gateway, which also feeds + * the ATOF sink that `start_runtime(..., streaming=True)` adds for `invoke_stream()`. + * The collector doesn't tell the SDK session's records from a terminal UI's, so with + * the SDK enabled a warning says that streamed invocations can lose or mix records once + * a terminal UI is used. + */ +export function terminalStreamingWarnings(sdk: boolean, relay: PiRelayRuntime | undefined): string[] { + if (!sdk || relay?.pluginConfig === undefined + || !atofStreamSinkNames(relay.pluginConfig).includes(FABRIC_STREAM_SINK)) { + return []; + } + return [ + `terminal UI turns reach the Relay ATOF sink ${FABRIC_STREAM_SINK} (start_runtime(..., streaming=True)), ` + + "so invoke_stream() output can lose records or include terminal UI records once a terminal UI is used; " + + "use invoke() or a separate runtime for streamed invocations", + ]; +} + /** Withdraws the terminal interface before the embedded session stops. */ export class PiTerminalSessionHandle implements PiSessionHandle { private readonly inner: PiSessionHandle; @@ -594,7 +621,10 @@ class PiTerminalInterface implements PiSessionFactory { metadata: { cause: error instanceof Error ? error.message : String(error) }, }); } - for (const warning of terminalEnvironmentWarnings(input)) { + for (const warning of [ + ...terminalEnvironmentWarnings(input), + ...terminalStreamingWarnings(sdkEnabled(input.config), handle.relay), + ]) { process.stderr.write(`Pi warning: ${warning}\n`); } return new PiTerminalSessionHandle(handle, interfaceHandle); diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index b2050ee8c..e7de17a73 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -17,8 +17,10 @@ import { terminalArguments, terminalEnabled, terminalEnvironmentWarnings, + terminalStreamingWarnings, withTerminalInterface, } from "../dist/terminal.js"; +import { runtimeDirectory } from "../dist/agent-directory.js"; const [major, minor] = process.versions.node.split(".").map(Number); const skip = major > 22 || (major === 22 && minor >= 19) ? false : "Pi requires Node >=22.19"; @@ -663,6 +665,41 @@ test("the terminal interface names, without values, the runtime variables its UI assert.deepEqual(terminalEnvironmentWarnings(input), []); }); +test("the terminal interface warns that streamed SDK invocations share Relay's stream sink", () => { + const sinks = (names) => ({ + pluginConfig: { + version: 1, + components: [{ kind: "observability", enabled: true, config: { atof: { enabled: true, + sinks: names.map((name) => ({ type: "stream", name })) } } }], + }, + }); + const [warning] = terminalStreamingWarnings(true, sinks(["nemo-fabric-stream"])); + assert.match(warning, /invoke_stream\(\)/); + // Without the SDK there is no invoke_stream(); native-only startup has its own warning. + assert.deepEqual(terminalStreamingWarnings(false, sinks(["nemo-fabric-stream"])), []); + assert.deepEqual(terminalStreamingWarnings(true, sinks(["own-sink"])), []); + assert.deepEqual(terminalStreamingWarnings(true, undefined), []); +}); + +test("the launcher clears Relay variables inherited from the person's shell", () => { + const script = launcherScript({ + node: "/node", cli: "/pi", agentDir: "/a", sessionDir: "/s", workspace: "/w", descriptor: "/d", args: [], + }); + assert.match(script, /^unset NEMO_RELAY_PI_COMMAND NEMO_RELAY_PI_GATEWAY_URL NEMO_RELAY_PI_OPENAI_UPSTREAM NEMO_RELAY_PI_ANTHROPIC_UPSTREAM$/m); + // The runtime's own Relay variables are exported after the unset. + const relay = launcherScript({ + node: "/node", cli: "/pi", agentDir: "/a", sessionDir: "/s", workspace: "/w", descriptor: "/d", args: [], + environment: { NEMO_RELAY_PI_GATEWAY_URL: "http://127.0.0.1:1" }, + }); + assert.ok(relay.indexOf("unset ") < relay.indexOf("export NEMO_RELAY_PI_GATEWAY_URL=")); +}); + +test("an empty artifact root resolves to /artifacts, as for Hermes", () => { + const input = startInput("/base", "http://127.0.0.1:9/v1"); + input.runtimeContext.artifacts = { root: "" }; + assert.equal(runtimeDirectory(input), join("/base", "artifacts", ".fabric", "pi", "runtimes", "rt-terminal")); +}); + test("the terminal interface refuses a model key variable Pi can't reference", { skip }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-key-name-"))); try { From 9ff16654c5777238990cb34abe620d76940e30bf Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 10:49:06 -0800 Subject: [PATCH 05/25] fix: keep suspended Pi terminal UIs and URL credentials under control - Record each terminal UI's process start time with its registration, so stop still closes a suspended terminal UI whose heartbeat went stale without signalling a later process that reuses its PID. - Close terminal UIs that register while stop withdraws the interface, after one more heartbeat period. - Refuse a base_url with a user name or password when the terminal interface or keep_state keeps the endpoint on disk. - Remove mcp.json at stop and after a failed start. - Pass module tool settings to the terminal UI through JSON.parse, so an own "__proto__" key survives. - Remove the tui.json staging file when publishing fails. - Say that terminal records can reach the stream sink without an SDK. - Wait for close, not exit, in the Relay smoke test. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- .../typescript/pi/src/native-configuration.ts | 20 +++ adapters/typescript/pi/src/native-only.ts | 4 +- adapters/typescript/pi/src/terminal.ts | 130 ++++++++++++++---- .../typescript/pi/test/relay-smoke.test.mjs | 3 +- adapters/typescript/pi/test/terminal.test.mjs | 70 +++++++++- 5 files changed, 189 insertions(+), 38 deletions(-) diff --git a/adapters/typescript/pi/src/native-configuration.ts b/adapters/typescript/pi/src/native-configuration.ts index da2cc8bdb..a16c8e9f9 100644 --- a/adapters/typescript/pi/src/native-configuration.ts +++ b/adapters/typescript/pi/src/native-configuration.ts @@ -741,6 +741,17 @@ async function resolveSkillPaths(baseDir: string, configured: string[]): Promise return resolved; } +/** Whether a URL carries a user name or password. */ +function urlHasCredentials(value: string | null | undefined): boolean { + if (value === undefined || value === null) return false; + try { + const url = new URL(value); + return url.username.length > 0 || url.password.length > 0; + } catch { + return false; + } +} + function credentialValue(input: AdapterStartInput, name: string): string | undefined { return input.runtimeContext.environment.env?.[name] ?? process.env[name]; } @@ -806,6 +817,15 @@ export async function preparePiConfiguration(input: AdapterStartInput): Promise< if (apiKeyEnv === undefined || apiKeyEnv === null || apiKeyEnv.length === 0) { throw new LifecycleError("pi_api_key_env_required", "The selected Pi model requires api_key_env"); } + if ((terminal || keepState) && urlHasCredentials(selected.base_url)) { + // models.json, and with Relay the terminal launcher, keep the endpoint on disk. + throw new LifecycleError( + "pi_base_url_credentials_unsupported", + "Pi's terminal interface and runtime.keep_state keep the model endpoint on disk; remove the user name and " + + "password from base_url and supply credentials through api_key_env", + { metadata: { field: "models.base_url" } }, + ); + } if (terminal && !ENVIRONMENT_VARIABLE_NAME.test(apiKeyEnv)) { // Pi's terminal UI reads the key through a ${NAME} reference in models.json. throw new LifecycleError( diff --git a/adapters/typescript/pi/src/native-only.ts b/adapters/typescript/pi/src/native-only.ts index 43f7d1007..2a4dd7150 100644 --- a/adapters/typescript/pi/src/native-only.ts +++ b/adapters/typescript/pi/src/native-only.ts @@ -67,8 +67,8 @@ export function sdkOnlySettings(relay: PiRelayRuntime | undefined): string[] { if (relay?.pluginConfig !== undefined && atofStreamSinkNames(relay.pluginConfig).includes(FABRIC_STREAM_SINK)) { // The collector correlates records with invocations; terminal TUI turns aren't invocations. warnings.push( - `the Relay ATOF sink ${FABRIC_STREAM_SINK} (start_runtime(..., streaming=True)) only streams SDK invocations, ` + - "and sdk.enabled is false, so it has no effect on the terminal TUI", + `the Relay ATOF sink ${FABRIC_STREAM_SINK} (start_runtime(..., streaming=True)) can receive terminal TUI ` + + "records, but sdk.enabled is false, so no invocation delivers them through invoke_stream()", ); } return warnings; diff --git a/adapters/typescript/pi/src/terminal.ts b/adapters/typescript/pi/src/terminal.ts index 80ca749c6..2e5d7408c 100644 --- a/adapters/typescript/pi/src/terminal.ts +++ b/adapters/typescript/pi/src/terminal.ts @@ -38,6 +38,8 @@ const TERMINAL_STOP_GRACE_MS = 5_000; /** A registration whose heartbeat is older than this belongs to a terminal UI that no longer runs. */ const TERMINAL_HEARTBEAT_STALE_MS = 3_000; const TERMINAL_HEARTBEAT_MS = 500; +/** How long `stop` waits after SIGTERM before SIGKILL for a terminal UI that registered during withdrawal. */ +const TERMINAL_LATE_GRACE_MS = 1_000; /** How long a terminal UI waits for its orderly shutdown before it sends itself SIGTERM. */ const TERMINAL_SELF_TERMINATE_MS = 2_000; const TOOL_NAME = /^[A-Za-z0-9_.:-]+$/u; @@ -133,7 +135,8 @@ export function launcherScript(options: { return [ "#!/bin/sh", "# Opens Pi's terminal UI in a separate session with this NeMo Fabric runtime's", - "# configuration. It holds paths and switches, never secrets: set the model key's", + "# configuration. It holds paths, switches and endpoints, never credentials (the", + "# runtime refuses a base_url with a user name or password): set the model key's", "# environment variable in the environment that runs this launcher.", `if [ ! -e ${shellQuote(options.descriptor)} ]; then`, " echo 'This NeMo Fabric runtime is not running.' >&2", @@ -164,6 +167,20 @@ const CLIENTS = ${JSON.stringify(clients)}; const RUNTIME_ID = ${JSON.stringify(runtimeId)}; const ENTRY = join(CLIENTS, String(process.pid)); +// This process's start time on Linux, recorded with its PID, so the runtime can still +// signal it while its heartbeat is stale (a suspended terminal UI) without signalling a +// later process that reuses the PID. +function startTime() { + try { + const stat = readFileSync("/proc/self/stat", "utf8"); + const start = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]; + return /^\\d+$/.test(start ?? "") ? start : ""; + } catch { + return ""; + } +} +const START = startTime(); + // Pi reruns extension factories when a person switches sessions (/new, /resume, // /fork), so one process-wide heartbeat serves every session, and it holds only // the current session's context. @@ -196,7 +213,7 @@ function beat() { } try { mkdirSync(CLIENTS, { recursive: true, mode: 0o700 }); - writeFileSync(ENTRY, "", { mode: 0o600 }); + writeFileSync(ENTRY, START, { mode: 0o600 }); } catch { // Retried on the next heartbeat; the runtime may be withdrawing the interface. } @@ -224,7 +241,10 @@ export function toolBridgeExtension(workspace: string, tools: readonly PiNativeC const imports = tools.map((tool, index) => `import * as tool${index} from ${JSON.stringify(tool.path)};`); const registrations = tools.map((tool, index) => ` pi.registerTool(await tool${index}[${JSON.stringify(tool.exportName)}](` + - `{ name: ${JSON.stringify(tool.name)}, settings: ${JSON.stringify(tool.settings)}, workspace: WORKSPACE }));`); + // JSON.parse keeps every configured key, including an own "__proto__", which an + // object literal would treat as a prototype setter. + `{ name: ${JSON.stringify(tool.name)}, settings: JSON.parse(${JSON.stringify(JSON.stringify(tool.settings))}), ` + + "workspace: WORKSPACE }));"); return [ "// Generated by the NeMo Fabric Pi adapter. Registers the runtime's tools.definitions.", ...imports, @@ -344,8 +364,13 @@ export class PiTerminal { async publish(): Promise { // Terminal UIs read it while they run, so it appears whole. const staging = `${this.descriptorPath}.${process.pid}.tmp`; - await writePrivate(staging, `${JSON.stringify(this.descriptor)}\n`); - await rename(staging, this.descriptorPath); + try { + await writePrivate(staging, `${JSON.stringify(this.descriptor)}\n`); + await rename(staging, this.descriptorPath); + } finally { + // Gone after a successful rename; otherwise don't leave it in a kept directory. + await rm(staging, { force: true }).catch(() => undefined); + } } /** @@ -370,28 +395,57 @@ export class PiTerminal { */ async function closeTerminals(clients: string): Promise { const terminals = await liveTerminals(clients); - if (terminals.length > 0) { - signal(terminals, "SIGTERM"); - const exited = new Set(); - const deadline = Date.now() + TERMINAL_STOP_GRACE_MS; - for (;;) { - for (const pid of terminals) if (!alive(pid)) exited.add(pid); - if (exited.size === terminals.length || Date.now() >= deadline) break; - await new Promise((resolve) => setTimeout(resolve, 100)); - } - // The group too: processes the terminal UI's tools started can outlive it. A terminal UI - // seen to exit gets no signal of its own, since its PID may now belong to another process. - signal(terminals.filter((pid) => !exited.has(pid)), "SIGKILL"); - signal(terminals.filter((pid) => exited.has(pid)), "SIGKILL", { groupOnly: true }); - } - // A terminal UI that registered while the attachment file was being removed closes itself - // on its next heartbeat; signal it too, so its tools' processes don't outlive the runtime. + await stopTerminals(terminals, TERMINAL_STOP_GRACE_MS); + // A heartbeat that read the attachment file just before it was removed can still register + // its terminal UI; after one more heartbeat period, close any that did. + await sleep(TERMINAL_HEARTBEAT_MS + 100); const late = (await liveTerminals(clients)).filter((pid) => !terminals.includes(pid)); - signal(late, "SIGKILL"); + await stopTerminals(late, TERMINAL_LATE_GRACE_MS); await rm(clients, { recursive: true, force: true }); } -/** Registered terminal UIs whose heartbeat is current; stale registrations are removed unsignalled. */ +/** SIGTERM each terminal UI's process group, then SIGKILL the groups after the grace period. */ +async function stopTerminals(terminals: readonly number[], graceMs: number): Promise { + if (terminals.length === 0) return; + signal(terminals, "SIGTERM"); + const exited = new Set(); + const deadline = Date.now() + graceMs; + for (;;) { + for (const pid of terminals) if (!alive(pid)) exited.add(pid); + if (exited.size === terminals.length || Date.now() >= deadline) break; + await sleep(100); + } + // The group too: processes the terminal UI's tools started can outlive it. A terminal UI + // seen to exit gets no signal of its own, since its PID may now belong to another process. + signal(terminals.filter((pid) => !exited.has(pid)), "SIGKILL"); + signal(terminals.filter((pid) => exited.has(pid)), "SIGKILL", { groupOnly: true }); +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** + * A process's start time in clock ticks since boot, from /proc//stat on Linux, which + * tells a terminal UI from a later process that reuses its PID. Undefined elsewhere. + */ +export async function processStartTime(pid: number | "self"): Promise { + try { + const stat = await readFile(`/proc/${pid}/stat`, "utf8"); + // Fields after the parenthesized command name; starttime is field 22, the 20th of these. + const start = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]; + return start !== undefined && /^\d+$/u.test(start) ? start : undefined; + } catch { + return undefined; + } +} + +/** + * Registered terminal UIs that still run. A current heartbeat means the registration's + * process runs; a stale one, as from a suspended terminal UI, still counts while the + * process start time the terminal UI recorded matches the process under its PID. Other + * registrations are removed unsignalled. + */ async function liveTerminals(clients: string): Promise { let entries: string[]; try { @@ -404,12 +458,17 @@ async function liveTerminals(clients: string): Promise { const path = join(clients, name); const pid = Number(name); try { - // A heartbeat from the future (clock skew on a shared volume) is not current. - const age = Date.now() - (await stat(path)).mtimeMs; - const fresh = age >= -TERMINAL_HEARTBEAT_MS && age < TERMINAL_HEARTBEAT_STALE_MS; - if (Number.isSafeInteger(pid) && pid > 1 && fresh && alive(pid)) { - live.push(pid); - continue; + if (Number.isSafeInteger(pid) && pid > 1 && alive(pid)) { + // A heartbeat from the future (clock skew on a shared volume) is not current. + const age = Date.now() - (await stat(path)).mtimeMs; + const fresh = age >= -TERMINAL_HEARTBEAT_MS && age < TERMINAL_HEARTBEAT_STALE_MS; + const recorded = (await readFile(path, "utf8")).trim(); + const current = recorded.length > 0 ? await processStartTime(pid) : undefined; + // With a recorded start time the process must match it, fresh or not. + if (recorded.length > 0 && current !== undefined ? current === recorded : fresh) { + live.push(pid); + continue; + } } } catch { // Removed while reading: that terminal UI exited. @@ -565,10 +624,22 @@ export class PiTerminalSessionHandle implements PiSessionHandle { ? error : new AggregateError([failure, error], "Pi terminal interface and session cleanup failed"); } + await removeTerminalMcpConfiguration(this.inner.configuration); if (failure !== undefined) throw failure; } } +/** + * Remove mcp.json, which only running terminal UIs read and which can hold literal MCP + * stdio env values. A kept directory gets a fresh one at the next start. + */ +async function removeTerminalMcpConfiguration(configuration: PiNativeConfiguration | undefined): Promise { + if (configuration === undefined) return; + await rm(join(configuration.agentDir, "mcp.json"), { force: true }).catch(() => { + process.stderr.write("Pi terminal MCP configuration cleanup failed\n"); + }); +} + /** * Add Pi's terminal interface to a runtime, as the runtime composes other native * processes beside the SDK session (Hermes's InterfaceChildren, Pi's Relay @@ -638,6 +709,7 @@ class PiTerminalInterface implements PiSessionFactory { await handle.relay?.stop().catch(() => { process.stderr.write("NeMo Relay cleanup failed after adapter startup error\n"); }); + await removeTerminalMcpConfiguration(handle.configuration); throw error; } } diff --git a/adapters/typescript/pi/test/relay-smoke.test.mjs b/adapters/typescript/pi/test/relay-smoke.test.mjs index ffa070b00..6279751d4 100644 --- a/adapters/typescript/pi/test/relay-smoke.test.mjs +++ b/adapters/typescript/pi/test/relay-smoke.test.mjs @@ -356,7 +356,8 @@ for (const sdk of [true, false]) { let output = ""; child.stdout.on("data", (chunk) => { output += chunk; }); child.stderr.on("data", (chunk) => { output += chunk; }); - const code = await new Promise((resolve) => child.on("exit", resolve)); + // close, not exit: both pipes are drained before the output assertions. + const code = await new Promise((resolve) => child.once("close", resolve)); assert.equal(code, 0, output); assert.match(output, /relay terminal ok/u); diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index e7de17a73..e666ed69f 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -17,6 +17,7 @@ import { terminalArguments, terminalEnabled, terminalEnvironmentWarnings, + processStartTime, terminalStreamingWarnings, withTerminalInterface, } from "../dist/terminal.js"; @@ -383,21 +384,26 @@ test("stopping the runtime closes an open terminal UI before the session stops", * A registered terminal UI that doesn't close itself when tui.json goes away, leading its own * process group as `openshell sandbox exec --tty` would start it, with a tool's child process in it. */ -async function fakeTerminal(clients, { ignoreSigterm }) { +async function fakeTerminal(clients, { ignoreSigterm, recordStart = false }) { const source = ` import { spawn } from "node:child_process"; - import { mkdirSync, writeFileSync } from "node:fs"; + import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; - const [clients, ignore] = process.argv.slice(1); + const [clients, ignore, record] = process.argv.slice(1); process.on("SIGTERM", () => { if (ignore !== "ignore") process.exit(143); }); const tool = spawn("sleep", ["60"], { stdio: "ignore" }); mkdirSync(clients, { recursive: true }); - const beat = () => writeFileSync(join(clients, String(process.pid)), ""); + // As the supervisor extension records it: this process's start time from /proc. + const stat = record === "record" ? readFileSync("/proc/self/stat", "utf8") : ""; + const start = stat ? stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19] : ""; + const beat = () => writeFileSync(join(clients, String(process.pid)), start); beat(); setInterval(beat, 200); console.log(tool.pid); `; - const child = spawn(process.execPath, ["--input-type=module", "-e", source, clients, ignoreSigterm ? "ignore" : "exit"], { + const child = spawn(process.execPath, [ + "--input-type=module", "-e", source, clients, ignoreSigterm ? "ignore" : "exit", recordStart ? "record" : "", + ], { detached: true, stdio: ["ignore", "pipe", "inherit"], }); @@ -415,6 +421,44 @@ function running(pid) { } } +test("processStartTime reads a Linux process's start time and is undefined elsewhere", async () => { + const start = await processStartTime("self"); + if (process.platform === "linux") assert.match(start, /^\d+$/); + else assert.equal(start, undefined); +}); + +test("stop closes a suspended terminal UI whose heartbeat went stale", { + skip: skip || (process.platform === "linux" ? false : "process identity needs /proc"), + timeout: 60_000, +}, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-suspended-"))); + const { server, url } = await modelServer(); + const clients = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal", "interfaces", "tui.clients"); + let session; + let terminal; + try { + session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + terminal = await fakeTerminal(clients, { ignoreSigterm: false, recordStart: true }); + // Suspended, as with Ctrl+Z: no heartbeat for longer than the stale limit. + process.kill(terminal.child.pid, "SIGSTOP"); + await new Promise((resolve) => setTimeout(resolve, 3_500)); + + await session.stop(); + session = undefined; + // SIGTERM waits while the process is stopped; the group SIGKILL after the grace period doesn't. + assert.deepEqual(await terminal.exited, { code: null, signal: "SIGKILL" }); + assert.equal(running(terminal.tool), false); + } finally { + if (terminal !== undefined) { + for (const pid of [-terminal.child.pid, terminal.tool]) try { process.kill(pid, "SIGKILL"); } catch {} + } + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + test("stop sends SIGTERM to open terminal UIs at once", { skip, timeout: 60_000 }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-sigterm-"))); const { server, url } = await modelServer(); @@ -590,7 +634,9 @@ async function toolsInput(workspace, url, settings) { input.config.tools = { enabled: null, blocked: [], - definitions: { fabric_tool: { kind: "module", ref: "fabric-tool.mjs", settings: { mode: "test" } } }, + // An own "__proto__" key, as JSON settings can carry, must reach both paths. + definitions: { fabric_tool: { kind: "module", ref: "fabric-tool.mjs", + settings: JSON.parse('{"mode":"test","__proto__":{"own":true}}') } }, }; input.config.mcp = { servers: { @@ -615,6 +661,7 @@ test("the terminal UI gets the SDK session's module tools and MCP servers", { sk await session.prompt("hello"); const sdkTools = toolDescriptions(requests[0]); assert.match(sdkTools.fabric_tool, /"mode":"test"/); + assert.match(sdkTools.fabric_tool, /"__proto__":\{"own":true\}/); const mcpTool = Object.keys(sdkTools).find((name) => name.includes("echo_secret")); assert.ok(mcpTool, JSON.stringify(Object.keys(sdkTools))); assert.match(sdkTools[mcpTool], /secret="a\$b !c"/); @@ -700,6 +747,17 @@ test("an empty artifact root resolves to /artifacts, as for Hermes", ( assert.equal(runtimeDirectory(input), join("/base", "artifacts", ".fabric", "pi", "runtimes", "rt-terminal")); }); +test("the terminal interface refuses a base_url with credentials", { skip }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-url-credentials-"))); + try { + const input = startInput(workspace, "http://user:secret@127.0.0.1:9/v1", { interfaces: { terminal: {} } }); + await assert.rejects(sessionFactory().create(input), { code: "pi_base_url_credentials_unsupported" }); + assert.equal(await exists(join(workspace, "artifacts")), false); + } finally { + await rm(workspace, { recursive: true, force: true }); + } +}); + test("the terminal interface refuses a model key variable Pi can't reference", { skip }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-key-name-"))); try { From f319abe2000f011128cea8e6cd2fcc2d293251f6 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 11:07:35 -0800 Subject: [PATCH 06/25] fix: close Pi terminal UIs without timing assumptions - Register a terminal UI before it checks tui.json. Stop removes tui.json before it scans registrations, so every terminal UI that saw the interface published is registered by then, and one that checks later closes itself, however long it pauses. This replaces the timed rescan. - Identify terminal UIs by process start time from /proc, or from ps where /proc is missing, and refuse the terminal interface on a host with neither (pi_terminal_unsupported_platform). - Refuse a base_url that doesn't parse when the terminal interface or keep_state keeps it on disk (pi_base_url_invalid), before anything is written. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- .../typescript/pi/src/native-configuration.ts | 37 +++++--- adapters/typescript/pi/src/terminal.ts | 88 ++++++++++++------- adapters/typescript/pi/test/terminal.test.mjs | 73 +++++++++++---- 3 files changed, 139 insertions(+), 59 deletions(-) diff --git a/adapters/typescript/pi/src/native-configuration.ts b/adapters/typescript/pi/src/native-configuration.ts index a16c8e9f9..f4f96e19a 100644 --- a/adapters/typescript/pi/src/native-configuration.ts +++ b/adapters/typescript/pi/src/native-configuration.ts @@ -741,14 +741,27 @@ async function resolveSkillPaths(baseDir: string, configured: string[]): Promise return resolved; } -/** Whether a URL carries a user name or password. */ -function urlHasCredentials(value: string | null | undefined): boolean { - if (value === undefined || value === null) return false; +/** + * Refuse a base_url that would be kept on disk and either fails to parse, so its parts + * can't be checked, or carries a user name or password. + */ +function rejectPersistedBaseUrl(value: string | null | undefined): void { + if (value === undefined || value === null) return; + let url: URL; try { - const url = new URL(value); - return url.username.length > 0 || url.password.length > 0; + url = new URL(value); } catch { - return false; + throw new LifecycleError("pi_base_url_invalid", "The selected model's base_url is not a valid URL", { + metadata: { field: "models.base_url" }, + }); + } + if (url.username.length > 0 || url.password.length > 0) { + throw new LifecycleError( + "pi_base_url_credentials_unsupported", + "Pi's terminal interface and runtime.keep_state keep the model endpoint on disk; remove the user name and " + + "password from base_url and supply credentials through api_key_env", + { metadata: { field: "models.base_url" } }, + ); } } @@ -817,14 +830,10 @@ export async function preparePiConfiguration(input: AdapterStartInput): Promise< if (apiKeyEnv === undefined || apiKeyEnv === null || apiKeyEnv.length === 0) { throw new LifecycleError("pi_api_key_env_required", "The selected Pi model requires api_key_env"); } - if ((terminal || keepState) && urlHasCredentials(selected.base_url)) { - // models.json, and with Relay the terminal launcher, keep the endpoint on disk. - throw new LifecycleError( - "pi_base_url_credentials_unsupported", - "Pi's terminal interface and runtime.keep_state keep the model endpoint on disk; remove the user name and " + - "password from base_url and supply credentials through api_key_env", - { metadata: { field: "models.base_url" } }, - ); + if (terminal || keepState) { + // models.json, and with Relay the terminal launcher, keep the endpoint on disk, so it + // is checked before anything is written. + rejectPersistedBaseUrl(selected.base_url); } if (terminal && !ENVIRONMENT_VARIABLE_NAME.test(apiKeyEnv)) { // Pi's terminal UI reads the key through a ${NAME} reference in models.json. diff --git a/adapters/typescript/pi/src/terminal.ts b/adapters/typescript/pi/src/terminal.ts index 2e5d7408c..c506b9af5 100644 --- a/adapters/typescript/pi/src/terminal.ts +++ b/adapters/typescript/pi/src/terminal.ts @@ -16,9 +16,11 @@ // so terminal conversations in pi-sessions outlive the runtime, and a start // first retires the terminal interface a runtime that ended without stop left. +import { execFile } from "node:child_process"; import { access, chmod, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; import type { AdapterCheckResult, CheckLevel } from "nemo-fabric-adapter-contract"; import { LifecycleError, type AdapterStartInput } from "nemo-fabric-adapters-common"; @@ -33,13 +35,13 @@ import { sdkEnabled, terminalEnabled } from "./settings.js"; export { terminalEnabled }; +const execFileAsync = promisify(execFile); + /** How long `stop` waits after SIGTERM before it sends SIGKILL to open terminal UIs, as the Hermes adapter does. */ const TERMINAL_STOP_GRACE_MS = 5_000; /** A registration whose heartbeat is older than this belongs to a terminal UI that no longer runs. */ const TERMINAL_HEARTBEAT_STALE_MS = 3_000; const TERMINAL_HEARTBEAT_MS = 500; -/** How long `stop` waits after SIGTERM before SIGKILL for a terminal UI that registered during withdrawal. */ -const TERMINAL_LATE_GRACE_MS = 1_000; /** How long a terminal UI waits for its orderly shutdown before it sends itself SIGTERM. */ const TERMINAL_SELF_TERMINATE_MS = 2_000; const TOOL_NAME = /^[A-Za-z0-9_.:-]+$/u; @@ -159,6 +161,7 @@ export function launcherScript(options: { */ export function supervisorExtension(descriptor: string, clients: string, runtimeId: string): string { return `// Generated by the NeMo Fabric Pi adapter. Ties this terminal UI to its runtime. +import { execFileSync } from "node:child_process"; import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -167,19 +170,28 @@ const CLIENTS = ${JSON.stringify(clients)}; const RUNTIME_ID = ${JSON.stringify(runtimeId)}; const ENTRY = join(CLIENTS, String(process.pid)); -// This process's start time on Linux, recorded with its PID, so the runtime can still -// signal it while its heartbeat is stale (a suspended terminal UI) without signalling a -// later process that reuses the PID. -function startTime() { +// This process's identity, recorded with its PID, so the runtime can still signal it +// while its heartbeat is stale (a suspended terminal UI) without signalling a later +// process that reuses the PID. It matches processIdentity() in the adapter. +function identity() { try { const stat = readFileSync("/proc/self/stat", "utf8"); const start = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]; - return /^\\d+$/.test(start ?? "") ? start : ""; + if (/^\\d+$/.test(start ?? "")) return "proc:" + start; } catch { - return ""; + // No /proc: ask ps. } + try { + const start = execFileSync("ps", ["-o", "lstart=", "-p", String(process.pid)], { + encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], + }).trim().replace(/\\s+/g, " "); + if (start.length > 0) return "ps:" + start; + } catch { + // No ps either; the adapter refuses to offer the interface on such a host. + } + return ""; } -const START = startTime(); +const IDENTITY = identity(); // Pi reruns extension factories when a person switches sessions (/new, /resume, // /fork), so one process-wide heartbeat serves every session, and it holds only @@ -197,6 +209,16 @@ function published() { function beat() { if (supervisor.stopping) return; + // Register before checking the attachment file. The runtime removes the file before it + // scans the registrations, so a terminal UI that still sees the file is registered by + // the time stop scans, and one that registers later finds the file gone and closes + // itself, however long it pauses in between. + try { + mkdirSync(CLIENTS, { recursive: true, mode: 0o700 }); + writeFileSync(ENTRY, IDENTITY, { mode: 0o600 }); + } catch { + // Retried on the next heartbeat; the runtime may be withdrawing the interface. + } if (!published()) { supervisor.stopping = true; clearInterval(supervisor.timer); @@ -209,13 +231,6 @@ function beat() { } catch { // A context Pi has already torn down; the SIGTERM above still closes Pi. } - return; - } - try { - mkdirSync(CLIENTS, { recursive: true, mode: 0o700 }); - writeFileSync(ENTRY, START, { mode: 0o600 }); - } catch { - // Retried on the next heartbeat; the runtime may be withdrawing the interface. } } @@ -308,6 +323,13 @@ export class PiTerminal { */ static async prepare(plan: PiNativeConfiguration, directory: string, runtimeId: string, node: string, cli: string, relay?: PiTerminalRelay): Promise { + // Stop tells a suspended terminal UI from a process that reused its PID by its identity. + if (await processIdentity(process.pid) === undefined) { + throw new LifecycleError( + "pi_terminal_unsupported_platform", + "Pi's terminal interface needs /proc or ps to identify the terminal UIs it closes at stop", + ); + } const sessionDir = plan.sessionDir; const interfaces = join(directory, "interfaces"); const descriptorPath = join(interfaces, "tui.json"); @@ -394,13 +416,9 @@ export class PiTerminal { * running after the grace period, and remove their registrations. */ async function closeTerminals(clients: string): Promise { - const terminals = await liveTerminals(clients); - await stopTerminals(terminals, TERMINAL_STOP_GRACE_MS); - // A heartbeat that read the attachment file just before it was removed can still register - // its terminal UI; after one more heartbeat period, close any that did. - await sleep(TERMINAL_HEARTBEAT_MS + 100); - const late = (await liveTerminals(clients)).filter((pid) => !terminals.includes(pid)); - await stopTerminals(late, TERMINAL_LATE_GRACE_MS); + // The attachment file is already gone. A terminal UI registers before it checks that file, + // so any terminal UI that saw it published is registered now; any other closes itself. + await stopTerminals(await liveTerminals(clients), TERMINAL_STOP_GRACE_MS); await rm(clients, { recursive: true, force: true }); } @@ -426,18 +444,28 @@ function sleep(ms: number): Promise { } /** - * A process's start time in clock ticks since boot, from /proc//stat on Linux, which - * tells a terminal UI from a later process that reuses its PID. Undefined elsewhere. + * A process's identity: its start time, which tells a terminal UI from a later process + * that reuses its PID. It is `proc:` from /proc//stat on + * Linux, otherwise `ps:` from ps, and undefined when neither is available. The + * generated supervisor extension records the same value for itself. */ -export async function processStartTime(pid: number | "self"): Promise { +export async function processIdentity(pid: number): Promise { try { const stat = await readFile(`/proc/${pid}/stat`, "utf8"); // Fields after the parenthesized command name; starttime is field 22, the 20th of these. const start = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]; - return start !== undefined && /^\d+$/u.test(start) ? start : undefined; + if (start !== undefined && /^\d+$/u.test(start)) return `proc:${start}`; + } catch { + // No /proc: ask ps. + } + try { + const { stdout } = await execFileAsync("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8" }); + const start = stdout.trim().replace(/\s+/gu, " "); + if (start.length > 0) return `ps:${start}`; } catch { - return undefined; + // No ps, or no such process. } + return undefined; } /** @@ -463,8 +491,8 @@ async function liveTerminals(clients: string): Promise { const age = Date.now() - (await stat(path)).mtimeMs; const fresh = age >= -TERMINAL_HEARTBEAT_MS && age < TERMINAL_HEARTBEAT_STALE_MS; const recorded = (await readFile(path, "utf8")).trim(); - const current = recorded.length > 0 ? await processStartTime(pid) : undefined; - // With a recorded start time the process must match it, fresh or not. + const current = recorded.length > 0 ? await processIdentity(pid) : undefined; + // With a recorded identity the process must match it, fresh or not. if (recorded.length > 0 && current !== undefined ? current === recorded : fresh) { live.push(pid); continue; diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index e666ed69f..f650574a9 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -17,7 +17,8 @@ import { terminalArguments, terminalEnabled, terminalEnvironmentWarnings, - processStartTime, + processIdentity, + supervisorExtension, terminalStreamingWarnings, withTerminalInterface, } from "../dist/terminal.js"; @@ -387,22 +388,23 @@ test("stopping the runtime closes an open terminal UI before the session stops", async function fakeTerminal(clients, { ignoreSigterm, recordStart = false }) { const source = ` import { spawn } from "node:child_process"; - import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; + import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; - const [clients, ignore, record] = process.argv.slice(1); + const [clients, ignore, record, terminalModule] = process.argv.slice(1); process.on("SIGTERM", () => { if (ignore !== "ignore") process.exit(143); }); const tool = spawn("sleep", ["60"], { stdio: "ignore" }); mkdirSync(clients, { recursive: true }); - // As the supervisor extension records it: this process's start time from /proc. - const stat = record === "record" ? readFileSync("/proc/self/stat", "utf8") : ""; - const start = stat ? stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19] : ""; - const beat = () => writeFileSync(join(clients, String(process.pid)), start); + // As the supervisor extension records it: this process's identity. + const identity = record === "record" + ? await (await import(terminalModule)).processIdentity(process.pid) : ""; + const beat = () => writeFileSync(join(clients, String(process.pid)), identity); beat(); setInterval(beat, 200); console.log(tool.pid); `; const child = spawn(process.execPath, [ "--input-type=module", "-e", source, clients, ignoreSigterm ? "ignore" : "exit", recordStart ? "record" : "", + new URL("../dist/terminal.js", import.meta.url).href, ], { detached: true, stdio: ["ignore", "pipe", "inherit"], @@ -421,16 +423,46 @@ function running(pid) { } } -test("processStartTime reads a Linux process's start time and is undefined elsewhere", async () => { - const start = await processStartTime("self"); - if (process.platform === "linux") assert.match(start, /^\d+$/); - else assert.equal(start, undefined); +test("processIdentity identifies a running process by its start time", async () => { + const identity = await processIdentity(process.pid); + assert.match(identity, process.platform === "linux" ? /^proc:\d+$/ : /^ps:\S/); + assert.equal(await processIdentity(process.pid), identity); }); -test("stop closes a suspended terminal UI whose heartbeat went stale", { - skip: skip || (process.platform === "linux" ? false : "process identity needs /proc"), - timeout: 60_000, -}, async () => { +test("the supervisor registers a terminal UI before it checks the attachment file", { timeout: 30_000 }, async () => { + const directory = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-supervisor-"))); + try { + const descriptor = join(directory, "tui.json"); + const clients = join(directory, "tui.clients"); + const extension = join(directory, "fabric-terminal.mjs"); + await writeFile(extension, supervisorExtension(descriptor, clients, "rt-supervisor")); + // No attachment file: the runtime has withdrawn the interface. A terminal UI that + // checks now must already be registered, so a stop scanning before this check sees it. + const host = ` + import { existsSync } from "node:fs"; + import { join } from "node:path"; + const [extension, clients] = process.argv.slice(1); + const handlers = {}; + (await import(extension)).default({ on: (name, handler) => { handlers[name] = handler; } }); + handlers.session_start({}, { ui: { notify() {} }, shutdown() { + console.log(JSON.stringify({ registered: existsSync(join(clients, String(process.pid))) })); + process.exit(0); + } }); + `; + const child = spawn(process.execPath, ["--input-type=module", "-e", host, extension, clients], { + stdio: ["ignore", "pipe", "inherit"], + }); + let stdout = ""; + child.stdout.setEncoding("utf8").on("data", (chunk) => { stdout += chunk; }); + const code = await new Promise((resolve) => child.once("close", resolve)); + assert.equal(code, 0); + assert.deepEqual(JSON.parse(stdout), { registered: true }); + } finally { + await rm(directory, { recursive: true, force: true }); + } +}); + +test("stop closes a suspended terminal UI whose heartbeat went stale", { skip, timeout: 60_000 }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-suspended-"))); const { server, url } = await modelServer(); const clients = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal", "interfaces", "tui.clients"); @@ -758,6 +790,17 @@ test("the terminal interface refuses a base_url with credentials", { skip }, asy } }); +test("the terminal interface refuses a malformed base_url before writing anything", { skip }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-url-invalid-"))); + try { + const input = startInput(workspace, "http://user:secret@localhost:99999/v1", { interfaces: { terminal: {} } }); + await assert.rejects(sessionFactory().create(input), { code: "pi_base_url_invalid" }); + assert.equal(await exists(join(workspace, "artifacts")), false); + } finally { + await rm(workspace, { recursive: true, force: true }); + } +}); + test("the terminal interface refuses a model key variable Pi can't reference", { skip }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-key-name-"))); try { From 1b6f2880c8589580e09bfed7dabf5da4805d297f Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 11:17:22 -0800 Subject: [PATCH 07/25] fix: require an identity for each Pi terminal UI - A terminal UI that can't identify its own process (no /proc, and no ps on PATH or in /bin or /usr/bin) closes with a notice instead of running unmanaged. - At stop, a stale registration whose identity can't be verified is not signalled, since its PID could belong to another process, but stop now warns about it instead of dropping it silently. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- adapters/typescript/pi/src/terminal.ts | 70 +++++++++++------ adapters/typescript/pi/test/terminal.test.mjs | 75 +++++++++++++++++++ 2 files changed, 122 insertions(+), 23 deletions(-) diff --git a/adapters/typescript/pi/src/terminal.ts b/adapters/typescript/pi/src/terminal.ts index c506b9af5..349768cc8 100644 --- a/adapters/typescript/pi/src/terminal.ts +++ b/adapters/typescript/pi/src/terminal.ts @@ -181,18 +181,35 @@ function identity() { } catch { // No /proc: ask ps. } - try { - const start = execFileSync("ps", ["-o", "lstart=", "-p", String(process.pid)], { - encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], - }).trim().replace(/\\s+/g, " "); - if (start.length > 0) return "ps:" + start; - } catch { - // No ps either; the adapter refuses to offer the interface on such a host. + // The launcher's PATH is the person's, so look in the usual places too. + for (const ps of ["ps", "/bin/ps", "/usr/bin/ps"]) { + try { + const start = execFileSync(ps, ["-o", "lstart=", "-p", String(process.pid)], { + encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], + }).trim().replace(/\\s+/g, " "); + if (start.length > 0) return "ps:" + start; + } catch { + // Try the next location. + } } return ""; } const IDENTITY = identity(); +function close(message) { + supervisor.stopping = true; + clearInterval(supervisor.timer); + // The terminal UI acts on shutdown() at once; other modes defer it until a + // command finishes, so fall back to SIGTERM, which Pi also handles in order. + setTimeout(() => process.kill(process.pid, "SIGTERM"), ${TERMINAL_SELF_TERMINATE_MS}); + try { + supervisor.context?.ui?.notify?.(message, "warning"); + supervisor.context?.shutdown(); + } catch { + // A context Pi has already torn down; the SIGTERM above still closes Pi. + } +} + // Pi reruns extension factories when a person switches sessions (/new, /resume, // /fork), so one process-wide heartbeat serves every session, and it holds only // the current session's context. @@ -209,6 +226,12 @@ function published() { function beat() { if (supervisor.stopping) return; + // Without an identity, stop couldn't tell this process from one that later reuses its + // PID, so it couldn't close a suspended terminal UI safely: don't run unmanaged. + if (IDENTITY === "") { + close("Pi can't identify its own process (no /proc or ps), so the NeMo Fabric runtime can't manage it; closing Pi."); + return; + } // Register before checking the attachment file. The runtime removes the file before it // scans the registrations, so a terminal UI that still sees the file is registered by // the time stop scans, and one that registers later finds the file gone and closes @@ -220,17 +243,7 @@ function beat() { // Retried on the next heartbeat; the runtime may be withdrawing the interface. } if (!published()) { - supervisor.stopping = true; - clearInterval(supervisor.timer); - // The terminal UI acts on shutdown() at once; other modes defer it until a - // command finishes, so fall back to SIGTERM, which Pi also handles in order. - setTimeout(() => process.kill(process.pid, "SIGTERM"), ${TERMINAL_SELF_TERMINATE_MS}); - try { - supervisor.context?.ui?.notify?.("The NeMo Fabric runtime stopped; closing Pi.", "warning"); - supervisor.context?.shutdown(); - } catch { - // A context Pi has already torn down; the SIGTERM above still closes Pi. - } + close("The NeMo Fabric runtime stopped; closing Pi."); } } @@ -470,9 +483,11 @@ export async function processIdentity(pid: number): Promise /** * Registered terminal UIs that still run. A current heartbeat means the registration's - * process runs; a stale one, as from a suspended terminal UI, still counts while the - * process start time the terminal UI recorded matches the process under its PID. Other - * registrations are removed unsignalled. + * process runs. A stale one, as from a suspended terminal UI, counts while the identity + * the terminal UI recorded matches the process under its PID; a mismatch means another + * process reuses the PID. A stale registration whose identity can't be compared is not + * signalled, since that could hit an unrelated process, but stop warns about it: the + * terminal UI closes itself when it resumes and finds the attachment file gone. */ async function liveTerminals(clients: string): Promise { let entries: string[]; @@ -490,13 +505,22 @@ async function liveTerminals(clients: string): Promise { // A heartbeat from the future (clock skew on a shared volume) is not current. const age = Date.now() - (await stat(path)).mtimeMs; const fresh = age >= -TERMINAL_HEARTBEAT_MS && age < TERMINAL_HEARTBEAT_STALE_MS; + if (fresh) { + live.push(pid); + continue; + } const recorded = (await readFile(path, "utf8")).trim(); const current = recorded.length > 0 ? await processIdentity(pid) : undefined; - // With a recorded identity the process must match it, fresh or not. - if (recorded.length > 0 && current !== undefined ? current === recorded : fresh) { + if (current === undefined) { + process.stderr.write( + `Pi warning: terminal UI ${pid} stopped its heartbeat and its process identity can't be verified, ` + + "so stop doesn't signal it; it closes itself when it resumes\n", + ); + } else if (current === recorded) { live.push(pid); continue; } + // Otherwise another process reuses the PID: drop the registration unsignalled. } } catch { // Removed while reading: that terminal UI exited. diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index f650574a9..d14d2871e 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -462,6 +462,81 @@ test("the supervisor registers a terminal UI before it checks the attachment fil } }); +test("a terminal UI that can't identify itself closes instead of running unmanaged", { timeout: 30_000 }, async () => { + const directory = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-supervisor-identity-"))); + try { + const descriptor = join(directory, "tui.json"); + const clients = join(directory, "tui.clients"); + await writeFile(descriptor, JSON.stringify({ runtime_id: "rt-supervisor" })); + const extension = join(directory, "fabric-terminal.mjs"); + // As on a host with neither /proc nor ps. + const source = supervisorExtension(descriptor, clients, "rt-supervisor"); + assert.match(source, /const IDENTITY = identity\(\);/); + await writeFile(extension, source.replace("const IDENTITY = identity();", 'const IDENTITY = "";')); + const host = ` + import { existsSync } from "node:fs"; + const [extension, clients] = process.argv.slice(1); + const handlers = {}; + (await import(extension)).default({ on: (name, handler) => { handlers[name] = handler; } }); + handlers.session_start({}, { ui: { notify(message) { console.error(message); } }, shutdown() { + console.log(JSON.stringify({ registered: existsSync(clients) })); + process.exit(0); + } }); + `; + const child = spawn(process.execPath, ["--input-type=module", "-e", host, extension, clients], { + stdio: ["ignore", "pipe", "pipe"], + }); + let stdout = ""; + let stderr = ""; + child.stdout.setEncoding("utf8").on("data", (chunk) => { stdout += chunk; }); + child.stderr.setEncoding("utf8").on("data", (chunk) => { stderr += chunk; }); + const code = await new Promise((resolve) => child.once("close", resolve)); + assert.equal(code, 0, stderr); + // It closes although the runtime is published, and never registers. + assert.deepEqual(JSON.parse(stdout), { registered: false }); + assert.match(stderr, /can't identify its own process/); + } finally { + await rm(directory, { recursive: true, force: true }); + } +}); + +test("stop warns about, and doesn't signal, a stale terminal UI it can't verify", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-unverified-"))); + const { server, url } = await modelServer(); + const clients = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal", "interfaces", "tui.clients"); + const write = process.stderr.write; + let warnings = ""; + let session; + let terminal; + try { + session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + // A registration without an identity, as an older supervisor would write. + terminal = await fakeTerminal(clients, { ignoreSigterm: false }); + process.kill(terminal.child.pid, "SIGSTOP"); + await new Promise((resolve) => setTimeout(resolve, 3_500)); + + process.stderr.write = (chunk, ...rest) => { + warnings += String(chunk); + return write.call(process.stderr, chunk, ...rest); + }; + await session.stop(); + session = undefined; + process.stderr.write = write; + assert.match(warnings, new RegExp(`terminal UI ${terminal.child.pid} stopped its heartbeat`)); + // Not signalled: an unverifiable PID could belong to another process. + assert.equal(running(terminal.child.pid), true); + } finally { + process.stderr.write = write; + if (terminal !== undefined) { + for (const pid of [-terminal.child.pid, terminal.tool]) try { process.kill(pid, "SIGKILL"); } catch {} + } + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + test("stop closes a suspended terminal UI whose heartbeat went stale", { skip, timeout: 60_000 }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-suspended-"))); const { server, url } = await modelServer(); From e1a8636ef26929afaef12e9b9eb300ed016fc319 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 11:22:02 -0800 Subject: [PATCH 08/25] feat: give Pi's terminal UI the runtime's environment over a socket A terminal UI runs Pi itself, in a process a person starts, so unlike the Hermes and OpenClaw backends it didn't inherit the runtime's environment.env or model key: MCP header references, tools and stdio MCP servers saw only the person's shell. While the runtime runs, an owner-only Unix socket in a private temporary directory now serves its environment.env and the model key from memory. The launcher, still free of secrets, execs a launch helper that fetches them, adds them to its own environment, and runs the pi CLI in the same process, so heartbeats keep its PID. The runtime's values win for its names, except the variables the launcher controls. tui.json names the socket as env_socket; stop closes it before closing terminal UIs, and a keep_state start removes a killed runtime's socket directory. Values are never written to disk. This replaces the startup warning that listed the variables the terminal UI didn't inherit. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- adapters/typescript/pi/src/terminal-client.ts | 49 ++++++ .../typescript/pi/src/terminal-environment.ts | 113 ++++++++++++++ adapters/typescript/pi/src/terminal-launch.ts | 40 +++++ adapters/typescript/pi/src/terminal.ts | 65 +++++--- adapters/typescript/pi/test/terminal.test.mjs | 141 +++++++++++++++--- adapters/typescript/scripts/check-package.mjs | 6 + 6 files changed, 374 insertions(+), 40 deletions(-) create mode 100644 adapters/typescript/pi/src/terminal-client.ts create mode 100644 adapters/typescript/pi/src/terminal-environment.ts create mode 100644 adapters/typescript/pi/src/terminal-launch.ts diff --git a/adapters/typescript/pi/src/terminal-client.ts b/adapters/typescript/pi/src/terminal-client.ts new file mode 100644 index 000000000..daac29edc --- /dev/null +++ b/adapters/typescript/pi/src/terminal-client.ts @@ -0,0 +1,49 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// The terminal launch helper's side of the runtime's environment socket. It uses only +// Node built-ins, so the helper loads nothing else before it starts Pi. + +import { connect } from "node:net"; + +const FETCH_TIMEOUT_MS = 5_000; + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** Read `{"version":1,"env":{...}}` from the runtime's environment socket. */ +export function fetchTerminalEnvironment(socketPath: string, timeoutMs = FETCH_TIMEOUT_MS): Promise> { + return new Promise((resolve, reject) => { + const chunks: Buffer[] = []; + const socket = connect(socketPath); + const timer = setTimeout(() => { + socket.destroy(); + reject(new Error("timed out")); + }, timeoutMs); + socket.on("data", (chunk: Buffer) => chunks.push(chunk)); + socket.on("error", (error) => { + clearTimeout(timer); + reject(error); + }); + socket.on("end", () => { + clearTimeout(timer); + try { + const message: unknown = JSON.parse(Buffer.concat(chunks).toString("utf8")); + if (!isRecord(message) || message.version !== 1 || !isRecord(message.env)) { + throw new Error("unexpected response"); + } + const environment: Record = {}; + for (const [name, value] of Object.entries(message.env)) { + if (typeof value !== "string") throw new Error("unexpected response"); + environment[name] = value; + } + resolve(environment); + } catch (error) { + reject(error); + } + }); + }); +} + +export { isRecord }; diff --git a/adapters/typescript/pi/src/terminal-environment.ts b/adapters/typescript/pi/src/terminal-environment.ts new file mode 100644 index 000000000..fb49edc5f --- /dev/null +++ b/adapters/typescript/pi/src/terminal-environment.ts @@ -0,0 +1,113 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// The runtime's environment for Pi's terminal UI. A terminal UI runs Pi itself, in a +// process a person starts, so it doesn't inherit the runtime's environment.env or the +// model key the way the Hermes and OpenClaw backends do. While the runtime runs, this +// server hands both to the terminal UI's launch helper over an owner-only Unix socket, +// so they reach the terminal UI from memory and are never written to disk; the +// launcher stays free of secrets. Stop closes the socket before it closes terminal UIs. + +import { chmod, mkdtemp, rm } from "node:fs/promises"; +import { createServer, type Server } from "node:net"; +import { tmpdir } from "node:os"; +import { basename, dirname, join } from "node:path"; + +import { LifecycleError, type AdapterStartInput } from "nemo-fabric-adapters-common"; + +import { RELAY_ENV_NAMES } from "./relay.js"; + +/** Variables the launcher sets for its own Pi process; the runtime's environment never overrides them. */ +export const LAUNCHER_ENV_NAMES: ReadonlySet = new Set([ + "PI_CODING_AGENT_DIR", + "PI_CODING_AGENT_SESSION_DIR", + "PI_OFFLINE", + "PI_SKIP_VERSION_CHECK", + "PI_TELEMETRY", + ...RELAY_ENV_NAMES, +]); + +/** The private directory that holds a runtime's environment socket. */ +const SOCKET_DIRECTORY_PREFIX = "nemo-fabric-pi-tui-"; +const SOCKET_NAME = "env.sock"; + +/** + * What a terminal UI gets from the runtime: its environment.env and the model key under + * its api_key_env name, as the embedded SDK session resolves them, without the variables + * the launcher controls. + */ +export function terminalEnvironment(input: AdapterStartInput, apiKeyEnv: string): Record { + const runtime = input.runtimeContext.environment.env ?? {}; + const environment: Record = {}; + for (const [name, value] of Object.entries(runtime)) { + if (!LAUNCHER_ENV_NAMES.has(name)) environment[name] = value; + } + const key = runtime[apiKeyEnv] ?? process.env[apiKeyEnv]; + if (key !== undefined && key.length > 0 && !LAUNCHER_ENV_NAMES.has(apiKeyEnv)) environment[apiKeyEnv] = key; + return environment; +} + +/** + * Serves one runtime's terminal environment. Each connection receives + * `{"version":1,"env":{...}}` followed by a newline, and the server closes it. + * The socket lives in a private temporary directory: Unix socket paths are short, + * and the runtime directory under the artifact root can be long. + */ +export class PiTerminalEnvironmentServer { + readonly socketPath: string; + private readonly server: Server; + private closed = false; + + private constructor(socketPath: string, server: Server) { + this.socketPath = socketPath; + this.server = server; + } + + static async start(environment: Readonly>): Promise { + const payload = `${JSON.stringify({ version: 1, env: environment })}\n`; + let directory: string | undefined; + try { + // mkdtemp creates the directory owner-only (0700); the socket is 0600 inside it. + directory = await mkdtemp(join(tmpdir(), SOCKET_DIRECTORY_PREFIX)); + const socketPath = join(directory, SOCKET_NAME); + const server = createServer((socket) => { + socket.on("error", () => undefined); + socket.end(payload); + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(socketPath, () => { + server.off("error", reject); + resolve(); + }); + }); + server.unref(); + await chmod(socketPath, 0o600); + return new PiTerminalEnvironmentServer(socketPath, server); + } catch (error) { + if (directory !== undefined) await rm(directory, { recursive: true, force: true }).catch(() => undefined); + throw new LifecycleError("pi_terminal_unavailable", "Pi's terminal environment socket could not be opened", { + metadata: { cause: error instanceof Error ? error.message : String(error) }, + }); + } + } + + /** Stop answering, then remove the socket and its directory. */ + async close(): Promise { + if (this.closed) return; + this.closed = true; + await new Promise((resolve) => this.server.close(() => resolve())); + await removeSocketDirectory(this.socketPath); + } +} + +/** + * Remove a terminal environment socket's private directory, as a runtime that ended + * without stop can leave it. Only a path this module created is removed. + */ +export async function removeSocketDirectory(socketPath: unknown): Promise { + if (typeof socketPath !== "string" || basename(socketPath) !== SOCKET_NAME) return; + const directory = dirname(socketPath); + if (!basename(directory).startsWith(SOCKET_DIRECTORY_PREFIX)) return; + await rm(directory, { recursive: true, force: true }); +} diff --git a/adapters/typescript/pi/src/terminal-launch.ts b/adapters/typescript/pi/src/terminal-launch.ts new file mode 100644 index 000000000..294087de3 --- /dev/null +++ b/adapters/typescript/pi/src/terminal-launch.ts @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// The launch helper the terminal launcher execs: `node terminal-launch.js +// [pi arguments...]`. It reads the runtime's attachment file, fetches the +// runtime's environment (environment.env and the model key) over the runtime's +// owner-only socket, adds it to its own environment in memory, and then runs the `pi` +// CLI in this same process, so the terminal UI keeps this process's PID. It holds +// nothing on disk. + +import { readFileSync } from "node:fs"; +import { pathToFileURL } from "node:url"; + +import { fetchTerminalEnvironment, isRecord } from "./terminal-client.js"; + +function unavailable(): never { + process.stderr.write( + "This NeMo Fabric runtime is not running, or its terminal environment is unavailable.\n", + ); + process.exit(1); +} + +const [descriptorPath, cli, ...args] = process.argv.slice(2); +if (descriptorPath === undefined || cli === undefined) unavailable(); + +let environment: Record; +try { + const descriptor: unknown = JSON.parse(readFileSync(descriptorPath, "utf8")); + if (!isRecord(descriptor) || typeof descriptor.env_socket !== "string") unavailable(); + environment = await fetchTerminalEnvironment(descriptor.env_socket); +} catch { + unavailable(); +} + +// The runtime's values win for its names, so the terminal UI runs with the configuration +// the SDK session uses; everything else comes from the person's shell. +Object.assign(process.env, environment); +// The pi CLI runs main(process.argv.slice(2)) when it loads. +process.argv = [process.argv[0]!, cli, ...args]; +await import(pathToFileURL(cli).href); diff --git a/adapters/typescript/pi/src/terminal.ts b/adapters/typescript/pi/src/terminal.ts index 349768cc8..aa2c8385a 100644 --- a/adapters/typescript/pi/src/terminal.ts +++ b/adapters/typescript/pi/src/terminal.ts @@ -32,11 +32,15 @@ import { atofStreamSinkNames } from "./relay-config.js"; import { RELAY_ENV_NAMES, type PiRelayRuntime } from "./relay.js"; import type { PiPromptOutcome, PiSessionFactory, PiSessionHandle } from "./runtime.js"; import { sdkEnabled, terminalEnabled } from "./settings.js"; +import { PiTerminalEnvironmentServer, removeSocketDirectory, terminalEnvironment } from "./terminal-environment.js"; export { terminalEnabled }; const execFileAsync = promisify(execFile); +/** The launch helper shipped beside this module (dist/terminal-launch.js). */ +const TERMINAL_LAUNCH_HELPER = fileURLToPath(new URL("./terminal-launch.js", import.meta.url)); + /** How long `stop` waits after SIGTERM before it sends SIGKILL to open terminal UIs, as the Hermes adapter does. */ const TERMINAL_STOP_GRACE_MS = 5_000; /** A registration whose heartbeat is older than this belongs to a terminal UI that no longer runs. */ @@ -117,6 +121,8 @@ export function terminalArguments(plan: PiNativeConfiguration, terminalExtension export function launcherScript(options: { node: string; + /** The launch helper, which fetches the runtime's environment and runs the CLI. */ + helper: string; cli: string; agentDir: string; sessionDir: string; @@ -138,8 +144,8 @@ export function launcherScript(options: { "#!/bin/sh", "# Opens Pi's terminal UI in a separate session with this NeMo Fabric runtime's", "# configuration. It holds paths, switches and endpoints, never credentials (the", - "# runtime refuses a base_url with a user name or password): set the model key's", - "# environment variable in the environment that runs this launcher.", + "# runtime refuses a base_url with a user name or password). Its launch helper", + "# fetches the runtime's environment and model key from the running runtime.", `if [ ! -e ${shellQuote(options.descriptor)} ]; then`, " echo 'This NeMo Fabric runtime is not running.' >&2", " exit 1", @@ -148,7 +154,7 @@ export function launcherScript(options: { `unset ${RELAY_ENV_NAMES.join(" ")}`, ...exports, `cd ${shellQuote(options.workspace)} || exit 1`, - `exec ${[options.node, options.cli, ...options.args].map(shellQuote).join(" ")} "$@"`, + `exec ${[options.node, options.helper, options.descriptor, options.cli, ...options.args].map(shellQuote).join(" ")} "$@"`, "", ].join("\n"); } @@ -307,6 +313,8 @@ export interface PiTuiDescriptor { workspace: string; agent_dir: string; session_dir: string; + /** The runtime's owner-only socket from which the launch helper fetches its environment. */ + env_socket: string; } /** What the launcher needs to load the runtime's Relay Pi extension. */ @@ -321,13 +329,16 @@ export class PiTerminal { readonly descriptorPath: string; private readonly descriptor: PiTuiDescriptor; private readonly clients: string; + private readonly server: PiTerminalEnvironmentServer; private withdrawn = false; - private constructor(launcher: string, descriptorPath: string, descriptor: PiTuiDescriptor, clients: string) { + private constructor(launcher: string, descriptorPath: string, descriptor: PiTuiDescriptor, clients: string, + server: PiTerminalEnvironmentServer) { this.launcher = launcher; this.descriptorPath = descriptorPath; this.descriptor = descriptor; this.clients = clients; + this.server = server; } /** @@ -335,7 +346,7 @@ export class PiTerminal { * directory, which the session already wrote; the launcher refuses to run until {@link publish}. */ static async prepare(plan: PiNativeConfiguration, directory: string, runtimeId: string, node: string, - cli: string, relay?: PiTerminalRelay): Promise { + cli: string, environment: Readonly>, relay?: PiTerminalRelay): Promise { // Stop tells a suspended terminal UI from a process that reused its PID by its identity. if (await processIdentity(process.pid) === undefined) { throw new LifecycleError( @@ -343,6 +354,17 @@ export class PiTerminal { "Pi's terminal interface needs /proc or ps to identify the terminal UIs it closes at stop", ); } + const server = await PiTerminalEnvironmentServer.start(environment); + try { + return await PiTerminal.write(plan, directory, runtimeId, node, cli, server, relay); + } catch (error) { + await server.close().catch(() => undefined); + throw error; + } + } + + private static async write(plan: PiNativeConfiguration, directory: string, runtimeId: string, node: string, + cli: string, server: PiTerminalEnvironmentServer, relay?: PiTerminalRelay): Promise { const sessionDir = plan.sessionDir; const interfaces = join(directory, "interfaces"); const descriptorPath = join(interfaces, "tui.json"); @@ -364,6 +386,7 @@ export class PiTerminal { const launcher = join(interfaces, "terminal"); await writePrivate(launcher, launcherScript({ node, + helper: TERMINAL_LAUNCH_HELPER, cli, agentDir: plan.agentDir, sessionDir, @@ -380,8 +403,9 @@ export class PiTerminal { workspace: plan.workspace, agent_dir: plan.agentDir, session_dir: sessionDir, + env_socket: server.socketPath, }; - return new PiTerminal(launcher, descriptorPath, descriptor, clients); + return new PiTerminal(launcher, descriptorPath, descriptor, clients, server); } /** Whether a person can open the terminal TUI now: the launcher and the published descriptor exist. */ @@ -417,6 +441,8 @@ export class PiTerminal { async withdraw(): Promise { if (this.withdrawn) return; await rm(this.descriptorPath, { force: true }); + // No new launch gets the runtime's environment once stop has begun. + await this.server.close(); // Withdrawn only once the terminal UIs are closed, so a retried stop closes them again. await closeTerminals(this.clients); this.withdrawn = true; @@ -539,7 +565,15 @@ async function liveTerminals(clients: string): Promise { export async function retireStaleTerminal(directory: string): Promise { const interfaces = join(directory, "interfaces"); try { + // A runtime killed without stop leaves its environment socket's directory behind. + let staleSocket: unknown; + try { + staleSocket = (JSON.parse(await readFile(join(interfaces, "tui.json"), "utf8")) as Record).env_socket; + } catch { + // No attachment file, or an unreadable one: nothing to remove. + } await rm(join(interfaces, "tui.json"), { force: true }); + await removeSocketDirectory(staleSocket); await closeTerminals(join(interfaces, "tui.clients")); for (const name of ["terminal", "fabric-terminal.ts", "fabric-tools.ts"]) { await rm(join(interfaces, name), { force: true }); @@ -583,21 +617,6 @@ function signal(pids: readonly number[], name: NodeJS.Signals, options: { groupO } } -/** - * The launcher holds no secrets, so Pi's terminal UI doesn't inherit the runtime's - * `environment.env`: its tools, its stdio MCP servers, and MCP header `${NAME}` - * references see the environment that runs the launcher. A warning names those - * variables, never their values, so a person can set them there. - */ -export function terminalEnvironmentWarnings(input: AdapterStartInput): string[] { - const names = Object.keys(input.runtimeContext.environment.env ?? {}).sort(); - if (names.length === 0) return []; - return [ - `Pi's terminal UI doesn't inherit environment.env; set ${names.join(", ")} in the environment ` + - "that runs the launcher if the terminal UI, its tools or its MCP servers need them", - ]; -} - /** * Terminal UIs send their Relay records through the runtime's gateway, which also feeds * the ATOF sink that `start_runtime(..., streaming=True)` adds for `invoke_stream()`. @@ -736,7 +755,8 @@ class PiTerminalInterface implements PiSessionFactory { const cli = await resolvePiCli(); try { interfaceHandle = await PiTerminal.prepare(handle.configuration, handle.configuration.runtimeDir, - input.runtimeContext.runtime_id, process.execPath, cli, handle.relay); + input.runtimeContext.runtime_id, process.execPath, cli, + terminalEnvironment(input, handle.configuration.apiKeyEnv), handle.relay); await interfaceHandle.publish(); } catch (error) { if (error instanceof LifecycleError) throw error; @@ -745,7 +765,6 @@ class PiTerminalInterface implements PiSessionFactory { }); } for (const warning of [ - ...terminalEnvironmentWarnings(input), ...terminalStreamingWarnings(sdkEnabled(input.config), handle.relay), ]) { process.stderr.write(`Pi warning: ${warning}\n`); diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index d14d2871e..9a71ecb20 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -6,7 +6,7 @@ import { spawn } from "node:child_process"; import { access, mkdir, mkdtemp, readdir, readFile, realpath, rm, stat, writeFile } from "node:fs/promises"; import { createServer } from "node:http"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import test from "node:test"; import { PiSdkSessionFactory } from "../dist/pi-sdk.js"; @@ -16,13 +16,13 @@ import { launcherScript, terminalArguments, terminalEnabled, - terminalEnvironmentWarnings, processIdentity, supervisorExtension, terminalStreamingWarnings, withTerminalInterface, } from "../dist/terminal.js"; import { runtimeDirectory } from "../dist/agent-directory.js"; +import { LAUNCHER_ENV_NAMES, terminalEnvironment } from "../dist/terminal-environment.js"; const [major, minor] = process.versions.node.split(".").map(Number); const skip = major > 22 || (major === 22 && minor >= 19) ? false : "Pi requires Node >=22.19"; @@ -115,7 +115,7 @@ function startInput(workspace, baseUrl, settings) { function launch(launcher, home, args, options = {}) { const child = spawn("/bin/sh", [launcher, ...args], { cwd: home, - env: { PATH: process.env.PATH, HOME: home, TEST_API_KEY: TERMINAL_KEY }, + env: options.env ?? { PATH: process.env.PATH, HOME: home, TEST_API_KEY: TERMINAL_KEY }, stdio: [options.stdin ?? "ignore", "pipe", "pipe"], }); let stdout = ""; @@ -189,6 +189,7 @@ test("terminal arguments reproduce the embedded session's isolation and tool pol test("the launcher quotes its paths and refuses to run without the tui.json descriptor", () => { const script = launcherScript({ node: "/usr/bin/node", + helper: "/opt/fabric/terminal-launch.js", cli: "/opt/pi/cli.js", agentDir: "/a'b", sessionDir: "/s", @@ -199,7 +200,8 @@ test("the launcher quotes its paths and refuses to run without the tui.json desc assert.match(script, /^#!\/bin\/sh\n/); assert.match(script, /if \[ ! -e '\/m' \]; then/); assert.match(script, /export PI_CODING_AGENT_DIR='\/a'\\''b'/); - assert.match(script, /exec '\/usr\/bin\/node' '\/opt\/pi\/cli.js' '--no-approve' "\$@"\n$/); + // The launch helper fetches the runtime's environment, then runs the CLI with the arguments. + assert.match(script, /exec '\/usr\/bin\/node' '\/opt\/fabric\/terminal-launch.js' '\/m' '\/opt\/pi\/cli.js' '--no-approve' "\$@"\n$/); }); test("the terminal factory passes a session through unchanged without interfaces.terminal", async () => { @@ -291,7 +293,8 @@ test("the launcher opens Pi on the runtime's model, key variable and system prom session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); // The attachment file is owner-only and versioned, with Pi's own launcher mode. assert.equal((await stat(descriptor)).mode & 0o777, 0o600); - assert.deepEqual(JSON.parse(await readFile(descriptor, "utf8")), { + const { env_socket: socket, ...published } = JSON.parse(await readFile(descriptor, "utf8")); + assert.deepEqual(published, { version: 1, mode: "launcher", launcher: "terminal", @@ -300,6 +303,10 @@ test("the launcher opens Pi on the runtime's model, key variable and system prom agent_dir: join(directory, "pi-agent"), session_dir: join(directory, "pi-sessions"), }); + // The environment socket is owner-only, in a private directory outside the artifact root. + assert.match(socket, /nemo-fabric-pi-tui-[^/]+\/env\.sock$/); + assert.equal((await stat(socket)).mode & 0o777, 0o600); + assert.equal((await stat(dirname(socket))).mode & 0o777, 0o700); assert.equal((await stat(launcher)).mode & 0o777, 0o700); assert.equal((await stat(join(directory, "interfaces"))).mode & 0o777, 0o700); // As for Hermes's native interfaces, terminal turns aren't observed, so activity is unknown. @@ -318,7 +325,8 @@ test("the launcher opens Pi on the runtime's model, key variable and system prom assert.match(run.stdout, /terminal-answer/); assert.equal(requests.length, 1); assert.equal(requests[0].path, "/v1/chat/completions"); - assert.equal(requests[0].authorization, `Bearer ${TERMINAL_KEY}`); + // The runtime's key wins over the one in the launcher's environment. + assert.equal(requests[0].authorization, `Bearer ${RUNTIME_KEY}`); assert.equal(requests[0].body.model, "test-model"); assert.match(JSON.stringify(requests[0].body.messages[0]), new RegExp(SYSTEM_PROMPT)); assert.deepEqual(requests[0].body.tools.map((tool) => tool.function.name).sort(), ["ls", "read"]); @@ -648,7 +656,8 @@ test("a native-only runtime writes Pi's files and the launcher but runs no SDK s assert.equal(run.code, 0, run.stderr); assert.match(run.stdout, /terminal-answer/); assert.equal(requests.length, 1); - assert.equal(requests[0].authorization, `Bearer ${TERMINAL_KEY}`); + // The runtime's key wins over the one in the launcher's environment. + assert.equal(requests[0].authorization, `Bearer ${RUNTIME_KEY}`); // A withdrawn interface fails the runtime's active and ready checks. await rm(descriptor); @@ -808,15 +817,111 @@ test("without the terminal interface the runtime writes no mcp.json", { skip, ti } }); -test("the terminal interface names, without values, the runtime variables its UI doesn't inherit", () => { +test("the terminal environment is the runtime's environment.env and model key, without launcher variables", () => { const input = startInput("/workspace", "http://127.0.0.1:9/v1"); - input.runtimeContext.environment.env = { TEST_API_KEY: RUNTIME_KEY, GITHUB_TOKEN: "ghp-secret" }; - const [warning, ...rest] = terminalEnvironmentWarnings(input); - assert.deepEqual(rest, []); - assert.match(warning, /GITHUB_TOKEN, TEST_API_KEY/); - assert.doesNotMatch(warning, /ghp-secret|runtime-key/); + input.runtimeContext.environment.env = { + TEST_API_KEY: RUNTIME_KEY, + GITHUB_TOKEN: "ghp-runtime", + PI_CODING_AGENT_DIR: "/elsewhere", + NEMO_RELAY_PI_GATEWAY_URL: "http://127.0.0.1:1", + }; + assert.deepEqual(terminalEnvironment(input, "TEST_API_KEY"), { TEST_API_KEY: RUNTIME_KEY, GITHUB_TOKEN: "ghp-runtime" }); + for (const name of ["PI_CODING_AGENT_DIR", "PI_CODING_AGENT_SESSION_DIR", "NEMO_RELAY_PI_GATEWAY_URL"]) { + assert.ok(LAUNCHER_ENV_NAMES.has(name), name); + } + // A key the adapter process holds, outside environment.env, reaches the terminal UI too. input.runtimeContext.environment.env = {}; - assert.deepEqual(terminalEnvironmentWarnings(input), []); + process.env.FABRIC_TEST_PROCESS_KEY = "process-key"; + try { + assert.deepEqual(terminalEnvironment(input, "FABRIC_TEST_PROCESS_KEY"), { FABRIC_TEST_PROCESS_KEY: "process-key" }); + } finally { + delete process.env.FABRIC_TEST_PROCESS_KEY; + } +}); + +test("the terminal UI gets the runtime's environment and key without any from the person's shell", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-env-"))); + const home = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-env-home-"))); + const { server, requests, url } = await modelServer(); + let session; + try { + await writeFile(join(workspace, "env-tool.mjs"), `export default function ({ name }) { + return { name, label: "Env", description: "runtime=" + process.env.FABRIC_RUNTIME_ONLY, + parameters: { type: "object", properties: {} }, + async execute() { return { content: [{ type: "text", text: "done" }], details: {} }; } }; + } +`); + const input = startInput(workspace, url, { sdk: { enabled: false }, interfaces: { terminal: {} } }); + input.config.tools = { enabled: null, blocked: [], definitions: { env_tool: { kind: "module", ref: "env-tool.mjs" } } }; + input.runtimeContext.environment.env.FABRIC_RUNTIME_ONLY = "from-runtime"; + session = await sessionFactory().create(input); + const launcher = join(session.configuration.runtimeDir, "interfaces", "terminal"); + // The person's shell holds neither the model key nor the runtime's variable. + const run = await launch(launcher, home, ["--print", "say hello"], { env: { PATH: process.env.PATH, HOME: home } }).exited; + assert.equal(run.code, 0, run.stderr); + assert.equal(requests.length, 1); + assert.equal(requests[0].authorization, `Bearer ${RUNTIME_KEY}`); + assert.equal(toolDescriptions(requests[0]).env_tool, "runtime=from-runtime"); + } finally { + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + await rm(home, { recursive: true, force: true }); + } +}); + +test("after stop, the environment socket is gone and a kept launcher can't start Pi", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-env-stop-"))); + const home = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-env-stop-home-"))); + const { server, requests, url } = await modelServer(); + let session; + try { + session = await sessionFactory().create(startInput(workspace, url, { sdk: { enabled: false }, interfaces: { terminal: {} } })); + const interfaces = join(session.configuration.runtimeDir, "interfaces"); + const attachment = await readFile(join(interfaces, "tui.json"), "utf8"); + const socket = JSON.parse(attachment).env_socket; + await session.stop(); + session = undefined; + assert.equal(await exists(dirname(socket)), false); + // Even with a stale tui.json put back, as a killed host could leave it, the helper refuses. + await writeFile(join(interfaces, "tui.json"), attachment, { mode: 0o600 }); + const run = await launch(join(interfaces, "terminal"), home, ["--print", "say hello"]).exited; + assert.equal(run.code, 1); + assert.match(run.stderr, /terminal environment is unavailable/); + assert.equal(requests.length, 0); + } finally { + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + await rm(home, { recursive: true, force: true }); + } +}); + +test("keep_state retirement removes a killed runtime's environment socket directory", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-kept-socket-"))); + const { server, url } = await modelServer(); + const state = join(workspace, "artifacts", ".fabric", "state", "nvidia.fabric.pi", "terminal-test"); + let first; + let second; + try { + first = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-one", state)); + const socket = JSON.parse(await readFile(join(state, "interfaces", "tui.json"), "utf8")).env_socket; + // The first runtime's host is killed: no stop. The next start retires what it left. + second = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-two", state)); + assert.equal(await exists(dirname(socket)), false); + const current = JSON.parse(await readFile(join(state, "interfaces", "tui.json"), "utf8")).env_socket; + assert.notEqual(current, socket); + assert.equal(await exists(current), true); + } finally { + await second?.stop(); + // The "killed" runtime's server still runs in this test process; close it. + await first?.stop().catch(() => undefined); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } }); test("the terminal interface warns that streamed SDK invocations share Relay's stream sink", () => { @@ -837,12 +942,12 @@ test("the terminal interface warns that streamed SDK invocations share Relay's s test("the launcher clears Relay variables inherited from the person's shell", () => { const script = launcherScript({ - node: "/node", cli: "/pi", agentDir: "/a", sessionDir: "/s", workspace: "/w", descriptor: "/d", args: [], + node: "/node", helper: "/helper", cli: "/pi", agentDir: "/a", sessionDir: "/s", workspace: "/w", descriptor: "/d", args: [], }); assert.match(script, /^unset NEMO_RELAY_PI_COMMAND NEMO_RELAY_PI_GATEWAY_URL NEMO_RELAY_PI_OPENAI_UPSTREAM NEMO_RELAY_PI_ANTHROPIC_UPSTREAM$/m); // The runtime's own Relay variables are exported after the unset. const relay = launcherScript({ - node: "/node", cli: "/pi", agentDir: "/a", sessionDir: "/s", workspace: "/w", descriptor: "/d", args: [], + node: "/node", helper: "/helper", cli: "/pi", agentDir: "/a", sessionDir: "/s", workspace: "/w", descriptor: "/d", args: [], environment: { NEMO_RELAY_PI_GATEWAY_URL: "http://127.0.0.1:1" }, }); assert.ok(relay.indexOf("unset ") < relay.indexOf("export NEMO_RELAY_PI_GATEWAY_URL=")); @@ -946,7 +1051,8 @@ test("with keep_state, a terminal conversation from one runtime continues in the try { session = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-one", state)); // The whole Pi directory is the state folder, where NemoClaw looks for a kept agent's interfaces. - assert.deepEqual(JSON.parse(await readFile(join(state, "interfaces", "tui.json"), "utf8")), { + const { env_socket: socket, ...published } = JSON.parse(await readFile(join(state, "interfaces", "tui.json"), "utf8")); + assert.deepEqual(published, { version: 1, mode: "launcher", launcher: "terminal", @@ -955,6 +1061,7 @@ test("with keep_state, a terminal conversation from one runtime continues in the agent_dir: join(state, "pi-agent"), session_dir: join(state, "pi-sessions"), }); + assert.match(socket, /nemo-fabric-pi-tui-[^/]+\/env\.sock$/); const first = await launch(launcher, home, ["--print", "remember the word heron"]).exited; assert.equal(first.code, 0, first.stderr); await session.stop(); diff --git a/adapters/typescript/scripts/check-package.mjs b/adapters/typescript/scripts/check-package.mjs index 94544164c..a27575c6a 100644 --- a/adapters/typescript/scripts/check-package.mjs +++ b/adapters/typescript/scripts/check-package.mjs @@ -92,6 +92,12 @@ const expectedByPackage = { "dist/runtime.js", "dist/settings.d.ts", "dist/settings.js", + "dist/terminal-client.d.ts", + "dist/terminal-client.js", + "dist/terminal-environment.d.ts", + "dist/terminal-environment.js", + "dist/terminal-launch.d.ts", + "dist/terminal-launch.js", "dist/terminal.d.ts", "dist/terminal.js", "package.json", From 4f22066f75a40e5ce82357730569714e461072af Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 11:33:44 -0800 Subject: [PATCH 09/25] fix: harden the Pi terminal environment socket and launch helper - Drop open connections when the socket closes, and time out idle ones, so a suspended or half-open client can't hold up stop. - Start the pi CLI with process.execve under the merged environment, so Node startup variables such as NODE_OPTIONS and NODE_EXTRA_CA_CERTS apply as they do for the SDK session, keeping the PID; fall back to an in-process import where execve is unavailable. - Keep the person's terminal variables (TERM, COLUMNS, ...), and resolve MCP header variables with the SDK session's fallback to the adapter's environment. - Fall back to /tmp when TMPDIR would make the socket path too long, close the listener when setup fails after listen, and report its later errors. - Remove only socket directories this module created, best effort, so a failed cleanup can't block a start; a retried stop still removes it. - Report a reason code when the launch helper can't reach the runtime. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- .../typescript/pi/src/terminal-environment.ts | 131 ++++++++++++++---- adapters/typescript/pi/src/terminal-launch.ts | 57 ++++++-- adapters/typescript/pi/src/terminal.ts | 4 +- adapters/typescript/pi/test/terminal.test.mjs | 112 ++++++++++++++- 4 files changed, 258 insertions(+), 46 deletions(-) diff --git a/adapters/typescript/pi/src/terminal-environment.ts b/adapters/typescript/pi/src/terminal-environment.ts index fb49edc5f..d4ba607fa 100644 --- a/adapters/typescript/pi/src/terminal-environment.ts +++ b/adapters/typescript/pi/src/terminal-environment.ts @@ -8,11 +8,12 @@ // so they reach the terminal UI from memory and are never written to disk; the // launcher stays free of secrets. Stop closes the socket before it closes terminal UIs. -import { chmod, mkdtemp, rm } from "node:fs/promises"; -import { createServer, type Server } from "node:net"; +import { chmod, lstat, mkdtemp, readdir, rm } from "node:fs/promises"; +import { createServer, type Server, type Socket } from "node:net"; import { tmpdir } from "node:os"; -import { basename, dirname, join } from "node:path"; +import { basename, dirname, isAbsolute, join } from "node:path"; +import type { AgentConfig } from "nemo-fabric-adapter-contract"; import { LifecycleError, type AdapterStartInput } from "nemo-fabric-adapters-common"; import { RELAY_ENV_NAMES } from "./relay.js"; @@ -27,26 +28,65 @@ export const LAUNCHER_ENV_NAMES: ReadonlySet = new Set([ ...RELAY_ENV_NAMES, ]); +/** Variables that describe the person's terminal; the person's shell keeps them. */ +export const TERMINAL_ENV_NAMES: ReadonlySet = new Set([ + "TERM", + "COLORTERM", + "COLUMNS", + "LINES", + "TERM_PROGRAM", + "TERM_PROGRAM_VERSION", +]); + /** The private directory that holds a runtime's environment socket. */ const SOCKET_DIRECTORY_PREFIX = "nemo-fabric-pi-tui-"; const SOCKET_NAME = "env.sock"; +/** Linux limits a Unix socket path to 107 bytes; keep well inside it. */ +const SOCKET_PATH_MAX_BYTES = 100; +/** How long a client may hold a connection before the server drops it. */ +const CONNECTION_TIMEOUT_MS = 5_000; + +const ENV_REFERENCE = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/gu; + +/** The variables MCP HTTP headers reference, which the SDK session resolves from the runtime's environment. */ +function mcpHeaderVariables(config: AgentConfig): string[] { + const names = new Set(); + for (const server of Object.values(config.mcp?.servers ?? {})) { + for (const value of Object.values(server.custom_headers ?? {})) { + for (const match of String(value).matchAll(ENV_REFERENCE)) names.add(match[1]!); + } + } + return [...names]; +} /** - * What a terminal UI gets from the runtime: its environment.env and the model key under - * its api_key_env name, as the embedded SDK session resolves them, without the variables - * the launcher controls. + * What a terminal UI gets from the runtime: its environment.env, plus the model key and + * the variables MCP headers reference, which the SDK session also looks up in the + * adapter's own environment. The variables the launcher controls, and those that + * describe the person's terminal, are left out. */ export function terminalEnvironment(input: AdapterStartInput, apiKeyEnv: string): Record { const runtime = input.runtimeContext.environment.env ?? {}; - const environment: Record = {}; - for (const [name, value] of Object.entries(runtime)) { - if (!LAUNCHER_ENV_NAMES.has(name)) environment[name] = value; + const environment: Record = { ...runtime }; + for (const name of [apiKeyEnv, ...mcpHeaderVariables(input.config)]) { + const value = runtime[name] ?? process.env[name]; + if (value !== undefined && value.length > 0) environment[name] = value; + } + for (const name of Object.keys(environment)) { + if (LAUNCHER_ENV_NAMES.has(name) || TERMINAL_ENV_NAMES.has(name)) delete environment[name]; } - const key = runtime[apiKeyEnv] ?? process.env[apiKeyEnv]; - if (key !== undefined && key.length > 0 && !LAUNCHER_ENV_NAMES.has(apiKeyEnv)) environment[apiKeyEnv] = key; return environment; } +/** A private directory for the socket, short enough for a Unix socket path. */ +async function socketDirectory(): Promise { + const directory = await mkdtemp(join(tmpdir(), SOCKET_DIRECTORY_PREFIX)); + if (Buffer.byteLength(join(directory, SOCKET_NAME)) <= SOCKET_PATH_MAX_BYTES) return directory; + // A long TMPDIR: fall back to /tmp. + await rm(directory, { recursive: true, force: true }); + return mkdtemp(join("/tmp", SOCKET_DIRECTORY_PREFIX)); +} + /** * Serves one runtime's terminal environment. Each connection receives * `{"version":1,"env":{...}}` followed by a newline, and the server closes it. @@ -56,35 +96,50 @@ export function terminalEnvironment(input: AdapterStartInput, apiKeyEnv: string) export class PiTerminalEnvironmentServer { readonly socketPath: string; private readonly server: Server; - private closed = false; + private readonly connections: Set; + private closing: Promise | undefined; + private removed = false; - private constructor(socketPath: string, server: Server) { + private constructor(socketPath: string, server: Server, connections: Set) { this.socketPath = socketPath; this.server = server; + this.connections = connections; } static async start(environment: Readonly>): Promise { const payload = `${JSON.stringify({ version: 1, env: environment })}\n`; + const connections = new Set(); let directory: string | undefined; + let server: Server | undefined; try { // mkdtemp creates the directory owner-only (0700); the socket is 0600 inside it. - directory = await mkdtemp(join(tmpdir(), SOCKET_DIRECTORY_PREFIX)); + directory = await socketDirectory(); const socketPath = join(directory, SOCKET_NAME); - const server = createServer((socket) => { + server = createServer((socket) => { + connections.add(socket); + socket.on("close", () => connections.delete(socket)); socket.on("error", () => undefined); + // A client that never reads or closes can't hold the connection, or stop, open. + socket.setTimeout(CONNECTION_TIMEOUT_MS, () => socket.destroy()); socket.end(payload); }); + const listening = server; await new Promise((resolve, reject) => { - server.once("error", reject); - server.listen(socketPath, () => { - server.off("error", reject); + listening.once("error", reject); + listening.listen(socketPath, () => { + listening.off("error", reject); resolve(); }); }); - server.unref(); + listening.on("error", (error) => { + process.stderr.write(`Pi terminal environment socket error: ${error.message}\n`); + }); + listening.unref(); await chmod(socketPath, 0o600); - return new PiTerminalEnvironmentServer(socketPath, server); + return new PiTerminalEnvironmentServer(socketPath, listening, connections); } catch (error) { + for (const socket of connections) socket.destroy(); + if (server?.listening === true) server.close(); if (directory !== undefined) await rm(directory, { recursive: true, force: true }).catch(() => undefined); throw new LifecycleError("pi_terminal_unavailable", "Pi's terminal environment socket could not be opened", { metadata: { cause: error instanceof Error ? error.message : String(error) }, @@ -92,22 +147,42 @@ export class PiTerminalEnvironmentServer { } } - /** Stop answering, then remove the socket and its directory. */ + /** Stop answering, drop open connections, then remove the socket and its directory. */ async close(): Promise { - if (this.closed) return; - this.closed = true; - await new Promise((resolve) => this.server.close(() => resolve())); - await removeSocketDirectory(this.socketPath); + if (this.closing === undefined) { + // close() refuses new connections at once; its callback waits for open ones, so drop them. + this.closing = new Promise((resolve) => this.server.close(() => resolve())); + for (const socket of this.connections) socket.destroy(); + } + await this.closing; + if (!this.removed) { + await removeSocketDirectory(this.socketPath); + this.removed = true; + } } } /** * Remove a terminal environment socket's private directory, as a runtime that ended - * without stop can leave it. Only a path this module created is removed. + * without stop can leave it. It removes only an absolute path this module created: a + * directory named for it, owned by this user, holding nothing but the socket. Removal + * is best effort: a failure is reported, never thrown, so it can't block a start. */ export async function removeSocketDirectory(socketPath: unknown): Promise { - if (typeof socketPath !== "string" || basename(socketPath) !== SOCKET_NAME) return; + if (typeof socketPath !== "string" || !isAbsolute(socketPath) || basename(socketPath) !== SOCKET_NAME) return; const directory = dirname(socketPath); if (!basename(directory).startsWith(SOCKET_DIRECTORY_PREFIX)) return; - await rm(directory, { recursive: true, force: true }); + try { + const info = await lstat(directory); + if (!info.isDirectory() || (process.getuid !== undefined && info.uid !== process.getuid())) return; + const entries = await readdir(directory); + if (entries.some((entry) => entry !== SOCKET_NAME)) return; + await rm(directory, { recursive: true, force: true }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return; + process.stderr.write( + `Pi warning: the terminal environment socket directory ${directory} could not be removed: ` + + `${(error as NodeJS.ErrnoException).code ?? "error"}\n`, + ); + } } diff --git a/adapters/typescript/pi/src/terminal-launch.ts b/adapters/typescript/pi/src/terminal-launch.ts index 294087de3..d59fc1b07 100644 --- a/adapters/typescript/pi/src/terminal-launch.ts +++ b/adapters/typescript/pi/src/terminal-launch.ts @@ -4,37 +4,64 @@ // The launch helper the terminal launcher execs: `node terminal-launch.js // [pi arguments...]`. It reads the runtime's attachment file, fetches the // runtime's environment (environment.env and the model key) over the runtime's -// owner-only socket, adds it to its own environment in memory, and then runs the `pi` -// CLI in this same process, so the terminal UI keeps this process's PID. It holds -// nothing on disk. +// owner-only socket, and replaces itself with `node [pi arguments...]` under +// that environment. execve keeps the PID, and Node reads startup variables such as +// NODE_OPTIONS and NODE_EXTRA_CA_CERTS as it would for the SDK session's process. +// Nothing is written to disk. import { readFileSync } from "node:fs"; import { pathToFileURL } from "node:url"; import { fetchTerminalEnvironment, isRecord } from "./terminal-client.js"; -function unavailable(): never { +function unavailable(reason: string): never { + // Only a reason code: an error message could quote part of a response. process.stderr.write( - "This NeMo Fabric runtime is not running, or its terminal environment is unavailable.\n", + `This NeMo Fabric runtime is not running, or its terminal environment is unavailable (${reason}).\n`, ); process.exit(1); } +function reasonOf(error: unknown): string { + const code = (error as NodeJS.ErrnoException | undefined)?.code; + if (typeof code === "string") return code; + return error instanceof SyntaxError ? "invalid response" : "error"; +} + const [descriptorPath, cli, ...args] = process.argv.slice(2); -if (descriptorPath === undefined || cli === undefined) unavailable(); +if (descriptorPath === undefined || cli === undefined) unavailable("usage"); -let environment: Record; +let socketPath: string; try { const descriptor: unknown = JSON.parse(readFileSync(descriptorPath, "utf8")); - if (!isRecord(descriptor) || typeof descriptor.env_socket !== "string") unavailable(); - environment = await fetchTerminalEnvironment(descriptor.env_socket); -} catch { - unavailable(); + if (!isRecord(descriptor) || typeof descriptor.env_socket !== "string") unavailable("no env_socket"); + socketPath = descriptor.env_socket; +} catch (error) { + unavailable(error instanceof SyntaxError ? "invalid tui.json" : reasonOf(error)); +} + +let environment: Record; +try { + environment = await fetchTerminalEnvironment(socketPath); +} catch (error) { + unavailable(reasonOf(error)); } // The runtime's values win for its names, so the terminal UI runs with the configuration // the SDK session uses; everything else comes from the person's shell. -Object.assign(process.env, environment); -// The pi CLI runs main(process.argv.slice(2)) when it loads. -process.argv = [process.argv[0]!, cli, ...args]; -await import(pathToFileURL(cli).href); +const merged: Record = {}; +for (const [name, value] of Object.entries(process.env)) { + if (value !== undefined) merged[name] = value; +} +Object.assign(merged, environment); + +if (typeof process.execve === "function") { + // As the launcher's exec did: a fresh Node, same PID, with the merged environment. + process.execve(process.execPath, [process.execPath, cli, ...args], merged); +} else { + // Without execve, run the CLI in this process; startup-only Node variables don't apply. + Object.assign(process.env, environment); + // The pi CLI runs main(process.argv.slice(2)) when it loads. + process.argv = [process.argv[0]!, cli, ...args]; + await import(pathToFileURL(cli).href); +} diff --git a/adapters/typescript/pi/src/terminal.ts b/adapters/typescript/pi/src/terminal.ts index aa2c8385a..abbf6d511 100644 --- a/adapters/typescript/pi/src/terminal.ts +++ b/adapters/typescript/pi/src/terminal.ts @@ -154,7 +154,9 @@ export function launcherScript(options: { `unset ${RELAY_ENV_NAMES.join(" ")}`, ...exports, `cd ${shellQuote(options.workspace)} || exit 1`, - `exec ${[options.node, options.helper, options.descriptor, options.cli, ...options.args].map(shellQuote).join(" ")} "$@"`, + // The helper uses process.execve, still experimental in Node; keep its warning off the TUI. + `exec ${[options.node, "--disable-warning=ExperimentalWarning", options.helper, options.descriptor, options.cli, + ...options.args].map(shellQuote).join(" ")} "$@"`, "", ].join("\n"); } diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index 9a71ecb20..1ee550db5 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -5,6 +5,7 @@ import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { access, mkdir, mkdtemp, readdir, readFile, realpath, rm, stat, writeFile } from "node:fs/promises"; import { createServer } from "node:http"; +import { connect, createServer as createNetServer } from "node:net"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import test from "node:test"; @@ -22,7 +23,13 @@ import { withTerminalInterface, } from "../dist/terminal.js"; import { runtimeDirectory } from "../dist/agent-directory.js"; -import { LAUNCHER_ENV_NAMES, terminalEnvironment } from "../dist/terminal-environment.js"; +import { + LAUNCHER_ENV_NAMES, + PiTerminalEnvironmentServer, + removeSocketDirectory, + terminalEnvironment, +} from "../dist/terminal-environment.js"; +import { fetchTerminalEnvironment } from "../dist/terminal-client.js"; const [major, minor] = process.versions.node.split(".").map(Number); const skip = major > 22 || (major === 22 && minor >= 19) ? false : "Pi requires Node >=22.19"; @@ -201,7 +208,7 @@ test("the launcher quotes its paths and refuses to run without the tui.json desc assert.match(script, /if \[ ! -e '\/m' \]; then/); assert.match(script, /export PI_CODING_AGENT_DIR='\/a'\\''b'/); // The launch helper fetches the runtime's environment, then runs the CLI with the arguments. - assert.match(script, /exec '\/usr\/bin\/node' '\/opt\/fabric\/terminal-launch.js' '\/m' '\/opt\/pi\/cli.js' '--no-approve' "\$@"\n$/); + assert.match(script, /exec '\/usr\/bin\/node' '--disable-warning=ExperimentalWarning' '\/opt\/fabric\/terminal-launch.js' '\/m' '\/opt\/pi\/cli.js' '--no-approve' "\$@"\n$/); }); test("the terminal factory passes a session through unchanged without interfaces.terminal", async () => { @@ -839,6 +846,107 @@ test("the terminal environment is the runtime's environment.env and model key, w } }); +test("the terminal environment leaves the person's terminal variables and resolves MCP header variables as the SDK does", () => { + const input = startInput("/workspace", "http://127.0.0.1:9/v1"); + input.runtimeContext.environment.env = { TEST_API_KEY: RUNTIME_KEY, TERM: "dumb", COLUMNS: "40", LOG_LEVEL: "debug" }; + input.config.mcp = { servers: { remote: { transport: "streamable-http", url: "https://mcp.example.com/mcp", + custom_headers: { Authorization: "Bearer ${FABRIC_TEST_HEADER_TOKEN}" } } } }; + process.env.FABRIC_TEST_HEADER_TOKEN = "from-adapter-process"; + try { + assert.deepEqual(terminalEnvironment(input, "TEST_API_KEY"), { + TEST_API_KEY: RUNTIME_KEY, + LOG_LEVEL: "debug", + FABRIC_TEST_HEADER_TOKEN: "from-adapter-process", + }); + } finally { + delete process.env.FABRIC_TEST_HEADER_TOKEN; + } +}); + +test("the environment client rejects a response that isn't the runtime's", async () => { + const directory = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-env-client-"))); + const socket = join(directory, "s.sock"); + const server = createNetServer((connection) => connection.end(JSON.stringify({ version: 2, env: {} }))); + await new Promise((resolve) => server.listen(socket, resolve)); + try { + await assert.rejects(fetchTerminalEnvironment(socket), /unexpected response/); + await assert.rejects(fetchTerminalEnvironment(join(directory, "missing.sock")), { code: "ENOENT" }); + } finally { + server.close(); + await rm(directory, { recursive: true, force: true }); + } +}); + +test("stop isn't held up by a client that keeps the environment socket open", { timeout: 30_000 }, async () => { + const server = await PiTerminalEnvironmentServer.start({ VALUE: "x" }); + // Connects and never reads or closes, as a suspended launch helper would. + const client = connect(server.socketPath); + client.pause(); + await new Promise((resolve) => client.once("connect", resolve)); + const started = Date.now(); + await server.close(); + assert.ok(Date.now() - started < 2_000, `close took ${Date.now() - started} ms`); + assert.equal(await exists(dirname(server.socketPath)), false); + client.destroy(); +}); + +test("socket directory removal only removes a directory it created", async () => { + const base = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-socket-removal-"))); + try { + // Holding something besides the socket: left alone. + const crowded = join(base, "nemo-fabric-pi-tui-crowded"); + await mkdir(crowded); + await writeFile(join(crowded, "env.sock"), ""); + await writeFile(join(crowded, "other"), ""); + await removeSocketDirectory(join(crowded, "env.sock")); + assert.equal(await exists(crowded), true); + // Not named for a socket directory, or not absolute: left alone. + const other = join(base, "other-directory"); + await mkdir(other); + await writeFile(join(other, "env.sock"), ""); + await removeSocketDirectory(join(other, "env.sock")); + await removeSocketDirectory("nemo-fabric-pi-tui-x/env.sock"); + assert.equal(await exists(other), true); + // Its own directory: removed. + const own = join(base, "nemo-fabric-pi-tui-own"); + await mkdir(own); + await writeFile(join(own, "env.sock"), ""); + await removeSocketDirectory(join(own, "env.sock")); + assert.equal(await exists(own), false); + } finally { + await rm(base, { recursive: true, force: true }); + } +}); + +test("Node startup variables from the runtime's environment take effect in the terminal UI", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-node-options-"))); + const home = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-node-options-home-"))); + const { server, url } = await modelServer(); + let session; + try { + const marker = join(workspace, "preloaded"); + const preload = join(workspace, "preload.cjs"); + await writeFile(preload, `require("node:fs").writeFileSync(${JSON.stringify(marker)}, String(process.pid));\n`); + const input = startInput(workspace, url, { sdk: { enabled: false }, interfaces: { terminal: {} } }); + // Node reads NODE_OPTIONS only when it starts, so this shows the terminal UI's Node started with it. + input.runtimeContext.environment.env.NODE_OPTIONS = `--require ${preload}`; + session = await sessionFactory().create(input); + const launched = launch(join(session.configuration.runtimeDir, "interfaces", "terminal"), home, + ["--print", "say hello"], { env: { PATH: process.env.PATH, HOME: home } }); + const run = await launched.exited; + assert.equal(run.code, 0, run.stderr); + assert.doesNotMatch(run.stderr, /ExperimentalWarning/); + // execve keeps the PID the launcher started. + assert.equal(await readFile(marker, "utf8"), String(launched.child.pid)); + } finally { + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + await rm(home, { recursive: true, force: true }); + } +}); + test("the terminal UI gets the runtime's environment and key without any from the person's shell", { skip, timeout: 60_000 }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-env-"))); const home = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-env-home-"))); From 6ffdbc5fe0218af8e80a8b419fac1096c371b180 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 11:54:18 -0800 Subject: [PATCH 10/25] fix: verify Pi terminal UIs at stop and keep unverified ones - Check a registration's recorded identity whenever it can be read, fresh heartbeat or not, so a PID reused after a crash isn't signalled; fall back to heartbeat freshness only when identity can't be read. - Keep a stale registration that can't be verified, don't signal it, and report pi_interface_cleanup_incomplete so a retried stop verifies it. - Close the environment socket even when removing tui.json fails. - Close a terminal UI whose first registration fails, and make the exit handler's registration removal best effort so process.exit can't throw. - Read ps lstart with TZ=UTC and LC_ALL=C on both sides. - Refuse an api_key_env the launcher or the person's terminal sets. - Keep "__proto__" and empty MCP header values in the runtime environment. - Remove mcp.json when a terminal-enabled start fails. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- .../typescript/pi/src/native-configuration.ts | 9 + adapters/typescript/pi/src/terminal-client.ts | 3 +- .../typescript/pi/src/terminal-environment.ts | 12 +- adapters/typescript/pi/src/terminal-launch.ts | 5 +- adapters/typescript/pi/src/terminal.ts | 110 ++++++++---- adapters/typescript/pi/test/terminal.test.mjs | 158 +++++++++++++++--- 6 files changed, 239 insertions(+), 58 deletions(-) diff --git a/adapters/typescript/pi/src/native-configuration.ts b/adapters/typescript/pi/src/native-configuration.ts index f4f96e19a..5b91eb453 100644 --- a/adapters/typescript/pi/src/native-configuration.ts +++ b/adapters/typescript/pi/src/native-configuration.ts @@ -18,6 +18,7 @@ import { LifecycleError, type AdapterStartInput } from "nemo-fabric-adapters-com import { agentDirectory, keepsState, runtimeDirectory, sessionDirectory, writeAgentDirectory } from "./agent-directory.js"; import { terminalEnabled } from "./settings.js"; +import { LAUNCHER_ENV_NAMES, TERMINAL_ENV_NAMES } from "./terminal-environment.js"; export interface PiNativeCustomTool { name: string; @@ -843,6 +844,14 @@ export async function preparePiConfiguration(input: AdapterStartInput): Promise< { metadata: { field: "models.api_key_env" } }, ); } + if (terminal && (LAUNCHER_ENV_NAMES.has(apiKeyEnv) || TERMINAL_ENV_NAMES.has(apiKeyEnv))) { + // The terminal UI's environment never takes the runtime's value for these names. + throw new LifecycleError( + "pi_api_key_env_invalid", + `Pi's terminal interface sets ${apiKeyEnv} itself; name the model key with another variable`, + { metadata: { field: "models.api_key_env" } }, + ); + } const apiKey = credentialValue(input, apiKeyEnv); if (apiKey === undefined || apiKey.length === 0) { throw new LifecycleError("pi_credential_missing", `Credential environment variable ${apiKeyEnv} is not set`); diff --git a/adapters/typescript/pi/src/terminal-client.ts b/adapters/typescript/pi/src/terminal-client.ts index daac29edc..5a487aa2a 100644 --- a/adapters/typescript/pi/src/terminal-client.ts +++ b/adapters/typescript/pi/src/terminal-client.ts @@ -33,7 +33,8 @@ export function fetchTerminalEnvironment(socketPath: string, timeoutMs = FETCH_T if (!isRecord(message) || message.version !== 1 || !isRecord(message.env)) { throw new Error("unexpected response"); } - const environment: Record = {}; + // A null-prototype map keeps every name, including "__proto__", as an own key. + const environment = Object.create(null) as Record; for (const [name, value] of Object.entries(message.env)) { if (typeof value !== "string") throw new Error("unexpected response"); environment[name] = value; diff --git a/adapters/typescript/pi/src/terminal-environment.ts b/adapters/typescript/pi/src/terminal-environment.ts index d4ba607fa..48cbe1d47 100644 --- a/adapters/typescript/pi/src/terminal-environment.ts +++ b/adapters/typescript/pi/src/terminal-environment.ts @@ -67,10 +67,14 @@ function mcpHeaderVariables(config: AgentConfig): string[] { */ export function terminalEnvironment(input: AdapterStartInput, apiKeyEnv: string): Record { const runtime = input.runtimeContext.environment.env ?? {}; - const environment: Record = { ...runtime }; - for (const name of [apiKeyEnv, ...mcpHeaderVariables(input.config)]) { - const value = runtime[name] ?? process.env[name]; - if (value !== undefined && value.length > 0) environment[name] = value; + // A null-prototype map keeps every name, including "__proto__", as an own key. + const environment: Record = Object.assign(Object.create(null) as Record, runtime); + const key = runtime[apiKeyEnv] ?? process.env[apiKeyEnv]; + if (key !== undefined && key.length > 0) environment[apiKeyEnv] = key; + for (const name of mcpHeaderVariables(input.config)) { + // As the SDK session expands them: the runtime's value, else the adapter's, empty included. + const value = Object.hasOwn(runtime, name) ? runtime[name] : process.env[name]; + if (value !== undefined) environment[name] = value; } for (const name of Object.keys(environment)) { if (LAUNCHER_ENV_NAMES.has(name) || TERMINAL_ENV_NAMES.has(name)) delete environment[name]; diff --git a/adapters/typescript/pi/src/terminal-launch.ts b/adapters/typescript/pi/src/terminal-launch.ts index d59fc1b07..9d4e86e18 100644 --- a/adapters/typescript/pi/src/terminal-launch.ts +++ b/adapters/typescript/pi/src/terminal-launch.ts @@ -49,11 +49,12 @@ try { // The runtime's values win for its names, so the terminal UI runs with the configuration // the SDK session uses; everything else comes from the person's shell. -const merged: Record = {}; +// A null-prototype map keeps every name, including "__proto__", as an own key. +const merged = Object.create(null) as Record; for (const [name, value] of Object.entries(process.env)) { if (value !== undefined) merged[name] = value; } -Object.assign(merged, environment); +for (const [name, value] of Object.entries(environment)) merged[name] = value; if (typeof process.execve === "function") { // As the launcher's exec did: a fresh Node, same PID, with the merged environment. diff --git a/adapters/typescript/pi/src/terminal.ts b/adapters/typescript/pi/src/terminal.ts index abbf6d511..ab084400b 100644 --- a/adapters/typescript/pi/src/terminal.ts +++ b/adapters/typescript/pi/src/terminal.ts @@ -25,7 +25,7 @@ import { promisify } from "node:util"; import type { AdapterCheckResult, CheckLevel } from "nemo-fabric-adapter-contract"; import { LifecycleError, type AdapterStartInput } from "nemo-fabric-adapters-common"; -import { keepsState, runtimeDirectory } from "./agent-directory.js"; +import { agentDirectory, keepsState, runtimeDirectory } from "./agent-directory.js"; import type { PiNativeConfiguration, PiNativeCustomTool } from "./native-configuration.js"; import { FABRIC_STREAM_SINK, PiNativeOnlySessionFactory } from "./native-only.js"; import { atofStreamSinkNames } from "./relay-config.js"; @@ -192,8 +192,10 @@ function identity() { // The launcher's PATH is the person's, so look in the usual places too. for (const ps of ["ps", "/bin/ps", "/usr/bin/ps"]) { try { + // lstart follows TZ and the locale; fix both so the runtime reads the same text. const start = execFileSync(ps, ["-o", "lstart=", "-p", String(process.pid)], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], + env: { ...process.env, TZ: "UTC", LC_ALL: "C" }, }).trim().replace(/\\s+/g, " "); if (start.length > 0) return "ps:" + start; } catch { @@ -222,7 +224,7 @@ function close(message) { // /fork), so one process-wide heartbeat serves every session, and it holds only // the current session's context. const STATE = Symbol.for("nemo-fabric.pi.terminal-supervisor"); -const supervisor = (globalThis[STATE] ??= { context: undefined, stopping: false, timer: undefined }); +const supervisor = (globalThis[STATE] ??= { context: undefined, stopping: false, timer: undefined, registered: false }); function published() { try { @@ -247,8 +249,14 @@ function beat() { try { mkdirSync(CLIENTS, { recursive: true, mode: 0o700 }); writeFileSync(ENTRY, IDENTITY, { mode: 0o600 }); + supervisor.registered = true; } catch { - // Retried on the next heartbeat; the runtime may be withdrawing the interface. + // Unregistered, stop couldn't find this terminal UI: don't run that way. A later + // heartbeat that fails is retried; the registration from earlier ones remains. + if (!supervisor.registered) { + close("Pi couldn't register with the NeMo Fabric runtime; closing Pi."); + return; + } } if (!published()) { close("The NeMo Fabric runtime stopped; closing Pi."); @@ -259,7 +267,14 @@ export default function (pi) { if (supervisor.timer === undefined) { supervisor.timer = setInterval(beat, ${TERMINAL_HEARTBEAT_MS}); supervisor.timer.unref?.(); - process.once("exit", () => rmSync(ENTRY, { force: true })); + process.once("exit", () => { + // Best effort: a throw here would make process.exit() itself throw. + try { + rmSync(ENTRY, { force: true }); + } catch { + // The registration directory is unusable; stop finds no registration either way. + } + }); } pi.on("session_start", (_event, ctx) => { supervisor.context = ctx; @@ -442,9 +457,16 @@ export class PiTerminal { */ async withdraw(): Promise { if (this.withdrawn) return; - await rm(this.descriptorPath, { force: true }); - // No new launch gets the runtime's environment once stop has begun. + let unpublishError: unknown; + try { + await rm(this.descriptorPath, { force: true }); + } catch (error) { + unpublishError = error; + } + // No new launch gets the runtime's environment once stop has begun, even if the + // attachment file couldn't be removed. await this.server.close(); + if (unpublishError !== undefined) throw unpublishError; // Withdrawn only once the terminal UIs are closed, so a retried stop closes them again. await closeTerminals(this.clients); this.withdrawn = true; @@ -459,7 +481,17 @@ export class PiTerminal { async function closeTerminals(clients: string): Promise { // The attachment file is already gone. A terminal UI registers before it checks that file, // so any terminal UI that saw it published is registered now; any other closes itself. - await stopTerminals(await liveTerminals(clients), TERMINAL_STOP_GRACE_MS); + const { live, unverified } = await liveTerminals(clients); + await stopTerminals(live, TERMINAL_STOP_GRACE_MS); + if (unverified.length > 0) { + // Keep these registrations for a retry; remove the ones just closed. + for (const pid of live) await rm(join(clients, String(pid)), { force: true }); + throw new LifecycleError( + "pi_interface_cleanup_incomplete", + "A Pi terminal UI stopped its heartbeat and its process couldn't be verified, so it wasn't signalled", + { metadata: { pids: unverified } }, + ); + } await rm(clients, { recursive: true, force: true }); } @@ -500,7 +532,11 @@ export async function processIdentity(pid: number): Promise // No /proc: ask ps. } try { - const { stdout } = await execFileAsync("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8" }); + // lstart follows TZ and the locale; fix both so it matches what the supervisor recorded. + const { stdout } = await execFileAsync("ps", ["-o", "lstart=", "-p", String(pid)], { + encoding: "utf8", + env: { ...process.env, TZ: "UTC", LC_ALL: "C" }, + }); const start = stdout.trim().replace(/\s+/gu, " "); if (start.length > 0) return `ps:${start}`; } catch { @@ -517,45 +553,49 @@ export async function processIdentity(pid: number): Promise * signalled, since that could hit an unrelated process, but stop warns about it: the * terminal UI closes itself when it resumes and finds the attachment file gone. */ -async function liveTerminals(clients: string): Promise { +async function liveTerminals(clients: string): Promise<{ live: number[]; unverified: number[] }> { let entries: string[]; try { entries = await readdir(clients); } catch { - return []; + return { live: [], unverified: [] }; } const live: number[] = []; + const unverified: number[] = []; for (const name of entries) { const path = join(clients, name); const pid = Number(name); try { if (Number.isSafeInteger(pid) && pid > 1 && alive(pid)) { - // A heartbeat from the future (clock skew on a shared volume) is not current. - const age = Date.now() - (await stat(path)).mtimeMs; - const fresh = age >= -TERMINAL_HEARTBEAT_MS && age < TERMINAL_HEARTBEAT_STALE_MS; - if (fresh) { - live.push(pid); - continue; - } const recorded = (await readFile(path, "utf8")).trim(); const current = recorded.length > 0 ? await processIdentity(pid) : undefined; - if (current === undefined) { - process.stderr.write( - `Pi warning: terminal UI ${pid} stopped its heartbeat and its process identity can't be verified, ` + - "so stop doesn't signal it; it closes itself when it resumes\n", - ); - } else if (current === recorded) { - live.push(pid); + if (current !== undefined) { + // The recorded identity decides, fresh or not: a match is this terminal UI, even + // suspended; a mismatch is a later process reusing the PID of one that died. + if (current === recorded) { + live.push(pid); + continue; + } + } else { + // A heartbeat from the future (clock skew on a shared volume) is not current. + const age = Date.now() - (await stat(path)).mtimeMs; + if (age >= -TERMINAL_HEARTBEAT_MS && age < TERMINAL_HEARTBEAT_STALE_MS) { + // Unverifiable but heartbeating within the stale limit: this terminal UI. + live.push(pid); + continue; + } + // Unverifiable and stale: don't signal what could be another process, and keep + // the registration so a retried stop can verify it. + unverified.push(pid); continue; } - // Otherwise another process reuses the PID: drop the registration unsignalled. } } catch { // Removed while reading: that terminal UI exited. } await rm(path, { force: true }); } - return live; + return { live, unverified }; } /** @@ -686,9 +726,11 @@ export class PiTerminalSessionHandle implements PiSessionHandle { try { await this.terminal.withdraw(); } catch (error) { - failure = new LifecycleError("pi_interface_cleanup_failed", "Pi's terminal interface could not be withdrawn", { - metadata: { cause: error instanceof Error ? error.message : String(error) }, - }); + failure = error instanceof LifecycleError + ? error + : new LifecycleError("pi_interface_cleanup_failed", "Pi's terminal interface could not be withdrawn", { + metadata: { cause: error instanceof Error ? error.message : String(error) }, + }); } try { await this.inner.stop(); @@ -745,7 +787,15 @@ class PiTerminalInterface implements PiSessionFactory { if (!terminal) { return this.sdk.create(input); } - const handle = await (sdkEnabled(input.config) ? this.sdk : this.nativeOnly).create(input); + let handle: PiSessionHandle; + try { + handle = await (sdkEnabled(input.config) ? this.sdk : this.nativeOnly).create(input); + } catch (error) { + // A start that fails after writing Pi's files mustn't leave mcp.json, which can hold + // literal MCP stdio env values, in the kept runtime directory. + await rm(join(agentDirectory(runtimeDirectory(input)), "mcp.json"), { force: true }).catch(() => undefined); + throw error; + } let interfaceHandle: PiTerminal | undefined; try { if (handle.configuration === undefined) { diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index 1ee550db5..13a6e97c5 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -400,7 +400,7 @@ test("stopping the runtime closes an open terminal UI before the session stops", * A registered terminal UI that doesn't close itself when tui.json goes away, leading its own * process group as `openshell sandbox exec --tty` would start it, with a tool's child process in it. */ -async function fakeTerminal(clients, { ignoreSigterm, recordStart = false }) { +async function fakeTerminal(clients, { ignoreSigterm, recordStart = false, identity = "" }) { const source = ` import { spawn } from "node:child_process"; import { mkdirSync, writeFileSync } from "node:fs"; @@ -411,14 +411,21 @@ async function fakeTerminal(clients, { ignoreSigterm, recordStart = false }) { mkdirSync(clients, { recursive: true }); // As the supervisor extension records it: this process's identity. const identity = record === "record" - ? await (await import(terminalModule)).processIdentity(process.pid) : ""; - const beat = () => writeFileSync(join(clients, String(process.pid)), identity); + ? await (await import(terminalModule)).processIdentity(process.pid) : record; + const beat = () => { + try { + mkdirSync(clients, { recursive: true }); + writeFileSync(join(clients, String(process.pid)), identity); + } catch { + // Stop removed the registrations; keep running as a terminal UI would until signalled. + } + }; beat(); setInterval(beat, 200); console.log(tool.pid); `; const child = spawn(process.execPath, [ - "--input-type=module", "-e", source, clients, ignoreSigterm ? "ignore" : "exit", recordStart ? "record" : "", + "--input-type=module", "-e", source, clients, ignoreSigterm ? "ignore" : "exit", recordStart ? "record" : identity, new URL("../dist/terminal.js", import.meta.url).href, ], { detached: true, @@ -438,6 +445,30 @@ function running(pid) { } } +/** Whether a process is gone or a zombie awaiting reaping, within a bounded wait. */ +async function terminated(pid, timeoutMs = 3_000) { + const deadline = Date.now() + timeoutMs; + for (;;) { + if (!running(pid)) return true; + try { + const stat = await readFile(`/proc/${pid}/stat`, "utf8"); + if (stat.slice(stat.lastIndexOf(")") + 2).startsWith("Z")) return true; + } catch { + // No /proc: only the liveness probe applies. + } + if (Date.now() >= deadline) return false; + await new Promise((resolve) => setTimeout(resolve, 100)); + } +} + +/** Resume a stopped process and report whether it is still running a moment later. */ +async function survivesResume(pid) { + process.kill(pid, "SIGCONT"); + // A pending SIGTERM is delivered on resume, and the fixture's handler exits at once. + await new Promise((resolve) => setTimeout(resolve, 1_000)); + return running(pid); +} + test("processIdentity identifies a running process by its start time", async () => { const identity = await processIdentity(process.pid); assert.match(identity, process.platform === "linux" ? /^proc:\d+$/ : /^ps:\S/); @@ -515,12 +546,71 @@ test("a terminal UI that can't identify itself closes instead of running unmanag } }); -test("stop warns about, and doesn't signal, a stale terminal UI it can't verify", { skip, timeout: 60_000 }, async () => { +test("a terminal UI that can't register closes instead of running unregistered", { timeout: 30_000 }, async () => { + const directory = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-supervisor-register-"))); + try { + const descriptor = join(directory, "tui.json"); + await writeFile(descriptor, JSON.stringify({ runtime_id: "rt-supervisor" })); + // tui.clients can't be created: its parent is a file. + const blocker = join(directory, "blocker"); + await writeFile(blocker, ""); + const extension = join(directory, "fabric-terminal.mjs"); + await writeFile(extension, supervisorExtension(descriptor, join(blocker, "tui.clients"), "rt-supervisor")); + const host = ` + const [extension] = process.argv.slice(1); + const handlers = {}; + (await import(extension)).default({ on: (name, handler) => { handlers[name] = handler; } }); + handlers.session_start({}, { ui: { notify(message) { console.error(message); } }, shutdown() { process.exit(0); } }); + `; + const child = spawn(process.execPath, ["--input-type=module", "-e", host, extension], { stdio: ["ignore", "ignore", "pipe"] }); + let stderr = ""; + child.stderr.setEncoding("utf8").on("data", (chunk) => { stderr += chunk; }); + const code = await new Promise((resolve) => child.once("close", resolve)); + assert.equal(code, 0, stderr); + assert.match(stderr, /couldn't register/); + } finally { + await rm(directory, { recursive: true, force: true }); + } +}); + +test("the terminal interface refuses a model key named like a variable the launcher sets", { skip }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-key-reserved-"))); + try { + for (const name of ["PI_OFFLINE", "TERM"]) { + const input = startInput(workspace, "http://127.0.0.1:9/v1", { interfaces: { terminal: {} } }); + input.config.models.default.api_key_env = name; + input.runtimeContext.environment.env[name] = RUNTIME_KEY; + await assert.rejects(sessionFactory().create(input), { code: "pi_api_key_env_invalid" }, name); + } + } finally { + await rm(workspace, { recursive: true, force: true }); + } +}); + +test("the environment socket keeps every variable name, including __proto__, and empty header values", async () => { + const input = startInput("/workspace", "http://127.0.0.1:9/v1"); + input.runtimeContext.environment.env = JSON.parse('{"__proto__":"proto-value","ORDINARY":"1","EMPTY":""}'); + input.config.mcp = { servers: { remote: { transport: "streamable-http", url: "https://mcp.example.com/mcp", + custom_headers: { Authorization: "Bearer pre${EMPTY}post" } } } }; + const environment = terminalEnvironment(input, "TEST_API_KEY"); + assert.equal(Object.hasOwn(environment, "__proto__"), true); + assert.equal(environment.EMPTY, ""); + const server = await PiTerminalEnvironmentServer.start(environment); + try { + const fetched = await fetchTerminalEnvironment(server.socketPath); + assert.equal(Object.hasOwn(fetched, "__proto__"), true); + assert.equal(Object.getOwnPropertyDescriptor(fetched, "__proto__").value, "proto-value"); + assert.equal(fetched.ORDINARY, "1"); + assert.equal(fetched.EMPTY, ""); + } finally { + await server.close(); + } +}); + +test("stop doesn't signal a stale terminal UI it can't verify, keeps it for a retry and reports it", { skip, timeout: 60_000 }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-unverified-"))); const { server, url } = await modelServer(); const clients = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal", "interfaces", "tui.clients"); - const write = process.stderr.write; - let warnings = ""; let session; let terminal; try { @@ -530,18 +620,44 @@ test("stop warns about, and doesn't signal, a stale terminal UI it can't verify" process.kill(terminal.child.pid, "SIGSTOP"); await new Promise((resolve) => setTimeout(resolve, 3_500)); - process.stderr.write = (chunk, ...rest) => { - warnings += String(chunk); - return write.call(process.stderr, chunk, ...rest); - }; + await assert.rejects(session.stop(), { code: "pi_interface_cleanup_incomplete" }); + // Kept for a retry. + assert.equal(await exists(join(clients, String(terminal.child.pid))), true); + // Neither SIGTERM nor SIGKILL was sent: resumed, it keeps running. + assert.equal(await survivesResume(terminal.child.pid), true); + // Once the process is gone, a retried stop completes. + for (const pid of [-terminal.child.pid, terminal.tool]) try { process.kill(pid, "SIGKILL"); } catch {} + await terminal.exited; await session.stop(); session = undefined; - process.stderr.write = write; - assert.match(warnings, new RegExp(`terminal UI ${terminal.child.pid} stopped its heartbeat`)); - // Not signalled: an unverifiable PID could belong to another process. + assert.equal(await exists(clients), false); + } finally { + if (terminal !== undefined) { + for (const pid of [-terminal.child.pid, terminal.tool]) try { process.kill(pid, "SIGKILL"); } catch {} + } + await session?.stop().catch(() => undefined); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + +test("stop doesn't signal a freshly registered PID whose identity doesn't match", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-reused-"))); + const { server, url } = await modelServer(); + const clients = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal", "interfaces", "tui.clients"); + let session; + let terminal; + try { + session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + // As when a terminal UI died without removing its registration and another process + // took its PID: the heartbeat is current, but the recorded identity is someone else's. + terminal = await fakeTerminal(clients, { ignoreSigterm: false, identity: "proc:1" }); + await session.stop(); + session = undefined; + await new Promise((resolve) => setTimeout(resolve, 500)); assert.equal(running(terminal.child.pid), true); } finally { - process.stderr.write = write; if (terminal !== undefined) { for (const pid of [-terminal.child.pid, terminal.tool]) try { process.kill(pid, "SIGKILL"); } catch {} } @@ -569,7 +685,7 @@ test("stop closes a suspended terminal UI whose heartbeat went stale", { skip, t session = undefined; // SIGTERM waits while the process is stopped; the group SIGKILL after the grace period doesn't. assert.deepEqual(await terminal.exited, { code: null, signal: "SIGKILL" }); - assert.equal(running(terminal.tool), false); + assert.equal(await terminated(terminal.tool), true); } finally { if (terminal !== undefined) { for (const pid of [-terminal.child.pid, terminal.tool]) try { process.kill(pid, "SIGKILL"); } catch {} @@ -625,8 +741,8 @@ test("stop kills an open terminal UI's process group five seconds after SIGTERM" assert.deepEqual(await terminal.exited, { code: null, signal: "SIGKILL" }); assert.ok(elapsed >= 4_500 && elapsed < 7_000, `stop took ${elapsed} ms`); const deadline = Date.now() + 1_000; - while (running(terminal.tool) && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 50)); - assert.equal(running(terminal.tool), false, "the terminal UI's tool process outlived stop"); + assert.equal(await terminated(terminal.tool, Math.max(deadline - Date.now(), 0)), true, + "the terminal UI's tool process outlived stop"); } finally { if (terminal !== undefined) { for (const pid of [-terminal.child.pid, terminal.tool]) try { process.kill(pid, "SIGKILL"); } catch {} @@ -832,7 +948,7 @@ test("the terminal environment is the runtime's environment.env and model key, w PI_CODING_AGENT_DIR: "/elsewhere", NEMO_RELAY_PI_GATEWAY_URL: "http://127.0.0.1:1", }; - assert.deepEqual(terminalEnvironment(input, "TEST_API_KEY"), { TEST_API_KEY: RUNTIME_KEY, GITHUB_TOKEN: "ghp-runtime" }); + assert.deepEqual({ ...terminalEnvironment(input, "TEST_API_KEY") }, { TEST_API_KEY: RUNTIME_KEY, GITHUB_TOKEN: "ghp-runtime" }); for (const name of ["PI_CODING_AGENT_DIR", "PI_CODING_AGENT_SESSION_DIR", "NEMO_RELAY_PI_GATEWAY_URL"]) { assert.ok(LAUNCHER_ENV_NAMES.has(name), name); } @@ -840,7 +956,7 @@ test("the terminal environment is the runtime's environment.env and model key, w input.runtimeContext.environment.env = {}; process.env.FABRIC_TEST_PROCESS_KEY = "process-key"; try { - assert.deepEqual(terminalEnvironment(input, "FABRIC_TEST_PROCESS_KEY"), { FABRIC_TEST_PROCESS_KEY: "process-key" }); + assert.deepEqual({ ...terminalEnvironment(input, "FABRIC_TEST_PROCESS_KEY") }, { FABRIC_TEST_PROCESS_KEY: "process-key" }); } finally { delete process.env.FABRIC_TEST_PROCESS_KEY; } @@ -853,7 +969,7 @@ test("the terminal environment leaves the person's terminal variables and resolv custom_headers: { Authorization: "Bearer ${FABRIC_TEST_HEADER_TOKEN}" } } } }; process.env.FABRIC_TEST_HEADER_TOKEN = "from-adapter-process"; try { - assert.deepEqual(terminalEnvironment(input, "TEST_API_KEY"), { + assert.deepEqual({ ...terminalEnvironment(input, "TEST_API_KEY") }, { TEST_API_KEY: RUNTIME_KEY, LOG_LEVEL: "debug", FABRIC_TEST_HEADER_TOKEN: "from-adapter-process", From eca9e582fd932db4790b987d151705a5ba20f315 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 11:58:30 -0800 Subject: [PATCH 11/25] fix: register Pi terminal launches before they get the environment The launch helper now writes its registration, with its process identity, before it fetches the runtime's environment, and refuses to start Pi if it can't register. Stop closes the environment socket before it scans registrations, so every process that obtained the environment is registered by then, however long it pauses before Pi starts, and one that fetches later finds the socket closed. execve keeps the PID and the identity, so Pi's supervisor keeps heartbeating the same registration. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- adapters/typescript/pi/src/terminal-client.ts | 31 +++++ adapters/typescript/pi/src/terminal-launch.ts | 44 +++++-- adapters/typescript/pi/test/terminal.test.mjs | 109 ++++++++++++++++++ 3 files changed, 175 insertions(+), 9 deletions(-) diff --git a/adapters/typescript/pi/src/terminal-client.ts b/adapters/typescript/pi/src/terminal-client.ts index 5a487aa2a..8a2081440 100644 --- a/adapters/typescript/pi/src/terminal-client.ts +++ b/adapters/typescript/pi/src/terminal-client.ts @@ -4,8 +4,39 @@ // The terminal launch helper's side of the runtime's environment socket. It uses only // Node built-ins, so the helper loads nothing else before it starts Pi. +import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; import { connect } from "node:net"; +/** + * This process's identity, as the adapter's processIdentity() and the generated + * supervisor extension compute it: `proc:` from /proc, else `ps:` + * read with TZ=UTC and LC_ALL=C, else "". It doesn't change across execve. + */ +export function ownProcessIdentity(): string { + try { + const stat = readFileSync("/proc/self/stat", "utf8"); + const start = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]; + if (start !== undefined && /^\d+$/u.test(start)) return `proc:${start}`; + } catch { + // No /proc: ask ps. + } + // The launcher's PATH is the person's, so look in the usual places too. + for (const ps of ["ps", "/bin/ps", "/usr/bin/ps"]) { + try { + const start = execFileSync(ps, ["-o", "lstart=", "-p", String(process.pid)], { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + env: { ...process.env, TZ: "UTC", LC_ALL: "C" }, + }).trim().replace(/\s+/gu, " "); + if (start.length > 0) return `ps:${start}`; + } catch { + // Try the next location. + } + } + return ""; +} + const FETCH_TIMEOUT_MS = 5_000; function isRecord(value: unknown): value is Record { diff --git a/adapters/typescript/pi/src/terminal-launch.ts b/adapters/typescript/pi/src/terminal-launch.ts index 9d4e86e18..2c4bbf4be 100644 --- a/adapters/typescript/pi/src/terminal-launch.ts +++ b/adapters/typescript/pi/src/terminal-launch.ts @@ -2,19 +2,31 @@ // SPDX-License-Identifier: Apache-2.0 // The launch helper the terminal launcher execs: `node terminal-launch.js -// [pi arguments...]`. It reads the runtime's attachment file, fetches the -// runtime's environment (environment.env and the model key) over the runtime's -// owner-only socket, and replaces itself with `node [pi arguments...]` under -// that environment. execve keeps the PID, and Node reads startup variables such as -// NODE_OPTIONS and NODE_EXTRA_CA_CERTS as it would for the SDK session's process. -// Nothing is written to disk. +// [pi arguments...]`. It registers this process with the runtime, reads the +// runtime's attachment file, fetches the runtime's environment (environment.env and +// the model key) over the runtime's owner-only socket, and replaces itself with +// `node [pi arguments...]` under that environment. execve keeps the PID and +// the process identity, so the terminal UI's supervisor keeps the same registration, +// and Node reads startup variables such as NODE_OPTIONS and NODE_EXTRA_CA_CERTS as it +// would for the SDK session's process. No secret is written to disk. -import { readFileSync } from "node:fs"; +import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; import { pathToFileURL } from "node:url"; -import { fetchTerminalEnvironment, isRecord } from "./terminal-client.js"; +import { fetchTerminalEnvironment, isRecord, ownProcessIdentity } from "./terminal-client.js"; + +const [descriptorPath, cli, ...args] = process.argv.slice(2); +let registration: string | undefined; function unavailable(reason: string): never { + if (registration !== undefined) { + try { + rmSync(registration, { force: true }); + } catch { + // Stop drops a registration whose process is gone. + } + } // Only a reason code: an error message could quote part of a response. process.stderr.write( `This NeMo Fabric runtime is not running, or its terminal environment is unavailable (${reason}).\n`, @@ -28,9 +40,23 @@ function reasonOf(error: unknown): string { return error instanceof SyntaxError ? "invalid response" : "error"; } -const [descriptorPath, cli, ...args] = process.argv.slice(2); if (descriptorPath === undefined || cli === undefined) unavailable("usage"); +// Register before fetching the environment. Stop closes the environment socket before it +// scans registrations, so any process that obtained the runtime's environment is +// registered by then, however long it pauses before Pi starts; one that fetches later +// finds the socket closed and never starts Pi. +const identity = ownProcessIdentity(); +if (identity.length === 0) unavailable("no process identity"); +try { + const clients = join(dirname(descriptorPath), "tui.clients"); + mkdirSync(clients, { recursive: true, mode: 0o700 }); + registration = join(clients, String(process.pid)); + writeFileSync(registration, identity, { mode: 0o600 }); +} catch (error) { + unavailable(`registration ${reasonOf(error)}`); +} + let socketPath: string; try { const descriptor: unknown = JSON.parse(readFileSync(descriptorPath, "utf8")); diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index 13a6e97c5..a602bc558 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -3,6 +3,7 @@ import assert from "node:assert/strict"; import { spawn } from "node:child_process"; +import { existsSync } from "node:fs"; import { access, mkdir, mkdtemp, readdir, readFile, realpath, rm, stat, writeFile } from "node:fs/promises"; import { createServer } from "node:http"; import { connect, createServer as createNetServer } from "node:net"; @@ -375,6 +376,13 @@ test("stopping the runtime closes an open terminal UI before the session stops", await new Promise((resolve) => setTimeout(resolve, 100)); } assert.deepEqual(await readdir(registry), [String(terminal.child.pid)]); + // The launch helper registers first; a heartbeat shows Pi itself, and its handlers, are up. + const registration = join(registry, String(terminal.child.pid)); + const registered = (await stat(registration)).mtimeMs; + while ((await stat(registration)).mtimeMs === registered) { + assert.ok(Date.now() < deadline, "the terminal UI never sent a heartbeat"); + await new Promise((resolve) => setTimeout(resolve, 100)); + } const started = Date.now(); await session.stop(); @@ -607,6 +615,107 @@ test("the environment socket keeps every variable name, including __proto__, and } }); +const LAUNCH_HELPER = new URL("../dist/terminal-launch.js", import.meta.url).pathname; +/** A stand-in for the pi CLI: prints what it was started with, then waits. */ +const STAND_IN_CLI = `console.log(JSON.stringify({ pid: process.pid, value: process.env.FROM_RUNTIME ?? null })); +setTimeout(() => {}, Number(process.argv[2] ?? 0)); +`; + +function runHelper(descriptor, cli, args = []) { + const child = spawn(process.execPath, ["--disable-warning=ExperimentalWarning", LAUNCH_HELPER, descriptor, cli, ...args], { + detached: true, + stdio: ["ignore", "pipe", "pipe"], + }); + let stdout = ""; + let stderr = ""; + child.stdout.setEncoding("utf8").on("data", (chunk) => { stdout += chunk; }); + child.stderr.setEncoding("utf8").on("data", (chunk) => { stderr += chunk; }); + const exited = new Promise((resolve) => child.once("close", (code, signal) => resolve({ code, signal, stdout, stderr }))); + return { child, exited }; +} + +test("the launch helper registers before it fetches the runtime's environment", { timeout: 30_000 }, async () => { + const directory = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-helper-order-"))); + const socket = join(directory, "env.sock"); + let registeredAtFetch; + let helper; + const server = createNetServer((connection) => { + registeredAtFetch = existsSync(join(directory, "tui.clients", String(helper.child.pid))); + connection.end(JSON.stringify({ version: 1, env: { FROM_RUNTIME: "from-runtime" } })); + }); + await new Promise((resolve) => server.listen(socket, resolve)); + try { + await writeFile(join(directory, "tui.json"), JSON.stringify({ env_socket: socket })); + await writeFile(join(directory, "cli.mjs"), STAND_IN_CLI); + helper = runHelper(join(directory, "tui.json"), join(directory, "cli.mjs")); + const run = await helper.exited; + assert.equal(run.code, 0, run.stderr); + // A stop that closes the socket before scanning sees every process that got the environment. + assert.equal(registeredAtFetch, true); + // execve kept the PID, under which it registered, and the runtime's value reached it. + assert.deepEqual(JSON.parse(run.stdout), { pid: helper.child.pid, value: "from-runtime" }); + } finally { + server.close(); + await rm(directory, { recursive: true, force: true }); + } +}); + +test("the launch helper refuses to start Pi when it can't register", { timeout: 30_000 }, async () => { + const directory = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-helper-register-"))); + const socket = join(directory, "env.sock"); + let fetched = false; + const server = createNetServer((connection) => { + fetched = true; + connection.end(JSON.stringify({ version: 1, env: {} })); + }); + await new Promise((resolve) => server.listen(socket, resolve)); + try { + await writeFile(join(directory, "tui.json"), JSON.stringify({ env_socket: socket })); + // The registry can't be created: a file is in its place. + await writeFile(join(directory, "tui.clients"), ""); + await writeFile(join(directory, "cli.mjs"), STAND_IN_CLI); + const run = await runHelper(join(directory, "tui.json"), join(directory, "cli.mjs")).exited; + assert.equal(run.code, 1); + assert.match(run.stderr, /registration/); + assert.equal(run.stdout, ""); + assert.equal(fetched, false); + } finally { + server.close(); + await rm(directory, { recursive: true, force: true }); + } +}); + +test("stop kills a launch suspended after it registered", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-paused-launch-"))); + const { server, url } = await modelServer(); + let session; + let helper; + try { + session = await sessionFactory().create(startInput(workspace, url, { sdk: { enabled: false }, interfaces: { terminal: {} } })); + const interfaces = join(session.configuration.runtimeDir, "interfaces"); + await writeFile(join(workspace, "cli.mjs"), STAND_IN_CLI); + helper = runHelper(join(interfaces, "tui.json"), join(workspace, "cli.mjs"), ["60000"]); + const registration = join(interfaces, "tui.clients", String(helper.child.pid)); + const deadline = Date.now() + 10_000; + while (!existsSync(registration) && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 20)); + assert.equal(existsSync(registration), true); + // Suspended mid-launch, before Pi's own supervisor would ever heartbeat. + process.kill(helper.child.pid, "SIGSTOP"); + await session.stop(); + session = undefined; + // Without a handler, SIGTERM's default action kills even a stopped process; with one, + // the group SIGKILL after the grace period does. Either way stop ended the launch. + const run = await helper.exited; + assert.ok(["SIGTERM", "SIGKILL"].includes(run.signal), `exit ${run.code} ${run.signal}`); + } finally { + if (helper !== undefined) try { process.kill(-helper.child.pid, "SIGKILL"); } catch {} + await session?.stop().catch(() => undefined); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + test("stop doesn't signal a stale terminal UI it can't verify, keeps it for a retry and reports it", { skip, timeout: 60_000 }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-unverified-"))); const { server, url } = await modelServer(); From 20869e1db6fadd3e7fdfe6abb79ea247a8b050ba Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 12:04:22 -0800 Subject: [PATCH 12/25] chore: stop asking for the model key in the Pi TUI example The launcher now fetches the runtime's model key itself, so the example no longer tells the person to set it before running the launcher. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- examples/interfaces/pi/pi_tui.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/interfaces/pi/pi_tui.py b/examples/interfaces/pi/pi_tui.py index 5d0d48060..1a8b58716 100644 --- a/examples/interfaces/pi/pi_tui.py +++ b/examples/interfaces/pi/pi_tui.py @@ -93,7 +93,8 @@ async def interactive(args: argparse.Namespace, output: Path) -> None: ) print(f"Runtime {runtime.runtime_id} is ready.", flush=True) print( - f"In a second terminal, with {args.api_key_env} set, run:\n {shlex.quote(str(launcher))}", + # The launcher fetches the runtime's model key itself; nothing needs exporting. + f"In a second terminal, run:\n {shlex.quote(str(launcher))}", flush=True, ) print( From e818fe6657adac3c3befd3397cefc3da10f926b1 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 12:16:57 -0800 Subject: [PATCH 13/25] fix: bind Pi terminal launches to their runtime and verify before signalling - The launcher passes its runtime ID; the launch helper refuses a tui.json another runtime of the agent published at the same path. - Re-check a terminal UI's identity before any per-process signal; group signals stay safe because the kernel doesn't reuse an in-use group ID. - Keep, and report as incomplete, a live terminal UI whose registration can't be read, and treat only a missing registry as empty. - Close registered terminal UIs even when removing tui.json fails, and keep the withdrawal retryable. - Write registrations atomically, so a failed heartbeat never leaves one without its identity. - Refuse MCP headers that reference variables the terminal UI sets itself. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- .../typescript/pi/src/native-configuration.ts | 14 +- .../typescript/pi/src/terminal-environment.ts | 2 +- adapters/typescript/pi/src/terminal-launch.ts | 23 +-- adapters/typescript/pi/src/terminal.ts | 135 +++++++++++------- adapters/typescript/pi/test/terminal.test.mjs | 91 ++++++++++-- 5 files changed, 191 insertions(+), 74 deletions(-) diff --git a/adapters/typescript/pi/src/native-configuration.ts b/adapters/typescript/pi/src/native-configuration.ts index 5b91eb453..ec552a337 100644 --- a/adapters/typescript/pi/src/native-configuration.ts +++ b/adapters/typescript/pi/src/native-configuration.ts @@ -18,7 +18,7 @@ import { LifecycleError, type AdapterStartInput } from "nemo-fabric-adapters-com import { agentDirectory, keepsState, runtimeDirectory, sessionDirectory, writeAgentDirectory } from "./agent-directory.js"; import { terminalEnabled } from "./settings.js"; -import { LAUNCHER_ENV_NAMES, TERMINAL_ENV_NAMES } from "./terminal-environment.js"; +import { LAUNCHER_ENV_NAMES, mcpHeaderVariables, TERMINAL_ENV_NAMES } from "./terminal-environment.js"; export interface PiNativeCustomTool { name: string; @@ -844,6 +844,18 @@ export async function preparePiConfiguration(input: AdapterStartInput): Promise< { metadata: { field: "models.api_key_env" } }, ); } + const reservedHeaderVariables = terminal + ? mcpHeaderVariables(input.config).filter((name) => LAUNCHER_ENV_NAMES.has(name) || TERMINAL_ENV_NAMES.has(name)) + : []; + if (reservedHeaderVariables.length > 0) { + // The terminal UI's environment never takes the runtime's value for these names, so a + // header that references one would resolve differently there than in the SDK session. + throw new LifecycleError( + "pi_mcp_header_variable_reserved", + "Pi's terminal interface sets the variables an MCP header references; reference other variables", + { metadata: { variables: reservedHeaderVariables } }, + ); + } if (terminal && (LAUNCHER_ENV_NAMES.has(apiKeyEnv) || TERMINAL_ENV_NAMES.has(apiKeyEnv))) { // The terminal UI's environment never takes the runtime's value for these names. throw new LifecycleError( diff --git a/adapters/typescript/pi/src/terminal-environment.ts b/adapters/typescript/pi/src/terminal-environment.ts index 48cbe1d47..6ea81d9f0 100644 --- a/adapters/typescript/pi/src/terminal-environment.ts +++ b/adapters/typescript/pi/src/terminal-environment.ts @@ -49,7 +49,7 @@ const CONNECTION_TIMEOUT_MS = 5_000; const ENV_REFERENCE = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/gu; /** The variables MCP HTTP headers reference, which the SDK session resolves from the runtime's environment. */ -function mcpHeaderVariables(config: AgentConfig): string[] { +export function mcpHeaderVariables(config: AgentConfig): string[] { const names = new Set(); for (const server of Object.values(config.mcp?.servers ?? {})) { for (const value of Object.values(server.custom_headers ?? {})) { diff --git a/adapters/typescript/pi/src/terminal-launch.ts b/adapters/typescript/pi/src/terminal-launch.ts index 2c4bbf4be..d85e042f7 100644 --- a/adapters/typescript/pi/src/terminal-launch.ts +++ b/adapters/typescript/pi/src/terminal-launch.ts @@ -2,21 +2,22 @@ // SPDX-License-Identifier: Apache-2.0 // The launch helper the terminal launcher execs: `node terminal-launch.js -// [pi arguments...]`. It registers this process with the runtime, reads the -// runtime's attachment file, fetches the runtime's environment (environment.env and -// the model key) over the runtime's owner-only socket, and replaces itself with -// `node [pi arguments...]` under that environment. execve keeps the PID and +// [pi arguments...]`. It registers this process with the runtime, +// reads the runtime's attachment file and checks it belongs to that runtime, fetches the +// runtime's environment (environment.env and the model key) over the runtime's +// owner-only socket, and replaces itself with `node [pi arguments...]` under +// that environment. execve keeps the PID and // the process identity, so the terminal UI's supervisor keeps the same registration, // and Node reads startup variables such as NODE_OPTIONS and NODE_EXTRA_CA_CERTS as it // would for the SDK session's process. No secret is written to disk. -import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { pathToFileURL } from "node:url"; import { fetchTerminalEnvironment, isRecord, ownProcessIdentity } from "./terminal-client.js"; -const [descriptorPath, cli, ...args] = process.argv.slice(2); +const [descriptorPath, runtimeId, cli, ...args] = process.argv.slice(2); let registration: string | undefined; function unavailable(reason: string): never { @@ -40,7 +41,7 @@ function reasonOf(error: unknown): string { return error instanceof SyntaxError ? "invalid response" : "error"; } -if (descriptorPath === undefined || cli === undefined) unavailable("usage"); +if (descriptorPath === undefined || runtimeId === undefined || cli === undefined) unavailable("usage"); // Register before fetching the environment. Stop closes the environment socket before it // scans registrations, so any process that obtained the runtime's environment is @@ -52,7 +53,10 @@ try { const clients = join(dirname(descriptorPath), "tui.clients"); mkdirSync(clients, { recursive: true, mode: 0o700 }); registration = join(clients, String(process.pid)); - writeFileSync(registration, identity, { mode: 0o600 }); + // Written whole, then renamed into place: a registration never holds a partial identity. + const staging = `${registration}.tmp`; + writeFileSync(staging, identity, { mode: 0o600 }); + renameSync(staging, registration); } catch (error) { unavailable(`registration ${reasonOf(error)}`); } @@ -61,6 +65,9 @@ let socketPath: string; try { const descriptor: unknown = JSON.parse(readFileSync(descriptorPath, "utf8")); if (!isRecord(descriptor) || typeof descriptor.env_socket !== "string") unavailable("no env_socket"); + // With runtime.keep_state, a later runtime of the agent publishes tui.json at the same + // path; this launcher's arguments belong to the runtime that wrote it. + if (descriptor.runtime_id !== runtimeId) unavailable("another runtime"); socketPath = descriptor.env_socket; } catch (error) { unavailable(error instanceof SyntaxError ? "invalid tui.json" : reasonOf(error)); diff --git a/adapters/typescript/pi/src/terminal.ts b/adapters/typescript/pi/src/terminal.ts index ab084400b..502463941 100644 --- a/adapters/typescript/pi/src/terminal.ts +++ b/adapters/typescript/pi/src/terminal.ts @@ -128,6 +128,8 @@ export function launcherScript(options: { sessionDir: string; workspace: string; descriptor: string; + /** The runtime that writes this launcher; the helper refuses another runtime's tui.json. */ + runtimeId: string; args: string[]; environment?: Readonly>; }): string { @@ -155,7 +157,7 @@ export function launcherScript(options: { ...exports, `cd ${shellQuote(options.workspace)} || exit 1`, // The helper uses process.execve, still experimental in Node; keep its warning off the TUI. - `exec ${[options.node, "--disable-warning=ExperimentalWarning", options.helper, options.descriptor, options.cli, + `exec ${[options.node, "--disable-warning=ExperimentalWarning", options.helper, options.descriptor, options.runtimeId, options.cli, ...options.args].map(shellQuote).join(" ")} "$@"`, "", ].join("\n"); @@ -170,13 +172,14 @@ export function launcherScript(options: { export function supervisorExtension(descriptor: string, clients: string, runtimeId: string): string { return `// Generated by the NeMo Fabric Pi adapter. Ties this terminal UI to its runtime. import { execFileSync } from "node:child_process"; -import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; const DESCRIPTOR = ${JSON.stringify(descriptor)}; const CLIENTS = ${JSON.stringify(clients)}; const RUNTIME_ID = ${JSON.stringify(runtimeId)}; const ENTRY = join(CLIENTS, String(process.pid)); +const STAGING = ENTRY + ".tmp"; // This process's identity, recorded with its PID, so the runtime can still signal it // while its heartbeat is stale (a suspended terminal UI) without signalling a later @@ -248,7 +251,10 @@ function beat() { // itself, however long it pauses in between. try { mkdirSync(CLIENTS, { recursive: true, mode: 0o700 }); - writeFileSync(ENTRY, IDENTITY, { mode: 0o600 }); + // Written whole, then renamed into place: a failed write never leaves the registration + // without its identity, which stop needs to close a suspended terminal UI. + writeFileSync(STAGING, IDENTITY, { mode: 0o600 }); + renameSync(STAGING, ENTRY); supervisor.registered = true; } catch { // Unregistered, stop couldn't find this terminal UI: don't run that way. A later @@ -409,6 +415,7 @@ export class PiTerminal { sessionDir, workspace: plan.workspace, descriptor: descriptorPath, + runtimeId, args: terminalArguments(plan, extensions), environment: relay?.extensionEnvironment, }), 0o700); @@ -466,9 +473,10 @@ export class PiTerminal { // No new launch gets the runtime's environment once stop has begun, even if the // attachment file couldn't be removed. await this.server.close(); - if (unpublishError !== undefined) throw unpublishError; - // Withdrawn only once the terminal UIs are closed, so a retried stop closes them again. + // Close terminal UIs even then: a suspended one can't close itself. Withdrawn only once + // the attachment file is gone and the terminal UIs are closed, so a retry repeats both. await closeTerminals(this.clients); + if (unpublishError !== undefined) throw unpublishError; this.withdrawn = true; } } @@ -485,31 +493,37 @@ async function closeTerminals(clients: string): Promise { await stopTerminals(live, TERMINAL_STOP_GRACE_MS); if (unverified.length > 0) { // Keep these registrations for a retry; remove the ones just closed. - for (const pid of live) await rm(join(clients, String(pid)), { force: true }); + for (const terminal of live) await rm(join(clients, String(terminal.pid)), { force: true }); throw new LifecycleError( "pi_interface_cleanup_incomplete", - "A Pi terminal UI stopped its heartbeat and its process couldn't be verified, so it wasn't signalled", + "A Pi terminal UI's registration or process couldn't be verified, so it wasn't signalled", { metadata: { pids: unverified } }, ); } await rm(clients, { recursive: true, force: true }); } +/** A registered terminal UI: its PID and the identity it recorded, if any. */ +interface RegisteredTerminal { + pid: number; + identity: string; +} + /** SIGTERM each terminal UI's process group, then SIGKILL the groups after the grace period. */ -async function stopTerminals(terminals: readonly number[], graceMs: number): Promise { +async function stopTerminals(terminals: readonly RegisteredTerminal[], graceMs: number): Promise { if (terminals.length === 0) return; - signal(terminals, "SIGTERM"); + await signal(terminals, "SIGTERM"); const exited = new Set(); const deadline = Date.now() + graceMs; for (;;) { - for (const pid of terminals) if (!alive(pid)) exited.add(pid); + for (const { pid } of terminals) if (!alive(pid)) exited.add(pid); if (exited.size === terminals.length || Date.now() >= deadline) break; await sleep(100); } // The group too: processes the terminal UI's tools started can outlive it. A terminal UI // seen to exit gets no signal of its own, since its PID may now belong to another process. - signal(terminals.filter((pid) => !exited.has(pid)), "SIGKILL"); - signal(terminals.filter((pid) => exited.has(pid)), "SIGKILL", { groupOnly: true }); + await signal(terminals.filter(({ pid }) => !exited.has(pid)), "SIGKILL"); + await signal(terminals.filter(({ pid }) => exited.has(pid)), "SIGKILL", { groupOnly: true }); } function sleep(ms: number): Promise { @@ -553,47 +567,56 @@ export async function processIdentity(pid: number): Promise * signalled, since that could hit an unrelated process, but stop warns about it: the * terminal UI closes itself when it resumes and finds the attachment file gone. */ -async function liveTerminals(clients: string): Promise<{ live: number[]; unverified: number[] }> { +async function liveTerminals(clients: string): Promise<{ live: RegisteredTerminal[]; unverified: number[] }> { let entries: string[]; try { entries = await readdir(clients); - } catch { - return { live: [], unverified: [] }; + } catch (error) { + // Only a missing registry is an empty one; one that can't be read may hide terminal UIs. + if ((error as NodeJS.ErrnoException).code === "ENOENT") return { live: [], unverified: [] }; + throw new LifecycleError("pi_interface_cleanup_incomplete", "Pi's terminal UI registrations couldn't be read", { + metadata: { cause: (error as NodeJS.ErrnoException).code ?? "error" }, + }); } - const live: number[] = []; + const live: RegisteredTerminal[] = []; const unverified: number[] = []; for (const name of entries) { const path = join(clients, name); const pid = Number(name); + if (!Number.isSafeInteger(pid) || pid <= 1 || !alive(pid)) { + // Not a registration (such as a staging file), or its process is gone. + await rm(path, { force: true }); + continue; + } + let recorded: string; + let mtimeMs: number; try { - if (Number.isSafeInteger(pid) && pid > 1 && alive(pid)) { - const recorded = (await readFile(path, "utf8")).trim(); - const current = recorded.length > 0 ? await processIdentity(pid) : undefined; - if (current !== undefined) { - // The recorded identity decides, fresh or not: a match is this terminal UI, even - // suspended; a mismatch is a later process reusing the PID of one that died. - if (current === recorded) { - live.push(pid); - continue; - } - } else { - // A heartbeat from the future (clock skew on a shared volume) is not current. - const age = Date.now() - (await stat(path)).mtimeMs; - if (age >= -TERMINAL_HEARTBEAT_MS && age < TERMINAL_HEARTBEAT_STALE_MS) { - // Unverifiable but heartbeating within the stale limit: this terminal UI. - live.push(pid); - continue; - } - // Unverifiable and stale: don't signal what could be another process, and keep - // the registration so a retried stop can verify it. - unverified.push(pid); - continue; - } - } - } catch { - // Removed while reading: that terminal UI exited. + recorded = (await readFile(path, "utf8")).trim(); + mtimeMs = (await stat(path)).mtimeMs; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; // That terminal UI exited. + // Unreadable while its PID lives: keep it for a retry, don't signal it. + unverified.push(pid); + continue; + } + const current = recorded.length > 0 ? await processIdentity(pid) : undefined; + if (current !== undefined) { + // The recorded identity decides, fresh or not: a match is this terminal UI, even + // suspended; a mismatch is a later process reusing the PID of one that died. + if (current === recorded) live.push({ pid, identity: recorded }); + else await rm(path, { force: true }); + continue; } - await rm(path, { force: true }); + // A heartbeat from the future (clock skew on a shared volume) is not current. + const age = Date.now() - mtimeMs; + if (age >= -TERMINAL_HEARTBEAT_MS && age < TERMINAL_HEARTBEAT_STALE_MS) { + // Unverifiable but heartbeating within the stale limit: this terminal UI. + live.push({ pid, identity: recorded }); + continue; + } + // Unverifiable and stale: don't signal what could be another process, and keep the + // registration so a retried stop can verify it. + unverified.push(pid); } return { live, unverified }; } @@ -641,20 +664,24 @@ function alive(pid: number): boolean { * OpenShell denies group signals (EPERM), and a terminal UI that doesn't lead its * own group has none under its PID (ESRCH). */ -function signal(pids: readonly number[], name: NodeJS.Signals, options: { groupOnly?: boolean } = {}): void { - for (const pid of pids) { - // Signal the process itself only while it still runs, and never for a terminal UI - // already seen to exit: its PID may belong to another process by now. - const fallback = options.groupOnly !== true && alive(pid); +async function signal(terminals: readonly RegisteredTerminal[], name: NodeJS.Signals, + options: { groupOnly?: boolean } = {}): Promise { + for (const { pid, identity } of terminals) { try { + // Safe after the leader exits: the kernel doesn't reuse a PID still in use as a group ID. process.kill(-pid, name); + continue; } catch { - if (!fallback) continue; - try { - process.kill(pid, name); - } catch { - // It has exited. - } + // Not a group leader, or group signals are denied (OpenShell): signal the process. + } + // Never a terminal UI already seen to exit, and only while the PID is still the same + // process: between polls it may have been reused. + if (options.groupOnly === true || !alive(pid)) continue; + if (identity.length > 0 && await processIdentity(pid) !== identity) continue; + try { + process.kill(pid, name); + } catch { + // It has exited. } } } diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index a602bc558..4b222e025 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -4,12 +4,13 @@ import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { existsSync } from "node:fs"; -import { access, mkdir, mkdtemp, readdir, readFile, realpath, rm, stat, writeFile } from "node:fs/promises"; +import { access, chmod, mkdir, mkdtemp, readdir, readFile, realpath, rm, stat, writeFile } from "node:fs/promises"; import { createServer } from "node:http"; import { connect, createServer as createNetServer } from "node:net"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import test from "node:test"; +import { fileURLToPath } from "node:url"; import { PiSdkSessionFactory } from "../dist/pi-sdk.js"; import { sdkEnabled } from "../dist/settings.js"; @@ -203,13 +204,14 @@ test("the launcher quotes its paths and refuses to run without the tui.json desc sessionDir: "/s", workspace: "/w", descriptor: "/m", + runtimeId: "rt-launcher", args: ["--no-approve"], }); assert.match(script, /^#!\/bin\/sh\n/); assert.match(script, /if \[ ! -e '\/m' \]; then/); assert.match(script, /export PI_CODING_AGENT_DIR='\/a'\\''b'/); // The launch helper fetches the runtime's environment, then runs the CLI with the arguments. - assert.match(script, /exec '\/usr\/bin\/node' '--disable-warning=ExperimentalWarning' '\/opt\/fabric\/terminal-launch.js' '\/m' '\/opt\/pi\/cli.js' '--no-approve' "\$@"\n$/); + assert.match(script, /exec '\/usr\/bin\/node' '--disable-warning=ExperimentalWarning' '\/opt\/fabric\/terminal-launch.js' '\/m' 'rt-launcher' '\/opt\/pi\/cli.js' '--no-approve' "\$@"\n$/); }); test("the terminal factory passes a session through unchanged without interfaces.terminal", async () => { @@ -615,14 +617,16 @@ test("the environment socket keeps every variable name, including __proto__, and } }); -const LAUNCH_HELPER = new URL("../dist/terminal-launch.js", import.meta.url).pathname; +const LAUNCH_HELPER = fileURLToPath(new URL("../dist/terminal-launch.js", import.meta.url)); /** A stand-in for the pi CLI: prints what it was started with, then waits. */ const STAND_IN_CLI = `console.log(JSON.stringify({ pid: process.pid, value: process.env.FROM_RUNTIME ?? null })); setTimeout(() => {}, Number(process.argv[2] ?? 0)); `; -function runHelper(descriptor, cli, args = []) { - const child = spawn(process.execPath, ["--disable-warning=ExperimentalWarning", LAUNCH_HELPER, descriptor, cli, ...args], { +function runHelper(descriptor, cli, args = [], runtimeId = "rt-helper") { + const child = spawn(process.execPath, [ + "--disable-warning=ExperimentalWarning", LAUNCH_HELPER, descriptor, runtimeId, cli, ...args, + ], { detached: true, stdio: ["ignore", "pipe", "pipe"], }); @@ -645,7 +649,7 @@ test("the launch helper registers before it fetches the runtime's environment", }); await new Promise((resolve) => server.listen(socket, resolve)); try { - await writeFile(join(directory, "tui.json"), JSON.stringify({ env_socket: socket })); + await writeFile(join(directory, "tui.json"), JSON.stringify({ runtime_id: "rt-helper", env_socket: socket })); await writeFile(join(directory, "cli.mjs"), STAND_IN_CLI); helper = runHelper(join(directory, "tui.json"), join(directory, "cli.mjs")); const run = await helper.exited; @@ -670,7 +674,7 @@ test("the launch helper refuses to start Pi when it can't register", { timeout: }); await new Promise((resolve) => server.listen(socket, resolve)); try { - await writeFile(join(directory, "tui.json"), JSON.stringify({ env_socket: socket })); + await writeFile(join(directory, "tui.json"), JSON.stringify({ runtime_id: "rt-helper", env_socket: socket })); // The registry can't be created: a file is in its place. await writeFile(join(directory, "tui.clients"), ""); await writeFile(join(directory, "cli.mjs"), STAND_IN_CLI); @@ -685,6 +689,73 @@ test("the launch helper refuses to start Pi when it can't register", { timeout: } }); +test("the launch helper refuses another runtime's tui.json", { timeout: 30_000 }, async () => { + const directory = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-helper-runtime-"))); + const socket = join(directory, "env.sock"); + let fetched = false; + const server = createNetServer((connection) => { + fetched = true; + connection.end(JSON.stringify({ version: 1, env: {} })); + }); + await new Promise((resolve) => server.listen(socket, resolve)); + try { + // A later runtime of the agent published at the same path (runtime.keep_state). + await writeFile(join(directory, "tui.json"), JSON.stringify({ runtime_id: "rt-later", env_socket: socket })); + await writeFile(join(directory, "cli.mjs"), STAND_IN_CLI); + const run = await runHelper(join(directory, "tui.json"), join(directory, "cli.mjs"), [], "rt-earlier").exited; + assert.equal(run.code, 1); + assert.match(run.stderr, /another runtime/); + assert.equal(fetched, false); + assert.equal(run.stdout, ""); + } finally { + server.close(); + await rm(directory, { recursive: true, force: true }); + } +}); + +test("the terminal interface refuses MCP headers that reference variables it sets", { skip }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-header-reserved-"))); + try { + const input = startInput(workspace, "http://127.0.0.1:9/v1", { interfaces: { terminal: {} } }); + input.config.mcp = { servers: { remote: { transport: "streamable-http", url: "https://mcp.example.com/mcp", + custom_headers: { Authorization: "Bearer ${TERM}" } } } }; + input.runtimeContext.environment.env.TERM = "runtime-value"; + await assert.rejects(sessionFactory().create(input), { code: "pi_mcp_header_variable_reserved" }); + } finally { + await rm(workspace, { recursive: true, force: true }); + } +}); + +test("stop keeps, and doesn't signal, a live terminal UI whose registration can't be read", { + skip: skip || (process.getuid?.() === 0 ? "root reads any file" : false), + timeout: 60_000, +}, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-unreadable-"))); + const { server, url } = await modelServer(); + const clients = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal", "interfaces", "tui.clients"); + let session; + let terminal; + try { + session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + terminal = await fakeTerminal(clients, { ignoreSigterm: false, recordStart: true }); + // Suspended, so its registration stays unreadable. + process.kill(terminal.child.pid, "SIGSTOP"); + const registration = join(clients, String(terminal.child.pid)); + await chmod(registration, 0o000); + await assert.rejects(session.stop(), { code: "pi_interface_cleanup_incomplete" }); + assert.equal(await exists(registration), true); + assert.equal(await survivesResume(terminal.child.pid), true); + } finally { + if (terminal !== undefined) { + for (const pid of [-terminal.child.pid, terminal.tool]) try { process.kill(pid, "SIGKILL"); } catch {} + } + await session?.stop().catch(() => undefined); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + test("stop kills a launch suspended after it registered", { skip, timeout: 60_000 }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-paused-launch-"))); const { server, url } = await modelServer(); @@ -694,7 +765,7 @@ test("stop kills a launch suspended after it registered", { skip, timeout: 60_00 session = await sessionFactory().create(startInput(workspace, url, { sdk: { enabled: false }, interfaces: { terminal: {} } })); const interfaces = join(session.configuration.runtimeDir, "interfaces"); await writeFile(join(workspace, "cli.mjs"), STAND_IN_CLI); - helper = runHelper(join(interfaces, "tui.json"), join(workspace, "cli.mjs"), ["60000"]); + helper = runHelper(join(interfaces, "tui.json"), join(workspace, "cli.mjs"), ["60000"], "rt-terminal"); const registration = join(interfaces, "tui.clients", String(helper.child.pid)); const deadline = Date.now() + 10_000; while (!existsSync(registration) && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 20)); @@ -1275,12 +1346,12 @@ test("the terminal interface warns that streamed SDK invocations share Relay's s test("the launcher clears Relay variables inherited from the person's shell", () => { const script = launcherScript({ - node: "/node", helper: "/helper", cli: "/pi", agentDir: "/a", sessionDir: "/s", workspace: "/w", descriptor: "/d", args: [], + node: "/node", helper: "/helper", cli: "/pi", agentDir: "/a", sessionDir: "/s", workspace: "/w", descriptor: "/d", runtimeId: "rt", args: [], }); assert.match(script, /^unset NEMO_RELAY_PI_COMMAND NEMO_RELAY_PI_GATEWAY_URL NEMO_RELAY_PI_OPENAI_UPSTREAM NEMO_RELAY_PI_ANTHROPIC_UPSTREAM$/m); // The runtime's own Relay variables are exported after the unset. const relay = launcherScript({ - node: "/node", helper: "/helper", cli: "/pi", agentDir: "/a", sessionDir: "/s", workspace: "/w", descriptor: "/d", args: [], + node: "/node", helper: "/helper", cli: "/pi", agentDir: "/a", sessionDir: "/s", workspace: "/w", descriptor: "/d", runtimeId: "rt", args: [], environment: { NEMO_RELAY_PI_GATEWAY_URL: "http://127.0.0.1:1" }, }); assert.ok(relay.indexOf("unset ") < relay.indexOf("export NEMO_RELAY_PI_GATEWAY_URL=")); From 76447c2183db5b6f0cf85acebad87249a9fc731e Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 12:19:44 -0800 Subject: [PATCH 14/25] fix: send empty MCP header variables from Pi's terminal UI as the SDK does Pi's configuration-value resolver treats an empty variable as missing, so a header such as `Bearer pre${EMPTY}post` failed in the terminal UI while the SDK session sent `Bearer prepost`. An empty value holds no secret, so mcp.json now resolves those references at start and keeps every other reference for the terminal UI to resolve from the runtime's environment. Test the terminal UI against a loopback streamable-HTTP MCP server with the real pi CLI and an empty shell environment, and test that a failing heartbeat write leaves a registration's identity whole. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- .../typescript/pi/src/native-configuration.ts | 15 ++- adapters/typescript/pi/test/terminal.test.mjs | 96 +++++++++++++++++++ 2 files changed, 107 insertions(+), 4 deletions(-) diff --git a/adapters/typescript/pi/src/native-configuration.ts b/adapters/typescript/pi/src/native-configuration.ts index ec552a337..4748c5c86 100644 --- a/adapters/typescript/pi/src/native-configuration.ts +++ b/adapters/typescript/pi/src/native-configuration.ts @@ -406,12 +406,14 @@ export function piConfigLiteral(value: string): string { * references stay references, which Pi's terminal UI resolves from its own * environment, and everything else is literal. */ -function piConfigHeader(value: string): string { +function piConfigHeader(value: string, isEmpty: (variable: string) => boolean): string { let result = ""; let index = 0; for (const match of value.matchAll(MCP_ENV_REFERENCE)) { result += piConfigLiteral(value.slice(index, match.index)); - result += match[0]; + // Pi treats an empty variable as missing, while the SDK session substitutes "". An empty + // value holds no secret, so it is resolved here; every other reference stays one. + if (!isEmpty(match[1]!)) result += match[0]; index = match.index + match[0].length; } return result + piConfigLiteral(value.slice(index)); @@ -423,11 +425,14 @@ function piConfigHeader(value: string): string { * configuration-value syntax, so both paths read the same values and none runs a * shell command. */ -function piNativeMcpServers(servers: Record): Record { +function piNativeMcpServers( + servers: Record, + isEmpty: (variable: string) => boolean, +): Record { return Object.fromEntries(Object.entries(servers).map(([name, server]) => { if ("headers" in server && server.headers !== undefined) { const headers = Object.fromEntries( - Object.entries(server.headers).map(([header, value]) => [header, piConfigHeader(value)]), + Object.entries(server.headers).map(([header, value]) => [header, piConfigHeader(value, isEmpty)]), ); return [name, { ...server, headers }]; } @@ -813,6 +818,8 @@ export async function preparePiConfiguration(input: AdapterStartInput): Promise< const mcpServers = selectPiMcpServers(input.config, environment, process.env); const nativeMcpServers = piNativeMcpServers( selectPiMcpServers(input.config, environment, process.env, { expandHeaders: false }), + // As expandMcpHeader resolves a reference: the runtime's environment, then the adapter's. + (variable) => (Object.hasOwn(environment, variable) ? environment[variable] : process.env[variable]) === "", ); const terminal = terminalEnabled(input.config); const keepState = keepsState(input); diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index 4b222e025..f048f8191 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -1385,6 +1385,102 @@ test("the terminal interface refuses a malformed base_url before writing anythin } }); +/** A loopback streamable-HTTP MCP server that records the headers each request carries. */ +async function httpMcpServer() { + const headers = []; + const server = createServer(async (request, response) => { + if (request.method !== "POST") { + response.writeHead(405).end(); + return; + } + headers.push({ authorization: request.headers.authorization, token: request.headers["x-token"] }); + const chunks = []; + for await (const chunk of request) chunks.push(chunk); + const message = JSON.parse(Buffer.concat(chunks).toString("utf8")); + if (message.id === undefined) { + response.writeHead(202).end(); + return; + } + const result = message.method === "initialize" + ? { protocolVersion: message.params.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: "http-test", version: "1" } } + : message.method === "tools/list" + ? { tools: [{ name: "http_tool", description: "an HTTP MCP tool", inputSchema: { type: "object", properties: {} } }] } + : {}; + response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result })); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + return { server, headers, url: `http://127.0.0.1:${server.address().port}/mcp` }; +} + +test("the terminal UI sends MCP headers as the SDK session would, empty variables included", { skip, timeout: 90_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-mcp-headers-"))); + const home = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-mcp-headers-home-"))); + const { server, requests, url } = await modelServer(); + const mcp = await httpMcpServer(); + let session; + try { + const input = startInput(workspace, url, { sdk: { enabled: false }, interfaces: { terminal: {} } }); + input.config.tools = { enabled: null, blocked: [] }; + input.config.mcp = { servers: { remote: { transport: "streamable-http", url: mcp.url, + custom_headers: { Authorization: "Bearer pre${EMPTY_PART}post", "X-Token": "${MCP_TOKEN}" } } } }; + input.runtimeContext.environment.env.EMPTY_PART = ""; + input.runtimeContext.environment.env.MCP_TOKEN = "runtime-token"; + session = await sessionFactory().create(input); + const written = await readFile(join(session.configuration.agentDir, "mcp.json"), "utf8"); + // The empty value is resolved in the file; the token stays a reference, off disk. + assert.doesNotMatch(written, /EMPTY_PART|runtime-token/); + assert.match(written, /\$\{MCP_TOKEN\}/); + // The person's shell holds neither variable. + const run = await launch(join(session.configuration.runtimeDir, "interfaces", "terminal"), home, + ["--print", "say hello"], { env: { PATH: process.env.PATH, HOME: home } }).exited; + assert.equal(run.code, 0, run.stderr); + assert.ok(mcp.headers.length > 0, "Pi's terminal UI never reached the MCP server"); + for (const sent of mcp.headers) assert.deepEqual(sent, { authorization: "Bearer prepost", token: "runtime-token" }); + assert.ok(Object.keys(toolDescriptions(requests[0])).some((name) => name.includes("http_tool"))); + } finally { + await session?.stop(); + server.closeAllConnections(); + server.close(); + mcp.server.closeAllConnections(); + mcp.server.close(); + await rm(workspace, { recursive: true, force: true }); + await rm(home, { recursive: true, force: true }); + } +}); + +test("a heartbeat that fails to write leaves the registration's identity whole", { timeout: 30_000 }, async () => { + const directory = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-supervisor-heartbeat-"))); + let child; + try { + const descriptor = join(directory, "tui.json"); + const clients = join(directory, "tui.clients"); + await writeFile(descriptor, JSON.stringify({ runtime_id: "rt-supervisor" })); + const extension = join(directory, "fabric-terminal.mjs"); + await writeFile(extension, supervisorExtension(descriptor, clients, "rt-supervisor")); + const host = ` + const [extension] = process.argv.slice(1); + const handlers = {}; + (await import(extension)).default({ on: (name, handler) => { handlers[name] = handler; } }); + handlers.session_start({}, { ui: { notify() {} }, shutdown() { process.exit(0); } }); + setInterval(() => {}, 1_000); + `; + child = spawn(process.execPath, ["--input-type=module", "-e", host, extension], { stdio: "ignore" }); + const registration = join(clients, String(child.pid)); + const deadline = Date.now() + 10_000; + while (!existsSync(registration) && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 20)); + const identity = await readFile(registration, "utf8"); + assert.match(identity, /^(proc|ps):/); + // Every later heartbeat now fails to write: its staging path is a directory. + await mkdir(`${registration}.tmp`); + await new Promise((resolve) => setTimeout(resolve, 1_500)); + assert.equal(running(child.pid), true); + assert.equal(await readFile(registration, "utf8"), identity); + } finally { + child?.kill("SIGKILL"); + await rm(directory, { recursive: true, force: true }); + } +}); + test("the terminal interface refuses a model key variable Pi can't reference", { skip }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-key-name-"))); try { From 0272daf7e37346c2db97e847b0f6f359a5cc6f39 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 12:24:22 -0800 Subject: [PATCH 15/25] fix: signal Pi terminal UIs only by verified identity A fresh heartbeat no longer admits a registration whose process identity can't be read or compared: its PID may have been reused since. Every terminal UI records an identity, so an unverifiable registration is kept, not signalled, and reported as pi_interface_cleanup_incomplete for a retried stop to verify. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- adapters/typescript/pi/src/terminal.ts | 30 +++++++------------ adapters/typescript/pi/test/terminal.test.mjs | 4 +-- 2 files changed, 12 insertions(+), 22 deletions(-) diff --git a/adapters/typescript/pi/src/terminal.ts b/adapters/typescript/pi/src/terminal.ts index 502463941..d4ba0be1b 100644 --- a/adapters/typescript/pi/src/terminal.ts +++ b/adapters/typescript/pi/src/terminal.ts @@ -17,7 +17,7 @@ // first retires the terminal interface a runtime that ended without stop left. import { execFile } from "node:child_process"; -import { access, chmod, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; +import { access, chmod, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; @@ -43,8 +43,6 @@ const TERMINAL_LAUNCH_HELPER = fileURLToPath(new URL("./terminal-launch.js", imp /** How long `stop` waits after SIGTERM before it sends SIGKILL to open terminal UIs, as the Hermes adapter does. */ const TERMINAL_STOP_GRACE_MS = 5_000; -/** A registration whose heartbeat is older than this belongs to a terminal UI that no longer runs. */ -const TERMINAL_HEARTBEAT_STALE_MS = 3_000; const TERMINAL_HEARTBEAT_MS = 500; /** How long a terminal UI waits for its orderly shutdown before it sends itself SIGTERM. */ const TERMINAL_SELF_TERMINATE_MS = 2_000; @@ -560,12 +558,12 @@ export async function processIdentity(pid: number): Promise } /** - * Registered terminal UIs that still run. A current heartbeat means the registration's - * process runs. A stale one, as from a suspended terminal UI, counts while the identity - * the terminal UI recorded matches the process under its PID; a mismatch means another - * process reuses the PID. A stale registration whose identity can't be compared is not - * signalled, since that could hit an unrelated process, but stop warns about it: the - * terminal UI closes itself when it resumes and finds the attachment file gone. + * Registered terminal UIs that still run, decided by process identity alone. A + * registration counts while the identity the terminal UI recorded matches the process + * under its PID, whatever its heartbeat says (a suspended terminal UI stops heartbeating); + * a mismatch means another process reuses the PID. A registration whose identity can't + * be read or compared is unverified: it isn't signalled, since that could hit an + * unrelated process, and it is kept for a retried stop to verify. */ async function liveTerminals(clients: string): Promise<{ live: RegisteredTerminal[]; unverified: number[] }> { let entries: string[]; @@ -589,10 +587,8 @@ async function liveTerminals(clients: string): Promise<{ live: RegisteredTermina continue; } let recorded: string; - let mtimeMs: number; try { recorded = (await readFile(path, "utf8")).trim(); - mtimeMs = (await stat(path)).mtimeMs; } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; // That terminal UI exited. // Unreadable while its PID lives: keep it for a retry, don't signal it. @@ -607,15 +603,9 @@ async function liveTerminals(clients: string): Promise<{ live: RegisteredTermina else await rm(path, { force: true }); continue; } - // A heartbeat from the future (clock skew on a shared volume) is not current. - const age = Date.now() - mtimeMs; - if (age >= -TERMINAL_HEARTBEAT_MS && age < TERMINAL_HEARTBEAT_STALE_MS) { - // Unverifiable but heartbeating within the stale limit: this terminal UI. - live.push({ pid, identity: recorded }); - continue; - } - // Unverifiable and stale: don't signal what could be another process, and keep the - // registration so a retried stop can verify it. + // Unverifiable, fresh heartbeat or not (its PID may have been reused since): don't + // signal what could be another process, and keep the registration so a retried stop + // can verify it. unverified.push(pid); } return { live, unverified }; diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index f048f8191..9d5bba105 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -885,7 +885,7 @@ test("stop sends SIGTERM to open terminal UIs at once", { skip, timeout: 60_000 let terminal; try { session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); - terminal = await fakeTerminal(clients, { ignoreSigterm: false }); + terminal = await fakeTerminal(clients, { ignoreSigterm: false, recordStart: true }); const started = Date.now(); await session.stop(); @@ -911,7 +911,7 @@ test("stop kills an open terminal UI's process group five seconds after SIGTERM" let terminal; try { session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); - terminal = await fakeTerminal(clients, { ignoreSigterm: true }); + terminal = await fakeTerminal(clients, { ignoreSigterm: true, recordStart: true }); assert.ok(running(terminal.tool)); const started = Date.now(); From c4e920df699a2ed6efce3cc998c476cb92025ef5 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 12:32:55 -0800 Subject: [PATCH 16/25] fix: verify a Pi terminal UI's PID before group signals too Stop now checks a terminal UI's identity before every signal, group signals included. A PID that another process holds was reused, which the kernel does only once no group uses it as an ID, so the terminal UI's group is gone and nothing is signalled. A PID no process holds can only reach the terminal UI's own remaining group, such as its tools. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- adapters/typescript/pi/src/terminal.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/adapters/typescript/pi/src/terminal.ts b/adapters/typescript/pi/src/terminal.ts index d4ba0be1b..fb1353c1b 100644 --- a/adapters/typescript/pi/src/terminal.ts +++ b/adapters/typescript/pi/src/terminal.ts @@ -657,17 +657,21 @@ function alive(pid: number): boolean { async function signal(terminals: readonly RegisteredTerminal[], name: NodeJS.Signals, options: { groupOnly?: boolean } = {}): Promise { for (const { pid, identity } of terminals) { + // The PID is verified before any signal. While it runs, it must still be this terminal + // UI; if another process now holds it, the kernel reused it, which it does only once no + // group uses it as an ID either, so this terminal UI's whole group is gone: signal + // nothing. If no process holds it, a group signal reaches only this terminal UI's own + // remaining group, such as its tools' processes. + const running = alive(pid); + if (running && await processIdentity(pid) !== identity) continue; try { - // Safe after the leader exits: the kernel doesn't reuse a PID still in use as a group ID. process.kill(-pid, name); continue; } catch { // Not a group leader, or group signals are denied (OpenShell): signal the process. } - // Never a terminal UI already seen to exit, and only while the PID is still the same - // process: between polls it may have been reused. - if (options.groupOnly === true || !alive(pid)) continue; - if (identity.length > 0 && await processIdentity(pid) !== identity) continue; + // Never a terminal UI already seen to exit. + if (options.groupOnly === true || !running) continue; try { process.kill(pid, name); } catch { From e33ae7e74d7ef29921376d2f8d660f2aa0320af3 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 12:47:47 -0800 Subject: [PATCH 17/25] fix: keep Pi terminal UIs whose identity can't be read when signalled If a terminal UI's identity can't be read at signal time, stop no longer treats it like a reused PID and drops it: it isn't signalled, its registration is kept, and stop reports pi_interface_cleanup_incomplete so a later stop can verify and signal it. A known mismatch still means the PID was reused and gets no signal. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- adapters/typescript/pi/src/terminal.ts | 37 +++++++++++++++++++------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/adapters/typescript/pi/src/terminal.ts b/adapters/typescript/pi/src/terminal.ts index fb1353c1b..e061a7a3e 100644 --- a/adapters/typescript/pi/src/terminal.ts +++ b/adapters/typescript/pi/src/terminal.ts @@ -488,10 +488,14 @@ async function closeTerminals(clients: string): Promise { // The attachment file is already gone. A terminal UI registers before it checks that file, // so any terminal UI that saw it published is registered now; any other closes itself. const { live, unverified } = await liveTerminals(clients); - await stopTerminals(live, TERMINAL_STOP_GRACE_MS); + // A terminal UI whose identity can't be read when it is signalled isn't signalled either. + const unsignalled = await stopTerminals(live, TERMINAL_STOP_GRACE_MS); + unverified.push(...unsignalled); if (unverified.length > 0) { // Keep these registrations for a retry; remove the ones just closed. - for (const terminal of live) await rm(join(clients, String(terminal.pid)), { force: true }); + for (const terminal of live) { + if (!unsignalled.includes(terminal.pid)) await rm(join(clients, String(terminal.pid)), { force: true }); + } throw new LifecycleError( "pi_interface_cleanup_incomplete", "A Pi terminal UI's registration or process couldn't be verified, so it wasn't signalled", @@ -507,9 +511,12 @@ interface RegisteredTerminal { identity: string; } -/** SIGTERM each terminal UI's process group, then SIGKILL the groups after the grace period. */ -async function stopTerminals(terminals: readonly RegisteredTerminal[], graceMs: number): Promise { - if (terminals.length === 0) return; +/** + * SIGTERM each terminal UI's process group, then SIGKILL the groups after the grace period. + * Returns the PIDs left unsignalled at the end because their identity couldn't be read. + */ +async function stopTerminals(terminals: readonly RegisteredTerminal[], graceMs: number): Promise { + if (terminals.length === 0) return []; await signal(terminals, "SIGTERM"); const exited = new Set(); const deadline = Date.now() + graceMs; @@ -520,8 +527,10 @@ async function stopTerminals(terminals: readonly RegisteredTerminal[], graceMs: } // The group too: processes the terminal UI's tools started can outlive it. A terminal UI // seen to exit gets no signal of its own, since its PID may now belong to another process. - await signal(terminals.filter(({ pid }) => !exited.has(pid)), "SIGKILL"); - await signal(terminals.filter(({ pid }) => exited.has(pid)), "SIGKILL", { groupOnly: true }); + return [ + ...await signal(terminals.filter(({ pid }) => !exited.has(pid)), "SIGKILL"), + ...await signal(terminals.filter(({ pid }) => exited.has(pid)), "SIGKILL", { groupOnly: true }), + ]; } function sleep(ms: number): Promise { @@ -655,7 +664,8 @@ function alive(pid: number): boolean { * own group has none under its PID (ESRCH). */ async function signal(terminals: readonly RegisteredTerminal[], name: NodeJS.Signals, - options: { groupOnly?: boolean } = {}): Promise { + options: { groupOnly?: boolean } = {}): Promise { + const unreadable: number[] = []; for (const { pid, identity } of terminals) { // The PID is verified before any signal. While it runs, it must still be this terminal // UI; if another process now holds it, the kernel reused it, which it does only once no @@ -663,7 +673,15 @@ async function signal(terminals: readonly RegisteredTerminal[], name: NodeJS.Sig // nothing. If no process holds it, a group signal reaches only this terminal UI's own // remaining group, such as its tools' processes. const running = alive(pid); - if (running && await processIdentity(pid) !== identity) continue; + if (running) { + const current = await processIdentity(pid); + if (current === undefined) { + // Can't tell whether it is still this terminal UI: don't signal, report it. + unreadable.push(pid); + continue; + } + if (current !== identity) continue; + } try { process.kill(-pid, name); continue; @@ -678,6 +696,7 @@ async function signal(terminals: readonly RegisteredTerminal[], name: NodeJS.Sig // It has exited. } } + return unreadable; } /** From 7800da44619faaa9a04db2c4ab820b35a5bf9da2 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 12:54:31 -0800 Subject: [PATCH 18/25] fix: report every Pi terminal cleanup failure and compare like identities - Treat a recorded identity of another kind (proc vs ps) as unverifiable, at the scan and at signal time: keep the registration, don't signal, report pi_interface_cleanup_incomplete. - When both removing tui.json and closing terminal UIs fail, report both causes instead of the last one. - Remove leftover non-registration entries recursively and best effort, so one can't stop live terminal UIs from closing. - Test a suspended terminal UI whose heartbeat writes fail: a real stop still finds and signals it. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- adapters/typescript/pi/src/terminal.ts | 39 ++++++- adapters/typescript/pi/test/terminal.test.mjs | 109 +++++++++++++++++- 2 files changed, 141 insertions(+), 7 deletions(-) diff --git a/adapters/typescript/pi/src/terminal.ts b/adapters/typescript/pi/src/terminal.ts index e061a7a3e..a79ce21b7 100644 --- a/adapters/typescript/pi/src/terminal.ts +++ b/adapters/typescript/pi/src/terminal.ts @@ -473,8 +473,18 @@ export class PiTerminal { await this.server.close(); // Close terminal UIs even then: a suspended one can't close itself. Withdrawn only once // the attachment file is gone and the terminal UIs are closed, so a retry repeats both. - await closeTerminals(this.clients); + let closeError: unknown; + try { + await closeTerminals(this.clients); + } catch (error) { + closeError = error; + } + if (unpublishError !== undefined && closeError !== undefined) { + // Both matter: tui.json may remain, and terminal UIs may still run. + throw new AggregateError([unpublishError, closeError], "Pi's terminal interface could not be withdrawn"); + } if (unpublishError !== undefined) throw unpublishError; + if (closeError !== undefined) throw closeError; this.withdrawn = true; } } @@ -533,6 +543,12 @@ async function stopTerminals(terminals: readonly RegisteredTerminal[], graceMs: ]; } +/** Whether two identities come from the same source (/proc or ps), so comparing them means something. */ +function comparableIdentities(a: string, b: string): boolean { + const kind = (identity: string) => identity.slice(0, identity.indexOf(":") + 1); + return kind(a).length > 0 && kind(a) === kind(b); +} + function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } @@ -591,8 +607,9 @@ async function liveTerminals(clients: string): Promise<{ live: RegisteredTermina const path = join(clients, name); const pid = Number(name); if (!Number.isSafeInteger(pid) || pid <= 1 || !alive(pid)) { - // Not a registration (such as a staging file), or its process is gone. - await rm(path, { force: true }); + // Not a registration (such as a staging file), or its process is gone. Best effort: + // a leftover that can't be removed doesn't stop the live terminal UIs from closing. + await rm(path, { recursive: true, force: true }).catch(() => undefined); continue; } let recorded: string; @@ -605,7 +622,7 @@ async function liveTerminals(clients: string): Promise<{ live: RegisteredTermina continue; } const current = recorded.length > 0 ? await processIdentity(pid) : undefined; - if (current !== undefined) { + if (current !== undefined && comparableIdentities(current, recorded)) { // The recorded identity decides, fresh or not: a match is this terminal UI, even // suspended; a mismatch is a later process reusing the PID of one that died. if (current === recorded) live.push({ pid, identity: recorded }); @@ -675,7 +692,7 @@ async function signal(terminals: readonly RegisteredTerminal[], name: NodeJS.Sig const running = alive(pid); if (running) { const current = await processIdentity(pid); - if (current === undefined) { + if (current === undefined || !comparableIdentities(current, identity)) { // Can't tell whether it is still this terminal UI: don't signal, report it. unreadable.push(pid); continue; @@ -769,7 +786,10 @@ export class PiTerminalSessionHandle implements PiSessionHandle { failure = error instanceof LifecycleError ? error : new LifecycleError("pi_interface_cleanup_failed", "Pi's terminal interface could not be withdrawn", { - metadata: { cause: error instanceof Error ? error.message : String(error) }, + metadata: error instanceof AggregateError + // Every cause, each by its lifecycle code or error code where it has one. + ? { causes: error.errors.map(describeCleanupError) } + : { cause: describeCleanupError(error) }, }); } try { @@ -784,6 +804,13 @@ export class PiTerminalSessionHandle implements PiSessionHandle { } } +function describeCleanupError(error: unknown): string { + if (error instanceof LifecycleError) return error.code; + const code = (error as NodeJS.ErrnoException | undefined)?.code; + if (typeof code === "string") return code; + return error instanceof Error ? error.message : String(error); +} + /** * Remove mcp.json, which only running terminal UIs read and which can hold literal MCP * stdio env values. A kept directory gets a fresh one at the next start. diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index 9d5bba105..2c3b68250 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -455,6 +455,11 @@ function running(pid) { } } +/** An identity this host's lookup produces the same kind of, but for another process. */ +const SAME_KIND_OTHER_IDENTITY = process.platform === "linux" ? "proc:1" : "ps:Thu Jan 1 00:00:00 1970"; +/** An identity of the kind this host's lookup doesn't produce. */ +const OTHER_KIND_IDENTITY = process.platform === "linux" ? "ps:Thu Jan 1 00:00:00 1970" : "proc:1"; + /** Whether a process is gone or a zombie awaiting reaping, within a bounded wait. */ async function terminated(pid, timeoutMs = 3_000) { const deadline = Date.now() + timeoutMs; @@ -822,6 +827,108 @@ test("stop doesn't signal a stale terminal UI it can't verify, keeps it for a re } }); +test("stop keeps, and doesn't signal, a terminal UI whose identity is of another kind", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-identity-kind-"))); + const { server, url } = await modelServer(); + const clients = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal", "interfaces", "tui.clients"); + let session; + let terminal; + try { + session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + // Recorded from ps where the runtime reads /proc, or the other way round: not comparable. + terminal = await fakeTerminal(clients, { ignoreSigterm: false, identity: OTHER_KIND_IDENTITY }); + await assert.rejects(session.stop(), { code: "pi_interface_cleanup_incomplete" }); + assert.equal(await exists(join(clients, String(terminal.child.pid))), true); + await new Promise((resolve) => setTimeout(resolve, 500)); + // Its SIGTERM handler exits at once, so it would be gone had it been signalled. + assert.equal(running(terminal.child.pid), true); + } finally { + if (terminal !== undefined) { + for (const pid of [-terminal.child.pid, terminal.tool]) try { process.kill(pid, "SIGKILL"); } catch {} + } + await session?.stop().catch(() => undefined); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + +test("stop reports both failures when tui.json can't be removed and terminal UIs can't be read", { + skip: skip || (process.getuid?.() === 0 ? "root reads any directory" : false), + timeout: 60_000, +}, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-withdraw-both-"))); + const { server, url } = await modelServer(); + const interfaces = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal", "interfaces"); + const clients = join(interfaces, "tui.clients"); + let session; + try { + session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + // tui.json can't be removed (a non-empty directory stands in its place)... + await rm(join(interfaces, "tui.json")); + await mkdir(join(interfaces, "tui.json")); + await writeFile(join(interfaces, "tui.json", "keep"), ""); + // ...and the registrations can't be listed. + await mkdir(clients, { recursive: true }); + await chmod(clients, 0o000); + await assert.rejects(session.stop(), (error) => { + assert.equal(error.code, "pi_interface_cleanup_failed"); + assert.equal(error.metadata.causes.length, 2); + assert.ok(error.metadata.causes.includes("pi_interface_cleanup_incomplete"), JSON.stringify(error.metadata)); + return true; + }); + } finally { + await chmod(clients, 0o700).catch(() => undefined); + await rm(join(interfaces, "tui.json"), { recursive: true, force: true }).catch(() => undefined); + await session?.stop().catch(() => undefined); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + +test("stop signals a terminal UI whose heartbeat writes fail, by its intact registration", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-heartbeat-stop-"))); + const { server, url } = await modelServer(); + const interfaces = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal", "interfaces"); + let session; + let child; + try { + session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + // The runtime's real supervisor extension, in a stand-in Pi host. + const extension = join(workspace, "fabric-terminal.mjs"); + await writeFile(extension, await readFile(join(interfaces, "fabric-terminal.ts"), "utf8")); + const host = ` + const [extension] = process.argv.slice(1); + const handlers = {}; + (await import(extension)).default({ on: (name, handler) => { handlers[name] = handler; } }); + handlers.session_start({}, { ui: { notify() {} }, shutdown() {} }); + setInterval(() => {}, 1_000); + `; + child = spawn(process.execPath, ["--input-type=module", "-e", host, extension], { detached: true, stdio: "ignore" }); + const exited = new Promise((resolve) => child.once("exit", (code, signal) => resolve({ code, signal }))); + const registration = join(interfaces, "tui.clients", String(child.pid)); + const deadline = Date.now() + 10_000; + while (!existsSync(registration) && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 20)); + const identity = await readFile(registration, "utf8"); + // Later heartbeats fail to write, and the terminal UI is suspended, so it can't close itself. + await mkdir(`${registration}.tmp`); + await new Promise((resolve) => setTimeout(resolve, 1_000)); + assert.equal(await readFile(registration, "utf8"), identity); + process.kill(child.pid, "SIGSTOP"); + await session.stop(); + session = undefined; + const exit = await exited; + assert.ok(["SIGTERM", "SIGKILL"].includes(exit.signal), `exit ${exit.code} ${exit.signal}`); + } finally { + if (child !== undefined) try { process.kill(-child.pid, "SIGKILL"); } catch {} + await session?.stop().catch(() => undefined); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + test("stop doesn't signal a freshly registered PID whose identity doesn't match", { skip, timeout: 60_000 }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-reused-"))); const { server, url } = await modelServer(); @@ -832,7 +939,7 @@ test("stop doesn't signal a freshly registered PID whose identity doesn't match" session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); // As when a terminal UI died without removing its registration and another process // took its PID: the heartbeat is current, but the recorded identity is someone else's. - terminal = await fakeTerminal(clients, { ignoreSigterm: false, identity: "proc:1" }); + terminal = await fakeTerminal(clients, { ignoreSigterm: false, identity: SAME_KIND_OTHER_IDENTITY }); await session.stop(); session = undefined; await new Promise((resolve) => setTimeout(resolve, 500)); From 78481c923a2f07650f34c2b0f1a0f8426f782800 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 12:57:57 -0800 Subject: [PATCH 19/25] test: cover partial heartbeat writes before a Pi terminal stop Run the runtime's real supervisor in a stand-in Pi host whose later writes put a fragment on disk and then fail, as on a full disk, and check the registration keeps its whole identity and a real stop still signals the suspended terminal UI. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- adapters/typescript/pi/test/terminal.test.mjs | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index 2c3b68250..0bf0eed9e 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -929,6 +929,62 @@ test("stop signals a terminal UI whose heartbeat writes fail, by its intact regi } }); +test("stop signals a terminal UI whose heartbeats write partially and fail", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-partial-write-"))); + const { server, url } = await modelServer(); + const interfaces = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal", "interfaces"); + let session; + let child; + try { + session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + const extension = join(workspace, "fabric-terminal.mjs"); + await writeFile(extension, await readFile(join(interfaces, "fabric-terminal.ts"), "utf8")); + // After the first registration, every write puts a few bytes on disk, then fails (as on a + // full disk). syncBuiltinESMExports makes the supervisor's named import see the patch. + const host = ` + import fs from "node:fs"; + import { syncBuiltinESMExports } from "node:module"; + const write = fs.writeFileSync; + let writes = 0; + fs.writeFileSync = (path, data, options) => { + writes += 1; + if (writes === 1) return write(path, data, options); + write(path, String(data).slice(0, 3), options); + throw Object.assign(new Error("no space left on device"), { code: "ENOSPC" }); + }; + syncBuiltinESMExports(); + const [extension] = process.argv.slice(1); + const handlers = {}; + (await import(extension)).default({ on: (name, handler) => { handlers[name] = handler; } }); + handlers.session_start({}, { ui: { notify() {} }, shutdown() {} }); + setInterval(() => {}, 1_000); + `; + child = spawn(process.execPath, ["--input-type=module", "-e", host, extension], { detached: true, stdio: "ignore" }); + const exited = new Promise((resolve) => child.once("exit", (code, signal) => resolve({ code, signal }))); + const registration = join(interfaces, "tui.clients", String(child.pid)); + const deadline = Date.now() + 10_000; + while (!existsSync(registration) && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 20)); + const identity = await readFile(registration, "utf8"); + assert.match(identity, /^(proc|ps):/); + // Several partial, failed heartbeats later, the staging file holds a fragment and the + // registration still holds the whole identity. + await new Promise((resolve) => setTimeout(resolve, 1_200)); + assert.equal((await readFile(`${registration}.tmp`, "utf8")).length, 3); + assert.equal(await readFile(registration, "utf8"), identity); + process.kill(child.pid, "SIGSTOP"); + await session.stop(); + session = undefined; + const exit = await exited; + assert.ok(["SIGTERM", "SIGKILL"].includes(exit.signal), `exit ${exit.code} ${exit.signal}`); + } finally { + if (child !== undefined) try { process.kill(-child.pid, "SIGKILL"); } catch {} + await session?.stop().catch(() => undefined); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + test("stop doesn't signal a freshly registered PID whose identity doesn't match", { skip, timeout: 60_000 }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-reused-"))); const { server, url } = await modelServer(); From 754f7b73177934f8fbe4e1f1f135764c69aa5420 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 13:02:47 -0800 Subject: [PATCH 20/25] fix: report Pi terminal UIs a failed signal leaves running If both the group signal and the process signal fail for a reason other than ESRCH and the terminal UI still runs, stop now keeps its registration and reports pi_interface_cleanup_incomplete instead of treating it as closed. Test a lookup that fails between the scan and SIGKILL through a replaceable identity lookup. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- adapters/typescript/pi/src/terminal.ts | 25 ++++++++++--- adapters/typescript/pi/test/terminal.test.mjs | 35 +++++++++++++++++++ 2 files changed, 55 insertions(+), 5 deletions(-) diff --git a/adapters/typescript/pi/src/terminal.ts b/adapters/typescript/pi/src/terminal.ts index a79ce21b7..3e8014454 100644 --- a/adapters/typescript/pi/src/terminal.ts +++ b/adapters/typescript/pi/src/terminal.ts @@ -523,7 +523,7 @@ interface RegisteredTerminal { /** * SIGTERM each terminal UI's process group, then SIGKILL the groups after the grace period. - * Returns the PIDs left unsignalled at the end because their identity couldn't be read. + * Returns the PIDs left unsignalled at the end: their identity couldn't be read, or the signal failed. */ async function stopTerminals(terminals: readonly RegisteredTerminal[], graceMs: number): Promise { if (terminals.length === 0) return []; @@ -553,6 +553,20 @@ function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } +/** How stop looks up a process's identity; tests replace it to simulate a failing lookup. */ +let lookupIdentity: (pid: number) => Promise = (pid) => processIdentity(pid); + +/** Replace the identity lookup stop uses, for tests; returns a function that restores it. */ +export function replaceIdentityLookupForTesting( + lookup: (pid: number) => Promise, +): () => void { + const previous = lookupIdentity; + lookupIdentity = lookup; + return () => { + lookupIdentity = previous; + }; +} + /** * A process's identity: its start time, which tells a terminal UI from a later process * that reuses its PID. It is `proc:` from /proc//stat on @@ -621,7 +635,7 @@ async function liveTerminals(clients: string): Promise<{ live: RegisteredTermina unverified.push(pid); continue; } - const current = recorded.length > 0 ? await processIdentity(pid) : undefined; + const current = recorded.length > 0 ? await lookupIdentity(pid) : undefined; if (current !== undefined && comparableIdentities(current, recorded)) { // The recorded identity decides, fresh or not: a match is this terminal UI, even // suspended; a mismatch is a later process reusing the PID of one that died. @@ -691,7 +705,7 @@ async function signal(terminals: readonly RegisteredTerminal[], name: NodeJS.Sig // remaining group, such as its tools' processes. const running = alive(pid); if (running) { - const current = await processIdentity(pid); + const current = await lookupIdentity(pid); if (current === undefined || !comparableIdentities(current, identity)) { // Can't tell whether it is still this terminal UI: don't signal, report it. unreadable.push(pid); @@ -709,8 +723,9 @@ async function signal(terminals: readonly RegisteredTerminal[], name: NodeJS.Sig if (options.groupOnly === true || !running) continue; try { process.kill(pid, name); - } catch { - // It has exited. + } catch (error) { + // ESRCH: it has exited. Anything else (EPERM) left a live terminal UI unsignalled. + if ((error as NodeJS.ErrnoException).code !== "ESRCH" && alive(pid)) unreadable.push(pid); } } return unreadable; diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index 0bf0eed9e..9af5f9107 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -20,6 +20,7 @@ import { terminalArguments, terminalEnabled, processIdentity, + replaceIdentityLookupForTesting, supervisorExtension, terminalStreamingWarnings, withTerminalInterface, @@ -985,6 +986,40 @@ test("stop signals a terminal UI whose heartbeats write partially and fail", { s } }); +test("stop keeps a terminal UI whose identity can't be read just before SIGKILL", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-late-lookup-"))); + const { server, url } = await modelServer(); + const clients = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal", "interfaces", "tui.clients"); + let session; + let terminal; + let restore; + try { + session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + // Ignores SIGTERM, so stop escalates to SIGKILL after the grace period. + terminal = await fakeTerminal(clients, { ignoreSigterm: true, recordStart: true }); + // The scan and the SIGTERM verify it; the lookup before SIGKILL fails. + let lookups = 0; + restore = replaceIdentityLookupForTesting((pid) => { + lookups += 1; + return lookups <= 2 ? processIdentity(pid) : Promise.resolve(undefined); + }); + await assert.rejects(session.stop(), { code: "pi_interface_cleanup_incomplete" }); + assert.equal(lookups, 3); + assert.equal(await exists(join(clients, String(terminal.child.pid))), true); + // Not killed: it ignored SIGTERM and never received SIGKILL. + assert.equal(running(terminal.child.pid), true); + } finally { + restore?.(); + if (terminal !== undefined) { + for (const pid of [-terminal.child.pid, terminal.tool]) try { process.kill(pid, "SIGKILL"); } catch {} + } + await session?.stop().catch(() => undefined); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + test("stop doesn't signal a freshly registered PID whose identity doesn't match", { skip, timeout: 60_000 }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-reused-"))); const { server, url } = await modelServer(); From 9b4229f9cd5443907463cfb9f7eef0959979f834 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Wed, 2 Dec 2026 13:08:04 -0800 Subject: [PATCH 21/25] test: cover denied signals at Pi terminal stop Stub process.kill so every real signal to a terminal UI fails with EPERM and check stop keeps its registration, reports incomplete cleanup, and leaves it running. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- adapters/typescript/pi/test/terminal.test.mjs | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index 9af5f9107..66bc6332d 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -1020,6 +1020,41 @@ test("stop keeps a terminal UI whose identity can't be read just before SIGKILL" } }); +test("stop keeps a terminal UI that a denied signal leaves running", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-eperm-"))); + const { server, url } = await modelServer(); + const clients = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal", "interfaces", "tui.clients"); + const kill = process.kill; + let session; + let terminal; + try { + session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + terminal = await fakeTerminal(clients, { ignoreSigterm: false, recordStart: true }); + const target = terminal.child.pid; + // Every real signal to the terminal UI, group or process, is denied, as for a process + // another user owns; liveness probes (signal 0) still work. + process.kill = (pid, signal) => { + if (Math.abs(pid) === target && signal !== 0) { + throw Object.assign(new Error("operation not permitted"), { code: "EPERM" }); + } + return kill.call(process, pid, signal); + }; + await assert.rejects(session.stop(), { code: "pi_interface_cleanup_incomplete" }); + process.kill = kill; + assert.equal(await exists(join(clients, String(target))), true); + assert.equal(running(target), true); + } finally { + process.kill = kill; + if (terminal !== undefined) { + for (const pid of [-terminal.child.pid, terminal.tool]) try { process.kill(pid, "SIGKILL"); } catch {} + } + await session?.stop().catch(() => undefined); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + test("stop doesn't signal a freshly registered PID whose identity doesn't match", { skip, timeout: 60_000 }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-reused-"))); const { server, url } = await modelServer(); From c45d46f85ffd109fcb43ad140bd4c2f89ed52c18 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Thu, 3 Dec 2026 09:36:13 -0800 Subject: [PATCH 22/25] fix: use the runtime's key over a saved Pi login in the terminal UI Pi's terminal UI prefers a login saved in auth.json to the key models.json names, while the SDK session never reads auth.json. With runtime.keep_state, a login saved for the configured provider made terminal turns use another key than SDK turns. Each start now removes that provider's saved login; logins for other providers stay. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- adapters/typescript/pi/src/agent-directory.ts | 30 +++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/adapters/typescript/pi/src/agent-directory.ts b/adapters/typescript/pi/src/agent-directory.ts index 56b226b52..93f23cd15 100644 --- a/adapters/typescript/pi/src/agent-directory.ts +++ b/adapters/typescript/pi/src/agent-directory.ts @@ -12,9 +12,10 @@ // 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, such as auth.json, stay. +// 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, rm, writeFile } from "node:fs/promises"; +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"; @@ -96,10 +97,35 @@ async function writePrivate(path: string, contents: string): Promise { 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 { + 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; + // 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 { 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. From 6a5aece54b1a69d9818475bb6bcb0fde753871f1 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Thu, 3 Dec 2026 09:36:15 -0800 Subject: [PATCH 23/25] fix: load Pi module tools only for the SDK session A terminal-only runtime imported each module tool and ran its factory at start, and every terminal UI then set the tool up again in its own process. A tool that binds a local socket made the terminal UI fail with EADDRINUSE. Without the SDK session, start now only checks the tool definitions and module paths, and the terminal UIs load the tools. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- .../typescript/pi/src/native-configuration.ts | 15 ++++- adapters/typescript/pi/test/terminal.test.mjs | 65 +++++++++++++++++++ 2 files changed, 78 insertions(+), 2 deletions(-) diff --git a/adapters/typescript/pi/src/native-configuration.ts b/adapters/typescript/pi/src/native-configuration.ts index 4748c5c86..e763587f5 100644 --- a/adapters/typescript/pi/src/native-configuration.ts +++ b/adapters/typescript/pi/src/native-configuration.ts @@ -17,7 +17,7 @@ import type { AgentConfig, AgentModelConfig, AgentToolDefinition, JsonObject } f import { LifecycleError, type AdapterStartInput } from "nemo-fabric-adapters-common"; import { agentDirectory, keepsState, runtimeDirectory, sessionDirectory, writeAgentDirectory } from "./agent-directory.js"; -import { terminalEnabled } from "./settings.js"; +import { sdkEnabled, terminalEnabled } from "./settings.js"; import { LAUNCHER_ENV_NAMES, mcpHeaderVariables, TERMINAL_ENV_NAMES } from "./terminal-environment.js"; export interface PiNativeCustomTool { @@ -643,9 +643,15 @@ function validateToolDefinition(name: string, value: unknown): ToolDefinition { return value as unknown as ToolDefinition; } +/** + * Check the configured module tools and, unless `load` is false, load them by running each + * module's factory. Only the SDK session needs them loaded: Pi's terminal UIs load the modules + * in their own processes, so loading them here too would run each tool's setup twice. + */ export async function resolveCustomTools( workspace: string, definitions: Record, + options: { load?: boolean } = {}, ): Promise { const jiti = createJiti(import.meta.url, { interopDefault: false }); const tools: ToolDefinition[] = []; @@ -659,6 +665,8 @@ export async function resolveCustomTools( throw new LifecycleError("pi_tool_kind_unsupported", "Pi supports only module tool definitions"); } const moduleReference = await resolveToolModule(workspace, definition.ref); + // Importing the module can run its setup as well as calling its factory. + if (options.load === false) continue; let loaded: unknown; try { loaded = await jiti.import(moduleReference.path); @@ -878,7 +886,10 @@ export async function preparePiConfiguration(input: AdapterStartInput): Promise< const extensionPaths = await resolveExtensionPaths(workspace, harnessSettings(input.config).extensions); const skillPaths = await resolveSkillPaths(input.baseDir, input.config.skills?.paths ?? []); - const customTools = await resolveCustomTools(workspace, input.config.tools?.definitions ?? {}); + // Without the SDK session, only Pi's terminal UIs run the tools, and they load them themselves. + const customTools = await resolveCustomTools(workspace, input.config.tools?.definitions ?? {}, { + load: sdkEnabled(input.config), + }); // Resolve the selected model as an overlay on Pi's built-in catalog entry (if any): supplied // config fields override, omitted ones keep Pi's native value, and for an unknown (gateway) diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index 66bc6332d..01be309cd 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -1972,3 +1972,68 @@ test("a native-only runtime warns that Fabric's invocation stream doesn't reach await rm(workspace, { recursive: true, force: true }); } }); + +test("with keep_state, the terminal UI uses the runtime's key, not a login Pi saved for the provider", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-saved-login-"))); + const home = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-saved-login-home-"))); + const { server, requests, url } = await modelServer(); + const state = join(workspace, "artifacts", ".fabric", "state", "nvidia.fabric.pi", "terminal-test"); + const auth = join(state, "pi-agent", "auth.json"); + let session; + try { + session = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-one", state)); + await session.stop(); + session = undefined; + // A terminal UI's /login saved a key for the configured provider, and one for another provider. + await writeFile(auth, `${JSON.stringify({ + "fabric-test": { type: "api_key", key: "old-saved-key" }, + other: { type: "api_key", key: "other-saved-key" }, + })}\n`, { mode: 0o644 }); + + session = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-two", state)); + const launcher = join(session.configuration.runtimeDir, "interfaces", "terminal"); + const run = await launch(launcher, home, ["--print", "say hello"]).exited; + assert.equal(run.code, 0, run.stderr); + assert.equal(requests.at(-1).authorization, `Bearer ${RUNTIME_KEY}`); + // Only the configured provider's login is gone, and the file stays owner-only. + assert.deepEqual(JSON.parse(await readFile(auth, "utf8")), { other: { type: "api_key", key: "other-saved-key" } }); + assert.equal((await stat(auth)).mode & 0o777, 0o600); + } finally { + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + await rm(home, { recursive: true, force: true }); + } +}); + +test("a native-only runtime loads no module tool, so each tool sets up only in the terminal UI", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-native-only-tools-"))); + const home = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-native-only-tools-home-"))); + const { server, requests, url } = await modelServer(); + const marker = join(workspace, "tool-setup.log"); + let session; + try { + const input = await toolsInput(workspace, url, { sdk: { enabled: false }, interfaces: { terminal: {} } }); + // Both importing the module and calling its factory record a setup. + await writeFile(join(workspace, "fabric-tool.mjs"), `import { appendFileSync } from "node:fs"; +appendFileSync(${JSON.stringify(marker)}, "import " + process.pid + "\\n"); +${TOOL_MODULE.replace("{ name, settings }) {", `{ name, settings }) {\n appendFileSync(${JSON.stringify(marker)}, "factory " + process.pid + "\\n");`)}`); + session = await sessionFactory().create(input); + assert.equal(await exists(marker), false); + + const launcher = join(session.configuration.runtimeDir, "interfaces", "terminal"); + const run = await launch(launcher, home, ["--print", "say hello"]).exited; + assert.equal(run.code, 0, run.stderr); + assert.match(toolDescriptions(requests.at(-1)).fabric_tool, /"mode":"test"/); + const setups = (await readFile(marker, "utf8")).trim().split("\n"); + assert.deepEqual(setups.map((line) => line.split(" ")[0]), ["import", "factory"]); + assert.notEqual(setups[0].split(" ")[1], String(process.pid)); + } finally { + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + await rm(home, { recursive: true, force: true }); + } +}); From 66666439f03d55c769e9d48c7c18383583e3bff4 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Thu, 3 Dec 2026 10:21:11 -0800 Subject: [PATCH 24/25] feat: refuse a Pi runtime with both the SDK and the terminal interface The SDK session and Pi's terminal UIs keep separate conversations, and Fabric's stream collector can't tell their Relay records apart, so a streamed invocation could lose records or include terminal UI turns. A runtime now runs one execution path: the schema and startup refuse the terminal interface unless sdk.enabled is false (pi_execution_path_conflict). The startup warning about the shared stream sink is gone, and the example no longer offers --sdk. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- adapters/typescript/pi/pi.fabric-adapter.json | 19 +- adapters/typescript/pi/src/settings.ts | 12 +- adapters/typescript/pi/src/terminal.ts | 45 +--- .../typescript/pi/test/relay-smoke.test.mjs | 213 +++++++++--------- adapters/typescript/pi/test/runtime.test.mjs | 8 +- adapters/typescript/pi/test/terminal.test.mjs | 111 ++++----- examples/interfaces/pi/pi_tui.py | 6 +- .../nemo_fabric_adapter_catalog/catalog.json | 51 ++++- tests/adapters/test_pi_adapter.py | 11 +- 9 files changed, 265 insertions(+), 211 deletions(-) diff --git a/adapters/typescript/pi/pi.fabric-adapter.json b/adapters/typescript/pi/pi.fabric-adapter.json index 5d09a8997..7cca01ff4 100644 --- a/adapters/typescript/pi/pi.fabric-adapter.json +++ b/adapters/typescript/pi/pi.fabric-adapter.json @@ -72,7 +72,7 @@ } }, "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 (/.fabric/pi/runtimes/, or the agent's state folder with runtime.keep_state) opens it on the runtime's agent directory in a separate conversation. 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." + "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 (/.fabric/pi/runtimes/, 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, @@ -84,7 +84,7 @@ "enabled": { "type": "boolean", "default": true, - "description": "Initialize the embedded SDK session during startup. Disable for native-only execution; SDK invocation then fails explicitly." + "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, @@ -107,6 +107,21 @@ } } } + }, + { + "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}}}} + } } ] }, diff --git a/adapters/typescript/pi/src/settings.ts b/adapters/typescript/pi/src/settings.ts index 517648d80..5baa096fa 100644 --- a/adapters/typescript/pi/src/settings.ts +++ b/adapters/typescript/pi/src/settings.ts @@ -34,11 +34,21 @@ export function terminalEnabled(config: AgentConfig): boolean { return switchedOn((interfaces as Record).terminal, false); } -/** The enabled execution paths; refuses a runtime with neither. */ +/** + * The enabled execution path; refuses a runtime with neither or both. The SDK session and + * Pi's terminal UIs keep separate conversations, and Fabric's stream collector can't tell + * their Relay records apart, so a runtime runs one of them. + */ export function executionPaths(config: AgentConfig): { sdk: boolean; terminal: boolean } { const paths = { sdk: sdkEnabled(config), terminal: terminalEnabled(config) }; if (!paths.sdk && !paths.terminal) { throw new LifecycleError("pi_no_execution_path", "Enable the Pi SDK or the terminal interface"); } + if (paths.sdk && paths.terminal) { + throw new LifecycleError( + "pi_execution_path_conflict", + "A Pi runtime runs the SDK session or the terminal interface, not both; set sdk.enabled to false to offer the terminal interface", + ); + } return paths; } diff --git a/adapters/typescript/pi/src/terminal.ts b/adapters/typescript/pi/src/terminal.ts index 3e8014454..ff314214f 100644 --- a/adapters/typescript/pi/src/terminal.ts +++ b/adapters/typescript/pi/src/terminal.ts @@ -27,11 +27,10 @@ import { LifecycleError, type AdapterStartInput } from "nemo-fabric-adapters-com import { agentDirectory, keepsState, runtimeDirectory } from "./agent-directory.js"; import type { PiNativeConfiguration, PiNativeCustomTool } from "./native-configuration.js"; -import { FABRIC_STREAM_SINK, PiNativeOnlySessionFactory } from "./native-only.js"; -import { atofStreamSinkNames } from "./relay-config.js"; +import { PiNativeOnlySessionFactory } from "./native-only.js"; import { RELAY_ENV_NAMES, type PiRelayRuntime } from "./relay.js"; import type { PiPromptOutcome, PiSessionFactory, PiSessionHandle } from "./runtime.js"; -import { sdkEnabled, terminalEnabled } from "./settings.js"; +import { executionPaths, terminalEnabled } from "./settings.js"; import { PiTerminalEnvironmentServer, removeSocketDirectory, terminalEnvironment } from "./terminal-environment.js"; export { terminalEnabled }; @@ -731,25 +730,6 @@ async function signal(terminals: readonly RegisteredTerminal[], name: NodeJS.Sig return unreadable; } -/** - * Terminal UIs send their Relay records through the runtime's gateway, which also feeds - * the ATOF sink that `start_runtime(..., streaming=True)` adds for `invoke_stream()`. - * The collector doesn't tell the SDK session's records from a terminal UI's, so with - * the SDK enabled a warning says that streamed invocations can lose or mix records once - * a terminal UI is used. - */ -export function terminalStreamingWarnings(sdk: boolean, relay: PiRelayRuntime | undefined): string[] { - if (!sdk || relay?.pluginConfig === undefined - || !atofStreamSinkNames(relay.pluginConfig).includes(FABRIC_STREAM_SINK)) { - return []; - } - return [ - `terminal UI turns reach the Relay ATOF sink ${FABRIC_STREAM_SINK} (start_runtime(..., streaming=True)), ` + - "so invoke_stream() output can lose records or include terminal UI records once a terminal UI is used; " + - "use invoke() or a separate runtime for streamed invocations", - ]; -} - /** Withdraws the terminal interface before the embedded session stops. */ export class PiTerminalSessionHandle implements PiSessionHandle { private readonly inner: PiSessionHandle; @@ -839,11 +819,11 @@ async function removeTerminalMcpConfiguration(configuration: PiNativeConfigurati /** * Add Pi's terminal interface to a runtime, as the runtime composes other native - * processes beside the SDK session (Hermes's InterfaceChildren, Pi's Relay - * gateway). Without interfaces.terminal, the SDK factory starts the runtime. - * With it, the SDK factory starts the runtime, or the native-only factory does - * when sdk.enabled is false; this then writes the launcher and descriptor from - * the runtime's configuration, and withdraws them before the runtime stops. + * processes (Hermes's InterfaceChildren, Pi's Relay gateway). Without + * interfaces.terminal, the SDK factory starts the runtime. With it, the native-only + * factory does, since a runtime with the terminal interface runs no SDK session; + * this then writes the launcher and descriptor from the runtime's configuration, + * and withdraws them before the runtime stops. */ export function withTerminalInterface( sdk: PiSessionFactory, @@ -862,8 +842,8 @@ class PiTerminalInterface implements PiSessionFactory { } async create(input: AdapterStartInput): Promise { - // Malformed settings fail here, before the session starts. - const terminal = terminalEnabled(input.config); + // Malformed settings, and a runtime with both execution paths, fail here, before the session starts. + const { terminal } = executionPaths(input.config); // An earlier runtime of the agent may have ended without stop, with or without this interface. if (keepsState(input)) await retireStaleTerminal(runtimeDirectory(input)); if (!terminal) { @@ -871,7 +851,7 @@ class PiTerminalInterface implements PiSessionFactory { } let handle: PiSessionHandle; try { - handle = await (sdkEnabled(input.config) ? this.sdk : this.nativeOnly).create(input); + handle = await this.nativeOnly.create(input); } catch (error) { // A start that fails after writing Pi's files mustn't leave mcp.json, which can hold // literal MCP stdio env values, in the kept runtime directory. @@ -898,11 +878,6 @@ class PiTerminalInterface implements PiSessionFactory { metadata: { cause: error instanceof Error ? error.message : String(error) }, }); } - for (const warning of [ - ...terminalStreamingWarnings(sdkEnabled(input.config), handle.relay), - ]) { - process.stderr.write(`Pi warning: ${warning}\n`); - } return new PiTerminalSessionHandle(handle, interfaceHandle); } catch (error) { await interfaceHandle?.withdraw().catch(() => { diff --git a/adapters/typescript/pi/test/relay-smoke.test.mjs b/adapters/typescript/pi/test/relay-smoke.test.mjs index 6279751d4..06f83754f 100644 --- a/adapters/typescript/pi/test/relay-smoke.test.mjs +++ b/adapters/typescript/pi/test/relay-smoke.test.mjs @@ -271,117 +271,112 @@ test( }, ); -for (const sdk of [true, false]) { - test( - `captures terminal TUI turns through the runtime's Relay gateway${sdk ? "" : " without the SDK"}`, - { skip: relayCommand === undefined ? "set FABRIC_TEST_NEMO_RELAY_COMMAND to the released CLI" : false, timeout: 90_000 }, - async () => { - const root = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-relay-terminal-"))); - const workspace = join(root, "workspace"); - const home = join(root, "home"); - const piAgentDir = join(root, "relay-install"); - const runtimeConfigPath = join(root, "relay-runtime.json"); - const upstream = createServer(async (request, response) => { - for await (const _chunk of request) { - // Drain the request. - } - response.writeHead(200, { "content-type": "text/event-stream" }); - response.end(openAiStream("relay terminal ok")); +test( + "captures terminal TUI turns through the runtime's Relay gateway", + { skip: relayCommand === undefined ? "set FABRIC_TEST_NEMO_RELAY_COMMAND to the released CLI" : false, timeout: 90_000 }, + async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-relay-terminal-"))); + const workspace = join(root, "workspace"); + const home = join(root, "home"); + const piAgentDir = join(root, "relay-install"); + const runtimeConfigPath = join(root, "relay-runtime.json"); + const upstream = createServer(async (request, response) => { + for await (const _chunk of request) { + // Drain the request. + } + response.writeHead(200, { "content-type": "text/event-stream" }); + response.end(openAiStream("relay terminal ok")); + }); + const upstreamUrl = await listen(upstream); + const previousConfigPath = process.env.FABRIC_RELAY_CONFIG_PATH; + let runtime; + try { + await mkdir(workspace); + await mkdir(home); + await execFileAsync(relayCommand, ["install", "pi", "--skip-doctor"], { + env: { ...process.env, PI_CODING_AGENT_DIR: piAgentDir }, + timeout: 10_000, }); - const upstreamUrl = await listen(upstream); - const previousConfigPath = process.env.FABRIC_RELAY_CONFIG_PATH; - let runtime; - try { - await mkdir(workspace); - await mkdir(home); - await execFileAsync(relayCommand, ["install", "pi", "--skip-doctor"], { - env: { ...process.env, PI_CODING_AGENT_DIR: piAgentDir }, - timeout: 10_000, - }); - const extensionPath = join(piAgentDir, "extensions", "nemo-relay"); - await writeFile(runtimeConfigPath, JSON.stringify({ relay: { config: { version: 1, components: [{ - kind: "observability", - enabled: true, - config: { - version: 4, - atof: { enabled: true, sinks: [{ type: "file", output_directory: join(root, "atof"), filename: "events.atof.jsonl" }] }, - atif: { enabled: true, output_directory: join(root, "atif") }, - }, - }] } } })); - process.env.FABRIC_RELAY_CONFIG_PATH = runtimeConfigPath; - const runtimeContext = { - artifacts: {}, - environment: { - control_location: "external_control", - env: { TEST_API_KEY: "credential-free-smoke" }, - environment_id: "environment-1", - ownership: "caller_owned", - provider: "local", - workspace, - }, - invocation_id: "start", - request_id: "request-start", - runtime_id: "relay-terminal", - telemetry: { relay_enabled: true }, - }; - runtime = new PiAdapterRuntime(withTerminalInterface(new PiSdkSessionFactory())); - await runtime.start({ - agentName: "pi-relay-terminal", - baseDir: root, - config: { - harness: { - settings: { - relay_extension_path: extensionPath, - interfaces: { terminal: {} }, - ...(sdk ? {} : { sdk: { enabled: false } }), - }, - }, - models: { - default: { api_key_env: "TEST_API_KEY", base_url: `${upstreamUrl}/v1`, model: "openai/gpt-oss-20b", provider: "nvidia" }, + const extensionPath = join(piAgentDir, "extensions", "nemo-relay"); + await writeFile(runtimeConfigPath, JSON.stringify({ relay: { config: { version: 1, components: [{ + kind: "observability", + enabled: true, + config: { + version: 4, + atof: { enabled: true, sinks: [{ type: "file", output_directory: join(root, "atof"), filename: "events.atof.jsonl" }] }, + atif: { enabled: true, output_directory: join(root, "atif") }, + }, + }] } } })); + process.env.FABRIC_RELAY_CONFIG_PATH = runtimeConfigPath; + const runtimeContext = { + artifacts: {}, + environment: { + control_location: "external_control", + env: { TEST_API_KEY: "credential-free-smoke" }, + environment_id: "environment-1", + ownership: "caller_owned", + provider: "local", + workspace, + }, + invocation_id: "start", + request_id: "request-start", + runtime_id: "relay-terminal", + telemetry: { relay_enabled: true }, + }; + runtime = new PiAdapterRuntime(withTerminalInterface(new PiSdkSessionFactory())); + await runtime.start({ + agentName: "pi-relay-terminal", + baseDir: root, + config: { + harness: { + settings: { + relay_extension_path: extensionPath, + interfaces: { terminal: {} }, + sdk: { enabled: false }, }, - tools: { enabled: [] }, }, - runtimeContext, - }); - if (sdk) { - assert.equal((await runtime.invoke({ input: "Reply from the SDK." }, runtimeContext)).status, "succeeded"); - } - // The launcher carries the Relay extension and its gateway; the person's environment has only the key. - const launcher = join(root, "artifacts", ".fabric", "pi", "runtimes", "relay-terminal", "interfaces", "terminal"); - const child = spawn("/bin/sh", [launcher, "--print", "Reply from the terminal UI."], { - cwd: home, - env: { PATH: process.env.PATH, HOME: home, TEST_API_KEY: "credential-free-smoke" }, - stdio: ["ignore", "pipe", "pipe"], - }); - let output = ""; - child.stdout.on("data", (chunk) => { output += chunk; }); - child.stderr.on("data", (chunk) => { output += chunk; }); - // close, not exit: both pipes are drained before the output assertions. - const code = await new Promise((resolve) => child.once("close", resolve)); - assert.equal(code, 0, output); - assert.match(output, /relay terminal ok/u); + models: { + default: { api_key_env: "TEST_API_KEY", base_url: `${upstreamUrl}/v1`, model: "openai/gpt-oss-20b", provider: "nvidia" }, + }, + tools: { enabled: [] }, + }, + runtimeContext, + }); + // The launcher carries the Relay extension and its gateway; the person's environment has only the key. + const launcher = join(root, "artifacts", ".fabric", "pi", "runtimes", "relay-terminal", "interfaces", "terminal"); + const child = spawn("/bin/sh", [launcher, "--print", "Reply from the terminal UI."], { + cwd: home, + env: { PATH: process.env.PATH, HOME: home, TEST_API_KEY: "credential-free-smoke" }, + stdio: ["ignore", "pipe", "pipe"], + }); + let output = ""; + child.stdout.on("data", (chunk) => { output += chunk; }); + child.stderr.on("data", (chunk) => { output += chunk; }); + // close, not exit: both pipes are drained before the output assertions. + const code = await new Promise((resolve) => child.once("close", resolve)); + assert.equal(code, 0, output); + assert.match(output, /relay terminal ok/u); - await runtime.stop(); - runtime = undefined; - const atof = (await readFile(join(root, "atof", "relay-terminal", "events.atof.jsonl"), "utf8")) - .trim().split("\n").map((line) => JSON.parse(line)); - const llmStarts = atof.filter((record) => - record.kind === "scope" && record.category === "llm" && record.scope_category === "start"); - assert.equal(llmStarts.length, sdk ? 2 : 1); - // Each Pi process is its own Relay session with its own trajectory. - const atifFiles = await readdir(join(root, "atif", "relay-terminal")); - assert.equal(atifFiles.length, sdk ? 2 : 1); - } finally { - await runtime?.stop().catch(() => undefined); - if (previousConfigPath === undefined) { - delete process.env.FABRIC_RELAY_CONFIG_PATH; - } else { - process.env.FABRIC_RELAY_CONFIG_PATH = previousConfigPath; - } - upstream.closeAllConnections(); - await new Promise((resolve) => upstream.close(resolve)); - await rm(root, { recursive: true, force: true }); + await runtime.stop(); + runtime = undefined; + const atof = (await readFile(join(root, "atof", "relay-terminal", "events.atof.jsonl"), "utf8")) + .trim().split("\n").map((line) => JSON.parse(line)); + const llmStarts = atof.filter((record) => + record.kind === "scope" && record.category === "llm" && record.scope_category === "start"); + assert.equal(llmStarts.length, 1); + // Each Pi process is its own Relay session with its own trajectory. + const atifFiles = await readdir(join(root, "atif", "relay-terminal")); + assert.equal(atifFiles.length, 1); + } finally { + await runtime?.stop().catch(() => undefined); + if (previousConfigPath === undefined) { + delete process.env.FABRIC_RELAY_CONFIG_PATH; + } else { + process.env.FABRIC_RELAY_CONFIG_PATH = previousConfigPath; } - }, - ); -} + upstream.closeAllConnections(); + await new Promise((resolve) => upstream.close(resolve)); + await rm(root, { recursive: true, force: true }); + } + }, +); diff --git a/adapters/typescript/pi/test/runtime.test.mjs b/adapters/typescript/pi/test/runtime.test.mjs index 292a75a0a..03942a0fb 100644 --- a/adapters/typescript/pi/test/runtime.test.mjs +++ b/adapters/typescript/pi/test/runtime.test.mjs @@ -590,7 +590,7 @@ test("a native-only runtime answers invocation with pi_sdk_disabled without prom await runtime.stop(); }); -test("a runtime with neither the SDK nor the terminal interface is refused before the session starts", async () => { +test("a runtime with neither or both of the SDK and the terminal interface is refused before the session starts", async () => { let created = false; const runtime = new PiAdapterRuntime({ async create() { @@ -604,6 +604,12 @@ test("a runtime with neither the SDK nor the terminal interface is refused befor ]) { await assert.rejects(runtime.start(startInputWith(settings)), (error) => error.code === "pi_no_execution_path"); } + for (const settings of [ + { interfaces: { terminal: {} } }, + { sdk: { enabled: true }, interfaces: { terminal: { enabled: true } } }, + ]) { + await assert.rejects(runtime.start(startInputWith(settings)), (error) => error.code === "pi_execution_path_conflict"); + } await assert.rejects( runtime.start(startInputWith({ sdk: { enabled: "false" }, interfaces: { terminal: {} } })), (error) => error.code === "pi_invalid_settings", diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index 01be309cd..7bf49b7dd 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -22,7 +22,6 @@ import { processIdentity, replaceIdentityLookupForTesting, supervisorExtension, - terminalStreamingWarnings, withTerminalInterface, } from "../dist/terminal.js"; import { runtimeDirectory } from "../dist/agent-directory.js"; @@ -54,6 +53,8 @@ function fakeHandle(configuration) { } const RUNTIME_KEY = "runtime-key-never-written"; +/** Settings that offer the terminal interface, which a runtime runs without the SDK session. */ +const TERMINAL = { sdk: { enabled: false }, interfaces: { terminal: {} } }; const TERMINAL_KEY = "terminal-key-from-launcher-environment"; const SYSTEM_PROMPT = "You are the NeMo Fabric terminal test agent."; @@ -156,7 +157,7 @@ async function filesUnder(directory) { test("terminalEnabled follows interfaces.terminal and its enabled switch", () => { assert.equal(terminalEnabled({}), false); assert.equal(terminalEnabled({ harness: { settings: { interfaces: {} } } }), false); - assert.equal(terminalEnabled({ harness: { settings: { interfaces: { terminal: {} } } } }), true); + assert.equal(terminalEnabled({ harness: { settings: TERMINAL } }), true); assert.equal(terminalEnabled({ harness: { settings: { interfaces: { terminal: { enabled: false } } } } }), false); assert.throws(() => terminalEnabled({ harness: { settings: { interfaces: { terminal: true } } } }), /schema/); }); @@ -227,22 +228,23 @@ test("the terminal factory passes a session through unchanged without interfaces test("the terminal factory stops the session when it can't write the terminal interface", async () => { const handle = fakeHandle(undefined); - const factory = withTerminalInterface({ create: async () => handle }); + const factory = withTerminalInterface({ create: async () => assert.fail("the SDK factory ran") }, + { create: async () => handle }); await assert.rejects( - factory.create(startInput("/nonexistent", "http://127.0.0.1:9/v1", { interfaces: { terminal: {} } })), + factory.create(startInput("/nonexistent", "http://127.0.0.1:9/v1", TERMINAL)), (error) => error.code === "pi_terminal_unavailable", ); assert.equal(handle.stopped, true); }); -test("the SDK session runs on the agent directory's files and ignores interfaces.terminal", { skip, timeout: 60_000 }, async () => { +test("the SDK session runs on the agent directory's files", { skip, timeout: 60_000 }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-sdk-"))); const { server, requests, url } = await modelServer(); - const directory = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal"); + const directory = join(workspace, "artifacts", ".fabric", "state", "nvidia.fabric.pi", "terminal-test"); let session; try { - session = await new PiSdkSessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); - // The terminal interface is the wrapper's; the session only writes Pi's own files. + session = await new PiSdkSessionFactory().create(keptInput(workspace, url, undefined, "rt-sdk", directory)); + // The session only writes Pi's own files. assert.equal(await exists(join(directory, "interfaces")), false); assert.deepEqual((await readdir(join(directory, "pi-agent"))).sort(), ["SYSTEM.md", "models.json", "settings.json"]); assert.equal(session.configuration.agentDir, join(directory, "pi-agent")); @@ -301,7 +303,7 @@ test("the launcher opens Pi on the runtime's model, key variable and system prom const descriptor = join(directory, "interfaces", "tui.json"); let session; try { - session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + session = await sessionFactory().create(startInput(workspace, url, TERMINAL)); // The attachment file is owner-only and versioned, with Pi's own launcher mode. assert.equal((await stat(descriptor)).mode & 0o777, 0o600); const { env_socket: socket, ...published } = JSON.parse(await readFile(descriptor, "utf8")); @@ -370,7 +372,7 @@ test("stopping the runtime closes an open terminal UI before the session stops", let session; let terminal; try { - session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + session = await sessionFactory().create(startInput(workspace, url, TERMINAL)); // RPC mode keeps Pi running without a TTY while its stdin stays open, as a terminal UI would. terminal = launch(join(directory, "interfaces", "terminal"), home, ["--mode", "rpc"], { stdin: "pipe" }); const deadline = Date.now() + 20_000; @@ -593,7 +595,7 @@ test("the terminal interface refuses a model key named like a variable the launc const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-key-reserved-"))); try { for (const name of ["PI_OFFLINE", "TERM"]) { - const input = startInput(workspace, "http://127.0.0.1:9/v1", { interfaces: { terminal: {} } }); + const input = startInput(workspace, "http://127.0.0.1:9/v1", TERMINAL); input.config.models.default.api_key_env = name; input.runtimeContext.environment.env[name] = RUNTIME_KEY; await assert.rejects(sessionFactory().create(input), { code: "pi_api_key_env_invalid" }, name); @@ -722,7 +724,7 @@ test("the launch helper refuses another runtime's tui.json", { timeout: 30_000 } test("the terminal interface refuses MCP headers that reference variables it sets", { skip }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-header-reserved-"))); try { - const input = startInput(workspace, "http://127.0.0.1:9/v1", { interfaces: { terminal: {} } }); + const input = startInput(workspace, "http://127.0.0.1:9/v1", TERMINAL); input.config.mcp = { servers: { remote: { transport: "streamable-http", url: "https://mcp.example.com/mcp", custom_headers: { Authorization: "Bearer ${TERM}" } } } }; input.runtimeContext.environment.env.TERM = "runtime-value"; @@ -742,7 +744,7 @@ test("stop keeps, and doesn't signal, a live terminal UI whose registration can' let session; let terminal; try { - session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + session = await sessionFactory().create(startInput(workspace, url, TERMINAL)); terminal = await fakeTerminal(clients, { ignoreSigterm: false, recordStart: true }); // Suspended, so its registration stays unreadable. process.kill(terminal.child.pid, "SIGSTOP"); @@ -800,7 +802,7 @@ test("stop doesn't signal a stale terminal UI it can't verify, keeps it for a re let session; let terminal; try { - session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + session = await sessionFactory().create(startInput(workspace, url, TERMINAL)); // A registration without an identity, as an older supervisor would write. terminal = await fakeTerminal(clients, { ignoreSigterm: false }); process.kill(terminal.child.pid, "SIGSTOP"); @@ -835,7 +837,7 @@ test("stop keeps, and doesn't signal, a terminal UI whose identity is of another let session; let terminal; try { - session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + session = await sessionFactory().create(startInput(workspace, url, TERMINAL)); // Recorded from ps where the runtime reads /proc, or the other way round: not comparable. terminal = await fakeTerminal(clients, { ignoreSigterm: false, identity: OTHER_KIND_IDENTITY }); await assert.rejects(session.stop(), { code: "pi_interface_cleanup_incomplete" }); @@ -864,7 +866,7 @@ test("stop reports both failures when tui.json can't be removed and terminal UIs const clients = join(interfaces, "tui.clients"); let session; try { - session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + session = await sessionFactory().create(startInput(workspace, url, TERMINAL)); // tui.json can't be removed (a non-empty directory stands in its place)... await rm(join(interfaces, "tui.json")); await mkdir(join(interfaces, "tui.json")); @@ -895,7 +897,7 @@ test("stop signals a terminal UI whose heartbeat writes fail, by its intact regi let session; let child; try { - session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + session = await sessionFactory().create(startInput(workspace, url, TERMINAL)); // The runtime's real supervisor extension, in a stand-in Pi host. const extension = join(workspace, "fabric-terminal.mjs"); await writeFile(extension, await readFile(join(interfaces, "fabric-terminal.ts"), "utf8")); @@ -937,7 +939,7 @@ test("stop signals a terminal UI whose heartbeats write partially and fail", { s let session; let child; try { - session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + session = await sessionFactory().create(startInput(workspace, url, TERMINAL)); const extension = join(workspace, "fabric-terminal.mjs"); await writeFile(extension, await readFile(join(interfaces, "fabric-terminal.ts"), "utf8")); // After the first registration, every write puts a few bytes on disk, then fails (as on a @@ -994,7 +996,7 @@ test("stop keeps a terminal UI whose identity can't be read just before SIGKILL" let terminal; let restore; try { - session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + session = await sessionFactory().create(startInput(workspace, url, TERMINAL)); // Ignores SIGTERM, so stop escalates to SIGKILL after the grace period. terminal = await fakeTerminal(clients, { ignoreSigterm: true, recordStart: true }); // The scan and the SIGTERM verify it; the lookup before SIGKILL fails. @@ -1028,7 +1030,7 @@ test("stop keeps a terminal UI that a denied signal leaves running", { skip, tim let session; let terminal; try { - session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + session = await sessionFactory().create(startInput(workspace, url, TERMINAL)); terminal = await fakeTerminal(clients, { ignoreSigterm: false, recordStart: true }); const target = terminal.child.pid; // Every real signal to the terminal UI, group or process, is denied, as for a process @@ -1062,7 +1064,7 @@ test("stop doesn't signal a freshly registered PID whose identity doesn't match" let session; let terminal; try { - session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + session = await sessionFactory().create(startInput(workspace, url, TERMINAL)); // As when a terminal UI died without removing its registration and another process // took its PID: the heartbeat is current, but the recorded identity is someone else's. terminal = await fakeTerminal(clients, { ignoreSigterm: false, identity: SAME_KIND_OTHER_IDENTITY }); @@ -1088,7 +1090,7 @@ test("stop closes a suspended terminal UI whose heartbeat went stale", { skip, t let session; let terminal; try { - session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + session = await sessionFactory().create(startInput(workspace, url, TERMINAL)); terminal = await fakeTerminal(clients, { ignoreSigterm: false, recordStart: true }); // Suspended, as with Ctrl+Z: no heartbeat for longer than the stale limit. process.kill(terminal.child.pid, "SIGSTOP"); @@ -1117,7 +1119,7 @@ test("stop sends SIGTERM to open terminal UIs at once", { skip, timeout: 60_000 let session; let terminal; try { - session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + session = await sessionFactory().create(startInput(workspace, url, TERMINAL)); terminal = await fakeTerminal(clients, { ignoreSigterm: false, recordStart: true }); const started = Date.now(); @@ -1143,7 +1145,7 @@ test("stop kills an open terminal UI's process group five seconds after SIGTERM" let session; let terminal; try { - session = await sessionFactory().create(startInput(workspace, url, { interfaces: { terminal: {} } })); + session = await sessionFactory().create(startInput(workspace, url, TERMINAL)); terminal = await fakeTerminal(clients, { ignoreSigterm: true, recordStart: true }); assert.ok(running(terminal.tool)); @@ -1303,14 +1305,17 @@ function toolDescriptions(request) { return Object.fromEntries((request.body.tools ?? []).map((tool) => [tool.function.name, tool.function.description])); } -test("the terminal UI gets the SDK session's module tools and MCP servers", { skip, timeout: 90_000 }, async () => { +test("the terminal UI gets the module tools and MCP servers an SDK session gets", { skip, timeout: 90_000 }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-tools-"))); const home = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-tools-home-"))); const { server, requests, url } = await modelServer(); let session; try { - session = await sessionFactory().create(await toolsInput(workspace, url, { interfaces: { terminal: {} } })); + // An SDK runtime and a terminal runtime from the same FabricConfig tools and MCP servers. + session = await sessionFactory().create(await toolsInput(workspace, url)); await session.prompt("hello"); + await session.stop(); + session = await sessionFactory().create(await toolsInput(workspace, url, TERMINAL)); const sdkTools = toolDescriptions(requests[0]); assert.match(sdkTools.fabric_tool, /"mode":"test"/); assert.match(sdkTools.fabric_tool, /"__proto__":\{"own":true\}/); @@ -1543,10 +1548,10 @@ test("keep_state retirement removes a killed runtime's environment socket direct let first; let second; try { - first = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-one", state)); + first = await sessionFactory().create(keptInput(workspace, url, TERMINAL, "rt-one", state)); const socket = JSON.parse(await readFile(join(state, "interfaces", "tui.json"), "utf8")).env_socket; // The first runtime's host is killed: no stop. The next start retires what it left. - second = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-two", state)); + second = await sessionFactory().create(keptInput(workspace, url, TERMINAL, "rt-two", state)); assert.equal(await exists(dirname(socket)), false); const current = JSON.parse(await readFile(join(state, "interfaces", "tui.json"), "utf8")).env_socket; assert.notEqual(current, socket); @@ -1561,20 +1566,17 @@ test("keep_state retirement removes a killed runtime's environment socket direct } }); -test("the terminal interface warns that streamed SDK invocations share Relay's stream sink", () => { - const sinks = (names) => ({ - pluginConfig: { - version: 1, - components: [{ kind: "observability", enabled: true, config: { atof: { enabled: true, - sinks: names.map((name) => ({ type: "stream", name })) } } }], - }, - }); - const [warning] = terminalStreamingWarnings(true, sinks(["nemo-fabric-stream"])); - assert.match(warning, /invoke_stream\(\)/); - // Without the SDK there is no invoke_stream(); native-only startup has its own warning. - assert.deepEqual(terminalStreamingWarnings(false, sinks(["nemo-fabric-stream"])), []); - assert.deepEqual(terminalStreamingWarnings(true, sinks(["own-sink"])), []); - assert.deepEqual(terminalStreamingWarnings(true, undefined), []); +test("a runtime refuses the SDK session and the terminal interface together, before writing anything", { skip }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-both-paths-"))); + try { + for (const settings of [{ interfaces: { terminal: {} } }, { sdk: { enabled: true }, interfaces: { terminal: {} } }]) { + await assert.rejects(sessionFactory().create(startInput(workspace, "http://127.0.0.1:9/v1", settings)), + (error) => error.code === "pi_execution_path_conflict"); + } + assert.equal(await exists(join(workspace, "artifacts")), false); + } finally { + await rm(workspace, { recursive: true, force: true }); + } }); test("the launcher clears Relay variables inherited from the person's shell", () => { @@ -1599,7 +1601,7 @@ test("an empty artifact root resolves to /artifacts, as for Hermes", ( test("the terminal interface refuses a base_url with credentials", { skip }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-url-credentials-"))); try { - const input = startInput(workspace, "http://user:secret@127.0.0.1:9/v1", { interfaces: { terminal: {} } }); + const input = startInput(workspace, "http://user:secret@127.0.0.1:9/v1", TERMINAL); await assert.rejects(sessionFactory().create(input), { code: "pi_base_url_credentials_unsupported" }); assert.equal(await exists(join(workspace, "artifacts")), false); } finally { @@ -1610,7 +1612,7 @@ test("the terminal interface refuses a base_url with credentials", { skip }, asy test("the terminal interface refuses a malformed base_url before writing anything", { skip }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-url-invalid-"))); try { - const input = startInput(workspace, "http://user:secret@localhost:99999/v1", { interfaces: { terminal: {} } }); + const input = startInput(workspace, "http://user:secret@localhost:99999/v1", TERMINAL); await assert.rejects(sessionFactory().create(input), { code: "pi_base_url_invalid" }); assert.equal(await exists(join(workspace, "artifacts")), false); } finally { @@ -1717,7 +1719,7 @@ test("a heartbeat that fails to write leaves the registration's identity whole", test("the terminal interface refuses a model key variable Pi can't reference", { skip }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-key-name-"))); try { - const input = startInput(workspace, "http://127.0.0.1:9/v1", { interfaces: { terminal: {} } }); + const input = startInput(workspace, "http://127.0.0.1:9/v1", TERMINAL); input.config.models.default.api_key_env = "TEST-API-KEY"; input.runtimeContext.environment.env["TEST-API-KEY"] = RUNTIME_KEY; await assert.rejects(sessionFactory().create(input), { code: "pi_api_key_env_invalid" }); @@ -1782,7 +1784,7 @@ test("with keep_state, a terminal conversation from one runtime continues in the const launcher = join(state, "interfaces", "terminal"); let session; try { - session = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-one", state)); + session = await sessionFactory().create(keptInput(workspace, url, TERMINAL, "rt-one", state)); // The whole Pi directory is the state folder, where NemoClaw looks for a kept agent's interfaces. const { env_socket: socket, ...published } = JSON.parse(await readFile(join(state, "interfaces", "tui.json"), "utf8")); assert.deepEqual(published, { @@ -1801,7 +1803,7 @@ test("with keep_state, a terminal conversation from one runtime continues in the session = undefined; assert.equal(await exists(join(workspace, "artifacts", ".fabric", "pi", "runtimes")), false); - session = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-two", state)); + session = await sessionFactory().create(keptInput(workspace, url, TERMINAL, "rt-two", state)); const second = await launch(launcher, home, ["--continue", "--print", "which word?"]).exited; assert.equal(second.code, 0, second.stderr); assert.equal(requests.length, 2); @@ -1824,7 +1826,7 @@ test("with keep_state, a start replaces what an earlier runtime left but keeps P const state = join(workspace, "artifacts", ".fabric", "state", "nvidia.fabric.pi", "terminal-test"); let session; try { - session = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-one", state)); + session = await sessionFactory().create(keptInput(workspace, url, TERMINAL, "rt-one", state)); // The runtime ends without stop, as when its host is killed; Pi saved a login of its own. session = undefined; await writeFile(join(state, "pi-agent", "auth.json"), "{\"other\":{\"type\":\"api_key\",\"key\":\"saved\"}}\n", { mode: 0o600 }); @@ -1866,7 +1868,7 @@ test("with keep_state, the next start closes a terminal UI left open by a killed let session; let terminal; try { - await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-one", state)); + await sessionFactory().create(keptInput(workspace, url, TERMINAL, "rt-one", state)); // rt-one's host is gone without stop; its terminal UI keeps running. terminal = launch(join(state, "interfaces", "terminal"), home, ["--mode", "rpc"], { stdin: "pipe" }); const deadline = Date.now() + 20_000; @@ -1875,7 +1877,7 @@ test("with keep_state, the next start closes a terminal UI left open by a killed await new Promise((resolve) => setTimeout(resolve, 100)); } - session = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-two", state)); + session = await sessionFactory().create(keptInput(workspace, url, TERMINAL, "rt-two", state)); // The new runtime started only after the old terminal UI stopped writing to the state folder. assert.notEqual(terminal.child.exitCode ?? terminal.child.signalCode, null, "rt-one's terminal UI still runs"); assert.equal(JSON.parse(await readFile(join(state, "interfaces", "tui.json"), "utf8")).runtime_id, "rt-two"); @@ -1896,12 +1898,13 @@ test("with keep_state, the SDK session's conversation is kept where the terminal const state = join(workspace, "artifacts", ".fabric", "state", "nvidia.fabric.pi", "terminal-test"); let session; try { - session = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-one", state)); + // An SDK runtime, then a terminal runtime, of one agent. + session = await sessionFactory().create(keptInput(workspace, url, undefined, "rt-one", state)); assert.equal((await session.prompt("invoked through the SDK")).text, "terminal-answer"); await session.stop(); session = undefined; - session = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-two", state)); + session = await sessionFactory().create(keptInput(workspace, url, TERMINAL, "rt-two", state)); const run = await launch(join(state, "interfaces", "terminal"), home, ["--continue", "--print", "and now?"]).exited; assert.equal(run.code, 0, run.stderr); assert.ok(userTexts(requests.at(-1)).some((text) => text.includes("invoked through the SDK"))); @@ -1981,7 +1984,7 @@ test("with keep_state, the terminal UI uses the runtime's key, not a login Pi sa const auth = join(state, "pi-agent", "auth.json"); let session; try { - session = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-one", state)); + session = await sessionFactory().create(keptInput(workspace, url, TERMINAL, "rt-one", state)); await session.stop(); session = undefined; // A terminal UI's /login saved a key for the configured provider, and one for another provider. @@ -1990,7 +1993,7 @@ test("with keep_state, the terminal UI uses the runtime's key, not a login Pi sa other: { type: "api_key", key: "other-saved-key" }, })}\n`, { mode: 0o644 }); - session = await sessionFactory().create(keptInput(workspace, url, { interfaces: { terminal: {} } }, "rt-two", state)); + session = await sessionFactory().create(keptInput(workspace, url, TERMINAL, "rt-two", state)); const launcher = join(session.configuration.runtimeDir, "interfaces", "terminal"); const run = await launch(launcher, home, ["--print", "say hello"]).exited; assert.equal(run.code, 0, run.stderr); diff --git a/examples/interfaces/pi/pi_tui.py b/examples/interfaces/pi/pi_tui.py index 1a8b58716..8f3aee9ac 100644 --- a/examples/interfaces/pi/pi_tui.py +++ b/examples/interfaces/pi/pi_tui.py @@ -59,7 +59,8 @@ def build_config(args: argparse.Namespace, output: Path) -> FabricConfig: "harness": { "adapter_id": "nvidia.fabric.pi", "settings": { - "sdk": {"enabled": args.sdk}, + # A runtime that offers the terminal interface runs no SDK session. + "sdk": {"enabled": False}, "interfaces": {"terminal": {}}, }, }, @@ -186,9 +187,6 @@ def main() -> None: default=32768, help="With --api: the model's context window", ) - parser.add_argument( - "--sdk", action="store_true", help="Also start the embedded SDK session" - ) parser.add_argument( "--no-keep-state", action="store_true", diff --git a/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json b/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json index 5012d62fc..ccb908817 100644 --- a/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json +++ b/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json @@ -3684,6 +3684,51 @@ "interfaces" ] } + }, + { + "if": { + "properties": { + "interfaces": { + "properties": { + "terminal": { + "not": { + "properties": { + "enabled": { + "const": false + } + }, + "required": [ + "enabled" + ] + } + } + }, + "required": [ + "terminal" + ] + } + }, + "required": [ + "interfaces" + ] + }, + "then": { + "properties": { + "sdk": { + "properties": { + "enabled": { + "const": false + } + }, + "required": [ + "enabled" + ] + } + }, + "required": [ + "sdk" + ] + } } ], "properties": { @@ -3720,7 +3765,7 @@ "properties": { "terminal": { "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 (/.fabric/pi/runtimes/, or the agent's state folder with runtime.keep_state) opens it on the runtime's agent directory in a separate conversation. 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.", + "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 (/.fabric/pi/runtimes/, 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.", "properties": { "enabled": { "default": true, @@ -3744,7 +3789,7 @@ "properties": { "enabled": { "default": true, - "description": "Initialize the embedded SDK session during startup. Disable for native-only execution; SDK invocation then fails explicitly.", + "description": "Initialize the embedded SDK session during startup. Disable for native-only execution, which the terminal interface requires; SDK invocation then fails explicitly.", "type": "boolean" } }, @@ -3792,7 +3837,7 @@ "name": "nemo-fabric-adapters-pi", "version": "0.8.0" }, - "sha256": "01e72ccce63d1a920f4649d1728159aa46c973714e3f21858b800aaa7e72d7f6", + "sha256": "284ece2aab39b82e05a909aa8d5f51c61effd7053ff62671c3161680c11990db", "source": "adapters/typescript/pi/pi.fabric-adapter.json" }, "nvidia.fabric.qwen": { diff --git a/tests/adapters/test_pi_adapter.py b/tests/adapters/test_pi_adapter.py index 5b6ae134a..41722c282 100644 --- a/tests/adapters/test_pi_adapter.py +++ b/tests/adapters/test_pi_adapter.py @@ -296,7 +296,6 @@ def config_with_settings(settings: dict[str, object]) -> FabricConfig: @pytest.mark.parametrize( "settings", [ - pytest.param({"interfaces": {"terminal": {}}}, id="terminal-and-sdk"), pytest.param( {"sdk": {"enabled": False}, "interfaces": {"terminal": {}}}, id="terminal-only", @@ -322,8 +321,16 @@ def test_pi_descriptor_plans_execution_paths(settings: dict[str, object]): {"sdk": {"enabled": False}, "interfaces": {"terminal": {"enabled": False}}}, id="disabled-terminal-is-not-execution", ), + pytest.param({"interfaces": {"terminal": {}}}, id="terminal-with-default-sdk"), + pytest.param( + {"sdk": {"enabled": True}, "interfaces": {"terminal": {"enabled": True}}}, + id="terminal-with-sdk", + ), pytest.param({"sdk": {"enabled": "false"}}, id="sdk-not-boolean"), - pytest.param({"interfaces": {"terminal": {"port": 9119}}}, id="terminal-takes-no-port"), + pytest.param( + {"sdk": {"enabled": False}, "interfaces": {"terminal": {"port": 9119}}}, + id="terminal-takes-no-port", + ), pytest.param({"interfaces": {"dashboard": {}}}, id="unsupported-interface"), ], ) From fac752f87aa01caceb531d74c647f9d7defc4631 Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Thu, 3 Dec 2026 11:25:11 -0800 Subject: [PATCH 25/25] fix: confirm Pi terminal UIs exit after SIGKILL and check readiness against models.json Stop now waits up to two seconds for each terminal UI it sent SIGKILL to exit. One that still runs, for example blocked in the kernel, keeps its registration and fails stop with pi_interface_cleanup_incomplete, so a kept agent directory's next runtime never starts while it can still write. A terminal-only runtime's ready check now loads models.json as it is on disk, with no credentials or network, as a new terminal UI would, rather than the model catalog read at start. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yuchen Zhang --- .../typescript/pi/src/native-configuration.ts | 22 +++++-- adapters/typescript/pi/src/native-only.ts | 31 ++++++--- adapters/typescript/pi/src/terminal.ts | 54 ++++++++++++++-- adapters/typescript/pi/test/terminal.test.mjs | 64 +++++++++++++++++++ 4 files changed, 151 insertions(+), 20 deletions(-) diff --git a/adapters/typescript/pi/src/native-configuration.ts b/adapters/typescript/pi/src/native-configuration.ts index e763587f5..5f1ab490b 100644 --- a/adapters/typescript/pi/src/native-configuration.ts +++ b/adapters/typescript/pi/src/native-configuration.ts @@ -976,6 +976,19 @@ export function directoryUnavailable(error: unknown): LifecycleError { }); } +/** + * Load Pi's model catalog from an agent directory's models.json, as the `pi` CLI loads it, + * with no credentials and no network. + */ +export async function loadAgentDirectoryModels(pi: PiSdkModules, agentDir: string): Promise { + return pi.ModelRuntime.create({ + credentials: new pi.InMemoryCredentialStore(), + modelsPath: join(agentDir, "models.json"), + allowModelNetwork: false, + refreshOnCreate: false, + }); +} + /** Write the configuration to its agent directory and load the selected model from those files. */ async function writeConfiguration(options: { pi: PiSdkModules; @@ -994,13 +1007,8 @@ async function writeConfiguration(options: { } catch (error) { throw directoryUnavailable(error); } - const modelRuntime = await pi.ModelRuntime.create({ - // The key stays in memory; models.json only names its variable. - credentials: new pi.InMemoryCredentialStore(), - modelsPath: join(configuration.agentDir, "models.json"), - allowModelNetwork: false, - refreshOnCreate: false, - }); + // The key stays in memory; models.json only names its variable. + const modelRuntime = await loadAgentDirectoryModels(pi, configuration.agentDir); const modelsError = modelRuntime.getError(); if (modelsError !== undefined) { // Pi reports 'no "api" specified' when it can't resolve the model's wire protocol (not a diff --git a/adapters/typescript/pi/src/native-only.ts b/adapters/typescript/pi/src/native-only.ts index 2a4dd7150..d592b7724 100644 --- a/adapters/typescript/pi/src/native-only.ts +++ b/adapters/typescript/pi/src/native-only.ts @@ -11,7 +11,12 @@ import type { AdapterCheckResult, CheckLevel, CheckSource } from "nemo-fabric-adapter-contract"; import { LifecycleError, unobservedHealth, type AdapterStartInput } from "nemo-fabric-adapters-common"; -import { preparePiConfiguration, type PiModelRuntime, type PiNativeConfiguration } from "./native-configuration.js"; +import { + loadAgentDirectoryModels, + preparePiConfiguration, + type PiNativeConfiguration, + type PiSdkModules, +} from "./native-configuration.js"; import { atofStreamSinkNames } from "./relay-config.js"; import { PiRelayFactory, type PiRelayControllerFactory, type PiRelayRuntime } from "./relay.js"; import type { PiPromptOutcome, PiSessionFactory, PiSessionHandle } from "./runtime.js"; @@ -20,15 +25,15 @@ class PiNativeOnlyHandle implements PiSessionHandle { readonly configuration: PiNativeConfiguration; readonly turnCount = 0; readonly relay?: PiRelayRuntime; - private readonly modelRuntime: PiModelRuntime; + private readonly pi: PiSdkModules; private readonly expectedModel: { id: string; provider: string }; private stopped = false; - constructor(configuration: PiNativeConfiguration, modelRuntime: PiModelRuntime, + constructor(configuration: PiNativeConfiguration, pi: PiSdkModules, expectedModel: { id: string; provider: string }, relay?: PiRelayRuntime) { this.configuration = configuration; this.relay = relay; - this.modelRuntime = modelRuntime; + this.pi = pi; this.expectedModel = expectedModel; } @@ -42,13 +47,23 @@ class PiNativeOnlyHandle implements PiSessionHandle { const source: CheckSource = level === "live" ? "fabric.adapter.liveness" : level === "active" ? "fabric.adapter.interface" : "fabric.adapter.readiness"; const observed_at = new Date().toISOString(); - if (level === "ready" - && this.modelRuntime.getModel(this.expectedModel.provider, this.expectedModel.id) === undefined) { + if (level === "ready" && !(await this.modelResolves())) { return { outcome: "failed", reason_code: "health_failed", activity: "unknown", source, observed_at }; } return { outcome: "passed", reason_code: null, activity: "unknown", source, observed_at }; } + /** Whether the selected model resolves from models.json as it is now, as a new terminal UI reads it. */ + private async modelResolves(): Promise { + try { + const models = await loadAgentDirectoryModels(this.pi, this.configuration.agentDir); + return models.getError() === undefined + && models.getModel(this.expectedModel.provider, this.expectedModel.id) !== undefined; + } catch { + return false; + } + } + async stop(): Promise { this.stopped = true; } @@ -82,11 +97,11 @@ export class PiNativeOnlySessionFactory implements PiSessionFactory { } async create(input: AdapterStartInput): Promise { - const { configuration, modelRuntime, model } = await preparePiConfiguration(input); + const { pi, configuration, model } = await preparePiConfiguration(input); const relay = await this.relayFactory.start(input, { api: model.api, baseUrl: model.baseUrl }); for (const warning of sdkOnlySettings(relay)) { process.stderr.write(`Pi warning: ${warning}\n`); } - return new PiNativeOnlyHandle(configuration, modelRuntime, { id: model.id, provider: model.provider }, relay); + return new PiNativeOnlyHandle(configuration, pi, { id: model.id, provider: model.provider }, relay); } } diff --git a/adapters/typescript/pi/src/terminal.ts b/adapters/typescript/pi/src/terminal.ts index ff314214f..9834f0b9d 100644 --- a/adapters/typescript/pi/src/terminal.ts +++ b/adapters/typescript/pi/src/terminal.ts @@ -42,6 +42,8 @@ const TERMINAL_LAUNCH_HELPER = fileURLToPath(new URL("./terminal-launch.js", imp /** How long `stop` waits after SIGTERM before it sends SIGKILL to open terminal UIs, as the Hermes adapter does. */ const TERMINAL_STOP_GRACE_MS = 5_000; +/** How long stop waits, after SIGKILL, for each terminal UI it signalled to exit. */ +const TERMINAL_KILL_CONFIRM_MS = 2_000; const TERMINAL_HEARTBEAT_MS = 500; /** How long a terminal UI waits for its orderly shutdown before it sends itself SIGTERM. */ const TERMINAL_SELF_TERMINATE_MS = 2_000; @@ -507,7 +509,7 @@ async function closeTerminals(clients: string): Promise { } throw new LifecycleError( "pi_interface_cleanup_incomplete", - "A Pi terminal UI's registration or process couldn't be verified, so it wasn't signalled", + "A Pi terminal UI couldn't be verified and signalled, or still ran after SIGKILL; its registration is kept", { metadata: { pids: unverified } }, ); } @@ -521,8 +523,9 @@ interface RegisteredTerminal { } /** - * SIGTERM each terminal UI's process group, then SIGKILL the groups after the grace period. - * Returns the PIDs left unsignalled at the end: their identity couldn't be read, or the signal failed. + * SIGTERM each terminal UI's process group, then SIGKILL the groups after the grace period, + * and wait for the terminal UIs SIGKILL reached to exit. Returns the PIDs stop can't show are + * gone: their identity couldn't be read, the signal failed, or the process still ran after SIGKILL. */ async function stopTerminals(terminals: readonly RegisteredTerminal[], graceMs: number): Promise { if (terminals.length === 0) return []; @@ -536,10 +539,51 @@ async function stopTerminals(terminals: readonly RegisteredTerminal[], graceMs: } // The group too: processes the terminal UI's tools started can outlive it. A terminal UI // seen to exit gets no signal of its own, since its PID may now belong to another process. - return [ - ...await signal(terminals.filter(({ pid }) => !exited.has(pid)), "SIGKILL"), + const killed = terminals.filter(({ pid }) => !exited.has(pid)); + const unsignalled = [ + ...await signal(killed, "SIGKILL"), ...await signal(terminals.filter(({ pid }) => exited.has(pid)), "SIGKILL", { groupOnly: true }), ]; + // SIGKILL takes effect asynchronously, and not while a process waits in the kernel, such as + // on a slow disk. A terminal UI's registration is removed only once it is gone, so a kept + // directory's next runtime never starts while it can still write to pi-sessions. + let running = killed.filter(({ pid }) => !unsignalled.includes(pid)); + const confirmBy = Date.now() + TERMINAL_KILL_CONFIRM_MS; + for (;;) { + const still: RegisteredTerminal[] = []; + for (const terminal of running) if (await stillRunning(terminal)) still.push(terminal); + running = still; + if (running.length === 0 || Date.now() >= confirmBy) break; + await sleep(50); + } + return [...unsignalled, ...running.map(({ pid }) => pid)]; +} + +/** + * Whether a terminal UI is still running: its PID is alive, isn't a zombie, and isn't held by + * a later process. An identity that can't be read counts as running, so stop keeps it. + */ +async function stillRunning({ pid, identity }: RegisteredTerminal): Promise { + if (!alive(pid)) return false; + const current = await lookupIdentity(pid); + if (current !== undefined && comparableIdentities(current, identity) && current !== identity) return false; + return !(await zombie(pid)); +} + +/** Whether a process has exited and waits for its parent to collect it, so it runs no code. */ +async function zombie(pid: number): Promise { + try { + const stat = await readFile(`/proc/${pid}/stat`, "utf8"); + return stat.slice(stat.lastIndexOf(")") + 2).startsWith("Z"); + } catch { + // No /proc: ask ps. + } + try { + const { stdout } = await execFileAsync("ps", ["-o", "stat=", "-p", String(pid)], { encoding: "utf8" }); + return stdout.trim().startsWith("Z"); + } catch { + return false; + } } /** Whether two identities come from the same source (/proc or ps), so comparing them means something. */ diff --git a/adapters/typescript/pi/test/terminal.test.mjs b/adapters/typescript/pi/test/terminal.test.mjs index 7bf49b7dd..7b6c1d404 100644 --- a/adapters/typescript/pi/test/terminal.test.mjs +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -1169,6 +1169,70 @@ test("stop kills an open terminal UI's process group five seconds after SIGTERM" } }); +test("stop keeps, and reports, a terminal UI still running after SIGKILL", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-terminal-unkilled-"))); + const { server, url } = await modelServer(); + const clients = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal", "interfaces", "tui.clients"); + const kill = process.kill; + let session; + let terminal; + try { + session = await sessionFactory().create(startInput(workspace, url, TERMINAL)); + terminal = await fakeTerminal(clients, { ignoreSigterm: true, recordStart: true }); + const target = terminal.child.pid; + // SIGKILL to the terminal UI, group or process, is accepted but doesn't take effect, as + // for a process stuck in uninterruptible sleep; other signals go through. + process.kill = (pid, signal) => { + if (Math.abs(pid) === target && signal === "SIGKILL") return true; + return kill.call(process, pid, signal); + }; + await assert.rejects(session.stop(), { code: "pi_interface_cleanup_incomplete" }); + process.kill = kill; + assert.equal(running(target), true); + // The registration is kept until the process is gone, so a later stop retries it. + await new Promise((resolve) => setTimeout(resolve, 500)); + assert.equal(await exists(join(clients, String(target))), true); + } finally { + process.kill = kill; + if (terminal !== undefined) { + for (const pid of [-terminal.child.pid, terminal.tool]) try { process.kill(pid, "SIGKILL"); } catch {} + } + await session?.stop().catch(() => undefined); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + +test("a native-only runtime's ready check reads models.json as a new terminal UI would", { skip, timeout: 60_000 }, async () => { + const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-native-ready-"))); + const { server, url } = await modelServer(); + const models = join(workspace, "artifacts", ".fabric", "pi", "runtimes", "rt-terminal", "pi-agent", "models.json"); + let session; + try { + session = await sessionFactory().create(startInput(workspace, url, TERMINAL)); + assert.equal((await session.check("ready")).outcome, "passed"); + const written = await readFile(models, "utf8"); + + // The selected model is gone from the file a terminal UI would load. + await writeFile(models, JSON.stringify({ providers: {} })); + assert.equal((await session.check("live")).outcome, "passed"); + assert.equal((await session.check("ready")).reason_code, "health_failed"); + + // A file Pi can't parse fails the check too. + await writeFile(models, "{"); + assert.equal((await session.check("ready")).reason_code, "health_failed"); + + await writeFile(models, written); + assert.equal((await session.check("ready")).outcome, "passed"); + } finally { + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + test("a native-only runtime writes Pi's files and the launcher but runs no SDK session",{ skip, timeout: 60_000 }, async () => { const workspace = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-native-only-"))); const home = await realpath(await mkdtemp(join(tmpdir(), "fabric-pi-native-only-home-")));