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
//! The manifest file's shapes, as serde reads them. Unknown keys are
//! errors; the same shapes give the manifest's JSON Schema.

use std::{fmt, marker::PhantomData};

use serde::{
    Deserialize, Deserializer,
    de::{self, MapAccess, Visitor},
};
use serde_json::Value;

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

/// Only the version, read first so a manifest of another version is
/// refused for that, not for its other keys.
#[derive(Debug, Deserialize)]
pub(crate) struct VersionOnly {
    pub version: u64,
}

/// Text inline, or the contents of a file relative to the manifest.
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schemars", schemars(untagged))]
#[derive(Debug, Clone)]
pub(crate) enum Text {
    /// The text itself.
    Inline(String),
    /// A file's contents, copied.
    File(FileRef),
    /// A SOURCE the item is read from (instructions only).
    From(FromRef),
}

/// `{ from = "<path>" }`: an item's SOURCE, relative to the manifest's
/// directory (AHA-1_AC-11).
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct FromRef {
    /// The path, relative to the manifest's directory.
    pub from: String,
}

/// A list of items, or `{ from = "<path>" }`, their SOURCE.
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schemars", schemars(untagged))]
#[derive(Debug, Clone)]
pub(crate) enum Many<T> {
    /// The items.
    List(Vec<T>),
    /// Read from a SOURCE.
    From(FromRef),
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for Many<T> {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct V<T>(PhantomData<T>);
        impl<'de, T: Deserialize<'de>> Visitor<'de> for V<T> {
            type Value = Many<T>;
            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("a list or { from = \"<path>\" }")
            }
            fn visit_seq<A: de::SeqAccess<'de>>(self, seq: A) -> Result<Many<T>, A::Error> {
                Vec::deserialize(de::value::SeqAccessDeserializer::new(seq)).map(Many::List)
            }
            fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Many<T>, A::Error> {
                FromRef::deserialize(de::value::MapAccessDeserializer::new(map)).map(Many::From)
            }
        }
        d.deserialize_any(V(PhantomData))
    }
}

/// `{ file = "<path>" }`: a file relative to the manifest's directory.
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct FileRef {
    /// The path, relative to the manifest's directory.
    pub file: String,
}

impl<'de> Deserialize<'de> for Text {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct V;
        impl<'de> Visitor<'de> for V {
            type Value = Text;
            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("a string, { file = \"<path>\" } or { from = \"<path>\" }")
            }
            fn visit_str<E: de::Error>(self, s: &str) -> Result<Text, E> {
                Ok(Text::Inline(s.to_string()))
            }
            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Text, A::Error> {
                let key: String = map
                    .next_key()?
                    .ok_or_else(|| de::Error::custom("expected `file` or `from`"))?;
                let path: String = map.next_value()?;
                if let Some(other) = map.next_key::<String>()? {
                    return Err(de::Error::custom(format!("unknown field `{other}`")));
                }
                match key.as_str() {
                    "file" => Ok(Text::File(FileRef { file: path })),
                    "from" => Ok(Text::From(FromRef { from: path })),
                    k => Err(de::Error::unknown_field(k, &["file", "from"])),
                }
            }
        }
        d.deserialize_any(V)
    }
}

impl<'de> Deserialize<'de> for Harnesses {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct V;
        impl<'de> Visitor<'de> for V {
            type Value = Harnesses;
            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("\"all\" or a list of harness ids")
            }
            fn visit_str<E: de::Error>(self, s: &str) -> Result<Harnesses, E> {
                Ok(Harnesses::All(s.to_string()))
            }
            fn visit_seq<A: de::SeqAccess<'de>>(self, seq: A) -> Result<Harnesses, A::Error> {
                Vec::deserialize(de::value::SeqAccessDeserializer::new(seq)).map(Harnesses::List)
            }
        }
        d.deserialize_any(V)
    }
}

/// A map that keeps its keys in the order written.
#[derive(Debug, Clone)]
pub(crate) struct Ordered<V>(pub Vec<(String, V)>);

impl<'de, V: Deserialize<'de>> Deserialize<'de> for Ordered<V> {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct Pairs<V>(PhantomData<V>);
        impl<'de, V: Deserialize<'de>> Visitor<'de> for Pairs<V> {
            type Value = Ordered<V>;
            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("a table")
            }
            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
                let mut out = Vec::new();
                while let Some(kv) = map.next_entry::<String, V>()? {
                    out.push(kv);
                }
                Ok(Ordered(out))
            }
        }
        d.deserialize_map(Pairs(PhantomData))
    }
}

#[cfg(feature = "schemars")]
impl<V: schemars::JsonSchema> schemars::JsonSchema for Ordered<V> {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        format!("Ordered_{}", V::schema_name()).into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        <std::collections::BTreeMap<String, V>>::json_schema(generator)
    }
}

/// `"all"`, or harness ids in the order the tool prefers them.
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schemars", schemars(untagged))]
#[derive(Debug, Clone)]
pub(crate) enum Harnesses {
    /// `"all"`: every built-in harness.
    All(String),
    /// These harnesses.
    List(Vec<String>),
}

/// Which hook entries are the tool's: `{ prefix = ".." }`,
/// `{ contains = ".." }` or `{ any = [..] }`.
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "lowercase", deny_unknown_fields)]
pub(crate) enum Match {
    /// The command starts with the text.
    Prefix(String),
    /// The command contains the text.
    Contains(String),
    /// Any of these matches.
    Any(Vec<Match>),
}

/// An agent skill: `dir`, or `name`, `description`, `body` and `files`.
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct SkillFile {
    /// A skill directory, relative to the manifest's directory: its
    /// `SKILL.md`, written as it is, and every other file in it but hidden
    /// ones. Not with the other fields.
    #[serde(default)]
    pub dir: Option<String>,
    /// The skill's name: lowercase, digits and `-`.
    #[serde(default)]
    pub name: Option<String>,
    /// When the agent should use it.
    #[serde(default)]
    pub description: Option<String>,
    /// The body after the frontmatter.
    #[serde(default)]
    pub body: Option<Text>,
    /// Extra files beside `SKILL.md`: path → text.
    #[serde(default)]
    pub files: Option<Ordered<Text>>,
}

/// A hook: `command` (a template the harness runs) or `run` (a command
/// `agent-harness-adapter hook` runs with the hook contract), not both.
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct HookFile {
    /// The event.
    pub event: Event,
    /// A hook command template: `{harness}` and `{event}` are filled in.
    #[serde(default)]
    pub command: Option<String>,
    /// A command bridged through `agent-harness-adapter hook`: it reads the hook input on
    /// stdin and writes an answer on stdout.
    #[serde(default)]
    pub run: Option<String>,
    /// Only for tool calls of this kind (pre tool, post tool).
    #[serde(default)]
    pub tools: Option<ToolKind>,
    /// A timeout in seconds.
    #[serde(default)]
    pub timeout: Option<u64>,
    /// Per-harness command templates: harness id → template.
    #[serde(default)]
    pub commands: Option<Ordered<String>>,
    /// Which entries in a harness's file are this hook's.
    #[serde(default)]
    pub owned: Option<Match>,
}

/// An MCP server: `command` (with `args`, `env`) or `url` (with `headers`).
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct McpFile {
    /// The server's name.
    pub name: String,
    /// The program of a local server.
    #[serde(default)]
    pub command: Option<String>,
    /// Its arguments.
    #[serde(default)]
    pub args: Option<Vec<String>>,
    /// Its environment variables.
    #[serde(default)]
    pub env: Option<Ordered<String>>,
    /// The URL of a remote server.
    #[serde(default)]
    pub url: Option<String>,
    /// Its HTTP headers.
    #[serde(default)]
    pub headers: Option<Ordered<String>>,
}

/// A tool of an MCP server the agent may call without asking.
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct McpToolFile {
    /// The server's name.
    pub server: String,
    /// The tool's name.
    pub tool: String,
}

/// A subagent or a slash command.
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct PromptFile {
    /// Its name.
    pub name: String,
    /// Its description.
    pub description: String,
    /// Its prompt (a command's `$ARGUMENTS` stands for what the user typed).
    pub prompt: Text,
}

/// A raw part for one harness.
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
pub(crate) enum PartFile {
    /// Whole files under a directory.
    File {
        /// The harness id.
        harness: String,
        /// The part's name.
        name: String,
        /// The directory, relative to the root.
        dir: String,
        /// Path (relative to `dir`) → text.
        files: Ordered<Text>,
    },
    /// The block between the tool's markers in a file.
    Region {
        /// The harness id.
        harness: String,
        /// The part's name.
        name: String,
        /// The file, relative to the root.
        file: String,
        /// The block.
        block: Text,
    },
    /// Entries in a JSON file, or members in a TOML file (`.toml`).
    Merge {
        /// The harness id.
        harness: String,
        /// The part's name.
        name: String,
        /// The file, relative to the root.
        file: String,
        /// The entries.
        ops: Vec<OpFile>,
    },
}

/// One merge operation on the file's JSON or TOML.
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
pub(crate) enum OpFile {
    /// `value` once in the array at `path`.
    ArrayEntry {
        /// Keys from the top level.
        path: Vec<String>,
        /// The entry.
        value: Value,
    },
    /// The member `key` of the object at `path` is `value`.
    ObjectMember {
        /// Keys from the top level.
        path: Vec<String>,
        /// The member's key.
        key: String,
        /// Its value.
        value: Value,
    },
    /// The tool's entries (by `field`) in the array at `path`.
    OwnedEntries {
        /// Keys from the top level.
        path: Vec<String>,
        /// The field that marks an entry as the tool's.
        field: String,
        /// Which values of the field are the tool's.
        owned: Match,
        /// The tool's entries.
        entries: Vec<Value>,
    },
    /// The tool's entries in the groups of the array at `path`.
    GroupEntries {
        /// Keys from the top level.
        path: Vec<String>,
        /// The key of a group's entries.
        entries: String,
        /// The field that marks an entry as the tool's.
        field: String,
        /// Which values of the field are the tool's.
        owned: Match,
        /// The groups, each holding the tool's entries under `entries`.
        groups: Vec<Value>,
    },
}

/// The item fields, written once: the top level and each scope table hold
/// them, and [`Items`] borrows them.
macro_rules! with_items {
    ($($(#[doc = $doc:literal])* $field:ident: $ty:ty,)*) => {
        /// The items of a manifest or of one scope table, borrowed.
        #[derive(Debug, Default, Clone, Copy)]
        pub(crate) struct Items<'a> {
            $(pub $field: Option<&'a $ty>,)*
        }

        impl<'a> Items<'a> {
            /// These items, each replaced by `scope`'s when it has one.
            pub fn with(self, scope: Items<'a>) -> Items<'a> {
                Items { $($field: scope.$field.or(self.$field),)* }
            }
        }

        /// A manifest file (version 1).
        #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
        #[cfg_attr(feature = "schemars", schemars(title = "AHA manifest"))]
        #[derive(Debug, Clone, Deserialize)]
        #[serde(deny_unknown_fields)]
        pub(crate) struct ManifestFile {
            /// The manifest format's version: 1.
            pub version: u64,
            /// The tool's name: letters, digits, `-`, `_` and `.`.
            pub name: String,
            /// `"all"` (the default), or harness ids in preference order.
            #[serde(default)]
            pub harnesses: Option<Harnesses>,
            /// The command bridged hooks run: `agent-harness-adapter` by default.
            #[serde(default)]
            pub adapter: Option<String>,
            /// The record file, relative to the scope's root.
            #[serde(default)]
            pub record: Option<String>,
            /// The declined parts' file, relative to the scope's root.
            #[serde(default)]
            pub declined: Option<String>,
            $($(#[doc = $doc])* #[serde(default)] pub $field: Option<$ty>,)*
            /// Per scope: the items and paths that replace the top level's.
            #[serde(default)]
            pub scopes: Option<ScopesFile>,
        }

        /// What one scope replaces.
        #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
        #[derive(Debug, Clone, Default, Deserialize)]
        #[serde(deny_unknown_fields)]
        pub(crate) struct ScopeFile {
            /// The record file at this scope.
            #[serde(default)]
            pub record: Option<String>,
            /// The declined parts' file at this scope.
            #[serde(default)]
            pub declined: Option<String>,
            $($(#[doc = $doc])* #[serde(default)] pub $field: Option<$ty>,)*
        }

        impl ManifestFile {
            pub fn items(&self) -> Items<'_> {
                Items { $($field: self.$field.as_ref(),)* }
            }
        }

        impl ScopeFile {
            pub fn items(&self) -> Items<'_> {
                Items { $($field: self.$field.as_ref(),)* }
            }
        }
    };
}

with_items! {
    /// The instructions block, placed between the tool's markers in the
    /// file each harness reads.
    instructions: Text,
    /// Which hook entries are the tool's, for hooks without `owned`.
    hook_match: Match,
    /// Agent skills, or `{ from = "<dir>" }`.
    skills: Many<SkillFile>,
    /// Hooks, or `{ from = "<hooks file>" }`.
    hooks: Many<HookFile>,
    /// MCP servers, or `{ from = "<MCP JSON file>" }`.
    mcp_servers: Many<McpFile>,
    /// Command prefixes the agent may run without asking.
    allow_commands: Vec<String>,
    /// MCP tools the agent may call without asking.
    allow_mcp_tools: Vec<McpToolFile>,
    /// Subagents, or `{ from = "<dir>" }`.
    agents: Many<PromptFile>,
    /// Slash commands.
    commands: Vec<PromptFile>,
    /// Raw parts for one harness.
    parts: Vec<PartFile>,
}

/// The scope tables.
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct ScopesFile {
    /// Project scope.
    #[serde(default)]
    pub project: Option<ScopeFile>,
    /// User scope.
    #[serde(default)]
    pub user: Option<ScopeFile>,
    /// Local scope.
    #[serde(default)]
    pub local: Option<ScopeFile>,
}