supercode-harness 0.4.16

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
//! ORCH-16 (observed tier): the inbound-trigger noun — an HTTP route or hook
//! mapping that opens a turn when something outside the harness fires.
//!
//! * **Hermes** — dynamic webhook subscriptions in
//!   `HERMES_HOME/webhook_subscriptions.json` (a flat map `route → {description,
//!   events, prompt, skills, deliver, deliver_extra{chat_id}, created_at,
//!   secret}`, written by `hermes webhook subscribe`) plus static routes under
//!   `platforms.webhook.extra.routes` in `config.yaml`; each serves
//!   `POST /webhooks/<route>` (`gateway/platforms/webhook.py`).
//! * **OpenClaw (pinned 2026.7.1-2)** — the `hooks` block in `openclaw.json`:
//!   `enabled`, `path`, `token`, and `hooks.mappings[]` (`id, match{path,source,
//!   event}, action wake|agent, agentId, sessionKey, wakeMode, deliver, channel,
//!   to, model`); when enabled the gateway also serves the built-in
//!   `POST <path>/wake` and `POST <path>/agent` endpoints
//!   (`docs/automation/cron-jobs.md#webhooks` at the pin). NOTE: `openclaw hooks`
//!   at the pin manages INTERNAL lifecycle hook packs, not these.
//! * **Claude Code** — channels are declared over the MCP protocol at connect
//!   time, not in a file; refused rather than guessed (as ORCH-14).
//!
//! Read-only, and no secret is ever read for anything but presence: the
//! per-route HMAC `secret` (Hermes) and the hook `token` (OpenClaw) are never
//! emitted.

use std::path::Path;

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

use crate::catalog::HarnessHomes;
use crate::profiles::{read_json5, yaml_child, yaml_key};
use crate::HarnessId;

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

/// Harnesses with an inbound-trigger concept supercode can read.
pub const TRIGGER_HARNESSES: &[&str] = &[
    HarnessId::HERMES,
    HarnessId::OPENCLAW,
    HarnessId::ORCHESTRATOR,
];

/// What kind of trigger a row is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TriggerKind {
    /// A Hermes webhook route (dynamic subscription or static config route).
    Webhook,
    /// An OpenClaw `hooks.mappings[]` entry.
    HookMapping,
    /// OpenClaw's built-in `/wake` endpoint (system event into the main session).
    BuiltinWake,
    /// OpenClaw's built-in `/agent` endpoint (isolated agent turn).
    BuiltinAgent,
}

/// Where the fired turn goes.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TriggerTarget {
    /// `wake` | `agent` (OpenClaw) or `background` (Hermes: an autonomous lane).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub action: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wake_mode: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
}

/// Where the reply is delivered.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TriggerDeliver {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chat_id: Option<String>,
}

/// One inbound trigger.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TriggerRow {
    pub name: String,
    pub harness: String,
    pub kind: TriggerKind,
    /// The HTTP route the trigger listens on (path only).
    pub route: String,
    /// Accepted event names (Hermes) or the mapping's match criteria rendered
    /// as `key=value` (OpenClaw); empty means any.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub events: Vec<String>,
    pub target: TriggerTarget,
    pub deliver: TriggerDeliver,
    pub enabled: bool,
    /// The route has an auth secret configured (presence only).
    pub authenticated: bool,
    /// Config file the trigger was read from.
    pub source: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Why a listing was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TriggerError {
    /// The harness has no inbound-trigger store supercode can read.
    UnsupportedHarness { harness: String },
}

impl std::fmt::Display for TriggerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TriggerError::UnsupportedHarness { harness } => write!(
                f,
                "`{harness}` has no inbound-trigger store supercode reads; `triggers.list` is supported for: {}",
                TRIGGER_HARNESSES.join(", ")
            ),
        }
    }
}

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

/// List inbound triggers, optionally for one harness.
pub fn list_triggers(
    homes: &HarnessHomes,
    harness: Option<&str>,
) -> Result<Vec<TriggerRow>, TriggerError> {
    let harnesses: Vec<&str> = match harness {
        Some(id) if TRIGGER_HARNESSES.contains(&id) => vec![id],
        Some(id) => {
            return Err(TriggerError::UnsupportedHarness {
                harness: id.to_string(),
            })
        }
        None => TRIGGER_HARNESSES.to_vec(),
    };
    let mut rows = Vec::new();
    for id in harnesses {
        match id {
            HarnessId::HERMES => rows.extend(hermes_rows(
                HarnessId::HERMES,
                homes.hermes.parent().unwrap_or(Path::new(".")),
                None,
            )),
            HarnessId::OPENCLAW => rows.extend(openclaw_rows(&homes.openclaw)),
            // ORC-7: `webhook_subscriptions.json` lives in each of the
            // orchestrator's profile folders, in Hermes's own shape
            // (`docs/ORCHESTRATOR-IR.md` §6), so the Hermes reader runs once
            // per folder with the folder's name as the route's profile.
            HarnessId::ORCHESTRATOR => {
                for (name, dir) in crate::orchestrator_profile_dirs(&homes.orchestrator) {
                    let profile = (name != "default").then_some(name);
                    rows.extend(hermes_rows(
                        HarnessId::ORCHESTRATOR,
                        &dir,
                        profile.as_deref(),
                    ));
                }
            }
            _ => {}
        }
    }
    Ok(rows)
}

fn text(value: &Value, key: &str) -> Option<String> {
    value
        .get(key)
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
}

fn string_list(value: &Value, key: &str) -> Vec<String> {
    value
        .get(key)
        .and_then(Value::as_array)
        .map(|list| {
            list.iter()
                .filter_map(Value::as_str)
                .map(str::to_string)
                .collect()
        })
        .unwrap_or_default()
}

fn hermes_route_row(
    harness: &str,
    name: &str,
    route: &Value,
    source: &str,
    profile: Option<&str>,
) -> TriggerRow {
    let deliver_extra = route.get("deliver_extra").cloned().unwrap_or(Value::Null);
    TriggerRow {
        name: name.to_string(),
        harness: harness.into(),
        kind: TriggerKind::Webhook,
        route: match profile {
            Some(p) => format!("/p/{p}/webhooks/{name}"),
            None => format!("/webhooks/{name}"),
        },
        events: string_list(route, "events"),
        target: TriggerTarget {
            action: Some("background".into()),
            profile: profile.map(str::to_string),
            ..TriggerTarget::default()
        },
        deliver: TriggerDeliver {
            target: text(route, "deliver").or_else(|| Some("log".into())),
            chat_id: text(&deliver_extra, "chat_id").or_else(|| text(route, "deliver_chat_id")),
        },
        enabled: route
            .get("enabled")
            .and_then(Value::as_bool)
            .unwrap_or(true),
        // Presence only: the value is a per-route HMAC secret and is never read.
        authenticated: route.get("secret").is_some(),
        source: source.to_string(),
        description: text(route, "description"),
    }
}

/// Read the webhook subscriptions of one Hermes-shaped home.
///
/// `home` is the folder holding `webhook_subscriptions.json` and
/// `config.yaml` (Hermes: HERMES_HOME; the orchestrator: one profile folder).
/// `profile` names the folder when it is a named profile, which is what puts
/// the route under `/p/<profile>/webhooks/<name>`.
fn hermes_rows(harness: &str, home: &Path, profile: Option<&str>) -> Vec<TriggerRow> {
    let mut rows = Vec::new();
    let subs_path = home.join("webhook_subscriptions.json");
    if let Ok(text) = std::fs::read_to_string(&subs_path) {
        if let Ok(Value::Object(map)) = serde_json::from_str::<Value>(&text) {
            let source = subs_path.display().to_string();
            for (name, route) in map {
                rows.push(hermes_route_row(harness, &name, &route, &source, profile));
            }
        }
    }
    let config_path = home.join("config.yaml");
    if let Ok(config) = std::fs::read_to_string(&config_path) {
        let webhook = yaml_child(&yaml_child(&config, "platforms"), "webhook");
        let routes = yaml_child(&yaml_child(&webhook, "extra"), "routes");
        let source = config_path.display().to_string();
        for (name, block) in yaml_route_blocks(&routes) {
            let mut route = serde_json::Map::new();
            for line in block.lines() {
                let trimmed = line.trim();
                let (Some(key), Some(value)) = (yaml_key(trimmed), scalar(trimmed)) else {
                    continue;
                };
                route.insert(key.to_string(), Value::String(value));
            }
            if let Some(events) = route.get("events").and_then(Value::as_str) {
                let list: Vec<Value> = events
                    .trim_matches(|c| c == '[' || c == ']')
                    .split(',')
                    .map(|e| e.trim().trim_matches(|c| c == '"' || c == '\''))
                    .filter(|e| !e.is_empty())
                    .map(|e| Value::String(e.to_string()))
                    .collect();
                route.insert("events".into(), Value::Array(list));
            }
            if let Some(enabled) = route.get("enabled").and_then(Value::as_str) {
                let flag = enabled != "false";
                route.insert("enabled".into(), Value::Bool(flag));
            }
            rows.push(hermes_route_row(
                harness,
                &name,
                &Value::Object(route),
                &source,
                profile,
            ));
        }
    }
    rows
}

/// Split a YAML mapping block (`name:\n  key: value …`) into named child blocks.
fn yaml_route_blocks(block: &str) -> Vec<(String, String)> {
    let mut out: Vec<(String, String)> = Vec::new();
    let mut base: Option<usize> = None;
    for line in block.lines() {
        let trimmed = line.trim_start();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        let indent = line.len() - trimmed.len();
        let base_indent = *base.get_or_insert(indent);
        if indent == base_indent {
            if let Some(name) = yaml_key(trimmed) {
                out.push((name.to_string(), String::new()));
            }
        } else if let Some((_, body)) = out.last_mut() {
            body.push_str(line);
            body.push('\n');
        }
    }
    out
}

fn scalar(line: &str) -> Option<String> {
    let (_, tail) = line.split_once(':')?;
    let tail = tail.trim();
    let tail = tail.split_once(" #").map(|(head, _)| head).unwrap_or(tail);
    Some(
        tail.trim()
            .trim_matches(|ch| ch == '"' || ch == '\'')
            .to_string(),
    )
}

/// OpenClaw: the `hooks` block of `openclaw.json` at the 2026.7.1-2 pin.
fn openclaw_rows(home: &Path) -> Vec<TriggerRow> {
    let config_path = home.join("openclaw.json");
    let config = read_json5(&config_path);
    let hooks = config.get("hooks").cloned().unwrap_or(Value::Null);
    if hooks.is_null() {
        return Vec::new();
    }
    let source = config_path.display().to_string();
    let enabled = hooks
        .get("enabled")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    // Presence only: `token` / `tokenFile` values are never read.
    let authenticated = hooks.get("token").is_some() || hooks.get("tokenFile").is_some();
    let base = text(&hooks, "path").unwrap_or_else(|| "/hooks".into());
    let base = base.trim_end_matches('/').to_string();
    let mut rows = vec![
        TriggerRow {
            name: "wake".into(),
            harness: HarnessId::OPENCLAW.into(),
            kind: TriggerKind::BuiltinWake,
            route: format!("{base}/wake"),
            events: Vec::new(),
            target: TriggerTarget {
                action: Some("wake".into()),
                session_key: Some("main".into()),
                ..TriggerTarget::default()
            },
            deliver: TriggerDeliver::default(),
            enabled,
            authenticated,
            source: source.clone(),
            description: Some("built-in: enqueue a system event into the main session".into()),
        },
        TriggerRow {
            name: "agent".into(),
            harness: HarnessId::OPENCLAW.into(),
            kind: TriggerKind::BuiltinAgent,
            route: format!("{base}/agent"),
            events: Vec::new(),
            target: TriggerTarget {
                action: Some("agent".into()),
                session_key: Some("isolated".into()),
                ..TriggerTarget::default()
            },
            deliver: TriggerDeliver::default(),
            enabled,
            authenticated,
            source: source.clone(),
            description: Some("built-in: run an isolated agent turn".into()),
        },
    ];
    if let Some(mappings) = hooks.get("mappings").and_then(Value::as_array) {
        for (index, mapping) in mappings.iter().enumerate() {
            let matcher = mapping.get("match").cloned().unwrap_or(Value::Null);
            let name = text(mapping, "id")
                .or_else(|| text(&matcher, "path").map(|p| p.trim_start_matches('/').to_string()))
                .unwrap_or_else(|| format!("mapping-{index}"));
            let path = text(&matcher, "path")
                .map(|p| format!("{base}/{}", p.trim_start_matches('/')))
                .unwrap_or_else(|| format!("{base}/{name}"));
            let mut events = Vec::new();
            for key in ["source", "event"] {
                if let Some(v) = text(&matcher, key) {
                    events.push(format!("{key}={v}"));
                }
            }
            rows.push(TriggerRow {
                name,
                harness: HarnessId::OPENCLAW.into(),
                kind: TriggerKind::HookMapping,
                route: path,
                events,
                target: TriggerTarget {
                    action: text(mapping, "action"),
                    profile: text(mapping, "agentId"),
                    session_key: text(mapping, "sessionKey"),
                    wake_mode: text(mapping, "wakeMode"),
                    model: text(mapping, "model"),
                },
                deliver: TriggerDeliver {
                    target: text(mapping, "deliver").or_else(|| text(mapping, "channel")),
                    chat_id: text(mapping, "to"),
                },
                enabled: enabled
                    && mapping
                        .get("enabled")
                        .and_then(Value::as_bool)
                        .unwrap_or(true),
                authenticated,
                source: source.clone(),
                description: text(mapping, "description"),
            });
        }
    }
    rows
}

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

    fn scratch(tag: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "supercode-triggers-{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
    }

    #[test]
    fn hermes_dynamic_and_static_routes_both_list_without_their_secrets() {
        let dir = scratch("hermes");
        std::fs::write(
            dir.join("webhook_subscriptions.json"),
            r#"{"deploys": {"description": "CI deploys", "events": ["push", "release"], "prompt": "Summarize {repo}", "skills": ["git"], "deliver": "telegram", "deliver_extra": {"chat_id": "123"}, "secret": "FAKE-HMAC-DO-NOT-EMIT", "created_at": "2026-09-03T00:00:00Z"}}"#,
        )
        .unwrap();
        std::fs::write(
            dir.join("config.yaml"),
            "platforms:\n  webhook:\n    enabled: true\n    extra:\n      routes:\n        alerts:\n          prompt: \"Triage\"\n          deliver: log\n          enabled: false\n          secret: \"FAKE-STATIC-SECRET\"\n",
        )
        .unwrap();
        let rows = hermes_rows(HarnessId::HERMES, &dir, None);
        assert_eq!(rows.len(), 2, "{rows:#?}");
        let deploys = &rows[0];
        assert_eq!(deploys.route, "/webhooks/deploys");
        assert_eq!(deploys.events, vec!["push", "release"]);
        assert_eq!(deploys.deliver.target.as_deref(), Some("telegram"));
        assert_eq!(deploys.deliver.chat_id.as_deref(), Some("123"));
        assert!(deploys.authenticated && deploys.enabled);
        let alerts = &rows[1];
        assert_eq!(alerts.kind, TriggerKind::Webhook);
        assert!(!alerts.enabled && alerts.authenticated);
        let rendered = serde_json::to_string(&rows).unwrap();
        assert!(!rendered.contains("FAKE-"), "{rendered}");
    }

    #[test]
    fn openclaw_hooks_block_yields_builtins_and_mappings() {
        let dir = scratch("openclaw");
        std::fs::write(
            dir.join("openclaw.json"),
            r#"{ "hooks": { "enabled": true, "token": "FAKE-HOOK-TOKEN", "path": "/hooks",
                 "mappings": [ { "id": "gmail", "match": { "path": "gmail", "source": "gmail" }, "action": "agent", "agentId": "main", "sessionKey": "hook:gmail:{{id}}", "deliver": "slack", "to": "C1" } ] } }"#,
        )
        .unwrap();
        let rows = openclaw_rows(dir.path_buf_hack());
        let names: Vec<&str> = rows.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, vec!["wake", "agent", "gmail"]);
        assert_eq!(rows[2].route, "/hooks/gmail");
        assert_eq!(rows[2].events, vec!["source=gmail"]);
        assert_eq!(rows[2].target.action.as_deref(), Some("agent"));
        assert_eq!(
            rows[2].target.session_key.as_deref(),
            Some("hook:gmail:{{id}}")
        );
        assert!(rows.iter().all(|r| r.authenticated && r.enabled));
        let rendered = serde_json::to_string(&rows).unwrap();
        assert!(!rendered.contains("FAKE-"), "{rendered}");
    }

    trait PathBufHack {
        fn path_buf_hack(&self) -> &Path;
    }
    impl PathBufHack for std::path::PathBuf {
        fn path_buf_hack(&self) -> &Path {
            self.as_path()
        }
    }

    #[test]
    fn a_core_harness_is_refused() {
        let err = list_triggers(&HarnessHomes::default(), Some("claude-code")).unwrap_err();
        assert!(err.to_string().contains("triggers.list"));
    }
}