supercode-harness 0.4.4

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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//! Trusted local receipts for attachable Supercode runtimes.
//!
//! A browser-facing host may reveal the opaque [`LiveRuntimeEndpoint`], but
//! never the HTTP bearer token stored in the receipt.  The harness service
//! resolves that endpoint inside the user's process, checks the source
//! session/workspace identity, and then authenticates to the runtime.

use std::fs::{self, OpenOptions};
use std::io::Write;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

#[cfg(test)]
use std::sync::{Mutex, MutexGuard, OnceLock};

use serde::{Deserialize, Serialize};

const RECEIPT_SCHEMA: &str = "supercode.live-runtime.v1";
const ENDPOINT_PREFIX: &str = "supercode-live://";

/// Stable source identity through which a hosted continuation is discovered.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LiveRuntimeSource {
    /// Harness that owns the persisted source transcript.
    pub harness: String,
    /// Harness-native source session identity.
    pub session_id: String,
    /// Project directory in which the runtime is operating.
    pub workspace: PathBuf,
}

/// Static runtime metadata recorded at registration. Dynamic state, actions,
/// controller, and observers are queried from the authenticated SDK endpoint.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct LiveRuntimeMetadata {
    /// Resolved composable emulation profile.
    pub profile: Option<String>,
    /// Canonical persistence location owned by Supercode. This is never the
    /// authority for a source harness's unchanged native transcript.
    pub persistence_location: Option<PathBuf>,
    /// Transport names exposed by this endpoint.
    pub endpoint_capabilities: Vec<String>,
    /// Optional process supervisor. This is presentation/lifecycle metadata;
    /// the authenticated SDK endpoint remains the runtime authority.
    pub supervisor: Option<LiveRuntimeSupervisor>,
}

/// Optional local process supervisor for an attachable runtime.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum LiveRuntimeSupervisor {
    /// A predictably named tmux session containing the owner and frontend.
    Tmux {
        /// Exact tmux session name accepted by `tmux attach-session -t`.
        session_name: String,
    },
}

/// Browser-safe inventory record for one reconciled live receipt.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LiveRuntimeRecord {
    /// Opaque receipt endpoint; it contains no bearer credential.
    pub endpoint: LiveRuntimeEndpoint,
    /// Stable SDK runtime/session id.
    pub runtime_session_id: String,
    /// Source harness identity.
    pub source: LiveRuntimeSource,
    /// Process that owns the runtime.
    pub pid: u32,
    /// Registration time in epoch milliseconds.
    pub created_at_ms: u128,
    /// Static registration metadata.
    pub metadata: LiveRuntimeMetadata,
}

/// Browser-safe reference to a trusted local runtime receipt.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LiveRuntimeEndpoint(String);

impl LiveRuntimeEndpoint {
    /// Parse an opaque live-runtime endpoint.
    pub fn parse(value: &str) -> Result<Self, LiveRuntimeReceiptError> {
        let id = value
            .strip_prefix(ENDPOINT_PREFIX)
            .filter(|id| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_hexdigit()))
            .ok_or(LiveRuntimeReceiptError::InvalidEndpoint)?;
        Ok(Self(format!("{ENDPOINT_PREFIX}{id}")))
    }

    /// Return the opaque endpoint string safe to expose to a local UI.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    fn receipt_id(&self) -> &str {
        self.0
            .strip_prefix(ENDPOINT_PREFIX)
            .expect("LiveRuntimeEndpoint is validated at construction")
    }
}

impl std::fmt::Display for LiveRuntimeEndpoint {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.0)
    }
}

/// Secret host-side information recovered from a verified receipt.
///
/// Do not serialize this value into browser-facing discovery results: it
/// contains the bearer token for the loopback SDK runtime.
pub struct ResolvedLiveRuntime {
    /// Opaque endpoint used to locate the receipt.
    pub endpoint: LiveRuntimeEndpoint,
    /// SDK runtime's stable session identity.
    pub runtime_session_id: String,
    /// Persisted source identity advertised by discovery.
    pub source: LiveRuntimeSource,
    /// Loopback HTTP address of the SDK runtime.
    pub base_url: String,
    /// Bearer token accepted by that runtime.
    pub token: String,
    /// Process that owns the runtime.
    pub pid: u32,
}

/// RAII registration for one live runtime. Dropping it removes only the
/// receipt created by this registration, leaving persisted chat data intact.
pub struct LiveRuntimeRegistration {
    endpoint: LiveRuntimeEndpoint,
    path: PathBuf,
}

impl LiveRuntimeRegistration {
    /// Opaque endpoint safe to publish in trusted-host discovery output.
    pub fn endpoint(&self) -> &LiveRuntimeEndpoint {
        &self.endpoint
    }
}

impl Drop for LiveRuntimeRegistration {
    fn drop(&mut self) {
        let Ok(bytes) = fs::read(&self.path) else {
            return;
        };
        let Ok(receipt) = serde_json::from_slice::<Receipt>(&bytes) else {
            return;
        };
        if receipt.receipt_id == self.endpoint.receipt_id() {
            let _ = fs::remove_file(&self.path);
        }
    }
}

/// Receipt registration or resolution failure.
#[derive(Debug, thiserror::Error)]
pub enum LiveRuntimeReceiptError {
    /// Opaque endpoint has an invalid scheme or identifier.
    #[error("invalid Supercode live-runtime endpoint")]
    InvalidEndpoint,
    /// Receipt no longer exists or its owning process is gone.
    #[error("Supercode live runtime is no longer available")]
    NotLive,
    /// Receipt exists but belongs to another source session or workspace.
    #[error("Supercode live-runtime receipt does not match the requested session")]
    IdentityMismatch,
    /// Receipt storage failed.
    #[error("Supercode live-runtime receipt I/O failed: {0}")]
    Io(#[from] std::io::Error),
    /// Receipt data was malformed or from another schema version.
    #[error("Supercode live-runtime receipt is invalid: {0}")]
    InvalidReceipt(String),
    /// More than one active receipt has the requested stable runtime id.
    #[error("multiple live runtimes share id `{0}`")]
    AmbiguousRuntime(String),
}

#[derive(Serialize, Deserialize)]
struct Receipt {
    schema: String,
    receipt_id: String,
    runtime_session_id: String,
    source: LiveRuntimeSource,
    base_url: String,
    token: String,
    pid: u32,
    created_at_ms: u128,
    #[serde(default)]
    metadata: LiveRuntimeMetadata,
}

/// Register an authenticated loopback runtime and return its opaque endpoint.
pub fn register_live_runtime(
    runtime_session_id: impl Into<String>,
    source: LiveRuntimeSource,
    base_url: impl Into<String>,
    token: impl Into<String>,
) -> Result<LiveRuntimeRegistration, LiveRuntimeReceiptError> {
    register_live_runtime_with_metadata(
        runtime_session_id,
        source,
        base_url,
        token,
        LiveRuntimeMetadata {
            endpoint_capabilities: vec!["http".into(), "acp".into()],
            ..LiveRuntimeMetadata::default()
        },
    )
}

/// Register a runtime with the static fields used by list/describe output.
pub fn register_live_runtime_with_metadata(
    runtime_session_id: impl Into<String>,
    source: LiveRuntimeSource,
    base_url: impl Into<String>,
    token: impl Into<String>,
    metadata: LiveRuntimeMetadata,
) -> Result<LiveRuntimeRegistration, LiveRuntimeReceiptError> {
    let runtime_session_id = runtime_session_id.into();
    let base_url = base_url.into();
    let token = token.into();
    if runtime_session_id.trim().is_empty()
        || source.harness.trim().is_empty()
        || source.session_id.trim().is_empty()
        || token.is_empty()
        || !is_loopback_http(&base_url)
    {
        return Err(LiveRuntimeReceiptError::InvalidReceipt(
            "missing identity/token or non-loopback HTTP address".into(),
        ));
    }

    let mut random = [0_u8; 16];
    getrandom::getrandom(&mut random).map_err(|error| {
        LiveRuntimeReceiptError::InvalidReceipt(format!("OS randomness unavailable: {error}"))
    })?;
    let receipt_id = random.iter().map(|byte| format!("{byte:02x}")).collect();
    let endpoint = LiveRuntimeEndpoint(format!("{ENDPOINT_PREFIX}{receipt_id}"));
    let receipt = Receipt {
        schema: RECEIPT_SCHEMA.into(),
        receipt_id,
        runtime_session_id,
        source: LiveRuntimeSource {
            workspace: normalized_path(&source.workspace),
            ..source
        },
        base_url,
        token,
        pid: std::process::id(),
        created_at_ms: now_ms(),
        metadata,
    };
    let directory = receipt_directory();
    fs::create_dir_all(&directory)?;
    #[cfg(unix)]
    fs::set_permissions(&directory, fs::Permissions::from_mode(0o700))?;
    let path = directory.join(format!("{}.json", endpoint.receipt_id()));
    let temporary = directory.join(format!(
        ".{}.{}.tmp",
        endpoint.receipt_id(),
        std::process::id()
    ));
    let bytes = serde_json::to_vec(&receipt)
        .map_err(|error| LiveRuntimeReceiptError::InvalidReceipt(error.to_string()))?;
    let mut options = OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    let mut file = options.open(&temporary)?;
    file.write_all(&bytes)?;
    file.sync_all()?;
    fs::rename(&temporary, &path)?;
    Ok(LiveRuntimeRegistration { endpoint, path })
}

/// List every reconciled live runtime without exposing its bearer token or
/// loopback address. Dead-process receipts are removed as part of the read.
pub fn list_live_runtimes() -> Result<Vec<LiveRuntimeRecord>, LiveRuntimeReceiptError> {
    let mut records = read_receipts()?
        .into_iter()
        .map(|receipt| LiveRuntimeRecord {
            endpoint: LiveRuntimeEndpoint(format!("{ENDPOINT_PREFIX}{}", receipt.receipt_id)),
            runtime_session_id: receipt.runtime_session_id,
            source: receipt.source,
            pid: receipt.pid,
            created_at_ms: receipt.created_at_ms,
            metadata: receipt.metadata,
        })
        .collect::<Vec<_>>();
    records.sort_by(|left, right| {
        right
            .created_at_ms
            .cmp(&left.created_at_ms)
            .then_with(|| left.runtime_session_id.cmp(&right.runtime_session_id))
    });
    Ok(records)
}

/// Resolve one stable runtime id, requiring an explicit choice if stale or
/// concurrent registrations would otherwise make attachment ambiguous.
pub fn find_live_runtime(
    runtime_session_id: &str,
) -> Result<Option<LiveRuntimeRecord>, LiveRuntimeReceiptError> {
    let mut matches = list_live_runtimes()?
        .into_iter()
        .filter(|record| record.runtime_session_id == runtime_session_id)
        .collect::<Vec<_>>();
    match matches.len() {
        0 => Ok(None),
        1 => Ok(matches.pop()),
        _ => Err(LiveRuntimeReceiptError::AmbiguousRuntime(
            runtime_session_id.into(),
        )),
    }
}

/// Remove only a stale attachment receipt. Canonical, sidecar, source-native,
/// and exported session data are never addressed by this operation.
pub fn forget_live_runtime(endpoint: &LiveRuntimeEndpoint) -> Result<(), LiveRuntimeReceiptError> {
    let path = receipt_directory().join(format!("{}.json", endpoint.receipt_id()));
    match fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error.into()),
    }
}

/// Find the newest live receipt matching a discovered source session.
pub fn discover_live_runtime(
    source: &LiveRuntimeSource,
) -> Result<Option<LiveRuntimeEndpoint>, LiveRuntimeReceiptError> {
    let mut matches = read_receipts()?
        .into_iter()
        .filter(|receipt| source_matches(&receipt.source, source))
        .collect::<Vec<_>>();
    matches.sort_by_key(|receipt| std::cmp::Reverse(receipt.created_at_ms));
    Ok(matches
        .first()
        .map(|receipt| LiveRuntimeEndpoint(format!("{ENDPOINT_PREFIX}{}", receipt.receipt_id))))
}

/// Resolve an opaque endpoint and verify that it belongs to `expected`.
pub fn resolve_live_runtime(
    endpoint: &LiveRuntimeEndpoint,
    expected: &LiveRuntimeSource,
) -> Result<ResolvedLiveRuntime, LiveRuntimeReceiptError> {
    let path = receipt_directory().join(format!("{}.json", endpoint.receipt_id()));
    let receipt = read_receipt(&path)?.ok_or(LiveRuntimeReceiptError::NotLive)?;
    if receipt.receipt_id != endpoint.receipt_id() || !source_matches(&receipt.source, expected) {
        return Err(LiveRuntimeReceiptError::IdentityMismatch);
    }
    Ok(ResolvedLiveRuntime {
        endpoint: endpoint.clone(),
        runtime_session_id: receipt.runtime_session_id,
        source: receipt.source,
        base_url: receipt.base_url,
        token: receipt.token,
        pid: receipt.pid,
    })
}

fn read_receipts() -> Result<Vec<Receipt>, LiveRuntimeReceiptError> {
    let directory = receipt_directory();
    let Ok(entries) = fs::read_dir(&directory) else {
        return Ok(Vec::new());
    };
    let mut receipts = Vec::new();
    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|value| value.to_str()) != Some("json") {
            continue;
        }
        // Discovery is best-effort across concurrently removed, stale, or
        // malformed receipts. Attachment re-reads and validates the selected
        // receipt strictly before using any secret it contains.
        if let Ok(Some(receipt)) = read_receipt(&path) {
            receipts.push(receipt);
        }
    }
    Ok(receipts)
}

fn read_receipt(path: &Path) -> Result<Option<Receipt>, LiveRuntimeReceiptError> {
    let bytes = match fs::read(path) {
        Ok(bytes) => bytes,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(error) => return Err(error.into()),
    };
    let receipt: Receipt = serde_json::from_slice(&bytes)
        .map_err(|error| LiveRuntimeReceiptError::InvalidReceipt(error.to_string()))?;
    if receipt.schema != RECEIPT_SCHEMA || !is_loopback_http(&receipt.base_url) {
        return Err(LiveRuntimeReceiptError::InvalidReceipt(
            "unsupported schema or non-loopback address".into(),
        ));
    }
    if !process_is_live(receipt.pid) {
        let _ = fs::remove_file(path);
        return Ok(None);
    }
    Ok(Some(receipt))
}

fn receipt_directory() -> PathBuf {
    crate::agent::global_instructions_dir().join("live-runtimes")
}

#[cfg(test)]
pub(crate) fn test_environment_lock() -> MutexGuard<'static, ()> {
    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
    LOCK.get_or_init(|| Mutex::new(()))
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

fn source_matches(left: &LiveRuntimeSource, right: &LiveRuntimeSource) -> bool {
    left.harness == right.harness
        && left.session_id == right.session_id
        && normalized_path(&left.workspace) == normalized_path(&right.workspace)
}

fn normalized_path(path: &Path) -> PathBuf {
    fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}

fn is_loopback_http(value: &str) -> bool {
    let Some(authority) = value
        .strip_prefix("http://")
        .and_then(|rest| rest.split('/').next())
    else {
        return false;
    };
    let host = authority
        .strip_prefix('[')
        .and_then(|rest| rest.split(']').next())
        .unwrap_or_else(|| authority.split(':').next().unwrap_or_default());
    matches!(host, "127.0.0.1" | "localhost" | "::1")
}

fn now_ms() -> u128 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis()
}

#[cfg(unix)]
fn process_is_live(pid: u32) -> bool {
    // SAFETY: signal 0 performs only a liveness/permission check.
    let result = unsafe { libc::kill(pid as libc::pid_t, 0) };
    result == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}

#[cfg(not(unix))]
fn process_is_live(pid: u32) -> bool {
    // Windows has no signal-0 equivalent in the current dependency set. A
    // receipt is still authenticated and identity-checked at HTTP connect.
    pid == std::process::id()
}

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

    #[test]
    fn receipt_is_opaque_private_and_identity_scoped() {
        let _guard = test_environment_lock();
        let root = std::env::temp_dir().join(format!(
            "supercode-live-receipt-{}-{}",
            std::process::id(),
            now_ms()
        ));
        let workspace = root.join("project");
        fs::create_dir_all(&workspace).unwrap();
        let workspace = fs::canonicalize(workspace).unwrap();
        std::env::set_var("SUPERCODE_HOME", &root);
        let source = LiveRuntimeSource {
            harness: "grok".into(),
            session_id: "source-1".into(),
            workspace: workspace.clone(),
        };
        let registration = register_live_runtime(
            "runtime-1",
            source.clone(),
            "http://127.0.0.1:43123",
            "secret-token",
        )
        .unwrap();
        assert!(registration
            .endpoint()
            .as_str()
            .starts_with(ENDPOINT_PREFIX));
        assert!(!registration.endpoint().as_str().contains("secret-token"));
        assert_eq!(
            discover_live_runtime(&source).unwrap().as_ref(),
            Some(registration.endpoint())
        );
        let records = list_live_runtimes().unwrap();
        assert_eq!(records.len(), 1);
        assert_eq!(records[0].runtime_session_id, "runtime-1");
        assert_eq!(records[0].source, source);
        assert_eq!(records[0].metadata.endpoint_capabilities, ["http", "acp"]);
        assert_eq!(
            find_live_runtime("runtime-1").unwrap().as_ref(),
            records.first()
        );
        let resolved = resolve_live_runtime(registration.endpoint(), &source).unwrap();
        assert_eq!(resolved.runtime_session_id, "runtime-1");
        assert_eq!(resolved.token, "secret-token");
        let wrong = LiveRuntimeSource {
            session_id: "other".into(),
            ..source.clone()
        };
        assert!(matches!(
            resolve_live_runtime(registration.endpoint(), &wrong),
            Err(LiveRuntimeReceiptError::IdentityMismatch)
        ));
        let receipt_path =
            receipt_directory().join(format!("{}.json", registration.endpoint().receipt_id()));
        #[cfg(unix)]
        {
            assert_eq!(
                fs::metadata(&receipt_path).unwrap().permissions().mode() & 0o777,
                0o600
            );
            assert_eq!(
                fs::metadata(receipt_directory())
                    .unwrap()
                    .permissions()
                    .mode()
                    & 0o777,
                0o700
            );
        }
        drop(registration);
        assert!(!receipt_path.exists());
        std::env::remove_var("SUPERCODE_HOME");
        fs::remove_dir_all(root).ok();
    }
}