a3s-use-core 0.2.10

Shared typed contracts for A3S Use domains
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
//! Immutable MCP, Skill, and Tool release descriptors shared with A3S Cloud.
//!
//! Descriptors are versioned machine-owned JSON. Their identity is the
//! SHA-256 of OLPC canonical JSON, so whitespace and object-key order never
//! change a release identity. Arrays representing sets must be sorted.

use std::collections::BTreeMap;

use olpc_cjson::CanonicalFormatter;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};

use crate::UseResult;

use self::validation::{descriptor_error, validate_common, verify_resolution};
use crate::plugin::validate_agent_schema;

mod validation;

pub const MCP_RELEASE_SCHEMA: &str = "a3s.use.mcp-release.v1";
pub const SKILL_RELEASE_SCHEMA: &str = "a3s.use.skill-release.v1";
pub const TOOL_RELEASE_SCHEMA: &str = "a3s.use.tool-release.v1";
pub const MAX_RELEASE_DESCRIPTOR_BYTES: usize = 256 * 1024;

const OCI_IMAGE_MANIFEST: &str = "application/vnd.oci.image.manifest.v1+json";
const OCI_IMAGE_INDEX: &str = "application/vnd.oci.image.index.v1+json";
const SKILL_BUNDLE: &str = "application/vnd.a3s.skill.bundle.v1+tar+gzip";

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ReleaseKind {
    Mcp,
    Skill,
    Tool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ReleaseProvenance {
    pub source_repository: String,
    pub commit_sha: String,
    pub manifest_digest: String,
    pub builder_id: String,
    pub build_operation_id: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ReleaseArtifact {
    pub media_type: String,
    pub digest: String,
    pub size_bytes: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ReleaseCompatibility {
    pub component: String,
    pub version_requirement: String,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ReleaseDependency {
    pub kind: ReleaseKind,
    pub name: String,
    pub version: String,
    pub descriptor_digest: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct HttpHealthContract {
    pub path: String,
    pub interval_ms: u64,
    pub timeout_ms: u64,
    pub success_threshold: u32,
    pub failure_threshold: u32,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum McpServiceTransport {
    StreamableHttp,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct McpServiceContract {
    pub transport: McpServiceTransport,
    pub protocol_version: String,
    pub port_name: String,
    pub port: u16,
    pub endpoint_path: String,
    pub health: HttpHealthContract,
    pub startup_timeout_ms: u64,
    pub shutdown_grace_ms: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct McpReleaseDescriptor {
    pub schema: String,
    pub kind: ReleaseKind,
    pub name: String,
    pub version: String,
    pub provenance: ReleaseProvenance,
    pub artifact: ReleaseArtifact,
    pub compatibility: Vec<ReleaseCompatibility>,
    pub dependencies: Vec<ReleaseDependency>,
    pub service: McpServiceContract,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SkillBindingTarget {
    AgentInput,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SkillBindingContract {
    pub target: SkillBindingTarget,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SkillContentContract {
    pub entrypoint: String,
    pub entrypoint_digest: String,
    pub required_capabilities: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SkillReleaseDescriptor {
    pub schema: String,
    pub kind: ReleaseKind,
    pub name: String,
    pub version: String,
    pub provenance: ReleaseProvenance,
    pub artifact: ReleaseArtifact,
    pub compatibility: Vec<ReleaseCompatibility>,
    pub dependencies: Vec<ReleaseDependency>,
    pub skill: SkillContentContract,
    pub binding: SkillBindingContract,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ToolTaskInterface {
    Cli,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ToolServiceInterface {
    Http,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ToolServiceNetwork {
    Private,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
    tag = "class",
    rename_all = "kebab-case",
    rename_all_fields = "camelCase",
    deny_unknown_fields
)]
pub enum ToolWorkloadContract {
    Task {
        interface: ToolTaskInterface,
        entrypoint: Vec<String>,
        interactive: bool,
        timeout_ms: u64,
        max_stdout_bytes: u64,
        max_stderr_bytes: u64,
        success_exit_codes: Vec<u8>,
    },
    Service {
        interface: ToolServiceInterface,
        network: ToolServiceNetwork,
        port_name: String,
        port: u16,
        base_path: String,
        health: HttpHealthContract,
        startup_timeout_ms: u64,
        shutdown_grace_ms: u64,
        #[serde(skip_serializing_if = "Option::is_none")]
        api_contract_digest: Option<String>,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ToolReleaseDescriptor {
    pub schema: String,
    pub kind: ReleaseKind,
    pub name: String,
    pub version: String,
    pub provenance: ReleaseProvenance,
    pub artifact: ReleaseArtifact,
    pub compatibility: Vec<ReleaseCompatibility>,
    pub dependencies: Vec<ReleaseDependency>,
    pub workload: ToolWorkloadContract,
    /// Optional agent-facing JSON contract. Legacy executable-only release
    /// descriptors may omit both schemas and remain host-only; a descriptor
    /// must provide the pair together when it participates in Agent-facing
    /// publication.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub input_schema: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output_schema: Option<Value>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReleaseResolution {
    pub components: BTreeMap<String, String>,
    pub dependencies: Vec<ReleaseDependency>,
}

impl McpReleaseDescriptor {
    pub fn from_json(input: &[u8]) -> UseResult<Self> {
        parse_descriptor(input, "MCP", Self::validate)
    }

    pub fn validate(&self) -> UseResult<()> {
        if self.schema != MCP_RELEASE_SCHEMA || self.kind != ReleaseKind::Mcp {
            return Err(descriptor_error(
                "The MCP release schema or kind is not supported.",
            ));
        }
        reject_unsupported_tool_dependencies(&self.dependencies)?;
        validate_common(
            &self.name,
            &self.version,
            &self.provenance,
            &self.artifact,
            &self.compatibility,
            &self.dependencies,
        )?;
        if !matches!(
            self.artifact.media_type.as_str(),
            OCI_IMAGE_MANIFEST | OCI_IMAGE_INDEX
        ) {
            return Err(descriptor_error(
                "An MCP release must reference a digest-pinned OCI image manifest or index.",
            ));
        }
        self.service.validate()
    }

    pub fn canonical_bytes(&self) -> UseResult<Vec<u8>> {
        self.validate()?;
        canonical_json(self)
    }

    pub fn descriptor_digest(&self) -> UseResult<String> {
        Ok(digest(self.canonical_bytes()?))
    }

    pub fn verify_resolution(&self, resolution: &ReleaseResolution) -> UseResult<()> {
        self.validate()?;
        verify_resolution(&self.compatibility, &self.dependencies, resolution)
    }
}

impl SkillReleaseDescriptor {
    pub fn from_json(input: &[u8]) -> UseResult<Self> {
        parse_descriptor(input, "Skill", Self::validate)
    }

    pub fn validate(&self) -> UseResult<()> {
        if self.schema != SKILL_RELEASE_SCHEMA || self.kind != ReleaseKind::Skill {
            return Err(descriptor_error(
                "The Skill release schema or kind is not supported.",
            ));
        }
        reject_unsupported_tool_dependencies(&self.dependencies)?;
        validate_common(
            &self.name,
            &self.version,
            &self.provenance,
            &self.artifact,
            &self.compatibility,
            &self.dependencies,
        )?;
        if self.artifact.media_type != SKILL_BUNDLE {
            return Err(descriptor_error(
                "A Skill release must reference an A3S Skill bundle.",
            ));
        }
        self.skill.validate()
    }

    pub fn canonical_bytes(&self) -> UseResult<Vec<u8>> {
        self.validate()?;
        canonical_json(self)
    }

    pub fn descriptor_digest(&self) -> UseResult<String> {
        Ok(digest(self.canonical_bytes()?))
    }

    pub fn verify_resolution(&self, resolution: &ReleaseResolution) -> UseResult<()> {
        self.validate()?;
        verify_resolution(&self.compatibility, &self.dependencies, resolution)
    }
}

impl ToolReleaseDescriptor {
    pub fn from_json(input: &[u8]) -> UseResult<Self> {
        parse_descriptor(input, "Tool", Self::validate)
    }

    pub fn validate(&self) -> UseResult<()> {
        if self.schema != TOOL_RELEASE_SCHEMA || self.kind != ReleaseKind::Tool {
            return Err(descriptor_error(
                "The Tool release schema or kind is not supported.",
            ));
        }
        validate_common(
            &self.name,
            &self.version,
            &self.provenance,
            &self.artifact,
            &self.compatibility,
            &self.dependencies,
        )?;
        if !matches!(
            self.artifact.media_type.as_str(),
            OCI_IMAGE_MANIFEST | OCI_IMAGE_INDEX
        ) {
            return Err(descriptor_error(
                "A Tool release must reference a digest-pinned OCI image manifest or index.",
            ));
        }
        self.workload.validate()?;
        match (&self.input_schema, &self.output_schema) {
            (Some(input), Some(output)) => {
                validate_agent_schema(input, true).map_err(|_| {
                    descriptor_error(
                        "A Tool release input schema must be a bounded closed agent schema.",
                    )
                })?;
                validate_agent_schema(output, true).map_err(|_| {
                    descriptor_error(
                        "A Tool release output schema must be a bounded closed agent schema.",
                    )
                })?;
            }
            (None, None) => {}
            _ => {
                return Err(descriptor_error(
                    "A Tool release must provide input and output schemas together.",
                ));
            }
        }
        Ok(())
    }

    pub fn canonical_bytes(&self) -> UseResult<Vec<u8>> {
        self.validate()?;
        canonical_json(self)
    }

    pub fn descriptor_digest(&self) -> UseResult<String> {
        Ok(digest(self.canonical_bytes()?))
    }

    /// Return the digests of the optional Agent-facing schemas. `None` marks
    /// a legacy host-only release descriptor.
    pub fn tool_schema_digests(&self) -> UseResult<Option<(String, String)>> {
        self.validate()?;
        let (Some(input), Some(output)) = (&self.input_schema, &self.output_schema) else {
            return Ok(None);
        };
        Ok(Some((
            crate::plugin::capability_schema_digest(input)?,
            crate::plugin::capability_schema_digest(output)?,
        )))
    }

    pub fn verify_resolution(&self, resolution: &ReleaseResolution) -> UseResult<()> {
        self.validate()?;
        verify_resolution(&self.compatibility, &self.dependencies, resolution)
    }
}

fn reject_unsupported_tool_dependencies(dependencies: &[ReleaseDependency]) -> UseResult<()> {
    if dependencies
        .iter()
        .any(|dependency| dependency.kind == ReleaseKind::Tool)
    {
        return Err(descriptor_error(
            "MCP and Skill release v1 descriptors cannot depend on Tool releases.",
        ));
    }
    Ok(())
}

fn parse_descriptor<T>(input: &[u8], label: &str, validate: fn(&T) -> UseResult<()>) -> UseResult<T>
where
    T: for<'de> Deserialize<'de>,
{
    if input.is_empty() || input.len() > MAX_RELEASE_DESCRIPTOR_BYTES {
        return Err(descriptor_error(format!(
            "The {label} release descriptor exceeds its input bounds."
        )));
    }
    let descriptor = serde_json::from_slice(input).map_err(|error| {
        descriptor_error(format!(
            "Failed to decode the {label} release descriptor at line {}, column {}.",
            error.line(),
            error.column()
        ))
    })?;
    validate(&descriptor)?;
    Ok(descriptor)
}

fn canonical_json<T: Serialize>(value: &T) -> UseResult<Vec<u8>> {
    let mut bytes = Vec::new();
    let mut serializer =
        serde_json::Serializer::with_formatter(&mut bytes, CanonicalFormatter::new());
    value.serialize(&mut serializer).map_err(|error| {
        descriptor_error(format!("Failed to encode canonical release JSON: {error}"))
    })?;
    if bytes.len() > MAX_RELEASE_DESCRIPTOR_BYTES {
        return Err(descriptor_error(
            "The canonical release descriptor exceeds its size bound.",
        ));
    }
    Ok(bytes)
}

fn digest(bytes: Vec<u8>) -> String {
    format!("sha256:{:x}", Sha256::digest(bytes))
}