Repository Public
1import Foundation2import WorkspaceCore34/// A fully resolved process launch: executable path, argv (never a shell string), environment and cwd.5public struct LaunchSpec: Sendable, Hashable {6 public var executable: String7 public var arguments: [String]8 public var environment: [String: String]9 public var workingDirectory: String?10 /// argv[0] override; login shells use "-zsh" so the shell sources profile files.11 public var execName: String?1213 public init(executable: String, arguments: [String] = [], environment: [String: String] = [:], workingDirectory: String? = nil, execName: String? = nil) {14 self.executable = executable15 self.arguments = arguments16 self.environment = environment17 self.workingDirectory = workingDirectory18 self.execName = execName19 }2021 /// Environment in `KEY=value` form as the PTY layer expects.22 public var environmentArray: [String] {23 environment.keys.sorted().map { "\($0)=\(environment[$0]!)" }24 }25}2627/// Resolves a `SessionProfile` into a concrete `LaunchSpec`. The app composes one of these from the28/// Claude, SSH and shell planners so `TerminalCore` never depends on those modules.29public protocol LaunchPlanning: Sendable {30 func launchSpec(for profile: SessionProfile, sessionID: SessionID) throws -> LaunchSpec31}3233public enum LaunchPlanningError: Error, LocalizedError, Sendable {34 case executableNotFound(String)35 case unsupported(String)3637 public var errorDescription: String? {38 switch self {39 case .executableNotFound(let name): return "Executable not found: \(name)"40 case .unsupported(let what): return "Unsupported session: \(what)"41 }42 }43}4445public enum ShellDiscovery {46 /// The user's login shell from the directory service, falling back to `$SHELL` then `/bin/zsh`.47 public static func loginShell() -> String {48 if let pw = getpwuid(getuid()), let shell = pw.pointee.pw_shell {49 let path = String(cString: shell)50 if FileManager.default.isExecutableFile(atPath: path) { return path }51 }52 if let shell = ProcessInfo.processInfo.environment["SHELL"], FileManager.default.isExecutableFile(atPath: shell) {53 return shell54 }55 return "/bin/zsh"56 }5758 /// Default directory for new sessions when none is configured.59 public static func homeDirectory() -> String {60 FileManager.default.homeDirectoryForCurrentUser.path61 }6263 /// Finds an executable on a search path list, checking common Homebrew and user locations in addition to `$PATH`.64 public static func resolveExecutable(_ name: String, extraSearchPaths: [String] = []) -> String? {65 if name.hasPrefix("/") {66 return FileManager.default.isExecutableFile(atPath: name) ? name : nil67 }68 let home = homeDirectory()69 var candidates = (ProcessInfo.processInfo.environment["PATH"] ?? "").split(separator: ":").map(String.init)70 candidates += extraSearchPaths71 candidates += ["/opt/homebrew/bin", "/usr/local/bin", "\(home)/.local/bin", "\(home)/.claude/local/bin", "\(home)/.claude/local", "/usr/bin", "/bin"]72 var seen = Set<String>()73 for dir in candidates where !dir.isEmpty && seen.insert(dir).inserted {74 let path = (dir as NSString).appendingPathComponent(name)75 if FileManager.default.isExecutableFile(atPath: path) { return path }76 }77 return nil78 }7980 public static let appVersion: String = {81 (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String) ?? "dev"82 }()8384 /// Base environment for every child process: inherits the app's environment (GUI apps get a85 /// minimal one) and sets terminal identification variables. Secrets are never injected.86 public static func baseEnvironment(sessionID: SessionID) -> [String: String] {87 var env = ProcessInfo.processInfo.environment88 env["TERM"] = "xterm-256color"89 env["COLORTERM"] = "truecolor"90 if env["LANG"] == nil { env["LANG"] = "en_US.UTF-8" }91 env["TERM_PROGRAM"] = "NEXTERM"92 env["TERM_PROGRAM_VERSION"] = appVersion93 env["NEXTERM_SESSION_ID"] = sessionID.rawValue.uuidString94 // Values Xcode/launchd leave behind that confuse child shells.95 for key in ["XPC_SERVICE_NAME", "XPC_FLAGS", "DYLD_INSERT_LIBRARIES", "DYLD_LIBRARY_PATH", "DYLD_FRAMEWORK_PATH"] {96 env.removeValue(forKey: key)97 }98 return env99 }100}101102/// Default planner: handles local shells, local tmux and raw commands. Claude and SSH are provided by the app.103public struct LocalLaunchPlanner: LaunchPlanning {104 public init() {}105106 public func launchSpec(for profile: SessionProfile, sessionID: SessionID) throws -> LaunchSpec {107 var env = ShellDiscovery.baseEnvironment(sessionID: sessionID)108 for (k, v) in profile.environment { env[k] = v }109 let cwd = profile.workingDirectory ?? ShellDiscovery.homeDirectory()110 switch profile.kind {111 case .shell(let path):112 let shell = path ?? ShellDiscovery.loginShell()113 guard FileManager.default.isExecutableFile(atPath: shell) else { throw LaunchPlanningError.executableNotFound(shell) }114 env["SHELL"] = shell115 let name = "-" + (shell as NSString).lastPathComponent116 return LaunchSpec(executable: shell, arguments: [], environment: env, workingDirectory: cwd, execName: name)117 case .tmux(let name):118 guard let tmux = ShellDiscovery.resolveExecutable("tmux") else { throw LaunchPlanningError.executableNotFound("tmux") }119 return LaunchSpec(executable: tmux, arguments: ["new-session", "-A", "-s", name], environment: env, workingDirectory: cwd)120 case .command(let executable, let arguments):121 guard let path = ShellDiscovery.resolveExecutable(executable) else { throw LaunchPlanningError.executableNotFound(executable) }122 return LaunchSpec(executable: path, arguments: arguments, environment: env, workingDirectory: cwd)123 case .claude, .ssh:124 throw LaunchPlanningError.unsupported("\(profile.kind)")125 }126 }127}128