agent-harness-adapter-core 0.2.2

One agent setup, every coding agent: install instructions, skills and hooks, declared once or read from AGENTS.md and .agents/, into Claude Code, Codex, Gemini CLI, Copilot, Cursor, OpenCode and more; hooks speak Claude Code's protocol everywhere.
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
547
548
549
550
551
552
553
554
555
556
557
//! The items of an integration and the standard renderings several
//! harnesses share.

use std::time::Duration;

use serde_json::{Map, Value, json};

use crate::{
    harness::EntryMatch,
    hook::{Event, ToolKind},
};

/// A frontmatter value: as is when plain YAML reads it back unchanged, else
/// double-quoted (as JSON, which YAML reads).
pub(super) fn yaml_scalar(text: &str) -> String {
    let plain = !text.is_empty()
        && !text.starts_with(|c: char| "-?:,[]{}#&*!|>'\"%@` ".contains(c))
        && !text.ends_with(' ')
        && !text.contains(": ")
        && !text.contains(" #")
        && !text.contains('\n');
    if plain {
        text.to_string()
    } else {
        Value::String(text.to_string()).to_string()
    }
}

/// A hook: an event and the command a harness runs for it.
///
/// The command is any command line: `{harness}` and `{event}` anywhere in
/// it, in any order, or not at all, are replaced by the harness id and the
/// event's name; `{{` and `}}` give literal braces.
// @zen-impl: KIT-11_AC-2
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Hook {
    event: Event,
    template: String,
    kind: Option<ToolKind>,
    timeout: Option<Duration>,
    owned: Option<EntryMatch>,
    overrides: Vec<(String, String)>,
}

impl Hook {
    /// Run `command` (a template) on `event`.
    pub fn new(event: Event, command: impl Into<String>) -> Self {
        Hook {
            event,
            template: command.into(),
            kind: None,
            timeout: None,
            owned: None,
            overrides: Vec::new(),
        }
    }

    /// Run `command` (a template) instead for the harness `harness`, e.g. a
    /// path through an environment variable only that harness sets.
    #[must_use]
    pub fn command_for(mut self, harness: impl Into<String>, command: impl Into<String>) -> Self {
        let harness = harness.into();
        self.overrides.retain(|(h, _)| *h != harness);
        self.overrides.push((harness, command.into()));
        self
    }

    /// Only for tool calls of `kind` (pre tool, post tool). A harness that
    /// can match tool names installs it as the matcher; another runs the
    /// hook for every tool, and the hook filters on
    /// [`HookInput::tool`](crate::hook::HookInput::tool).
    #[must_use]
    pub fn tools(mut self, kind: ToolKind) -> Self {
        self.kind = Some(kind);
        self
    }

    /// With a timeout.
    #[must_use]
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// The hook entries that are this hook's in a harness's file: those
    /// whose command `owned` matches, instead of the default (see
    /// [`Integration::hook_owner`](crate::integration::Integration::hook_owner)).
    #[must_use]
    pub fn owned(mut self, owned: EntryMatch) -> Self {
        self.owned = Some(owned);
        self
    }

    /// The event.
    pub fn event(&self) -> Event {
        self.event
    }

    /// The command template as given.
    pub fn template(&self) -> &str {
        &self.template
    }

    /// The template `harness` runs: its own, else the hook's.
    pub fn template_for(&self, harness: &str) -> &str {
        self.overrides
            .iter()
            .find(|(h, _)| h == harness)
            .map_or(&self.template, |(_, t)| t)
    }

    /// The command a harness runs: placeholders filled, braces unescaped.
    pub fn command(&self, harness: &str) -> String {
        fill(self.template_for(harness), harness, self.event.as_str())
    }

    /// The tool kind the hook is limited to.
    pub fn tool_kind(&self) -> Option<ToolKind> {
        self.kind
    }

    /// The timeout.
    pub fn timeout_value(&self) -> Option<Duration> {
        self.timeout
    }

    /// The entry match set on this hook.
    pub fn owned_by(&self) -> Option<&EntryMatch> {
        self.owned.as_ref()
    }

    /// For each template (the hook's, then each harness's own), its text
    /// before its first placeholder, unescaped; the whole template when it
    /// has none.
    pub(crate) fn prefixes(&self) -> Vec<String> {
        std::iter::once(self.template.as_str())
            .chain(self.overrides.iter().map(|(_, t)| t.as_str()))
            .map(prefix)
            .collect()
    }
}

/// `template`'s text before its first placeholder, unescaped.
fn prefix(template: &str) -> String {
    let mut out = String::new();
    let mut rest = template;
    while !rest.is_empty() {
        if let Some(r) = rest.strip_prefix("{{") {
            out.push('{');
            rest = r;
        } else if let Some(r) = rest.strip_prefix("}}") {
            out.push('}');
            rest = r;
        } else if rest.starts_with("{harness}") || rest.starts_with("{event}") {
            break;
        } else {
            let c = rest.chars().next().expect("not empty");
            out.push(c);
            rest = &rest[c.len_utf8()..];
        }
    }
    out
}

/// `template` with `{harness}` and `{event}` replaced and `{{` / `}}`
/// unescaped; any other brace is kept as written.
fn fill(template: &str, harness: &str, event: &str) -> String {
    let mut out = String::new();
    let mut rest = template;
    while !rest.is_empty() {
        if let Some(r) = rest.strip_prefix("{{") {
            out.push('{');
            rest = r;
        } else if let Some(r) = rest.strip_prefix("}}") {
            out.push('}');
            rest = r;
        } else if let Some(r) = rest.strip_prefix("{harness}") {
            out.push_str(harness);
            rest = r;
        } else if let Some(r) = rest.strip_prefix("{event}") {
            out.push_str(event);
            rest = r;
        } else {
            let c = rest.chars().next().expect("not empty");
            out.push(c);
            rest = &rest[c.len_utf8()..];
        }
    }
    out
}

/// How an MCP server is reached.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Transport {
    /// A local process on stdin / stdout.
    Stdio {
        /// The program.
        command: String,
        /// Its arguments.
        args: Vec<String>,
        /// Environment variables.
        env: Vec<(String, String)>,
    },
    /// A remote server over HTTP.
    Http {
        /// The URL.
        url: String,
        /// HTTP headers.
        headers: Vec<(String, String)>,
    },
}

/// An MCP server the tool provides.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct McpServer {
    name: String,
    transport: Transport,
}

impl McpServer {
    /// A server named `name` that runs `command` with `args`.
    pub fn stdio<I: IntoIterator<Item = S>, S: Into<String>>(
        name: impl Into<String>,
        command: impl Into<String>,
        args: I,
    ) -> Self {
        McpServer {
            name: name.into(),
            transport: Transport::Stdio {
                command: command.into(),
                args: args.into_iter().map(Into::into).collect(),
                env: Vec::new(),
            },
        }
    }

    /// A server named `name` at `url`.
    pub fn http(name: impl Into<String>, url: impl Into<String>) -> Self {
        McpServer {
            name: name.into(),
            transport: Transport::Http {
                url: url.into(),
                headers: Vec::new(),
            },
        }
    }

    /// With an environment variable (a stdio server; ignored for http).
    #[must_use]
    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        if let Transport::Stdio { env, .. } = &mut self.transport {
            env.push((key.into(), value.into()));
        }
        self
    }

    /// With an HTTP header (an http server; ignored for stdio).
    #[must_use]
    pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        if let Transport::Http { headers, .. } = &mut self.transport {
            headers.push((key.into(), value.into()));
        }
        self
    }

    /// The server's name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// How it is reached.
    pub fn transport(&self) -> &Transport {
        &self.transport
    }

    /// The common `mcpServers` entry: `{command, args, env?}` or `{url,
    /// headers?}`; empty `env` and `headers` are left out.
    pub fn to_json(&self) -> Value {
        match &self.transport {
            Transport::Stdio { command, args, env } => {
                let mut v = json!({ "command": command, "args": args });
                if !env.is_empty() {
                    v["env"] = pairs(env);
                }
                v
            }
            Transport::Http { url, headers } => {
                let mut v = json!({ "url": url });
                if !headers.is_empty() {
                    v["headers"] = pairs(headers);
                }
                v
            }
        }
    }
}

/// Key-value pairs as a JSON object, in order.
fn pairs(kv: &[(String, String)]) -> Value {
    Value::Object(
        kv.iter()
            .map(|(k, v)| (k.clone(), Value::String(v.clone())))
            .collect::<Map<_, _>>(),
    )
}

/// A subagent: a name, a description and its system prompt.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Agent {
    name: String,
    description: String,
    prompt: String,
    /// The markdown file it was read from, kept as written (KIT-17_AC-10).
    source_md: Option<String>,
}

impl Agent {
    /// An agent.
    pub fn new(
        name: impl Into<String>,
        description: impl Into<String>,
        prompt: impl Into<String>,
    ) -> Self {
        Agent {
            name: name.into(),
            description: description.into(),
            prompt: prompt.into(),
            source_md: None,
        }
    }

    /// The markdown agent `text`, read from `path` (for messages):
    /// frontmatter `name` (else the file's stem) and `description`, the
    /// body as the prompt; the text is kept as written.
    ///
    /// # Errors
    ///
    /// [`Error::File`](crate::Error::File) when it has no frontmatter.
    // @zen-impl: KIT-17_AC-10
    pub fn from_markdown(text: &str, path: &std::path::Path) -> crate::Result<Self> {
        let (front, body) = super::skill::split_frontmatter(text).ok_or_else(|| {
            crate::Error::file(
                path.display().to_string(),
                "no frontmatter between `---` lines at the top",
            )
        })?;
        let stem = path.file_stem().map(|s| s.to_string_lossy().into_owned());
        let name = super::skill::field(front, "name")
            .or(stem)
            .unwrap_or_default();
        let body = body
            .strip_prefix("\r\n")
            .or_else(|| body.strip_prefix('\n'))
            .unwrap_or(body);
        Ok(Agent {
            name,
            description: super::skill::field(front, "description").unwrap_or_default(),
            prompt: body.to_string(),
            source_md: Some(text.to_string()),
        })
    }

    /// The markdown file it was read from, when it was.
    pub fn source_markdown(&self) -> Option<&str> {
        self.source_md.as_deref()
    }

    /// The agent's name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The agent's description.
    pub fn description(&self) -> &str {
        &self.description
    }

    /// The agent's system prompt.
    pub fn prompt(&self) -> &str {
        &self.prompt
    }

    /// The common Markdown agent: frontmatter `name`, `description`, then
    /// `extra` (key, value), then the prompt as the body. An agent read from
    /// a file is that file, with each `extra` key it lacks added at the end
    /// of its frontmatter (HAR-14_AC-5).
    // @zen-impl: HAR-14_AC-5
    pub fn to_markdown(&self, extra: &[(&str, &str)]) -> String {
        let source = self.source_md.as_deref();
        if let Some((text, (front, _))) =
            source.and_then(|t| super::skill::split_frontmatter(t).map(|f| (t, f)))
        {
            // `front` is a slice of `text`: the frontmatter ends where it does.
            let end = front.as_ptr() as usize - text.as_ptr() as usize + front.len();
            let mut out = text[..end].to_string();
            if !out.ends_with('\n') {
                out.push('\n');
            }
            for (k, v) in extra {
                if super::skill::field(front, k).is_none() {
                    out.push_str(&format!("{k}: {}\n", yaml_scalar(v)));
                }
            }
            out.push_str(&text[end..]);
            return out;
        }
        let mut out = format!(
            "---\nname: {}\ndescription: {}\n",
            self.name,
            yaml_scalar(&self.description)
        );
        for (k, v) in extra {
            out.push_str(&format!("{k}: {}\n", yaml_scalar(v)));
        }
        out.push_str("---\n\n");
        out.push_str(&self.prompt);
        out
    }
}

/// A slash command: a name, a description and its prompt, where
/// `$ARGUMENTS` stands for what the user typed after it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Command {
    name: String,
    description: String,
    prompt: String,
}

impl Command {
    /// A command.
    pub fn new(
        name: impl Into<String>,
        description: impl Into<String>,
        prompt: impl Into<String>,
    ) -> Self {
        Command {
            name: name.into(),
            description: description.into(),
            prompt: prompt.into(),
        }
    }

    /// The command's name, as typed after `/`.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The command's description.
    pub fn description(&self) -> &str {
        &self.description
    }

    /// The command's prompt.
    pub fn prompt(&self) -> &str {
        &self.prompt
    }

    /// The common Markdown command: frontmatter `description`, then the
    /// prompt as the body.
    pub fn to_markdown(&self) -> String {
        format!(
            "---\ndescription: {}\n---\n\n{}",
            yaml_scalar(&self.description),
            self.prompt
        )
    }
}

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

    #[test]
    fn yaml_scalars_are_plain_when_safe() {
        assert_eq!(yaml_scalar("Checks things."), "Checks things.");
        for quoted in ["", "a: b", "- x", "x #y", "two\nlines", "'q'", " x", "x "] {
            assert!(yaml_scalar(quoted).starts_with('"'), "{quoted}");
        }
    }

    // @zen-test: KIT-11_AC-2
    #[test]
    fn hook_commands_fill_placeholders_anywhere() {
        let h = Hook::new(Event::Stop, "mytool hook {harness} {event}");
        assert_eq!(h.command("codex"), "mytool hook codex stop");
        assert_eq!(h.prefixes()[0], "mytool hook ");
        let h = Hook::new(Event::PreTool, "guard --event={event} --agent={harness}");
        assert_eq!(h.command("cursor"), "guard --event=pre-tool --agent=cursor");
        assert_eq!(h.prefixes()[0], "guard --event=");
        let h = Hook::new(Event::Stop, "mytool-stop");
        assert_eq!(h.command("pi"), "mytool-stop");
        assert_eq!(h.prefixes()[0], "mytool-stop");
        let h = Hook::new(Event::Stop, "sh -c 'x {{a}} {y}' {event}");
        assert_eq!(h.command("claude"), "sh -c 'x {a} {y}' stop");
        assert_eq!(h.prefixes()[0], "sh -c 'x {a} {y}' ");
        let h = Hook::new(Event::Stop, "{harness}-hook")
            .tools(ToolKind::Shell)
            .timeout(Duration::from_secs(5))
            .owned(EntryMatch::Contains("-hook".into()));
        assert_eq!(h.prefixes()[0], "");
        assert_eq!(h.command("gemini"), "gemini-hook");
        assert_eq!(h.template(), "{harness}-hook");
        assert_eq!(h.tool_kind(), Some(ToolKind::Shell));
        assert_eq!(h.timeout_value(), Some(Duration::from_secs(5)));
        assert_eq!(h.owned_by(), Some(&EntryMatch::Contains("-hook".into())));
        assert_eq!(h.event(), Event::Stop);
        assert_eq!(fill("é{event}", "c", "stop"), "éstop");
    }

    #[test]
    fn mcp_servers_render_the_common_entry() {
        let s = McpServer::stdio("tool", "tool", ["mcp"])
            .env("A", "1")
            .header("ignored", "x");
        assert_eq!(
            s.to_json(),
            json!({"command": "tool", "args": ["mcp"], "env": {"A": "1"}})
        );
        assert_eq!(s.name(), "tool");
        let h = McpServer::http("web", "https://x/mcp")
            .header("Authorization", "Bearer t")
            .env("ignored", "x");
        assert_eq!(
            h.to_json(),
            json!({"url": "https://x/mcp", "headers": {"Authorization": "Bearer t"}})
        );
        assert!(matches!(h.transport(), Transport::Http { .. }));
        assert_eq!(
            McpServer::stdio("t", "t", Vec::<String>::new()).to_json(),
            json!({"command": "t", "args": []})
        );
    }

    #[test]
    fn agents_and_commands_render_markdown() {
        let a = Agent::new("reviewer", "Reviews code.", "You review.\n");
        assert_eq!(
            a.to_markdown(&[("model", "inherit")]),
            "---\nname: reviewer\ndescription: Reviews code.\nmodel: inherit\n---\n\nYou review.\n"
        );
        assert_eq!(
            (a.name(), a.description(), a.prompt()),
            ("reviewer", "Reviews code.", "You review.\n")
        );
        let c = Command::new("check", "Run the check.", "Check $ARGUMENTS.\n");
        assert_eq!(
            c.to_markdown(),
            "---\ndescription: Run the check.\n---\n\nCheck $ARGUMENTS.\n"
        );
        assert_eq!(
            (c.name(), c.description(), c.prompt()),
            ("check", "Run the check.", "Check $ARGUMENTS.\n")
        );
    }
}