Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
spawn a restricted public-review TUI as a direct PTY, not inside a login shell (#6159)
[._.]/ Adam Eivya6e02aa8b145
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex c86d009d5d..0cc5082656 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -93,10 +93,14 @@ const PROVIDER_SIGNAL_POLL_MS = 5000;// The filename is per agent instance — see doneSentinelName in ../lib/agentSentinel.js./**- * Thin wrapper around `shellService.createShellSession` for the agent TUI- * path. Centralizes the agent-side defaults (kind, label, initialCommand)- * and pairs the returned session id with its underlying pty process so- * callers don't have to make a second `getSessionProcess` call inline.+ * Open the agent TUI's PTY and pair the returned session id with its underlying+ * pty process, so callers don't have to make a second `getSessionProcess` call+ * inline. Centralizes the agent-side defaults (kind, label, initialCommand).+ *+ * Three shapes, in the order they are checked: the CoS runner's own PTY; a+ * DIRECT PTY running the provider binary itself (public-content stages only —+ * see the `restricted` branch); and otherwise an interactive login shell with+ * the CLI command typed into it.** Returns `{ sessionId, ptyProcess, pid }`. When the shell service fails* to create the session, `sessionId` is null and the caller is expected@@ -121,19 +125,15 @@ export async function createAgentTuiSession({// A public-content stage's PTY starts from the SAME environment its headless// sibling gets — no forge credential, no SSH config, no cloud key, no// arbitrary provider var — so it calls the very builder the headless path- // uses rather than re-deriving the profile→allowlist mapping here. The result- // is a COMPLETE environment, not the delta `createShellSession` normally- // takes: the shell service unions a delta onto `buildSafeEnv(process.env)`,- // which would restore everything the allowlist just withheld, hence- // `envReplace` below.+ // uses rather than re-deriving the profile→allowlist mapping here.//- // KNOWN RESIDUAL (tracked separately, see #6159): this path hosts the CLI inside an- // interactive login shell, so the operator's own rc file runs before the- // provider does and can re-export anything it likes. That is not a hole this- // allowlist can close — closing it means spawning the recipe command as the- // PTY directly, the way the runner's `/spawn-tui` already does. What the- // allowlist DOES close is the server's own process environment, which is- // where a newly-added PortOS secret would otherwise appear for free.+ // The two branches produce DIFFERENT KINDS of value, which is why they route+ // to different spawn entry points below. `buildCliChildEnv` returns a COMPLETE+ // environment, so a restricted stage goes to `spawnCommandSession`, which+ // unions nothing underneath it — and which is also what removes the login+ // shell, so the operator's rc file can no longer run between this allowlist+ // and the provider and re-export whatever it likes (#6159). The ordinary+ // branch is a DELTA: `createShellSession` unions it onto `buildSafeEnv`.const env = restricted? buildCliChildEnv({ before: forgeTokenEnv, provider, model, cwd, guard: true, safetyProfile }): { ...composeProviderEnv({ before: forgeTokenEnv, provider, model }), ...agentGuardEnv() };@@ -174,6 +174,36 @@ export async function createAgentTuiSession({return session;}+ if (restricted) {+ // Launch the vendor recipe AS the PTY — no hosting shell, so no rc file runs+ // between the allowlist above and the provider (#6159). Same shape the+ // runner's `/spawn-tui` uses; `env` is already the COMPLETE environment, and+ // `spawnCommandSession` unions nothing underneath it.+ //+ // The login shell's two handshake affordances go with it. `waitForPromptReady`+ // probed a shell that no longer exists — the CLI is the first thing to run, so+ // there is nothing to wait for; the readiness gate opens here, before the+ // spawn, exactly as the runner branch above opens it, so the TUI's first+ // bracketed-paste/input-ready bytes are not discarded. `exitWithCommand` was+ // emulating "the session ends when the CLI ends", which is now simply true:+ // the PTY's own exit IS the CLI's, carrying its status and any signal+ // straight to `onExit`.+ onInitialCommandSent?.();+ const sessionId = shellService.spawnCommandSession(tuiConfig.command, tuiConfig.args, {+ cwd,+ env,+ kind: 'agent-tui',+ agentId,+ label: `${provider.name} ${agentId}`,+ command: tuiConfig.commandLine,+ onData,+ onExit,+ });+ if (!sessionId) return { sessionId: null, ptyProcess: null, pid: null };+ const ptyProcess = shellService.getSessionProcess(sessionId);+ return { sessionId, ptyProcess, pid: ptyProcess?.pid || null };+ }+// This shell exists only to host the CoS TUI. `exitWithCommand` makes it// follow the TUI's lifetime and preserve the TUI exit status; otherwise the// login shell returns to its prompt when the provider exits and the spawner@@ -210,9 +240,6 @@ export async function createAgentTuiSession({// whose real base env is assembled downstream. Only AI agent sessions get// the shim; the user's own Shell page does not.env,- // …except under a public-content posture, where `env` above is not a delta- // at all but the complete, allowlisted environment (see its construction).- envReplace: restricted,onData,onExit,});@@ -305,7 +332,7 @@ function createPasteRetryController({agentId,sessionId,pid,- useDurableRunner,+ directLaunch,prompt,tuiConfig,mcpBoot,@@ -397,11 +424,12 @@ function createPasteRetryController({// `^[[200~ …` session. If the shell has no live child, the command is gone:// fail loudly with whatever it printed instead of pasting into the shell.//- // Runner mode has no launch shell — the TUI IS the PTY process — so "does- // this pid have a live child?" is the wrong question (claude may have zero- // children at paste time) and a TUI exit kills the PTY, firing onExit. Skip- // the probe there.- if (!useDurableRunner && !(await shellHasLiveChild(pid))) {+ // A direct launch — runner mode, or a public-content stage spawned as its+ // own PTY (#6159) — has no launch shell: the TUI IS the PTY process. "Does+ // this pid have a live child?" is then the wrong question (claude may have+ // zero children at paste time) and a TUI exit kills the PTY, firing onExit.+ // Skip the probe there.+ if (!directLaunch && !(await shellHasLiveChild(pid))) {if (isFinalized()) return; // a real onExit may have finalized during the probe awaitawait finishStartupFailure('tui-exited-early',@@ -622,6 +650,17 @@ export async function spawnTuiAgent({// gets the same allowlisted environment its headless sibling would.safetyProfile = null,}) {+ // Will this run's PTY BE the provider binary, rather than a login shell with+ // the command typed into it? True for the CoS runner's own PTY and for a+ // public-content stage, which drops the shell so the operator's rc file can't+ // run inside its allowlisted environment (#6159). Both cases are settled by+ // createAgentTuiSession — a restricted stage never reaches the runner (it+ // throws) — but the handshake below is wired before the spawn, so the same+ // predicate is resolved here. Two things read it: the input-ready tracker+ // (nothing toggles shell paste-mode off when there is no shell) and the paste+ // liveness guard ("does this pid have a live child?" is meaningless when the+ // pid IS the CLI).+ const directLaunch = useDurableRunner || isPublicReviewRestrictedProfile(safetyProfile);const outputFile = join(agentDir, 'output.txt');// Raw PTY bytes spool to disk continuously rather than accumulate in-memory.// A chatty TUI (token-tick repaints, status lines) emits hundreds of chunks@@ -747,11 +786,11 @@ export async function spawnTuiAgent({// paste into a startup banner, a trust menu, or a returned shell prompt.// agy enables bracketed paste on alt-screen entry, before its composer (and// before its trust gate) exists, so it needs the extra composer-footer gate.- // The durable runner pty.spawns the TUI directly (no launch shell), so the- // tracker must not wait for a shell paste-mode OFF that will never come.+ // A direct launch pty.spawns the TUI itself (no launch shell), so the tracker+ // must not wait for a shell paste-mode OFF that will never come.const inputReady = createInputReadyTracker({...(isAntigravityCommand(tuiConfig.command) ? { readyTextPattern: AGY_INPUT_READY_PATTERN } : {}),- directLaunch: useDurableRunner,+ directLaunch,});let trustAccepted = false;let autoModeDeclined = false;@@ -1398,17 +1437,23 @@ export async function spawnTuiAgent({// record as a completed run. finish() intercepts that case — see its// host-shutdown guard (#3202).const code = typeof exitCode === 'number' ? exitCode : killed ? 130 : 0;- // A signal-terminated shell reports the wait-status exit code — 0 for a+ // A signal-terminated process reports the wait-status exit code — 0 for a// plain SIGTERM/SIGHUP — so `code === 0` alone cannot mean "finished// normally". Treat any signal as an abnormal end. This is the backstop for// the case the host-shutdown guard can't cover: a SIGKILL'd or crashed// portos-server never runs its shutdown handler, so the flag is never set,// yet the agent's PTY still dies with us (#3202).+ //+ // The reading holds for BOTH session shapes. A login shell carried its+ // hosted CLI's status out via the run-then-exit wrapper; a direct PTY+ // (#6159) simply IS the CLI, so the code and signal are the CLI's own. The+ // `shell-*` reason codes are what COMPLETION_REASON_ANALYSES registers, so+ // they stay verbatim — only the prose drops the now-wrong noun.const signaled = !!signal;const outcome = killed- ? { error: 'TUI shell session was killed', reason: 'shell-killed' }+ ? { error: 'TUI session was killed', reason: 'shell-killed' }: signaled- ? { error: `TUI shell session was terminated by signal ${signal} — the run was cut short, not completed`, reason: 'shell-signaled' }+ ? { error: `TUI session was terminated by signal ${signal} — the run was cut short, not completed`, reason: 'shell-signaled' }: { error: null, reason: 'shell-exit' };await finish({ success: code === 0 && !killed && !signaled, exitCode: code, ...outcome });};@@ -1476,7 +1521,13 @@ export async function spawnTuiAgent({// PTY. Distinguish that deterministic configuration failure from a runner// outage/refusal so it is blocked with the existing actionable// command-not-found guidance rather than retried as a transient rejection.- const reason = useDurableRunner && /^Command executable unavailable:/i.test(message)+ //+ // A LOCAL direct PTY has the same deterministic failure but reports it+ // differently: node-pty throws `File not found: <cmd>` rather than opening a+ // PTY (#6159). The login-shell path never threw here — its shell opened+ // fine and PRINTED "command not found", which handleData classifies — so+ // without this the same misconfiguration would be filed as a host problem.+ const reason = /^Command executable unavailable:/i.test(message) || /file not found/i.test(message)? 'command-not-found': useDurableRunner ? 'spawn-rejected' : 'spawn-error';if (useDurableRunner) {@@ -1614,7 +1665,7 @@ export async function spawnTuiAgent({agentId,sessionId,pid,- useDurableRunner,+ directLaunch,prompt,tuiConfig,mcpBoot,diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 99785a438d..118fcf64be 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -6,6 +6,7 @@ import { join } from 'path';vi.mock('./shell.js', () => ({createShellSession: vi.fn(),+ spawnCommandSession: vi.fn(),writeToSession: vi.fn(),pasteToSession: vi.fn(),killSession: vi.fn(),@@ -692,8 +693,23 @@ describe('spawnTuiAgent runtime', () => {return SESSION_ID;});+ // The direct-PTY path a public-content stage takes (#6159). Real shell.js+ // has no readiness probe there — the CLI *is* the PTY — so+ // createAgentTuiSession opens the paste gate itself before the spawn; the+ // mock therefore does NOT invoke onInitialCommandSent.+ vi.mocked(shellService.spawnCommandSession).mockImplementation((_command, _args, opts) => {+ capturedOnData = opts.onData;+ capturedOnExit = opts.onExit;+ return SESSION_ID;+ });+vi.mocked(shellService.getSessionProcess).mockReturnValue(null);vi.mocked(shellService.getSession).mockReturnValue({ id: SESSION_ID });+ // Restore the liveness probe's "assume alive" default. `clearAllMocks` clears+ // call history but KEEPS implementations, so a test that makes the probe+ // report "no live child" would otherwise leak that verdict into whichever+ // test runs next and strand it at the paste gate.+ vi.mocked(execFile).mockImplementation((_file, _args, _opts, cb) => cb(new Error('not mocked')));vi.mocked(spawnTuiSessionViaRunner).mockImplementation(async (options) => {capturedOnData = options.onData;capturedOnExit = options.onExit;@@ -780,7 +796,11 @@ describe('spawnTuiAgent runtime', () => {// environment its headless sibling would; a TUI Stage 3 running with the// server's own inherited environment would be a real regression, not a// cosmetic one — the whole posture assumes no forge credential is reachable.- it('hands an actions-posture PTY the allowlisted env verbatim instead of unioning it onto the shell base', async () => {+ //+ // #6159 closed the residual that allowlist could not: the stage no longer runs+ // inside a login shell at all, so the operator's rc file never executes between+ // the allowlist and the provider.+ it('spawns an actions-posture stage as its own PTY with the allowlisted env, never inside a login shell', async () => {let resolveComplete;const completeDone = new Promise((r) => { resolveComplete = r; });vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });@@ -789,13 +809,17 @@ describe('spawnTuiAgent runtime', () => {runSpawn({provider: { id: 'claude-tui', name: 'Local Claude TUI', type: 'tui', command: 'claude', envVars: {} },safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,+ tuiConfig: { command: 'claude', args: ['--permission-mode', 'plan'], commandLine: 'claude --permission-mode plan', promptDelayMs: 100 },});await flushMicrotasks();- const opts = vi.mocked(shellService.createShellSession).mock.calls[0][1];- // envReplace is what stops shell.js unioning buildSafeEnv(process.env) back- // underneath the allowlist we just applied.- expect(opts.envReplace).toBe(true);+ // No login shell is created at all — that is what makes an rc-file export+ // unreachable, and no env assertion on its own can prove it.+ expect(shellService.createShellSession).not.toHaveBeenCalled();+ const [command, args, opts] = vi.mocked(shellService.spawnCommandSession).mock.calls[0];+ // The PTY's process is the provider binary from the vendor recipe.+ expect(command).toBe('claude');+ expect(args).toEqual(['--permission-mode', 'plan']);expect(opts.env.PORTOS_TEST_6062_SECRET).toBeUndefined();expect(opts.env.GH_TOKEN).toBeUndefined();// …while the variables the stage legitimately needs survive.@@ -817,15 +841,54 @@ describe('spawnTuiAgent runtime', () => {runSpawn();await flushMicrotasks();- // `env` stays a DELTA here — the regression this guards is flipping every- // agent session onto the public-review allowlist, which would strip the- // toolchain vars an ordinary coding agent needs.- expect(vi.mocked(shellService.createShellSession).mock.calls[0][1].envReplace).toBeFalsy();+ // The operator's rc file is a FEATURE for an ordinary coding agent — it is+ // where their toolchain (nvm, pyenv, PATH edits) comes from. #6159 removes+ // the hosting shell only for the restricted posture, and `env` stays a+ // DELTA that createShellSession unions onto its own base: the regression+ // this guards is flipping every agent session onto the public-review+ // allowlist, which would strip the toolchain vars a coding agent needs.+ expect(shellService.spawnCommandSession).not.toHaveBeenCalled();+ const opts = vi.mocked(shellService.createShellSession).mock.calls[0][1];+ expect(opts.initialCommand).toBe('codex');+ expect(opts.waitForPromptReady).toBe(true);await capturedOnExit({ exitCode: 0, killed: false });await completeDone;});+ // #6159 — the direct PTY loses both affordances the login shell supplied:+ // shell.js's readiness probe (which fired onInitialCommandSent, opening the+ // paste gate) and the shell's bracketed-paste OFF that the input-ready tracker+ // waited for. It also invalidates the "does this pid have a live child?" guard,+ // because the pid IS the CLI. If any of those were left wired for the shell+ // shape, the prompt would never be delivered — silently, on a live stage.+ it('still delivers the prompt for a direct actions-posture PTY, with no shell probe or paste-mode OFF', async () => {+ // Truthy pid AND a probe that reports no child of it — exactly the state+ // that trips `tui-exited-early` on the login-shell path.+ vi.mocked(shellService.getSessionProcess).mockReturnValue({ pid: 4242 });+ vi.mocked(execFile).mockImplementation((_file, _args, _opts, cb) => cb(null, '1\n1\n999\n'));++ runSpawn({+ provider: { id: 'claude-tui', name: 'Local Claude TUI', type: 'tui', command: 'claude', envVars: {} },+ safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,+ tuiConfig: { command: 'claude', args: [], commandLine: 'claude', promptDelayMs: 100 },+ });+ await flushMicrotasks();++ // The TUI owns the PTY from byte zero: its composer turns bracketed-paste ON+ // with no preceding shell OFF.+ await capturedOnData(Buffer.from('\x1b[?2004hClaude Code v2.1.186\n'));+ await flushMicrotasks();+ await vi.advanceTimersByTimeAsync(2000);+ await flushMicrotasks();++ const pasteWrites = vi.mocked(shellService.writeToSession).mock.calls+ .filter(([, data]) => typeof data === 'string' && data.includes('\x1b[200~'));+ expect(pasteWrites).toHaveLength(1);++ await capturedOnExit({ exitCode: 0, killed: false });+ });+it('refuses to route a public-content stage through the shared CoS runner', async () => {// The runner builds its own child env from ITS ambient environment// (`/spawn-tui` → `buildCliChildEnv` with no profile), so a restricted stage@@ -840,6 +903,7 @@ describe('spawnTuiAgent runtime', () => {expect(spawnTuiSessionViaRunner).not.toHaveBeenCalled();expect(shellService.createShellSession).not.toHaveBeenCalled();+ expect(shellService.spawnCommandSession).not.toHaveBeenCalled();await expect(spawned).resolves.toBeNull();});diff --git a/server/services/shell.js b/server/services/shell.jsindex c625fa1bbd..52c9563477 100644--- a/server/services/shell.js+++ b/server/services/shell.js@@ -1,5 +1,6 @@import * as pty from 'node-pty';import os from 'os';+import { basename } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import { withSpawnCwdEnv } from '../lib/spawnCwd.js';import { scheduleSubmitEnters, SUBMIT_KEY } from '../lib/tuiHandshake.js';@@ -7,6 +8,7 @@ import { buildCdCommand } from '../lib/shellCd.js';import { resolveInteractiveShell } from '../lib/interactiveShellResolver.js';import { buildRunThenExitCommand } from '../lib/shellExit.js';import { buildReadinessProbe } from '../lib/shellReadinessProbe.js';+import { prepareCliSpawn } from '../lib/bufferedSpawn.js';// Store active shell sessions (persist across socket reconnects)const shellSessions = new Map();@@ -127,58 +129,30 @@ function getDefaultShell() {}/**- * Create a new shell session+ * True when the service already holds its ceiling of PTYs it spawned itself.+ *+ * Only sessions this service spawned count. External views (one-shot TUI runs+ * registered via registerExternalSession) are governed by their own runner and+ * must not consume a slot.*/-export function createShellSession(socket, options = {}) {- // Only user-spawned interactive shells count toward the cap. External views- // (one-shot TUI runs registered via registerExternalSession) are governed by- // their own runner and must not consume a shell slot.- const interactiveCount = [...shellSessions.values()].filter(s => !s.external).length;- if (interactiveCount >= MAX_TOTAL_SESSIONS) {- console.warn(`🐚 Max total sessions reached (${MAX_TOTAL_SESSIONS})`);- socket?.emit?.('shell:error', { error: `Max ${MAX_TOTAL_SESSIONS} shell sessions. Kill an existing session first.` });- return null;- }-- const sessionId = uuidv4();- const shell = options.shell || getDefaultShell();- const cwd = options.cwd || os.homedir();- const cols = options.cols || 80;- const rows = options.rows || 24;-- console.log(`🐚 Creating shell session ${sessionId.slice(0, 8)} (${shell})`);-- let ptyProcess;- try {- ptyProcess = pty.spawn(shell, [], {- name: 'xterm-256color',- cols,- rows,- cwd,- // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). An interactive- // login shell rewrites PWD itself at startup, but a non-login shell may- // not, and an agent-TUI session injects its CLI command into this shell.- env: withSpawnCwdEnv({- // `envReplace` callers own the WHOLE environment: buildSafeEnv is a- // union, so a caller that has already narrowed its env to a strict- // allowlist (a public-content review stage — see- // agentTuiSpawning.js#createAgentTuiSession) would have every inherited- // variable it just withheld added straight back underneath it.- ...(options.envReplace ? {} : buildSafeEnv()), // filters process.env to prevent leaking inherited secrets (e.g. shell-inherited API keys)- // options.env is the caller's explicit opt-in env (e.g. TUI provider API keys for codex/claude).- // Callers are responsible for not passing vars they don't want visible inside attachable shells.- // Single-user/single-instance deployment (Tailscale-only) makes this acceptable.- ...(options.env || {}),- TERM: 'xterm-256color',- COLORTERM: 'truecolor'- }, cwd)- });- } catch (err) {- console.error(`❌ Failed to spawn PTY: ${err.message}`);- socket?.emit?.('shell:error', { error: `Failed to spawn shell: ${err.message}` });- return null;- }+function atSessionCap() {+ return [...shellSessions.values()].filter(s => !s.external).length >= MAX_TOTAL_SESSIONS;+}+/**+ * Register a PTY this service just spawned and wire its output/exit handling.+ *+ * Shared by the two spawn entry points — `createShellSession` (a login shell)+ * and `spawnCommandSession` (the command itself as the PTY) — so both produce+ * the same registry entry, the same 50KB re-attach ring buffer, and the same+ * hook semantics. Only the process differs.+ *+ * `shell` is the hosting shell binary, or `null` when the PTY *is* the launched+ * command. Everything that injects a command line into a session reads it (see+ * `changeSessionDirectory`), so a null value is the load-bearing signal that+ * there is no shell to type at.+ */+function adoptOwnedPty(sessionId, ptyProcess, options = {}) {// Buffer recent output for re-attach (last 50KB)const outputBuffer = [];let bufferSize = 0;@@ -189,11 +163,12 @@ export function createShellSession(socket, options = {}) {_id: sessionId.slice(0, 8),hookQueue: Promise.resolve(),pty: ptyProcess,- socket,- cwd,+ socket: options.socket || null,+ cwd: options.cwd || null,// The spawned shell binary — kept so cd-style commands injected later can be// written in the dialect this session actually speaks (see changeSessionDirectory).- shell,+ // Null for a direct command session: there is no shell reading those lines.+ shell: options.shell || null,createdAt: Date.now(),label: options.label || null,kind: options.kind || 'shell',@@ -235,6 +210,57 @@ export function createShellSession(socket, options = {}) {if (session) runHook('onExit', session, session.onExit, { exitCode, signal: signal ?? null });broadcastSessionList();});+}++/**+ * Create a new shell session+ */+export function createShellSession(socket, options = {}) {+ if (atSessionCap()) {+ console.warn(`🐚 Max total sessions reached (${MAX_TOTAL_SESSIONS})`);+ socket?.emit?.('shell:error', { error: `Max ${MAX_TOTAL_SESSIONS} shell sessions. Kill an existing session first.` });+ return null;+ }++ const sessionId = uuidv4();+ const shell = options.shell || getDefaultShell();+ const cwd = options.cwd || os.homedir();+ const cols = options.cols || 80;+ const rows = options.rows || 24;++ console.log(`🐚 Creating shell session ${sessionId.slice(0, 8)} (${shell})`);++ let ptyProcess;+ try {+ ptyProcess = pty.spawn(shell, [], {+ name: 'xterm-256color',+ cols,+ rows,+ cwd,+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). An interactive+ // login shell rewrites PWD itself at startup, but a non-login shell may+ // not, and an agent-TUI session injects its CLI command into this shell.+ env: withSpawnCwdEnv({+ // `options.env` is a DELTA here — this base is always unioned underneath+ // it. A caller that has already narrowed its environment to a strict+ // allowlist must use `spawnCommandSession` instead, which unions nothing+ // (and gets no rc file either — see its docstring).+ ...buildSafeEnv(), // filters process.env to prevent leaking inherited secrets (e.g. shell-inherited API keys)+ // options.env is the caller's explicit opt-in env (e.g. TUI provider API keys for codex/claude).+ // Callers are responsible for not passing vars they don't want visible inside attachable shells.+ // Single-user/single-instance deployment (Tailscale-only) makes this acceptable.+ ...(options.env || {}),+ TERM: 'xterm-256color',+ COLORTERM: 'truecolor'+ }, cwd)+ });+ } catch (err) {+ console.error(`❌ Failed to spawn PTY: ${err.message}`);+ socket?.emit?.('shell:error', { error: `Failed to spawn shell: ${err.message}` });+ return null;+ }++ adoptOwnedPty(sessionId, ptyProcess, { ...options, socket, cwd, shell });// Starting a fresh shell means the user moved on from whatever they were// viewing — release any TUI-run views they held so those runs resume normal@@ -345,6 +371,72 @@ export function createShellSession(socket, options = {}) {return sessionId;}+/**+ * Spawn `command` AS the PTY — no hosting shell — and register it as an+ * ordinary attachable session.+ *+ * Why this exists next to `createShellSession`: that function's PTY is an+ * interactive login shell into which a command is later typed, so the+ * operator's own rc file (`.zshrc`, `.bash_profile`, …) runs BEFORE the command+ * and can re-export anything it likes. For a public-content review stage whose+ * whole posture is a strict environment allowlist, that rc file is a hole no+ * allowlist can close (#6159). Here the launched binary is the PTY's own+ * process, so `env` is exactly what the child gets.+ *+ * `env` is the COMPLETE environment, not a delta: nothing is unioned underneath+ * it (`buildSafeEnv` is deliberately not consulted), because the callers that+ * need this have already narrowed the environment themselves.+ *+ * Ordinary agent TUI sessions keep the login shell — the operator's rc file is+ * a feature there, not a leak — so this is not a drop-in replacement for+ * `createShellSession`.+ *+ * Unlike `createShellSession` this THROWS when the PTY will not open (node-pty+ * reports a missing executable that way). The caller is a spawner that already+ * classifies its own startup failures, and swallowing the message would cost it+ * the only evidence of what went wrong.+ *+ * @param {string} command - the binary to run (bare name or path)+ * @param {string[]} [args]+ * @param {object} [options] - { cwd, env, cols, rows, label, kind, agentId, command, onData, onExit }+ * @returns {string|null} sessionId, or null when the session cap is reached+ */+export function spawnCommandSession(command, args = [], options = {}) {+ if (atSessionCap()) {+ console.warn(`🐚 Max total sessions reached (${MAX_TOTAL_SESSIONS})`);+ return null;+ }++ const sessionId = uuidv4();+ const cwd = options.cwd || os.homedir();+ const env = withSpawnCwdEnv({+ // No buildSafeEnv union — see the docstring. The caller owns this env whole.+ ...(options.env || {}),+ TERM: 'xterm-256color',+ COLORTERM: 'truecolor'+ }, cwd);+ // Windows resolves a bare name to its `.cmd`/`.bat` shim and must launch it+ // through cmd.exe (never the user's shell — that wrapper runs no profile);+ // on POSIX both steps are no-ops and the binary is spawned directly. Same+ // helper the CoS runner's /spawn-tui uses, so the two direct-PTY paths can't+ // drift on escaping.+ const { command: ptyCommand, args: ptyArgs } = prepareCliSpawn(command, args, env);++ // basename only: a resolved path can embed the local account name.+ console.log(`🐚 Creating command session ${sessionId.slice(0, 8)} (${basename(command)})`);+ const ptyProcess = pty.spawn(ptyCommand, ptyArgs, {+ name: 'xterm-256color',+ cols: options.cols || 80,+ rows: options.rows || 24,+ cwd,+ env+ });++ adoptOwnedPty(sessionId, ptyProcess, { ...options, socket: null, cwd, shell: null });+ broadcastSessionList();+ return sessionId;+}+/*** A socket can stay bound to multiple sessions (the registry allows it), but a* user views one at a time. `isExternalSessionAttached` keys off socket binding,@@ -615,17 +707,18 @@ export function submitToSession(sessionId, line) {** @param {string} sessionId* @param {string} dirPath- * @returns {boolean} false when the session is unknown or is an external TUI run+ * @returns {boolean} false when the session is unknown, or has no hosting shell*/export function changeSessionDirectory(sessionId, dirPath) {const session = shellSessions.get(sessionId);if (!session) return false;- // An external (TUI-run) session has no shell reading that line: the bytes land in+ // A session with no hosting shell — an external (TUI-run) view, or a direct+ // `spawnCommandSession` PTY — has nothing reading that line: the bytes land in// the agent as typed text and the trailing Enter posts them as a message. Refuse// rather than type into someone else's run — socket.js turns this into an error the// Shell page shows. Its `cwd` also stays pinned to the repo the RUN was spawned in,// which is what workspaceContext groups runs by.- if (session.external) return false;+ if (session.external || !session.shell) return false;if (!submitToSession(sessionId, buildCdCommand(dirPath, session.shell))) return false;// Track the cd optimistically so the Shell tab label and the Workspace Contexts// widget follow the session instead of staying pinned to its spawn directory.diff --git a/server/services/shell.test.js b/server/services/shell.test.jsindex 991c3b412e..0804c24f44 100644--- a/server/services/shell.test.js+++ b/server/services/shell.test.js@@ -544,6 +544,95 @@ describe('changeSessionDirectory', () => {});});+describe('spawnCommandSession', () => {+ it('spawns the command itself as the PTY, so no rc file runs before it (#6159)', () => {+ // The whole point of this entry point: a public-content review stage's+ // environment is an allowlist, and an interactive login shell would run the+ // operator's `.zshrc` between that allowlist and the provider. Asserting+ // WHICH process the PTY is, is what proves no rc file can execute.+ const id = shell.spawnCommandSession('claude', ['--permission-mode', 'plan'], {+ cwd: '/tmp/ws',+ env: { PATH: '/usr/bin', HOME: '/home/example' },+ kind: 'agent-tui',+ agentId: 'agent-1',+ });++ expect(typeof id).toBe('string');+ const [spawnedCommand, spawnedArgs] = vi.mocked(defaultSpawn).mock.calls[0];+ expect(spawnedCommand).toBe('claude');+ expect(spawnedArgs).toEqual(['--permission-mode', 'plan']);+ // No shell binary anywhere in the launch, and no shell recorded on the+ // session (which is what `changeSessionDirectory` reads).+ expect(spawnedCommand).not.toMatch(/sh$|zsh$|bash$|cmd\.exe$/i);+ expect(shell.getSession(id).shell).toBeNull();+ });++ it('hands the child EXACTLY the caller env — buildSafeEnv is not unioned underneath', () => {+ // createShellSession unions buildSafeEnv(process.env) under its delta. Doing+ // that here would restore every inherited variable the caller's allowlist+ // just withheld, which is the regression this guards.+ process.env.PORTOS_TEST_6159_SECRET = 'must-not-reach-the-child';+ try {+ shell.spawnCommandSession('claude', [], {+ cwd: '/tmp/ws',+ env: { PATH: '/usr/bin', HOME: '/home/example' },+ });+ const { env } = vi.mocked(defaultSpawn).mock.calls[0][2];+ expect(env.PORTOS_TEST_6159_SECRET).toBeUndefined();+ expect(env.PATH).toBe('/usr/bin');+ // PWD is pinned to the spawn cwd for the CLIs that read it (#3193).+ expect(env.PWD).toBe('/tmp/ws');+ expect(env.TERM).toBe('xterm-256color');+ } finally {+ delete process.env.PORTOS_TEST_6159_SECRET;+ }+ });++ it('registers an attachable session whose onData/onExit hooks fire like a shell session’s', () => {+ const onData = vi.fn();+ const onExit = vi.fn();+ const observer = makeSocket('obs-direct');+ const id = shell.spawnCommandSession('claude', [], {+ cwd: '/tmp/ws',+ env: { PATH: '/usr/bin' },+ kind: 'agent-tui',+ agentId: 'agent-1',+ label: 'Local Claude TUI agent-1',+ command: 'claude',+ onData,+ onExit,+ });+ shell.attachSession(id, observer);++ ptyInstances[0].emitData('hello');+ expect(observer.emit).toHaveBeenCalledWith('shell:output', { sessionId: id, data: 'hello' });++ // The CLI's own exit IS the session's exit now — code and signal reach the+ // hook unchanged, which is what handleExit's success reading depends on.+ ptyInstances[0].emitExit({ exitCode: 3, signal: null });+ return flushMicrotasks().then(() => {+ expect(onData).toHaveBeenCalledWith('hello');+ expect(onExit).toHaveBeenCalledWith({ exitCode: 3, signal: null });+ expect(shell.getSession(id)).toBeNull();+ });+ });++ it('refuses a cd rather than typing it into the agent', () => {+ // Same reasoning as an external TUI run: there is no shell reading that line.+ const id = shell.spawnCommandSession('claude', [], { cwd: '/tmp/ws', env: { PATH: '/usr/bin' } });+ expect(shell.changeSessionDirectory(id, '/tmp/other')).toBe(false);+ expect(ptyInstances[0].write).not.toHaveBeenCalled();+ });++ it('propagates a PTY that will not open instead of collapsing it to null', () => {+ // node-pty reports a missing executable by throwing; the message is the only+ // evidence the spawner has for classifying it as command-not-found.+ spawnImpl = () => { throw new Error('File not found: claude'); };+ expect(() => shell.spawnCommandSession('claude', [], { cwd: '/tmp/ws', env: {} }))+ .toThrow(/File not found/);+ });+});+describe('initialCommand + exitWithCommand', () => {it('wraps the command so the shell exits with it, in that shell\'s dialect', () => {// The wrapper is rendered here rather than by the caller because only this