use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use crate::adapters::AdapterSpec;
use crate::adapters::detect::find_executable;
use crate::diagnostics::log;
use crate::env::{Env, Os};
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::process::hide_window;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SignInKind {
Command,
InClient,
Connector,
Unsupported,
}
impl SignInKind {
pub const fn as_str(self) -> &'static str {
match self {
SignInKind::Command => "command",
SignInKind::InClient => "in_client",
SignInKind::Connector => "connector",
SignInKind::Unsupported => "unsupported",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SignIn {
pub kind: SignInKind,
pub command: Option<&'static [&'static str]>,
pub steps: &'static str,
pub docs_url: Option<&'static str>,
pub verified: bool,
}
impl SignIn {
pub const UNKNOWN: Self = Self {
kind: SignInKind::InClient,
command: None,
steps: "If {client} supports OAuth for remote servers, it asks you to sign in when it \
first connects to {name}. See its documentation.",
docs_url: None,
verified: false,
};
pub const NO_REMOTE: Self = Self {
kind: SignInKind::Unsupported,
command: None,
steps: "{client} does not run remote servers, so it cannot sign in to {name}.",
docs_url: None,
verified: false,
};
pub fn for_spec(spec: &AdapterSpec) -> Self {
let Some(mcp) = spec.mcp.as_ref() else {
return Self::NO_REMOTE;
};
let remote = mcp.caps.transports.http || mcp.caps.transports.sse;
if remote || mcp.sign_in.kind == SignInKind::Connector {
mcp.sign_in
} else {
Self::NO_REMOTE
}
}
pub fn command_line(&self, name: &str) -> Option<Vec<String>> {
self.command.map(|words| {
words
.iter()
.map(|word| word.replace("{name}", name))
.collect()
})
}
pub fn for_entry(spec: &AdapterSpec, name: &str) -> Self {
let mut sign_in = Self::for_spec(spec);
if sign_in.kind == SignInKind::Command && !runnable_name(name) {
sign_in.kind = SignInKind::InClient;
}
sign_in
}
pub fn command_text(&self, name: &str, os: Os) -> Option<String> {
self.command_line("ed(name, os))
.map(|words| words.join(" "))
}
pub fn steps_for(&self, client: &str, name: &str, os: Os) -> String {
self.steps
.replace("{client}", client)
.replace("{name}", "ed(name, os))
}
}
pub fn runnable_name(name: &str) -> bool {
!name.is_empty()
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
}
fn quoted(name: &str, os: Os) -> String {
if runnable_name(name) {
name.to_owned()
} else if os == Os::Windows {
format!("\"{}\"", name.replace('"', "\"\""))
} else {
format!("'{}'", name.replace('\'', "'\\''"))
}
}
fn kill_tree(taskkill: &Option<PathBuf>, child: &mut std::process::Child) {
#[cfg(windows)]
if let Some(taskkill) = taskkill {
let _ = hide_window(&mut Command::new(taskkill))
.args(["/T", "/F", "/PID", &child.id().to_string()])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
#[cfg(not(windows))]
let _ = taskkill;
let _ = child.kill();
let _ = child.wait();
}
pub const CODEX: SignIn = SignIn {
kind: SignInKind::Command,
command: Some(&["codex", "mcp", "login", "{name}"]),
steps: "Run `codex mcp login {name}` in a terminal. It opens your browser to sign in.",
docs_url: Some("https://developers.openai.com/codex/mcp"),
verified: true,
};
pub const CLAUDE_CODE: SignIn = SignIn {
kind: SignInKind::Command,
command: Some(&["claude", "mcp", "login", "{name}"]),
steps: "Run `claude mcp login {name}` in a terminal, or type /mcp in a Claude Code session, \
pick {name} and choose Authenticate. It opens your browser to sign in.",
docs_url: Some("https://code.claude.com/docs/en/mcp"),
verified: true,
};
pub const OPENCODE: SignIn = SignIn {
kind: SignInKind::Command,
command: Some(&["opencode", "mcp", "auth", "{name}"]),
steps: "Run `opencode mcp auth {name}` in a terminal, or open /mcps in OpenCode and \
authenticate {name}. It opens your browser to sign in.",
docs_url: Some("https://opencode.ai/docs/mcp-servers/"),
verified: true,
};
pub const GEMINI: SignIn = SignIn {
kind: SignInKind::InClient,
command: None,
steps: "In a Gemini CLI session, run `/mcp auth {name}`. It opens your browser to sign in.",
docs_url: Some(
"https://github.com/google-gemini/gemini-cli/blob/main/docs/tools/mcp-server.md",
),
verified: true,
};
pub const CLAUDE_DESKTOP: SignIn = SignIn {
kind: SignInKind::Connector,
command: None,
steps: "Claude Desktop does not read remote servers from its config file. Add the address \
as a custom connector in its settings (Connectors), then connect to sign in.",
docs_url: None,
verified: false,
};
pub const SIGN_IN_TIMEOUT: Duration = Duration::from_secs(15 * 60);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StartedSignIn {
pub program: PathBuf,
pub command_line: String,
}
pub fn start(
env: &Env,
fs: &dyn Fs,
spec: &AdapterSpec,
name: &str,
timeout: Duration,
) -> Result<StartedSignIn, CoreError> {
let sign_in = SignIn::for_spec(spec);
let words = match sign_in.command_line(name) {
Some(words) if sign_in.kind == SignInKind::Command && sign_in.verified => words,
_ => {
return Err(CoreError::new(
ErrorCode::NotFound,
format!(
"{} has no login command Surjection can run",
spec.display_name
),
));
}
};
if !runnable_name(name) {
return Err(CoreError::new(
ErrorCode::InvalidValue,
format!("{name:?} is not an entry name a login command can take"),
));
}
let (program_name, args) = words.split_first().expect("a command has a program");
let program = find_executable(env, fs, program_name).ok_or_else(|| {
CoreError::new(
ErrorCode::NotFound,
format!(
"{program_name} was not found on PATH; run `{}` in a terminal instead",
words.join(" ")
),
)
})?;
let command_line = words.join(" ");
let mut child = hide_window(&mut Command::new(&program))
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.map_err(|err| {
CoreError::new(
ErrorCode::IoError,
format!("cannot start {program_name}: {err}"),
)
})?;
let client = spec.id;
let taskkill = env
.var("SystemRoot")
.map(|root| PathBuf::from(root).join("System32").join("taskkill.exe"));
log::event(
"sign_in_started",
&[("client", &client), ("command", &command_line)],
);
let started = Instant::now();
std::thread::spawn(move || {
let outcome = loop {
match child.try_wait() {
Ok(Some(status)) => {
break status
.code()
.map_or_else(|| "ended".to_owned(), |code| format!("exit {code}"));
}
Ok(None) if started.elapsed() >= timeout => {
kill_tree(&taskkill, &mut child);
break "stopped (timed out)".to_owned();
}
Ok(None) => std::thread::sleep(Duration::from_millis(250)),
Err(err) => break format!("unknown ({err})"),
}
};
let seconds = started.elapsed().as_secs();
log::event(
"sign_in_finished",
&[
("client", &client),
("outcome", &outcome),
("secs", &seconds),
],
);
});
Ok(StartedSignIn {
program,
command_line,
})
}