supercode-harness 0.4.19

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
546
//! ORCH-14 — the `channel` noun at the OBSERVED tier: one uniform row per
//! transport + account a gateway harness is reachable on, read from the
//! harness's own config file and never written.
//!
//! Two sources, one row shape:
//!
//! * **Hermes** — the platform blocks of `HERMES_HOME/config.yaml`, keyed by
//!   `gateway.config.Platform` values (`telegram`, `slack`, `discord`,
//!   `api_server`, `webhook`, …) and carrying `enabled`, `extra.*` and the
//!   platform's own credential keys. `load_gateway_config` merges FOUR
//!   places into one map, so all four are read — see [`hermes_rows`]. Hermes
//!   also enables a platform from the ENVIRONMENT alone
//!   (`_apply_env_overrides`), so a platform with no config block but with
//!   its credential env var set is reported too — by the var's PRESENCE,
//!   never its value.
//! * **OpenClaw** — `channels.<name>` in `<openclaw home>/openclaw.json`
//!   (JSON5), with `channels.<name>.accounts` splitting a channel into one
//!   row per account id.
//!
//! **Claude Code is deliberately absent.** Its channels are MCP servers that
//! declare the channel capability over the MCP protocol at connect time
//! (`docs/composable-harness/inventory/claude-code.md` §7 "Channels": the
//! channel contract is "capability declaration, notification events, reply
//! tools, sender gating, permission relay"). Nothing in `settings.json` or
//! `.mcp.json` marks a server as a channel — `channelsEnabled` and
//! `allowedChannelPlugins` are enterprise GATES, not declarations — so
//! supercode cannot tell a channel server from any other MCP server without
//! connecting to it. Guessing a key name would fabricate rows, so
//! `claude-code` is refused with [`ChannelError::UnsupportedHarness`].
//!
//! # Secrecy
//!
//! This module never emits a token, key, secret or password, and never reads
//! one to decide anything but PRESENCE. Two mechanisms enforce that:
//!
//! * values are read only for key names on [`HERMES_ACCOUNT_KEYS`] /
//!   [`OPENCLAW_ACCOUNT_KEYS`] — public identifiers (`app_id`, `client_id`,
//!   `phone_number_id`, …), never a credential;
//! * `configured` is decided by [`is_credential_key`], which looks at the
//!   key NAME only, and by `std::env::var_os(..).is_some()` for the env
//!   fallbacks — the value never leaves the check.
//!
//! Everything here is read-only: no harness home is created or written. A
//! harness with no channel concept is refused, never answered with an empty
//! list.

use std::collections::BTreeMap;
use std::path::Path;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::{HarnessHomes, HarnessId};

/// Stable row schema shared by Rust, JSON-RPC, the SDKs, and the CLI.
pub const CHANNELS_SCHEMA: &str = "supercode.channels.v1";

/// Harnesses with a channel concept supercode reads, in product order.
/// Every other harness id is [`ChannelError::UnsupportedHarness`].
pub const CHANNEL_HARNESSES: &[&str] = &[
    HarnessId::HERMES,
    HarnessId::OPENCLAW,
    HarnessId::ORCHESTRATOR,
];

/// Key names whose VALUE is a public account identifier, safe to emit. Read
/// from a Hermes platform block's `extra` first, then its top level. Nothing
/// outside this list is ever read for a value.
///
/// Transcribed from the identifiers `gateway/config.py::_apply_env_overrides`
/// stores in `PlatformConfig.extra` (hermes-agent 0.21.0 on the build box):
/// `client_id` (DingTalk), `app_id` (Feishu, QQ, Yuanbao), `bot_id` (WeCom),
/// `corp_id` (WeCom callback), `phone_number_id` (WhatsApp Cloud), `account`
/// (Signal), `account_id` (Weixin).
pub const HERMES_ACCOUNT_KEYS: &[&str] = &[
    "account",
    "account_id",
    "app_id",
    "bot_id",
    "client_id",
    "corp_id",
    "phone_number_id",
    "user_id",
];

/// Key names whose VALUE is a public account identifier in an OpenClaw
/// channel entry. The `accounts` MAP's keys are account ids in their own
/// right and are used first; this list covers a single-account entry that
/// names its account inline.
pub const OPENCLAW_ACCOUNT_KEYS: &[&str] = &[
    "accountId",
    "account_id",
    "account",
    "teamId",
    "appId",
    "userId",
];

/// Env vars whose PRESENCE enables a Hermes platform, per platform.
///
/// Transcribed from `gateway/config.py::_ENV_ENABLE_CREDENTIALS`
/// ("Env var(s) whose presence drives each platform's env-enable branch")
/// plus the `api_server` branch, whose credential is `API_SERVER_KEY` and
/// which that map does not carry because its branch is terminal.
///
/// The bool mirrors the branch's own conjunction: WhatsApp Cloud, e-mail,
/// DingTalk, Feishu, WeCom, WeCom callback, BlueBubbles and Yuanbao require
/// BOTH of their vars (`if a and b:`); Matrix, Weixin and QQ accept EITHER
/// (`if a or b:`); single-var platforms read the same under both.
const HERMES_ENV_CREDENTIALS: &[(&str, &[&str], bool)] = &[
    ("telegram", &["TELEGRAM_BOT_TOKEN"], false),
    ("discord", &["DISCORD_BOT_TOKEN"], false),
    ("slack", &["SLACK_BOT_TOKEN"], false),
    (
        "whatsapp_cloud",
        &[
            "WHATSAPP_CLOUD_PHONE_NUMBER_ID",
            "WHATSAPP_CLOUD_ACCESS_TOKEN",
        ],
        true,
    ),
    ("signal", &["SIGNAL_HTTP_URL"], false),
    ("mattermost", &["MATTERMOST_TOKEN"], false),
    ("matrix", &["MATRIX_ACCESS_TOKEN", "MATRIX_PASSWORD"], false),
    ("homeassistant", &["HASS_TOKEN"], false),
    (
        "email",
        &[
            "EMAIL_ADDRESS",
            "EMAIL_PASSWORD",
            "EMAIL_IMAP_HOST",
            "EMAIL_SMTP_HOST",
        ],
        true,
    ),
    ("sms", &["TWILIO_ACCOUNT_SID"], false),
    (
        "dingtalk",
        &["DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"],
        true,
    ),
    ("feishu", &["FEISHU_APP_ID", "FEISHU_APP_SECRET"], true),
    ("wecom", &["WECOM_BOT_ID", "WECOM_SECRET"], true),
    (
        "wecom_callback",
        &["WECOM_CALLBACK_CORP_ID", "WECOM_CALLBACK_CORP_SECRET"],
        true,
    ),
    ("weixin", &["WEIXIN_TOKEN", "WEIXIN_ACCOUNT_ID"], false),
    (
        "bluebubbles",
        &["BLUEBUBBLES_SERVER_URL", "BLUEBUBBLES_PASSWORD"],
        true,
    ),
    ("qqbot", &["QQ_APP_ID", "QQ_CLIENT_SECRET"], false),
    ("yuanbao", &["YUANBAO_APP_ID", "YUANBAO_APP_SECRET"], true),
    ("relay", &["GATEWAY_RELAY_URL"], false),
    ("api_server", &["API_SERVER_KEY"], false),
];

/// Every key name that parses as a Hermes `Platform`, so a config key can be
/// told apart from an ordinary setting.
///
/// The built-in members of `gateway/config.py::Platform` (hermes-agent 0.21.0
/// on the build box) plus the bundled plugin adapters, which `Platform`
/// admits through `_missing_` after scanning `plugins/platforms/`. `local` is
/// omitted on purpose: it is Hermes's own CLI/TUI surface, not a transport
/// into an external identity space, and `load_gateway_config`'s shared-key
/// loop skips it too.
pub const HERMES_PLATFORMS: &[&str] = &[
    "a2a",
    "api_server",
    "bluebubbles",
    "buzz",
    "dingtalk",
    "discord",
    "email",
    "feishu",
    "google_chat",
    "homeassistant",
    "irc",
    "line",
    "matrix",
    "mattermost",
    "msgraph_webhook",
    "ntfy",
    "photon",
    "qqbot",
    "raft",
    "relay",
    "signal",
    "simplex",
    "slack",
    "sms",
    "teams",
    "telegram",
    "webhook",
    "wecom",
    "wecom_callback",
    "weixin",
    "whatsapp",
    "whatsapp_cloud",
    "yuanbao",
];

/// Whether a live probe answered, and what it said.
///
/// At the OBSERVED tier every row answers [`ChannelStatus::Unknown`]: both
/// harnesses report a channel's connection state from a RUNNING gateway
/// (`hermes gateway status`, `openclaw channels status` over the Gateway
/// socket), which is the gateway-health concept, not this one. Reporting
/// `up` from a config file would be a claim about a process nobody asked.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChannelStatus {
    /// A probe reached the channel's transport.
    Up,
    /// A probe ran and the channel's transport did not answer.
    Down,
    /// No cheap local probe exists for this harness's channels.
    Unknown,
}

impl ChannelStatus {
    /// Stable wire spelling, identical to the serde representation.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Up => "up",
            Self::Down => "down",
            Self::Unknown => "unknown",
        }
    }
}

/// One transport + account a harness is reachable on, uniform across
/// harnesses.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChannelRow {
    /// Unique handle within the harness: the transport id for a single
    /// account (`telegram`), `<transport>/<account>` when the harness's
    /// config splits one transport across several accounts.
    pub name: String,
    /// Owning harness id.
    pub harness: String,
    /// Transport id: a Hermes `Platform` value or an OpenClaw channel key
    /// (`telegram`, `slack`, `discord`, `api_server`, `webhook`, …).
    pub kind: String,
    /// Public account id or label; `None` when the config names none. Never
    /// a token, key or secret.
    pub account: Option<String>,
    /// Whether the harness would start this channel. `None` when the config
    /// does not say and the harness's own default is not stated in a source
    /// this workspace pins.
    pub enabled: Option<bool>,
    /// Whether the entry has what the harness needs to start it, judged
    /// only by the PRESENCE of a credential key or credential env var.
    pub configured: bool,
    /// Connection state; always [`ChannelStatus::Unknown`] at this tier.
    pub status: ChannelStatus,
    /// Discovered sessions whose surface platform is this row's `kind`;
    /// `None` when discovery could not run. Rows that share a `kind` across
    /// accounts share the count — a session key names the transport, not
    /// the account.
    pub sessions: Option<u64>,
}

/// Read-only channel failures.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ChannelError {
    /// The harness has no channel concept supercode reads.
    #[error("harness `{harness}` has no channel concept (channels exist for: {})", CHANNEL_HARNESSES.join(", "))]
    UnsupportedHarness {
        /// The harness id that was asked for.
        harness: String,
    },
    /// The harness has channels, but not this one.
    #[error("`{harness}` has no channel `{name}`")]
    NotFound {
        /// Harness that was searched.
        harness: String,
        /// Channel name that was not found.
        name: String,
    },
}

/// List every channel supercode can see, optionally restricted to one
/// harness. Rows are ordered by harness (as in [`CHANNEL_HARNESSES`]) then
/// by name.
pub fn list_channels(
    homes: &HarnessHomes,
    harness: Option<&str>,
) -> Result<Vec<ChannelRow>, ChannelError> {
    if let Some(harness) = harness {
        if !CHANNEL_HARNESSES.contains(&harness) {
            return Err(ChannelError::UnsupportedHarness {
                harness: harness.to_string(),
            });
        }
    }
    use supercode_interchange::orchestration::codec::{
        from_hermes, from_openclaw, load_home, Flavor,
    };
    let mut rows = Vec::new();
    for id in CHANNEL_HARNESSES {
        if harness.is_some_and(|requested| requested != *id) {
            continue;
        }
        let sessions = session_counts(homes, id);
        match *id {
            HarnessId::HERMES => {
                if let Ok(loaded) = from_hermes(homes.hermes.parent().unwrap_or(Path::new("."))) {
                    // Hermes's platforms are the root home's
                    rows.extend(hermes_shaped_rows(
                        HarnessId::HERMES,
                        &loaded.orchestration.profiles["default"],
                        sessions.as_ref(),
                        true,
                    ));
                }
            }
            HarnessId::OPENCLAW => {
                if let Ok(loaded) = from_openclaw(&homes.openclaw) {
                    rows.extend(openclaw_rows(&loaded, sessions.as_ref()));
                }
            }
            HarnessId::ORCHESTRATOR => {
                if let Ok(loaded) = load_home(&homes.orchestrator, Flavor::Orchestrator) {
                    let mut names: Vec<&String> = loaded.orchestration.profiles.keys().collect();
                    names.sort_by_key(|name| (name.as_str() != "default", name.as_str()));
                    for name in names {
                        rows.extend(hermes_shaped_rows(
                            HarnessId::ORCHESTRATOR,
                            &loaded.orchestration.profiles[name],
                            sessions.as_ref(),
                            false,
                        ));
                    }
                }
            }
            _ => {}
        }
    }
    Ok(rows)
}

/// Read one channel's row by harness and name. `status` is
/// [`ChannelStatus::Unknown`] at this tier for every harness; the verb
/// exists so the noun is complete and the driven tier has one door to fill.
pub fn channel_status(
    homes: &HarnessHomes,
    harness: &str,
    name: &str,
) -> Result<ChannelRow, ChannelError> {
    list_channels(homes, Some(harness))?
        .into_iter()
        .find(|row| row.name == name)
        .ok_or_else(|| ChannelError::NotFound {
            harness: harness.to_string(),
            name: name.to_string(),
        })
}

// ---------------------------------------------------------------------------
// Session counts
// ---------------------------------------------------------------------------

/// Sessions per surface platform, from the SAME discovery rows
/// `supercode sessions list` shows. `None` means discovery failed, which is
/// unknown — never zero.
fn session_counts(homes: &HarnessHomes, harness: &str) -> Option<BTreeMap<String, u64>> {
    let query = crate::DiscoveryQuery {
        harnesses: vec![HarnessId::new(harness)],
        homes: homes.clone(),
        ..Default::default()
    };
    let sessions = crate::HarnessCatalog::new().discover(&query).ok()?;
    let mut counts: BTreeMap<String, u64> = BTreeMap::new();
    for session in sessions {
        if let Some(platform) = session
            .nouns
            .surface
            .as_ref()
            .and_then(|surface| surface.platform.as_ref())
        {
            *counts.entry(platform.clone()).or_default() += 1;
        }
    }
    Some(counts)
}

// ---------------------------------------------------------------------------
// Credentials — presence only
// ---------------------------------------------------------------------------

/// Whether the env credential(s) for a Hermes platform are present. Only
/// presence is tested; no value is read. `None` means Hermes lists no env
/// credential for this platform at all.
fn hermes_env_credentials_present(platform: &str) -> Option<bool> {
    let (_, vars, all) = HERMES_ENV_CREDENTIALS
        .iter()
        .find(|(name, _, _)| *name == platform)?;
    let present = |name: &&str| std::env::var_os(name).is_some();
    Some(if *all {
        vars.iter().all(present)
    } else {
        vars.iter().any(present)
    })
}

// ---------------------------------------------------------------------------
// Hermes
// ---------------------------------------------------------------------------

/// Hermes channels are the platform blocks of `HERMES_HOME/config.yaml`.
///
/// `load_gateway_config` merges FOUR places into one platform map, later
/// winning (`gateway/config.py::_merge_platform_map` and the shared-key loop
/// after it) — verified against the real `~/.hermes/config.yaml` on the build
/// box, which writes NONE of the first three and would have read as empty had
/// only the documented `platforms:` key been honoured:
///
/// 1. `gateway.platforms.<platform>`
/// 2. `platforms.<platform>` (the shape the ORCH-5 probe writes)
/// 3. `gateway.<platform>` for any key that parses as a `Platform` value
/// 4. a TOP-LEVEL `<platform>:` block, which is the only one whose `enabled`
///    is treated as explicit (`enabled_was_explicit = _cfg_toplevel and …`)
///
/// [`HERMES_PLATFORMS`] is what makes 3 and 4 decidable: a key is a platform
/// block only when its name is a `Platform` value. A platform Hermes would
/// enable from the environment alone (`_apply_env_overrides`) is listed too,
/// so an env-only install is not reported as empty.
///
/// `state_db` is `HarnessHomes::hermes` (`HERMES_HOME/state.db`).
/// A profile's platforms as the orchestration codec reads `config.yaml`:
/// one row per configured channel (credentials are the codec's secret
/// refs; the account id sits in the channel's extras), plus — for Hermes's
/// root home — the platforms the process environment alone enables.
fn hermes_shaped_rows(
    harness: &str,
    profile: &supercode_interchange::orchestration::Profile,
    sessions: Option<&BTreeMap<String, u64>>,
    env_fallback: bool,
) -> Vec<ChannelRow> {
    let mut names: Vec<String> = profile.channels.keys().cloned().collect();
    if env_fallback {
        for (platform, _, _) in HERMES_ENV_CREDENTIALS {
            if hermes_env_credentials_present(platform) == Some(true)
                && !names.iter().any(|name| name == platform)
            {
                names.push((*platform).to_string());
            }
        }
    }
    names.sort();
    names.dedup();
    names
        .into_iter()
        .map(|name| {
            let channel = profile.channels.get(&name);
            let env_present = env_fallback
                .then(|| hermes_env_credentials_present(&name))
                .flatten();
            let enabled = match channel {
                Some(channel) => channel.enabled,
                None => env_present == Some(true),
            };
            let configured = env_present == Some(true)
                || channel.is_some_and(|channel| !channel.credentials.is_empty())
                || env_present.is_none();
            let account = channel.and_then(|channel| {
                HERMES_ACCOUNT_KEYS.iter().find_map(|key| {
                    channel
                        .extra
                        .get(*key)
                        .or_else(|| channel.extra.get(&format!("extra.{key}")))
                        .and_then(|v| match v {
                            Value::String(s) => Some(s.clone()),
                            Value::Number(n) => Some(n.to_string()),
                            _ => None,
                        })
                        .filter(|value| !value.is_empty())
                })
            });
            ChannelRow {
                name: name.clone(),
                harness: harness.to_string(),
                kind: name.clone(),
                account,
                enabled: Some(enabled),
                configured,
                status: ChannelStatus::Unknown,
                sessions: sessions.map(|counts| counts.get(&name).copied().unwrap_or(0)),
            }
        })
        .collect()
}

/// OpenClaw's channels as the orchestration codec reads `openclaw.json`:
/// one row per channel or per account (`<kind>/<account>`), the kind,
/// account and where `enabled` was set riding on the channel's extras.
fn openclaw_rows(
    loaded: &supercode_interchange::orchestration::codec::OpenclawLoaded,
    sessions: Option<&BTreeMap<String, u64>>,
) -> Vec<ChannelRow> {
    loaded.orchestration.profiles["default"]
        .channels
        .iter()
        .map(|(name, channel)| {
            let text = |key: &str| {
                channel
                    .extra
                    .get(key)
                    .and_then(Value::as_str)
                    .map(str::to_string)
            };
            let kind = text("kind").unwrap_or_else(|| name.clone());
            ChannelRow {
                name: name.clone(),
                harness: HarnessId::OPENCLAW.to_string(),
                kind: kind.clone(),
                account: text("accountId"),
                enabled: text("enabled_on").map(|_| channel.enabled),
                configured: !channel.credentials.is_empty(),
                status: ChannelStatus::Unknown,
                sessions: sessions.map(|counts| counts.get(&kind).copied().unwrap_or(0)),
            }
        })
        .collect()
}

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

    #[test]
    fn unsupported_harness_is_refused_not_silently_empty() {
        let error = list_channels(&HarnessHomes::default(), Some(HarnessId::CLAUDE_CODE))
            .expect_err("claude-code channels are MCP-protocol declarations");
        assert_eq!(
            error,
            ChannelError::UnsupportedHarness {
                harness: HarnessId::CLAUDE_CODE.to_string()
            }
        );
    }
}