import { withClaudeAgentViewPlugin } from '../../../shared/claude-agent-view-launch' import { resolveStartupShell } from '../../../shared/tui-agent-startup-shell' import { resolveLocalWindowsAgentStartupShell } from '../../../shared/windows-terminal-shell' import { getAppEnvironment } from '../../../shared/app-environment' import type { GlobalSettings } from '../../../shared/global-settings-types' import { isTuiAgent } from '../../../shared/tui-agent-config' import { withCodexTerminalServerIsolationEnv } from '../../../shared/codex-terminal-server-isolation' import { getLegacyOpenCodeEnvKeysToDelete } from '../../opencode/legacy-shared-config-dir' import { prepareOpenCodePtyLaunch } from '../../opencode/opencode-pty-launch' import { LEGACY_TERMINAL_SHIM_REMOTE_ENV_KEYS } from '../../pty/legacy-terminal-shim-dir' import { PI_PROCESS_OWNER_ENV_KEYS } from '../../pty/pi-process-owner-env' import { planCodexNoDaemonLaunch } from '../../pty/codex-no-daemon-launch-command' import { applyAgentWorkspaceTrustToSpawn } from '../../agent-workspace-trust-spawn' import type { PtySpawnOptions } from '../../providers/pty-provider-contract' import type { CodexAccountSelectionTarget } from '../../codex-accounts/runtime-selection' import { getStartupTerminalIngressIntent } from '../terminal-startup-color-query-replies' import { CODEX_HOME_ENV_KEYS } from './host-env/codex-home' import { mergePtyEnvDeletions, removeCodexHomeDeletionRequests, getInheritedAgentHookEnvKeysToDelete, getInheritedAgentSessionStampEnvKeysToDelete } from './host-env/pi-agent' import { promoteAgentTeamsShimPath, deleteRequestedEnvKeys } from './host-env/path' import { resolveConfiguredTerminalShellArgs } from './configured-terminal-shell-args' import { ptySizes } from './delivery/visibility-state' import { shouldSeedPreAttachPtySize } from './delivery/attached-pty-size' type TrustInput = Parameters[0] /** Carries deletions to provider-owned environments, including persistent older daemons. */ export function assemblePtySpawnEnvDeletions(input: { env: Record | undefined callerEnvToDelete: string[] | undefined /** Window only: an Agent Teams refresh drops TERM_PROGRAM; host callers pre-merge their own. */ agentTeamsEnvToDelete: readonly string[] isDaemonHostSpawn: boolean connectionId: string | null | undefined skipCodexHomeEnv: boolean stripInheritedOrcaCodexHome: boolean codexResumeHomeSelected: boolean settings: GlobalSettings | undefined }): { env: Record | undefined; envToDelete: string[] } { // Apply isolation at the common environment boundary used by every provider. const env = withCodexTerminalServerIsolationEnv(input.env, input.settings) let envToDelete = mergePtyEnvDeletions( input.callerEnvToDelete ?? [], // Persistent daemons and older SSH hosts must not resurrect a parent Pi's ownership. PI_PROCESS_OWNER_ENV_KEYS, input.agentTeamsEnvToDelete, // Disable legacy hooks on old hosts while preserving ORCA_REAL pointers needed by Windows shims. input.isDaemonHostSpawn || input.connectionId ? LEGACY_TERMINAL_SHIM_REMOTE_ENV_KEYS : [], input.isDaemonHostSpawn ? getInheritedAgentHookEnvKeysToDelete(env) : [], // The daemon must judge its own inherited value; main may have a different config. !input.connectionId && !input.isDaemonHostSpawn ? getLegacyOpenCodeEnvKeysToDelete(env, getAppEnvironment().getPath('userData')) : [], // Local/relay providers also merge ambient env, so remove inherited session stamps on every path. getInheritedAgentSessionStampEnvKeysToDelete(env), input.skipCodexHomeEnv ? CODEX_HOME_ENV_KEYS : [], // Persistent daemons must compare their own merged Codex home markers. input.stripInheritedOrcaCodexHome ? ['ORCA_CODEX_HOME'] : [] ) ?? [] if (input.codexResumeHomeSelected) { envToDelete = removeCodexHomeDeletionRequests(envToDelete) ?? [] } deleteRequestedEnvKeys(env, envToDelete) return { env, envToDelete } } export type PtySpawnLaunchOptionsInput = { args: { cols: number rows: number launchAgent?: unknown command?: string commandDelivery?: PtySpawnOptions['commandDelivery'] startupCommandDelivery?: PtySpawnOptions['startupCommandDelivery'] worktreeId?: string tabId?: unknown connectionId?: string | null shellOverride?: string telemetry?: { agent_kind?: unknown } } env: Record | undefined /** Mutated: OpenCode prep may add the keys its launch must drop. */ envToDelete: string[] launchCommand: string | undefined cwd: string | undefined /** Window only: the renderer validated cwd; a daemon re-validates it in its own process. */ prevalidatedCwd?: string isDaemonHostSpawn: boolean preAdoptedStablePane: boolean isNewSession: boolean codexRuntime: CodexAccountSelectionTarget['runtime'] expectedWslDistro: string | null requestedAgentTeamsPath: string | undefined selectedCodexHomePath: string | null shellOverride: string | undefined paneKey: string | null | undefined sessionId: string | undefined /** Each lane's own admission rule for which caller intents reach the provider. */ spawnIntent: PtySpawnOptions['spawnIntent'] /** Host history is sampled before preparation; otherwise read it after OpenCode preparation. */ historyIsolationEnabled?: boolean getSettings?: () => GlobalSettings | undefined store: TrustInput['store'] claudeAuth: TrustInput['claudeAuth'] } export async function assemblePtySpawnLaunchOptions(input: PtySpawnLaunchOptionsInput): Promise<{ spawnOptions: PtySpawnOptions env: Record | undefined launchCommand: string | undefined }> { const { args } = input const connectionId = args.connectionId ?? undefined const launchAgent = isTuiAgent(args.launchAgent) ? args.launchAgent : undefined const shell = resolveStartupShell( input.codexRuntime === 'wsl' ? 'linux' : process.platform, resolveLocalWindowsAgentStartupShell({ platform: process.platform, isRemote: Boolean(connectionId) || input.codexRuntime === 'wsl', terminalWindowsShell: input.shellOverride ?? input.getSettings?.()?.terminalWindowsShell }) ) const openCodeLaunch = await prepareOpenCodePtyLaunch({ command: input.launchCommand, agent: launchAgent, env: input.env, envToDelete: input.envToDelete, cwd: input.cwd, connectionId, isFreshLaunch: !input.preAdoptedStablePane && input.launchCommand !== undefined, shell, ...(input.codexRuntime === 'wsl' ? { wsl: { distro: input.expectedWslDistro ?? undefined } } : {}) }) const env = openCodeLaunch.env const pluginDir = !connectionId ? env?.ORCA_CLAUDE_AGENT_VIEW_PLUGIN_DIR : undefined const launchCommand = pluginDir && openCodeLaunch.command ? withClaudeAgentViewPlugin(openCodeLaunch.command, pluginDir, shell) : openCodeLaunch.command promoteAgentTeamsShimPath(env, input.requestedAgentTeamsPath) const spawnOptions: PtySpawnOptions = { cols: args.cols, rows: args.rows, cwd: input.cwd, ...(input.prevalidatedCwd && !input.isDaemonHostSpawn ? { prevalidatedCwd: input.prevalidatedCwd } : {}), env, historyIsolationEnabled: input.historyIsolationEnabled ?? input.getSettings?.()?.terminalScopeHistoryByWorktree ?? true, ...(input.isNewSession ? { isNewSession: true } : {}), envToDelete: input.envToDelete } if (!connectionId && !input.isDaemonHostSpawn) { spawnOptions.codexHomePathOverride = { value: input.selectedCodexHomePath } } const noDaemonLaunch = planCodexNoDaemonLaunch({ command: launchCommand, executesOnThisHost: !connectionId && input.codexRuntime !== 'wsl', shellOverride: input.shellOverride, env, envToDelete: input.envToDelete, cwd: input.cwd }) const command = noDaemonLaunch ? await noDaemonLaunch : launchCommand if (command !== undefined) { spawnOptions.command = command } if (args.commandDelivery !== undefined) { spawnOptions.commandDelivery = args.commandDelivery } if (args.startupCommandDelivery !== undefined) { spawnOptions.startupCommandDelivery = args.startupCommandDelivery } if (launchAgent) { spawnOptions.launchAgent = launchAgent } if (args.worktreeId !== undefined) { spawnOptions.worktreeId = args.worktreeId } if (input.spawnIntent) { spawnOptions.spawnIntent = input.spawnIntent } const startupIngress = getStartupTerminalIngressIntent(args) if (startupIngress) { spawnOptions.startupIngress = startupIngress } const trustWrite = applyAgentWorkspaceTrustToSpawn({ launchAgent: args.launchAgent, worktreeId: args.worktreeId, cwd: input.cwd, store: input.store, isFreshLaunch: !input.preAdoptedStablePane && launchCommand !== undefined, settings: input.getSettings?.(), env, claudeAuth: input.claudeAuth, wslDistro: input.expectedWslDistro, connectionId: connectionId ?? null, codexHome: input.selectedCodexHomePath, spawnOptions }) if (trustWrite) { await trustWrite } if (input.paneKey) { spawnOptions.paneKey = input.paneKey } if (typeof args.tabId === 'string' && args.tabId.length > 0 && args.tabId.length <= 512) { spawnOptions.tabId = args.tabId } if (input.sessionId !== undefined) { spawnOptions.sessionId = input.sessionId } if (!connectionId) { // Daemon spawns must honor saved Windows shell preference too. if (input.shellOverride !== undefined) { spawnOptions.shellOverride = input.shellOverride } spawnOptions.terminalShellArgs = resolveConfiguredTerminalShellArgs({ connectionId, requestedShellOverride: args.shellOverride, launchCommand, settings: input.getSettings?.() }) if (process.platform === 'win32') { // Preserve the PowerShell implementation choice across both provider paths. spawnOptions.terminalWindowsWslDistro = input.expectedWslDistro spawnOptions.terminalWindowsPowerShellImplementation = input.getSettings ? (input.getSettings()?.terminalWindowsPowerShellImplementation ?? 'auto') : undefined } } return { spawnOptions, env, launchCommand } } export type PtySpawnSizeSeed = { cachedBeforeAttach: { cols: number; rows: number } | undefined rollback: (options?: { reattachId?: string; exitedBeforeSpawnReply?: boolean }) => void } /** Samples and seeds geometry only when preparation reaches this resource. */ export function seedPtySpawnSize(input: { sessionId: string | undefined sessionAppId: string | undefined isFreshSessionId: boolean requestIsUnmeasured: boolean cols: number rows: number }): PtySpawnSizeSeed { const key = input.sessionAppId ?? input.sessionId const cachedBeforeAttach = key !== undefined ? ptySizes.get(key) : undefined if ( input.sessionId !== undefined && shouldSeedPreAttachPtySize({ isFreshSessionId: input.isFreshSessionId, hasCachedSize: cachedBeforeAttach !== undefined, requestIsUnmeasured: input.requestIsUnmeasured }) ) { // Daemon output can precede the reply; the grid must exist before byte zero. ptySizes.set(key!, { cols: input.cols, rows: input.rows }) } return { cachedBeforeAttach, rollback: (options) => { if (input.sessionId === undefined || key === options?.reattachId) { return } if (cachedBeforeAttach && !options?.exitedBeforeSpawnReply) { ptySizes.set(key!, cachedBeforeAttach) } else { ptySizes.delete(key!) } } } } /** Takes the acquired seed so teardown and outer failure cannot restore it twice. */ export function restoreProvisionalPtySize( state: { provisionalPtySize: PtySpawnSizeSeed | undefined }, options?: Parameters[0] ): void { const seed = state.provisionalPtySize state.provisionalPtySize = undefined seed?.rollback(options) }