supercode-harness 0.4.20

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
//! ORCH-15 (observed tier): the routing noun — which profile / agent a
//! surface tuple resolves to.
//!
//! * **Hermes** — `gateway.profile_routes` in `HERMES_HOME/config.yaml`: a list
//!   of `{platform, guild_id?, chat_id?, thread_id?, profile}` entries, most
//!   specific wins (thread 8 > chat 4 > guild 2 > platform 0), the default
//!   profile otherwise (`docs/HERMES-IDEAL-SUPPORT-DESIGN.md` §1).
//! * **OpenClaw** — `bindings[]` in `openclaw.json`: `{agentId, match{channel,
//!   accountId, peer{kind,id}, guildId, teamId, roles}}`, evaluated exact peer →
//!   parent peer → wildcard peer → guild+roles → guild → team → account →
//!   channel → default agent (§1b).
//!
//! Read-only. Editing a route stays the harness's own config edit.

use std::path::Path;

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

use crate::catalog::HarnessHomes;
use crate::HarnessId;

/// Wire schema of `harness.v1.routes.list`.
pub const ROUTES_SCHEMA: &str = "supercode.routes.v1";

/// Harnesses with a routing concept.
pub const ROUTE_HARNESSES: &[&str] = &[
    HarnessId::HERMES,
    HarnessId::OPENCLAW,
    HarnessId::ORCHESTRATOR,
];

/// The match side of a route, in the shared-noun vocabulary.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RouteMatch {
    /// Transport / platform (`slack`, `telegram`, …), or `None` for a catch-all.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub platform: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub account: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub guild: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub team: Option<String>,
    /// Chat / channel / group id, or the peer id (OpenClaw).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chat_id: Option<String>,
    /// OpenClaw peer kind (`user` | `channel` | `group` | `thread`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub peer_kind: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub thread_id: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub roles: Vec<String>,
}

/// One routing entry.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RouteRow {
    pub harness: String,
    /// Target profile (Hermes) or agent id (OpenClaw).
    pub target: String,
    #[serde(rename = "match")]
    pub matcher: RouteMatch,
    /// The harness's own precedence rank; higher wins.
    pub specificity: u32,
    /// The fallback route (no match fields).
    pub default: bool,
    /// Config file the route was read from.
    pub source: String,
}

/// Why a listing was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RouteError {
    /// The harness has no routing concept.
    UnsupportedHarness { harness: String },
}

impl std::fmt::Display for RouteError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RouteError::UnsupportedHarness { harness } => write!(
                f,
                "`{harness}` has no routing concept; `routes.list` is supported for: {}",
                ROUTE_HARNESSES.join(", ")
            ),
        }
    }
}

impl std::error::Error for RouteError {}

/// List routes, optionally for one harness and/or one target.
pub fn list_routes(
    homes: &HarnessHomes,
    harness: Option<&str>,
    target: Option<&str>,
) -> Result<Vec<RouteRow>, RouteError> {
    let harnesses: Vec<&str> = match harness {
        Some(id) if ROUTE_HARNESSES.contains(&id) => vec![id],
        Some(id) => {
            return Err(RouteError::UnsupportedHarness {
                harness: id.to_string(),
            })
        }
        None => ROUTE_HARNESSES.to_vec(),
    };
    use supercode_interchange::orchestration::codec::{
        from_hermes, from_openclaw, load_home, Flavor,
    };
    let mut rows = Vec::new();
    for id in harnesses {
        match id {
            HarnessId::HERMES => {
                if let Ok(loaded) = from_hermes(homes.hermes.parent().unwrap_or(Path::new("."))) {
                    rows.extend(hermes_shaped_rows(HarnessId::HERMES, &loaded.orchestration));
                }
            }
            HarnessId::OPENCLAW => {
                if let Ok(loaded) = from_openclaw(&homes.openclaw) {
                    rows.extend(openclaw_rows(&loaded));
                }
            }
            HarnessId::ORCHESTRATOR => {
                if let Ok(loaded) = load_home(&homes.orchestrator, Flavor::Orchestrator) {
                    rows.extend(hermes_shaped_rows(
                        HarnessId::ORCHESTRATOR,
                        &loaded.orchestration,
                    ));
                }
            }
            _ => {}
        }
    }
    if let Some(target) = target {
        rows.retain(|row| row.target == target);
    }
    rows.sort_by(|a, b| {
        a.harness
            .cmp(&b.harness)
            .then(b.specificity.cmp(&a.specificity))
            .then(a.target.cmp(&b.target))
    });
    Ok(rows)
}

/// Read `gateway.profile_routes` out of one Hermes-shaped home.
///
/// `home` is the folder holding `config.yaml` (Hermes: HERMES_HOME, the
/// parent of `HarnessHomes::hermes`; the orchestrator: one profile folder).
/// `with_default` emits the catch-all row for the home that owns unmatched
/// traffic.
/// The `profile_routes` of a Hermes-shaped home as the orchestration codec
/// reads them: every profile's routes (the root's for Hermes, each folder's
/// for the orchestrator) weighted by what they name, plus the root's
/// catch-all row.
fn hermes_shaped_rows(
    harness: &str,
    orchestration: &supercode_interchange::orchestration::Orchestration,
) -> Vec<RouteRow> {
    let mut rows = Vec::new();
    let mut names: Vec<&String> = orchestration.profiles.keys().collect();
    names.sort_by_key(|name| (name.as_str() != "default", name.as_str()));
    for name in names {
        let profile = &orchestration.profiles[name];
        let source = profile.dir.join("config.yaml").display().to_string();
        for route in &profile.routes {
            let matcher = RouteMatch {
                platform: Some(route.matches.platform.clone()).filter(|p| !p.is_empty()),
                guild: route.matches.guild_id.clone(),
                chat_id: route.matches.chat_id.clone(),
                thread_id: route.matches.thread_id.clone(),
                ..RouteMatch::default()
            };
            let specificity = matcher.thread_id.as_ref().map_or(0, |_| 8)
                + matcher.chat_id.as_ref().map_or(0, |_| 4)
                + matcher.guild.as_ref().map_or(0, |_| 2);
            rows.push(RouteRow {
                harness: harness.into(),
                target: route.profile.clone(),
                matcher,
                specificity,
                default: false,
                source: source.clone(),
            });
        }
        if name == "default" {
            rows.push(RouteRow {
                harness: harness.into(),
                target: "default".into(),
                matcher: RouteMatch::default(),
                specificity: 0,
                default: true,
                source,
            });
        }
    }
    rows
}

/// OpenClaw's `bindings` as the orchestration codec reads them (the match
/// vocabulary the orchestration does not model — account, team, peer kind,
/// roles — rides in the route's residue), weighted by the documented
/// cascade, plus the default agent's catch-all row.
fn openclaw_rows(
    loaded: &supercode_interchange::orchestration::codec::OpenclawLoaded,
) -> Vec<RouteRow> {
    let source = loaded
        .root
        .state_dir
        .join("openclaw.json")
        .display()
        .to_string();
    let mut routes: Vec<_> = loaded
        .orchestration
        .profiles
        .values()
        .flat_map(|profile| profile.routes.iter())
        .collect();
    routes.sort_by_key(|route| route.residue.0.get("index").and_then(Value::as_u64));
    let mut rows = Vec::new();
    for route in routes {
        let residue = &route.residue.0;
        let m = residue.get("match").and_then(Value::as_object);
        let text = |key: &str| {
            m.and_then(|m| m.get(key)).and_then(|v| match v {
                Value::String(s) => Some(s.clone()),
                Value::Number(n) => Some(n.to_string()),
                _ => None,
            })
        };
        let peer_kind = m
            .and_then(|m| m.get("peer"))
            .and_then(|p| p.get("kind"))
            .and_then(Value::as_str)
            .map(str::to_string);
        let roles: Vec<String> = m
            .and_then(|m| m.get("roles"))
            .and_then(Value::as_array)
            .map(|list| {
                list.iter()
                    .filter_map(Value::as_str)
                    .map(str::to_string)
                    .collect()
            })
            .unwrap_or_default();
        let guild = route.matches.guild_id.clone();
        let team = text("teamId");
        let account = text("accountId");
        let channel = Some(route.matches.platform.clone()).filter(|p| !p.is_empty());
        let peer_id = route.matches.chat_id.clone();
        let specificity = match (&peer_id, &peer_kind) {
            (Some(id), _) if id == "*" => 6,
            (Some(_), Some(kind)) if kind == "parent" => 7,
            (Some(_), _) => 8,
            _ if guild.is_some() && !roles.is_empty() => 5,
            _ if guild.is_some() => 4,
            _ if team.is_some() => 3,
            _ if account.is_some() => 2,
            _ if channel.is_some() => 1,
            _ => 0,
        };
        let target = residue
            .get("agent_id")
            .and_then(Value::as_str)
            .map(str::to_string)
            .or_else(|| {
                loaded
                    .profiles
                    .get(&route.profile)
                    .map(|io| io.agent_id.clone())
            })
            .unwrap_or_else(|| route.profile.clone());
        rows.push(RouteRow {
            harness: HarnessId::OPENCLAW.into(),
            target,
            matcher: RouteMatch {
                platform: channel,
                account,
                guild,
                team,
                chat_id: peer_id,
                peer_kind,
                thread_id: None,
                roles,
            },
            specificity,
            default: false,
            source: source.clone(),
        });
    }
    rows.push(RouteRow {
        harness: HarnessId::OPENCLAW.into(),
        target: loaded.root.default_agent.clone(),
        matcher: RouteMatch::default(),
        specificity: 0,
        default: true,
        source,
    });
    rows
}

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

    fn scratch(tag: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "supercode-routes-{tag}-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    /// ORC-7: the orchestrator's routes come from every profile folder's own
    /// `config.yaml`, and the unmatched-traffic default row belongs to the
    /// ROOT folder alone — a named profile's table does not get to claim it.
    #[test]
    fn orchestrator_routes_are_read_per_profile_folder_with_one_default() {
        let dir = scratch("orchestrator");
        std::fs::create_dir_all(dir.join("profiles/ops")).unwrap();
        std::fs::write(
            dir.join("config.yaml"),
            "gateway:\n  profile_routes:\n    - platform: slack\n      chat_id: C1\n      profile: ops\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("profiles/ops/config.yaml"),
            "gateway:\n  profile_routes:\n    - platform: telegram\n      profile: ops\n",
        )
        .unwrap();
        let homes = HarnessHomes {
            orchestrator: dir.clone(),
            ..HarnessHomes::default()
        };
        let rows = list_routes(&homes, Some(HarnessId::ORCHESTRATOR), None).unwrap();
        assert!(
            rows.iter()
                .all(|row| row.harness == HarnessId::ORCHESTRATOR),
            "{rows:?}"
        );
        assert_eq!(rows.iter().filter(|row| row.default).count(), 1, "{rows:?}");
        // Both folders' tables are read: two routes to `ops` (the root's
        // slack one and the named profile's telegram one) plus the default.
        assert_eq!(
            rows.iter().filter(|row| row.target == "ops").count(),
            2,
            "{rows:?}"
        );
        // Hermes's own weights, unchanged: chat 4, platform-only 0. (Rows are
        // ordered by specificity then target, which is the existing shared
        // ordering — the default is not pinned last on a specificity tie.)
        assert_eq!(rows[0].specificity, 4);
        assert_eq!(rows[0].matcher.chat_id.as_deref(), Some("C1"));
        assert!(
            rows.iter()
                .any(|row| row.matcher.platform.as_deref() == Some("telegram")
                    && row.specificity == 0)
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn openclaw_bindings_follow_the_documented_cascade() {
        let dir = scratch("openclaw");
        std::fs::write(
            dir.join("openclaw.json"),
            r#"{ "agents": { "list": [ { "id": "main", "default": true }, { "id": "design" } ] },
                "bindings": [
                  { "type": "route", "agentId": "design", "match": { "channel": "slack" } },
                  { "type": "route", "agentId": "ops", "match": { "channel": "discord", "guildId": "G1", "roles": ["admin"] } },
                  { "type": "route", "agentId": "vip", "match": { "channel": "telegram", "peer": { "kind": "user", "id": "U1" } } }
                ] }"#,
        )
        .unwrap();
        let loaded = supercode_interchange::orchestration::codec::from_openclaw(&dir).unwrap();
        let rows = openclaw_rows(&loaded);
        let spec: Vec<(String, u32)> = rows
            .iter()
            .map(|r| (r.target.clone(), r.specificity))
            .collect();
        assert_eq!(
            spec,
            vec![
                ("design".into(), 1),
                ("ops".into(), 5),
                ("vip".into(), 8),
                ("main".into(), 0)
            ]
        );
        assert!(rows[3].default);
    }

    #[test]
    fn unsupported_harness_is_refused() {
        let err = list_routes(&HarnessHomes::default(), Some("codex"), None).unwrap_err();
        assert!(err.to_string().contains("routes.list"));
    }
}