diff --git a/adapters/typescript/pi/pi.fabric-adapter.json b/adapters/typescript/pi/pi.fabric-adapter.json index 1cae737c4..7cca01ff4 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,72 @@ "type": "string", "minLength": 1, "description": "Absolute path or environment.workspace-relative path to the NeMo Relay Pi extension matching the CLI release" + }, + "interfaces": { + "type": "object", + "properties": { + "terminal": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "default": true, + "description": "Offer Pi's terminal TUI. A present terminal interface is on unless this is false." + } + }, + "additionalProperties": false, + "description": "Experimental: Pi's terminal TUI, which runs in its own process and needs no port: the launcher interfaces/terminal in the runtime's Pi directory (/.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, + "description": "Native interfaces offered by the runtime." + }, + "sdk": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "default": true, + "description": "Initialize the embedded SDK session during startup. Disable for native-only execution, which the terminal interface requires; SDK invocation then fails explicitly." + } + }, + "additionalProperties": false, + "description": "Embedded SDK execution, enabled by default. Runtime management remains available when disabled." } }, - "additionalProperties": false + "additionalProperties": false, + "allOf": [ + { + "if": { + "required": ["sdk"], + "properties": {"sdk": {"required": ["enabled"], "properties": {"enabled": {"const": false}}}} + }, + "then": { + "required": ["interfaces"], + "properties": { + "interfaces": { + "required": ["terminal"], + "properties": {"terminal": {"properties": {"enabled": {"const": true}}}} + } + } + } + }, + { + "if": { + "required": ["interfaces"], + "properties": { + "interfaces": { + "required": ["terminal"], + "properties": {"terminal": {"not": {"required": ["enabled"], "properties": {"enabled": {"const": false}}}}} + } + } + }, + "then": { + "required": ["sdk"], + "properties": {"sdk": {"required": ["enabled"], "properties": {"enabled": {"const": false}}}} + } + } + ] }, "model_schema": { "type": "object", diff --git a/adapters/typescript/pi/src/agent-directory.ts b/adapters/typescript/pi/src/agent-directory.ts new file mode 100644 index 000000000..93f23cd15 --- /dev/null +++ b/adapters/typescript/pi/src/agent-directory.ts @@ -0,0 +1,150 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// The runtime's Pi agent directory: Pi's own configuration files, written from +// what the adapter resolved from FabricConfig. The embedded SDK session loads its +// settings, model catalog, MCP servers and system prompt from these files, and +// Pi's terminal UI reads the same files, so both run on one configuration. +// models.json names the model key's environment variable, and the SDK session +// supplies the key in memory. mcp.json holds the configured MCP servers as +// FabricConfig gives them, including any literal stdio env values, so every file +// is owner-only. Without the terminal interface or runtime.keep_state the +// directory is temporary and stop removes it. +// With runtime.keep_state, every runtime of the agent uses the same directory, so +// each start rewrites these files from FabricConfig and removes the ones it no +// longer configures; files Pi writes itself stay, except a login auth.json holds +// for the configured provider, which the runtime's key replaces. + +import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { join, resolve } from "node:path"; + +import type { JsonObject } from "nemo-fabric-adapter-contract"; +import type { AdapterStartInput } from "nemo-fabric-adapters-common"; + +import type { PiNativeConfiguration } from "./native-configuration.js"; + +/** + * The agent's state folder (`RuntimeContext.state_dir`) with runtime.keep_state, as the + * Hermes adapter uses it for its home; otherwise `/.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 = + // 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); +} + +/** 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 }); + // writeFile applies the mode only to a new file; Pi may have recreated one in a kept directory. + await chmod(path, 0o600); +} + +/** + * Remove the login that Pi's auth.json saved for the configured provider, such as one a + * terminal UI's /login stored in a kept directory. Pi's terminal UI prefers a saved login to + * the key models.json names, so it would otherwise use another key than the SDK session, + * which never reads auth.json. Logins for other providers stay; a file Pi can't parse is + * left as it is, because Pi ignores it too. + */ +async function removeSavedLogin(directory: string, provider: string): Promise { + 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. + // Only Pi's terminal UI reads mcp.json; the SDK session gets its MCP servers in memory. + if (configuration.terminal && Object.keys(configuration.mcpServers).length > 0) { + await writePrivate( + join(directory, "mcp.json"), + `${JSON.stringify({ mcpServers: configuration.mcpServers }, null, 2)}\n`, + ); + } else { + await rm(join(directory, "mcp.json"), { force: true }); + } + // Pi appends /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); + } 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..5f1ab490b --- /dev/null +++ b/adapters/typescript/pi/src/native-configuration.ts @@ -0,0 +1,1045 @@ +// 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 { 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"; +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"; +import { sdkEnabled, terminalEnabled } from "./settings.js"; +import { LAUNCHER_ENV_NAMES, mcpHeaderVariables, TERMINAL_ENV_NAMES } from "./terminal-environment.js"; + +export interface PiNativeCustomTool { + name: string; + path: string; + exportName: string; + settings: JsonObject; +} + +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; + /** 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. */ + 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 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; +} + +// 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; +/** 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 { + 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; +} + +/** + * 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. + */ +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, 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)); + // 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)); +} + +/** + * 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, + 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, isEmpty)]), + ); + 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]; + })); +} + +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; +} + +/** + * 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[] = []; + 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); + // 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); + } 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; +} + +/** + * 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 { + url = new URL(value); + } catch { + 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" } }, + ); + } +} + +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 for the SDK session, with header references expanded; never written to disk. */ + 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. 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 }), + // 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); + 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"); + } + 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. + 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 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( + "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`); + } + + const extensionPaths = await resolveExtensionPaths(workspace, harnessSettings(input.config).extensions); + const skillPaths = await resolveSkillPaths(input.baseDir, input.config.skills?.paths ?? []); + // 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) + // 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 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, + terminal, + 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; + } +} + +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) }, + }); +} + +/** + * 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; + 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. + try { + await writeAgentDirectory(configuration); + } catch (error) { + throw directoryUnavailable(error); + } + // 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 + // 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"); + } + return { + pi, + configuration, + modelRuntime, + model, + extensionPaths: options.extensionPaths, + skillPaths: options.skillPaths, + customTools: options.customTools, + mcpServers: options.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..d592b7724 --- /dev/null +++ b/adapters/typescript/pi/src/native-only.ts @@ -0,0 +1,107 @@ +// 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 { + 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"; + +class PiNativeOnlyHandle implements PiSessionHandle { + readonly configuration: PiNativeConfiguration; + readonly turnCount = 0; + readonly relay?: PiRelayRuntime; + private readonly pi: PiSdkModules; + private readonly expectedModel: { id: string; provider: string }; + private stopped = false; + + constructor(configuration: PiNativeConfiguration, pi: PiSdkModules, + expectedModel: { id: string; provider: string }, relay?: PiRelayRuntime) { + this.configuration = configuration; + this.relay = relay; + this.pi = pi; + 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" && !(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; + } +} + +/** The Relay ATOF sink that the Python SDK adds for `start_runtime(..., streaming=True)`. */ +export 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)) can receive terminal TUI ` + + "records, but sdk.enabled is false, so no invocation delivers them through invoke_stream()", + ); + } + 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 { 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, pi, { 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..697611c72 100644 --- a/adapters/typescript/pi/src/pi-sdk.ts +++ b/adapters/typescript/pi/src/pi-sdk.ts @@ -1,13 +1,13 @@ // 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 { rm } from "node:fs/promises"; +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 +19,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 +27,22 @@ import { type PiRelayControllerFactory, type PiRelayRuntime, } from "./relay.js"; +import { + containedBy, + directoryUnavailable, + 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 +198,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 +234,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 ""; @@ -868,6 +257,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; @@ -875,20 +271,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,6 +387,8 @@ class PiSdkSessionHandle implements PiSessionHandle { return; } this.stopped = true; + // 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 { try { @@ -1014,7 +412,7 @@ class PiSdkSessionHandle implements PiSessionHandle { failure ??= error; } } finally { - await rm(this.runtimeDir, { recursive: true, force: true }); + await removeEphemeralDirectory(this.configuration); } if (failure !== undefined) { throw failure; @@ -1030,114 +428,17 @@ 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`); + 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"); } - - // 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, - }, - }); + const { pi, configuration, modelRuntime, model, extensionPaths, skillPaths, customTools, mcpServers } = + await preparePiConfiguration(input); + const { workspace, agentDir } = configuration; let relay: PiRelayRuntime | undefined; let handle: PiSdkSessionHandle | undefined; - let runtimeDir: string | undefined; try { + const settings = pi.SettingsManager.create(workspace, agentDir, { projectTrusted: false }); relay = await this.relayFactory.start(input, { api: model.api, baseUrl: model.baseUrl, @@ -1145,8 +446,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 +474,10 @@ 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, + // Discovery would append /APPEND_SYSTEM.md, which FabricConfig never configures. + appendSystemPrompt: [], }); await resourceLoader.reload(); const extensionResult = resourceLoader.getExtensions(); @@ -1233,14 +534,20 @@ 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).catch((error: unknown) => { + throw directoryUnavailable(error); + })) + : 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,8 +591,8 @@ 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 }); + if (handle === undefined) { + await removeEphemeralDirectory(configuration); } 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..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", @@ -121,10 +122,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 +145,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 +168,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 +181,7 @@ export class PiRelayRuntime { constructor(options: { extensionPath: string; + extensionEnvironment?: Record; pluginConfig: RelayPluginConfig; atifMatchers: RelayAtifMatcher[]; child: ChildProcess; @@ -181,6 +191,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 +334,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..5baa096fa --- /dev/null +++ b/adapters/typescript/pi/src/settings.ts @@ -0,0 +1,54 @@ +// 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 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-client.ts b/adapters/typescript/pi/src/terminal-client.ts new file mode 100644 index 000000000..8a2081440 --- /dev/null +++ b/adapters/typescript/pi/src/terminal-client.ts @@ -0,0 +1,81 @@ +// 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 { 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 { + 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"); + } + // 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; + } + 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..6ea81d9f0 --- /dev/null +++ b/adapters/typescript/pi/src/terminal-environment.ts @@ -0,0 +1,192 @@ +// 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, 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, 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"; + +/** 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, +]); + +/** 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. */ +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 ?? {})) { + 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, 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 ?? {}; + // 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]; + } + 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. + * 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 readonly connections: Set; + private closing: Promise | undefined; + private removed = false; + + 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 socketDirectory(); + const socketPath = join(directory, SOCKET_NAME); + 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) => { + listening.once("error", reject); + listening.listen(socketPath, () => { + listening.off("error", reject); + resolve(); + }); + }); + 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, 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) }, + }); + } + } + + /** Stop answering, drop open connections, then remove the socket and its directory. */ + async close(): Promise { + 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. 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" || !isAbsolute(socketPath) || basename(socketPath) !== SOCKET_NAME) return; + const directory = dirname(socketPath); + if (!basename(directory).startsWith(SOCKET_DIRECTORY_PREFIX)) return; + 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 new file mode 100644 index 000000000..d85e042f7 --- /dev/null +++ b/adapters/typescript/pi/src/terminal-launch.ts @@ -0,0 +1,101 @@ +// 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 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, 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, runtimeId, 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`, + ); + 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"; +} + +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 +// 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)); + // 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)}`); +} + +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)); +} + +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. +// 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; +} +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. + 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 new file mode 100644 index 000000000..9834f0b9d --- /dev/null +++ b/adapters/typescript/pi/src/terminal.ts @@ -0,0 +1,940 @@ +// 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 { execFile } from "node:child_process"; +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"; + +import type { AdapterCheckResult, CheckLevel } from "nemo-fabric-adapter-contract"; +import { LifecycleError, type AdapterStartInput } from "nemo-fabric-adapters-common"; + +import { agentDirectory, keepsState, runtimeDirectory } from "./agent-directory.js"; +import type { PiNativeConfiguration, PiNativeCustomTool } from "./native-configuration.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 { executionPaths, 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; +/** 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; +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; + /** The launch helper, which fetches the runtime's environment and runs the CLI. */ + helper: string; + cli: string; + agentDir: string; + 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 { + 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, switches and endpoints, never credentials (the", + "# 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", + "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`, + // 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.runtimeId, 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 { execFileSync } from "node:child_process"; +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 +// 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]; + if (/^\\d+$/.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 { + // 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 { + // 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. +const STATE = Symbol.for("nemo-fabric.pi.terminal-supervisor"); +const supervisor = (globalThis[STATE] ??= { context: undefined, stopping: false, timer: undefined, registered: false }); + +function published() { + try { + return JSON.parse(readFileSync(DESCRIPTOR, "utf8")).runtime_id === RUNTIME_ID; + } catch { + return false; + } +} + +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 + // itself, however long it pauses in between. + try { + mkdirSync(CLIENTS, { recursive: true, mode: 0o700 }); + // 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 + // 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."); + } +} + +export default function (pi) { + if (supervisor.timer === undefined) { + supervisor.timer = setInterval(beat, ${TERMINAL_HEARTBEAT_MS}); + supervisor.timer.unref?.(); + 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; + beat(); + }); + pi.on("session_shutdown", () => { + supervisor.context = undefined; + }); +} +`; +} + +/** 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)}](` + + // 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, + "", + `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 }); + // writeFile applies the mode only to a new file; a kept directory can hold an older one. + await chmod(path, 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; + /** 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. */ +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 readonly server: PiTerminalEnvironmentServer; + private withdrawn = false; + + 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; + } + + /** + * 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, 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( + "pi_terminal_unsupported_platform", + "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"); + 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, + helper: TERMINAL_LAUNCH_HELPER, + cli, + agentDir: plan.agentDir, + sessionDir, + workspace: plan.workspace, + descriptor: descriptorPath, + runtimeId, + 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, + env_socket: server.socketPath, + }; + return new PiTerminal(launcher, descriptorPath, descriptor, clients, server); + } + + /** 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`; + 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); + } + } + + /** + * 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; + 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(); + // 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. + 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; + } +} + +/** + * 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 { + // 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); + // 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) { + 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 couldn't be verified and signalled, or still ran after SIGKILL; its registration is kept", + { 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, + * 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 []; + 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); + 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. + 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. */ +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)); +} + +/** 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 + * Linux, otherwise `ps:` from ps, and undefined when neither is available. The + * generated supervisor extension records the same value for itself. + */ +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]; + if (start !== undefined && /^\d+$/u.test(start)) return `proc:${start}`; + } catch { + // No /proc: ask ps. + } + try { + // 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 { + // No ps, or no such process. + } + return undefined; +} + +/** + * 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[]; + try { + entries = await readdir(clients); + } 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: 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. 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; + try { + recorded = (await readFile(path, "utf8")).trim(); + } 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 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. + if (current === recorded) live.push({ pid, identity: recorded }); + else await rm(path, { force: true }); + continue; + } + // 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 }; +} + +/** + * 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 { + // 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 }); + } + } 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). + */ +async function signal(terminals: readonly RegisteredTerminal[], name: NodeJS.Signals, + 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 + // 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) { + 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); + continue; + } + if (current !== identity) continue; + } + try { + 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. + if (options.groupOnly === true || !running) continue; + try { + process.kill(pid, name); + } 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; +} + +/** 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 instanceof LifecycleError + ? error + : new LifecycleError("pi_interface_cleanup_failed", "Pi's terminal interface could not be withdrawn", { + 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 { + await this.inner.stop(); + } catch (error) { + failure = failure === undefined + ? error + : new AggregateError([failure, error], "Pi terminal interface and session cleanup failed"); + } + await removeTerminalMcpConfiguration(this.inner.configuration); + if (failure !== undefined) throw failure; + } +} + +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. + */ +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 (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, + 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, 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) { + return this.sdk.create(input); + } + let handle: PiSessionHandle; + try { + 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. + await rm(join(agentDirectory(runtimeDirectory(input)), "mcp.json"), { force: true }).catch(() => undefined); + throw error; + } + 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", + ); + } + const cli = await resolvePiCli(); + try { + interfaceHandle = await PiTerminal.prepare(handle.configuration, handle.configuration.runtimeDir, + 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; + 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(() => { + 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"); + }); + await removeTerminalMcpConfiguration(handle.configuration); + 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..06f83754f 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,113 @@ test( } }, ); + +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 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 }, + }, + }, + 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, 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 1726e6201..03942a0fb 100644 --- a/adapters/typescript/pi/test/runtime.test.mjs +++ b/adapters/typescript/pi/test/runtime.test.mjs @@ -557,3 +557,62 @@ 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 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() { + 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"); + } + 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", + ); + 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..7b6c1d404 --- /dev/null +++ b/adapters/typescript/pi/test/terminal.test.mjs @@ -0,0 +1,2106 @@ +// 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 { existsSync } from "node:fs"; +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"; +import { PiNativeOnlySessionFactory } from "../dist/native-only.js"; +import { + launcherScript, + terminalArguments, + terminalEnabled, + processIdentity, + replaceIdentityLookupForTesting, + supervisorExtension, + withTerminalInterface, +} from "../dist/terminal.js"; +import { runtimeDirectory } from "../dist/agent-directory.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"; + +/** 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"; +/** 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."; + +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: options.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: 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", + helper: "/opt/fabric/terminal-launch.js", + cli: "/opt/pi/cli.js", + agentDir: "/a'b", + 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' 'rt-launcher' '\/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 () => assert.fail("the SDK factory ran") }, + { create: async () => handle }); + await assert.rejects( + 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", { 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", "state", "nvidia.fabric.pi", "terminal-test"); + let session; + try { + 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")); + // 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 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 { 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(); + 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, 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")); + assert.deepEqual(published, { + version: 1, + mode: "launcher", + launcher: "terminal", + runtime_id: "rt-terminal", + workspace, + 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. + 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"); + // 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"]); + // 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, 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)]); + // 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(); + 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, recordStart = false, identity = "" }) { + const source = ` + import { spawn } from "node:child_process"; + import { mkdirSync, writeFileSync } from "node:fs"; + import { join } from "node:path"; + 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 identity. + const identity = record === "record" + ? 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" : identity, + new URL("../dist/terminal.js", import.meta.url).href, + ], { + 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; + } +} + +/** 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; + 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/); + assert.equal(await processIdentity(process.pid), identity); +}); + +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("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("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", 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(); + } +}); + +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 = [], runtimeId = "rt-helper") { + const child = spawn(process.execPath, [ + "--disable-warning=ExperimentalWarning", LAUNCH_HELPER, descriptor, runtimeId, 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({ 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; + 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({ 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); + 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("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", 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, 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(); + 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"], "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)); + 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(); + 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, 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)); + + 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; + 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 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, 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, 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, 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 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, 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 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, 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 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, 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(); + 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, 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 }); + await session.stop(); + session = undefined; + await new Promise((resolve) => setTimeout(resolve, 500)); + 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(); + 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(); + 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, 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(await terminated(terminal.tool), true); + } 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(); + 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, TERMINAL)); + terminal = await fakeTerminal(clients, { ignoreSigterm: false, recordStart: true }); + + 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, TERMINAL)); + terminal = await fakeTerminal(clients, { ignoreSigterm: true, recordStart: 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; + 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 {} + } + await session?.stop(); + server.closeAllConnections(); + server.close(); + await rm(workspace, { recursive: true, force: true }); + } +}); + +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-"))); + 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); + // 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); + 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("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 }); + } +}); + +/** 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: [], + // 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: { + 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 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 { + // 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\}/); + 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 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-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 = {}; + 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 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-"))); + 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, 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, 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("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", () => { + const script = launcherScript({ + 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", 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=")); +}); + +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 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", 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 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", 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 }); + } +}); + +/** 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 { + 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" }); + 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"); + 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, 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, { + version: 1, + mode: "launcher", + launcher: "terminal", + runtime_id: "rt-one", + workspace, + 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(); + session = undefined; + assert.equal(await exists(join(workspace, "artifacts", ".fabric", "pi", "runtimes")), false); + + 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); + // 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, 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, 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 }); + // 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"), ""); + + // 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/); + // 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(); + 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, 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, 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 { + // 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, 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 sink warning. + const quiet = await start([own]); + assert.doesNotMatch(quiet.stderr, /nemo-fabric-stream|ATOF/); + } finally { + 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, 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, 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 }); + } +}); 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..a27575c6a 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,16 @@ const expectedByPackage = { "dist/relay.js", "dist/runtime.d.ts", "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", "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..8f3aee9ac --- /dev/null +++ b/examples/interfaces/pi/pi_tui.py @@ -0,0 +1,218 @@ +# 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": { + # A runtime that offers the terminal interface runs no SDK session. + "sdk": {"enabled": False}, + "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( + # 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( + "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( + "--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..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 @@ -3449,7 +3449,8 @@ "tools.blocked", "skills", "mcp", - "mcp.tool_filters" + "mcp.tool_filters", + "runtime.keep_state" ], "system_instruction_modes": [ "replace" @@ -3643,6 +3644,93 @@ }, "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" + ] + } + }, + { + "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": { "extensions": { "items": { @@ -3671,10 +3759,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. 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, + "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, which the terminal interface requires; SDK invocation then fails explicitly.", + "type": "boolean" + } + }, + "type": "object" } }, "type": "object" @@ -3718,7 +3837,7 @@ "name": "nemo-fabric-adapters-pi", "version": "0.8.0" }, - "sha256": "1d3f4b6933689530782ba0ebd019ca9af3476a8f9b7d5b955783d0a59b743283", + "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 4eea74aec..41722c282 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) @@ -274,3 +285,55 @@ 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( + {"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({"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( + {"sdk": {"enabled": False}, "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)