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
address self-review: resolve the executable in the launcher, name the launch shape once
[._.]/ Adam Eivye99be3745651
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.jsindex bef09cd3b6..99cabd0ba8 100644--- a/server/services/agentErrorAnalysis.js+++ b/server/services/agentErrorAnalysis.js@@ -962,7 +962,7 @@ export const COMPLETION_REASON_ANALYSES = {actionable: true,escalation: 'Confirm the required CLI/tool is installed and on PATH for the agent user (or fix the command), then approve the retry.',message: 'Failed to start the agent session',- suggestedFix: 'The shell/PTY session could not be created. Check system resources and the provider command configuration.'+ suggestedFix: 'The PTY session could not be created. Check system resources, whether too many sessions are already open, and the provider command configuration.'},// The runner refused the spawn outright — a command missing from its// allowlist, malformed cliArgs, or the runner simply unreachable. No childdiff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 0cc5082656..89dd989e4c 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -66,6 +66,7 @@ import {extractVerifiablePromptPrefix,isPasteConfirmed,SUBMIT_KEY,+ detectMissingTuiBinary,} from '../lib/tuiHandshake.js';import { buildVendorSpawnConfig, injectTuiModelAndEffort, supportsTuiPublicReviewPosture } from '../lib/providerVendors.js';import { isPublicReviewRestrictedProfile, publicReviewPostureForProfile } from '../lib/agentExecutionProfiles.js';@@ -92,15 +93,38 @@ const PROVIDER_SIGNAL_POLL_MS = 5000;// waiting for a shell exit or repeatedly touching the filesystem.// The filename is per agent instance — see doneSentinelName in ../lib/agentSentinel.js.+/**+ * What kind of PTY a TUI run gets. Resolved ONCE per run and threaded, rather+ * than re-derived wherever it matters: two consumers wire the prompt handshake+ * BEFORE the spawn happens, and a predicate that silently disagreed with the+ * branch actually taken fails by never delivering the prompt — no error, on a+ * live run.+ *+ * 'runner' — the CoS Runner owns the PTY, in another process.+ * 'direct' — this process pty.spawns the provider binary itself.+ * 'login-shell' — an interactive login shell with the CLI typed into it.+ *+ * A public-content stage is `direct` because a login shell would run the+ * operator's rc file inside its allowlisted environment (#6159). It is never+ * `runner`: the runner builds its own child env, which would drop that+ * allowlist, so `agentLifecycle.js` forces those stages direct-only and+ * `createAgentTuiSession` fails closed if one arrives anyway.+ *+ * This is a separate axis from `isPublicReviewRestrictedProfile` itself, which+ * answers a different question (is the env COMPLETE or a delta?) — the runner+ * case is the proof they are not the same axis.+ */+export function resolveTuiLaunchShape({ useDurableRunner = false, safetyProfile = null } = {}) {+ if (useDurableRunner) return 'runner';+ return isPublicReviewRestrictedProfile(safetyProfile) ? 'direct' : 'login-shell';+}+/*** 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.+ * Which of the three PTY shapes it opens is `resolveTuiLaunchShape`'s call.** Returns `{ sessionId, ptyProcess, pid }`. When the shell service fails* to create the session, `sessionId` is null and the caller is expected@@ -137,7 +161,19 @@ export async function createAgentTuiSession({const env = restricted? buildCliChildEnv({ before: forgeTokenEnv, provider, model, cwd, guard: true, safetyProfile }): { ...composeProviderEnv({ before: forgeTokenEnv, provider, model }), ...agentGuardEnv() };- if (useDurableRunner) {+ // How this session identifies itself in the Shell UI and the session registry.+ // Identical for all three spawn shapes below — an attached human sees the same+ // tab whichever one opened the PTY.+ const sessionOptions = {+ cwd,+ kind: 'agent-tui',+ agentId,+ label: `${provider.name} ${agentId}`,+ command: tuiConfig.commandLine,+ };+ const launchShape = resolveTuiLaunchShape({ useDurableRunner, safetyProfile });+ let sessionId;+ if (launchShape === 'runner') {// The CoS runner is a shared long-lived process and builds its own child// env from ITS ambient environment (`/spawn-tui` → `buildCliChildEnv`// without a profile), so a public-content stage routed through it would@@ -164,86 +200,71 @@ export async function createAgentTuiSession({onData,onExit,});- shellService.registerExternalSession(session.sessionId, session.ptyProcess, {- cwd,- kind: 'agent-tui',- agentId,- label: `${provider.name} ${agentId}`,- command: tuiConfig.commandLine,- });+ shellService.registerExternalSession(session.sessionId, session.ptyProcess, sessionOptions);+ // The runner owns this PTY, so it already returns the pty/pid pair the tail+ // below would otherwise have to look up locally.return session;}- if (restricted) {+ if (launchShape === 'direct') {// 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.+ // between the allowlist above and the provider (#6159). `env` is already the+ // COMPLETE environment, which is what `spawnCommandSession` takes.//- // 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`.+ // `spawnCommandSession` resolves the executable before it spawns and throws+ // `Command executable unavailable: …` when it cannot — which the caller's+ // catch maps to `command-not-found`. That pre-flight has to live in the+ // launcher: a PTY has no shell to print "command not found", so handleData's+ // output-driven probe can never fire on this path.+ //+ // No shell readiness probe fires `onInitialCommandSent` here, so open the+ // paste gate before the spawn — exactly as the runner branch above does —+ // or the TUI's first bracketed-paste/input-ready bytes are discarded.onInitialCommandSent?.();- const sessionId = shellService.spawnCommandSession(tuiConfig.command, tuiConfig.args, {- cwd,+ sessionId = shellService.spawnCommandSession(tuiConfig.command, tuiConfig.args, {+ ...sessionOptions,+ env,+ onData,+ onExit,+ });+ } else {+ // 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+ // cannot observe completion until the wall-clock backstop fires. The wrapper+ // is dialect-specific, so shell.js renders it once it knows which shell the+ // session got (see lib/shellExit.js).+ sessionId = shellService.createShellSession(null, {+ ...sessionOptions,+ initialCommand: tuiConfig.commandLine,+ exitWithCommand: true,+ // Wait until the shell can actually RUN commands before injecting the CLI+ // command — a fixed delay races a heavy interactive shell and the launched+ // TUI can fall straight back to a half-loaded prompt (see shell.js+ // waitForPromptReady, which proves readiness with a round-trip probe).+ waitForPromptReady: true,+ // Fires when the CLI command is actually injected. We start observing+ // claude's input-readiness only after this so the readiness probe's own+ // shell activity can't prematurely open the paste gate.+ onInitialCommandSent,+ // A DELTA, not a full env — buildSafeEnv inside createShellSession supplies+ // the base and shell.js does the PWD pin. composeProviderEnv owns the layer+ // order (forgeTokenEnv before provider.envVars so an explicit provider+ // GH_TOKEN still wins; the OpenCode declared-models map after it, overriding+ // the static config). forgeTokenEnv has to be threaded in explicitly because+ // buildSafeEnv strips GH_TOKEN from the inherited env (resolveForgeTokenEnv).+ //+ // agentGuardEnv() is spread last so the pm2 shim wins over any provider PATH.+ // It reads PATH from process.env rather than the composed env — correct here+ // and NOT what buildCliChildEnv's `guard` does, because this is an overlay+ // whose real base env is assembled downstream. Only AI agent sessions get+ // the shim; the user's own Shell page does not.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- // cannot observe completion until the wall-clock backstop fires. The wrapper- // is dialect-specific, so shell.js renders it once it knows which shell the- // session got (see lib/shellExit.js).- const sessionId = shellService.createShellSession(null, {- cwd,- initialCommand: tuiConfig.commandLine,- exitWithCommand: true,- kind: 'agent-tui',- agentId,- label: `${provider.name} ${agentId}`,- command: tuiConfig.commandLine,- // Wait until the shell can actually RUN commands before injecting the CLI- // command — a fixed delay races a heavy interactive shell and the launched- // TUI can fall straight back to a half-loaded prompt (see shell.js- // waitForPromptReady, which proves readiness with a round-trip probe).- waitForPromptReady: true,- // Fires when the CLI command is actually injected. We start observing- // claude's input-readiness only after this so the readiness probe's own- // shell activity can't prematurely open the paste gate.- onInitialCommandSent,- // A DELTA, not a full env — buildSafeEnv inside createShellSession supplies- // the base and shell.js does the PWD pin. composeProviderEnv owns the layer- // order (forgeTokenEnv before provider.envVars so an explicit provider- // GH_TOKEN still wins; the OpenCode declared-models map after it, overriding- // the static config). forgeTokenEnv has to be threaded in explicitly because- // buildSafeEnv strips GH_TOKEN from the inherited env (resolveForgeTokenEnv).- //- // agentGuardEnv() is spread last so the pm2 shim wins over any provider PATH.- // It reads PATH from process.env rather than the composed env — correct here- // and NOT what buildCliChildEnv's `guard` does, because this is an overlay- // whose real base env is assembled downstream. Only AI agent sessions get- // the shim; the user's own Shell page does not.- env,- onData,- onExit,- });-if (!sessionId) {return { sessionId: null, ptyProcess: null, pid: null };}@@ -650,17 +671,11 @@ 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);+ // The SAME call `createAgentTuiSession` branches on — resolved here because+ // the prompt handshake below is wired before the spawn happens. Everything+ // that is not a login shell has the provider binary as its own PTY process,+ // which is what both consumers below actually depend on.+ const directLaunch = resolveTuiLaunchShape({ useDurableRunner, safetyProfile }) !== 'login-shell';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@@ -1403,8 +1418,10 @@ export async function spawnTuiAgent({}if (!promptSentAt) {- const lowerStripped = stripped.toLowerCase();- if (lowerStripped.includes('command not found') && lowerStripped.includes(commandName.toLowerCase())) {+ // Only the login-shell path can reach this: it is the shell PRINTING+ // "command not found". A direct PTY resolves the executable before it+ // spawns (createAgentTuiSession), because there is no shell to print it.+ if (detectMissingTuiBinary(stripped, commandName)) {// finish() uses try/finally internally: finalizeAgent errors re-throw after// cleanup, so finish() can reject. The outer try/catch in handleData already// handles any such rejection via emitLog — no additional .catch() needed here.@@ -1446,9 +1463,9 @@ export async function spawnTuiAgent({//// 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.+ // (#6159) simply IS the CLI, so the code and signal are the CLI's own.+ // Reason codes stay `shell-*`: that is what COMPLETION_REASON_ANALYSES+ // registers.const signaled = !!signal;const outcome = killed? { error: 'TUI session was killed', reason: 'shell-killed' }@@ -1522,12 +1539,10 @@ export async function spawnTuiAgent({// outage/refusal so it is blocked with the existing actionable// command-not-found guidance rather than retried as a transient rejection.//- // 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)+ // A LOCAL direct PTY raises the SAME failure with the same prefix — see the+ // pre-spawn resolve in createAgentTuiSession's restricted branch (#6159) —+ // so the test is no longer gated on the runner.+ const reason = /^Command executable unavailable:/i.test(message)? 'command-not-found': useDurableRunner ? 'spawn-rejected' : 'spawn-error';if (useDurableRunner) {diff --git a/server/services/shell.js b/server/services/shell.jsindex 52c9563477..4642eb4e30 100644--- a/server/services/shell.js+++ b/server/services/shell.js@@ -9,6 +9,7 @@ import { resolveInteractiveShell } from '../lib/interactiveShellResolver.js';import { buildRunThenExitCommand } from '../lib/shellExit.js';import { buildReadinessProbe } from '../lib/shellReadinessProbe.js';import { prepareCliSpawn } from '../lib/bufferedSpawn.js';+import { findCommandOnPath } from '../lib/processEnv.js';// Store active shell sessions (persist across socket reconnects)const shellSessions = new Map();@@ -129,30 +130,64 @@ function getDefaultShell() {}/**- * True when the service already holds its ceiling of PTYs it spawned itself.+ * True — and warns — when the service already holds its ceiling of PTYs it+ * spawned itself. Only ever called in the refusal position, so the log lives+ * here rather than being spelled out at each spawn entry point.** 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.*/-function atSessionCap() {- return [...shellSessions.values()].filter(s => !s.external).length >= MAX_TOTAL_SESSIONS;+function refusedForSessionCap() {+ let owned = 0;+ for (const session of shellSessions.values()) {+ if (!session.external) owned += 1;+ }+ if (owned < MAX_TOTAL_SESSIONS) return false;+ console.warn(`🐚 Max total sessions reached (${MAX_TOTAL_SESSIONS})`);+ return true;+}++// Every PTY this service opens is a 256-color terminal.+const TERM_ENV = { TERM: 'xterm-256color', COLORTERM: 'truecolor' };++/**+ * The non-env half of the `pty.spawn` options both entry points use, so the+ * terminal name and the geometry defaults are stated once.+ *+ * `env` is deliberately NOT assembled here. Each caller wraps its own env in+ * `withSpawnCwdEnv` at its own `pty.spawn` call, which keeps the #3193 PWD pin+ * visible at every spawn site — and keeps `lib/spawnCwd.test.js` counting pins+ * one-for-one against spawns, instead of one shared pin covering both.+ */+function ptyTerminalOptions({ cwd, cols, rows }) {+ return {+ name: 'xterm-256color',+ cols: cols || 80,+ rows: rows || 24,+ cwd+ };}/**- * Register a PTY this service just spawned and wire its output/exit handling.+ * Put a PTY in the session registry and wire its output (and, for a PTY this+ * service owns, its exit) — so every attachable session, however it was+ * started, has the same record shape and the same 50KB re-attach ring buffer.*- * 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.+ * Three callers, differing only in the process behind the PTY:+ * - `createShellSession` — an interactive login shell+ * - `spawnCommandSession` — the launched command itself+ * - `registerExternalSession` — a PTY spawned elsewhere (`external: true`)** `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.+ *+ * `external` sessions skip the exit wiring: their lifecycle belongs to whoever+ * spawned them, which ends the session through `unregisterExternalSession`.*/-function adoptOwnedPty(sessionId, ptyProcess, options = {}) {+function adoptPtySession(sessionId, ptyProcess, options = {}) {// Buffer recent output for re-attach (last 50KB)const outputBuffer = [];let bufferSize = 0;@@ -176,6 +211,9 @@ function adoptOwnedPty(sessionId, ptyProcess, options = {}) {command: options.command || null,onData: options.onData || null,onExit: options.onExit || null,+ // Keeps the session out of the interactive cap count and out of Shell's+ // auto-attach — you opt into watching a run by clicking its tab.+ ...(options.external ? { external: true } : {}),outputBuffer,bufferSize: () => bufferSize});@@ -193,6 +231,11 @@ function adoptOwnedPty(sessionId, ptyProcess, options = {}) {if (session) runHook('onData', session, session.onData, data);});+ // An external PTY's lifecycle belongs to whoever spawned it — it ends the+ // session through unregisterExternalSession — so registering an exit listener+ // here would delete the record out from under that owner.+ if (options.external) return;+// Handle pty exit//// `signal` is forwarded, not discarded: on POSIX a shell killed by a signal@@ -216,8 +259,7 @@ function adoptOwnedPty(sessionId, ptyProcess, options = {}) {* Create a new shell session*/export function createShellSession(socket, options = {}) {- if (atSessionCap()) {- console.warn(`🐚 Max total sessions reached (${MAX_TOTAL_SESSIONS})`);+ if (refusedForSessionCap()) {socket?.emit?.('shell:error', { error: `Max ${MAX_TOTAL_SESSIONS} shell sessions. Kill an existing session first.` });return null;}@@ -225,18 +267,13 @@ export function createShellSession(socket, options = {}) {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,+ ...ptyTerminalOptions({ cwd, cols: options.cols, rows: options.rows }),// 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.@@ -250,8 +287,7 @@ export function createShellSession(socket, options = {}) {// 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'+ ...TERM_ENV}, cwd)});} catch (err) {@@ -260,7 +296,7 @@ export function createShellSession(socket, options = {}) {return null;}- adoptOwnedPty(sessionId, ptyProcess, { ...options, socket, cwd, shell });+ adoptPtySession(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@@ -391,48 +427,55 @@ export function createShellSession(socket, options = {}) {* 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.+ * Unlike `createShellSession`, every failure here THROWS rather than returning+ * null. The caller is a spawner that records a cause on the agent record, and a+ * bare null would make "the binary isn't installed" and "the session cap is+ * full" indistinguishable — both then get filed as a generic host problem.** @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+ * @returns {string} sessionId+ * @throws when the session cap is reached, the command is not on the child's+ * PATH, or the PTY will not open*/export function spawnCommandSession(command, args = [], options = {}) {- if (atSessionCap()) {- console.warn(`🐚 Max total sessions reached (${MAX_TOTAL_SESSIONS})`);- return null;+ if (refusedForSessionCap()) {+ throw new Error(`Max ${MAX_TOTAL_SESSIONS} shell sessions are already open; kill one before starting another`);}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);+ // No buildSafeEnv union — see the docstring. The caller owns this env whole.+ // PWD is still pinned to the spawn cwd (#3193): a directly-launched CLI reads+ // it (OpenCode resolves its project root from it) and no shell will fix it up.+ const childEnv = withSpawnCwdEnv({ ...(options.env || {}), ...TERM_ENV }, cwd);++ // Resolve the executable BEFORE spawning. A PTY has no shell to print+ // "command not found": on POSIX node-pty forks and `execvp` fails in the+ // child, which exits 1 with an EMPTY screen, so an output-driven probe can+ // never see it and the run finalizes as a bare exit-1 with no cause. Resolve+ // against the CHILD's PATH — a caller's env may replace PATH with only the+ // provider's own bin dir. Same pre-flight `tuiPromptRunner` and the CoS+ // runner's `/spawn-tui` do; `basename` keeps the resolved path, which can+ // embed the local account name, out of the message.+ if (!findCommandOnPath(command, { env: childEnv, cwd })) {+ throw new Error(`Command executable unavailable: ${basename(command)} is not on the PATH for this session. Install it or update the configured command.`);+ }// 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);+ const { command: ptyCommand, args: ptyArgs } = prepareCliSpawn(command, args, childEnv);- // 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+ ...ptyTerminalOptions({ cwd, cols: options.cols, rows: options.rows }),+ env: childEnv});- adoptOwnedPty(sessionId, ptyProcess, { ...options, socket: null, cwd, shell: null });+ adoptPtySession(sessionId, ptyProcess, { ...options, cwd, shell: null });broadcastSessionList();return sessionId;}@@ -487,39 +530,19 @@ function releaseExternalViews(socket, exceptId = null) {export function registerExternalSession(sessionId, ptyProcess, options = {}) {if (shellSessions.has(sessionId)) return sessionId;- // Mirror createShellSession's 50KB re-attach ring buffer so a viewer who- // opens the run mid-stream still sees the recent screen state.- const outputBuffer = [];- let bufferSize = 0;- const MAX_BUFFER = 50 * 1024;-- shellSessions.set(sessionId, {- _id: sessionId.slice(0, 8),- hookQueue: Promise.resolve(),- pty: ptyProcess,- socket: null,- cwd: options.cwd || null,- createdAt: Date.now(),- label: options.label || null,+ // Same record and same 50KB re-attach ring buffer every other session gets, so+ // a viewer who opens the run mid-stream sees the recent screen state — the+ // only differences are `external` and that the exit wiring stays with the+ // owner (see adoptPtySession).+ adoptPtySession(sessionId, ptyProcess, {+ ...options,kind: options.kind || 'tui-run',- agentId: options.agentId || null,- command: options.command || null,- onData: null,- onExit: null,external: true,- outputBuffer,- bufferSize: () => bufferSize- });-- ptyProcess.onData((data) => {- outputBuffer.push(data);- bufferSize += data.length;- while (bufferSize > MAX_BUFFER && outputBuffer.length > 1) {- bufferSize -= outputBuffer.shift().length;- }- // Re-read the session each time — the attached socket changes as viewers- // come and go; a null socket (no viewer) just drops the emit.- shellSessions.get(sessionId)?.socket?.emit('shell:output', { sessionId, data });+ // The PTY is not ours to type a command line into, and its hooks belong to+ // the process that spawned it.+ shell: null,+ onData: null,+ onExit: null});console.log(`🐚 Registered external TUI session ${sessionId.slice(0, 8)} (${options.label || options.command || 'tui'})`);diff --git a/server/services/shell.test.js b/server/services/shell.test.jsindex 0804c24f44..0fe7624e94 100644--- a/server/services/shell.test.js+++ b/server/services/shell.test.js@@ -1,4 +1,5 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { dirname } from 'path';let ptyInstances = [];let spawnImpl;@@ -545,21 +546,29 @@ describe('changeSessionDirectory', () => {});describe('spawnCommandSession', () => {+ // A REAL resolvable executable. `spawnCommandSession` resolves the command+ // against the child PATH before spawning (there is no shell to report a+ // missing binary), so a made-up provider name would fail that pre-flight+ // rather than reach pty.spawn. node is the one binary this suite can name on+ // any platform.+ const REAL_BIN = process.execPath;+ const REAL_BIN_DIR = dirname(process.execPath);+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'], {+ const id = shell.spawnCommandSession(REAL_BIN, ['--permission-mode', 'plan'], {cwd: '/tmp/ws',- env: { PATH: '/usr/bin', HOME: '/home/example' },+ env: { PATH: REAL_BIN_DIR, 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(spawnedCommand).toBe(REAL_BIN);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).@@ -573,13 +582,13 @@ describe('spawnCommandSession', () => {// just withheld, which is the regression this guards.process.env.PORTOS_TEST_6159_SECRET = 'must-not-reach-the-child';try {- shell.spawnCommandSession('claude', [], {+ shell.spawnCommandSession(REAL_BIN, [], {cwd: '/tmp/ws',- env: { PATH: '/usr/bin', HOME: '/home/example' },+ env: { PATH: REAL_BIN_DIR, 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');+ expect(env.PATH).toBe(REAL_BIN_DIR);// 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');@@ -592,9 +601,9 @@ describe('spawnCommandSession', () => {const onData = vi.fn();const onExit = vi.fn();const observer = makeSocket('obs-direct');- const id = shell.spawnCommandSession('claude', [], {+ const id = shell.spawnCommandSession(REAL_BIN, [], {cwd: '/tmp/ws',- env: { PATH: '/usr/bin' },+ env: { PATH: REAL_BIN_DIR },kind: 'agent-tui',agentId: 'agent-1',label: 'Local Claude TUI agent-1',@@ -619,17 +628,28 @@ describe('spawnCommandSession', () => {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' } });+ const id = shell.spawnCommandSession(REAL_BIN, [], { cwd: '/tmp/ws', env: { PATH: REAL_BIN_DIR } });expect(shell.changeSessionDirectory(id, '/tmp/other')).toBe(false);expect(ptyInstances[0].write).not.toHaveBeenCalled();});+ it('resolves the command against the CHILD PATH before spawning, and names it when missing', () => {+ // A PTY has no shell to print "command not found" — on POSIX node-pty forks+ // and `execvp` fails in the CHILD, which exits 1 with an empty screen. So a+ // missing binary has to be caught before the spawn, or the run finalizes as+ // a bare exit-1 with no cause. The env's PATH is the one that counts: a+ // caller may replace it with only the provider's own bin dir.+ expect(() => shell.spawnCommandSession('definitely-not-installed-xyz', [], {+ cwd: '/tmp/ws',+ env: { PATH: '/nonexistent-bin' },+ })).toThrow(/^Command executable unavailable: definitely-not-installed-xyz/);+ expect(vi.mocked(defaultSpawn)).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/);+ spawnImpl = () => { throw new Error('posix_spawnp failed'); };+ expect(() => shell.spawnCommandSession('node', [], { cwd: '/tmp/ws', env: { PATH: process.env.PATH } }))+ .toThrow(/posix_spawnp failed/);});});