supercode-harness 0.4.13

The optional native Supercode agent and tool harness
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! Native coding-harness authentication coordination.
//!
//! Supercode never reads, copies, or stores another harness's credentials. It
//! discovers the native CLI's supported sign-in mechanisms, returns an
//! explicit launch plan to the embedding host, and verifies the result through
//! the harness's own status command.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::Duration;

use serde::{Deserialize, Serialize};

use crate::HarnessId;

/// Stable schema identifier shared by authentication reports and launch plans.
pub const HARNESS_AUTHENTICATION_SCHEMA: &str = "supercode.harness-authentication.v1";

/// Environment in which the native authentication interaction must work.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HarnessAuthenticationEnvironment {
    /// A local graphical browser may be opened by the native harness.
    LocalBrowser,
    /// No browser can be opened on the machine running the harness.
    Headless,
}

/// Stable identifier for a harness-native authentication mechanism.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HarnessAuthenticationMethodId {
    /// The native CLI opens or directs the user to a browser sign-in.
    Browser,
    /// The native CLI prints a device code completed in another browser.
    DeviceCode,
}

/// User interaction presented by an authentication method.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum HarnessAuthenticationInteraction {
    /// A browser-based sign-in with progress retained in a terminal.
    Browser,
    /// A short-lived code entered on another device.
    DeviceCode,
}

/// Whether the native CLI itself is expected to open a browser.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum HarnessBrowserBehavior {
    /// The harness owns automatic browser opening and any redirect listener.
    NativeAuto,
    /// This method does not open a local browser.
    None,
}

/// Credential readiness reported without exposing credential material.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum HarnessAuthenticationState {
    /// The harness's native status command confirms an active sign-in.
    Authenticated,
    /// Credential evidence exists, but native status did not confirm it.
    Configured,
    /// No native sign-in or local credential evidence was found.
    Required,
    /// The harness is absent or has no verified Supercode auth adapter.
    Unavailable,
}

/// One verified native authentication mechanism supported by a harness.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct HarnessAuthenticationMethod {
    /// Stable mechanism identifier.
    pub id: HarnessAuthenticationMethodId,
    /// Short user-facing label.
    pub label: &'static str,
    /// User-facing explanation of the native flow.
    pub description: &'static str,
    /// Interaction the host must present.
    pub interaction: HarnessAuthenticationInteraction,
    /// Browser-opening behavior owned by the native CLI.
    pub browser_behavior: HarnessBrowserBehavior,
    /// Whether the method is verified for machines without a local browser.
    pub headless: bool,
    /// Whether local interactive hosts should prefer this method.
    pub recommended: bool,
}

/// Process launch that an embedding host must run in a user-visible terminal.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct HarnessAuthenticationLaunch {
    /// Working directory inherited by the native harness.
    pub cwd: PathBuf,
    /// Resolved native harness executable.
    pub program: String,
    /// Authentication arguments supported by that executable.
    pub arguments: Vec<String>,
    /// Deliberate environment additions; credential values are never included.
    pub env: BTreeMap<String, String>,
}

/// Host-executable plan for one selected authentication method.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct HarnessAuthenticationPlan {
    /// Wire schema identifier.
    pub schema: &'static str,
    /// Harness that owns the credentials and interaction.
    pub harness: HarnessId,
    /// Selected native method.
    pub method: HarnessAuthenticationMethodId,
    /// Interaction the host must surface.
    pub interaction: HarnessAuthenticationInteraction,
    /// Browser-opening behavior of the native CLI.
    pub browser_behavior: HarnessBrowserBehavior,
    /// Whether this plan is verified for a browserless machine.
    pub headless: bool,
    /// Native process to run in a visible, host-owned terminal.
    pub launch: HarnessAuthenticationLaunch,
    /// Concise instructions for the host to display alongside the terminal.
    pub instructions: &'static str,
}

/// Redacted native authentication readiness and available methods.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct HarnessAuthenticationReport {
    /// Wire schema identifier.
    pub schema: &'static str,
    /// Inspected harness.
    pub harness: HarnessId,
    /// Whether its native executable is installed.
    pub installed: bool,
    /// Resolved executable path, when installed.
    pub executable: Option<String>,
    /// Redacted credential readiness.
    pub state: HarnessAuthenticationState,
    /// Verified native methods Supercode can coordinate.
    pub methods: Vec<HarnessAuthenticationMethod>,
    /// Human-readable status explanation without native command output.
    pub reason: Option<String>,
}

/// Failure to construct a truthful native authentication plan.
#[derive(Debug, thiserror::Error)]
pub enum HarnessAuthenticationError {
    /// The harness id is not in Supercode's registry.
    #[error("unknown harness `{0}`")]
    UnknownHarness(String),
    /// The registered native executable is absent.
    #[error("{0} is not installed or its executable is not on PATH")]
    NotInstalled(String),
    /// The requested environment or method has no verified native adapter.
    #[error("{0}")]
    Unsupported(String),
}

/// Return the verified native authentication methods for a harness.
pub fn harness_authentication_methods(
    harness: &HarnessId,
) -> Result<Vec<HarnessAuthenticationMethod>, HarnessAuthenticationError> {
    let methods = match harness.as_str() {
        HarnessId::CLAUDE_CODE => vec![HarnessAuthenticationMethod {
            id: HarnessAuthenticationMethodId::Browser,
            label: "Sign in with browser",
            description: "Claude Code opens its native sign-in page and keeps the terminal available for status and fallback instructions.",
            interaction: HarnessAuthenticationInteraction::Browser,
            browser_behavior: HarnessBrowserBehavior::NativeAuto,
            headless: false,
            recommended: true,
        }],
        HarnessId::CODEX => vec![
            HarnessAuthenticationMethod {
                id: HarnessAuthenticationMethodId::Browser,
                label: "Sign in with browser",
                description: "Codex opens its native ChatGPT sign-in flow in the local browser.",
                interaction: HarnessAuthenticationInteraction::Browser,
                browser_behavior: HarnessBrowserBehavior::NativeAuto,
                headless: false,
                recommended: true,
            },
            HarnessAuthenticationMethod {
                id: HarnessAuthenticationMethodId::DeviceCode,
                label: "Use another device",
                description: "Codex prints a short-lived code and verification address for a phone or another browser.",
                interaction: HarnessAuthenticationInteraction::DeviceCode,
                browser_behavior: HarnessBrowserBehavior::None,
                headless: true,
                recommended: false,
            },
        ],
        value
            if crate::harness_support_registry()
                .harnesses
                .iter()
                .any(|descriptor| descriptor.id == *harness) =>
        {
            return Err(HarnessAuthenticationError::Unsupported(format!(
                "Supercode does not yet have a verified native sign-in adapter for `{value}`"
            )))
        }
        value => return Err(HarnessAuthenticationError::UnknownHarness(value.into())),
    };
    Ok(methods)
}

/// Select a method for the requested environment and create its host-owned launch plan.
pub fn harness_authentication_plan(
    harness: &HarnessId,
    environment: HarnessAuthenticationEnvironment,
    requested_method: Option<HarnessAuthenticationMethodId>,
    cwd: &Path,
) -> Result<HarnessAuthenticationPlan, HarnessAuthenticationError> {
    let methods = harness_authentication_methods(harness)?;
    let selected = requested_method
        .and_then(|id| methods.iter().find(|method| method.id == id))
        .or_else(|| match environment {
            HarnessAuthenticationEnvironment::LocalBrowser => {
                methods.iter().find(|method| method.recommended)
            }
            HarnessAuthenticationEnvironment::Headless => {
                methods.iter().find(|method| method.headless)
            }
        })
        .ok_or_else(|| {
            HarnessAuthenticationError::Unsupported(format!(
                "{} does not expose a verified {} sign-in flow in this Supercode version",
                harness.as_str(),
                match environment {
                    HarnessAuthenticationEnvironment::LocalBrowser => "local-browser",
                    HarnessAuthenticationEnvironment::Headless => "headless",
                }
            ))
        })?;
    if requested_method.is_some_and(|id| !methods.iter().any(|method| method.id == id)) {
        return Err(HarnessAuthenticationError::Unsupported(format!(
            "{} does not support the requested sign-in method",
            harness.as_str()
        )));
    }
    let program = default_auth_program(harness)
        .ok_or_else(|| HarnessAuthenticationError::UnknownHarness(harness.as_str().into()))?;
    let executable = find_executable(&program)
        .ok_or_else(|| HarnessAuthenticationError::NotInstalled(harness.as_str().to_string()))?;
    let arguments = match (harness.as_str(), selected.id) {
        (HarnessId::CLAUDE_CODE, HarnessAuthenticationMethodId::Browser) => {
            vec!["auth".into(), "login".into()]
        }
        (HarnessId::CODEX, HarnessAuthenticationMethodId::Browser) => vec!["login".into()],
        (HarnessId::CODEX, HarnessAuthenticationMethodId::DeviceCode) => {
            vec!["login".into(), "--device-auth".into()]
        }
        _ => {
            return Err(HarnessAuthenticationError::Unsupported(format!(
                "{} does not support the requested sign-in method",
                harness.as_str()
            )))
        }
    };
    Ok(HarnessAuthenticationPlan {
        schema: HARNESS_AUTHENTICATION_SCHEMA,
        harness: harness.clone(),
        method: selected.id,
        interaction: selected.interaction,
        browser_behavior: selected.browser_behavior,
        headless: selected.headless,
        launch: HarnessAuthenticationLaunch {
            cwd: cwd.to_path_buf(),
            program: executable.to_string_lossy().into_owned(),
            arguments,
            env: BTreeMap::new(),
        },
        instructions: match selected.interaction {
            HarnessAuthenticationInteraction::Browser => {
                "Keep the native sign-in terminal open until the harness confirms completion. If a browser cannot open, use any fallback instructions printed there."
            }
            HarnessAuthenticationInteraction::DeviceCode => {
                "Keep the native sign-in terminal open, then visit the printed address on any device and enter the short-lived code."
            }
        },
    })
}

/// Inspect redacted sign-in status using the harness's own bounded status command.
pub async fn inspect_harness_authentication(harness: &HarnessId) -> HarnessAuthenticationReport {
    let methods = harness_authentication_methods(harness);
    let Some(program) = default_auth_program(harness) else {
        return HarnessAuthenticationReport {
            schema: HARNESS_AUTHENTICATION_SCHEMA,
            harness: harness.clone(),
            installed: false,
            executable: None,
            state: HarnessAuthenticationState::Unavailable,
            methods: Vec::new(),
            reason: Some("No native sign-in executable is registered.".into()),
        };
    };
    let Some(executable) = find_executable(&program) else {
        return HarnessAuthenticationReport {
            schema: HARNESS_AUTHENTICATION_SCHEMA,
            harness: harness.clone(),
            installed: false,
            executable: None,
            state: HarnessAuthenticationState::Unavailable,
            methods: methods.unwrap_or_default(),
            reason: Some(format!("`{program}` was not found on PATH.")),
        };
    };
    let methods = match methods {
        Ok(methods) => methods,
        Err(error) => {
            return HarnessAuthenticationReport {
                schema: HARNESS_AUTHENTICATION_SCHEMA,
                harness: harness.clone(),
                installed: true,
                executable: Some(executable.to_string_lossy().into_owned()),
                state: HarnessAuthenticationState::Unavailable,
                methods: Vec::new(),
                reason: Some(error.to_string()),
            }
        }
    };
    let verified = native_auth_status(harness, &executable).await;
    let configured = super::harness_service::auth_evidence(harness.as_str());
    let (state, reason) = if verified {
        (
            HarnessAuthenticationState::Authenticated,
            Some("The native harness reports an active sign-in.".into()),
        )
    } else if configured {
        (
            HarnessAuthenticationState::Configured,
            Some("Local credential evidence exists, but the native status command did not confirm an active sign-in.".into()),
        )
    } else {
        (
            HarnessAuthenticationState::Required,
            Some("The native harness does not report an active sign-in.".into()),
        )
    };
    HarnessAuthenticationReport {
        schema: HARNESS_AUTHENTICATION_SCHEMA,
        harness: harness.clone(),
        installed: true,
        executable: Some(executable.to_string_lossy().into_owned()),
        state,
        methods,
        reason,
    }
}

async fn native_auth_status(harness: &HarnessId, executable: &Path) -> bool {
    let mut command = tokio::process::Command::new(executable);
    match harness.as_str() {
        HarnessId::CLAUDE_CODE => {
            command.args(["auth", "status", "--json"]);
        }
        HarnessId::CODEX => {
            command.args(["login", "status"]);
        }
        _ => return false,
    }
    command
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .kill_on_drop(true);
    let Ok(Ok(output)) = tokio::time::timeout(Duration::from_secs(3), command.output()).await
    else {
        return false;
    };
    if !output.status.success() {
        return false;
    }
    if harness.as_str() == HarnessId::CLAUDE_CODE {
        return serde_json::from_slice::<serde_json::Value>(&output.stdout)
            .ok()
            .and_then(|value| value.get("loggedIn").and_then(serde_json::Value::as_bool))
            .unwrap_or(false);
    }
    true
}

fn default_auth_program(harness: &HarnessId) -> Option<String> {
    crate::harness_support_registry()
        .harnesses
        .into_iter()
        .find(|descriptor| descriptor.id == *harness)
        .and_then(|descriptor| descriptor.runtime.default_launch)
        .map(|launch| launch.program)
}

fn find_executable(program: &str) -> Option<PathBuf> {
    let path = std::env::var_os("PATH")?;
    std::env::split_paths(&path).find_map(|directory| {
        let candidate = directory.join(program);
        if candidate.is_file() {
            return std::fs::canonicalize(&candidate).ok().or(Some(candidate));
        }
        #[cfg(windows)]
        for extension in ["exe", "cmd", "bat"] {
            let candidate = directory.join(format!("{program}.{extension}"));
            if candidate.is_file() {
                return std::fs::canonicalize(&candidate).ok().or(Some(candidate));
            }
        }
        None
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn adapter_selection_never_substitutes_a_browser_flow_for_headless_login() {
        let codex = HarnessId::new(HarnessId::CODEX);
        let claude = HarnessId::new(HarnessId::CLAUDE_CODE);
        let methods = harness_authentication_methods(&codex).unwrap();
        assert_eq!(
            methods
                .iter()
                .find(|method| method.headless)
                .map(|method| method.id),
            Some(HarnessAuthenticationMethodId::DeviceCode)
        );
        assert!(!harness_authentication_methods(&claude)
            .unwrap()
            .iter()
            .any(|method| method.headless));
    }
}